ctl.c revision 345112
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * Copyright (c) 2014-2017 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#include <sys/cdefs.h>
44__FBSDID("$FreeBSD: stable/11/sys/cam/ctl/ctl.c 345112 2019-03-13 20:26:46Z mav $");
45
46#include <sys/param.h>
47#include <sys/systm.h>
48#include <sys/ctype.h>
49#include <sys/kernel.h>
50#include <sys/types.h>
51#include <sys/kthread.h>
52#include <sys/bio.h>
53#include <sys/fcntl.h>
54#include <sys/lock.h>
55#include <sys/module.h>
56#include <sys/mutex.h>
57#include <sys/condvar.h>
58#include <sys/malloc.h>
59#include <sys/conf.h>
60#include <sys/ioccom.h>
61#include <sys/queue.h>
62#include <sys/sbuf.h>
63#include <sys/smp.h>
64#include <sys/endian.h>
65#include <sys/proc.h>
66#include <sys/sched.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 scsi_da_rw_recovery_page rw_er_page_default = {
97	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
98	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
99	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
100	/*read_retry_count*/0,
101	/*correction_span*/0,
102	/*head_offset_count*/0,
103	/*data_strobe_offset_cnt*/0,
104	/*byte8*/SMS_RWER_LBPERE,
105	/*write_retry_count*/0,
106	/*reserved2*/0,
107	/*recovery_time_limit*/{0, 0},
108};
109
110const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
111	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
112	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
113	/*byte3*/SMS_RWER_PER,
114	/*read_retry_count*/0,
115	/*correction_span*/0,
116	/*head_offset_count*/0,
117	/*data_strobe_offset_cnt*/0,
118	/*byte8*/SMS_RWER_LBPERE,
119	/*write_retry_count*/0,
120	/*reserved2*/0,
121	/*recovery_time_limit*/{0, 0},
122};
123
124const static struct scsi_format_page format_page_default = {
125	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
126	/*page_length*/sizeof(struct scsi_format_page) - 2,
127	/*tracks_per_zone*/ {0, 0},
128	/*alt_sectors_per_zone*/ {0, 0},
129	/*alt_tracks_per_zone*/ {0, 0},
130	/*alt_tracks_per_lun*/ {0, 0},
131	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
132			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
133	/*bytes_per_sector*/ {0, 0},
134	/*interleave*/ {0, 0},
135	/*track_skew*/ {0, 0},
136	/*cylinder_skew*/ {0, 0},
137	/*flags*/ SFP_HSEC,
138	/*reserved*/ {0, 0, 0}
139};
140
141const static struct scsi_format_page format_page_changeable = {
142	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
143	/*page_length*/sizeof(struct scsi_format_page) - 2,
144	/*tracks_per_zone*/ {0, 0},
145	/*alt_sectors_per_zone*/ {0, 0},
146	/*alt_tracks_per_zone*/ {0, 0},
147	/*alt_tracks_per_lun*/ {0, 0},
148	/*sectors_per_track*/ {0, 0},
149	/*bytes_per_sector*/ {0, 0},
150	/*interleave*/ {0, 0},
151	/*track_skew*/ {0, 0},
152	/*cylinder_skew*/ {0, 0},
153	/*flags*/ 0,
154	/*reserved*/ {0, 0, 0}
155};
156
157const static struct scsi_rigid_disk_page rigid_disk_page_default = {
158	/*page_code*/SMS_RIGID_DISK_PAGE,
159	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
160	/*cylinders*/ {0, 0, 0},
161	/*heads*/ CTL_DEFAULT_HEADS,
162	/*start_write_precomp*/ {0, 0, 0},
163	/*start_reduced_current*/ {0, 0, 0},
164	/*step_rate*/ {0, 0},
165	/*landing_zone_cylinder*/ {0, 0, 0},
166	/*rpl*/ SRDP_RPL_DISABLED,
167	/*rotational_offset*/ 0,
168	/*reserved1*/ 0,
169	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
170			   CTL_DEFAULT_ROTATION_RATE & 0xff},
171	/*reserved2*/ {0, 0}
172};
173
174const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
175	/*page_code*/SMS_RIGID_DISK_PAGE,
176	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
177	/*cylinders*/ {0, 0, 0},
178	/*heads*/ 0,
179	/*start_write_precomp*/ {0, 0, 0},
180	/*start_reduced_current*/ {0, 0, 0},
181	/*step_rate*/ {0, 0},
182	/*landing_zone_cylinder*/ {0, 0, 0},
183	/*rpl*/ 0,
184	/*rotational_offset*/ 0,
185	/*reserved1*/ 0,
186	/*rotation_rate*/ {0, 0},
187	/*reserved2*/ {0, 0}
188};
189
190const static struct scsi_da_verify_recovery_page verify_er_page_default = {
191	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
192	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
193	/*byte3*/0,
194	/*read_retry_count*/0,
195	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
196	/*recovery_time_limit*/{0, 0},
197};
198
199const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
200	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
201	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
202	/*byte3*/SMS_VER_PER,
203	/*read_retry_count*/0,
204	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
205	/*recovery_time_limit*/{0, 0},
206};
207
208const static struct scsi_caching_page caching_page_default = {
209	/*page_code*/SMS_CACHING_PAGE,
210	/*page_length*/sizeof(struct scsi_caching_page) - 2,
211	/*flags1*/ SCP_DISC | SCP_WCE,
212	/*ret_priority*/ 0,
213	/*disable_pf_transfer_len*/ {0xff, 0xff},
214	/*min_prefetch*/ {0, 0},
215	/*max_prefetch*/ {0xff, 0xff},
216	/*max_pf_ceiling*/ {0xff, 0xff},
217	/*flags2*/ 0,
218	/*cache_segments*/ 0,
219	/*cache_seg_size*/ {0, 0},
220	/*reserved*/ 0,
221	/*non_cache_seg_size*/ {0, 0, 0}
222};
223
224const static struct scsi_caching_page caching_page_changeable = {
225	/*page_code*/SMS_CACHING_PAGE,
226	/*page_length*/sizeof(struct scsi_caching_page) - 2,
227	/*flags1*/ SCP_WCE | SCP_RCD,
228	/*ret_priority*/ 0,
229	/*disable_pf_transfer_len*/ {0, 0},
230	/*min_prefetch*/ {0, 0},
231	/*max_prefetch*/ {0, 0},
232	/*max_pf_ceiling*/ {0, 0},
233	/*flags2*/ 0,
234	/*cache_segments*/ 0,
235	/*cache_seg_size*/ {0, 0},
236	/*reserved*/ 0,
237	/*non_cache_seg_size*/ {0, 0, 0}
238};
239
240const static struct scsi_control_page control_page_default = {
241	/*page_code*/SMS_CONTROL_MODE_PAGE,
242	/*page_length*/sizeof(struct scsi_control_page) - 2,
243	/*rlec*/0,
244	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245	/*eca_and_aen*/0,
246	/*flags4*/SCP_TAS,
247	/*aen_holdoff_period*/{0, 0},
248	/*busy_timeout_period*/{0, 0},
249	/*extended_selftest_completion_time*/{0, 0}
250};
251
252const static struct scsi_control_page control_page_changeable = {
253	/*page_code*/SMS_CONTROL_MODE_PAGE,
254	/*page_length*/sizeof(struct scsi_control_page) - 2,
255	/*rlec*/SCP_DSENSE,
256	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
257	/*eca_and_aen*/SCP_SWP,
258	/*flags4*/0,
259	/*aen_holdoff_period*/{0, 0},
260	/*busy_timeout_period*/{0, 0},
261	/*extended_selftest_completion_time*/{0, 0}
262};
263
264#define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
265
266const static struct scsi_control_ext_page control_ext_page_default = {
267	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268	/*subpage_code*/0x01,
269	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270	/*flags*/0,
271	/*prio*/0,
272	/*max_sense*/0
273};
274
275const static struct scsi_control_ext_page control_ext_page_changeable = {
276	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277	/*subpage_code*/0x01,
278	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279	/*flags*/0,
280	/*prio*/0,
281	/*max_sense*/0xff
282};
283
284const static struct scsi_info_exceptions_page ie_page_default = {
285	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287	/*info_flags*/SIEP_FLAGS_EWASC,
288	/*mrie*/SIEP_MRIE_NO,
289	/*interval_timer*/{0, 0, 0, 0},
290	/*report_count*/{0, 0, 0, 1}
291};
292
293const static struct scsi_info_exceptions_page ie_page_changeable = {
294	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
297	    SIEP_FLAGS_LOGERR,
298	/*mrie*/0x0f,
299	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
300	/*report_count*/{0xff, 0xff, 0xff, 0xff}
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*/SLBPP_SITUA,
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;
405SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
406    &worker_threads, 1, "Number of worker threads");
407static int ctl_debug = CTL_DEBUG_NONE;
408SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
409    &ctl_debug, 0, "Enabled debug flags");
410static int ctl_lun_map_size = 1024;
411SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
412    &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
413#ifdef  CTL_TIME_IO
414static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
415SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
416    &ctl_time_io_secs, 0, "Log requests taking more seconds");
417#endif
418
419/*
420 * Maximum number of LUNs we support.  MUST be a power of 2.
421 */
422#define	CTL_DEFAULT_MAX_LUNS	1024
423static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
424TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
425SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
426    &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
427
428/*
429 * Maximum number of ports registered at one time.
430 */
431#define	CTL_DEFAULT_MAX_PORTS		256
432static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
433TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
434SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
435    &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
436
437/*
438 * Maximum number of initiators we support.
439 */
440#define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
441
442/*
443 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
444 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
445 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
446 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
447 */
448#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
449
450static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
451				  int param);
452static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
453static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
454static int ctl_init(void);
455static int ctl_shutdown(void);
456static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
457static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
458static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
459static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
460			      struct ctl_ooa *ooa_hdr,
461			      struct ctl_ooa_entry *kern_entries);
462static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
463		     struct thread *td);
464static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
465			 struct ctl_be_lun *be_lun);
466static int ctl_free_lun(struct ctl_lun *lun);
467static void ctl_create_lun(struct ctl_be_lun *be_lun);
468
469static int ctl_do_mode_select(union ctl_io *io);
470static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
471			   uint64_t res_key, uint64_t sa_res_key,
472			   uint8_t type, uint32_t residx,
473			   struct ctl_scsiio *ctsio,
474			   struct scsi_per_res_out *cdb,
475			   struct scsi_per_res_out_parms* param);
476static void ctl_pro_preempt_other(struct ctl_lun *lun,
477				  union ctl_ha_msg *msg);
478static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
479static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
480static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
481static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
482static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
483static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
484static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
485					 int alloc_len);
486static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
487					 int alloc_len);
488static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
489static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
490static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
491static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
492static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
493static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
494    bool seq);
495static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
496static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
497    union ctl_io *pending_io, union ctl_io *ooa_io);
498static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
499				union ctl_io *starting_io);
500static int ctl_check_blocked(struct ctl_lun *lun);
501static int ctl_scsiio_lun_check(struct ctl_lun *lun,
502				const struct ctl_cmd_entry *entry,
503				struct ctl_scsiio *ctsio);
504static void ctl_failover_lun(union ctl_io *io);
505static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
506			       struct ctl_scsiio *ctsio);
507static int ctl_scsiio(struct ctl_scsiio *ctsio);
508
509static int ctl_target_reset(union ctl_io *io);
510static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
511			 ctl_ua_type ua_type);
512static int ctl_lun_reset(union ctl_io *io);
513static int ctl_abort_task(union ctl_io *io);
514static int ctl_abort_task_set(union ctl_io *io);
515static int ctl_query_task(union ctl_io *io, int task_set);
516static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
517			      ctl_ua_type ua_type);
518static int ctl_i_t_nexus_reset(union ctl_io *io);
519static int ctl_query_async_event(union ctl_io *io);
520static void ctl_run_task(union ctl_io *io);
521#ifdef CTL_IO_DELAY
522static void ctl_datamove_timer_wakeup(void *arg);
523static void ctl_done_timer_wakeup(void *arg);
524#endif /* CTL_IO_DELAY */
525
526static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
527static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
528static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
529static void ctl_datamove_remote_write(union ctl_io *io);
530static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
531static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
532static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
533static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
534				    ctl_ha_dt_cb callback);
535static void ctl_datamove_remote_read(union ctl_io *io);
536static void ctl_datamove_remote(union ctl_io *io);
537static void ctl_process_done(union ctl_io *io);
538static void ctl_lun_thread(void *arg);
539static void ctl_thresh_thread(void *arg);
540static void ctl_work_thread(void *arg);
541static void ctl_enqueue_incoming(union ctl_io *io);
542static void ctl_enqueue_rtr(union ctl_io *io);
543static void ctl_enqueue_done(union ctl_io *io);
544static void ctl_enqueue_isc(union ctl_io *io);
545static const struct ctl_cmd_entry *
546    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
547static const struct ctl_cmd_entry *
548    ctl_validate_command(struct ctl_scsiio *ctsio);
549static int ctl_cmd_applicable(uint8_t lun_type,
550    const struct ctl_cmd_entry *entry);
551static int ctl_ha_init(void);
552static int ctl_ha_shutdown(void);
553
554static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
555static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
556static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
557static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
558
559/*
560 * Load the serialization table.  This isn't very pretty, but is probably
561 * the easiest way to do it.
562 */
563#include "ctl_ser_table.c"
564
565/*
566 * We only need to define open, close and ioctl routines for this driver.
567 */
568static struct cdevsw ctl_cdevsw = {
569	.d_version =	D_VERSION,
570	.d_flags =	0,
571	.d_open =	ctl_open,
572	.d_close =	ctl_close,
573	.d_ioctl =	ctl_ioctl,
574	.d_name =	"ctl",
575};
576
577
578MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
579
580static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
581
582static moduledata_t ctl_moduledata = {
583	"ctl",
584	ctl_module_event_handler,
585	NULL
586};
587
588DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
589MODULE_VERSION(ctl, 1);
590
591static struct ctl_frontend ha_frontend =
592{
593	.name = "ha",
594	.init = ctl_ha_init,
595	.shutdown = ctl_ha_shutdown,
596};
597
598static int
599ctl_ha_init(void)
600{
601	struct ctl_softc *softc = control_softc;
602
603	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
604	                    &softc->othersc_pool) != 0)
605		return (ENOMEM);
606	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
607		ctl_pool_free(softc->othersc_pool);
608		return (EIO);
609	}
610	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
611	    != CTL_HA_STATUS_SUCCESS) {
612		ctl_ha_msg_destroy(softc);
613		ctl_pool_free(softc->othersc_pool);
614		return (EIO);
615	}
616	return (0);
617};
618
619static int
620ctl_ha_shutdown(void)
621{
622	struct ctl_softc *softc = control_softc;
623	struct ctl_port *port;
624
625	ctl_ha_msg_shutdown(softc);
626	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
627		return (EIO);
628	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
629		return (EIO);
630	ctl_pool_free(softc->othersc_pool);
631	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
632		ctl_port_deregister(port);
633		free(port->port_name, M_CTL);
634		free(port, M_CTL);
635	}
636	return (0);
637};
638
639static void
640ctl_ha_datamove(union ctl_io *io)
641{
642	struct ctl_lun *lun = CTL_LUN(io);
643	struct ctl_sg_entry *sgl;
644	union ctl_ha_msg msg;
645	uint32_t sg_entries_sent;
646	int do_sg_copy, i, j;
647
648	memset(&msg.dt, 0, sizeof(msg.dt));
649	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
650	msg.hdr.original_sc = io->io_hdr.remote_io;
651	msg.hdr.serializing_sc = io;
652	msg.hdr.nexus = io->io_hdr.nexus;
653	msg.hdr.status = io->io_hdr.status;
654	msg.dt.flags = io->io_hdr.flags;
655
656	/*
657	 * We convert everything into a S/G list here.  We can't
658	 * pass by reference, only by value between controllers.
659	 * So we can't pass a pointer to the S/G list, only as many
660	 * S/G entries as we can fit in here.  If it's possible for
661	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
662	 * then we need to break this up into multiple transfers.
663	 */
664	if (io->scsiio.kern_sg_entries == 0) {
665		msg.dt.kern_sg_entries = 1;
666#if 0
667		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
668			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
669		} else {
670			/* XXX KDM use busdma here! */
671			msg.dt.sg_list[0].addr =
672			    (void *)vtophys(io->scsiio.kern_data_ptr);
673		}
674#else
675		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
676		    ("HA does not support BUS_ADDR"));
677		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
678#endif
679		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
680		do_sg_copy = 0;
681	} else {
682		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
683		do_sg_copy = 1;
684	}
685
686	msg.dt.kern_data_len = io->scsiio.kern_data_len;
687	msg.dt.kern_total_len = io->scsiio.kern_total_len;
688	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
689	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
690	msg.dt.sg_sequence = 0;
691
692	/*
693	 * Loop until we've sent all of the S/G entries.  On the
694	 * other end, we'll recompose these S/G entries into one
695	 * contiguous list before processing.
696	 */
697	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
698	    msg.dt.sg_sequence++) {
699		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
700		    sizeof(msg.dt.sg_list[0])),
701		    msg.dt.kern_sg_entries - sg_entries_sent);
702		if (do_sg_copy != 0) {
703			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
704			for (i = sg_entries_sent, j = 0;
705			     i < msg.dt.cur_sg_entries; i++, j++) {
706#if 0
707				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
708					msg.dt.sg_list[j].addr = sgl[i].addr;
709				} else {
710					/* XXX KDM use busdma here! */
711					msg.dt.sg_list[j].addr =
712					    (void *)vtophys(sgl[i].addr);
713				}
714#else
715				KASSERT((io->io_hdr.flags &
716				    CTL_FLAG_BUS_ADDR) == 0,
717				    ("HA does not support BUS_ADDR"));
718				msg.dt.sg_list[j].addr = sgl[i].addr;
719#endif
720				msg.dt.sg_list[j].len = sgl[i].len;
721			}
722		}
723
724		sg_entries_sent += msg.dt.cur_sg_entries;
725		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
726		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
727		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
728		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
729		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
730			io->io_hdr.port_status = 31341;
731			io->scsiio.be_move_done(io);
732			return;
733		}
734		msg.dt.sent_sg_entries = sg_entries_sent;
735	}
736
737	/*
738	 * Officially handover the request from us to peer.
739	 * If failover has just happened, then we must return error.
740	 * If failover happen just after, then it is not our problem.
741	 */
742	if (lun)
743		mtx_lock(&lun->lun_lock);
744	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
745		if (lun)
746			mtx_unlock(&lun->lun_lock);
747		io->io_hdr.port_status = 31342;
748		io->scsiio.be_move_done(io);
749		return;
750	}
751	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
752	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
753	if (lun)
754		mtx_unlock(&lun->lun_lock);
755}
756
757static void
758ctl_ha_done(union ctl_io *io)
759{
760	union ctl_ha_msg msg;
761
762	if (io->io_hdr.io_type == CTL_IO_SCSI) {
763		memset(&msg, 0, sizeof(msg));
764		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
765		msg.hdr.original_sc = io->io_hdr.remote_io;
766		msg.hdr.nexus = io->io_hdr.nexus;
767		msg.hdr.status = io->io_hdr.status;
768		msg.scsi.scsi_status = io->scsiio.scsi_status;
769		msg.scsi.tag_num = io->scsiio.tag_num;
770		msg.scsi.tag_type = io->scsiio.tag_type;
771		msg.scsi.sense_len = io->scsiio.sense_len;
772		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
773		    io->scsiio.sense_len);
774		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
775		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
776		    msg.scsi.sense_len, M_WAITOK);
777	}
778	ctl_free_io(io);
779}
780
781static void
782ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
783			    union ctl_ha_msg *msg_info)
784{
785	struct ctl_scsiio *ctsio;
786
787	if (msg_info->hdr.original_sc == NULL) {
788		printf("%s: original_sc == NULL!\n", __func__);
789		/* XXX KDM now what? */
790		return;
791	}
792
793	ctsio = &msg_info->hdr.original_sc->scsiio;
794	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
795	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
796	ctsio->io_hdr.status = msg_info->hdr.status;
797	ctsio->scsi_status = msg_info->scsi.scsi_status;
798	ctsio->sense_len = msg_info->scsi.sense_len;
799	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
800	       msg_info->scsi.sense_len);
801	ctl_enqueue_isc((union ctl_io *)ctsio);
802}
803
804static void
805ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
806				union ctl_ha_msg *msg_info)
807{
808	struct ctl_scsiio *ctsio;
809
810	if (msg_info->hdr.serializing_sc == NULL) {
811		printf("%s: serializing_sc == NULL!\n", __func__);
812		/* XXX KDM now what? */
813		return;
814	}
815
816	ctsio = &msg_info->hdr.serializing_sc->scsiio;
817	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
818	ctl_enqueue_isc((union ctl_io *)ctsio);
819}
820
821void
822ctl_isc_announce_lun(struct ctl_lun *lun)
823{
824	struct ctl_softc *softc = lun->ctl_softc;
825	union ctl_ha_msg *msg;
826	struct ctl_ha_msg_lun_pr_key pr_key;
827	int i, k;
828
829	if (softc->ha_link != CTL_HA_LINK_ONLINE)
830		return;
831	mtx_lock(&lun->lun_lock);
832	i = sizeof(msg->lun);
833	if (lun->lun_devid)
834		i += lun->lun_devid->len;
835	i += sizeof(pr_key) * lun->pr_key_count;
836alloc:
837	mtx_unlock(&lun->lun_lock);
838	msg = malloc(i, M_CTL, M_WAITOK);
839	mtx_lock(&lun->lun_lock);
840	k = sizeof(msg->lun);
841	if (lun->lun_devid)
842		k += lun->lun_devid->len;
843	k += sizeof(pr_key) * lun->pr_key_count;
844	if (i < k) {
845		free(msg, M_CTL);
846		i = k;
847		goto alloc;
848	}
849	bzero(&msg->lun, sizeof(msg->lun));
850	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
851	msg->hdr.nexus.targ_lun = lun->lun;
852	msg->hdr.nexus.targ_mapped_lun = lun->lun;
853	msg->lun.flags = lun->flags;
854	msg->lun.pr_generation = lun->pr_generation;
855	msg->lun.pr_res_idx = lun->pr_res_idx;
856	msg->lun.pr_res_type = lun->pr_res_type;
857	msg->lun.pr_key_count = lun->pr_key_count;
858	i = 0;
859	if (lun->lun_devid) {
860		msg->lun.lun_devid_len = lun->lun_devid->len;
861		memcpy(&msg->lun.data[i], lun->lun_devid->data,
862		    msg->lun.lun_devid_len);
863		i += msg->lun.lun_devid_len;
864	}
865	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
866		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
867			continue;
868		pr_key.pr_iid = k;
869		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
870		i += sizeof(pr_key);
871	}
872	mtx_unlock(&lun->lun_lock);
873	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
874	    M_WAITOK);
875	free(msg, M_CTL);
876
877	if (lun->flags & CTL_LUN_PRIMARY_SC) {
878		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
879			ctl_isc_announce_mode(lun, -1,
880			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
881			    lun->mode_pages.index[i].subpage);
882		}
883	}
884}
885
886void
887ctl_isc_announce_port(struct ctl_port *port)
888{
889	struct ctl_softc *softc = port->ctl_softc;
890	union ctl_ha_msg *msg;
891	int i;
892
893	if (port->targ_port < softc->port_min ||
894	    port->targ_port >= softc->port_max ||
895	    softc->ha_link != CTL_HA_LINK_ONLINE)
896		return;
897	i = sizeof(msg->port) + strlen(port->port_name) + 1;
898	if (port->lun_map)
899		i += port->lun_map_size * sizeof(uint32_t);
900	if (port->port_devid)
901		i += port->port_devid->len;
902	if (port->target_devid)
903		i += port->target_devid->len;
904	if (port->init_devid)
905		i += port->init_devid->len;
906	msg = malloc(i, M_CTL, M_WAITOK);
907	bzero(&msg->port, sizeof(msg->port));
908	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
909	msg->hdr.nexus.targ_port = port->targ_port;
910	msg->port.port_type = port->port_type;
911	msg->port.physical_port = port->physical_port;
912	msg->port.virtual_port = port->virtual_port;
913	msg->port.status = port->status;
914	i = 0;
915	msg->port.name_len = sprintf(&msg->port.data[i],
916	    "%d:%s", softc->ha_id, port->port_name) + 1;
917	i += msg->port.name_len;
918	if (port->lun_map) {
919		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
920		memcpy(&msg->port.data[i], port->lun_map,
921		    msg->port.lun_map_len);
922		i += msg->port.lun_map_len;
923	}
924	if (port->port_devid) {
925		msg->port.port_devid_len = port->port_devid->len;
926		memcpy(&msg->port.data[i], port->port_devid->data,
927		    msg->port.port_devid_len);
928		i += msg->port.port_devid_len;
929	}
930	if (port->target_devid) {
931		msg->port.target_devid_len = port->target_devid->len;
932		memcpy(&msg->port.data[i], port->target_devid->data,
933		    msg->port.target_devid_len);
934		i += msg->port.target_devid_len;
935	}
936	if (port->init_devid) {
937		msg->port.init_devid_len = port->init_devid->len;
938		memcpy(&msg->port.data[i], port->init_devid->data,
939		    msg->port.init_devid_len);
940		i += msg->port.init_devid_len;
941	}
942	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
943	    M_WAITOK);
944	free(msg, M_CTL);
945}
946
947void
948ctl_isc_announce_iid(struct ctl_port *port, int iid)
949{
950	struct ctl_softc *softc = port->ctl_softc;
951	union ctl_ha_msg *msg;
952	int i, l;
953
954	if (port->targ_port < softc->port_min ||
955	    port->targ_port >= softc->port_max ||
956	    softc->ha_link != CTL_HA_LINK_ONLINE)
957		return;
958	mtx_lock(&softc->ctl_lock);
959	i = sizeof(msg->iid);
960	l = 0;
961	if (port->wwpn_iid[iid].name)
962		l = strlen(port->wwpn_iid[iid].name) + 1;
963	i += l;
964	msg = malloc(i, M_CTL, M_NOWAIT);
965	if (msg == NULL) {
966		mtx_unlock(&softc->ctl_lock);
967		return;
968	}
969	bzero(&msg->iid, sizeof(msg->iid));
970	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
971	msg->hdr.nexus.targ_port = port->targ_port;
972	msg->hdr.nexus.initid = iid;
973	msg->iid.in_use = port->wwpn_iid[iid].in_use;
974	msg->iid.name_len = l;
975	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
976	if (port->wwpn_iid[iid].name)
977		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
978	mtx_unlock(&softc->ctl_lock);
979	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
980	free(msg, M_CTL);
981}
982
983void
984ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
985    uint8_t page, uint8_t subpage)
986{
987	struct ctl_softc *softc = lun->ctl_softc;
988	union ctl_ha_msg msg;
989	u_int i;
990
991	if (softc->ha_link != CTL_HA_LINK_ONLINE)
992		return;
993	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
994		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
995		    page && lun->mode_pages.index[i].subpage == subpage)
996			break;
997	}
998	if (i == CTL_NUM_MODE_PAGES)
999		return;
1000
1001	/* Don't try to replicate pages not present on this device. */
1002	if (lun->mode_pages.index[i].page_data == NULL)
1003		return;
1004
1005	bzero(&msg.mode, sizeof(msg.mode));
1006	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
1007	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1008	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1009	msg.hdr.nexus.targ_lun = lun->lun;
1010	msg.hdr.nexus.targ_mapped_lun = lun->lun;
1011	msg.mode.page_code = page;
1012	msg.mode.subpage = subpage;
1013	msg.mode.page_len = lun->mode_pages.index[i].page_len;
1014	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
1015	    msg.mode.page_len);
1016	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
1017	    M_WAITOK);
1018}
1019
1020static void
1021ctl_isc_ha_link_up(struct ctl_softc *softc)
1022{
1023	struct ctl_port *port;
1024	struct ctl_lun *lun;
1025	union ctl_ha_msg msg;
1026	int i;
1027
1028	/* Announce this node parameters to peer for validation. */
1029	msg.login.msg_type = CTL_MSG_LOGIN;
1030	msg.login.version = CTL_HA_VERSION;
1031	msg.login.ha_mode = softc->ha_mode;
1032	msg.login.ha_id = softc->ha_id;
1033	msg.login.max_luns = ctl_max_luns;
1034	msg.login.max_ports = ctl_max_ports;
1035	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1036	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1037	    M_WAITOK);
1038
1039	STAILQ_FOREACH(port, &softc->port_list, links) {
1040		ctl_isc_announce_port(port);
1041		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1042			if (port->wwpn_iid[i].in_use)
1043				ctl_isc_announce_iid(port, i);
1044		}
1045	}
1046	STAILQ_FOREACH(lun, &softc->lun_list, links)
1047		ctl_isc_announce_lun(lun);
1048}
1049
1050static void
1051ctl_isc_ha_link_down(struct ctl_softc *softc)
1052{
1053	struct ctl_port *port;
1054	struct ctl_lun *lun;
1055	union ctl_io *io;
1056	int i;
1057
1058	mtx_lock(&softc->ctl_lock);
1059	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1060		mtx_lock(&lun->lun_lock);
1061		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1062			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1063			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1064		}
1065		mtx_unlock(&lun->lun_lock);
1066
1067		mtx_unlock(&softc->ctl_lock);
1068		io = ctl_alloc_io(softc->othersc_pool);
1069		mtx_lock(&softc->ctl_lock);
1070		ctl_zero_io(io);
1071		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1072		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1073		ctl_enqueue_isc(io);
1074	}
1075
1076	STAILQ_FOREACH(port, &softc->port_list, links) {
1077		if (port->targ_port >= softc->port_min &&
1078		    port->targ_port < softc->port_max)
1079			continue;
1080		port->status &= ~CTL_PORT_STATUS_ONLINE;
1081		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1082			port->wwpn_iid[i].in_use = 0;
1083			free(port->wwpn_iid[i].name, M_CTL);
1084			port->wwpn_iid[i].name = NULL;
1085		}
1086	}
1087	mtx_unlock(&softc->ctl_lock);
1088}
1089
1090static void
1091ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1092{
1093	struct ctl_lun *lun;
1094	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1095
1096	mtx_lock(&softc->ctl_lock);
1097	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1098	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1099		mtx_unlock(&softc->ctl_lock);
1100		return;
1101	}
1102	mtx_lock(&lun->lun_lock);
1103	mtx_unlock(&softc->ctl_lock);
1104	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1105		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1106	if (msg->ua.ua_all) {
1107		if (msg->ua.ua_set)
1108			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1109		else
1110			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1111	} else {
1112		if (msg->ua.ua_set)
1113			ctl_est_ua(lun, iid, msg->ua.ua_type);
1114		else
1115			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1116	}
1117	mtx_unlock(&lun->lun_lock);
1118}
1119
1120static void
1121ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1122{
1123	struct ctl_lun *lun;
1124	struct ctl_ha_msg_lun_pr_key pr_key;
1125	int i, k;
1126	ctl_lun_flags oflags;
1127	uint32_t targ_lun;
1128
1129	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1130	mtx_lock(&softc->ctl_lock);
1131	if (targ_lun >= ctl_max_luns ||
1132	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1133		mtx_unlock(&softc->ctl_lock);
1134		return;
1135	}
1136	mtx_lock(&lun->lun_lock);
1137	mtx_unlock(&softc->ctl_lock);
1138	if (lun->flags & CTL_LUN_DISABLED) {
1139		mtx_unlock(&lun->lun_lock);
1140		return;
1141	}
1142	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1143	if (msg->lun.lun_devid_len != i || (i > 0 &&
1144	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1145		mtx_unlock(&lun->lun_lock);
1146		printf("%s: Received conflicting HA LUN %d\n",
1147		    __func__, targ_lun);
1148		return;
1149	} else {
1150		/* Record whether peer is primary. */
1151		oflags = lun->flags;
1152		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1153		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1154			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1155		else
1156			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1157		if (oflags != lun->flags)
1158			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1159
1160		/* If peer is primary and we are not -- use data */
1161		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1162		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1163			lun->pr_generation = msg->lun.pr_generation;
1164			lun->pr_res_idx = msg->lun.pr_res_idx;
1165			lun->pr_res_type = msg->lun.pr_res_type;
1166			lun->pr_key_count = msg->lun.pr_key_count;
1167			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1168				ctl_clr_prkey(lun, k);
1169			for (k = 0; k < msg->lun.pr_key_count; k++) {
1170				memcpy(&pr_key, &msg->lun.data[i],
1171				    sizeof(pr_key));
1172				ctl_alloc_prkey(lun, pr_key.pr_iid);
1173				ctl_set_prkey(lun, pr_key.pr_iid,
1174				    pr_key.pr_key);
1175				i += sizeof(pr_key);
1176			}
1177		}
1178
1179		mtx_unlock(&lun->lun_lock);
1180		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1181		    __func__, targ_lun,
1182		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1183		    "primary" : "secondary"));
1184
1185		/* If we are primary but peer doesn't know -- notify */
1186		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1187		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1188			ctl_isc_announce_lun(lun);
1189	}
1190}
1191
1192static void
1193ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1194{
1195	struct ctl_port *port;
1196	struct ctl_lun *lun;
1197	int i, new;
1198
1199	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1200	if (port == NULL) {
1201		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1202		    msg->hdr.nexus.targ_port));
1203		new = 1;
1204		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1205		port->frontend = &ha_frontend;
1206		port->targ_port = msg->hdr.nexus.targ_port;
1207		port->fe_datamove = ctl_ha_datamove;
1208		port->fe_done = ctl_ha_done;
1209	} else if (port->frontend == &ha_frontend) {
1210		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1211		    msg->hdr.nexus.targ_port));
1212		new = 0;
1213	} else {
1214		printf("%s: Received conflicting HA port %d\n",
1215		    __func__, msg->hdr.nexus.targ_port);
1216		return;
1217	}
1218	port->port_type = msg->port.port_type;
1219	port->physical_port = msg->port.physical_port;
1220	port->virtual_port = msg->port.virtual_port;
1221	port->status = msg->port.status;
1222	i = 0;
1223	free(port->port_name, M_CTL);
1224	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1225	    M_CTL);
1226	i += msg->port.name_len;
1227	if (msg->port.lun_map_len != 0) {
1228		if (port->lun_map == NULL ||
1229		    port->lun_map_size * sizeof(uint32_t) <
1230		    msg->port.lun_map_len) {
1231			port->lun_map_size = 0;
1232			free(port->lun_map, M_CTL);
1233			port->lun_map = malloc(msg->port.lun_map_len,
1234			    M_CTL, M_WAITOK);
1235		}
1236		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1237		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1238		i += msg->port.lun_map_len;
1239	} else {
1240		port->lun_map_size = 0;
1241		free(port->lun_map, M_CTL);
1242		port->lun_map = NULL;
1243	}
1244	if (msg->port.port_devid_len != 0) {
1245		if (port->port_devid == NULL ||
1246		    port->port_devid->len < msg->port.port_devid_len) {
1247			free(port->port_devid, M_CTL);
1248			port->port_devid = malloc(sizeof(struct ctl_devid) +
1249			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1250		}
1251		memcpy(port->port_devid->data, &msg->port.data[i],
1252		    msg->port.port_devid_len);
1253		port->port_devid->len = msg->port.port_devid_len;
1254		i += msg->port.port_devid_len;
1255	} else {
1256		free(port->port_devid, M_CTL);
1257		port->port_devid = NULL;
1258	}
1259	if (msg->port.target_devid_len != 0) {
1260		if (port->target_devid == NULL ||
1261		    port->target_devid->len < msg->port.target_devid_len) {
1262			free(port->target_devid, M_CTL);
1263			port->target_devid = malloc(sizeof(struct ctl_devid) +
1264			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1265		}
1266		memcpy(port->target_devid->data, &msg->port.data[i],
1267		    msg->port.target_devid_len);
1268		port->target_devid->len = msg->port.target_devid_len;
1269		i += msg->port.target_devid_len;
1270	} else {
1271		free(port->target_devid, M_CTL);
1272		port->target_devid = NULL;
1273	}
1274	if (msg->port.init_devid_len != 0) {
1275		if (port->init_devid == NULL ||
1276		    port->init_devid->len < msg->port.init_devid_len) {
1277			free(port->init_devid, M_CTL);
1278			port->init_devid = malloc(sizeof(struct ctl_devid) +
1279			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1280		}
1281		memcpy(port->init_devid->data, &msg->port.data[i],
1282		    msg->port.init_devid_len);
1283		port->init_devid->len = msg->port.init_devid_len;
1284		i += msg->port.init_devid_len;
1285	} else {
1286		free(port->init_devid, M_CTL);
1287		port->init_devid = NULL;
1288	}
1289	if (new) {
1290		if (ctl_port_register(port) != 0) {
1291			printf("%s: ctl_port_register() failed with error\n",
1292			    __func__);
1293		}
1294	}
1295	mtx_lock(&softc->ctl_lock);
1296	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1297		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1298			continue;
1299		mtx_lock(&lun->lun_lock);
1300		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1301		mtx_unlock(&lun->lun_lock);
1302	}
1303	mtx_unlock(&softc->ctl_lock);
1304}
1305
1306static void
1307ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1308{
1309	struct ctl_port *port;
1310	int iid;
1311
1312	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1313	if (port == NULL) {
1314		printf("%s: Received IID for unknown port %d\n",
1315		    __func__, msg->hdr.nexus.targ_port);
1316		return;
1317	}
1318	iid = msg->hdr.nexus.initid;
1319	if (port->wwpn_iid[iid].in_use != 0 &&
1320	    msg->iid.in_use == 0)
1321		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1322	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1323	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1324	free(port->wwpn_iid[iid].name, M_CTL);
1325	if (msg->iid.name_len) {
1326		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1327		    msg->iid.name_len, M_CTL);
1328	} else
1329		port->wwpn_iid[iid].name = NULL;
1330}
1331
1332static void
1333ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1334{
1335
1336	if (msg->login.version != CTL_HA_VERSION) {
1337		printf("CTL HA peers have different versions %d != %d\n",
1338		    msg->login.version, CTL_HA_VERSION);
1339		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1340		return;
1341	}
1342	if (msg->login.ha_mode != softc->ha_mode) {
1343		printf("CTL HA peers have different ha_mode %d != %d\n",
1344		    msg->login.ha_mode, softc->ha_mode);
1345		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1346		return;
1347	}
1348	if (msg->login.ha_id == softc->ha_id) {
1349		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1350		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1351		return;
1352	}
1353	if (msg->login.max_luns != ctl_max_luns ||
1354	    msg->login.max_ports != ctl_max_ports ||
1355	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1356		printf("CTL HA peers have different limits\n");
1357		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1358		return;
1359	}
1360}
1361
1362static void
1363ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1364{
1365	struct ctl_lun *lun;
1366	u_int i;
1367	uint32_t initidx, targ_lun;
1368
1369	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1370	mtx_lock(&softc->ctl_lock);
1371	if (targ_lun >= ctl_max_luns ||
1372	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1373		mtx_unlock(&softc->ctl_lock);
1374		return;
1375	}
1376	mtx_lock(&lun->lun_lock);
1377	mtx_unlock(&softc->ctl_lock);
1378	if (lun->flags & CTL_LUN_DISABLED) {
1379		mtx_unlock(&lun->lun_lock);
1380		return;
1381	}
1382	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1383		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1384		    msg->mode.page_code &&
1385		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1386			break;
1387	}
1388	if (i == CTL_NUM_MODE_PAGES) {
1389		mtx_unlock(&lun->lun_lock);
1390		return;
1391	}
1392	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1393	    lun->mode_pages.index[i].page_len);
1394	initidx = ctl_get_initindex(&msg->hdr.nexus);
1395	if (initidx != -1)
1396		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1397	mtx_unlock(&lun->lun_lock);
1398}
1399
1400/*
1401 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1402 * subsystem come in here.
1403 */
1404static void
1405ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1406{
1407	struct ctl_softc *softc = control_softc;
1408	union ctl_io *io;
1409	struct ctl_prio *presio;
1410	ctl_ha_status isc_status;
1411
1412	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1413	if (event == CTL_HA_EVT_MSG_RECV) {
1414		union ctl_ha_msg *msg, msgbuf;
1415
1416		if (param > sizeof(msgbuf))
1417			msg = malloc(param, M_CTL, M_WAITOK);
1418		else
1419			msg = &msgbuf;
1420		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1421		    M_WAITOK);
1422		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1423			printf("%s: Error receiving message: %d\n",
1424			    __func__, isc_status);
1425			if (msg != &msgbuf)
1426				free(msg, M_CTL);
1427			return;
1428		}
1429
1430		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1431		switch (msg->hdr.msg_type) {
1432		case CTL_MSG_SERIALIZE:
1433			io = ctl_alloc_io(softc->othersc_pool);
1434			ctl_zero_io(io);
1435			// populate ctsio from msg
1436			io->io_hdr.io_type = CTL_IO_SCSI;
1437			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1438			io->io_hdr.remote_io = msg->hdr.original_sc;
1439			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1440					    CTL_FLAG_IO_ACTIVE;
1441			/*
1442			 * If we're in serialization-only mode, we don't
1443			 * want to go through full done processing.  Thus
1444			 * the COPY flag.
1445			 *
1446			 * XXX KDM add another flag that is more specific.
1447			 */
1448			if (softc->ha_mode != CTL_HA_MODE_XFER)
1449				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1450			io->io_hdr.nexus = msg->hdr.nexus;
1451			io->scsiio.tag_num = msg->scsi.tag_num;
1452			io->scsiio.tag_type = msg->scsi.tag_type;
1453#ifdef CTL_TIME_IO
1454			io->io_hdr.start_time = time_uptime;
1455			getbinuptime(&io->io_hdr.start_bt);
1456#endif /* CTL_TIME_IO */
1457			io->scsiio.cdb_len = msg->scsi.cdb_len;
1458			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1459			       CTL_MAX_CDBLEN);
1460			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1461				const struct ctl_cmd_entry *entry;
1462
1463				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1464				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1465				io->io_hdr.flags |=
1466					entry->flags & CTL_FLAG_DATA_MASK;
1467			}
1468			ctl_enqueue_isc(io);
1469			break;
1470
1471		/* Performed on the Originating SC, XFER mode only */
1472		case CTL_MSG_DATAMOVE: {
1473			struct ctl_sg_entry *sgl;
1474			int i, j;
1475
1476			io = msg->hdr.original_sc;
1477			if (io == NULL) {
1478				printf("%s: original_sc == NULL!\n", __func__);
1479				/* XXX KDM do something here */
1480				break;
1481			}
1482			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1483			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1484			/*
1485			 * Keep track of this, we need to send it back over
1486			 * when the datamove is complete.
1487			 */
1488			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1489			if (msg->hdr.status == CTL_SUCCESS)
1490				io->io_hdr.status = msg->hdr.status;
1491
1492			if (msg->dt.sg_sequence == 0) {
1493#ifdef CTL_TIME_IO
1494				getbinuptime(&io->io_hdr.dma_start_bt);
1495#endif
1496				i = msg->dt.kern_sg_entries +
1497				    msg->dt.kern_data_len /
1498				    CTL_HA_DATAMOVE_SEGMENT + 1;
1499				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1500				    M_WAITOK | M_ZERO);
1501				CTL_RSGL(io) = sgl;
1502				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1503
1504				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1505
1506				io->scsiio.kern_sg_entries =
1507					msg->dt.kern_sg_entries;
1508				io->scsiio.rem_sg_entries =
1509					msg->dt.kern_sg_entries;
1510				io->scsiio.kern_data_len =
1511					msg->dt.kern_data_len;
1512				io->scsiio.kern_total_len =
1513					msg->dt.kern_total_len;
1514				io->scsiio.kern_data_resid =
1515					msg->dt.kern_data_resid;
1516				io->scsiio.kern_rel_offset =
1517					msg->dt.kern_rel_offset;
1518				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1519				io->io_hdr.flags |= msg->dt.flags &
1520				    CTL_FLAG_BUS_ADDR;
1521			} else
1522				sgl = (struct ctl_sg_entry *)
1523					io->scsiio.kern_data_ptr;
1524
1525			for (i = msg->dt.sent_sg_entries, j = 0;
1526			     i < (msg->dt.sent_sg_entries +
1527			     msg->dt.cur_sg_entries); i++, j++) {
1528				sgl[i].addr = msg->dt.sg_list[j].addr;
1529				sgl[i].len = msg->dt.sg_list[j].len;
1530			}
1531
1532			/*
1533			 * If this is the last piece of the I/O, we've got
1534			 * the full S/G list.  Queue processing in the thread.
1535			 * Otherwise wait for the next piece.
1536			 */
1537			if (msg->dt.sg_last != 0)
1538				ctl_enqueue_isc(io);
1539			break;
1540		}
1541		/* Performed on the Serializing (primary) SC, XFER mode only */
1542		case CTL_MSG_DATAMOVE_DONE: {
1543			if (msg->hdr.serializing_sc == NULL) {
1544				printf("%s: serializing_sc == NULL!\n",
1545				       __func__);
1546				/* XXX KDM now what? */
1547				break;
1548			}
1549			/*
1550			 * We grab the sense information here in case
1551			 * there was a failure, so we can return status
1552			 * back to the initiator.
1553			 */
1554			io = msg->hdr.serializing_sc;
1555			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1556			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1557			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1558			io->io_hdr.port_status = msg->scsi.port_status;
1559			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1560			if (msg->hdr.status != CTL_STATUS_NONE) {
1561				io->io_hdr.status = msg->hdr.status;
1562				io->scsiio.scsi_status = msg->scsi.scsi_status;
1563				io->scsiio.sense_len = msg->scsi.sense_len;
1564				memcpy(&io->scsiio.sense_data,
1565				    &msg->scsi.sense_data,
1566				    msg->scsi.sense_len);
1567				if (msg->hdr.status == CTL_SUCCESS)
1568					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1569			}
1570			ctl_enqueue_isc(io);
1571			break;
1572		}
1573
1574		/* Preformed on Originating SC, SER_ONLY mode */
1575		case CTL_MSG_R2R:
1576			io = msg->hdr.original_sc;
1577			if (io == NULL) {
1578				printf("%s: original_sc == NULL!\n",
1579				    __func__);
1580				break;
1581			}
1582			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1583			io->io_hdr.msg_type = CTL_MSG_R2R;
1584			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1585			ctl_enqueue_isc(io);
1586			break;
1587
1588		/*
1589		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1590		 * mode.
1591		 * Performed on the Originating (i.e. secondary) SC in XFER
1592		 * mode
1593		 */
1594		case CTL_MSG_FINISH_IO:
1595			if (softc->ha_mode == CTL_HA_MODE_XFER)
1596				ctl_isc_handler_finish_xfer(softc, msg);
1597			else
1598				ctl_isc_handler_finish_ser_only(softc, msg);
1599			break;
1600
1601		/* Preformed on Originating SC */
1602		case CTL_MSG_BAD_JUJU:
1603			io = msg->hdr.original_sc;
1604			if (io == NULL) {
1605				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1606				       __func__);
1607				break;
1608			}
1609			ctl_copy_sense_data(msg, io);
1610			/*
1611			 * IO should have already been cleaned up on other
1612			 * SC so clear this flag so we won't send a message
1613			 * back to finish the IO there.
1614			 */
1615			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1616			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1617
1618			/* io = msg->hdr.serializing_sc; */
1619			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1620			ctl_enqueue_isc(io);
1621			break;
1622
1623		/* Handle resets sent from the other side */
1624		case CTL_MSG_MANAGE_TASKS: {
1625			struct ctl_taskio *taskio;
1626			taskio = (struct ctl_taskio *)ctl_alloc_io(
1627			    softc->othersc_pool);
1628			ctl_zero_io((union ctl_io *)taskio);
1629			taskio->io_hdr.io_type = CTL_IO_TASK;
1630			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1631			taskio->io_hdr.nexus = msg->hdr.nexus;
1632			taskio->task_action = msg->task.task_action;
1633			taskio->tag_num = msg->task.tag_num;
1634			taskio->tag_type = msg->task.tag_type;
1635#ifdef CTL_TIME_IO
1636			taskio->io_hdr.start_time = time_uptime;
1637			getbinuptime(&taskio->io_hdr.start_bt);
1638#endif /* CTL_TIME_IO */
1639			ctl_run_task((union ctl_io *)taskio);
1640			break;
1641		}
1642		/* Persistent Reserve action which needs attention */
1643		case CTL_MSG_PERS_ACTION:
1644			presio = (struct ctl_prio *)ctl_alloc_io(
1645			    softc->othersc_pool);
1646			ctl_zero_io((union ctl_io *)presio);
1647			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1648			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1649			presio->io_hdr.nexus = msg->hdr.nexus;
1650			presio->pr_msg = msg->pr;
1651			ctl_enqueue_isc((union ctl_io *)presio);
1652			break;
1653		case CTL_MSG_UA:
1654			ctl_isc_ua(softc, msg, param);
1655			break;
1656		case CTL_MSG_PORT_SYNC:
1657			ctl_isc_port_sync(softc, msg, param);
1658			break;
1659		case CTL_MSG_LUN_SYNC:
1660			ctl_isc_lun_sync(softc, msg, param);
1661			break;
1662		case CTL_MSG_IID_SYNC:
1663			ctl_isc_iid_sync(softc, msg, param);
1664			break;
1665		case CTL_MSG_LOGIN:
1666			ctl_isc_login(softc, msg, param);
1667			break;
1668		case CTL_MSG_MODE_SYNC:
1669			ctl_isc_mode_sync(softc, msg, param);
1670			break;
1671		default:
1672			printf("Received HA message of unknown type %d\n",
1673			    msg->hdr.msg_type);
1674			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1675			break;
1676		}
1677		if (msg != &msgbuf)
1678			free(msg, M_CTL);
1679	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1680		printf("CTL: HA link status changed from %d to %d\n",
1681		    softc->ha_link, param);
1682		if (param == softc->ha_link)
1683			return;
1684		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1685			softc->ha_link = param;
1686			ctl_isc_ha_link_down(softc);
1687		} else {
1688			softc->ha_link = param;
1689			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1690				ctl_isc_ha_link_up(softc);
1691		}
1692		return;
1693	} else {
1694		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1695		return;
1696	}
1697}
1698
1699static void
1700ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1701{
1702
1703	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1704	    src->scsi.sense_len);
1705	dest->scsiio.scsi_status = src->scsi.scsi_status;
1706	dest->scsiio.sense_len = src->scsi.sense_len;
1707	dest->io_hdr.status = src->hdr.status;
1708}
1709
1710static void
1711ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1712{
1713
1714	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1715	    src->scsiio.sense_len);
1716	dest->scsi.scsi_status = src->scsiio.scsi_status;
1717	dest->scsi.sense_len = src->scsiio.sense_len;
1718	dest->hdr.status = src->io_hdr.status;
1719}
1720
1721void
1722ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1723{
1724	struct ctl_softc *softc = lun->ctl_softc;
1725	ctl_ua_type *pu;
1726
1727	if (initidx < softc->init_min || initidx >= softc->init_max)
1728		return;
1729	mtx_assert(&lun->lun_lock, MA_OWNED);
1730	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1731	if (pu == NULL)
1732		return;
1733	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1734}
1735
1736void
1737ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1738{
1739	int i;
1740
1741	mtx_assert(&lun->lun_lock, MA_OWNED);
1742	if (lun->pending_ua[port] == NULL)
1743		return;
1744	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1745		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1746			continue;
1747		lun->pending_ua[port][i] |= ua;
1748	}
1749}
1750
1751void
1752ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1753{
1754	struct ctl_softc *softc = lun->ctl_softc;
1755	int i;
1756
1757	mtx_assert(&lun->lun_lock, MA_OWNED);
1758	for (i = softc->port_min; i < softc->port_max; i++)
1759		ctl_est_ua_port(lun, i, except, ua);
1760}
1761
1762void
1763ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1764{
1765	struct ctl_softc *softc = lun->ctl_softc;
1766	ctl_ua_type *pu;
1767
1768	if (initidx < softc->init_min || initidx >= softc->init_max)
1769		return;
1770	mtx_assert(&lun->lun_lock, MA_OWNED);
1771	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1772	if (pu == NULL)
1773		return;
1774	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1775}
1776
1777void
1778ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1779{
1780	struct ctl_softc *softc = lun->ctl_softc;
1781	int i, j;
1782
1783	mtx_assert(&lun->lun_lock, MA_OWNED);
1784	for (i = softc->port_min; i < softc->port_max; i++) {
1785		if (lun->pending_ua[i] == NULL)
1786			continue;
1787		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1788			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1789				continue;
1790			lun->pending_ua[i][j] &= ~ua;
1791		}
1792	}
1793}
1794
1795void
1796ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1797    ctl_ua_type ua_type)
1798{
1799	struct ctl_lun *lun;
1800
1801	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1802	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1803		mtx_lock(&lun->lun_lock);
1804		ctl_clr_ua(lun, initidx, ua_type);
1805		mtx_unlock(&lun->lun_lock);
1806	}
1807}
1808
1809static int
1810ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1811{
1812	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1813	struct ctl_lun *lun;
1814	struct ctl_lun_req ireq;
1815	int error, value;
1816
1817	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1818	error = sysctl_handle_int(oidp, &value, 0, req);
1819	if ((error != 0) || (req->newptr == NULL))
1820		return (error);
1821
1822	mtx_lock(&softc->ctl_lock);
1823	if (value == 0)
1824		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1825	else
1826		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1827	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1828		mtx_unlock(&softc->ctl_lock);
1829		bzero(&ireq, sizeof(ireq));
1830		ireq.reqtype = CTL_LUNREQ_MODIFY;
1831		ireq.reqdata.modify.lun_id = lun->lun;
1832		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1833		    curthread);
1834		if (ireq.status != CTL_LUN_OK) {
1835			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1836			    __func__, ireq.status, ireq.error_str);
1837		}
1838		mtx_lock(&softc->ctl_lock);
1839	}
1840	mtx_unlock(&softc->ctl_lock);
1841	return (0);
1842}
1843
1844static int
1845ctl_init(void)
1846{
1847	struct make_dev_args args;
1848	struct ctl_softc *softc;
1849	int i, error;
1850
1851	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1852			       M_WAITOK | M_ZERO);
1853
1854	make_dev_args_init(&args);
1855	args.mda_devsw = &ctl_cdevsw;
1856	args.mda_uid = UID_ROOT;
1857	args.mda_gid = GID_OPERATOR;
1858	args.mda_mode = 0600;
1859	args.mda_si_drv1 = softc;
1860	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1861	if (error != 0) {
1862		free(softc, M_DEVBUF);
1863		control_softc = NULL;
1864		return (error);
1865	}
1866
1867	sysctl_ctx_init(&softc->sysctl_ctx);
1868	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1869		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1870		CTLFLAG_RD, 0, "CAM Target Layer");
1871
1872	if (softc->sysctl_tree == NULL) {
1873		printf("%s: unable to allocate sysctl tree\n", __func__);
1874		destroy_dev(softc->dev);
1875		free(softc, M_DEVBUF);
1876		control_softc = NULL;
1877		return (ENOMEM);
1878	}
1879
1880	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1881	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1882	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1883	softc->flags = 0;
1884
1885	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1886	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1887	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1888
1889	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1890		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1891		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1892		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1893	}
1894	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1895	    M_DEVBUF, M_WAITOK | M_ZERO);
1896	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1897	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1898	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1899		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1900		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1901		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1902	}
1903	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1904	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1905	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1906	     M_DEVBUF, M_WAITOK | M_ZERO);
1907
1908
1909	/*
1910	 * In Copan's HA scheme, the "master" and "slave" roles are
1911	 * figured out through the slot the controller is in.  Although it
1912	 * is an active/active system, someone has to be in charge.
1913	 */
1914	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1915	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1916	    "HA head ID (0 - no HA)");
1917	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1918		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1919		softc->is_single = 1;
1920		softc->port_cnt = ctl_max_ports;
1921		softc->port_min = 0;
1922	} else {
1923		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1924		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1925	}
1926	softc->port_max = softc->port_min + softc->port_cnt;
1927	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1928	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1929
1930	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1931	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1932	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1933
1934	STAILQ_INIT(&softc->lun_list);
1935	STAILQ_INIT(&softc->pending_lun_queue);
1936	STAILQ_INIT(&softc->fe_list);
1937	STAILQ_INIT(&softc->port_list);
1938	STAILQ_INIT(&softc->be_list);
1939	ctl_tpc_init(softc);
1940
1941	if (worker_threads <= 0)
1942		worker_threads = max(1, mp_ncpus / 4);
1943	if (worker_threads > CTL_MAX_THREADS)
1944		worker_threads = CTL_MAX_THREADS;
1945
1946	for (i = 0; i < worker_threads; i++) {
1947		struct ctl_thread *thr = &softc->threads[i];
1948
1949		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1950		thr->ctl_softc = softc;
1951		STAILQ_INIT(&thr->incoming_queue);
1952		STAILQ_INIT(&thr->rtr_queue);
1953		STAILQ_INIT(&thr->done_queue);
1954		STAILQ_INIT(&thr->isc_queue);
1955
1956		error = kproc_kthread_add(ctl_work_thread, thr,
1957		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1958		if (error != 0) {
1959			printf("error creating CTL work thread!\n");
1960			return (error);
1961		}
1962	}
1963	error = kproc_kthread_add(ctl_lun_thread, softc,
1964	    &softc->ctl_proc, &softc->lun_thread, 0, 0, "ctl", "lun");
1965	if (error != 0) {
1966		printf("error creating CTL lun thread!\n");
1967		return (error);
1968	}
1969	error = kproc_kthread_add(ctl_thresh_thread, softc,
1970	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1971	if (error != 0) {
1972		printf("error creating CTL threshold thread!\n");
1973		return (error);
1974	}
1975
1976	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1977	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1978	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1979
1980	if (softc->is_single == 0) {
1981		if (ctl_frontend_register(&ha_frontend) != 0)
1982			softc->is_single = 1;
1983	}
1984	return (0);
1985}
1986
1987static int
1988ctl_shutdown(void)
1989{
1990	struct ctl_softc *softc = control_softc;
1991	int i;
1992
1993	if (softc->is_single == 0)
1994		ctl_frontend_deregister(&ha_frontend);
1995
1996	destroy_dev(softc->dev);
1997
1998	/* Shutdown CTL threads. */
1999	softc->shutdown = 1;
2000	for (i = 0; i < worker_threads; i++) {
2001		struct ctl_thread *thr = &softc->threads[i];
2002		while (thr->thread != NULL) {
2003			wakeup(thr);
2004			if (thr->thread != NULL)
2005				pause("CTL thr shutdown", 1);
2006		}
2007		mtx_destroy(&thr->queue_lock);
2008	}
2009	while (softc->lun_thread != NULL) {
2010		wakeup(&softc->pending_lun_queue);
2011		if (softc->lun_thread != NULL)
2012			pause("CTL thr shutdown", 1);
2013	}
2014	while (softc->thresh_thread != NULL) {
2015		wakeup(softc->thresh_thread);
2016		if (softc->thresh_thread != NULL)
2017			pause("CTL thr shutdown", 1);
2018	}
2019
2020	ctl_tpc_shutdown(softc);
2021	uma_zdestroy(softc->io_zone);
2022	mtx_destroy(&softc->ctl_lock);
2023
2024	free(softc->ctl_luns, M_DEVBUF);
2025	free(softc->ctl_lun_mask, M_DEVBUF);
2026	free(softc->ctl_port_mask, M_DEVBUF);
2027	free(softc->ctl_ports, M_DEVBUF);
2028
2029	sysctl_ctx_free(&softc->sysctl_ctx);
2030
2031	free(softc, M_DEVBUF);
2032	control_softc = NULL;
2033	return (0);
2034}
2035
2036static int
2037ctl_module_event_handler(module_t mod, int what, void *arg)
2038{
2039
2040	switch (what) {
2041	case MOD_LOAD:
2042		return (ctl_init());
2043	case MOD_UNLOAD:
2044		return (ctl_shutdown());
2045	default:
2046		return (EOPNOTSUPP);
2047	}
2048}
2049
2050/*
2051 * XXX KDM should we do some access checks here?  Bump a reference count to
2052 * prevent a CTL module from being unloaded while someone has it open?
2053 */
2054static int
2055ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2056{
2057	return (0);
2058}
2059
2060static int
2061ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2062{
2063	return (0);
2064}
2065
2066/*
2067 * Remove an initiator by port number and initiator ID.
2068 * Returns 0 for success, -1 for failure.
2069 */
2070int
2071ctl_remove_initiator(struct ctl_port *port, int iid)
2072{
2073	struct ctl_softc *softc = port->ctl_softc;
2074	int last;
2075
2076	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2077
2078	if (iid > CTL_MAX_INIT_PER_PORT) {
2079		printf("%s: initiator ID %u > maximun %u!\n",
2080		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2081		return (-1);
2082	}
2083
2084	mtx_lock(&softc->ctl_lock);
2085	last = (--port->wwpn_iid[iid].in_use == 0);
2086	port->wwpn_iid[iid].last_use = time_uptime;
2087	mtx_unlock(&softc->ctl_lock);
2088	if (last)
2089		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2090	ctl_isc_announce_iid(port, iid);
2091
2092	return (0);
2093}
2094
2095/*
2096 * Add an initiator to the initiator map.
2097 * Returns iid for success, < 0 for failure.
2098 */
2099int
2100ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2101{
2102	struct ctl_softc *softc = port->ctl_softc;
2103	time_t best_time;
2104	int i, best;
2105
2106	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2107
2108	if (iid >= CTL_MAX_INIT_PER_PORT) {
2109		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2110		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2111		free(name, M_CTL);
2112		return (-1);
2113	}
2114
2115	mtx_lock(&softc->ctl_lock);
2116
2117	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2118		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2119			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2120				iid = i;
2121				break;
2122			}
2123			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2124			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2125				iid = i;
2126				break;
2127			}
2128		}
2129	}
2130
2131	if (iid < 0) {
2132		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2133			if (port->wwpn_iid[i].in_use == 0 &&
2134			    port->wwpn_iid[i].wwpn == 0 &&
2135			    port->wwpn_iid[i].name == NULL) {
2136				iid = i;
2137				break;
2138			}
2139		}
2140	}
2141
2142	if (iid < 0) {
2143		best = -1;
2144		best_time = INT32_MAX;
2145		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2146			if (port->wwpn_iid[i].in_use == 0) {
2147				if (port->wwpn_iid[i].last_use < best_time) {
2148					best = i;
2149					best_time = port->wwpn_iid[i].last_use;
2150				}
2151			}
2152		}
2153		iid = best;
2154	}
2155
2156	if (iid < 0) {
2157		mtx_unlock(&softc->ctl_lock);
2158		free(name, M_CTL);
2159		return (-2);
2160	}
2161
2162	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2163		/*
2164		 * This is not an error yet.
2165		 */
2166		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2167#if 0
2168			printf("%s: port %d iid %u WWPN %#jx arrived"
2169			    " again\n", __func__, port->targ_port,
2170			    iid, (uintmax_t)wwpn);
2171#endif
2172			goto take;
2173		}
2174		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2175		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2176#if 0
2177			printf("%s: port %d iid %u name '%s' arrived"
2178			    " again\n", __func__, port->targ_port,
2179			    iid, name);
2180#endif
2181			goto take;
2182		}
2183
2184		/*
2185		 * This is an error, but what do we do about it?  The
2186		 * driver is telling us we have a new WWPN for this
2187		 * initiator ID, so we pretty much need to use it.
2188		 */
2189		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2190		    " but WWPN %#jx '%s' is still at that address\n",
2191		    __func__, port->targ_port, iid, wwpn, name,
2192		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2193		    port->wwpn_iid[iid].name);
2194	}
2195take:
2196	free(port->wwpn_iid[iid].name, M_CTL);
2197	port->wwpn_iid[iid].name = name;
2198	port->wwpn_iid[iid].wwpn = wwpn;
2199	port->wwpn_iid[iid].in_use++;
2200	mtx_unlock(&softc->ctl_lock);
2201	ctl_isc_announce_iid(port, iid);
2202
2203	return (iid);
2204}
2205
2206static int
2207ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2208{
2209	int len;
2210
2211	switch (port->port_type) {
2212	case CTL_PORT_FC:
2213	{
2214		struct scsi_transportid_fcp *id =
2215		    (struct scsi_transportid_fcp *)buf;
2216		if (port->wwpn_iid[iid].wwpn == 0)
2217			return (0);
2218		memset(id, 0, sizeof(*id));
2219		id->format_protocol = SCSI_PROTO_FC;
2220		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2221		return (sizeof(*id));
2222	}
2223	case CTL_PORT_ISCSI:
2224	{
2225		struct scsi_transportid_iscsi_port *id =
2226		    (struct scsi_transportid_iscsi_port *)buf;
2227		if (port->wwpn_iid[iid].name == NULL)
2228			return (0);
2229		memset(id, 0, 256);
2230		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2231		    SCSI_PROTO_ISCSI;
2232		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2233		len = roundup2(min(len, 252), 4);
2234		scsi_ulto2b(len, id->additional_length);
2235		return (sizeof(*id) + len);
2236	}
2237	case CTL_PORT_SAS:
2238	{
2239		struct scsi_transportid_sas *id =
2240		    (struct scsi_transportid_sas *)buf;
2241		if (port->wwpn_iid[iid].wwpn == 0)
2242			return (0);
2243		memset(id, 0, sizeof(*id));
2244		id->format_protocol = SCSI_PROTO_SAS;
2245		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2246		return (sizeof(*id));
2247	}
2248	default:
2249	{
2250		struct scsi_transportid_spi *id =
2251		    (struct scsi_transportid_spi *)buf;
2252		memset(id, 0, sizeof(*id));
2253		id->format_protocol = SCSI_PROTO_SPI;
2254		scsi_ulto2b(iid, id->scsi_addr);
2255		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2256		return (sizeof(*id));
2257	}
2258	}
2259}
2260
2261/*
2262 * Serialize a command that went down the "wrong" side, and so was sent to
2263 * this controller for execution.  The logic is a little different than the
2264 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2265 * sent back to the other side, but in the success case, we execute the
2266 * command on this side (XFER mode) or tell the other side to execute it
2267 * (SER_ONLY mode).
2268 */
2269static void
2270ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2271{
2272	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2273	struct ctl_port *port = CTL_PORT(ctsio);
2274	union ctl_ha_msg msg_info;
2275	struct ctl_lun *lun;
2276	const struct ctl_cmd_entry *entry;
2277	uint32_t targ_lun;
2278
2279	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2280
2281	/* Make sure that we know about this port. */
2282	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2283		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2284					 /*retry_count*/ 1);
2285		goto badjuju;
2286	}
2287
2288	/* Make sure that we know about this LUN. */
2289	mtx_lock(&softc->ctl_lock);
2290	if (targ_lun >= ctl_max_luns ||
2291	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2292		mtx_unlock(&softc->ctl_lock);
2293
2294		/*
2295		 * The other node would not send this request to us unless
2296		 * received announce that we are primary node for this LUN.
2297		 * If this LUN does not exist now, it is probably result of
2298		 * a race, so respond to initiator in the most opaque way.
2299		 */
2300		ctl_set_busy(ctsio);
2301		goto badjuju;
2302	}
2303	mtx_lock(&lun->lun_lock);
2304	mtx_unlock(&softc->ctl_lock);
2305
2306	/*
2307	 * If the LUN is invalid, pretend that it doesn't exist.
2308	 * It will go away as soon as all pending I/Os completed.
2309	 */
2310	if (lun->flags & CTL_LUN_DISABLED) {
2311		mtx_unlock(&lun->lun_lock);
2312		ctl_set_busy(ctsio);
2313		goto badjuju;
2314	}
2315
2316	entry = ctl_get_cmd_entry(ctsio, NULL);
2317	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2318		mtx_unlock(&lun->lun_lock);
2319		goto badjuju;
2320	}
2321
2322	CTL_LUN(ctsio) = lun;
2323	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2324
2325	/*
2326	 * Every I/O goes into the OOA queue for a
2327	 * particular LUN, and stays there until completion.
2328	 */
2329#ifdef CTL_TIME_IO
2330	if (TAILQ_EMPTY(&lun->ooa_queue))
2331		lun->idle_time += getsbinuptime() - lun->last_busy;
2332#endif
2333	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2334
2335	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2336		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2337		 ooa_links))) {
2338	case CTL_ACTION_BLOCK:
2339		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2340		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2341				  blocked_links);
2342		mtx_unlock(&lun->lun_lock);
2343		break;
2344	case CTL_ACTION_PASS:
2345	case CTL_ACTION_SKIP:
2346		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2347			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2348			ctl_enqueue_rtr((union ctl_io *)ctsio);
2349			mtx_unlock(&lun->lun_lock);
2350		} else {
2351			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2352			mtx_unlock(&lun->lun_lock);
2353
2354			/* send msg back to other side */
2355			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2356			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2357			msg_info.hdr.msg_type = CTL_MSG_R2R;
2358			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2359			    sizeof(msg_info.hdr), M_WAITOK);
2360		}
2361		break;
2362	case CTL_ACTION_OVERLAP:
2363		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2364		mtx_unlock(&lun->lun_lock);
2365		ctl_set_overlapped_cmd(ctsio);
2366		goto badjuju;
2367	case CTL_ACTION_OVERLAP_TAG:
2368		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2369		mtx_unlock(&lun->lun_lock);
2370		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2371		goto badjuju;
2372	case CTL_ACTION_ERROR:
2373	default:
2374		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2375		mtx_unlock(&lun->lun_lock);
2376
2377		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2378					 /*retry_count*/ 0);
2379badjuju:
2380		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2381		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2382		msg_info.hdr.serializing_sc = NULL;
2383		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2384		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2385		    sizeof(msg_info.scsi), M_WAITOK);
2386		ctl_free_io((union ctl_io *)ctsio);
2387		break;
2388	}
2389}
2390
2391/*
2392 * Returns 0 for success, errno for failure.
2393 */
2394static void
2395ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2396		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2397{
2398	union ctl_io *io;
2399
2400	mtx_lock(&lun->lun_lock);
2401	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2402	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2403	     ooa_links)) {
2404		struct ctl_ooa_entry *entry;
2405
2406		/*
2407		 * If we've got more than we can fit, just count the
2408		 * remaining entries.
2409		 */
2410		if (*cur_fill_num >= ooa_hdr->alloc_num)
2411			continue;
2412
2413		entry = &kern_entries[*cur_fill_num];
2414
2415		entry->tag_num = io->scsiio.tag_num;
2416		entry->lun_num = lun->lun;
2417#ifdef CTL_TIME_IO
2418		entry->start_bt = io->io_hdr.start_bt;
2419#endif
2420		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2421		entry->cdb_len = io->scsiio.cdb_len;
2422		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2423			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2424
2425		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2426			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2427
2428		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2429			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2430
2431		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2432			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2433
2434		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2435			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2436	}
2437	mtx_unlock(&lun->lun_lock);
2438}
2439
2440static void *
2441ctl_copyin_alloc(void *user_addr, unsigned int len, char *error_str,
2442		 size_t error_str_len)
2443{
2444	void *kptr;
2445
2446	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2447
2448	if (copyin(user_addr, kptr, len) != 0) {
2449		snprintf(error_str, error_str_len, "Error copying %d bytes "
2450			 "from user address %p to kernel address %p", len,
2451			 user_addr, kptr);
2452		free(kptr, M_CTL);
2453		return (NULL);
2454	}
2455
2456	return (kptr);
2457}
2458
2459static void
2460ctl_free_args(int num_args, struct ctl_be_arg *args)
2461{
2462	int i;
2463
2464	if (args == NULL)
2465		return;
2466
2467	for (i = 0; i < num_args; i++) {
2468		free(args[i].kname, M_CTL);
2469		free(args[i].kvalue, M_CTL);
2470	}
2471
2472	free(args, M_CTL);
2473}
2474
2475static struct ctl_be_arg *
2476ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2477		char *error_str, size_t error_str_len)
2478{
2479	struct ctl_be_arg *args;
2480	int i;
2481
2482	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2483				error_str, error_str_len);
2484
2485	if (args == NULL)
2486		goto bailout;
2487
2488	for (i = 0; i < num_args; i++) {
2489		args[i].kname = NULL;
2490		args[i].kvalue = NULL;
2491	}
2492
2493	for (i = 0; i < num_args; i++) {
2494		uint8_t *tmpptr;
2495
2496		if (args[i].namelen == 0) {
2497			snprintf(error_str, error_str_len, "Argument %d "
2498				 "name length is zero", i);
2499			goto bailout;
2500		}
2501
2502		args[i].kname = ctl_copyin_alloc(args[i].name,
2503			args[i].namelen, error_str, error_str_len);
2504		if (args[i].kname == NULL)
2505			goto bailout;
2506
2507		if (args[i].kname[args[i].namelen - 1] != '\0') {
2508			snprintf(error_str, error_str_len, "Argument %d "
2509				 "name is not NUL-terminated", i);
2510			goto bailout;
2511		}
2512
2513		if (args[i].flags & CTL_BEARG_RD) {
2514			if (args[i].vallen == 0) {
2515				snprintf(error_str, error_str_len, "Argument %d "
2516					 "value length is zero", i);
2517				goto bailout;
2518			}
2519
2520			tmpptr = ctl_copyin_alloc(args[i].value,
2521				args[i].vallen, error_str, error_str_len);
2522			if (tmpptr == NULL)
2523				goto bailout;
2524
2525			if ((args[i].flags & CTL_BEARG_ASCII)
2526			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2527				snprintf(error_str, error_str_len, "Argument "
2528				    "%d value is not NUL-terminated", i);
2529				free(tmpptr, M_CTL);
2530				goto bailout;
2531			}
2532			args[i].kvalue = tmpptr;
2533		} else {
2534			args[i].kvalue = malloc(args[i].vallen,
2535			    M_CTL, M_WAITOK | M_ZERO);
2536		}
2537	}
2538
2539	return (args);
2540bailout:
2541
2542	ctl_free_args(num_args, args);
2543
2544	return (NULL);
2545}
2546
2547static void
2548ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2549{
2550	int i;
2551
2552	for (i = 0; i < num_args; i++) {
2553		if (args[i].flags & CTL_BEARG_WR)
2554			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2555	}
2556}
2557
2558/*
2559 * Escape characters that are illegal or not recommended in XML.
2560 */
2561int
2562ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2563{
2564	char *end = str + size;
2565	int retval;
2566
2567	retval = 0;
2568
2569	for (; *str && str < end; str++) {
2570		switch (*str) {
2571		case '&':
2572			retval = sbuf_printf(sb, "&amp;");
2573			break;
2574		case '>':
2575			retval = sbuf_printf(sb, "&gt;");
2576			break;
2577		case '<':
2578			retval = sbuf_printf(sb, "&lt;");
2579			break;
2580		default:
2581			retval = sbuf_putc(sb, *str);
2582			break;
2583		}
2584
2585		if (retval != 0)
2586			break;
2587
2588	}
2589
2590	return (retval);
2591}
2592
2593static void
2594ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2595{
2596	struct scsi_vpd_id_descriptor *desc;
2597	int i;
2598
2599	if (id == NULL || id->len < 4)
2600		return;
2601	desc = (struct scsi_vpd_id_descriptor *)id->data;
2602	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2603	case SVPD_ID_TYPE_T10:
2604		sbuf_printf(sb, "t10.");
2605		break;
2606	case SVPD_ID_TYPE_EUI64:
2607		sbuf_printf(sb, "eui.");
2608		break;
2609	case SVPD_ID_TYPE_NAA:
2610		sbuf_printf(sb, "naa.");
2611		break;
2612	case SVPD_ID_TYPE_SCSI_NAME:
2613		break;
2614	}
2615	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2616	case SVPD_ID_CODESET_BINARY:
2617		for (i = 0; i < desc->length; i++)
2618			sbuf_printf(sb, "%02x", desc->identifier[i]);
2619		break;
2620	case SVPD_ID_CODESET_ASCII:
2621		sbuf_printf(sb, "%.*s", (int)desc->length,
2622		    (char *)desc->identifier);
2623		break;
2624	case SVPD_ID_CODESET_UTF8:
2625		sbuf_printf(sb, "%s", (char *)desc->identifier);
2626		break;
2627	}
2628}
2629
2630static int
2631ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2632	  struct thread *td)
2633{
2634	struct ctl_softc *softc = dev->si_drv1;
2635	struct ctl_port *port;
2636	struct ctl_lun *lun;
2637	int retval;
2638
2639	retval = 0;
2640
2641	switch (cmd) {
2642	case CTL_IO:
2643		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2644		break;
2645	case CTL_ENABLE_PORT:
2646	case CTL_DISABLE_PORT:
2647	case CTL_SET_PORT_WWNS: {
2648		struct ctl_port *port;
2649		struct ctl_port_entry *entry;
2650
2651		entry = (struct ctl_port_entry *)addr;
2652
2653		mtx_lock(&softc->ctl_lock);
2654		STAILQ_FOREACH(port, &softc->port_list, links) {
2655			int action, done;
2656
2657			if (port->targ_port < softc->port_min ||
2658			    port->targ_port >= softc->port_max)
2659				continue;
2660
2661			action = 0;
2662			done = 0;
2663			if ((entry->port_type == CTL_PORT_NONE)
2664			 && (entry->targ_port == port->targ_port)) {
2665				/*
2666				 * If the user only wants to enable or
2667				 * disable or set WWNs on a specific port,
2668				 * do the operation and we're done.
2669				 */
2670				action = 1;
2671				done = 1;
2672			} else if (entry->port_type & port->port_type) {
2673				/*
2674				 * Compare the user's type mask with the
2675				 * particular frontend type to see if we
2676				 * have a match.
2677				 */
2678				action = 1;
2679				done = 0;
2680
2681				/*
2682				 * Make sure the user isn't trying to set
2683				 * WWNs on multiple ports at the same time.
2684				 */
2685				if (cmd == CTL_SET_PORT_WWNS) {
2686					printf("%s: Can't set WWNs on "
2687					       "multiple ports\n", __func__);
2688					retval = EINVAL;
2689					break;
2690				}
2691			}
2692			if (action == 0)
2693				continue;
2694
2695			/*
2696			 * XXX KDM we have to drop the lock here, because
2697			 * the online/offline operations can potentially
2698			 * block.  We need to reference count the frontends
2699			 * so they can't go away,
2700			 */
2701			if (cmd == CTL_ENABLE_PORT) {
2702				mtx_unlock(&softc->ctl_lock);
2703				ctl_port_online(port);
2704				mtx_lock(&softc->ctl_lock);
2705			} else if (cmd == CTL_DISABLE_PORT) {
2706				mtx_unlock(&softc->ctl_lock);
2707				ctl_port_offline(port);
2708				mtx_lock(&softc->ctl_lock);
2709			} else if (cmd == CTL_SET_PORT_WWNS) {
2710				ctl_port_set_wwns(port,
2711				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2712				    1 : 0, entry->wwnn,
2713				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2714				    1 : 0, entry->wwpn);
2715			}
2716			if (done != 0)
2717				break;
2718		}
2719		mtx_unlock(&softc->ctl_lock);
2720		break;
2721	}
2722	case CTL_GET_OOA: {
2723		struct ctl_ooa *ooa_hdr;
2724		struct ctl_ooa_entry *entries;
2725		uint32_t cur_fill_num;
2726
2727		ooa_hdr = (struct ctl_ooa *)addr;
2728
2729		if ((ooa_hdr->alloc_len == 0)
2730		 || (ooa_hdr->alloc_num == 0)) {
2731			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2732			       "must be non-zero\n", __func__,
2733			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2734			retval = EINVAL;
2735			break;
2736		}
2737
2738		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2739		    sizeof(struct ctl_ooa_entry))) {
2740			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2741			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2742			       __func__, ooa_hdr->alloc_len,
2743			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2744			retval = EINVAL;
2745			break;
2746		}
2747
2748		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2749		if (entries == NULL) {
2750			printf("%s: could not allocate %d bytes for OOA "
2751			       "dump\n", __func__, ooa_hdr->alloc_len);
2752			retval = ENOMEM;
2753			break;
2754		}
2755
2756		mtx_lock(&softc->ctl_lock);
2757		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2758		    (ooa_hdr->lun_num >= ctl_max_luns ||
2759		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2760			mtx_unlock(&softc->ctl_lock);
2761			free(entries, M_CTL);
2762			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2763			       __func__, (uintmax_t)ooa_hdr->lun_num);
2764			retval = EINVAL;
2765			break;
2766		}
2767
2768		cur_fill_num = 0;
2769
2770		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2771			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2772				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2773				    ooa_hdr, entries);
2774			}
2775		} else {
2776			lun = softc->ctl_luns[ooa_hdr->lun_num];
2777			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2778			    entries);
2779		}
2780		mtx_unlock(&softc->ctl_lock);
2781
2782		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2783		ooa_hdr->fill_len = ooa_hdr->fill_num *
2784			sizeof(struct ctl_ooa_entry);
2785		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2786		if (retval != 0) {
2787			printf("%s: error copying out %d bytes for OOA dump\n",
2788			       __func__, ooa_hdr->fill_len);
2789		}
2790
2791		getbinuptime(&ooa_hdr->cur_bt);
2792
2793		if (cur_fill_num > ooa_hdr->alloc_num) {
2794			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2795			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2796		} else {
2797			ooa_hdr->dropped_num = 0;
2798			ooa_hdr->status = CTL_OOA_OK;
2799		}
2800
2801		free(entries, M_CTL);
2802		break;
2803	}
2804	case CTL_DELAY_IO: {
2805		struct ctl_io_delay_info *delay_info;
2806
2807		delay_info = (struct ctl_io_delay_info *)addr;
2808
2809#ifdef CTL_IO_DELAY
2810		mtx_lock(&softc->ctl_lock);
2811		if (delay_info->lun_id >= ctl_max_luns ||
2812		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2813			mtx_unlock(&softc->ctl_lock);
2814			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2815			break;
2816		}
2817		mtx_lock(&lun->lun_lock);
2818		mtx_unlock(&softc->ctl_lock);
2819		delay_info->status = CTL_DELAY_STATUS_OK;
2820		switch (delay_info->delay_type) {
2821		case CTL_DELAY_TYPE_CONT:
2822		case CTL_DELAY_TYPE_ONESHOT:
2823			break;
2824		default:
2825			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2826			break;
2827		}
2828		switch (delay_info->delay_loc) {
2829		case CTL_DELAY_LOC_DATAMOVE:
2830			lun->delay_info.datamove_type = delay_info->delay_type;
2831			lun->delay_info.datamove_delay = delay_info->delay_secs;
2832			break;
2833		case CTL_DELAY_LOC_DONE:
2834			lun->delay_info.done_type = delay_info->delay_type;
2835			lun->delay_info.done_delay = delay_info->delay_secs;
2836			break;
2837		default:
2838			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2839			break;
2840		}
2841		mtx_unlock(&lun->lun_lock);
2842#else
2843		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2844#endif /* CTL_IO_DELAY */
2845		break;
2846	}
2847#ifdef CTL_LEGACY_STATS
2848	case CTL_GETSTATS: {
2849		struct ctl_stats *stats = (struct ctl_stats *)addr;
2850		int i;
2851
2852		/*
2853		 * XXX KDM no locking here.  If the LUN list changes,
2854		 * things can blow up.
2855		 */
2856		i = 0;
2857		stats->status = CTL_SS_OK;
2858		stats->fill_len = 0;
2859		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2860			if (stats->fill_len + sizeof(lun->legacy_stats) >
2861			    stats->alloc_len) {
2862				stats->status = CTL_SS_NEED_MORE_SPACE;
2863				break;
2864			}
2865			retval = copyout(&lun->legacy_stats, &stats->lun_stats[i++],
2866					 sizeof(lun->legacy_stats));
2867			if (retval != 0)
2868				break;
2869			stats->fill_len += sizeof(lun->legacy_stats);
2870		}
2871		stats->num_luns = softc->num_luns;
2872		stats->flags = CTL_STATS_FLAG_NONE;
2873#ifdef CTL_TIME_IO
2874		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
2875#endif
2876		getnanouptime(&stats->timestamp);
2877		break;
2878	}
2879#endif /* CTL_LEGACY_STATS */
2880	case CTL_ERROR_INJECT: {
2881		struct ctl_error_desc *err_desc, *new_err_desc;
2882
2883		err_desc = (struct ctl_error_desc *)addr;
2884
2885		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2886				      M_WAITOK | M_ZERO);
2887		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2888
2889		mtx_lock(&softc->ctl_lock);
2890		if (err_desc->lun_id >= ctl_max_luns ||
2891		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2892			mtx_unlock(&softc->ctl_lock);
2893			free(new_err_desc, M_CTL);
2894			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2895			       __func__, (uintmax_t)err_desc->lun_id);
2896			retval = EINVAL;
2897			break;
2898		}
2899		mtx_lock(&lun->lun_lock);
2900		mtx_unlock(&softc->ctl_lock);
2901
2902		/*
2903		 * We could do some checking here to verify the validity
2904		 * of the request, but given the complexity of error
2905		 * injection requests, the checking logic would be fairly
2906		 * complex.
2907		 *
2908		 * For now, if the request is invalid, it just won't get
2909		 * executed and might get deleted.
2910		 */
2911		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2912
2913		/*
2914		 * XXX KDM check to make sure the serial number is unique,
2915		 * in case we somehow manage to wrap.  That shouldn't
2916		 * happen for a very long time, but it's the right thing to
2917		 * do.
2918		 */
2919		new_err_desc->serial = lun->error_serial;
2920		err_desc->serial = lun->error_serial;
2921		lun->error_serial++;
2922
2923		mtx_unlock(&lun->lun_lock);
2924		break;
2925	}
2926	case CTL_ERROR_INJECT_DELETE: {
2927		struct ctl_error_desc *delete_desc, *desc, *desc2;
2928		int delete_done;
2929
2930		delete_desc = (struct ctl_error_desc *)addr;
2931		delete_done = 0;
2932
2933		mtx_lock(&softc->ctl_lock);
2934		if (delete_desc->lun_id >= ctl_max_luns ||
2935		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2936			mtx_unlock(&softc->ctl_lock);
2937			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2938			       __func__, (uintmax_t)delete_desc->lun_id);
2939			retval = EINVAL;
2940			break;
2941		}
2942		mtx_lock(&lun->lun_lock);
2943		mtx_unlock(&softc->ctl_lock);
2944		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2945			if (desc->serial != delete_desc->serial)
2946				continue;
2947
2948			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2949				      links);
2950			free(desc, M_CTL);
2951			delete_done = 1;
2952		}
2953		mtx_unlock(&lun->lun_lock);
2954		if (delete_done == 0) {
2955			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2956			       "error serial %ju on LUN %u\n", __func__,
2957			       delete_desc->serial, delete_desc->lun_id);
2958			retval = EINVAL;
2959			break;
2960		}
2961		break;
2962	}
2963	case CTL_DUMP_STRUCTS: {
2964		int j, k;
2965		struct ctl_port *port;
2966		struct ctl_frontend *fe;
2967
2968		mtx_lock(&softc->ctl_lock);
2969		printf("CTL Persistent Reservation information start:\n");
2970		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2971			mtx_lock(&lun->lun_lock);
2972			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2973				mtx_unlock(&lun->lun_lock);
2974				continue;
2975			}
2976
2977			for (j = 0; j < ctl_max_ports; j++) {
2978				if (lun->pr_keys[j] == NULL)
2979					continue;
2980				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2981					if (lun->pr_keys[j][k] == 0)
2982						continue;
2983					printf("  LUN %ju port %d iid %d key "
2984					       "%#jx\n", lun->lun, j, k,
2985					       (uintmax_t)lun->pr_keys[j][k]);
2986				}
2987			}
2988			mtx_unlock(&lun->lun_lock);
2989		}
2990		printf("CTL Persistent Reservation information end\n");
2991		printf("CTL Ports:\n");
2992		STAILQ_FOREACH(port, &softc->port_list, links) {
2993			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2994			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2995			       port->frontend->name, port->port_type,
2996			       port->physical_port, port->virtual_port,
2997			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2998			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2999				if (port->wwpn_iid[j].in_use == 0 &&
3000				    port->wwpn_iid[j].wwpn == 0 &&
3001				    port->wwpn_iid[j].name == NULL)
3002					continue;
3003
3004				printf("    iid %u use %d WWPN %#jx '%s'\n",
3005				    j, port->wwpn_iid[j].in_use,
3006				    (uintmax_t)port->wwpn_iid[j].wwpn,
3007				    port->wwpn_iid[j].name);
3008			}
3009		}
3010		printf("CTL Port information end\n");
3011		mtx_unlock(&softc->ctl_lock);
3012		/*
3013		 * XXX KDM calling this without a lock.  We'd likely want
3014		 * to drop the lock before calling the frontend's dump
3015		 * routine anyway.
3016		 */
3017		printf("CTL Frontends:\n");
3018		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3019			printf("  Frontend '%s'\n", fe->name);
3020			if (fe->fe_dump != NULL)
3021				fe->fe_dump();
3022		}
3023		printf("CTL Frontend information end\n");
3024		break;
3025	}
3026	case CTL_LUN_REQ: {
3027		struct ctl_lun_req *lun_req;
3028		struct ctl_backend_driver *backend;
3029
3030		lun_req = (struct ctl_lun_req *)addr;
3031
3032		backend = ctl_backend_find(lun_req->backend);
3033		if (backend == NULL) {
3034			lun_req->status = CTL_LUN_ERROR;
3035			snprintf(lun_req->error_str,
3036				 sizeof(lun_req->error_str),
3037				 "Backend \"%s\" not found.",
3038				 lun_req->backend);
3039			break;
3040		}
3041		if (lun_req->num_be_args > 0) {
3042			lun_req->kern_be_args = ctl_copyin_args(
3043				lun_req->num_be_args,
3044				lun_req->be_args,
3045				lun_req->error_str,
3046				sizeof(lun_req->error_str));
3047			if (lun_req->kern_be_args == NULL) {
3048				lun_req->status = CTL_LUN_ERROR;
3049				break;
3050			}
3051		}
3052
3053		retval = backend->ioctl(dev, cmd, addr, flag, td);
3054
3055		if (lun_req->num_be_args > 0) {
3056			ctl_copyout_args(lun_req->num_be_args,
3057				      lun_req->kern_be_args);
3058			ctl_free_args(lun_req->num_be_args,
3059				      lun_req->kern_be_args);
3060		}
3061		break;
3062	}
3063	case CTL_LUN_LIST: {
3064		struct sbuf *sb;
3065		struct ctl_lun_list *list;
3066		struct ctl_option *opt;
3067
3068		list = (struct ctl_lun_list *)addr;
3069
3070		/*
3071		 * Allocate a fixed length sbuf here, based on the length
3072		 * of the user's buffer.  We could allocate an auto-extending
3073		 * buffer, and then tell the user how much larger our
3074		 * amount of data is than his buffer, but that presents
3075		 * some problems:
3076		 *
3077		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3078		 *     we can't hold a lock while calling them with an
3079		 *     auto-extending buffer.
3080 		 *
3081		 * 2.  There is not currently a LUN reference counting
3082		 *     mechanism, outside of outstanding transactions on
3083		 *     the LUN's OOA queue.  So a LUN could go away on us
3084		 *     while we're getting the LUN number, backend-specific
3085		 *     information, etc.  Thus, given the way things
3086		 *     currently work, we need to hold the CTL lock while
3087		 *     grabbing LUN information.
3088		 *
3089		 * So, from the user's standpoint, the best thing to do is
3090		 * allocate what he thinks is a reasonable buffer length,
3091		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3092		 * double the buffer length and try again.  (And repeat
3093		 * that until he succeeds.)
3094		 */
3095		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3096		if (sb == NULL) {
3097			list->status = CTL_LUN_LIST_ERROR;
3098			snprintf(list->error_str, sizeof(list->error_str),
3099				 "Unable to allocate %d bytes for LUN list",
3100				 list->alloc_len);
3101			break;
3102		}
3103
3104		sbuf_printf(sb, "<ctllunlist>\n");
3105
3106		mtx_lock(&softc->ctl_lock);
3107		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3108			mtx_lock(&lun->lun_lock);
3109			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3110					     (uintmax_t)lun->lun);
3111
3112			/*
3113			 * Bail out as soon as we see that we've overfilled
3114			 * the buffer.
3115			 */
3116			if (retval != 0)
3117				break;
3118
3119			retval = sbuf_printf(sb, "\t<backend_type>%s"
3120					     "</backend_type>\n",
3121					     (lun->backend == NULL) ?  "none" :
3122					     lun->backend->name);
3123
3124			if (retval != 0)
3125				break;
3126
3127			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3128					     lun->be_lun->lun_type);
3129
3130			if (retval != 0)
3131				break;
3132
3133			if (lun->backend == NULL) {
3134				retval = sbuf_printf(sb, "</lun>\n");
3135				if (retval != 0)
3136					break;
3137				continue;
3138			}
3139
3140			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3141					     (lun->be_lun->maxlba > 0) ?
3142					     lun->be_lun->maxlba + 1 : 0);
3143
3144			if (retval != 0)
3145				break;
3146
3147			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3148					     lun->be_lun->blocksize);
3149
3150			if (retval != 0)
3151				break;
3152
3153			retval = sbuf_printf(sb, "\t<serial_number>");
3154
3155			if (retval != 0)
3156				break;
3157
3158			retval = ctl_sbuf_printf_esc(sb,
3159			    lun->be_lun->serial_num,
3160			    sizeof(lun->be_lun->serial_num));
3161
3162			if (retval != 0)
3163				break;
3164
3165			retval = sbuf_printf(sb, "</serial_number>\n");
3166
3167			if (retval != 0)
3168				break;
3169
3170			retval = sbuf_printf(sb, "\t<device_id>");
3171
3172			if (retval != 0)
3173				break;
3174
3175			retval = ctl_sbuf_printf_esc(sb,
3176			    lun->be_lun->device_id,
3177			    sizeof(lun->be_lun->device_id));
3178
3179			if (retval != 0)
3180				break;
3181
3182			retval = sbuf_printf(sb, "</device_id>\n");
3183
3184			if (retval != 0)
3185				break;
3186
3187			if (lun->backend->lun_info != NULL) {
3188				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3189				if (retval != 0)
3190					break;
3191			}
3192			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3193				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3194				    opt->name, opt->value, opt->name);
3195				if (retval != 0)
3196					break;
3197			}
3198
3199			retval = sbuf_printf(sb, "</lun>\n");
3200
3201			if (retval != 0)
3202				break;
3203			mtx_unlock(&lun->lun_lock);
3204		}
3205		if (lun != NULL)
3206			mtx_unlock(&lun->lun_lock);
3207		mtx_unlock(&softc->ctl_lock);
3208
3209		if ((retval != 0)
3210		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3211			retval = 0;
3212			sbuf_delete(sb);
3213			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3214			snprintf(list->error_str, sizeof(list->error_str),
3215				 "Out of space, %d bytes is too small",
3216				 list->alloc_len);
3217			break;
3218		}
3219
3220		sbuf_finish(sb);
3221
3222		retval = copyout(sbuf_data(sb), list->lun_xml,
3223				 sbuf_len(sb) + 1);
3224
3225		list->fill_len = sbuf_len(sb) + 1;
3226		list->status = CTL_LUN_LIST_OK;
3227		sbuf_delete(sb);
3228		break;
3229	}
3230	case CTL_ISCSI: {
3231		struct ctl_iscsi *ci;
3232		struct ctl_frontend *fe;
3233
3234		ci = (struct ctl_iscsi *)addr;
3235
3236		fe = ctl_frontend_find("iscsi");
3237		if (fe == NULL) {
3238			ci->status = CTL_ISCSI_ERROR;
3239			snprintf(ci->error_str, sizeof(ci->error_str),
3240			    "Frontend \"iscsi\" not found.");
3241			break;
3242		}
3243
3244		retval = fe->ioctl(dev, cmd, addr, flag, td);
3245		break;
3246	}
3247	case CTL_PORT_REQ: {
3248		struct ctl_req *req;
3249		struct ctl_frontend *fe;
3250
3251		req = (struct ctl_req *)addr;
3252
3253		fe = ctl_frontend_find(req->driver);
3254		if (fe == NULL) {
3255			req->status = CTL_LUN_ERROR;
3256			snprintf(req->error_str, sizeof(req->error_str),
3257			    "Frontend \"%s\" not found.", req->driver);
3258			break;
3259		}
3260		if (req->num_args > 0) {
3261			req->kern_args = ctl_copyin_args(req->num_args,
3262			    req->args, req->error_str, sizeof(req->error_str));
3263			if (req->kern_args == NULL) {
3264				req->status = CTL_LUN_ERROR;
3265				break;
3266			}
3267		}
3268
3269		if (fe->ioctl)
3270			retval = fe->ioctl(dev, cmd, addr, flag, td);
3271		else
3272			retval = ENODEV;
3273
3274		if (req->num_args > 0) {
3275			ctl_copyout_args(req->num_args, req->kern_args);
3276			ctl_free_args(req->num_args, req->kern_args);
3277		}
3278		break;
3279	}
3280	case CTL_PORT_LIST: {
3281		struct sbuf *sb;
3282		struct ctl_port *port;
3283		struct ctl_lun_list *list;
3284		struct ctl_option *opt;
3285		int j;
3286		uint32_t plun;
3287
3288		list = (struct ctl_lun_list *)addr;
3289
3290		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3291		if (sb == NULL) {
3292			list->status = CTL_LUN_LIST_ERROR;
3293			snprintf(list->error_str, sizeof(list->error_str),
3294				 "Unable to allocate %d bytes for LUN list",
3295				 list->alloc_len);
3296			break;
3297		}
3298
3299		sbuf_printf(sb, "<ctlportlist>\n");
3300
3301		mtx_lock(&softc->ctl_lock);
3302		STAILQ_FOREACH(port, &softc->port_list, links) {
3303			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3304					     (uintmax_t)port->targ_port);
3305
3306			/*
3307			 * Bail out as soon as we see that we've overfilled
3308			 * the buffer.
3309			 */
3310			if (retval != 0)
3311				break;
3312
3313			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3314			    "</frontend_type>\n", port->frontend->name);
3315			if (retval != 0)
3316				break;
3317
3318			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3319					     port->port_type);
3320			if (retval != 0)
3321				break;
3322
3323			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3324			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3325			if (retval != 0)
3326				break;
3327
3328			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3329			    port->port_name);
3330			if (retval != 0)
3331				break;
3332
3333			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3334			    port->physical_port);
3335			if (retval != 0)
3336				break;
3337
3338			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3339			    port->virtual_port);
3340			if (retval != 0)
3341				break;
3342
3343			if (port->target_devid != NULL) {
3344				sbuf_printf(sb, "\t<target>");
3345				ctl_id_sbuf(port->target_devid, sb);
3346				sbuf_printf(sb, "</target>\n");
3347			}
3348
3349			if (port->port_devid != NULL) {
3350				sbuf_printf(sb, "\t<port>");
3351				ctl_id_sbuf(port->port_devid, sb);
3352				sbuf_printf(sb, "</port>\n");
3353			}
3354
3355			if (port->port_info != NULL) {
3356				retval = port->port_info(port->onoff_arg, sb);
3357				if (retval != 0)
3358					break;
3359			}
3360			STAILQ_FOREACH(opt, &port->options, links) {
3361				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3362				    opt->name, opt->value, opt->name);
3363				if (retval != 0)
3364					break;
3365			}
3366
3367			if (port->lun_map != NULL) {
3368				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3369				for (j = 0; j < port->lun_map_size; j++) {
3370					plun = ctl_lun_map_from_port(port, j);
3371					if (plun == UINT32_MAX)
3372						continue;
3373					sbuf_printf(sb,
3374					    "\t<lun id=\"%u\">%u</lun>\n",
3375					    j, plun);
3376				}
3377			}
3378
3379			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3380				if (port->wwpn_iid[j].in_use == 0 ||
3381				    (port->wwpn_iid[j].wwpn == 0 &&
3382				     port->wwpn_iid[j].name == NULL))
3383					continue;
3384
3385				if (port->wwpn_iid[j].name != NULL)
3386					retval = sbuf_printf(sb,
3387					    "\t<initiator id=\"%u\">%s</initiator>\n",
3388					    j, port->wwpn_iid[j].name);
3389				else
3390					retval = sbuf_printf(sb,
3391					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3392					    j, port->wwpn_iid[j].wwpn);
3393				if (retval != 0)
3394					break;
3395			}
3396			if (retval != 0)
3397				break;
3398
3399			retval = sbuf_printf(sb, "</targ_port>\n");
3400			if (retval != 0)
3401				break;
3402		}
3403		mtx_unlock(&softc->ctl_lock);
3404
3405		if ((retval != 0)
3406		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3407			retval = 0;
3408			sbuf_delete(sb);
3409			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3410			snprintf(list->error_str, sizeof(list->error_str),
3411				 "Out of space, %d bytes is too small",
3412				 list->alloc_len);
3413			break;
3414		}
3415
3416		sbuf_finish(sb);
3417
3418		retval = copyout(sbuf_data(sb), list->lun_xml,
3419				 sbuf_len(sb) + 1);
3420
3421		list->fill_len = sbuf_len(sb) + 1;
3422		list->status = CTL_LUN_LIST_OK;
3423		sbuf_delete(sb);
3424		break;
3425	}
3426	case CTL_LUN_MAP: {
3427		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3428		struct ctl_port *port;
3429
3430		mtx_lock(&softc->ctl_lock);
3431		if (lm->port < softc->port_min ||
3432		    lm->port >= softc->port_max ||
3433		    (port = softc->ctl_ports[lm->port]) == NULL) {
3434			mtx_unlock(&softc->ctl_lock);
3435			return (ENXIO);
3436		}
3437		if (port->status & CTL_PORT_STATUS_ONLINE) {
3438			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3439				if (ctl_lun_map_to_port(port, lun->lun) ==
3440				    UINT32_MAX)
3441					continue;
3442				mtx_lock(&lun->lun_lock);
3443				ctl_est_ua_port(lun, lm->port, -1,
3444				    CTL_UA_LUN_CHANGE);
3445				mtx_unlock(&lun->lun_lock);
3446			}
3447		}
3448		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3449		if (lm->plun != UINT32_MAX) {
3450			if (lm->lun == UINT32_MAX)
3451				retval = ctl_lun_map_unset(port, lm->plun);
3452			else if (lm->lun < ctl_max_luns &&
3453			    softc->ctl_luns[lm->lun] != NULL)
3454				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3455			else
3456				return (ENXIO);
3457		} else {
3458			if (lm->lun == UINT32_MAX)
3459				retval = ctl_lun_map_deinit(port);
3460			else
3461				retval = ctl_lun_map_init(port);
3462		}
3463		if (port->status & CTL_PORT_STATUS_ONLINE)
3464			ctl_isc_announce_port(port);
3465		break;
3466	}
3467	case CTL_GET_LUN_STATS: {
3468		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3469		int i;
3470
3471		/*
3472		 * XXX KDM no locking here.  If the LUN list changes,
3473		 * things can blow up.
3474		 */
3475		i = 0;
3476		stats->status = CTL_SS_OK;
3477		stats->fill_len = 0;
3478		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3479			if (lun->lun < stats->first_item)
3480				continue;
3481			if (stats->fill_len + sizeof(lun->stats) >
3482			    stats->alloc_len) {
3483				stats->status = CTL_SS_NEED_MORE_SPACE;
3484				break;
3485			}
3486			retval = copyout(&lun->stats, &stats->stats[i++],
3487					 sizeof(lun->stats));
3488			if (retval != 0)
3489				break;
3490			stats->fill_len += sizeof(lun->stats);
3491		}
3492		stats->num_items = softc->num_luns;
3493		stats->flags = CTL_STATS_FLAG_NONE;
3494#ifdef CTL_TIME_IO
3495		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3496#endif
3497		getnanouptime(&stats->timestamp);
3498		break;
3499	}
3500	case CTL_GET_PORT_STATS: {
3501		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3502		int i;
3503
3504		/*
3505		 * XXX KDM no locking here.  If the LUN list changes,
3506		 * things can blow up.
3507		 */
3508		i = 0;
3509		stats->status = CTL_SS_OK;
3510		stats->fill_len = 0;
3511		STAILQ_FOREACH(port, &softc->port_list, links) {
3512			if (port->targ_port < stats->first_item)
3513				continue;
3514			if (stats->fill_len + sizeof(port->stats) >
3515			    stats->alloc_len) {
3516				stats->status = CTL_SS_NEED_MORE_SPACE;
3517				break;
3518			}
3519			retval = copyout(&port->stats, &stats->stats[i++],
3520					 sizeof(port->stats));
3521			if (retval != 0)
3522				break;
3523			stats->fill_len += sizeof(port->stats);
3524		}
3525		stats->num_items = softc->num_ports;
3526		stats->flags = CTL_STATS_FLAG_NONE;
3527#ifdef CTL_TIME_IO
3528		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3529#endif
3530		getnanouptime(&stats->timestamp);
3531		break;
3532	}
3533	default: {
3534		/* XXX KDM should we fix this? */
3535#if 0
3536		struct ctl_backend_driver *backend;
3537		unsigned int type;
3538		int found;
3539
3540		found = 0;
3541
3542		/*
3543		 * We encode the backend type as the ioctl type for backend
3544		 * ioctls.  So parse it out here, and then search for a
3545		 * backend of this type.
3546		 */
3547		type = _IOC_TYPE(cmd);
3548
3549		STAILQ_FOREACH(backend, &softc->be_list, links) {
3550			if (backend->type == type) {
3551				found = 1;
3552				break;
3553			}
3554		}
3555		if (found == 0) {
3556			printf("ctl: unknown ioctl command %#lx or backend "
3557			       "%d\n", cmd, type);
3558			retval = EINVAL;
3559			break;
3560		}
3561		retval = backend->ioctl(dev, cmd, addr, flag, td);
3562#endif
3563		retval = ENOTTY;
3564		break;
3565	}
3566	}
3567	return (retval);
3568}
3569
3570uint32_t
3571ctl_get_initindex(struct ctl_nexus *nexus)
3572{
3573	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3574}
3575
3576int
3577ctl_lun_map_init(struct ctl_port *port)
3578{
3579	struct ctl_softc *softc = port->ctl_softc;
3580	struct ctl_lun *lun;
3581	int size = ctl_lun_map_size;
3582	uint32_t i;
3583
3584	if (port->lun_map == NULL || port->lun_map_size < size) {
3585		port->lun_map_size = 0;
3586		free(port->lun_map, M_CTL);
3587		port->lun_map = malloc(size * sizeof(uint32_t),
3588		    M_CTL, M_NOWAIT);
3589	}
3590	if (port->lun_map == NULL)
3591		return (ENOMEM);
3592	for (i = 0; i < size; i++)
3593		port->lun_map[i] = UINT32_MAX;
3594	port->lun_map_size = size;
3595	if (port->status & CTL_PORT_STATUS_ONLINE) {
3596		if (port->lun_disable != NULL) {
3597			STAILQ_FOREACH(lun, &softc->lun_list, links)
3598				port->lun_disable(port->targ_lun_arg, lun->lun);
3599		}
3600		ctl_isc_announce_port(port);
3601	}
3602	return (0);
3603}
3604
3605int
3606ctl_lun_map_deinit(struct ctl_port *port)
3607{
3608	struct ctl_softc *softc = port->ctl_softc;
3609	struct ctl_lun *lun;
3610
3611	if (port->lun_map == NULL)
3612		return (0);
3613	port->lun_map_size = 0;
3614	free(port->lun_map, M_CTL);
3615	port->lun_map = NULL;
3616	if (port->status & CTL_PORT_STATUS_ONLINE) {
3617		if (port->lun_enable != NULL) {
3618			STAILQ_FOREACH(lun, &softc->lun_list, links)
3619				port->lun_enable(port->targ_lun_arg, lun->lun);
3620		}
3621		ctl_isc_announce_port(port);
3622	}
3623	return (0);
3624}
3625
3626int
3627ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3628{
3629	int status;
3630	uint32_t old;
3631
3632	if (port->lun_map == NULL) {
3633		status = ctl_lun_map_init(port);
3634		if (status != 0)
3635			return (status);
3636	}
3637	if (plun >= port->lun_map_size)
3638		return (EINVAL);
3639	old = port->lun_map[plun];
3640	port->lun_map[plun] = glun;
3641	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3642		if (port->lun_enable != NULL)
3643			port->lun_enable(port->targ_lun_arg, plun);
3644		ctl_isc_announce_port(port);
3645	}
3646	return (0);
3647}
3648
3649int
3650ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3651{
3652	uint32_t old;
3653
3654	if (port->lun_map == NULL || plun >= port->lun_map_size)
3655		return (0);
3656	old = port->lun_map[plun];
3657	port->lun_map[plun] = UINT32_MAX;
3658	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3659		if (port->lun_disable != NULL)
3660			port->lun_disable(port->targ_lun_arg, plun);
3661		ctl_isc_announce_port(port);
3662	}
3663	return (0);
3664}
3665
3666uint32_t
3667ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3668{
3669
3670	if (port == NULL)
3671		return (UINT32_MAX);
3672	if (port->lun_map == NULL)
3673		return (lun_id);
3674	if (lun_id > port->lun_map_size)
3675		return (UINT32_MAX);
3676	return (port->lun_map[lun_id]);
3677}
3678
3679uint32_t
3680ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3681{
3682	uint32_t i;
3683
3684	if (port == NULL)
3685		return (UINT32_MAX);
3686	if (port->lun_map == NULL)
3687		return (lun_id);
3688	for (i = 0; i < port->lun_map_size; i++) {
3689		if (port->lun_map[i] == lun_id)
3690			return (i);
3691	}
3692	return (UINT32_MAX);
3693}
3694
3695uint32_t
3696ctl_decode_lun(uint64_t encoded)
3697{
3698	uint8_t lun[8];
3699	uint32_t result = 0xffffffff;
3700
3701	be64enc(lun, encoded);
3702	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3703	case RPL_LUNDATA_ATYP_PERIPH:
3704		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3705		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3706			result = lun[1];
3707		break;
3708	case RPL_LUNDATA_ATYP_FLAT:
3709		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3710		    lun[6] == 0 && lun[7] == 0)
3711			result = ((lun[0] & 0x3f) << 8) + lun[1];
3712		break;
3713	case RPL_LUNDATA_ATYP_EXTLUN:
3714		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3715		case 0x02:
3716			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3717			case 0x00:
3718				result = lun[1];
3719				break;
3720			case 0x10:
3721				result = (lun[1] << 16) + (lun[2] << 8) +
3722				    lun[3];
3723				break;
3724			case 0x20:
3725				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3726					result = (lun[2] << 24) +
3727					    (lun[3] << 16) + (lun[4] << 8) +
3728					    lun[5];
3729				break;
3730			}
3731			break;
3732		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3733			result = 0xffffffff;
3734			break;
3735		}
3736		break;
3737	}
3738	return (result);
3739}
3740
3741uint64_t
3742ctl_encode_lun(uint32_t decoded)
3743{
3744	uint64_t l = decoded;
3745
3746	if (l <= 0xff)
3747		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3748	if (l <= 0x3fff)
3749		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3750	if (l <= 0xffffff)
3751		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3752		    (l << 32));
3753	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3754}
3755
3756int
3757ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3758{
3759	int i;
3760
3761	for (i = first; i < last; i++) {
3762		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3763			return (i);
3764	}
3765	return (-1);
3766}
3767
3768int
3769ctl_set_mask(uint32_t *mask, uint32_t bit)
3770{
3771	uint32_t chunk, piece;
3772
3773	chunk = bit >> 5;
3774	piece = bit % (sizeof(uint32_t) * 8);
3775
3776	if ((mask[chunk] & (1 << piece)) != 0)
3777		return (-1);
3778	else
3779		mask[chunk] |= (1 << piece);
3780
3781	return (0);
3782}
3783
3784int
3785ctl_clear_mask(uint32_t *mask, uint32_t bit)
3786{
3787	uint32_t chunk, piece;
3788
3789	chunk = bit >> 5;
3790	piece = bit % (sizeof(uint32_t) * 8);
3791
3792	if ((mask[chunk] & (1 << piece)) == 0)
3793		return (-1);
3794	else
3795		mask[chunk] &= ~(1 << piece);
3796
3797	return (0);
3798}
3799
3800int
3801ctl_is_set(uint32_t *mask, uint32_t bit)
3802{
3803	uint32_t chunk, piece;
3804
3805	chunk = bit >> 5;
3806	piece = bit % (sizeof(uint32_t) * 8);
3807
3808	if ((mask[chunk] & (1 << piece)) == 0)
3809		return (0);
3810	else
3811		return (1);
3812}
3813
3814static uint64_t
3815ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3816{
3817	uint64_t *t;
3818
3819	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3820	if (t == NULL)
3821		return (0);
3822	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3823}
3824
3825static void
3826ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3827{
3828	uint64_t *t;
3829
3830	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3831	if (t == NULL)
3832		return;
3833	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3834}
3835
3836static void
3837ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3838{
3839	uint64_t *p;
3840	u_int i;
3841
3842	i = residx/CTL_MAX_INIT_PER_PORT;
3843	if (lun->pr_keys[i] != NULL)
3844		return;
3845	mtx_unlock(&lun->lun_lock);
3846	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3847	    M_WAITOK | M_ZERO);
3848	mtx_lock(&lun->lun_lock);
3849	if (lun->pr_keys[i] == NULL)
3850		lun->pr_keys[i] = p;
3851	else
3852		free(p, M_CTL);
3853}
3854
3855static void
3856ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3857{
3858	uint64_t *t;
3859
3860	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3861	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3862	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3863}
3864
3865/*
3866 * ctl_softc, pool_name, total_ctl_io are passed in.
3867 * npool is passed out.
3868 */
3869int
3870ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3871		uint32_t total_ctl_io, void **npool)
3872{
3873	struct ctl_io_pool *pool;
3874
3875	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3876					    M_NOWAIT | M_ZERO);
3877	if (pool == NULL)
3878		return (ENOMEM);
3879
3880	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3881	pool->ctl_softc = ctl_softc;
3882#ifdef IO_POOLS
3883	pool->zone = uma_zsecond_create(pool->name, NULL,
3884	    NULL, NULL, NULL, ctl_softc->io_zone);
3885	/* uma_prealloc(pool->zone, total_ctl_io); */
3886#else
3887	pool->zone = ctl_softc->io_zone;
3888#endif
3889
3890	*npool = pool;
3891	return (0);
3892}
3893
3894void
3895ctl_pool_free(struct ctl_io_pool *pool)
3896{
3897
3898	if (pool == NULL)
3899		return;
3900
3901#ifdef IO_POOLS
3902	uma_zdestroy(pool->zone);
3903#endif
3904	free(pool, M_CTL);
3905}
3906
3907union ctl_io *
3908ctl_alloc_io(void *pool_ref)
3909{
3910	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3911	union ctl_io *io;
3912
3913	io = uma_zalloc(pool->zone, M_WAITOK);
3914	if (io != NULL) {
3915		io->io_hdr.pool = pool_ref;
3916		CTL_SOFTC(io) = pool->ctl_softc;
3917	}
3918	return (io);
3919}
3920
3921union ctl_io *
3922ctl_alloc_io_nowait(void *pool_ref)
3923{
3924	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3925	union ctl_io *io;
3926
3927	io = uma_zalloc(pool->zone, M_NOWAIT);
3928	if (io != NULL) {
3929		io->io_hdr.pool = pool_ref;
3930		CTL_SOFTC(io) = pool->ctl_softc;
3931	}
3932	return (io);
3933}
3934
3935void
3936ctl_free_io(union ctl_io *io)
3937{
3938	struct ctl_io_pool *pool;
3939
3940	if (io == NULL)
3941		return;
3942
3943	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3944	uma_zfree(pool->zone, io);
3945}
3946
3947void
3948ctl_zero_io(union ctl_io *io)
3949{
3950	struct ctl_io_pool *pool;
3951
3952	if (io == NULL)
3953		return;
3954
3955	/*
3956	 * May need to preserve linked list pointers at some point too.
3957	 */
3958	pool = io->io_hdr.pool;
3959	memset(io, 0, sizeof(*io));
3960	io->io_hdr.pool = pool;
3961	CTL_SOFTC(io) = pool->ctl_softc;
3962}
3963
3964int
3965ctl_expand_number(const char *buf, uint64_t *num)
3966{
3967	char *endptr;
3968	uint64_t number;
3969	unsigned shift;
3970
3971	number = strtoq(buf, &endptr, 0);
3972
3973	switch (tolower((unsigned char)*endptr)) {
3974	case 'e':
3975		shift = 60;
3976		break;
3977	case 'p':
3978		shift = 50;
3979		break;
3980	case 't':
3981		shift = 40;
3982		break;
3983	case 'g':
3984		shift = 30;
3985		break;
3986	case 'm':
3987		shift = 20;
3988		break;
3989	case 'k':
3990		shift = 10;
3991		break;
3992	case 'b':
3993	case '\0': /* No unit. */
3994		*num = number;
3995		return (0);
3996	default:
3997		/* Unrecognized unit. */
3998		return (-1);
3999	}
4000
4001	if ((number << shift) >> shift != number) {
4002		/* Overflow */
4003		return (-1);
4004	}
4005	*num = number << shift;
4006	return (0);
4007}
4008
4009
4010/*
4011 * This routine could be used in the future to load default and/or saved
4012 * mode page parameters for a particuar lun.
4013 */
4014static int
4015ctl_init_page_index(struct ctl_lun *lun)
4016{
4017	int i, page_code;
4018	struct ctl_page_index *page_index;
4019	const char *value;
4020	uint64_t ival;
4021
4022	memcpy(&lun->mode_pages.index, page_index_template,
4023	       sizeof(page_index_template));
4024
4025	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4026
4027		page_index = &lun->mode_pages.index[i];
4028		if (lun->be_lun->lun_type == T_DIRECT &&
4029		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4030			continue;
4031		if (lun->be_lun->lun_type == T_PROCESSOR &&
4032		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4033			continue;
4034		if (lun->be_lun->lun_type == T_CDROM &&
4035		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4036			continue;
4037
4038		page_code = page_index->page_code & SMPH_PC_MASK;
4039		switch (page_code) {
4040		case SMS_RW_ERROR_RECOVERY_PAGE: {
4041			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4042			    ("subpage %#x for page %#x is incorrect!",
4043			    page_index->subpage, page_code));
4044			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4045			       &rw_er_page_default,
4046			       sizeof(rw_er_page_default));
4047			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4048			       &rw_er_page_changeable,
4049			       sizeof(rw_er_page_changeable));
4050			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4051			       &rw_er_page_default,
4052			       sizeof(rw_er_page_default));
4053			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4054			       &rw_er_page_default,
4055			       sizeof(rw_er_page_default));
4056			page_index->page_data =
4057				(uint8_t *)lun->mode_pages.rw_er_page;
4058			break;
4059		}
4060		case SMS_FORMAT_DEVICE_PAGE: {
4061			struct scsi_format_page *format_page;
4062
4063			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4064			    ("subpage %#x for page %#x is incorrect!",
4065			    page_index->subpage, page_code));
4066
4067			/*
4068			 * Sectors per track are set above.  Bytes per
4069			 * sector need to be set here on a per-LUN basis.
4070			 */
4071			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4072			       &format_page_default,
4073			       sizeof(format_page_default));
4074			memcpy(&lun->mode_pages.format_page[
4075			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4076			       sizeof(format_page_changeable));
4077			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4078			       &format_page_default,
4079			       sizeof(format_page_default));
4080			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4081			       &format_page_default,
4082			       sizeof(format_page_default));
4083
4084			format_page = &lun->mode_pages.format_page[
4085				CTL_PAGE_CURRENT];
4086			scsi_ulto2b(lun->be_lun->blocksize,
4087				    format_page->bytes_per_sector);
4088
4089			format_page = &lun->mode_pages.format_page[
4090				CTL_PAGE_DEFAULT];
4091			scsi_ulto2b(lun->be_lun->blocksize,
4092				    format_page->bytes_per_sector);
4093
4094			format_page = &lun->mode_pages.format_page[
4095				CTL_PAGE_SAVED];
4096			scsi_ulto2b(lun->be_lun->blocksize,
4097				    format_page->bytes_per_sector);
4098
4099			page_index->page_data =
4100				(uint8_t *)lun->mode_pages.format_page;
4101			break;
4102		}
4103		case SMS_RIGID_DISK_PAGE: {
4104			struct scsi_rigid_disk_page *rigid_disk_page;
4105			uint32_t sectors_per_cylinder;
4106			uint64_t cylinders;
4107#ifndef	__XSCALE__
4108			int shift;
4109#endif /* !__XSCALE__ */
4110
4111			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4112			    ("subpage %#x for page %#x is incorrect!",
4113			    page_index->subpage, page_code));
4114
4115			/*
4116			 * Rotation rate and sectors per track are set
4117			 * above.  We calculate the cylinders here based on
4118			 * capacity.  Due to the number of heads and
4119			 * sectors per track we're using, smaller arrays
4120			 * may turn out to have 0 cylinders.  Linux and
4121			 * FreeBSD don't pay attention to these mode pages
4122			 * to figure out capacity, but Solaris does.  It
4123			 * seems to deal with 0 cylinders just fine, and
4124			 * works out a fake geometry based on the capacity.
4125			 */
4126			memcpy(&lun->mode_pages.rigid_disk_page[
4127			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4128			       sizeof(rigid_disk_page_default));
4129			memcpy(&lun->mode_pages.rigid_disk_page[
4130			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4131			       sizeof(rigid_disk_page_changeable));
4132
4133			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4134				CTL_DEFAULT_HEADS;
4135
4136			/*
4137			 * The divide method here will be more accurate,
4138			 * probably, but results in floating point being
4139			 * used in the kernel on i386 (__udivdi3()).  On the
4140			 * XScale, though, __udivdi3() is implemented in
4141			 * software.
4142			 *
4143			 * The shift method for cylinder calculation is
4144			 * accurate if sectors_per_cylinder is a power of
4145			 * 2.  Otherwise it might be slightly off -- you
4146			 * might have a bit of a truncation problem.
4147			 */
4148#ifdef	__XSCALE__
4149			cylinders = (lun->be_lun->maxlba + 1) /
4150				sectors_per_cylinder;
4151#else
4152			for (shift = 31; shift > 0; shift--) {
4153				if (sectors_per_cylinder & (1 << shift))
4154					break;
4155			}
4156			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4157#endif
4158
4159			/*
4160			 * We've basically got 3 bytes, or 24 bits for the
4161			 * cylinder size in the mode page.  If we're over,
4162			 * just round down to 2^24.
4163			 */
4164			if (cylinders > 0xffffff)
4165				cylinders = 0xffffff;
4166
4167			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4168				CTL_PAGE_DEFAULT];
4169			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4170
4171			if ((value = ctl_get_opt(&lun->be_lun->options,
4172			    "rpm")) != NULL) {
4173				scsi_ulto2b(strtol(value, NULL, 0),
4174				     rigid_disk_page->rotation_rate);
4175			}
4176
4177			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4178			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4179			       sizeof(rigid_disk_page_default));
4180			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4181			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4182			       sizeof(rigid_disk_page_default));
4183
4184			page_index->page_data =
4185				(uint8_t *)lun->mode_pages.rigid_disk_page;
4186			break;
4187		}
4188		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4189			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4190			    ("subpage %#x for page %#x is incorrect!",
4191			    page_index->subpage, page_code));
4192			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4193			       &verify_er_page_default,
4194			       sizeof(verify_er_page_default));
4195			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4196			       &verify_er_page_changeable,
4197			       sizeof(verify_er_page_changeable));
4198			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4199			       &verify_er_page_default,
4200			       sizeof(verify_er_page_default));
4201			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4202			       &verify_er_page_default,
4203			       sizeof(verify_er_page_default));
4204			page_index->page_data =
4205				(uint8_t *)lun->mode_pages.verify_er_page;
4206			break;
4207		}
4208		case SMS_CACHING_PAGE: {
4209			struct scsi_caching_page *caching_page;
4210
4211			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4212			    ("subpage %#x for page %#x is incorrect!",
4213			    page_index->subpage, page_code));
4214			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4215			       &caching_page_default,
4216			       sizeof(caching_page_default));
4217			memcpy(&lun->mode_pages.caching_page[
4218			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4219			       sizeof(caching_page_changeable));
4220			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4221			       &caching_page_default,
4222			       sizeof(caching_page_default));
4223			caching_page = &lun->mode_pages.caching_page[
4224			    CTL_PAGE_SAVED];
4225			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4226			if (value != NULL && strcmp(value, "off") == 0)
4227				caching_page->flags1 &= ~SCP_WCE;
4228			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4229			if (value != NULL && strcmp(value, "off") == 0)
4230				caching_page->flags1 |= SCP_RCD;
4231			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4232			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4233			       sizeof(caching_page_default));
4234			page_index->page_data =
4235				(uint8_t *)lun->mode_pages.caching_page;
4236			break;
4237		}
4238		case SMS_CONTROL_MODE_PAGE: {
4239			switch (page_index->subpage) {
4240			case SMS_SUBPAGE_PAGE_0: {
4241				struct scsi_control_page *control_page;
4242
4243				memcpy(&lun->mode_pages.control_page[
4244				    CTL_PAGE_DEFAULT],
4245				       &control_page_default,
4246				       sizeof(control_page_default));
4247				memcpy(&lun->mode_pages.control_page[
4248				    CTL_PAGE_CHANGEABLE],
4249				       &control_page_changeable,
4250				       sizeof(control_page_changeable));
4251				memcpy(&lun->mode_pages.control_page[
4252				    CTL_PAGE_SAVED],
4253				       &control_page_default,
4254				       sizeof(control_page_default));
4255				control_page = &lun->mode_pages.control_page[
4256				    CTL_PAGE_SAVED];
4257				value = ctl_get_opt(&lun->be_lun->options,
4258				    "reordering");
4259				if (value != NULL &&
4260				    strcmp(value, "unrestricted") == 0) {
4261					control_page->queue_flags &=
4262					    ~SCP_QUEUE_ALG_MASK;
4263					control_page->queue_flags |=
4264					    SCP_QUEUE_ALG_UNRESTRICTED;
4265				}
4266				memcpy(&lun->mode_pages.control_page[
4267				    CTL_PAGE_CURRENT],
4268				       &lun->mode_pages.control_page[
4269				    CTL_PAGE_SAVED],
4270				       sizeof(control_page_default));
4271				page_index->page_data =
4272				    (uint8_t *)lun->mode_pages.control_page;
4273				break;
4274			}
4275			case 0x01:
4276				memcpy(&lun->mode_pages.control_ext_page[
4277				    CTL_PAGE_DEFAULT],
4278				       &control_ext_page_default,
4279				       sizeof(control_ext_page_default));
4280				memcpy(&lun->mode_pages.control_ext_page[
4281				    CTL_PAGE_CHANGEABLE],
4282				       &control_ext_page_changeable,
4283				       sizeof(control_ext_page_changeable));
4284				memcpy(&lun->mode_pages.control_ext_page[
4285				    CTL_PAGE_SAVED],
4286				       &control_ext_page_default,
4287				       sizeof(control_ext_page_default));
4288				memcpy(&lun->mode_pages.control_ext_page[
4289				    CTL_PAGE_CURRENT],
4290				       &lun->mode_pages.control_ext_page[
4291				    CTL_PAGE_SAVED],
4292				       sizeof(control_ext_page_default));
4293				page_index->page_data =
4294				    (uint8_t *)lun->mode_pages.control_ext_page;
4295				break;
4296			default:
4297				panic("subpage %#x for page %#x is incorrect!",
4298				      page_index->subpage, page_code);
4299			}
4300			break;
4301		}
4302		case SMS_INFO_EXCEPTIONS_PAGE: {
4303			switch (page_index->subpage) {
4304			case SMS_SUBPAGE_PAGE_0:
4305				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4306				       &ie_page_default,
4307				       sizeof(ie_page_default));
4308				memcpy(&lun->mode_pages.ie_page[
4309				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4310				       sizeof(ie_page_changeable));
4311				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4312				       &ie_page_default,
4313				       sizeof(ie_page_default));
4314				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4315				       &ie_page_default,
4316				       sizeof(ie_page_default));
4317				page_index->page_data =
4318					(uint8_t *)lun->mode_pages.ie_page;
4319				break;
4320			case 0x02: {
4321				struct ctl_logical_block_provisioning_page *page;
4322
4323				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4324				       &lbp_page_default,
4325				       sizeof(lbp_page_default));
4326				memcpy(&lun->mode_pages.lbp_page[
4327				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4328				       sizeof(lbp_page_changeable));
4329				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4330				       &lbp_page_default,
4331				       sizeof(lbp_page_default));
4332				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4333				value = ctl_get_opt(&lun->be_lun->options,
4334				    "avail-threshold");
4335				if (value != NULL &&
4336				    ctl_expand_number(value, &ival) == 0) {
4337					page->descr[0].flags |= SLBPPD_ENABLED |
4338					    SLBPPD_ARMING_DEC;
4339					if (lun->be_lun->blocksize)
4340						ival /= lun->be_lun->blocksize;
4341					else
4342						ival /= 512;
4343					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4344					    page->descr[0].count);
4345				}
4346				value = ctl_get_opt(&lun->be_lun->options,
4347				    "used-threshold");
4348				if (value != NULL &&
4349				    ctl_expand_number(value, &ival) == 0) {
4350					page->descr[1].flags |= SLBPPD_ENABLED |
4351					    SLBPPD_ARMING_INC;
4352					if (lun->be_lun->blocksize)
4353						ival /= lun->be_lun->blocksize;
4354					else
4355						ival /= 512;
4356					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4357					    page->descr[1].count);
4358				}
4359				value = ctl_get_opt(&lun->be_lun->options,
4360				    "pool-avail-threshold");
4361				if (value != NULL &&
4362				    ctl_expand_number(value, &ival) == 0) {
4363					page->descr[2].flags |= SLBPPD_ENABLED |
4364					    SLBPPD_ARMING_DEC;
4365					if (lun->be_lun->blocksize)
4366						ival /= lun->be_lun->blocksize;
4367					else
4368						ival /= 512;
4369					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4370					    page->descr[2].count);
4371				}
4372				value = ctl_get_opt(&lun->be_lun->options,
4373				    "pool-used-threshold");
4374				if (value != NULL &&
4375				    ctl_expand_number(value, &ival) == 0) {
4376					page->descr[3].flags |= SLBPPD_ENABLED |
4377					    SLBPPD_ARMING_INC;
4378					if (lun->be_lun->blocksize)
4379						ival /= lun->be_lun->blocksize;
4380					else
4381						ival /= 512;
4382					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4383					    page->descr[3].count);
4384				}
4385				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4386				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4387				       sizeof(lbp_page_default));
4388				page_index->page_data =
4389					(uint8_t *)lun->mode_pages.lbp_page;
4390				break;
4391			}
4392			default:
4393				panic("subpage %#x for page %#x is incorrect!",
4394				      page_index->subpage, page_code);
4395			}
4396			break;
4397		}
4398		case SMS_CDDVD_CAPS_PAGE:{
4399			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4400			    ("subpage %#x for page %#x is incorrect!",
4401			    page_index->subpage, page_code));
4402			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4403			       &cddvd_page_default,
4404			       sizeof(cddvd_page_default));
4405			memcpy(&lun->mode_pages.cddvd_page[
4406			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4407			       sizeof(cddvd_page_changeable));
4408			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4409			       &cddvd_page_default,
4410			       sizeof(cddvd_page_default));
4411			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4412			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4413			       sizeof(cddvd_page_default));
4414			page_index->page_data =
4415				(uint8_t *)lun->mode_pages.cddvd_page;
4416			break;
4417		}
4418		default:
4419			panic("invalid page code value %#x", page_code);
4420		}
4421	}
4422
4423	return (CTL_RETVAL_COMPLETE);
4424}
4425
4426static int
4427ctl_init_log_page_index(struct ctl_lun *lun)
4428{
4429	struct ctl_page_index *page_index;
4430	int i, j, k, prev;
4431
4432	memcpy(&lun->log_pages.index, log_page_index_template,
4433	       sizeof(log_page_index_template));
4434
4435	prev = -1;
4436	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4437
4438		page_index = &lun->log_pages.index[i];
4439		if (lun->be_lun->lun_type == T_DIRECT &&
4440		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4441			continue;
4442		if (lun->be_lun->lun_type == T_PROCESSOR &&
4443		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4444			continue;
4445		if (lun->be_lun->lun_type == T_CDROM &&
4446		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4447			continue;
4448
4449		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4450		    lun->backend->lun_attr == NULL)
4451			continue;
4452
4453		if (page_index->page_code != prev) {
4454			lun->log_pages.pages_page[j] = page_index->page_code;
4455			prev = page_index->page_code;
4456			j++;
4457		}
4458		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4459		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4460		k++;
4461	}
4462	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4463	lun->log_pages.index[0].page_len = j;
4464	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4465	lun->log_pages.index[1].page_len = k * 2;
4466	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4467	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4468	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4469	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4470	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4471	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4472
4473	return (CTL_RETVAL_COMPLETE);
4474}
4475
4476static int
4477hex2bin(const char *str, uint8_t *buf, int buf_size)
4478{
4479	int i;
4480	u_char c;
4481
4482	memset(buf, 0, buf_size);
4483	while (isspace(str[0]))
4484		str++;
4485	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4486		str += 2;
4487	buf_size *= 2;
4488	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4489		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4490			str++;
4491		c = str[i];
4492		if (isdigit(c))
4493			c -= '0';
4494		else if (isalpha(c))
4495			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4496		else
4497			break;
4498		if (c >= 16)
4499			break;
4500		if ((i & 1) == 0)
4501			buf[i / 2] |= (c << 4);
4502		else
4503			buf[i / 2] |= c;
4504	}
4505	return ((i + 1) / 2);
4506}
4507
4508/*
4509 * LUN allocation.
4510 *
4511 * Requirements:
4512 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4513 *   wants us to allocate the LUN and he can block.
4514 * - ctl_softc is always set
4515 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4516 *
4517 * Returns 0 for success, non-zero (errno) for failure.
4518 */
4519static int
4520ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4521	      struct ctl_be_lun *const be_lun)
4522{
4523	struct ctl_lun *nlun, *lun;
4524	struct scsi_vpd_id_descriptor *desc;
4525	struct scsi_vpd_id_t10 *t10id;
4526	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4527	int lun_number, lun_malloced;
4528	int devidlen, idlen1, idlen2 = 0, len;
4529
4530	if (be_lun == NULL)
4531		return (EINVAL);
4532
4533	/*
4534	 * We currently only support Direct Access or Processor LUN types.
4535	 */
4536	switch (be_lun->lun_type) {
4537	case T_DIRECT:
4538	case T_PROCESSOR:
4539	case T_CDROM:
4540		break;
4541	case T_SEQUENTIAL:
4542	case T_CHANGER:
4543	default:
4544		be_lun->lun_config_status(be_lun->be_lun,
4545					  CTL_LUN_CONFIG_FAILURE);
4546		break;
4547	}
4548	if (ctl_lun == NULL) {
4549		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4550		lun_malloced = 1;
4551	} else {
4552		lun_malloced = 0;
4553		lun = ctl_lun;
4554	}
4555
4556	memset(lun, 0, sizeof(*lun));
4557	if (lun_malloced)
4558		lun->flags = CTL_LUN_MALLOCED;
4559
4560	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4561	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4562	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4563	    M_DEVBUF, M_WAITOK | M_ZERO);
4564	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4565	    M_DEVBUF, M_WAITOK | M_ZERO);
4566
4567	/* Generate LUN ID. */
4568	devidlen = max(CTL_DEVID_MIN_LEN,
4569	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4570	idlen1 = sizeof(*t10id) + devidlen;
4571	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4572	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4573	if (scsiname != NULL) {
4574		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4575		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4576	}
4577	eui = ctl_get_opt(&be_lun->options, "eui");
4578	if (eui != NULL) {
4579		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4580	}
4581	naa = ctl_get_opt(&be_lun->options, "naa");
4582	if (naa != NULL) {
4583		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4584	}
4585	uuid = ctl_get_opt(&be_lun->options, "uuid");
4586	if (uuid != NULL) {
4587		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4588	}
4589	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4590	    M_CTL, M_WAITOK | M_ZERO);
4591	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4592	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4593	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4594	desc->length = idlen1;
4595	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4596	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4597	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4598		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4599	} else {
4600		strncpy(t10id->vendor, vendor,
4601		    min(sizeof(t10id->vendor), strlen(vendor)));
4602	}
4603	strncpy((char *)t10id->vendor_spec_id,
4604	    (char *)be_lun->device_id, devidlen);
4605	if (scsiname != NULL) {
4606		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4607		    desc->length);
4608		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4609		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4610		    SVPD_ID_TYPE_SCSI_NAME;
4611		desc->length = idlen2;
4612		strlcpy(desc->identifier, scsiname, idlen2);
4613	}
4614	if (eui != NULL) {
4615		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4616		    desc->length);
4617		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4618		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4619		    SVPD_ID_TYPE_EUI64;
4620		desc->length = hex2bin(eui, desc->identifier, 16);
4621		desc->length = desc->length > 12 ? 16 :
4622		    (desc->length > 8 ? 12 : 8);
4623		len -= 16 - desc->length;
4624	}
4625	if (naa != NULL) {
4626		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4627		    desc->length);
4628		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4629		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4630		    SVPD_ID_TYPE_NAA;
4631		desc->length = hex2bin(naa, desc->identifier, 16);
4632		desc->length = desc->length > 8 ? 16 : 8;
4633		len -= 16 - desc->length;
4634	}
4635	if (uuid != NULL) {
4636		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4637		    desc->length);
4638		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4639		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4640		    SVPD_ID_TYPE_UUID;
4641		desc->identifier[0] = 0x10;
4642		hex2bin(uuid, &desc->identifier[2], 16);
4643		desc->length = 18;
4644	}
4645	lun->lun_devid->len = len;
4646
4647	mtx_lock(&ctl_softc->ctl_lock);
4648	/*
4649	 * See if the caller requested a particular LUN number.  If so, see
4650	 * if it is available.  Otherwise, allocate the first available LUN.
4651	 */
4652	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4653		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4654		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4655			mtx_unlock(&ctl_softc->ctl_lock);
4656			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4657				printf("ctl: requested LUN ID %d is higher "
4658				       "than ctl_max_luns - 1 (%d)\n",
4659				       be_lun->req_lun_id, ctl_max_luns - 1);
4660			} else {
4661				/*
4662				 * XXX KDM return an error, or just assign
4663				 * another LUN ID in this case??
4664				 */
4665				printf("ctl: requested LUN ID %d is already "
4666				       "in use\n", be_lun->req_lun_id);
4667			}
4668fail:
4669			free(lun->lun_devid, M_CTL);
4670			if (lun->flags & CTL_LUN_MALLOCED)
4671				free(lun, M_CTL);
4672			be_lun->lun_config_status(be_lun->be_lun,
4673						  CTL_LUN_CONFIG_FAILURE);
4674			return (ENOSPC);
4675		}
4676		lun_number = be_lun->req_lun_id;
4677	} else {
4678		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4679		if (lun_number == -1) {
4680			mtx_unlock(&ctl_softc->ctl_lock);
4681			printf("ctl: can't allocate LUN, out of LUNs\n");
4682			goto fail;
4683		}
4684	}
4685	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4686	mtx_unlock(&ctl_softc->ctl_lock);
4687
4688	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4689	lun->lun = lun_number;
4690	lun->be_lun = be_lun;
4691	/*
4692	 * The processor LUN is always enabled.  Disk LUNs come on line
4693	 * disabled, and must be enabled by the backend.
4694	 */
4695	lun->flags |= CTL_LUN_DISABLED;
4696	lun->backend = be_lun->be;
4697	be_lun->ctl_lun = lun;
4698	be_lun->lun_id = lun_number;
4699	atomic_add_int(&be_lun->be->num_luns, 1);
4700	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4701		lun->flags |= CTL_LUN_EJECTED;
4702	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4703		lun->flags |= CTL_LUN_NO_MEDIA;
4704	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4705		lun->flags |= CTL_LUN_STOPPED;
4706
4707	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4708		lun->flags |= CTL_LUN_PRIMARY_SC;
4709
4710	value = ctl_get_opt(&be_lun->options, "removable");
4711	if (value != NULL) {
4712		if (strcmp(value, "on") == 0)
4713			lun->flags |= CTL_LUN_REMOVABLE;
4714	} else if (be_lun->lun_type == T_CDROM)
4715		lun->flags |= CTL_LUN_REMOVABLE;
4716
4717	lun->ctl_softc = ctl_softc;
4718#ifdef CTL_TIME_IO
4719	lun->last_busy = getsbinuptime();
4720#endif
4721	TAILQ_INIT(&lun->ooa_queue);
4722	TAILQ_INIT(&lun->blocked_queue);
4723	STAILQ_INIT(&lun->error_list);
4724	lun->ie_reported = 1;
4725	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4726	ctl_tpc_lun_init(lun);
4727	if (lun->flags & CTL_LUN_REMOVABLE) {
4728		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4729		    M_CTL, M_WAITOK);
4730	}
4731
4732	/*
4733	 * Initialize the mode and log page index.
4734	 */
4735	ctl_init_page_index(lun);
4736	ctl_init_log_page_index(lun);
4737
4738	/* Setup statistics gathering */
4739#ifdef CTL_LEGACY_STATS
4740	lun->legacy_stats.device_type = be_lun->lun_type;
4741	lun->legacy_stats.lun_number = lun_number;
4742	lun->legacy_stats.blocksize = be_lun->blocksize;
4743	if (be_lun->blocksize == 0)
4744		lun->legacy_stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4745	lun->legacy_stats.ports = malloc(sizeof(struct ctl_lun_io_port_stats) *
4746	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4747	for (len = 0; len < ctl_max_ports; len++)
4748		lun->legacy_stats.ports[len].targ_port = len;
4749#endif /* CTL_LEGACY_STATS */
4750	lun->stats.item = lun_number;
4751
4752	/*
4753	 * Now, before we insert this lun on the lun list, set the lun
4754	 * inventory changed UA for all other luns.
4755	 */
4756	mtx_lock(&ctl_softc->ctl_lock);
4757	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4758		mtx_lock(&nlun->lun_lock);
4759		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4760		mtx_unlock(&nlun->lun_lock);
4761	}
4762	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4763	ctl_softc->ctl_luns[lun_number] = lun;
4764	ctl_softc->num_luns++;
4765	mtx_unlock(&ctl_softc->ctl_lock);
4766
4767	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4768	return (0);
4769}
4770
4771/*
4772 * Delete a LUN.
4773 * Assumptions:
4774 * - LUN has already been marked invalid and any pending I/O has been taken
4775 *   care of.
4776 */
4777static int
4778ctl_free_lun(struct ctl_lun *lun)
4779{
4780	struct ctl_softc *softc = lun->ctl_softc;
4781	struct ctl_lun *nlun;
4782	int i;
4783
4784	KASSERT(TAILQ_EMPTY(&lun->ooa_queue),
4785	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4786
4787	mtx_lock(&softc->ctl_lock);
4788	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4789	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4790	softc->ctl_luns[lun->lun] = NULL;
4791	softc->num_luns--;
4792	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4793		mtx_lock(&nlun->lun_lock);
4794		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4795		mtx_unlock(&nlun->lun_lock);
4796	}
4797	mtx_unlock(&softc->ctl_lock);
4798
4799	/*
4800	 * Tell the backend to free resources, if this LUN has a backend.
4801	 */
4802	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4803	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4804
4805	lun->ie_reportcnt = UINT32_MAX;
4806	callout_drain(&lun->ie_callout);
4807	ctl_tpc_lun_shutdown(lun);
4808	mtx_destroy(&lun->lun_lock);
4809	free(lun->lun_devid, M_CTL);
4810	for (i = 0; i < ctl_max_ports; i++)
4811		free(lun->pending_ua[i], M_CTL);
4812	free(lun->pending_ua, M_DEVBUF);
4813	for (i = 0; i < ctl_max_ports; i++)
4814		free(lun->pr_keys[i], M_CTL);
4815	free(lun->pr_keys, M_DEVBUF);
4816	free(lun->write_buffer, M_CTL);
4817	free(lun->prevent, M_CTL);
4818	if (lun->flags & CTL_LUN_MALLOCED)
4819		free(lun, M_CTL);
4820
4821	return (0);
4822}
4823
4824static void
4825ctl_create_lun(struct ctl_be_lun *be_lun)
4826{
4827
4828	/*
4829	 * ctl_alloc_lun() should handle all potential failure cases.
4830	 */
4831	ctl_alloc_lun(control_softc, NULL, be_lun);
4832}
4833
4834int
4835ctl_add_lun(struct ctl_be_lun *be_lun)
4836{
4837	struct ctl_softc *softc = control_softc;
4838
4839	mtx_lock(&softc->ctl_lock);
4840	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4841	mtx_unlock(&softc->ctl_lock);
4842	wakeup(&softc->pending_lun_queue);
4843
4844	return (0);
4845}
4846
4847int
4848ctl_enable_lun(struct ctl_be_lun *be_lun)
4849{
4850	struct ctl_softc *softc;
4851	struct ctl_port *port, *nport;
4852	struct ctl_lun *lun;
4853	int retval;
4854
4855	lun = (struct ctl_lun *)be_lun->ctl_lun;
4856	softc = lun->ctl_softc;
4857
4858	mtx_lock(&softc->ctl_lock);
4859	mtx_lock(&lun->lun_lock);
4860	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4861		/*
4862		 * eh?  Why did we get called if the LUN is already
4863		 * enabled?
4864		 */
4865		mtx_unlock(&lun->lun_lock);
4866		mtx_unlock(&softc->ctl_lock);
4867		return (0);
4868	}
4869	lun->flags &= ~CTL_LUN_DISABLED;
4870	mtx_unlock(&lun->lun_lock);
4871
4872	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4873		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4874		    port->lun_map != NULL || port->lun_enable == NULL)
4875			continue;
4876
4877		/*
4878		 * Drop the lock while we call the FETD's enable routine.
4879		 * This can lead to a callback into CTL (at least in the
4880		 * case of the internal initiator frontend.
4881		 */
4882		mtx_unlock(&softc->ctl_lock);
4883		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4884		mtx_lock(&softc->ctl_lock);
4885		if (retval != 0) {
4886			printf("%s: FETD %s port %d returned error "
4887			       "%d for lun_enable on lun %jd\n",
4888			       __func__, port->port_name, port->targ_port,
4889			       retval, (intmax_t)lun->lun);
4890		}
4891	}
4892
4893	mtx_unlock(&softc->ctl_lock);
4894	ctl_isc_announce_lun(lun);
4895
4896	return (0);
4897}
4898
4899int
4900ctl_disable_lun(struct ctl_be_lun *be_lun)
4901{
4902	struct ctl_softc *softc;
4903	struct ctl_port *port;
4904	struct ctl_lun *lun;
4905	int retval;
4906
4907	lun = (struct ctl_lun *)be_lun->ctl_lun;
4908	softc = lun->ctl_softc;
4909
4910	mtx_lock(&softc->ctl_lock);
4911	mtx_lock(&lun->lun_lock);
4912	if (lun->flags & CTL_LUN_DISABLED) {
4913		mtx_unlock(&lun->lun_lock);
4914		mtx_unlock(&softc->ctl_lock);
4915		return (0);
4916	}
4917	lun->flags |= CTL_LUN_DISABLED;
4918	mtx_unlock(&lun->lun_lock);
4919
4920	STAILQ_FOREACH(port, &softc->port_list, links) {
4921		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4922		    port->lun_map != NULL || port->lun_disable == NULL)
4923			continue;
4924
4925		/*
4926		 * Drop the lock before we call the frontend's disable
4927		 * routine, to avoid lock order reversals.
4928		 *
4929		 * XXX KDM what happens if the frontend list changes while
4930		 * we're traversing it?  It's unlikely, but should be handled.
4931		 */
4932		mtx_unlock(&softc->ctl_lock);
4933		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4934		mtx_lock(&softc->ctl_lock);
4935		if (retval != 0) {
4936			printf("%s: FETD %s port %d returned error "
4937			       "%d for lun_disable on lun %jd\n",
4938			       __func__, port->port_name, port->targ_port,
4939			       retval, (intmax_t)lun->lun);
4940		}
4941	}
4942
4943	mtx_unlock(&softc->ctl_lock);
4944	ctl_isc_announce_lun(lun);
4945
4946	return (0);
4947}
4948
4949int
4950ctl_start_lun(struct ctl_be_lun *be_lun)
4951{
4952	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4953
4954	mtx_lock(&lun->lun_lock);
4955	lun->flags &= ~CTL_LUN_STOPPED;
4956	mtx_unlock(&lun->lun_lock);
4957	return (0);
4958}
4959
4960int
4961ctl_stop_lun(struct ctl_be_lun *be_lun)
4962{
4963	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4964
4965	mtx_lock(&lun->lun_lock);
4966	lun->flags |= CTL_LUN_STOPPED;
4967	mtx_unlock(&lun->lun_lock);
4968	return (0);
4969}
4970
4971int
4972ctl_lun_no_media(struct ctl_be_lun *be_lun)
4973{
4974	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4975
4976	mtx_lock(&lun->lun_lock);
4977	lun->flags |= CTL_LUN_NO_MEDIA;
4978	mtx_unlock(&lun->lun_lock);
4979	return (0);
4980}
4981
4982int
4983ctl_lun_has_media(struct ctl_be_lun *be_lun)
4984{
4985	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4986	union ctl_ha_msg msg;
4987
4988	mtx_lock(&lun->lun_lock);
4989	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4990	if (lun->flags & CTL_LUN_REMOVABLE)
4991		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4992	mtx_unlock(&lun->lun_lock);
4993	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4994	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4995		bzero(&msg.ua, sizeof(msg.ua));
4996		msg.hdr.msg_type = CTL_MSG_UA;
4997		msg.hdr.nexus.initid = -1;
4998		msg.hdr.nexus.targ_port = -1;
4999		msg.hdr.nexus.targ_lun = lun->lun;
5000		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5001		msg.ua.ua_all = 1;
5002		msg.ua.ua_set = 1;
5003		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
5004		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5005		    M_WAITOK);
5006	}
5007	return (0);
5008}
5009
5010int
5011ctl_lun_ejected(struct ctl_be_lun *be_lun)
5012{
5013	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5014
5015	mtx_lock(&lun->lun_lock);
5016	lun->flags |= CTL_LUN_EJECTED;
5017	mtx_unlock(&lun->lun_lock);
5018	return (0);
5019}
5020
5021int
5022ctl_lun_primary(struct ctl_be_lun *be_lun)
5023{
5024	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5025
5026	mtx_lock(&lun->lun_lock);
5027	lun->flags |= CTL_LUN_PRIMARY_SC;
5028	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5029	mtx_unlock(&lun->lun_lock);
5030	ctl_isc_announce_lun(lun);
5031	return (0);
5032}
5033
5034int
5035ctl_lun_secondary(struct ctl_be_lun *be_lun)
5036{
5037	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5038
5039	mtx_lock(&lun->lun_lock);
5040	lun->flags &= ~CTL_LUN_PRIMARY_SC;
5041	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5042	mtx_unlock(&lun->lun_lock);
5043	ctl_isc_announce_lun(lun);
5044	return (0);
5045}
5046
5047int
5048ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5049{
5050	struct ctl_softc *softc;
5051	struct ctl_lun *lun;
5052
5053	lun = (struct ctl_lun *)be_lun->ctl_lun;
5054	softc = lun->ctl_softc;
5055
5056	mtx_lock(&lun->lun_lock);
5057
5058	/*
5059	 * The LUN needs to be disabled before it can be marked invalid.
5060	 */
5061	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5062		mtx_unlock(&lun->lun_lock);
5063		return (-1);
5064	}
5065	/*
5066	 * Mark the LUN invalid.
5067	 */
5068	lun->flags |= CTL_LUN_INVALID;
5069
5070	/*
5071	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5072	 * If we have something in the OOA queue, we'll free it when the
5073	 * last I/O completes.
5074	 */
5075	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5076		mtx_unlock(&lun->lun_lock);
5077		ctl_free_lun(lun);
5078	} else
5079		mtx_unlock(&lun->lun_lock);
5080
5081	return (0);
5082}
5083
5084void
5085ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5086{
5087	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5088	union ctl_ha_msg msg;
5089
5090	mtx_lock(&lun->lun_lock);
5091	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5092	mtx_unlock(&lun->lun_lock);
5093	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5094		/* Send msg to other side. */
5095		bzero(&msg.ua, sizeof(msg.ua));
5096		msg.hdr.msg_type = CTL_MSG_UA;
5097		msg.hdr.nexus.initid = -1;
5098		msg.hdr.nexus.targ_port = -1;
5099		msg.hdr.nexus.targ_lun = lun->lun;
5100		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5101		msg.ua.ua_all = 1;
5102		msg.ua.ua_set = 1;
5103		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5104		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5105		    M_WAITOK);
5106	}
5107}
5108
5109/*
5110 * Backend "memory move is complete" callback for requests that never
5111 * make it down to say RAIDCore's configuration code.
5112 */
5113int
5114ctl_config_move_done(union ctl_io *io)
5115{
5116	int retval;
5117
5118	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5119	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5120	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5121
5122	if ((io->io_hdr.port_status != 0) &&
5123	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5124	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5125		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5126		    /*retry_count*/ io->io_hdr.port_status);
5127	} else if (io->scsiio.kern_data_resid != 0 &&
5128	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5129	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5130	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5131		ctl_set_invalid_field_ciu(&io->scsiio);
5132	}
5133
5134	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5135		ctl_data_print(io);
5136	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5137	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5138	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5139	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5140		/*
5141		 * XXX KDM just assuming a single pointer here, and not a
5142		 * S/G list.  If we start using S/G lists for config data,
5143		 * we'll need to know how to clean them up here as well.
5144		 */
5145		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5146			free(io->scsiio.kern_data_ptr, M_CTL);
5147		ctl_done(io);
5148		retval = CTL_RETVAL_COMPLETE;
5149	} else {
5150		/*
5151		 * XXX KDM now we need to continue data movement.  Some
5152		 * options:
5153		 * - call ctl_scsiio() again?  We don't do this for data
5154		 *   writes, because for those at least we know ahead of
5155		 *   time where the write will go and how long it is.  For
5156		 *   config writes, though, that information is largely
5157		 *   contained within the write itself, thus we need to
5158		 *   parse out the data again.
5159		 *
5160		 * - Call some other function once the data is in?
5161		 */
5162
5163		/*
5164		 * XXX KDM call ctl_scsiio() again for now, and check flag
5165		 * bits to see whether we're allocated or not.
5166		 */
5167		retval = ctl_scsiio(&io->scsiio);
5168	}
5169	return (retval);
5170}
5171
5172/*
5173 * This gets called by a backend driver when it is done with a
5174 * data_submit method.
5175 */
5176void
5177ctl_data_submit_done(union ctl_io *io)
5178{
5179	/*
5180	 * If the IO_CONT flag is set, we need to call the supplied
5181	 * function to continue processing the I/O, instead of completing
5182	 * the I/O just yet.
5183	 *
5184	 * If there is an error, though, we don't want to keep processing.
5185	 * Instead, just send status back to the initiator.
5186	 */
5187	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5188	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5189	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5190	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5191		io->scsiio.io_cont(io);
5192		return;
5193	}
5194	ctl_done(io);
5195}
5196
5197/*
5198 * This gets called by a backend driver when it is done with a
5199 * configuration write.
5200 */
5201void
5202ctl_config_write_done(union ctl_io *io)
5203{
5204	uint8_t *buf;
5205
5206	/*
5207	 * If the IO_CONT flag is set, we need to call the supplied
5208	 * function to continue processing the I/O, instead of completing
5209	 * the I/O just yet.
5210	 *
5211	 * If there is an error, though, we don't want to keep processing.
5212	 * Instead, just send status back to the initiator.
5213	 */
5214	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5215	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5216	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5217	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5218		io->scsiio.io_cont(io);
5219		return;
5220	}
5221	/*
5222	 * Since a configuration write can be done for commands that actually
5223	 * have data allocated, like write buffer, and commands that have
5224	 * no data, like start/stop unit, we need to check here.
5225	 */
5226	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5227		buf = io->scsiio.kern_data_ptr;
5228	else
5229		buf = NULL;
5230	ctl_done(io);
5231	if (buf)
5232		free(buf, M_CTL);
5233}
5234
5235void
5236ctl_config_read_done(union ctl_io *io)
5237{
5238	uint8_t *buf;
5239
5240	/*
5241	 * If there is some error -- we are done, skip data transfer.
5242	 */
5243	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5244	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5245	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5246		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5247			buf = io->scsiio.kern_data_ptr;
5248		else
5249			buf = NULL;
5250		ctl_done(io);
5251		if (buf)
5252			free(buf, M_CTL);
5253		return;
5254	}
5255
5256	/*
5257	 * If the IO_CONT flag is set, we need to call the supplied
5258	 * function to continue processing the I/O, instead of completing
5259	 * the I/O just yet.
5260	 */
5261	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5262		io->scsiio.io_cont(io);
5263		return;
5264	}
5265
5266	ctl_datamove(io);
5267}
5268
5269/*
5270 * SCSI release command.
5271 */
5272int
5273ctl_scsi_release(struct ctl_scsiio *ctsio)
5274{
5275	struct ctl_lun *lun = CTL_LUN(ctsio);
5276	uint32_t residx;
5277
5278	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5279
5280	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5281
5282	/*
5283	 * XXX KDM right now, we only support LUN reservation.  We don't
5284	 * support 3rd party reservations, or extent reservations, which
5285	 * might actually need the parameter list.  If we've gotten this
5286	 * far, we've got a LUN reservation.  Anything else got kicked out
5287	 * above.  So, according to SPC, ignore the length.
5288	 */
5289
5290	mtx_lock(&lun->lun_lock);
5291
5292	/*
5293	 * According to SPC, it is not an error for an intiator to attempt
5294	 * to release a reservation on a LUN that isn't reserved, or that
5295	 * is reserved by another initiator.  The reservation can only be
5296	 * released, though, by the initiator who made it or by one of
5297	 * several reset type events.
5298	 */
5299	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5300			lun->flags &= ~CTL_LUN_RESERVED;
5301
5302	mtx_unlock(&lun->lun_lock);
5303
5304	ctl_set_success(ctsio);
5305	ctl_done((union ctl_io *)ctsio);
5306	return (CTL_RETVAL_COMPLETE);
5307}
5308
5309int
5310ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5311{
5312	struct ctl_lun *lun = CTL_LUN(ctsio);
5313	uint32_t residx;
5314
5315	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5316
5317	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5318
5319	/*
5320	 * XXX KDM right now, we only support LUN reservation.  We don't
5321	 * support 3rd party reservations, or extent reservations, which
5322	 * might actually need the parameter list.  If we've gotten this
5323	 * far, we've got a LUN reservation.  Anything else got kicked out
5324	 * above.  So, according to SPC, ignore the length.
5325	 */
5326
5327	mtx_lock(&lun->lun_lock);
5328	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5329		ctl_set_reservation_conflict(ctsio);
5330		goto bailout;
5331	}
5332
5333	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5334	if (lun->flags & CTL_LUN_PR_RESERVED) {
5335		ctl_set_success(ctsio);
5336		goto bailout;
5337	}
5338
5339	lun->flags |= CTL_LUN_RESERVED;
5340	lun->res_idx = residx;
5341	ctl_set_success(ctsio);
5342
5343bailout:
5344	mtx_unlock(&lun->lun_lock);
5345	ctl_done((union ctl_io *)ctsio);
5346	return (CTL_RETVAL_COMPLETE);
5347}
5348
5349int
5350ctl_start_stop(struct ctl_scsiio *ctsio)
5351{
5352	struct ctl_lun *lun = CTL_LUN(ctsio);
5353	struct scsi_start_stop_unit *cdb;
5354	int retval;
5355
5356	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5357
5358	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5359
5360	if ((cdb->how & SSS_PC_MASK) == 0) {
5361		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5362		    (cdb->how & SSS_START) == 0) {
5363			uint32_t residx;
5364
5365			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5366			if (ctl_get_prkey(lun, residx) == 0 ||
5367			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5368
5369				ctl_set_reservation_conflict(ctsio);
5370				ctl_done((union ctl_io *)ctsio);
5371				return (CTL_RETVAL_COMPLETE);
5372			}
5373		}
5374
5375		if ((cdb->how & SSS_LOEJ) &&
5376		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5377			ctl_set_invalid_field(ctsio,
5378					      /*sks_valid*/ 1,
5379					      /*command*/ 1,
5380					      /*field*/ 4,
5381					      /*bit_valid*/ 1,
5382					      /*bit*/ 1);
5383			ctl_done((union ctl_io *)ctsio);
5384			return (CTL_RETVAL_COMPLETE);
5385		}
5386
5387		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5388		    lun->prevent_count > 0) {
5389			/* "Medium removal prevented" */
5390			ctl_set_sense(ctsio, /*current_error*/ 1,
5391			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5392			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5393			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5394			ctl_done((union ctl_io *)ctsio);
5395			return (CTL_RETVAL_COMPLETE);
5396		}
5397	}
5398
5399	retval = lun->backend->config_write((union ctl_io *)ctsio);
5400	return (retval);
5401}
5402
5403int
5404ctl_prevent_allow(struct ctl_scsiio *ctsio)
5405{
5406	struct ctl_lun *lun = CTL_LUN(ctsio);
5407	struct scsi_prevent *cdb;
5408	int retval;
5409	uint32_t initidx;
5410
5411	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5412
5413	cdb = (struct scsi_prevent *)ctsio->cdb;
5414
5415	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5416		ctl_set_invalid_opcode(ctsio);
5417		ctl_done((union ctl_io *)ctsio);
5418		return (CTL_RETVAL_COMPLETE);
5419	}
5420
5421	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5422	mtx_lock(&lun->lun_lock);
5423	if ((cdb->how & PR_PREVENT) &&
5424	    ctl_is_set(lun->prevent, initidx) == 0) {
5425		ctl_set_mask(lun->prevent, initidx);
5426		lun->prevent_count++;
5427	} else if ((cdb->how & PR_PREVENT) == 0 &&
5428	    ctl_is_set(lun->prevent, initidx)) {
5429		ctl_clear_mask(lun->prevent, initidx);
5430		lun->prevent_count--;
5431	}
5432	mtx_unlock(&lun->lun_lock);
5433	retval = lun->backend->config_write((union ctl_io *)ctsio);
5434	return (retval);
5435}
5436
5437/*
5438 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5439 * we don't really do anything with the LBA and length fields if the user
5440 * passes them in.  Instead we'll just flush out the cache for the entire
5441 * LUN.
5442 */
5443int
5444ctl_sync_cache(struct ctl_scsiio *ctsio)
5445{
5446	struct ctl_lun *lun = CTL_LUN(ctsio);
5447	struct ctl_lba_len_flags *lbalen;
5448	uint64_t starting_lba;
5449	uint32_t block_count;
5450	int retval;
5451	uint8_t byte2;
5452
5453	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5454
5455	retval = 0;
5456
5457	switch (ctsio->cdb[0]) {
5458	case SYNCHRONIZE_CACHE: {
5459		struct scsi_sync_cache *cdb;
5460		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5461
5462		starting_lba = scsi_4btoul(cdb->begin_lba);
5463		block_count = scsi_2btoul(cdb->lb_count);
5464		byte2 = cdb->byte2;
5465		break;
5466	}
5467	case SYNCHRONIZE_CACHE_16: {
5468		struct scsi_sync_cache_16 *cdb;
5469		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5470
5471		starting_lba = scsi_8btou64(cdb->begin_lba);
5472		block_count = scsi_4btoul(cdb->lb_count);
5473		byte2 = cdb->byte2;
5474		break;
5475	}
5476	default:
5477		ctl_set_invalid_opcode(ctsio);
5478		ctl_done((union ctl_io *)ctsio);
5479		goto bailout;
5480		break; /* NOTREACHED */
5481	}
5482
5483	/*
5484	 * We check the LBA and length, but don't do anything with them.
5485	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5486	 * get flushed.  This check will just help satisfy anyone who wants
5487	 * to see an error for an out of range LBA.
5488	 */
5489	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5490		ctl_set_lba_out_of_range(ctsio,
5491		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5492		ctl_done((union ctl_io *)ctsio);
5493		goto bailout;
5494	}
5495
5496	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5497	lbalen->lba = starting_lba;
5498	lbalen->len = block_count;
5499	lbalen->flags = byte2;
5500	retval = lun->backend->config_write((union ctl_io *)ctsio);
5501
5502bailout:
5503	return (retval);
5504}
5505
5506int
5507ctl_format(struct ctl_scsiio *ctsio)
5508{
5509	struct scsi_format *cdb;
5510	int length, defect_list_len;
5511
5512	CTL_DEBUG_PRINT(("ctl_format\n"));
5513
5514	cdb = (struct scsi_format *)ctsio->cdb;
5515
5516	length = 0;
5517	if (cdb->byte2 & SF_FMTDATA) {
5518		if (cdb->byte2 & SF_LONGLIST)
5519			length = sizeof(struct scsi_format_header_long);
5520		else
5521			length = sizeof(struct scsi_format_header_short);
5522	}
5523
5524	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5525	 && (length > 0)) {
5526		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5527		ctsio->kern_data_len = length;
5528		ctsio->kern_total_len = length;
5529		ctsio->kern_rel_offset = 0;
5530		ctsio->kern_sg_entries = 0;
5531		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5532		ctsio->be_move_done = ctl_config_move_done;
5533		ctl_datamove((union ctl_io *)ctsio);
5534
5535		return (CTL_RETVAL_COMPLETE);
5536	}
5537
5538	defect_list_len = 0;
5539
5540	if (cdb->byte2 & SF_FMTDATA) {
5541		if (cdb->byte2 & SF_LONGLIST) {
5542			struct scsi_format_header_long *header;
5543
5544			header = (struct scsi_format_header_long *)
5545				ctsio->kern_data_ptr;
5546
5547			defect_list_len = scsi_4btoul(header->defect_list_len);
5548			if (defect_list_len != 0) {
5549				ctl_set_invalid_field(ctsio,
5550						      /*sks_valid*/ 1,
5551						      /*command*/ 0,
5552						      /*field*/ 2,
5553						      /*bit_valid*/ 0,
5554						      /*bit*/ 0);
5555				goto bailout;
5556			}
5557		} else {
5558			struct scsi_format_header_short *header;
5559
5560			header = (struct scsi_format_header_short *)
5561				ctsio->kern_data_ptr;
5562
5563			defect_list_len = scsi_2btoul(header->defect_list_len);
5564			if (defect_list_len != 0) {
5565				ctl_set_invalid_field(ctsio,
5566						      /*sks_valid*/ 1,
5567						      /*command*/ 0,
5568						      /*field*/ 2,
5569						      /*bit_valid*/ 0,
5570						      /*bit*/ 0);
5571				goto bailout;
5572			}
5573		}
5574	}
5575
5576	ctl_set_success(ctsio);
5577bailout:
5578
5579	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5580		free(ctsio->kern_data_ptr, M_CTL);
5581		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5582	}
5583
5584	ctl_done((union ctl_io *)ctsio);
5585	return (CTL_RETVAL_COMPLETE);
5586}
5587
5588int
5589ctl_read_buffer(struct ctl_scsiio *ctsio)
5590{
5591	struct ctl_lun *lun = CTL_LUN(ctsio);
5592	uint64_t buffer_offset;
5593	uint32_t len;
5594	uint8_t byte2;
5595	static uint8_t descr[4];
5596	static uint8_t echo_descr[4] = { 0 };
5597
5598	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5599
5600	switch (ctsio->cdb[0]) {
5601	case READ_BUFFER: {
5602		struct scsi_read_buffer *cdb;
5603
5604		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5605		buffer_offset = scsi_3btoul(cdb->offset);
5606		len = scsi_3btoul(cdb->length);
5607		byte2 = cdb->byte2;
5608		break;
5609	}
5610	case READ_BUFFER_16: {
5611		struct scsi_read_buffer_16 *cdb;
5612
5613		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5614		buffer_offset = scsi_8btou64(cdb->offset);
5615		len = scsi_4btoul(cdb->length);
5616		byte2 = cdb->byte2;
5617		break;
5618	}
5619	default: /* This shouldn't happen. */
5620		ctl_set_invalid_opcode(ctsio);
5621		ctl_done((union ctl_io *)ctsio);
5622		return (CTL_RETVAL_COMPLETE);
5623	}
5624
5625	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5626	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5627		ctl_set_invalid_field(ctsio,
5628				      /*sks_valid*/ 1,
5629				      /*command*/ 1,
5630				      /*field*/ 6,
5631				      /*bit_valid*/ 0,
5632				      /*bit*/ 0);
5633		ctl_done((union ctl_io *)ctsio);
5634		return (CTL_RETVAL_COMPLETE);
5635	}
5636
5637	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5638		descr[0] = 0;
5639		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5640		ctsio->kern_data_ptr = descr;
5641		len = min(len, sizeof(descr));
5642	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5643		ctsio->kern_data_ptr = echo_descr;
5644		len = min(len, sizeof(echo_descr));
5645	} else {
5646		if (lun->write_buffer == NULL) {
5647			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5648			    M_CTL, M_WAITOK);
5649		}
5650		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5651	}
5652	ctsio->kern_data_len = len;
5653	ctsio->kern_total_len = len;
5654	ctsio->kern_rel_offset = 0;
5655	ctsio->kern_sg_entries = 0;
5656	ctl_set_success(ctsio);
5657	ctsio->be_move_done = ctl_config_move_done;
5658	ctl_datamove((union ctl_io *)ctsio);
5659	return (CTL_RETVAL_COMPLETE);
5660}
5661
5662int
5663ctl_write_buffer(struct ctl_scsiio *ctsio)
5664{
5665	struct ctl_lun *lun = CTL_LUN(ctsio);
5666	struct scsi_write_buffer *cdb;
5667	int buffer_offset, len;
5668
5669	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5670
5671	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5672
5673	len = scsi_3btoul(cdb->length);
5674	buffer_offset = scsi_3btoul(cdb->offset);
5675
5676	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5677		ctl_set_invalid_field(ctsio,
5678				      /*sks_valid*/ 1,
5679				      /*command*/ 1,
5680				      /*field*/ 6,
5681				      /*bit_valid*/ 0,
5682				      /*bit*/ 0);
5683		ctl_done((union ctl_io *)ctsio);
5684		return (CTL_RETVAL_COMPLETE);
5685	}
5686
5687	/*
5688	 * If we've got a kernel request that hasn't been malloced yet,
5689	 * malloc it and tell the caller the data buffer is here.
5690	 */
5691	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5692		if (lun->write_buffer == NULL) {
5693			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5694			    M_CTL, M_WAITOK);
5695		}
5696		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5697		ctsio->kern_data_len = len;
5698		ctsio->kern_total_len = len;
5699		ctsio->kern_rel_offset = 0;
5700		ctsio->kern_sg_entries = 0;
5701		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5702		ctsio->be_move_done = ctl_config_move_done;
5703		ctl_datamove((union ctl_io *)ctsio);
5704
5705		return (CTL_RETVAL_COMPLETE);
5706	}
5707
5708	ctl_set_success(ctsio);
5709	ctl_done((union ctl_io *)ctsio);
5710	return (CTL_RETVAL_COMPLETE);
5711}
5712
5713int
5714ctl_write_same(struct ctl_scsiio *ctsio)
5715{
5716	struct ctl_lun *lun = CTL_LUN(ctsio);
5717	struct ctl_lba_len_flags *lbalen;
5718	uint64_t lba;
5719	uint32_t num_blocks;
5720	int len, retval;
5721	uint8_t byte2;
5722
5723	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5724
5725	switch (ctsio->cdb[0]) {
5726	case WRITE_SAME_10: {
5727		struct scsi_write_same_10 *cdb;
5728
5729		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5730
5731		lba = scsi_4btoul(cdb->addr);
5732		num_blocks = scsi_2btoul(cdb->length);
5733		byte2 = cdb->byte2;
5734		break;
5735	}
5736	case WRITE_SAME_16: {
5737		struct scsi_write_same_16 *cdb;
5738
5739		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5740
5741		lba = scsi_8btou64(cdb->addr);
5742		num_blocks = scsi_4btoul(cdb->length);
5743		byte2 = cdb->byte2;
5744		break;
5745	}
5746	default:
5747		/*
5748		 * We got a command we don't support.  This shouldn't
5749		 * happen, commands should be filtered out above us.
5750		 */
5751		ctl_set_invalid_opcode(ctsio);
5752		ctl_done((union ctl_io *)ctsio);
5753
5754		return (CTL_RETVAL_COMPLETE);
5755		break; /* NOTREACHED */
5756	}
5757
5758	/* ANCHOR flag can be used only together with UNMAP */
5759	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5760		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5761		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5762		ctl_done((union ctl_io *)ctsio);
5763		return (CTL_RETVAL_COMPLETE);
5764	}
5765
5766	/*
5767	 * The first check is to make sure we're in bounds, the second
5768	 * check is to catch wrap-around problems.  If the lba + num blocks
5769	 * is less than the lba, then we've wrapped around and the block
5770	 * range is invalid anyway.
5771	 */
5772	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5773	 || ((lba + num_blocks) < lba)) {
5774		ctl_set_lba_out_of_range(ctsio,
5775		    MAX(lba, lun->be_lun->maxlba + 1));
5776		ctl_done((union ctl_io *)ctsio);
5777		return (CTL_RETVAL_COMPLETE);
5778	}
5779
5780	/* Zero number of blocks means "to the last logical block" */
5781	if (num_blocks == 0) {
5782		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5783			ctl_set_invalid_field(ctsio,
5784					      /*sks_valid*/ 0,
5785					      /*command*/ 1,
5786					      /*field*/ 0,
5787					      /*bit_valid*/ 0,
5788					      /*bit*/ 0);
5789			ctl_done((union ctl_io *)ctsio);
5790			return (CTL_RETVAL_COMPLETE);
5791		}
5792		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5793	}
5794
5795	len = lun->be_lun->blocksize;
5796
5797	/*
5798	 * If we've got a kernel request that hasn't been malloced yet,
5799	 * malloc it and tell the caller the data buffer is here.
5800	 */
5801	if ((byte2 & SWS_NDOB) == 0 &&
5802	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5803		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5804		ctsio->kern_data_len = len;
5805		ctsio->kern_total_len = len;
5806		ctsio->kern_rel_offset = 0;
5807		ctsio->kern_sg_entries = 0;
5808		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5809		ctsio->be_move_done = ctl_config_move_done;
5810		ctl_datamove((union ctl_io *)ctsio);
5811
5812		return (CTL_RETVAL_COMPLETE);
5813	}
5814
5815	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5816	lbalen->lba = lba;
5817	lbalen->len = num_blocks;
5818	lbalen->flags = byte2;
5819	retval = lun->backend->config_write((union ctl_io *)ctsio);
5820
5821	return (retval);
5822}
5823
5824int
5825ctl_unmap(struct ctl_scsiio *ctsio)
5826{
5827	struct ctl_lun *lun = CTL_LUN(ctsio);
5828	struct scsi_unmap *cdb;
5829	struct ctl_ptr_len_flags *ptrlen;
5830	struct scsi_unmap_header *hdr;
5831	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5832	uint64_t lba;
5833	uint32_t num_blocks;
5834	int len, retval;
5835	uint8_t byte2;
5836
5837	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5838
5839	cdb = (struct scsi_unmap *)ctsio->cdb;
5840	len = scsi_2btoul(cdb->length);
5841	byte2 = cdb->byte2;
5842
5843	/*
5844	 * If we've got a kernel request that hasn't been malloced yet,
5845	 * malloc it and tell the caller the data buffer is here.
5846	 */
5847	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5848		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5849		ctsio->kern_data_len = len;
5850		ctsio->kern_total_len = len;
5851		ctsio->kern_rel_offset = 0;
5852		ctsio->kern_sg_entries = 0;
5853		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5854		ctsio->be_move_done = ctl_config_move_done;
5855		ctl_datamove((union ctl_io *)ctsio);
5856
5857		return (CTL_RETVAL_COMPLETE);
5858	}
5859
5860	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5861	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5862	if (len < sizeof (*hdr) ||
5863	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5864	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5865	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5866		ctl_set_invalid_field(ctsio,
5867				      /*sks_valid*/ 0,
5868				      /*command*/ 0,
5869				      /*field*/ 0,
5870				      /*bit_valid*/ 0,
5871				      /*bit*/ 0);
5872		goto done;
5873	}
5874	len = scsi_2btoul(hdr->desc_length);
5875	buf = (struct scsi_unmap_desc *)(hdr + 1);
5876	end = buf + len / sizeof(*buf);
5877
5878	endnz = buf;
5879	for (range = buf; range < end; range++) {
5880		lba = scsi_8btou64(range->lba);
5881		num_blocks = scsi_4btoul(range->length);
5882		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5883		 || ((lba + num_blocks) < lba)) {
5884			ctl_set_lba_out_of_range(ctsio,
5885			    MAX(lba, lun->be_lun->maxlba + 1));
5886			ctl_done((union ctl_io *)ctsio);
5887			return (CTL_RETVAL_COMPLETE);
5888		}
5889		if (num_blocks != 0)
5890			endnz = range + 1;
5891	}
5892
5893	/*
5894	 * Block backend can not handle zero last range.
5895	 * Filter it out and return if there is nothing left.
5896	 */
5897	len = (uint8_t *)endnz - (uint8_t *)buf;
5898	if (len == 0) {
5899		ctl_set_success(ctsio);
5900		goto done;
5901	}
5902
5903	mtx_lock(&lun->lun_lock);
5904	ptrlen = (struct ctl_ptr_len_flags *)
5905	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5906	ptrlen->ptr = (void *)buf;
5907	ptrlen->len = len;
5908	ptrlen->flags = byte2;
5909	ctl_check_blocked(lun);
5910	mtx_unlock(&lun->lun_lock);
5911
5912	retval = lun->backend->config_write((union ctl_io *)ctsio);
5913	return (retval);
5914
5915done:
5916	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5917		free(ctsio->kern_data_ptr, M_CTL);
5918		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5919	}
5920	ctl_done((union ctl_io *)ctsio);
5921	return (CTL_RETVAL_COMPLETE);
5922}
5923
5924int
5925ctl_default_page_handler(struct ctl_scsiio *ctsio,
5926			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5927{
5928	struct ctl_lun *lun = CTL_LUN(ctsio);
5929	uint8_t *current_cp;
5930	int set_ua;
5931	uint32_t initidx;
5932
5933	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5934	set_ua = 0;
5935
5936	current_cp = (page_index->page_data + (page_index->page_len *
5937	    CTL_PAGE_CURRENT));
5938
5939	mtx_lock(&lun->lun_lock);
5940	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5941		memcpy(current_cp, page_ptr, page_index->page_len);
5942		set_ua = 1;
5943	}
5944	if (set_ua != 0)
5945		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5946	mtx_unlock(&lun->lun_lock);
5947	if (set_ua) {
5948		ctl_isc_announce_mode(lun,
5949		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5950		    page_index->page_code, page_index->subpage);
5951	}
5952	return (CTL_RETVAL_COMPLETE);
5953}
5954
5955static void
5956ctl_ie_timer(void *arg)
5957{
5958	struct ctl_lun *lun = arg;
5959	uint64_t t;
5960
5961	if (lun->ie_asc == 0)
5962		return;
5963
5964	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5965		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5966	else
5967		lun->ie_reported = 0;
5968
5969	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5970		lun->ie_reportcnt++;
5971		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5972		if (t == 0 || t == UINT32_MAX)
5973			t = 3000;  /* 5 min */
5974		callout_schedule(&lun->ie_callout, t * hz / 10);
5975	}
5976}
5977
5978int
5979ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5980			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5981{
5982	struct ctl_lun *lun = CTL_LUN(ctsio);
5983	struct scsi_info_exceptions_page *pg;
5984	uint64_t t;
5985
5986	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5987
5988	pg = (struct scsi_info_exceptions_page *)page_ptr;
5989	mtx_lock(&lun->lun_lock);
5990	if (pg->info_flags & SIEP_FLAGS_TEST) {
5991		lun->ie_asc = 0x5d;
5992		lun->ie_ascq = 0xff;
5993		if (pg->mrie == SIEP_MRIE_UA) {
5994			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5995			lun->ie_reported = 1;
5996		} else {
5997			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5998			lun->ie_reported = -1;
5999		}
6000		lun->ie_reportcnt = 1;
6001		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
6002			lun->ie_reportcnt++;
6003			t = scsi_4btoul(pg->interval_timer);
6004			if (t == 0 || t == UINT32_MAX)
6005				t = 3000;  /* 5 min */
6006			callout_reset(&lun->ie_callout, t * hz / 10,
6007			    ctl_ie_timer, lun);
6008		}
6009	} else {
6010		lun->ie_asc = 0;
6011		lun->ie_ascq = 0;
6012		lun->ie_reported = 1;
6013		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6014		lun->ie_reportcnt = UINT32_MAX;
6015		callout_stop(&lun->ie_callout);
6016	}
6017	mtx_unlock(&lun->lun_lock);
6018	return (CTL_RETVAL_COMPLETE);
6019}
6020
6021static int
6022ctl_do_mode_select(union ctl_io *io)
6023{
6024	struct ctl_lun *lun = CTL_LUN(io);
6025	struct scsi_mode_page_header *page_header;
6026	struct ctl_page_index *page_index;
6027	struct ctl_scsiio *ctsio;
6028	int page_len, page_len_offset, page_len_size;
6029	union ctl_modepage_info *modepage_info;
6030	uint16_t *len_left, *len_used;
6031	int retval, i;
6032
6033	ctsio = &io->scsiio;
6034	page_index = NULL;
6035	page_len = 0;
6036
6037	modepage_info = (union ctl_modepage_info *)
6038		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6039	len_left = &modepage_info->header.len_left;
6040	len_used = &modepage_info->header.len_used;
6041
6042do_next_page:
6043
6044	page_header = (struct scsi_mode_page_header *)
6045		(ctsio->kern_data_ptr + *len_used);
6046
6047	if (*len_left == 0) {
6048		free(ctsio->kern_data_ptr, M_CTL);
6049		ctl_set_success(ctsio);
6050		ctl_done((union ctl_io *)ctsio);
6051		return (CTL_RETVAL_COMPLETE);
6052	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6053
6054		free(ctsio->kern_data_ptr, M_CTL);
6055		ctl_set_param_len_error(ctsio);
6056		ctl_done((union ctl_io *)ctsio);
6057		return (CTL_RETVAL_COMPLETE);
6058
6059	} else if ((page_header->page_code & SMPH_SPF)
6060		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6061
6062		free(ctsio->kern_data_ptr, M_CTL);
6063		ctl_set_param_len_error(ctsio);
6064		ctl_done((union ctl_io *)ctsio);
6065		return (CTL_RETVAL_COMPLETE);
6066	}
6067
6068
6069	/*
6070	 * XXX KDM should we do something with the block descriptor?
6071	 */
6072	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6073		page_index = &lun->mode_pages.index[i];
6074		if (lun->be_lun->lun_type == T_DIRECT &&
6075		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6076			continue;
6077		if (lun->be_lun->lun_type == T_PROCESSOR &&
6078		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6079			continue;
6080		if (lun->be_lun->lun_type == T_CDROM &&
6081		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6082			continue;
6083
6084		if ((page_index->page_code & SMPH_PC_MASK) !=
6085		    (page_header->page_code & SMPH_PC_MASK))
6086			continue;
6087
6088		/*
6089		 * If neither page has a subpage code, then we've got a
6090		 * match.
6091		 */
6092		if (((page_index->page_code & SMPH_SPF) == 0)
6093		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6094			page_len = page_header->page_length;
6095			break;
6096		}
6097
6098		/*
6099		 * If both pages have subpages, then the subpage numbers
6100		 * have to match.
6101		 */
6102		if ((page_index->page_code & SMPH_SPF)
6103		  && (page_header->page_code & SMPH_SPF)) {
6104			struct scsi_mode_page_header_sp *sph;
6105
6106			sph = (struct scsi_mode_page_header_sp *)page_header;
6107			if (page_index->subpage == sph->subpage) {
6108				page_len = scsi_2btoul(sph->page_length);
6109				break;
6110			}
6111		}
6112	}
6113
6114	/*
6115	 * If we couldn't find the page, or if we don't have a mode select
6116	 * handler for it, send back an error to the user.
6117	 */
6118	if ((i >= CTL_NUM_MODE_PAGES)
6119	 || (page_index->select_handler == NULL)) {
6120		ctl_set_invalid_field(ctsio,
6121				      /*sks_valid*/ 1,
6122				      /*command*/ 0,
6123				      /*field*/ *len_used,
6124				      /*bit_valid*/ 0,
6125				      /*bit*/ 0);
6126		free(ctsio->kern_data_ptr, M_CTL);
6127		ctl_done((union ctl_io *)ctsio);
6128		return (CTL_RETVAL_COMPLETE);
6129	}
6130
6131	if (page_index->page_code & SMPH_SPF) {
6132		page_len_offset = 2;
6133		page_len_size = 2;
6134	} else {
6135		page_len_size = 1;
6136		page_len_offset = 1;
6137	}
6138
6139	/*
6140	 * If the length the initiator gives us isn't the one we specify in
6141	 * the mode page header, or if they didn't specify enough data in
6142	 * the CDB to avoid truncating this page, kick out the request.
6143	 */
6144	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6145		ctl_set_invalid_field(ctsio,
6146				      /*sks_valid*/ 1,
6147				      /*command*/ 0,
6148				      /*field*/ *len_used + page_len_offset,
6149				      /*bit_valid*/ 0,
6150				      /*bit*/ 0);
6151		free(ctsio->kern_data_ptr, M_CTL);
6152		ctl_done((union ctl_io *)ctsio);
6153		return (CTL_RETVAL_COMPLETE);
6154	}
6155	if (*len_left < page_index->page_len) {
6156		free(ctsio->kern_data_ptr, M_CTL);
6157		ctl_set_param_len_error(ctsio);
6158		ctl_done((union ctl_io *)ctsio);
6159		return (CTL_RETVAL_COMPLETE);
6160	}
6161
6162	/*
6163	 * Run through the mode page, checking to make sure that the bits
6164	 * the user changed are actually legal for him to change.
6165	 */
6166	for (i = 0; i < page_index->page_len; i++) {
6167		uint8_t *user_byte, *change_mask, *current_byte;
6168		int bad_bit;
6169		int j;
6170
6171		user_byte = (uint8_t *)page_header + i;
6172		change_mask = page_index->page_data +
6173			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6174		current_byte = page_index->page_data +
6175			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6176
6177		/*
6178		 * Check to see whether the user set any bits in this byte
6179		 * that he is not allowed to set.
6180		 */
6181		if ((*user_byte & ~(*change_mask)) ==
6182		    (*current_byte & ~(*change_mask)))
6183			continue;
6184
6185		/*
6186		 * Go through bit by bit to determine which one is illegal.
6187		 */
6188		bad_bit = 0;
6189		for (j = 7; j >= 0; j--) {
6190			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6191			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6192				bad_bit = i;
6193				break;
6194			}
6195		}
6196		ctl_set_invalid_field(ctsio,
6197				      /*sks_valid*/ 1,
6198				      /*command*/ 0,
6199				      /*field*/ *len_used + i,
6200				      /*bit_valid*/ 1,
6201				      /*bit*/ bad_bit);
6202		free(ctsio->kern_data_ptr, M_CTL);
6203		ctl_done((union ctl_io *)ctsio);
6204		return (CTL_RETVAL_COMPLETE);
6205	}
6206
6207	/*
6208	 * Decrement these before we call the page handler, since we may
6209	 * end up getting called back one way or another before the handler
6210	 * returns to this context.
6211	 */
6212	*len_left -= page_index->page_len;
6213	*len_used += page_index->page_len;
6214
6215	retval = page_index->select_handler(ctsio, page_index,
6216					    (uint8_t *)page_header);
6217
6218	/*
6219	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6220	 * wait until this queued command completes to finish processing
6221	 * the mode page.  If it returns anything other than
6222	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6223	 * already set the sense information, freed the data pointer, and
6224	 * completed the io for us.
6225	 */
6226	if (retval != CTL_RETVAL_COMPLETE)
6227		goto bailout_no_done;
6228
6229	/*
6230	 * If the initiator sent us more than one page, parse the next one.
6231	 */
6232	if (*len_left > 0)
6233		goto do_next_page;
6234
6235	ctl_set_success(ctsio);
6236	free(ctsio->kern_data_ptr, M_CTL);
6237	ctl_done((union ctl_io *)ctsio);
6238
6239bailout_no_done:
6240
6241	return (CTL_RETVAL_COMPLETE);
6242
6243}
6244
6245int
6246ctl_mode_select(struct ctl_scsiio *ctsio)
6247{
6248	struct ctl_lun *lun = CTL_LUN(ctsio);
6249	union ctl_modepage_info *modepage_info;
6250	int bd_len, i, header_size, param_len, pf, rtd, sp;
6251	uint32_t initidx;
6252
6253	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6254	switch (ctsio->cdb[0]) {
6255	case MODE_SELECT_6: {
6256		struct scsi_mode_select_6 *cdb;
6257
6258		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6259
6260		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6261		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6262		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6263		param_len = cdb->length;
6264		header_size = sizeof(struct scsi_mode_header_6);
6265		break;
6266	}
6267	case MODE_SELECT_10: {
6268		struct scsi_mode_select_10 *cdb;
6269
6270		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6271
6272		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6273		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6274		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6275		param_len = scsi_2btoul(cdb->length);
6276		header_size = sizeof(struct scsi_mode_header_10);
6277		break;
6278	}
6279	default:
6280		ctl_set_invalid_opcode(ctsio);
6281		ctl_done((union ctl_io *)ctsio);
6282		return (CTL_RETVAL_COMPLETE);
6283	}
6284
6285	if (rtd) {
6286		if (param_len != 0) {
6287			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6288			    /*command*/ 1, /*field*/ 0,
6289			    /*bit_valid*/ 0, /*bit*/ 0);
6290			ctl_done((union ctl_io *)ctsio);
6291			return (CTL_RETVAL_COMPLETE);
6292		}
6293
6294		/* Revert to defaults. */
6295		ctl_init_page_index(lun);
6296		mtx_lock(&lun->lun_lock);
6297		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6298		mtx_unlock(&lun->lun_lock);
6299		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6300			ctl_isc_announce_mode(lun, -1,
6301			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6302			    lun->mode_pages.index[i].subpage);
6303		}
6304		ctl_set_success(ctsio);
6305		ctl_done((union ctl_io *)ctsio);
6306		return (CTL_RETVAL_COMPLETE);
6307	}
6308
6309	/*
6310	 * From SPC-3:
6311	 * "A parameter list length of zero indicates that the Data-Out Buffer
6312	 * shall be empty. This condition shall not be considered as an error."
6313	 */
6314	if (param_len == 0) {
6315		ctl_set_success(ctsio);
6316		ctl_done((union ctl_io *)ctsio);
6317		return (CTL_RETVAL_COMPLETE);
6318	}
6319
6320	/*
6321	 * Since we'll hit this the first time through, prior to
6322	 * allocation, we don't need to free a data buffer here.
6323	 */
6324	if (param_len < header_size) {
6325		ctl_set_param_len_error(ctsio);
6326		ctl_done((union ctl_io *)ctsio);
6327		return (CTL_RETVAL_COMPLETE);
6328	}
6329
6330	/*
6331	 * Allocate the data buffer and grab the user's data.  In theory,
6332	 * we shouldn't have to sanity check the parameter list length here
6333	 * because the maximum size is 64K.  We should be able to malloc
6334	 * that much without too many problems.
6335	 */
6336	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6337		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6338		ctsio->kern_data_len = param_len;
6339		ctsio->kern_total_len = param_len;
6340		ctsio->kern_rel_offset = 0;
6341		ctsio->kern_sg_entries = 0;
6342		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6343		ctsio->be_move_done = ctl_config_move_done;
6344		ctl_datamove((union ctl_io *)ctsio);
6345
6346		return (CTL_RETVAL_COMPLETE);
6347	}
6348
6349	switch (ctsio->cdb[0]) {
6350	case MODE_SELECT_6: {
6351		struct scsi_mode_header_6 *mh6;
6352
6353		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6354		bd_len = mh6->blk_desc_len;
6355		break;
6356	}
6357	case MODE_SELECT_10: {
6358		struct scsi_mode_header_10 *mh10;
6359
6360		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6361		bd_len = scsi_2btoul(mh10->blk_desc_len);
6362		break;
6363	}
6364	default:
6365		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6366	}
6367
6368	if (param_len < (header_size + bd_len)) {
6369		free(ctsio->kern_data_ptr, M_CTL);
6370		ctl_set_param_len_error(ctsio);
6371		ctl_done((union ctl_io *)ctsio);
6372		return (CTL_RETVAL_COMPLETE);
6373	}
6374
6375	/*
6376	 * Set the IO_CONT flag, so that if this I/O gets passed to
6377	 * ctl_config_write_done(), it'll get passed back to
6378	 * ctl_do_mode_select() for further processing, or completion if
6379	 * we're all done.
6380	 */
6381	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6382	ctsio->io_cont = ctl_do_mode_select;
6383
6384	modepage_info = (union ctl_modepage_info *)
6385		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6386	memset(modepage_info, 0, sizeof(*modepage_info));
6387	modepage_info->header.len_left = param_len - header_size - bd_len;
6388	modepage_info->header.len_used = header_size + bd_len;
6389
6390	return (ctl_do_mode_select((union ctl_io *)ctsio));
6391}
6392
6393int
6394ctl_mode_sense(struct ctl_scsiio *ctsio)
6395{
6396	struct ctl_lun *lun = CTL_LUN(ctsio);
6397	int pc, page_code, dbd, llba, subpage;
6398	int alloc_len, page_len, header_len, total_len;
6399	struct scsi_mode_block_descr *block_desc;
6400	struct ctl_page_index *page_index;
6401
6402	dbd = 0;
6403	llba = 0;
6404	block_desc = NULL;
6405
6406	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6407
6408	switch (ctsio->cdb[0]) {
6409	case MODE_SENSE_6: {
6410		struct scsi_mode_sense_6 *cdb;
6411
6412		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6413
6414		header_len = sizeof(struct scsi_mode_hdr_6);
6415		if (cdb->byte2 & SMS_DBD)
6416			dbd = 1;
6417		else
6418			header_len += sizeof(struct scsi_mode_block_descr);
6419
6420		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6421		page_code = cdb->page & SMS_PAGE_CODE;
6422		subpage = cdb->subpage;
6423		alloc_len = cdb->length;
6424		break;
6425	}
6426	case MODE_SENSE_10: {
6427		struct scsi_mode_sense_10 *cdb;
6428
6429		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6430
6431		header_len = sizeof(struct scsi_mode_hdr_10);
6432
6433		if (cdb->byte2 & SMS_DBD)
6434			dbd = 1;
6435		else
6436			header_len += sizeof(struct scsi_mode_block_descr);
6437		if (cdb->byte2 & SMS10_LLBAA)
6438			llba = 1;
6439		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6440		page_code = cdb->page & SMS_PAGE_CODE;
6441		subpage = cdb->subpage;
6442		alloc_len = scsi_2btoul(cdb->length);
6443		break;
6444	}
6445	default:
6446		ctl_set_invalid_opcode(ctsio);
6447		ctl_done((union ctl_io *)ctsio);
6448		return (CTL_RETVAL_COMPLETE);
6449		break; /* NOTREACHED */
6450	}
6451
6452	/*
6453	 * We have to make a first pass through to calculate the size of
6454	 * the pages that match the user's query.  Then we allocate enough
6455	 * memory to hold it, and actually copy the data into the buffer.
6456	 */
6457	switch (page_code) {
6458	case SMS_ALL_PAGES_PAGE: {
6459		u_int i;
6460
6461		page_len = 0;
6462
6463		/*
6464		 * At the moment, values other than 0 and 0xff here are
6465		 * reserved according to SPC-3.
6466		 */
6467		if ((subpage != SMS_SUBPAGE_PAGE_0)
6468		 && (subpage != SMS_SUBPAGE_ALL)) {
6469			ctl_set_invalid_field(ctsio,
6470					      /*sks_valid*/ 1,
6471					      /*command*/ 1,
6472					      /*field*/ 3,
6473					      /*bit_valid*/ 0,
6474					      /*bit*/ 0);
6475			ctl_done((union ctl_io *)ctsio);
6476			return (CTL_RETVAL_COMPLETE);
6477		}
6478
6479		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6480			page_index = &lun->mode_pages.index[i];
6481
6482			/* Make sure the page is supported for this dev type */
6483			if (lun->be_lun->lun_type == T_DIRECT &&
6484			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6485				continue;
6486			if (lun->be_lun->lun_type == T_PROCESSOR &&
6487			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6488				continue;
6489			if (lun->be_lun->lun_type == T_CDROM &&
6490			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6491				continue;
6492
6493			/*
6494			 * We don't use this subpage if the user didn't
6495			 * request all subpages.
6496			 */
6497			if ((page_index->subpage != 0)
6498			 && (subpage == SMS_SUBPAGE_PAGE_0))
6499				continue;
6500
6501			page_len += page_index->page_len;
6502		}
6503		break;
6504	}
6505	default: {
6506		u_int i;
6507
6508		page_len = 0;
6509
6510		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6511			page_index = &lun->mode_pages.index[i];
6512
6513			/* Make sure the page is supported for this dev type */
6514			if (lun->be_lun->lun_type == T_DIRECT &&
6515			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6516				continue;
6517			if (lun->be_lun->lun_type == T_PROCESSOR &&
6518			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6519				continue;
6520			if (lun->be_lun->lun_type == T_CDROM &&
6521			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6522				continue;
6523
6524			/* Look for the right page code */
6525			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6526				continue;
6527
6528			/* Look for the right subpage or the subpage wildcard*/
6529			if ((page_index->subpage != subpage)
6530			 && (subpage != SMS_SUBPAGE_ALL))
6531				continue;
6532
6533			page_len += page_index->page_len;
6534		}
6535
6536		if (page_len == 0) {
6537			ctl_set_invalid_field(ctsio,
6538					      /*sks_valid*/ 1,
6539					      /*command*/ 1,
6540					      /*field*/ 2,
6541					      /*bit_valid*/ 1,
6542					      /*bit*/ 5);
6543			ctl_done((union ctl_io *)ctsio);
6544			return (CTL_RETVAL_COMPLETE);
6545		}
6546		break;
6547	}
6548	}
6549
6550	total_len = header_len + page_len;
6551
6552	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6553	ctsio->kern_sg_entries = 0;
6554	ctsio->kern_rel_offset = 0;
6555	ctsio->kern_data_len = min(total_len, alloc_len);
6556	ctsio->kern_total_len = ctsio->kern_data_len;
6557
6558	switch (ctsio->cdb[0]) {
6559	case MODE_SENSE_6: {
6560		struct scsi_mode_hdr_6 *header;
6561
6562		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6563
6564		header->datalen = MIN(total_len - 1, 254);
6565		if (lun->be_lun->lun_type == T_DIRECT) {
6566			header->dev_specific = 0x10; /* DPOFUA */
6567			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6568			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6569				header->dev_specific |= 0x80; /* WP */
6570		}
6571		if (dbd)
6572			header->block_descr_len = 0;
6573		else
6574			header->block_descr_len =
6575				sizeof(struct scsi_mode_block_descr);
6576		block_desc = (struct scsi_mode_block_descr *)&header[1];
6577		break;
6578	}
6579	case MODE_SENSE_10: {
6580		struct scsi_mode_hdr_10 *header;
6581		int datalen;
6582
6583		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6584
6585		datalen = MIN(total_len - 2, 65533);
6586		scsi_ulto2b(datalen, header->datalen);
6587		if (lun->be_lun->lun_type == T_DIRECT) {
6588			header->dev_specific = 0x10; /* DPOFUA */
6589			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6590			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6591				header->dev_specific |= 0x80; /* WP */
6592		}
6593		if (dbd)
6594			scsi_ulto2b(0, header->block_descr_len);
6595		else
6596			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6597				    header->block_descr_len);
6598		block_desc = (struct scsi_mode_block_descr *)&header[1];
6599		break;
6600	}
6601	default:
6602		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6603	}
6604
6605	/*
6606	 * If we've got a disk, use its blocksize in the block
6607	 * descriptor.  Otherwise, just set it to 0.
6608	 */
6609	if (dbd == 0) {
6610		if (lun->be_lun->lun_type == T_DIRECT)
6611			scsi_ulto3b(lun->be_lun->blocksize,
6612				    block_desc->block_len);
6613		else
6614			scsi_ulto3b(0, block_desc->block_len);
6615	}
6616
6617	switch (page_code) {
6618	case SMS_ALL_PAGES_PAGE: {
6619		int i, data_used;
6620
6621		data_used = header_len;
6622		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6623			struct ctl_page_index *page_index;
6624
6625			page_index = &lun->mode_pages.index[i];
6626			if (lun->be_lun->lun_type == T_DIRECT &&
6627			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6628				continue;
6629			if (lun->be_lun->lun_type == T_PROCESSOR &&
6630			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6631				continue;
6632			if (lun->be_lun->lun_type == T_CDROM &&
6633			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6634				continue;
6635
6636			/*
6637			 * We don't use this subpage if the user didn't
6638			 * request all subpages.  We already checked (above)
6639			 * to make sure the user only specified a subpage
6640			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6641			 */
6642			if ((page_index->subpage != 0)
6643			 && (subpage == SMS_SUBPAGE_PAGE_0))
6644				continue;
6645
6646			/*
6647			 * Call the handler, if it exists, to update the
6648			 * page to the latest values.
6649			 */
6650			if (page_index->sense_handler != NULL)
6651				page_index->sense_handler(ctsio, page_index,pc);
6652
6653			memcpy(ctsio->kern_data_ptr + data_used,
6654			       page_index->page_data +
6655			       (page_index->page_len * pc),
6656			       page_index->page_len);
6657			data_used += page_index->page_len;
6658		}
6659		break;
6660	}
6661	default: {
6662		int i, data_used;
6663
6664		data_used = header_len;
6665
6666		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6667			struct ctl_page_index *page_index;
6668
6669			page_index = &lun->mode_pages.index[i];
6670
6671			/* Look for the right page code */
6672			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6673				continue;
6674
6675			/* Look for the right subpage or the subpage wildcard*/
6676			if ((page_index->subpage != subpage)
6677			 && (subpage != SMS_SUBPAGE_ALL))
6678				continue;
6679
6680			/* Make sure the page is supported for this dev type */
6681			if (lun->be_lun->lun_type == T_DIRECT &&
6682			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6683				continue;
6684			if (lun->be_lun->lun_type == T_PROCESSOR &&
6685			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6686				continue;
6687			if (lun->be_lun->lun_type == T_CDROM &&
6688			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6689				continue;
6690
6691			/*
6692			 * Call the handler, if it exists, to update the
6693			 * page to the latest values.
6694			 */
6695			if (page_index->sense_handler != NULL)
6696				page_index->sense_handler(ctsio, page_index,pc);
6697
6698			memcpy(ctsio->kern_data_ptr + data_used,
6699			       page_index->page_data +
6700			       (page_index->page_len * pc),
6701			       page_index->page_len);
6702			data_used += page_index->page_len;
6703		}
6704		break;
6705	}
6706	}
6707
6708	ctl_set_success(ctsio);
6709	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6710	ctsio->be_move_done = ctl_config_move_done;
6711	ctl_datamove((union ctl_io *)ctsio);
6712	return (CTL_RETVAL_COMPLETE);
6713}
6714
6715int
6716ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6717			       struct ctl_page_index *page_index,
6718			       int pc)
6719{
6720	struct ctl_lun *lun = CTL_LUN(ctsio);
6721	struct scsi_log_param_header *phdr;
6722	uint8_t *data;
6723	uint64_t val;
6724
6725	data = page_index->page_data;
6726
6727	if (lun->backend->lun_attr != NULL &&
6728	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6729	     != UINT64_MAX) {
6730		phdr = (struct scsi_log_param_header *)data;
6731		scsi_ulto2b(0x0001, phdr->param_code);
6732		phdr->param_control = SLP_LBIN | SLP_LP;
6733		phdr->param_len = 8;
6734		data = (uint8_t *)(phdr + 1);
6735		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6736		data[4] = 0x02; /* per-pool */
6737		data += phdr->param_len;
6738	}
6739
6740	if (lun->backend->lun_attr != NULL &&
6741	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6742	     != UINT64_MAX) {
6743		phdr = (struct scsi_log_param_header *)data;
6744		scsi_ulto2b(0x0002, phdr->param_code);
6745		phdr->param_control = SLP_LBIN | SLP_LP;
6746		phdr->param_len = 8;
6747		data = (uint8_t *)(phdr + 1);
6748		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6749		data[4] = 0x01; /* per-LUN */
6750		data += phdr->param_len;
6751	}
6752
6753	if (lun->backend->lun_attr != NULL &&
6754	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6755	     != UINT64_MAX) {
6756		phdr = (struct scsi_log_param_header *)data;
6757		scsi_ulto2b(0x00f1, phdr->param_code);
6758		phdr->param_control = SLP_LBIN | SLP_LP;
6759		phdr->param_len = 8;
6760		data = (uint8_t *)(phdr + 1);
6761		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6762		data[4] = 0x02; /* per-pool */
6763		data += phdr->param_len;
6764	}
6765
6766	if (lun->backend->lun_attr != NULL &&
6767	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6768	     != UINT64_MAX) {
6769		phdr = (struct scsi_log_param_header *)data;
6770		scsi_ulto2b(0x00f2, phdr->param_code);
6771		phdr->param_control = SLP_LBIN | SLP_LP;
6772		phdr->param_len = 8;
6773		data = (uint8_t *)(phdr + 1);
6774		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6775		data[4] = 0x02; /* per-pool */
6776		data += phdr->param_len;
6777	}
6778
6779	page_index->page_len = data - page_index->page_data;
6780	return (0);
6781}
6782
6783int
6784ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6785			       struct ctl_page_index *page_index,
6786			       int pc)
6787{
6788	struct ctl_lun *lun = CTL_LUN(ctsio);
6789	struct stat_page *data;
6790	struct bintime *t;
6791
6792	data = (struct stat_page *)page_index->page_data;
6793
6794	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6795	data->sap.hdr.param_control = SLP_LBIN;
6796	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6797	    sizeof(struct scsi_log_param_header);
6798	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6799	    data->sap.read_num);
6800	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6801	    data->sap.write_num);
6802	if (lun->be_lun->blocksize > 0) {
6803		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6804		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6805		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6806		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6807	}
6808	t = &lun->stats.time[CTL_STATS_READ];
6809	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6810	    data->sap.read_int);
6811	t = &lun->stats.time[CTL_STATS_WRITE];
6812	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6813	    data->sap.write_int);
6814	scsi_u64to8b(0, data->sap.weighted_num);
6815	scsi_u64to8b(0, data->sap.weighted_int);
6816	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6817	data->it.hdr.param_control = SLP_LBIN;
6818	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6819	    sizeof(struct scsi_log_param_header);
6820#ifdef CTL_TIME_IO
6821	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6822#endif
6823	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6824	data->it.hdr.param_control = SLP_LBIN;
6825	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6826	    sizeof(struct scsi_log_param_header);
6827	scsi_ulto4b(3, data->ti.exponent);
6828	scsi_ulto4b(1, data->ti.integer);
6829	return (0);
6830}
6831
6832int
6833ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6834			       struct ctl_page_index *page_index,
6835			       int pc)
6836{
6837	struct ctl_lun *lun = CTL_LUN(ctsio);
6838	struct scsi_log_informational_exceptions *data;
6839
6840	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6841
6842	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6843	data->hdr.param_control = SLP_LBIN;
6844	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6845	    sizeof(struct scsi_log_param_header);
6846	data->ie_asc = lun->ie_asc;
6847	data->ie_ascq = lun->ie_ascq;
6848	data->temperature = 0xff;
6849	return (0);
6850}
6851
6852int
6853ctl_log_sense(struct ctl_scsiio *ctsio)
6854{
6855	struct ctl_lun *lun = CTL_LUN(ctsio);
6856	int i, pc, page_code, subpage;
6857	int alloc_len, total_len;
6858	struct ctl_page_index *page_index;
6859	struct scsi_log_sense *cdb;
6860	struct scsi_log_header *header;
6861
6862	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6863
6864	cdb = (struct scsi_log_sense *)ctsio->cdb;
6865	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6866	page_code = cdb->page & SLS_PAGE_CODE;
6867	subpage = cdb->subpage;
6868	alloc_len = scsi_2btoul(cdb->length);
6869
6870	page_index = NULL;
6871	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6872		page_index = &lun->log_pages.index[i];
6873
6874		/* Look for the right page code */
6875		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6876			continue;
6877
6878		/* Look for the right subpage or the subpage wildcard*/
6879		if (page_index->subpage != subpage)
6880			continue;
6881
6882		break;
6883	}
6884	if (i >= CTL_NUM_LOG_PAGES) {
6885		ctl_set_invalid_field(ctsio,
6886				      /*sks_valid*/ 1,
6887				      /*command*/ 1,
6888				      /*field*/ 2,
6889				      /*bit_valid*/ 0,
6890				      /*bit*/ 0);
6891		ctl_done((union ctl_io *)ctsio);
6892		return (CTL_RETVAL_COMPLETE);
6893	}
6894
6895	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6896
6897	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6898	ctsio->kern_sg_entries = 0;
6899	ctsio->kern_rel_offset = 0;
6900	ctsio->kern_data_len = min(total_len, alloc_len);
6901	ctsio->kern_total_len = ctsio->kern_data_len;
6902
6903	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6904	header->page = page_index->page_code;
6905	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6906		header->page |= SL_DS;
6907	if (page_index->subpage) {
6908		header->page |= SL_SPF;
6909		header->subpage = page_index->subpage;
6910	}
6911	scsi_ulto2b(page_index->page_len, header->datalen);
6912
6913	/*
6914	 * Call the handler, if it exists, to update the
6915	 * page to the latest values.
6916	 */
6917	if (page_index->sense_handler != NULL)
6918		page_index->sense_handler(ctsio, page_index, pc);
6919
6920	memcpy(header + 1, page_index->page_data, page_index->page_len);
6921
6922	ctl_set_success(ctsio);
6923	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6924	ctsio->be_move_done = ctl_config_move_done;
6925	ctl_datamove((union ctl_io *)ctsio);
6926	return (CTL_RETVAL_COMPLETE);
6927}
6928
6929int
6930ctl_read_capacity(struct ctl_scsiio *ctsio)
6931{
6932	struct ctl_lun *lun = CTL_LUN(ctsio);
6933	struct scsi_read_capacity *cdb;
6934	struct scsi_read_capacity_data *data;
6935	uint32_t lba;
6936
6937	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6938
6939	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6940
6941	lba = scsi_4btoul(cdb->addr);
6942	if (((cdb->pmi & SRC_PMI) == 0)
6943	 && (lba != 0)) {
6944		ctl_set_invalid_field(/*ctsio*/ ctsio,
6945				      /*sks_valid*/ 1,
6946				      /*command*/ 1,
6947				      /*field*/ 2,
6948				      /*bit_valid*/ 0,
6949				      /*bit*/ 0);
6950		ctl_done((union ctl_io *)ctsio);
6951		return (CTL_RETVAL_COMPLETE);
6952	}
6953
6954	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6955	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6956	ctsio->kern_data_len = sizeof(*data);
6957	ctsio->kern_total_len = sizeof(*data);
6958	ctsio->kern_rel_offset = 0;
6959	ctsio->kern_sg_entries = 0;
6960
6961	/*
6962	 * If the maximum LBA is greater than 0xfffffffe, the user must
6963	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6964	 * serivce action set.
6965	 */
6966	if (lun->be_lun->maxlba > 0xfffffffe)
6967		scsi_ulto4b(0xffffffff, data->addr);
6968	else
6969		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6970
6971	/*
6972	 * XXX KDM this may not be 512 bytes...
6973	 */
6974	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6975
6976	ctl_set_success(ctsio);
6977	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6978	ctsio->be_move_done = ctl_config_move_done;
6979	ctl_datamove((union ctl_io *)ctsio);
6980	return (CTL_RETVAL_COMPLETE);
6981}
6982
6983int
6984ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6985{
6986	struct ctl_lun *lun = CTL_LUN(ctsio);
6987	struct scsi_read_capacity_16 *cdb;
6988	struct scsi_read_capacity_data_long *data;
6989	uint64_t lba;
6990	uint32_t alloc_len;
6991
6992	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6993
6994	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6995
6996	alloc_len = scsi_4btoul(cdb->alloc_len);
6997	lba = scsi_8btou64(cdb->addr);
6998
6999	if ((cdb->reladr & SRC16_PMI)
7000	 && (lba != 0)) {
7001		ctl_set_invalid_field(/*ctsio*/ ctsio,
7002				      /*sks_valid*/ 1,
7003				      /*command*/ 1,
7004				      /*field*/ 2,
7005				      /*bit_valid*/ 0,
7006				      /*bit*/ 0);
7007		ctl_done((union ctl_io *)ctsio);
7008		return (CTL_RETVAL_COMPLETE);
7009	}
7010
7011	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7012	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7013	ctsio->kern_rel_offset = 0;
7014	ctsio->kern_sg_entries = 0;
7015	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7016	ctsio->kern_total_len = ctsio->kern_data_len;
7017
7018	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7019	/* XXX KDM this may not be 512 bytes... */
7020	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7021	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7022	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7023	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7024		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
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_get_lba_status(struct ctl_scsiio *ctsio)
7035{
7036	struct ctl_lun *lun = CTL_LUN(ctsio);
7037	struct scsi_get_lba_status *cdb;
7038	struct scsi_get_lba_status_data *data;
7039	struct ctl_lba_len_flags *lbalen;
7040	uint64_t lba;
7041	uint32_t alloc_len, total_len;
7042	int retval;
7043
7044	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7045
7046	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7047	lba = scsi_8btou64(cdb->addr);
7048	alloc_len = scsi_4btoul(cdb->alloc_len);
7049
7050	if (lba > lun->be_lun->maxlba) {
7051		ctl_set_lba_out_of_range(ctsio, lba);
7052		ctl_done((union ctl_io *)ctsio);
7053		return (CTL_RETVAL_COMPLETE);
7054	}
7055
7056	total_len = sizeof(*data) + sizeof(data->descr[0]);
7057	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7058	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7059	ctsio->kern_rel_offset = 0;
7060	ctsio->kern_sg_entries = 0;
7061	ctsio->kern_data_len = min(total_len, alloc_len);
7062	ctsio->kern_total_len = ctsio->kern_data_len;
7063
7064	/* Fill dummy data in case backend can't tell anything. */
7065	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7066	scsi_u64to8b(lba, data->descr[0].addr);
7067	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7068	    data->descr[0].length);
7069	data->descr[0].status = 0; /* Mapped or unknown. */
7070
7071	ctl_set_success(ctsio);
7072	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7073	ctsio->be_move_done = ctl_config_move_done;
7074
7075	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7076	lbalen->lba = lba;
7077	lbalen->len = total_len;
7078	lbalen->flags = 0;
7079	retval = lun->backend->config_read((union ctl_io *)ctsio);
7080	return (retval);
7081}
7082
7083int
7084ctl_read_defect(struct ctl_scsiio *ctsio)
7085{
7086	struct scsi_read_defect_data_10 *ccb10;
7087	struct scsi_read_defect_data_12 *ccb12;
7088	struct scsi_read_defect_data_hdr_10 *data10;
7089	struct scsi_read_defect_data_hdr_12 *data12;
7090	uint32_t alloc_len, data_len;
7091	uint8_t format;
7092
7093	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7094
7095	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7096		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7097		format = ccb10->format;
7098		alloc_len = scsi_2btoul(ccb10->alloc_length);
7099		data_len = sizeof(*data10);
7100	} else {
7101		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7102		format = ccb12->format;
7103		alloc_len = scsi_4btoul(ccb12->alloc_length);
7104		data_len = sizeof(*data12);
7105	}
7106	if (alloc_len == 0) {
7107		ctl_set_success(ctsio);
7108		ctl_done((union ctl_io *)ctsio);
7109		return (CTL_RETVAL_COMPLETE);
7110	}
7111
7112	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7113	ctsio->kern_rel_offset = 0;
7114	ctsio->kern_sg_entries = 0;
7115	ctsio->kern_data_len = min(data_len, alloc_len);
7116	ctsio->kern_total_len = ctsio->kern_data_len;
7117
7118	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7119		data10 = (struct scsi_read_defect_data_hdr_10 *)
7120		    ctsio->kern_data_ptr;
7121		data10->format = format;
7122		scsi_ulto2b(0, data10->length);
7123	} else {
7124		data12 = (struct scsi_read_defect_data_hdr_12 *)
7125		    ctsio->kern_data_ptr;
7126		data12->format = format;
7127		scsi_ulto2b(0, data12->generation);
7128		scsi_ulto4b(0, data12->length);
7129	}
7130
7131	ctl_set_success(ctsio);
7132	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7133	ctsio->be_move_done = ctl_config_move_done;
7134	ctl_datamove((union ctl_io *)ctsio);
7135	return (CTL_RETVAL_COMPLETE);
7136}
7137
7138int
7139ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7140{
7141	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7142	struct ctl_lun *lun = CTL_LUN(ctsio);
7143	struct scsi_maintenance_in *cdb;
7144	int retval;
7145	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7146	int num_ha_groups, num_target_ports, shared_group;
7147	struct ctl_port *port;
7148	struct scsi_target_group_data *rtg_ptr;
7149	struct scsi_target_group_data_extended *rtg_ext_ptr;
7150	struct scsi_target_port_group_descriptor *tpg_desc;
7151
7152	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7153
7154	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7155	retval = CTL_RETVAL_COMPLETE;
7156
7157	switch (cdb->byte2 & STG_PDF_MASK) {
7158	case STG_PDF_LENGTH:
7159		ext = 0;
7160		break;
7161	case STG_PDF_EXTENDED:
7162		ext = 1;
7163		break;
7164	default:
7165		ctl_set_invalid_field(/*ctsio*/ ctsio,
7166				      /*sks_valid*/ 1,
7167				      /*command*/ 1,
7168				      /*field*/ 2,
7169				      /*bit_valid*/ 1,
7170				      /*bit*/ 5);
7171		ctl_done((union ctl_io *)ctsio);
7172		return(retval);
7173	}
7174
7175	num_target_ports = 0;
7176	shared_group = (softc->is_single != 0);
7177	mtx_lock(&softc->ctl_lock);
7178	STAILQ_FOREACH(port, &softc->port_list, links) {
7179		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7180			continue;
7181		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7182			continue;
7183		num_target_ports++;
7184		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7185			shared_group = 1;
7186	}
7187	mtx_unlock(&softc->ctl_lock);
7188	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7189
7190	if (ext)
7191		total_len = sizeof(struct scsi_target_group_data_extended);
7192	else
7193		total_len = sizeof(struct scsi_target_group_data);
7194	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7195		(shared_group + num_ha_groups) +
7196	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7197
7198	alloc_len = scsi_4btoul(cdb->length);
7199
7200	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7201	ctsio->kern_sg_entries = 0;
7202	ctsio->kern_rel_offset = 0;
7203	ctsio->kern_data_len = min(total_len, alloc_len);
7204	ctsio->kern_total_len = ctsio->kern_data_len;
7205
7206	if (ext) {
7207		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7208		    ctsio->kern_data_ptr;
7209		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7210		rtg_ext_ptr->format_type = 0x10;
7211		rtg_ext_ptr->implicit_transition_time = 0;
7212		tpg_desc = &rtg_ext_ptr->groups[0];
7213	} else {
7214		rtg_ptr = (struct scsi_target_group_data *)
7215		    ctsio->kern_data_ptr;
7216		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7217		tpg_desc = &rtg_ptr->groups[0];
7218	}
7219
7220	mtx_lock(&softc->ctl_lock);
7221	pg = softc->port_min / softc->port_cnt;
7222	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7223		/* Some shelf is known to be primary. */
7224		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7225			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7226		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7227			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7228		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7229			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7230		else
7231			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7232		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7233			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7234		} else {
7235			ts = os;
7236			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7237		}
7238	} else {
7239		/* No known primary shelf. */
7240		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7241			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7242			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7243		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7244			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7245			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7246		} else {
7247			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7248		}
7249	}
7250	if (shared_group) {
7251		tpg_desc->pref_state = ts;
7252		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7253		    TPG_U_SUP | TPG_T_SUP;
7254		scsi_ulto2b(1, tpg_desc->target_port_group);
7255		tpg_desc->status = TPG_IMPLICIT;
7256		pc = 0;
7257		STAILQ_FOREACH(port, &softc->port_list, links) {
7258			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7259				continue;
7260			if (!softc->is_single &&
7261			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7262				continue;
7263			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7264				continue;
7265			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7266			    relative_target_port_identifier);
7267			pc++;
7268		}
7269		tpg_desc->target_port_count = pc;
7270		tpg_desc = (struct scsi_target_port_group_descriptor *)
7271		    &tpg_desc->descriptors[pc];
7272	}
7273	for (g = 0; g < num_ha_groups; g++) {
7274		tpg_desc->pref_state = (g == pg) ? ts : os;
7275		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7276		    TPG_U_SUP | TPG_T_SUP;
7277		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7278		tpg_desc->status = TPG_IMPLICIT;
7279		pc = 0;
7280		STAILQ_FOREACH(port, &softc->port_list, links) {
7281			if (port->targ_port < g * softc->port_cnt ||
7282			    port->targ_port >= (g + 1) * softc->port_cnt)
7283				continue;
7284			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7285				continue;
7286			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7287				continue;
7288			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7289				continue;
7290			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7291			    relative_target_port_identifier);
7292			pc++;
7293		}
7294		tpg_desc->target_port_count = pc;
7295		tpg_desc = (struct scsi_target_port_group_descriptor *)
7296		    &tpg_desc->descriptors[pc];
7297	}
7298	mtx_unlock(&softc->ctl_lock);
7299
7300	ctl_set_success(ctsio);
7301	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7302	ctsio->be_move_done = ctl_config_move_done;
7303	ctl_datamove((union ctl_io *)ctsio);
7304	return(retval);
7305}
7306
7307int
7308ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7309{
7310	struct ctl_lun *lun = CTL_LUN(ctsio);
7311	struct scsi_report_supported_opcodes *cdb;
7312	const struct ctl_cmd_entry *entry, *sentry;
7313	struct scsi_report_supported_opcodes_all *all;
7314	struct scsi_report_supported_opcodes_descr *descr;
7315	struct scsi_report_supported_opcodes_one *one;
7316	int retval;
7317	int alloc_len, total_len;
7318	int opcode, service_action, i, j, num;
7319
7320	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7321
7322	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7323	retval = CTL_RETVAL_COMPLETE;
7324
7325	opcode = cdb->requested_opcode;
7326	service_action = scsi_2btoul(cdb->requested_service_action);
7327	switch (cdb->options & RSO_OPTIONS_MASK) {
7328	case RSO_OPTIONS_ALL:
7329		num = 0;
7330		for (i = 0; i < 256; i++) {
7331			entry = &ctl_cmd_table[i];
7332			if (entry->flags & CTL_CMD_FLAG_SA5) {
7333				for (j = 0; j < 32; j++) {
7334					sentry = &((const struct ctl_cmd_entry *)
7335					    entry->execute)[j];
7336					if (ctl_cmd_applicable(
7337					    lun->be_lun->lun_type, sentry))
7338						num++;
7339				}
7340			} else {
7341				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7342				    entry))
7343					num++;
7344			}
7345		}
7346		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7347		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7348		break;
7349	case RSO_OPTIONS_OC:
7350		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7351			ctl_set_invalid_field(/*ctsio*/ ctsio,
7352					      /*sks_valid*/ 1,
7353					      /*command*/ 1,
7354					      /*field*/ 2,
7355					      /*bit_valid*/ 1,
7356					      /*bit*/ 2);
7357			ctl_done((union ctl_io *)ctsio);
7358			return (CTL_RETVAL_COMPLETE);
7359		}
7360		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7361		break;
7362	case RSO_OPTIONS_OC_SA:
7363		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7364		    service_action >= 32) {
7365			ctl_set_invalid_field(/*ctsio*/ ctsio,
7366					      /*sks_valid*/ 1,
7367					      /*command*/ 1,
7368					      /*field*/ 2,
7369					      /*bit_valid*/ 1,
7370					      /*bit*/ 2);
7371			ctl_done((union ctl_io *)ctsio);
7372			return (CTL_RETVAL_COMPLETE);
7373		}
7374		/* FALLTHROUGH */
7375	case RSO_OPTIONS_OC_ASA:
7376		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7377		break;
7378	default:
7379		ctl_set_invalid_field(/*ctsio*/ ctsio,
7380				      /*sks_valid*/ 1,
7381				      /*command*/ 1,
7382				      /*field*/ 2,
7383				      /*bit_valid*/ 1,
7384				      /*bit*/ 2);
7385		ctl_done((union ctl_io *)ctsio);
7386		return (CTL_RETVAL_COMPLETE);
7387	}
7388
7389	alloc_len = scsi_4btoul(cdb->length);
7390
7391	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7392	ctsio->kern_sg_entries = 0;
7393	ctsio->kern_rel_offset = 0;
7394	ctsio->kern_data_len = min(total_len, alloc_len);
7395	ctsio->kern_total_len = ctsio->kern_data_len;
7396
7397	switch (cdb->options & RSO_OPTIONS_MASK) {
7398	case RSO_OPTIONS_ALL:
7399		all = (struct scsi_report_supported_opcodes_all *)
7400		    ctsio->kern_data_ptr;
7401		num = 0;
7402		for (i = 0; i < 256; i++) {
7403			entry = &ctl_cmd_table[i];
7404			if (entry->flags & CTL_CMD_FLAG_SA5) {
7405				for (j = 0; j < 32; j++) {
7406					sentry = &((const struct ctl_cmd_entry *)
7407					    entry->execute)[j];
7408					if (!ctl_cmd_applicable(
7409					    lun->be_lun->lun_type, sentry))
7410						continue;
7411					descr = &all->descr[num++];
7412					descr->opcode = i;
7413					scsi_ulto2b(j, descr->service_action);
7414					descr->flags = RSO_SERVACTV;
7415					scsi_ulto2b(sentry->length,
7416					    descr->cdb_length);
7417				}
7418			} else {
7419				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7420				    entry))
7421					continue;
7422				descr = &all->descr[num++];
7423				descr->opcode = i;
7424				scsi_ulto2b(0, descr->service_action);
7425				descr->flags = 0;
7426				scsi_ulto2b(entry->length, descr->cdb_length);
7427			}
7428		}
7429		scsi_ulto4b(
7430		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7431		    all->length);
7432		break;
7433	case RSO_OPTIONS_OC:
7434		one = (struct scsi_report_supported_opcodes_one *)
7435		    ctsio->kern_data_ptr;
7436		entry = &ctl_cmd_table[opcode];
7437		goto fill_one;
7438	case RSO_OPTIONS_OC_SA:
7439		one = (struct scsi_report_supported_opcodes_one *)
7440		    ctsio->kern_data_ptr;
7441		entry = &ctl_cmd_table[opcode];
7442		entry = &((const struct ctl_cmd_entry *)
7443		    entry->execute)[service_action];
7444fill_one:
7445		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7446			one->support = 3;
7447			scsi_ulto2b(entry->length, one->cdb_length);
7448			one->cdb_usage[0] = opcode;
7449			memcpy(&one->cdb_usage[1], entry->usage,
7450			    entry->length - 1);
7451		} else
7452			one->support = 1;
7453		break;
7454	case RSO_OPTIONS_OC_ASA:
7455		one = (struct scsi_report_supported_opcodes_one *)
7456		    ctsio->kern_data_ptr;
7457		entry = &ctl_cmd_table[opcode];
7458		if (entry->flags & CTL_CMD_FLAG_SA5) {
7459			entry = &((const struct ctl_cmd_entry *)
7460			    entry->execute)[service_action];
7461		} else if (service_action != 0) {
7462			one->support = 1;
7463			break;
7464		}
7465		goto fill_one;
7466	}
7467
7468	ctl_set_success(ctsio);
7469	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7470	ctsio->be_move_done = ctl_config_move_done;
7471	ctl_datamove((union ctl_io *)ctsio);
7472	return(retval);
7473}
7474
7475int
7476ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7477{
7478	struct scsi_report_supported_tmf *cdb;
7479	struct scsi_report_supported_tmf_ext_data *data;
7480	int retval;
7481	int alloc_len, total_len;
7482
7483	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7484
7485	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7486
7487	retval = CTL_RETVAL_COMPLETE;
7488
7489	if (cdb->options & RST_REPD)
7490		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7491	else
7492		total_len = sizeof(struct scsi_report_supported_tmf_data);
7493	alloc_len = scsi_4btoul(cdb->length);
7494
7495	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7496	ctsio->kern_sg_entries = 0;
7497	ctsio->kern_rel_offset = 0;
7498	ctsio->kern_data_len = min(total_len, alloc_len);
7499	ctsio->kern_total_len = ctsio->kern_data_len;
7500
7501	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7502	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7503	    RST_TRS;
7504	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7505	data->length = total_len - 4;
7506
7507	ctl_set_success(ctsio);
7508	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7509	ctsio->be_move_done = ctl_config_move_done;
7510	ctl_datamove((union ctl_io *)ctsio);
7511	return (retval);
7512}
7513
7514int
7515ctl_report_timestamp(struct ctl_scsiio *ctsio)
7516{
7517	struct scsi_report_timestamp *cdb;
7518	struct scsi_report_timestamp_data *data;
7519	struct timeval tv;
7520	int64_t timestamp;
7521	int retval;
7522	int alloc_len, total_len;
7523
7524	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7525
7526	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7527
7528	retval = CTL_RETVAL_COMPLETE;
7529
7530	total_len = sizeof(struct scsi_report_timestamp_data);
7531	alloc_len = scsi_4btoul(cdb->length);
7532
7533	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7534	ctsio->kern_sg_entries = 0;
7535	ctsio->kern_rel_offset = 0;
7536	ctsio->kern_data_len = min(total_len, alloc_len);
7537	ctsio->kern_total_len = ctsio->kern_data_len;
7538
7539	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7540	scsi_ulto2b(sizeof(*data) - 2, data->length);
7541	data->origin = RTS_ORIG_OUTSIDE;
7542	getmicrotime(&tv);
7543	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7544	scsi_ulto4b(timestamp >> 16, data->timestamp);
7545	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7546
7547	ctl_set_success(ctsio);
7548	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7549	ctsio->be_move_done = ctl_config_move_done;
7550	ctl_datamove((union ctl_io *)ctsio);
7551	return (retval);
7552}
7553
7554int
7555ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7556{
7557	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7558	struct ctl_lun *lun = CTL_LUN(ctsio);
7559	struct scsi_per_res_in *cdb;
7560	int alloc_len, total_len = 0;
7561	/* struct scsi_per_res_in_rsrv in_data; */
7562	uint64_t key;
7563
7564	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7565
7566	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7567
7568	alloc_len = scsi_2btoul(cdb->length);
7569
7570retry:
7571	mtx_lock(&lun->lun_lock);
7572	switch (cdb->action) {
7573	case SPRI_RK: /* read keys */
7574		total_len = sizeof(struct scsi_per_res_in_keys) +
7575			lun->pr_key_count *
7576			sizeof(struct scsi_per_res_key);
7577		break;
7578	case SPRI_RR: /* read reservation */
7579		if (lun->flags & CTL_LUN_PR_RESERVED)
7580			total_len = sizeof(struct scsi_per_res_in_rsrv);
7581		else
7582			total_len = sizeof(struct scsi_per_res_in_header);
7583		break;
7584	case SPRI_RC: /* report capabilities */
7585		total_len = sizeof(struct scsi_per_res_cap);
7586		break;
7587	case SPRI_RS: /* read full status */
7588		total_len = sizeof(struct scsi_per_res_in_header) +
7589		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7590		    lun->pr_key_count;
7591		break;
7592	default:
7593		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7594	}
7595	mtx_unlock(&lun->lun_lock);
7596
7597	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7598	ctsio->kern_rel_offset = 0;
7599	ctsio->kern_sg_entries = 0;
7600	ctsio->kern_data_len = min(total_len, alloc_len);
7601	ctsio->kern_total_len = ctsio->kern_data_len;
7602
7603	mtx_lock(&lun->lun_lock);
7604	switch (cdb->action) {
7605	case SPRI_RK: { // read keys
7606        struct scsi_per_res_in_keys *res_keys;
7607		int i, key_count;
7608
7609		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7610
7611		/*
7612		 * We had to drop the lock to allocate our buffer, which
7613		 * leaves time for someone to come in with another
7614		 * persistent reservation.  (That is unlikely, though,
7615		 * since this should be the only persistent reservation
7616		 * command active right now.)
7617		 */
7618		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7619		    (lun->pr_key_count *
7620		     sizeof(struct scsi_per_res_key)))){
7621			mtx_unlock(&lun->lun_lock);
7622			free(ctsio->kern_data_ptr, M_CTL);
7623			printf("%s: reservation length changed, retrying\n",
7624			       __func__);
7625			goto retry;
7626		}
7627
7628		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7629
7630		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7631			     lun->pr_key_count, res_keys->header.length);
7632
7633		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7634			if ((key = ctl_get_prkey(lun, i)) == 0)
7635				continue;
7636
7637			/*
7638			 * We used lun->pr_key_count to calculate the
7639			 * size to allocate.  If it turns out the number of
7640			 * initiators with the registered flag set is
7641			 * larger than that (i.e. they haven't been kept in
7642			 * sync), we've got a problem.
7643			 */
7644			if (key_count >= lun->pr_key_count) {
7645				key_count++;
7646				continue;
7647			}
7648			scsi_u64to8b(key, res_keys->keys[key_count].key);
7649			key_count++;
7650		}
7651		break;
7652	}
7653	case SPRI_RR: { // read reservation
7654		struct scsi_per_res_in_rsrv *res;
7655		int tmp_len, header_only;
7656
7657		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7658
7659		scsi_ulto4b(lun->pr_generation, res->header.generation);
7660
7661		if (lun->flags & CTL_LUN_PR_RESERVED)
7662		{
7663			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7664			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7665				    res->header.length);
7666			header_only = 0;
7667		} else {
7668			tmp_len = sizeof(struct scsi_per_res_in_header);
7669			scsi_ulto4b(0, res->header.length);
7670			header_only = 1;
7671		}
7672
7673		/*
7674		 * We had to drop the lock to allocate our buffer, which
7675		 * leaves time for someone to come in with another
7676		 * persistent reservation.  (That is unlikely, though,
7677		 * since this should be the only persistent reservation
7678		 * command active right now.)
7679		 */
7680		if (tmp_len != total_len) {
7681			mtx_unlock(&lun->lun_lock);
7682			free(ctsio->kern_data_ptr, M_CTL);
7683			printf("%s: reservation status changed, retrying\n",
7684			       __func__);
7685			goto retry;
7686		}
7687
7688		/*
7689		 * No reservation held, so we're done.
7690		 */
7691		if (header_only != 0)
7692			break;
7693
7694		/*
7695		 * If the registration is an All Registrants type, the key
7696		 * is 0, since it doesn't really matter.
7697		 */
7698		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7699			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7700			    res->data.reservation);
7701		}
7702		res->data.scopetype = lun->pr_res_type;
7703		break;
7704	}
7705	case SPRI_RC:     //report capabilities
7706	{
7707		struct scsi_per_res_cap *res_cap;
7708		uint16_t type_mask;
7709
7710		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7711		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7712		res_cap->flags1 = SPRI_CRH;
7713		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7714		type_mask = SPRI_TM_WR_EX_AR |
7715			    SPRI_TM_EX_AC_RO |
7716			    SPRI_TM_WR_EX_RO |
7717			    SPRI_TM_EX_AC |
7718			    SPRI_TM_WR_EX |
7719			    SPRI_TM_EX_AC_AR;
7720		scsi_ulto2b(type_mask, res_cap->type_mask);
7721		break;
7722	}
7723	case SPRI_RS: { // read full status
7724		struct scsi_per_res_in_full *res_status;
7725		struct scsi_per_res_in_full_desc *res_desc;
7726		struct ctl_port *port;
7727		int i, len;
7728
7729		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7730
7731		/*
7732		 * We had to drop the lock to allocate our buffer, which
7733		 * leaves time for someone to come in with another
7734		 * persistent reservation.  (That is unlikely, though,
7735		 * since this should be the only persistent reservation
7736		 * command active right now.)
7737		 */
7738		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7739		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7740		     lun->pr_key_count)){
7741			mtx_unlock(&lun->lun_lock);
7742			free(ctsio->kern_data_ptr, M_CTL);
7743			printf("%s: reservation length changed, retrying\n",
7744			       __func__);
7745			goto retry;
7746		}
7747
7748		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7749
7750		res_desc = &res_status->desc[0];
7751		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7752			if ((key = ctl_get_prkey(lun, i)) == 0)
7753				continue;
7754
7755			scsi_u64to8b(key, res_desc->res_key.key);
7756			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7757			    (lun->pr_res_idx == i ||
7758			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7759				res_desc->flags = SPRI_FULL_R_HOLDER;
7760				res_desc->scopetype = lun->pr_res_type;
7761			}
7762			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7763			    res_desc->rel_trgt_port_id);
7764			len = 0;
7765			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7766			if (port != NULL)
7767				len = ctl_create_iid(port,
7768				    i % CTL_MAX_INIT_PER_PORT,
7769				    res_desc->transport_id);
7770			scsi_ulto4b(len, res_desc->additional_length);
7771			res_desc = (struct scsi_per_res_in_full_desc *)
7772			    &res_desc->transport_id[len];
7773		}
7774		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7775		    res_status->header.length);
7776		break;
7777	}
7778	default:
7779		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7780	}
7781	mtx_unlock(&lun->lun_lock);
7782
7783	ctl_set_success(ctsio);
7784	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7785	ctsio->be_move_done = ctl_config_move_done;
7786	ctl_datamove((union ctl_io *)ctsio);
7787	return (CTL_RETVAL_COMPLETE);
7788}
7789
7790/*
7791 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7792 * it should return.
7793 */
7794static int
7795ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7796		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7797		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7798		struct scsi_per_res_out_parms* param)
7799{
7800	union ctl_ha_msg persis_io;
7801	int i;
7802
7803	mtx_lock(&lun->lun_lock);
7804	if (sa_res_key == 0) {
7805		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7806			/* validate scope and type */
7807			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7808			     SPR_LU_SCOPE) {
7809				mtx_unlock(&lun->lun_lock);
7810				ctl_set_invalid_field(/*ctsio*/ ctsio,
7811						      /*sks_valid*/ 1,
7812						      /*command*/ 1,
7813						      /*field*/ 2,
7814						      /*bit_valid*/ 1,
7815						      /*bit*/ 4);
7816				ctl_done((union ctl_io *)ctsio);
7817				return (1);
7818			}
7819
7820		        if (type>8 || type==2 || type==4 || type==0) {
7821				mtx_unlock(&lun->lun_lock);
7822				ctl_set_invalid_field(/*ctsio*/ ctsio,
7823       	           				      /*sks_valid*/ 1,
7824						      /*command*/ 1,
7825						      /*field*/ 2,
7826						      /*bit_valid*/ 1,
7827						      /*bit*/ 0);
7828				ctl_done((union ctl_io *)ctsio);
7829				return (1);
7830		        }
7831
7832			/*
7833			 * Unregister everybody else and build UA for
7834			 * them
7835			 */
7836			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7837				if (i == residx || ctl_get_prkey(lun, i) == 0)
7838					continue;
7839
7840				ctl_clr_prkey(lun, i);
7841				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7842			}
7843			lun->pr_key_count = 1;
7844			lun->pr_res_type = type;
7845			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7846			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7847				lun->pr_res_idx = residx;
7848			lun->pr_generation++;
7849			mtx_unlock(&lun->lun_lock);
7850
7851			/* send msg to other side */
7852			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7853			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7854			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7855			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7856			persis_io.pr.pr_info.res_type = type;
7857			memcpy(persis_io.pr.pr_info.sa_res_key,
7858			       param->serv_act_res_key,
7859			       sizeof(param->serv_act_res_key));
7860			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7861			    sizeof(persis_io.pr), M_WAITOK);
7862		} else {
7863			/* not all registrants */
7864			mtx_unlock(&lun->lun_lock);
7865			free(ctsio->kern_data_ptr, M_CTL);
7866			ctl_set_invalid_field(ctsio,
7867					      /*sks_valid*/ 1,
7868					      /*command*/ 0,
7869					      /*field*/ 8,
7870					      /*bit_valid*/ 0,
7871					      /*bit*/ 0);
7872			ctl_done((union ctl_io *)ctsio);
7873			return (1);
7874		}
7875	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7876		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7877		int found = 0;
7878
7879		if (res_key == sa_res_key) {
7880			/* special case */
7881			/*
7882			 * The spec implies this is not good but doesn't
7883			 * say what to do. There are two choices either
7884			 * generate a res conflict or check condition
7885			 * with illegal field in parameter data. Since
7886			 * that is what is done when the sa_res_key is
7887			 * zero I'll take that approach since this has
7888			 * to do with the sa_res_key.
7889			 */
7890			mtx_unlock(&lun->lun_lock);
7891			free(ctsio->kern_data_ptr, M_CTL);
7892			ctl_set_invalid_field(ctsio,
7893					      /*sks_valid*/ 1,
7894					      /*command*/ 0,
7895					      /*field*/ 8,
7896					      /*bit_valid*/ 0,
7897					      /*bit*/ 0);
7898			ctl_done((union ctl_io *)ctsio);
7899			return (1);
7900		}
7901
7902		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7903			if (ctl_get_prkey(lun, i) != sa_res_key)
7904				continue;
7905
7906			found = 1;
7907			ctl_clr_prkey(lun, i);
7908			lun->pr_key_count--;
7909			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7910		}
7911		if (!found) {
7912			mtx_unlock(&lun->lun_lock);
7913			free(ctsio->kern_data_ptr, M_CTL);
7914			ctl_set_reservation_conflict(ctsio);
7915			ctl_done((union ctl_io *)ctsio);
7916			return (CTL_RETVAL_COMPLETE);
7917		}
7918		lun->pr_generation++;
7919		mtx_unlock(&lun->lun_lock);
7920
7921		/* send msg to other side */
7922		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7923		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7924		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7925		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7926		persis_io.pr.pr_info.res_type = type;
7927		memcpy(persis_io.pr.pr_info.sa_res_key,
7928		       param->serv_act_res_key,
7929		       sizeof(param->serv_act_res_key));
7930		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7931		    sizeof(persis_io.pr), M_WAITOK);
7932	} else {
7933		/* Reserved but not all registrants */
7934		/* sa_res_key is res holder */
7935		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7936			/* validate scope and type */
7937			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7938			     SPR_LU_SCOPE) {
7939				mtx_unlock(&lun->lun_lock);
7940				ctl_set_invalid_field(/*ctsio*/ ctsio,
7941						      /*sks_valid*/ 1,
7942						      /*command*/ 1,
7943						      /*field*/ 2,
7944						      /*bit_valid*/ 1,
7945						      /*bit*/ 4);
7946				ctl_done((union ctl_io *)ctsio);
7947				return (1);
7948			}
7949
7950			if (type>8 || type==2 || type==4 || type==0) {
7951				mtx_unlock(&lun->lun_lock);
7952				ctl_set_invalid_field(/*ctsio*/ ctsio,
7953						      /*sks_valid*/ 1,
7954						      /*command*/ 1,
7955						      /*field*/ 2,
7956						      /*bit_valid*/ 1,
7957						      /*bit*/ 0);
7958				ctl_done((union ctl_io *)ctsio);
7959				return (1);
7960			}
7961
7962			/*
7963			 * Do the following:
7964			 * if sa_res_key != res_key remove all
7965			 * registrants w/sa_res_key and generate UA
7966			 * for these registrants(Registrations
7967			 * Preempted) if it wasn't an exclusive
7968			 * reservation generate UA(Reservations
7969			 * Preempted) for all other registered nexuses
7970			 * if the type has changed. Establish the new
7971			 * reservation and holder. If res_key and
7972			 * sa_res_key are the same do the above
7973			 * except don't unregister the res holder.
7974			 */
7975
7976			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7977				if (i == residx || ctl_get_prkey(lun, i) == 0)
7978					continue;
7979
7980				if (sa_res_key == ctl_get_prkey(lun, i)) {
7981					ctl_clr_prkey(lun, i);
7982					lun->pr_key_count--;
7983					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7984				} else if (type != lun->pr_res_type &&
7985				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7986				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7987					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7988				}
7989			}
7990			lun->pr_res_type = type;
7991			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7992			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7993				lun->pr_res_idx = residx;
7994			else
7995				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7996			lun->pr_generation++;
7997			mtx_unlock(&lun->lun_lock);
7998
7999			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8000			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8001			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8002			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8003			persis_io.pr.pr_info.res_type = type;
8004			memcpy(persis_io.pr.pr_info.sa_res_key,
8005			       param->serv_act_res_key,
8006			       sizeof(param->serv_act_res_key));
8007			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8008			    sizeof(persis_io.pr), M_WAITOK);
8009		} else {
8010			/*
8011			 * sa_res_key is not the res holder just
8012			 * remove registrants
8013			 */
8014			int found=0;
8015
8016			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8017				if (sa_res_key != ctl_get_prkey(lun, i))
8018					continue;
8019
8020				found = 1;
8021				ctl_clr_prkey(lun, i);
8022				lun->pr_key_count--;
8023				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8024			}
8025
8026			if (!found) {
8027				mtx_unlock(&lun->lun_lock);
8028				free(ctsio->kern_data_ptr, M_CTL);
8029				ctl_set_reservation_conflict(ctsio);
8030				ctl_done((union ctl_io *)ctsio);
8031		        	return (1);
8032			}
8033			lun->pr_generation++;
8034			mtx_unlock(&lun->lun_lock);
8035
8036			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8037			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8038			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8039			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8040			persis_io.pr.pr_info.res_type = type;
8041			memcpy(persis_io.pr.pr_info.sa_res_key,
8042			       param->serv_act_res_key,
8043			       sizeof(param->serv_act_res_key));
8044			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8045			    sizeof(persis_io.pr), M_WAITOK);
8046		}
8047	}
8048	return (0);
8049}
8050
8051static void
8052ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8053{
8054	uint64_t sa_res_key;
8055	int i;
8056
8057	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8058
8059	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8060	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8061	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8062		if (sa_res_key == 0) {
8063			/*
8064			 * Unregister everybody else and build UA for
8065			 * them
8066			 */
8067			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8068				if (i == msg->pr.pr_info.residx ||
8069				    ctl_get_prkey(lun, i) == 0)
8070					continue;
8071
8072				ctl_clr_prkey(lun, i);
8073				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8074			}
8075
8076			lun->pr_key_count = 1;
8077			lun->pr_res_type = msg->pr.pr_info.res_type;
8078			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8079			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8080				lun->pr_res_idx = msg->pr.pr_info.residx;
8081		} else {
8082		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8083				if (sa_res_key == ctl_get_prkey(lun, i))
8084					continue;
8085
8086				ctl_clr_prkey(lun, i);
8087				lun->pr_key_count--;
8088				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8089			}
8090		}
8091	} else {
8092		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8093			if (i == msg->pr.pr_info.residx ||
8094			    ctl_get_prkey(lun, i) == 0)
8095				continue;
8096
8097			if (sa_res_key == ctl_get_prkey(lun, i)) {
8098				ctl_clr_prkey(lun, i);
8099				lun->pr_key_count--;
8100				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8101			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8102			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8103			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8104				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8105			}
8106		}
8107		lun->pr_res_type = msg->pr.pr_info.res_type;
8108		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8109		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8110			lun->pr_res_idx = msg->pr.pr_info.residx;
8111		else
8112			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8113	}
8114	lun->pr_generation++;
8115
8116}
8117
8118
8119int
8120ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8121{
8122	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8123	struct ctl_lun *lun = CTL_LUN(ctsio);
8124	int retval;
8125	u_int32_t param_len;
8126	struct scsi_per_res_out *cdb;
8127	struct scsi_per_res_out_parms* param;
8128	uint32_t residx;
8129	uint64_t res_key, sa_res_key, key;
8130	uint8_t type;
8131	union ctl_ha_msg persis_io;
8132	int    i;
8133
8134	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8135
8136	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8137	retval = CTL_RETVAL_COMPLETE;
8138
8139	/*
8140	 * We only support whole-LUN scope.  The scope & type are ignored for
8141	 * register, register and ignore existing key and clear.
8142	 * We sometimes ignore scope and type on preempts too!!
8143	 * Verify reservation type here as well.
8144	 */
8145	type = cdb->scope_type & SPR_TYPE_MASK;
8146	if ((cdb->action == SPRO_RESERVE)
8147	 || (cdb->action == SPRO_RELEASE)) {
8148		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8149			ctl_set_invalid_field(/*ctsio*/ ctsio,
8150					      /*sks_valid*/ 1,
8151					      /*command*/ 1,
8152					      /*field*/ 2,
8153					      /*bit_valid*/ 1,
8154					      /*bit*/ 4);
8155			ctl_done((union ctl_io *)ctsio);
8156			return (CTL_RETVAL_COMPLETE);
8157		}
8158
8159		if (type>8 || type==2 || type==4 || type==0) {
8160			ctl_set_invalid_field(/*ctsio*/ ctsio,
8161					      /*sks_valid*/ 1,
8162					      /*command*/ 1,
8163					      /*field*/ 2,
8164					      /*bit_valid*/ 1,
8165					      /*bit*/ 0);
8166			ctl_done((union ctl_io *)ctsio);
8167			return (CTL_RETVAL_COMPLETE);
8168		}
8169	}
8170
8171	param_len = scsi_4btoul(cdb->length);
8172
8173	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8174		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8175		ctsio->kern_data_len = param_len;
8176		ctsio->kern_total_len = param_len;
8177		ctsio->kern_rel_offset = 0;
8178		ctsio->kern_sg_entries = 0;
8179		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8180		ctsio->be_move_done = ctl_config_move_done;
8181		ctl_datamove((union ctl_io *)ctsio);
8182
8183		return (CTL_RETVAL_COMPLETE);
8184	}
8185
8186	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8187
8188	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8189	res_key = scsi_8btou64(param->res_key.key);
8190	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8191
8192	/*
8193	 * Validate the reservation key here except for SPRO_REG_IGNO
8194	 * This must be done for all other service actions
8195	 */
8196	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8197		mtx_lock(&lun->lun_lock);
8198		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8199			if (res_key != key) {
8200				/*
8201				 * The current key passed in doesn't match
8202				 * the one the initiator previously
8203				 * registered.
8204				 */
8205				mtx_unlock(&lun->lun_lock);
8206				free(ctsio->kern_data_ptr, M_CTL);
8207				ctl_set_reservation_conflict(ctsio);
8208				ctl_done((union ctl_io *)ctsio);
8209				return (CTL_RETVAL_COMPLETE);
8210			}
8211		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8212			/*
8213			 * We are not registered
8214			 */
8215			mtx_unlock(&lun->lun_lock);
8216			free(ctsio->kern_data_ptr, M_CTL);
8217			ctl_set_reservation_conflict(ctsio);
8218			ctl_done((union ctl_io *)ctsio);
8219			return (CTL_RETVAL_COMPLETE);
8220		} else if (res_key != 0) {
8221			/*
8222			 * We are not registered and trying to register but
8223			 * the register key isn't zero.
8224			 */
8225			mtx_unlock(&lun->lun_lock);
8226			free(ctsio->kern_data_ptr, M_CTL);
8227			ctl_set_reservation_conflict(ctsio);
8228			ctl_done((union ctl_io *)ctsio);
8229			return (CTL_RETVAL_COMPLETE);
8230		}
8231		mtx_unlock(&lun->lun_lock);
8232	}
8233
8234	switch (cdb->action & SPRO_ACTION_MASK) {
8235	case SPRO_REGISTER:
8236	case SPRO_REG_IGNO: {
8237
8238		/*
8239		 * We don't support any of these options, as we report in
8240		 * the read capabilities request (see
8241		 * ctl_persistent_reserve_in(), above).
8242		 */
8243		if ((param->flags & SPR_SPEC_I_PT)
8244		 || (param->flags & SPR_ALL_TG_PT)
8245		 || (param->flags & SPR_APTPL)) {
8246			int bit_ptr;
8247
8248			if (param->flags & SPR_APTPL)
8249				bit_ptr = 0;
8250			else if (param->flags & SPR_ALL_TG_PT)
8251				bit_ptr = 2;
8252			else /* SPR_SPEC_I_PT */
8253				bit_ptr = 3;
8254
8255			free(ctsio->kern_data_ptr, M_CTL);
8256			ctl_set_invalid_field(ctsio,
8257					      /*sks_valid*/ 1,
8258					      /*command*/ 0,
8259					      /*field*/ 20,
8260					      /*bit_valid*/ 1,
8261					      /*bit*/ bit_ptr);
8262			ctl_done((union ctl_io *)ctsio);
8263			return (CTL_RETVAL_COMPLETE);
8264		}
8265
8266		mtx_lock(&lun->lun_lock);
8267
8268		/*
8269		 * The initiator wants to clear the
8270		 * key/unregister.
8271		 */
8272		if (sa_res_key == 0) {
8273			if ((res_key == 0
8274			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8275			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8276			  && ctl_get_prkey(lun, residx) == 0)) {
8277				mtx_unlock(&lun->lun_lock);
8278				goto done;
8279			}
8280
8281			ctl_clr_prkey(lun, residx);
8282			lun->pr_key_count--;
8283
8284			if (residx == lun->pr_res_idx) {
8285				lun->flags &= ~CTL_LUN_PR_RESERVED;
8286				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8287
8288				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8289				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8290				    lun->pr_key_count) {
8291					/*
8292					 * If the reservation is a registrants
8293					 * only type we need to generate a UA
8294					 * for other registered inits.  The
8295					 * sense code should be RESERVATIONS
8296					 * RELEASED
8297					 */
8298
8299					for (i = softc->init_min; i < softc->init_max; i++){
8300						if (ctl_get_prkey(lun, i) == 0)
8301							continue;
8302						ctl_est_ua(lun, i,
8303						    CTL_UA_RES_RELEASE);
8304					}
8305				}
8306				lun->pr_res_type = 0;
8307			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8308				if (lun->pr_key_count==0) {
8309					lun->flags &= ~CTL_LUN_PR_RESERVED;
8310					lun->pr_res_type = 0;
8311					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8312				}
8313			}
8314			lun->pr_generation++;
8315			mtx_unlock(&lun->lun_lock);
8316
8317			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8318			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8319			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8320			persis_io.pr.pr_info.residx = residx;
8321			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8322			    sizeof(persis_io.pr), M_WAITOK);
8323		} else /* sa_res_key != 0 */ {
8324
8325			/*
8326			 * If we aren't registered currently then increment
8327			 * the key count and set the registered flag.
8328			 */
8329			ctl_alloc_prkey(lun, residx);
8330			if (ctl_get_prkey(lun, residx) == 0)
8331				lun->pr_key_count++;
8332			ctl_set_prkey(lun, residx, sa_res_key);
8333			lun->pr_generation++;
8334			mtx_unlock(&lun->lun_lock);
8335
8336			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8337			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8338			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8339			persis_io.pr.pr_info.residx = residx;
8340			memcpy(persis_io.pr.pr_info.sa_res_key,
8341			       param->serv_act_res_key,
8342			       sizeof(param->serv_act_res_key));
8343			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8344			    sizeof(persis_io.pr), M_WAITOK);
8345		}
8346
8347		break;
8348	}
8349	case SPRO_RESERVE:
8350		mtx_lock(&lun->lun_lock);
8351		if (lun->flags & CTL_LUN_PR_RESERVED) {
8352			/*
8353			 * if this isn't the reservation holder and it's
8354			 * not a "all registrants" type or if the type is
8355			 * different then we have a conflict
8356			 */
8357			if ((lun->pr_res_idx != residx
8358			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8359			 || lun->pr_res_type != type) {
8360				mtx_unlock(&lun->lun_lock);
8361				free(ctsio->kern_data_ptr, M_CTL);
8362				ctl_set_reservation_conflict(ctsio);
8363				ctl_done((union ctl_io *)ctsio);
8364				return (CTL_RETVAL_COMPLETE);
8365			}
8366			mtx_unlock(&lun->lun_lock);
8367		} else /* create a reservation */ {
8368			/*
8369			 * If it's not an "all registrants" type record
8370			 * reservation holder
8371			 */
8372			if (type != SPR_TYPE_WR_EX_AR
8373			 && type != SPR_TYPE_EX_AC_AR)
8374				lun->pr_res_idx = residx; /* Res holder */
8375			else
8376				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8377
8378			lun->flags |= CTL_LUN_PR_RESERVED;
8379			lun->pr_res_type = type;
8380
8381			mtx_unlock(&lun->lun_lock);
8382
8383			/* send msg to other side */
8384			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8385			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8386			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8387			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8388			persis_io.pr.pr_info.res_type = type;
8389			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8390			    sizeof(persis_io.pr), M_WAITOK);
8391		}
8392		break;
8393
8394	case SPRO_RELEASE:
8395		mtx_lock(&lun->lun_lock);
8396		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8397			/* No reservation exists return good status */
8398			mtx_unlock(&lun->lun_lock);
8399			goto done;
8400		}
8401		/*
8402		 * Is this nexus a reservation holder?
8403		 */
8404		if (lun->pr_res_idx != residx
8405		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8406			/*
8407			 * not a res holder return good status but
8408			 * do nothing
8409			 */
8410			mtx_unlock(&lun->lun_lock);
8411			goto done;
8412		}
8413
8414		if (lun->pr_res_type != type) {
8415			mtx_unlock(&lun->lun_lock);
8416			free(ctsio->kern_data_ptr, M_CTL);
8417			ctl_set_illegal_pr_release(ctsio);
8418			ctl_done((union ctl_io *)ctsio);
8419			return (CTL_RETVAL_COMPLETE);
8420		}
8421
8422		/* okay to release */
8423		lun->flags &= ~CTL_LUN_PR_RESERVED;
8424		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8425		lun->pr_res_type = 0;
8426
8427		/*
8428		 * If this isn't an exclusive access reservation and NUAR
8429		 * is not set, generate UA for all other registrants.
8430		 */
8431		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8432		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8433			for (i = softc->init_min; i < softc->init_max; i++) {
8434				if (i == residx || ctl_get_prkey(lun, i) == 0)
8435					continue;
8436				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8437			}
8438		}
8439		mtx_unlock(&lun->lun_lock);
8440
8441		/* Send msg to other side */
8442		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8443		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8444		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8445		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8446		     sizeof(persis_io.pr), M_WAITOK);
8447		break;
8448
8449	case SPRO_CLEAR:
8450		/* send msg to other side */
8451
8452		mtx_lock(&lun->lun_lock);
8453		lun->flags &= ~CTL_LUN_PR_RESERVED;
8454		lun->pr_res_type = 0;
8455		lun->pr_key_count = 0;
8456		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8457
8458		ctl_clr_prkey(lun, residx);
8459		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8460			if (ctl_get_prkey(lun, i) != 0) {
8461				ctl_clr_prkey(lun, i);
8462				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8463			}
8464		lun->pr_generation++;
8465		mtx_unlock(&lun->lun_lock);
8466
8467		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8468		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8469		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8470		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8471		     sizeof(persis_io.pr), M_WAITOK);
8472		break;
8473
8474	case SPRO_PREEMPT:
8475	case SPRO_PRE_ABO: {
8476		int nretval;
8477
8478		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8479					  residx, ctsio, cdb, param);
8480		if (nretval != 0)
8481			return (CTL_RETVAL_COMPLETE);
8482		break;
8483	}
8484	default:
8485		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8486	}
8487
8488done:
8489	free(ctsio->kern_data_ptr, M_CTL);
8490	ctl_set_success(ctsio);
8491	ctl_done((union ctl_io *)ctsio);
8492
8493	return (retval);
8494}
8495
8496/*
8497 * This routine is for handling a message from the other SC pertaining to
8498 * persistent reserve out. All the error checking will have been done
8499 * so only perorming the action need be done here to keep the two
8500 * in sync.
8501 */
8502static void
8503ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8504{
8505	struct ctl_softc *softc = CTL_SOFTC(io);
8506	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8507	struct ctl_lun *lun;
8508	int i;
8509	uint32_t residx, targ_lun;
8510
8511	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8512	mtx_lock(&softc->ctl_lock);
8513	if (targ_lun >= ctl_max_luns ||
8514	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8515		mtx_unlock(&softc->ctl_lock);
8516		return;
8517	}
8518	mtx_lock(&lun->lun_lock);
8519	mtx_unlock(&softc->ctl_lock);
8520	if (lun->flags & CTL_LUN_DISABLED) {
8521		mtx_unlock(&lun->lun_lock);
8522		return;
8523	}
8524	residx = ctl_get_initindex(&msg->hdr.nexus);
8525	switch(msg->pr.pr_info.action) {
8526	case CTL_PR_REG_KEY:
8527		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8528		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8529			lun->pr_key_count++;
8530		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8531		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8532		lun->pr_generation++;
8533		break;
8534
8535	case CTL_PR_UNREG_KEY:
8536		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8537		lun->pr_key_count--;
8538
8539		/* XXX Need to see if the reservation has been released */
8540		/* if so do we need to generate UA? */
8541		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8542			lun->flags &= ~CTL_LUN_PR_RESERVED;
8543			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8544
8545			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8546			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8547			    lun->pr_key_count) {
8548				/*
8549				 * If the reservation is a registrants
8550				 * only type we need to generate a UA
8551				 * for other registered inits.  The
8552				 * sense code should be RESERVATIONS
8553				 * RELEASED
8554				 */
8555
8556				for (i = softc->init_min; i < softc->init_max; i++) {
8557					if (ctl_get_prkey(lun, i) == 0)
8558						continue;
8559
8560					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8561				}
8562			}
8563			lun->pr_res_type = 0;
8564		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8565			if (lun->pr_key_count==0) {
8566				lun->flags &= ~CTL_LUN_PR_RESERVED;
8567				lun->pr_res_type = 0;
8568				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8569			}
8570		}
8571		lun->pr_generation++;
8572		break;
8573
8574	case CTL_PR_RESERVE:
8575		lun->flags |= CTL_LUN_PR_RESERVED;
8576		lun->pr_res_type = msg->pr.pr_info.res_type;
8577		lun->pr_res_idx = msg->pr.pr_info.residx;
8578
8579		break;
8580
8581	case CTL_PR_RELEASE:
8582		/*
8583		 * If this isn't an exclusive access reservation and NUAR
8584		 * is not set, generate UA for all other registrants.
8585		 */
8586		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8587		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8588		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8589			for (i = softc->init_min; i < softc->init_max; i++)
8590				if (i == residx || ctl_get_prkey(lun, i) == 0)
8591					continue;
8592				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8593		}
8594
8595		lun->flags &= ~CTL_LUN_PR_RESERVED;
8596		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8597		lun->pr_res_type = 0;
8598		break;
8599
8600	case CTL_PR_PREEMPT:
8601		ctl_pro_preempt_other(lun, msg);
8602		break;
8603	case CTL_PR_CLEAR:
8604		lun->flags &= ~CTL_LUN_PR_RESERVED;
8605		lun->pr_res_type = 0;
8606		lun->pr_key_count = 0;
8607		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8608
8609		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8610			if (ctl_get_prkey(lun, i) == 0)
8611				continue;
8612			ctl_clr_prkey(lun, i);
8613			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8614		}
8615		lun->pr_generation++;
8616		break;
8617	}
8618
8619	mtx_unlock(&lun->lun_lock);
8620}
8621
8622int
8623ctl_read_write(struct ctl_scsiio *ctsio)
8624{
8625	struct ctl_lun *lun = CTL_LUN(ctsio);
8626	struct ctl_lba_len_flags *lbalen;
8627	uint64_t lba;
8628	uint32_t num_blocks;
8629	int flags, retval;
8630	int isread;
8631
8632	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8633
8634	flags = 0;
8635	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8636	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8637	switch (ctsio->cdb[0]) {
8638	case READ_6:
8639	case WRITE_6: {
8640		struct scsi_rw_6 *cdb;
8641
8642		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8643
8644		lba = scsi_3btoul(cdb->addr);
8645		/* only 5 bits are valid in the most significant address byte */
8646		lba &= 0x1fffff;
8647		num_blocks = cdb->length;
8648		/*
8649		 * This is correct according to SBC-2.
8650		 */
8651		if (num_blocks == 0)
8652			num_blocks = 256;
8653		break;
8654	}
8655	case READ_10:
8656	case WRITE_10: {
8657		struct scsi_rw_10 *cdb;
8658
8659		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8660		if (cdb->byte2 & SRW10_FUA)
8661			flags |= CTL_LLF_FUA;
8662		if (cdb->byte2 & SRW10_DPO)
8663			flags |= CTL_LLF_DPO;
8664		lba = scsi_4btoul(cdb->addr);
8665		num_blocks = scsi_2btoul(cdb->length);
8666		break;
8667	}
8668	case WRITE_VERIFY_10: {
8669		struct scsi_write_verify_10 *cdb;
8670
8671		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8672		flags |= CTL_LLF_FUA;
8673		if (cdb->byte2 & SWV_DPO)
8674			flags |= CTL_LLF_DPO;
8675		lba = scsi_4btoul(cdb->addr);
8676		num_blocks = scsi_2btoul(cdb->length);
8677		break;
8678	}
8679	case READ_12:
8680	case WRITE_12: {
8681		struct scsi_rw_12 *cdb;
8682
8683		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8684		if (cdb->byte2 & SRW12_FUA)
8685			flags |= CTL_LLF_FUA;
8686		if (cdb->byte2 & SRW12_DPO)
8687			flags |= CTL_LLF_DPO;
8688		lba = scsi_4btoul(cdb->addr);
8689		num_blocks = scsi_4btoul(cdb->length);
8690		break;
8691	}
8692	case WRITE_VERIFY_12: {
8693		struct scsi_write_verify_12 *cdb;
8694
8695		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8696		flags |= CTL_LLF_FUA;
8697		if (cdb->byte2 & SWV_DPO)
8698			flags |= CTL_LLF_DPO;
8699		lba = scsi_4btoul(cdb->addr);
8700		num_blocks = scsi_4btoul(cdb->length);
8701		break;
8702	}
8703	case READ_16:
8704	case WRITE_16: {
8705		struct scsi_rw_16 *cdb;
8706
8707		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8708		if (cdb->byte2 & SRW12_FUA)
8709			flags |= CTL_LLF_FUA;
8710		if (cdb->byte2 & SRW12_DPO)
8711			flags |= CTL_LLF_DPO;
8712		lba = scsi_8btou64(cdb->addr);
8713		num_blocks = scsi_4btoul(cdb->length);
8714		break;
8715	}
8716	case WRITE_ATOMIC_16: {
8717		struct scsi_write_atomic_16 *cdb;
8718
8719		if (lun->be_lun->atomicblock == 0) {
8720			ctl_set_invalid_opcode(ctsio);
8721			ctl_done((union ctl_io *)ctsio);
8722			return (CTL_RETVAL_COMPLETE);
8723		}
8724
8725		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8726		if (cdb->byte2 & SRW12_FUA)
8727			flags |= CTL_LLF_FUA;
8728		if (cdb->byte2 & SRW12_DPO)
8729			flags |= CTL_LLF_DPO;
8730		lba = scsi_8btou64(cdb->addr);
8731		num_blocks = scsi_2btoul(cdb->length);
8732		if (num_blocks > lun->be_lun->atomicblock) {
8733			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8734			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8735			    /*bit*/ 0);
8736			ctl_done((union ctl_io *)ctsio);
8737			return (CTL_RETVAL_COMPLETE);
8738		}
8739		break;
8740	}
8741	case WRITE_VERIFY_16: {
8742		struct scsi_write_verify_16 *cdb;
8743
8744		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8745		flags |= CTL_LLF_FUA;
8746		if (cdb->byte2 & SWV_DPO)
8747			flags |= CTL_LLF_DPO;
8748		lba = scsi_8btou64(cdb->addr);
8749		num_blocks = scsi_4btoul(cdb->length);
8750		break;
8751	}
8752	default:
8753		/*
8754		 * We got a command we don't support.  This shouldn't
8755		 * happen, commands should be filtered out above us.
8756		 */
8757		ctl_set_invalid_opcode(ctsio);
8758		ctl_done((union ctl_io *)ctsio);
8759
8760		return (CTL_RETVAL_COMPLETE);
8761		break; /* NOTREACHED */
8762	}
8763
8764	/*
8765	 * The first check is to make sure we're in bounds, the second
8766	 * check is to catch wrap-around problems.  If the lba + num blocks
8767	 * is less than the lba, then we've wrapped around and the block
8768	 * range is invalid anyway.
8769	 */
8770	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8771	 || ((lba + num_blocks) < lba)) {
8772		ctl_set_lba_out_of_range(ctsio,
8773		    MAX(lba, lun->be_lun->maxlba + 1));
8774		ctl_done((union ctl_io *)ctsio);
8775		return (CTL_RETVAL_COMPLETE);
8776	}
8777
8778	/*
8779	 * According to SBC-3, a transfer length of 0 is not an error.
8780	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8781	 * translates to 256 blocks for those commands.
8782	 */
8783	if (num_blocks == 0) {
8784		ctl_set_success(ctsio);
8785		ctl_done((union ctl_io *)ctsio);
8786		return (CTL_RETVAL_COMPLETE);
8787	}
8788
8789	/* Set FUA and/or DPO if caches are disabled. */
8790	if (isread) {
8791		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8792			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8793	} else {
8794		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8795			flags |= CTL_LLF_FUA;
8796	}
8797
8798	lbalen = (struct ctl_lba_len_flags *)
8799	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8800	lbalen->lba = lba;
8801	lbalen->len = num_blocks;
8802	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8803
8804	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8805	ctsio->kern_rel_offset = 0;
8806
8807	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8808
8809	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8810	return (retval);
8811}
8812
8813static int
8814ctl_cnw_cont(union ctl_io *io)
8815{
8816	struct ctl_lun *lun = CTL_LUN(io);
8817	struct ctl_scsiio *ctsio;
8818	struct ctl_lba_len_flags *lbalen;
8819	int retval;
8820
8821	ctsio = &io->scsiio;
8822	ctsio->io_hdr.status = CTL_STATUS_NONE;
8823	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8824	lbalen = (struct ctl_lba_len_flags *)
8825	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8826	lbalen->flags &= ~CTL_LLF_COMPARE;
8827	lbalen->flags |= CTL_LLF_WRITE;
8828
8829	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8830	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8831	return (retval);
8832}
8833
8834int
8835ctl_cnw(struct ctl_scsiio *ctsio)
8836{
8837	struct ctl_lun *lun = CTL_LUN(ctsio);
8838	struct ctl_lba_len_flags *lbalen;
8839	uint64_t lba;
8840	uint32_t num_blocks;
8841	int flags, retval;
8842
8843	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8844
8845	flags = 0;
8846	switch (ctsio->cdb[0]) {
8847	case COMPARE_AND_WRITE: {
8848		struct scsi_compare_and_write *cdb;
8849
8850		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8851		if (cdb->byte2 & SRW10_FUA)
8852			flags |= CTL_LLF_FUA;
8853		if (cdb->byte2 & SRW10_DPO)
8854			flags |= CTL_LLF_DPO;
8855		lba = scsi_8btou64(cdb->addr);
8856		num_blocks = cdb->length;
8857		break;
8858	}
8859	default:
8860		/*
8861		 * We got a command we don't support.  This shouldn't
8862		 * happen, commands should be filtered out above us.
8863		 */
8864		ctl_set_invalid_opcode(ctsio);
8865		ctl_done((union ctl_io *)ctsio);
8866
8867		return (CTL_RETVAL_COMPLETE);
8868		break; /* NOTREACHED */
8869	}
8870
8871	/*
8872	 * The first check is to make sure we're in bounds, the second
8873	 * check is to catch wrap-around problems.  If the lba + num blocks
8874	 * is less than the lba, then we've wrapped around and the block
8875	 * range is invalid anyway.
8876	 */
8877	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8878	 || ((lba + num_blocks) < lba)) {
8879		ctl_set_lba_out_of_range(ctsio,
8880		    MAX(lba, lun->be_lun->maxlba + 1));
8881		ctl_done((union ctl_io *)ctsio);
8882		return (CTL_RETVAL_COMPLETE);
8883	}
8884
8885	/*
8886	 * According to SBC-3, a transfer length of 0 is not an error.
8887	 */
8888	if (num_blocks == 0) {
8889		ctl_set_success(ctsio);
8890		ctl_done((union ctl_io *)ctsio);
8891		return (CTL_RETVAL_COMPLETE);
8892	}
8893
8894	/* Set FUA if write cache is disabled. */
8895	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8896		flags |= CTL_LLF_FUA;
8897
8898	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8899	ctsio->kern_rel_offset = 0;
8900
8901	/*
8902	 * Set the IO_CONT flag, so that if this I/O gets passed to
8903	 * ctl_data_submit_done(), it'll get passed back to
8904	 * ctl_ctl_cnw_cont() for further processing.
8905	 */
8906	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8907	ctsio->io_cont = ctl_cnw_cont;
8908
8909	lbalen = (struct ctl_lba_len_flags *)
8910	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8911	lbalen->lba = lba;
8912	lbalen->len = num_blocks;
8913	lbalen->flags = CTL_LLF_COMPARE | flags;
8914
8915	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8916	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8917	return (retval);
8918}
8919
8920int
8921ctl_verify(struct ctl_scsiio *ctsio)
8922{
8923	struct ctl_lun *lun = CTL_LUN(ctsio);
8924	struct ctl_lba_len_flags *lbalen;
8925	uint64_t lba;
8926	uint32_t num_blocks;
8927	int bytchk, flags;
8928	int retval;
8929
8930	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8931
8932	bytchk = 0;
8933	flags = CTL_LLF_FUA;
8934	switch (ctsio->cdb[0]) {
8935	case VERIFY_10: {
8936		struct scsi_verify_10 *cdb;
8937
8938		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8939		if (cdb->byte2 & SVFY_BYTCHK)
8940			bytchk = 1;
8941		if (cdb->byte2 & SVFY_DPO)
8942			flags |= CTL_LLF_DPO;
8943		lba = scsi_4btoul(cdb->addr);
8944		num_blocks = scsi_2btoul(cdb->length);
8945		break;
8946	}
8947	case VERIFY_12: {
8948		struct scsi_verify_12 *cdb;
8949
8950		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8951		if (cdb->byte2 & SVFY_BYTCHK)
8952			bytchk = 1;
8953		if (cdb->byte2 & SVFY_DPO)
8954			flags |= CTL_LLF_DPO;
8955		lba = scsi_4btoul(cdb->addr);
8956		num_blocks = scsi_4btoul(cdb->length);
8957		break;
8958	}
8959	case VERIFY_16: {
8960		struct scsi_rw_16 *cdb;
8961
8962		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8963		if (cdb->byte2 & SVFY_BYTCHK)
8964			bytchk = 1;
8965		if (cdb->byte2 & SVFY_DPO)
8966			flags |= CTL_LLF_DPO;
8967		lba = scsi_8btou64(cdb->addr);
8968		num_blocks = scsi_4btoul(cdb->length);
8969		break;
8970	}
8971	default:
8972		/*
8973		 * We got a command we don't support.  This shouldn't
8974		 * happen, commands should be filtered out above us.
8975		 */
8976		ctl_set_invalid_opcode(ctsio);
8977		ctl_done((union ctl_io *)ctsio);
8978		return (CTL_RETVAL_COMPLETE);
8979	}
8980
8981	/*
8982	 * The first check is to make sure we're in bounds, the second
8983	 * check is to catch wrap-around problems.  If the lba + num blocks
8984	 * is less than the lba, then we've wrapped around and the block
8985	 * range is invalid anyway.
8986	 */
8987	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8988	 || ((lba + num_blocks) < lba)) {
8989		ctl_set_lba_out_of_range(ctsio,
8990		    MAX(lba, lun->be_lun->maxlba + 1));
8991		ctl_done((union ctl_io *)ctsio);
8992		return (CTL_RETVAL_COMPLETE);
8993	}
8994
8995	/*
8996	 * According to SBC-3, a transfer length of 0 is not an error.
8997	 */
8998	if (num_blocks == 0) {
8999		ctl_set_success(ctsio);
9000		ctl_done((union ctl_io *)ctsio);
9001		return (CTL_RETVAL_COMPLETE);
9002	}
9003
9004	lbalen = (struct ctl_lba_len_flags *)
9005	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9006	lbalen->lba = lba;
9007	lbalen->len = num_blocks;
9008	if (bytchk) {
9009		lbalen->flags = CTL_LLF_COMPARE | flags;
9010		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9011	} else {
9012		lbalen->flags = CTL_LLF_VERIFY | flags;
9013		ctsio->kern_total_len = 0;
9014	}
9015	ctsio->kern_rel_offset = 0;
9016
9017	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9018	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9019	return (retval);
9020}
9021
9022int
9023ctl_report_luns(struct ctl_scsiio *ctsio)
9024{
9025	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9026	struct ctl_port *port = CTL_PORT(ctsio);
9027	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9028	struct scsi_report_luns *cdb;
9029	struct scsi_report_luns_data *lun_data;
9030	int num_filled, num_luns, num_port_luns, retval;
9031	uint32_t alloc_len, lun_datalen;
9032	uint32_t initidx, targ_lun_id, lun_id;
9033
9034	retval = CTL_RETVAL_COMPLETE;
9035	cdb = (struct scsi_report_luns *)ctsio->cdb;
9036
9037	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9038
9039	num_luns = 0;
9040	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9041	mtx_lock(&softc->ctl_lock);
9042	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9043		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9044			num_luns++;
9045	}
9046	mtx_unlock(&softc->ctl_lock);
9047
9048	switch (cdb->select_report) {
9049	case RPL_REPORT_DEFAULT:
9050	case RPL_REPORT_ALL:
9051	case RPL_REPORT_NONSUBSID:
9052		break;
9053	case RPL_REPORT_WELLKNOWN:
9054	case RPL_REPORT_ADMIN:
9055	case RPL_REPORT_CONGLOM:
9056		num_luns = 0;
9057		break;
9058	default:
9059		ctl_set_invalid_field(ctsio,
9060				      /*sks_valid*/ 1,
9061				      /*command*/ 1,
9062				      /*field*/ 2,
9063				      /*bit_valid*/ 0,
9064				      /*bit*/ 0);
9065		ctl_done((union ctl_io *)ctsio);
9066		return (retval);
9067		break; /* NOTREACHED */
9068	}
9069
9070	alloc_len = scsi_4btoul(cdb->length);
9071	/*
9072	 * The initiator has to allocate at least 16 bytes for this request,
9073	 * so he can at least get the header and the first LUN.  Otherwise
9074	 * we reject the request (per SPC-3 rev 14, section 6.21).
9075	 */
9076	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9077	    sizeof(struct scsi_report_luns_lundata))) {
9078		ctl_set_invalid_field(ctsio,
9079				      /*sks_valid*/ 1,
9080				      /*command*/ 1,
9081				      /*field*/ 6,
9082				      /*bit_valid*/ 0,
9083				      /*bit*/ 0);
9084		ctl_done((union ctl_io *)ctsio);
9085		return (retval);
9086	}
9087
9088	lun_datalen = sizeof(*lun_data) +
9089		(num_luns * sizeof(struct scsi_report_luns_lundata));
9090
9091	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9092	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9093	ctsio->kern_sg_entries = 0;
9094
9095	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9096
9097	mtx_lock(&softc->ctl_lock);
9098	for (targ_lun_id = 0, num_filled = 0;
9099	    targ_lun_id < num_port_luns && num_filled < num_luns;
9100	    targ_lun_id++) {
9101		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9102		if (lun_id == UINT32_MAX)
9103			continue;
9104		lun = softc->ctl_luns[lun_id];
9105		if (lun == NULL)
9106			continue;
9107
9108		be64enc(lun_data->luns[num_filled++].lundata,
9109		    ctl_encode_lun(targ_lun_id));
9110
9111		/*
9112		 * According to SPC-3, rev 14 section 6.21:
9113		 *
9114		 * "The execution of a REPORT LUNS command to any valid and
9115		 * installed logical unit shall clear the REPORTED LUNS DATA
9116		 * HAS CHANGED unit attention condition for all logical
9117		 * units of that target with respect to the requesting
9118		 * initiator. A valid and installed logical unit is one
9119		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9120		 * INQUIRY data (see 6.4.2)."
9121		 *
9122		 * If request_lun is NULL, the LUN this report luns command
9123		 * was issued to is either disabled or doesn't exist. In that
9124		 * case, we shouldn't clear any pending lun change unit
9125		 * attention.
9126		 */
9127		if (request_lun != NULL) {
9128			mtx_lock(&lun->lun_lock);
9129			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9130			mtx_unlock(&lun->lun_lock);
9131		}
9132	}
9133	mtx_unlock(&softc->ctl_lock);
9134
9135	/*
9136	 * It's quite possible that we've returned fewer LUNs than we allocated
9137	 * space for.  Trim it.
9138	 */
9139	lun_datalen = sizeof(*lun_data) +
9140		(num_filled * sizeof(struct scsi_report_luns_lundata));
9141	ctsio->kern_rel_offset = 0;
9142	ctsio->kern_sg_entries = 0;
9143	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9144	ctsio->kern_total_len = ctsio->kern_data_len;
9145
9146	/*
9147	 * We set this to the actual data length, regardless of how much
9148	 * space we actually have to return results.  If the user looks at
9149	 * this value, he'll know whether or not he allocated enough space
9150	 * and reissue the command if necessary.  We don't support well
9151	 * known logical units, so if the user asks for that, return none.
9152	 */
9153	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9154
9155	/*
9156	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9157	 * this request.
9158	 */
9159	ctl_set_success(ctsio);
9160	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9161	ctsio->be_move_done = ctl_config_move_done;
9162	ctl_datamove((union ctl_io *)ctsio);
9163	return (retval);
9164}
9165
9166int
9167ctl_request_sense(struct ctl_scsiio *ctsio)
9168{
9169	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9170	struct ctl_lun *lun = CTL_LUN(ctsio);
9171	struct scsi_request_sense *cdb;
9172	struct scsi_sense_data *sense_ptr, *ps;
9173	uint32_t initidx;
9174	int have_error;
9175	u_int sense_len = SSD_FULL_SIZE;
9176	scsi_sense_data_type sense_format;
9177	ctl_ua_type ua_type;
9178	uint8_t asc = 0, ascq = 0;
9179
9180	cdb = (struct scsi_request_sense *)ctsio->cdb;
9181
9182	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9183
9184	/*
9185	 * Determine which sense format the user wants.
9186	 */
9187	if (cdb->byte2 & SRS_DESC)
9188		sense_format = SSD_TYPE_DESC;
9189	else
9190		sense_format = SSD_TYPE_FIXED;
9191
9192	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9193	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9194	ctsio->kern_sg_entries = 0;
9195	ctsio->kern_rel_offset = 0;
9196
9197	/*
9198	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9199	 * larger than the largest allowed value for the length field in the
9200	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9201	 */
9202	ctsio->kern_data_len = cdb->length;
9203	ctsio->kern_total_len = cdb->length;
9204
9205	/*
9206	 * If we don't have a LUN, we don't have any pending sense.
9207	 */
9208	if (lun == NULL ||
9209	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9210	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9211		/* "Logical unit not supported" */
9212		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9213		    /*current_error*/ 1,
9214		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9215		    /*asc*/ 0x25,
9216		    /*ascq*/ 0x00,
9217		    SSD_ELEM_NONE);
9218		goto send;
9219	}
9220
9221	have_error = 0;
9222	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9223	/*
9224	 * Check for pending sense, and then for pending unit attentions.
9225	 * Pending sense gets returned first, then pending unit attentions.
9226	 */
9227	mtx_lock(&lun->lun_lock);
9228	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9229	if (ps != NULL)
9230		ps += initidx % CTL_MAX_INIT_PER_PORT;
9231	if (ps != NULL && ps->error_code != 0) {
9232		scsi_sense_data_type stored_format;
9233
9234		/*
9235		 * Check to see which sense format was used for the stored
9236		 * sense data.
9237		 */
9238		stored_format = scsi_sense_type(ps);
9239
9240		/*
9241		 * If the user requested a different sense format than the
9242		 * one we stored, then we need to convert it to the other
9243		 * format.  If we're going from descriptor to fixed format
9244		 * sense data, we may lose things in translation, depending
9245		 * on what options were used.
9246		 *
9247		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9248		 * for some reason we'll just copy it out as-is.
9249		 */
9250		if ((stored_format == SSD_TYPE_FIXED)
9251		 && (sense_format == SSD_TYPE_DESC))
9252			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9253			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9254		else if ((stored_format == SSD_TYPE_DESC)
9255		      && (sense_format == SSD_TYPE_FIXED))
9256			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9257			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9258		else
9259			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9260
9261		ps->error_code = 0;
9262		have_error = 1;
9263	} else {
9264		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9265		    sense_format);
9266		if (ua_type != CTL_UA_NONE)
9267			have_error = 1;
9268	}
9269	if (have_error == 0) {
9270		/*
9271		 * Report informational exception if have one and allowed.
9272		 */
9273		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9274			asc = lun->ie_asc;
9275			ascq = lun->ie_ascq;
9276		}
9277		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9278		    /*current_error*/ 1,
9279		    /*sense_key*/ SSD_KEY_NO_SENSE,
9280		    /*asc*/ asc,
9281		    /*ascq*/ ascq,
9282		    SSD_ELEM_NONE);
9283	}
9284	mtx_unlock(&lun->lun_lock);
9285
9286send:
9287	/*
9288	 * We report the SCSI status as OK, since the status of the command
9289	 * itself is OK.  We're reporting sense as parameter data.
9290	 */
9291	ctl_set_success(ctsio);
9292	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9293	ctsio->be_move_done = ctl_config_move_done;
9294	ctl_datamove((union ctl_io *)ctsio);
9295	return (CTL_RETVAL_COMPLETE);
9296}
9297
9298int
9299ctl_tur(struct ctl_scsiio *ctsio)
9300{
9301
9302	CTL_DEBUG_PRINT(("ctl_tur\n"));
9303
9304	ctl_set_success(ctsio);
9305	ctl_done((union ctl_io *)ctsio);
9306
9307	return (CTL_RETVAL_COMPLETE);
9308}
9309
9310/*
9311 * SCSI VPD page 0x00, the Supported VPD Pages page.
9312 */
9313static int
9314ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9315{
9316	struct ctl_lun *lun = CTL_LUN(ctsio);
9317	struct scsi_vpd_supported_pages *pages;
9318	int sup_page_size;
9319	int p;
9320
9321	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9322	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9323	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9324	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9325	ctsio->kern_rel_offset = 0;
9326	ctsio->kern_sg_entries = 0;
9327	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9328	ctsio->kern_total_len = ctsio->kern_data_len;
9329
9330	/*
9331	 * The control device is always connected.  The disk device, on the
9332	 * other hand, may not be online all the time.  Need to change this
9333	 * to figure out whether the disk device is actually online or not.
9334	 */
9335	if (lun != NULL)
9336		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9337				lun->be_lun->lun_type;
9338	else
9339		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9340
9341	p = 0;
9342	/* Supported VPD pages */
9343	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9344	/* Serial Number */
9345	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9346	/* Device Identification */
9347	pages->page_list[p++] = SVPD_DEVICE_ID;
9348	/* Extended INQUIRY Data */
9349	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9350	/* Mode Page Policy */
9351	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9352	/* SCSI Ports */
9353	pages->page_list[p++] = SVPD_SCSI_PORTS;
9354	/* Third-party Copy */
9355	pages->page_list[p++] = SVPD_SCSI_TPC;
9356	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9357		/* Block limits */
9358		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9359		/* Block Device Characteristics */
9360		pages->page_list[p++] = SVPD_BDC;
9361		/* Logical Block Provisioning */
9362		pages->page_list[p++] = SVPD_LBP;
9363	}
9364	pages->length = p;
9365
9366	ctl_set_success(ctsio);
9367	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9368	ctsio->be_move_done = ctl_config_move_done;
9369	ctl_datamove((union ctl_io *)ctsio);
9370	return (CTL_RETVAL_COMPLETE);
9371}
9372
9373/*
9374 * SCSI VPD page 0x80, the Unit Serial Number page.
9375 */
9376static int
9377ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9378{
9379	struct ctl_lun *lun = CTL_LUN(ctsio);
9380	struct scsi_vpd_unit_serial_number *sn_ptr;
9381	int data_len;
9382
9383	data_len = 4 + CTL_SN_LEN;
9384	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9385	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9386	ctsio->kern_rel_offset = 0;
9387	ctsio->kern_sg_entries = 0;
9388	ctsio->kern_data_len = min(data_len, alloc_len);
9389	ctsio->kern_total_len = ctsio->kern_data_len;
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 ctl_lun *lun = CTL_LUN(ctsio);
9429	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9430	int data_len;
9431
9432	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9433	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9434	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9435	ctsio->kern_sg_entries = 0;
9436	ctsio->kern_rel_offset = 0;
9437	ctsio->kern_data_len = min(data_len, alloc_len);
9438	ctsio->kern_total_len = ctsio->kern_data_len;
9439
9440	/*
9441	 * The control device is always connected.  The disk device, on the
9442	 * other hand, may not be online all the time.
9443	 */
9444	if (lun != NULL)
9445		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9446				     lun->be_lun->lun_type;
9447	else
9448		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9449	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9450	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9451	/*
9452	 * We support head of queue, ordered and simple tags.
9453	 */
9454	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9455	/*
9456	 * Volatile cache supported.
9457	 */
9458	eid_ptr->flags3 = SVPD_EID_V_SUP;
9459
9460	/*
9461	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9462	 * attention for a particular IT nexus on all LUNs once we report
9463	 * it to that nexus once.  This bit is required as of SPC-4.
9464	 */
9465	eid_ptr->flags4 = SVPD_EID_LUICLR;
9466
9467	/*
9468	 * We support revert to defaults (RTD) bit in MODE SELECT.
9469	 */
9470	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9471
9472	/*
9473	 * XXX KDM in order to correctly answer this, we would need
9474	 * information from the SIM to determine how much sense data it
9475	 * can send.  So this would really be a path inquiry field, most
9476	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9477	 * but the hardware may or may not be able to support that much.
9478	 * 0 just means that the maximum sense data length is not reported.
9479	 */
9480	eid_ptr->max_sense_length = 0;
9481
9482	ctl_set_success(ctsio);
9483	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9484	ctsio->be_move_done = ctl_config_move_done;
9485	ctl_datamove((union ctl_io *)ctsio);
9486	return (CTL_RETVAL_COMPLETE);
9487}
9488
9489static int
9490ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9491{
9492	struct ctl_lun *lun = CTL_LUN(ctsio);
9493	struct scsi_vpd_mode_page_policy *mpp_ptr;
9494	int data_len;
9495
9496	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9497	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9498
9499	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9500	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9501	ctsio->kern_rel_offset = 0;
9502	ctsio->kern_sg_entries = 0;
9503	ctsio->kern_data_len = min(data_len, alloc_len);
9504	ctsio->kern_total_len = ctsio->kern_data_len;
9505
9506	/*
9507	 * The control device is always connected.  The disk device, on the
9508	 * other hand, may not be online all the time.
9509	 */
9510	if (lun != NULL)
9511		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9512				     lun->be_lun->lun_type;
9513	else
9514		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9515	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9516	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9517	mpp_ptr->descr[0].page_code = 0x3f;
9518	mpp_ptr->descr[0].subpage_code = 0xff;
9519	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9520
9521	ctl_set_success(ctsio);
9522	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9523	ctsio->be_move_done = ctl_config_move_done;
9524	ctl_datamove((union ctl_io *)ctsio);
9525	return (CTL_RETVAL_COMPLETE);
9526}
9527
9528/*
9529 * SCSI VPD page 0x83, the Device Identification page.
9530 */
9531static int
9532ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9533{
9534	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9535	struct ctl_port *port = CTL_PORT(ctsio);
9536	struct ctl_lun *lun = CTL_LUN(ctsio);
9537	struct scsi_vpd_device_id *devid_ptr;
9538	struct scsi_vpd_id_descriptor *desc;
9539	int data_len, g;
9540	uint8_t proto;
9541
9542	data_len = sizeof(struct scsi_vpd_device_id) +
9543	    sizeof(struct scsi_vpd_id_descriptor) +
9544		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9545	    sizeof(struct scsi_vpd_id_descriptor) +
9546		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9547	if (lun && lun->lun_devid)
9548		data_len += lun->lun_devid->len;
9549	if (port && port->port_devid)
9550		data_len += port->port_devid->len;
9551	if (port && port->target_devid)
9552		data_len += port->target_devid->len;
9553
9554	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9555	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9556	ctsio->kern_sg_entries = 0;
9557	ctsio->kern_rel_offset = 0;
9558	ctsio->kern_sg_entries = 0;
9559	ctsio->kern_data_len = min(data_len, alloc_len);
9560	ctsio->kern_total_len = ctsio->kern_data_len;
9561
9562	/*
9563	 * The control device is always connected.  The disk device, on the
9564	 * other hand, may not be online all the time.
9565	 */
9566	if (lun != NULL)
9567		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9568				     lun->be_lun->lun_type;
9569	else
9570		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9571	devid_ptr->page_code = SVPD_DEVICE_ID;
9572	scsi_ulto2b(data_len - 4, devid_ptr->length);
9573
9574	if (port && port->port_type == CTL_PORT_FC)
9575		proto = SCSI_PROTO_FC << 4;
9576	else if (port && port->port_type == CTL_PORT_SAS)
9577		proto = SCSI_PROTO_SAS << 4;
9578	else if (port && port->port_type == CTL_PORT_ISCSI)
9579		proto = SCSI_PROTO_ISCSI << 4;
9580	else
9581		proto = SCSI_PROTO_SPI << 4;
9582	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9583
9584	/*
9585	 * We're using a LUN association here.  i.e., this device ID is a
9586	 * per-LUN identifier.
9587	 */
9588	if (lun && lun->lun_devid) {
9589		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9590		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9591		    lun->lun_devid->len);
9592	}
9593
9594	/*
9595	 * This is for the WWPN which is a port association.
9596	 */
9597	if (port && port->port_devid) {
9598		memcpy(desc, port->port_devid->data, port->port_devid->len);
9599		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9600		    port->port_devid->len);
9601	}
9602
9603	/*
9604	 * This is for the Relative Target Port(type 4h) identifier
9605	 */
9606	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9607	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9608	    SVPD_ID_TYPE_RELTARG;
9609	desc->length = 4;
9610	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9611	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9612	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9613
9614	/*
9615	 * This is for the Target Port Group(type 5h) identifier
9616	 */
9617	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9618	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9619	    SVPD_ID_TYPE_TPORTGRP;
9620	desc->length = 4;
9621	if (softc->is_single ||
9622	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9623		g = 1;
9624	else
9625		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9626	scsi_ulto2b(g, &desc->identifier[2]);
9627	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9628	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9629
9630	/*
9631	 * This is for the Target identifier
9632	 */
9633	if (port && port->target_devid) {
9634		memcpy(desc, port->target_devid->data, port->target_devid->len);
9635	}
9636
9637	ctl_set_success(ctsio);
9638	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9639	ctsio->be_move_done = ctl_config_move_done;
9640	ctl_datamove((union ctl_io *)ctsio);
9641	return (CTL_RETVAL_COMPLETE);
9642}
9643
9644static int
9645ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9646{
9647	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9648	struct ctl_lun *lun = CTL_LUN(ctsio);
9649	struct scsi_vpd_scsi_ports *sp;
9650	struct scsi_vpd_port_designation *pd;
9651	struct scsi_vpd_port_designation_cont *pdc;
9652	struct ctl_port *port;
9653	int data_len, num_target_ports, iid_len, id_len;
9654
9655	num_target_ports = 0;
9656	iid_len = 0;
9657	id_len = 0;
9658	mtx_lock(&softc->ctl_lock);
9659	STAILQ_FOREACH(port, &softc->port_list, links) {
9660		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9661			continue;
9662		if (lun != NULL &&
9663		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9664			continue;
9665		num_target_ports++;
9666		if (port->init_devid)
9667			iid_len += port->init_devid->len;
9668		if (port->port_devid)
9669			id_len += port->port_devid->len;
9670	}
9671	mtx_unlock(&softc->ctl_lock);
9672
9673	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9674	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9675	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9676	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9677	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9678	ctsio->kern_sg_entries = 0;
9679	ctsio->kern_rel_offset = 0;
9680	ctsio->kern_sg_entries = 0;
9681	ctsio->kern_data_len = min(data_len, alloc_len);
9682	ctsio->kern_total_len = ctsio->kern_data_len;
9683
9684	/*
9685	 * The control device is always connected.  The disk device, on the
9686	 * other hand, may not be online all the time.  Need to change this
9687	 * to figure out whether the disk device is actually online or not.
9688	 */
9689	if (lun != NULL)
9690		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9691				  lun->be_lun->lun_type;
9692	else
9693		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9694
9695	sp->page_code = SVPD_SCSI_PORTS;
9696	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9697	    sp->page_length);
9698	pd = &sp->design[0];
9699
9700	mtx_lock(&softc->ctl_lock);
9701	STAILQ_FOREACH(port, &softc->port_list, links) {
9702		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9703			continue;
9704		if (lun != NULL &&
9705		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9706			continue;
9707		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9708		if (port->init_devid) {
9709			iid_len = port->init_devid->len;
9710			memcpy(pd->initiator_transportid,
9711			    port->init_devid->data, port->init_devid->len);
9712		} else
9713			iid_len = 0;
9714		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9715		pdc = (struct scsi_vpd_port_designation_cont *)
9716		    (&pd->initiator_transportid[iid_len]);
9717		if (port->port_devid) {
9718			id_len = port->port_devid->len;
9719			memcpy(pdc->target_port_descriptors,
9720			    port->port_devid->data, port->port_devid->len);
9721		} else
9722			id_len = 0;
9723		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9724		pd = (struct scsi_vpd_port_designation *)
9725		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9726	}
9727	mtx_unlock(&softc->ctl_lock);
9728
9729	ctl_set_success(ctsio);
9730	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9731	ctsio->be_move_done = ctl_config_move_done;
9732	ctl_datamove((union ctl_io *)ctsio);
9733	return (CTL_RETVAL_COMPLETE);
9734}
9735
9736static int
9737ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9738{
9739	struct ctl_lun *lun = CTL_LUN(ctsio);
9740	struct scsi_vpd_block_limits *bl_ptr;
9741	uint64_t ival;
9742
9743	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9744	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9745	ctsio->kern_sg_entries = 0;
9746	ctsio->kern_rel_offset = 0;
9747	ctsio->kern_sg_entries = 0;
9748	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9749	ctsio->kern_total_len = ctsio->kern_data_len;
9750
9751	/*
9752	 * The control device is always connected.  The disk device, on the
9753	 * other hand, may not be online all the time.  Need to change this
9754	 * to figure out whether the disk device is actually online or not.
9755	 */
9756	if (lun != NULL)
9757		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9758				  lun->be_lun->lun_type;
9759	else
9760		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9761
9762	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9763	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9764	bl_ptr->max_cmp_write_len = 0xff;
9765	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9766	if (lun != NULL) {
9767		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9768		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9769			ival = 0xffffffff;
9770			ctl_get_opt_number(&lun->be_lun->options,
9771			    "unmap_max_lba", &ival);
9772			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9773			ival = 0xffffffff;
9774			ctl_get_opt_number(&lun->be_lun->options,
9775			    "unmap_max_descr", &ival);
9776			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9777			if (lun->be_lun->ublockexp != 0) {
9778				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9779				    bl_ptr->opt_unmap_grain);
9780				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9781				    bl_ptr->unmap_grain_align);
9782			}
9783		}
9784		scsi_ulto4b(lun->be_lun->atomicblock,
9785		    bl_ptr->max_atomic_transfer_length);
9786		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9787		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9788		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9789		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9790		ival = UINT64_MAX;
9791		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9792		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9793	}
9794
9795	ctl_set_success(ctsio);
9796	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9797	ctsio->be_move_done = ctl_config_move_done;
9798	ctl_datamove((union ctl_io *)ctsio);
9799	return (CTL_RETVAL_COMPLETE);
9800}
9801
9802static int
9803ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9804{
9805	struct ctl_lun *lun = CTL_LUN(ctsio);
9806	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9807	const char *value;
9808	u_int i;
9809
9810	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9811	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9812	ctsio->kern_sg_entries = 0;
9813	ctsio->kern_rel_offset = 0;
9814	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9815	ctsio->kern_total_len = ctsio->kern_data_len;
9816
9817	/*
9818	 * The control device is always connected.  The disk device, on the
9819	 * other hand, may not be online all the time.  Need to change this
9820	 * to figure out whether the disk device is actually online or not.
9821	 */
9822	if (lun != NULL)
9823		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9824				  lun->be_lun->lun_type;
9825	else
9826		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9827	bdc_ptr->page_code = SVPD_BDC;
9828	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9829	if (lun != NULL &&
9830	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9831		i = strtol(value, NULL, 0);
9832	else
9833		i = CTL_DEFAULT_ROTATION_RATE;
9834	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9835	if (lun != NULL &&
9836	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9837		i = strtol(value, NULL, 0);
9838	else
9839		i = 0;
9840	bdc_ptr->wab_wac_ff = (i & 0x0f);
9841	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9842
9843	ctl_set_success(ctsio);
9844	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9845	ctsio->be_move_done = ctl_config_move_done;
9846	ctl_datamove((union ctl_io *)ctsio);
9847	return (CTL_RETVAL_COMPLETE);
9848}
9849
9850static int
9851ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9852{
9853	struct ctl_lun *lun = CTL_LUN(ctsio);
9854	struct scsi_vpd_logical_block_prov *lbp_ptr;
9855	const char *value;
9856
9857	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9858	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9859	ctsio->kern_sg_entries = 0;
9860	ctsio->kern_rel_offset = 0;
9861	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9862	ctsio->kern_total_len = ctsio->kern_data_len;
9863
9864	/*
9865	 * The control device is always connected.  The disk device, on the
9866	 * other hand, may not be online all the time.  Need to change this
9867	 * to figure out whether the disk device is actually online or not.
9868	 */
9869	if (lun != NULL)
9870		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9871				  lun->be_lun->lun_type;
9872	else
9873		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9874
9875	lbp_ptr->page_code = SVPD_LBP;
9876	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9877	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9878	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9879		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9880		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9881		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
9882		if (value != NULL) {
9883			if (strcmp(value, "resource") == 0)
9884				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9885			else if (strcmp(value, "thin") == 0)
9886				lbp_ptr->prov_type = SVPD_LBP_THIN;
9887		} else
9888			lbp_ptr->prov_type = SVPD_LBP_THIN;
9889	}
9890
9891	ctl_set_success(ctsio);
9892	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9893	ctsio->be_move_done = ctl_config_move_done;
9894	ctl_datamove((union ctl_io *)ctsio);
9895	return (CTL_RETVAL_COMPLETE);
9896}
9897
9898/*
9899 * INQUIRY with the EVPD bit set.
9900 */
9901static int
9902ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9903{
9904	struct ctl_lun *lun = CTL_LUN(ctsio);
9905	struct scsi_inquiry *cdb;
9906	int alloc_len, retval;
9907
9908	cdb = (struct scsi_inquiry *)ctsio->cdb;
9909	alloc_len = scsi_2btoul(cdb->length);
9910
9911	switch (cdb->page_code) {
9912	case SVPD_SUPPORTED_PAGES:
9913		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9914		break;
9915	case SVPD_UNIT_SERIAL_NUMBER:
9916		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9917		break;
9918	case SVPD_DEVICE_ID:
9919		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9920		break;
9921	case SVPD_EXTENDED_INQUIRY_DATA:
9922		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9923		break;
9924	case SVPD_MODE_PAGE_POLICY:
9925		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9926		break;
9927	case SVPD_SCSI_PORTS:
9928		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9929		break;
9930	case SVPD_SCSI_TPC:
9931		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9932		break;
9933	case SVPD_BLOCK_LIMITS:
9934		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9935			goto err;
9936		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9937		break;
9938	case SVPD_BDC:
9939		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9940			goto err;
9941		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9942		break;
9943	case SVPD_LBP:
9944		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9945			goto err;
9946		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9947		break;
9948	default:
9949err:
9950		ctl_set_invalid_field(ctsio,
9951				      /*sks_valid*/ 1,
9952				      /*command*/ 1,
9953				      /*field*/ 2,
9954				      /*bit_valid*/ 0,
9955				      /*bit*/ 0);
9956		ctl_done((union ctl_io *)ctsio);
9957		retval = CTL_RETVAL_COMPLETE;
9958		break;
9959	}
9960
9961	return (retval);
9962}
9963
9964/*
9965 * Standard INQUIRY data.
9966 */
9967static int
9968ctl_inquiry_std(struct ctl_scsiio *ctsio)
9969{
9970	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9971	struct ctl_port *port = CTL_PORT(ctsio);
9972	struct ctl_lun *lun = CTL_LUN(ctsio);
9973	struct scsi_inquiry_data *inq_ptr;
9974	struct scsi_inquiry *cdb;
9975	char *val;
9976	uint32_t alloc_len, data_len;
9977	ctl_port_type port_type;
9978
9979	port_type = port->port_type;
9980	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
9981		port_type = CTL_PORT_SCSI;
9982
9983	cdb = (struct scsi_inquiry *)ctsio->cdb;
9984	alloc_len = scsi_2btoul(cdb->length);
9985
9986	/*
9987	 * We malloc the full inquiry data size here and fill it
9988	 * in.  If the user only asks for less, we'll give him
9989	 * that much.
9990	 */
9991	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
9992	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9993	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9994	ctsio->kern_sg_entries = 0;
9995	ctsio->kern_rel_offset = 0;
9996	ctsio->kern_data_len = min(data_len, alloc_len);
9997	ctsio->kern_total_len = ctsio->kern_data_len;
9998
9999	if (lun != NULL) {
10000		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10001		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10002			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10003			    lun->be_lun->lun_type;
10004		} else {
10005			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10006			    lun->be_lun->lun_type;
10007		}
10008		if (lun->flags & CTL_LUN_REMOVABLE)
10009			inq_ptr->dev_qual2 |= SID_RMB;
10010	} else
10011		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10012
10013	/* RMB in byte 2 is 0 */
10014	inq_ptr->version = SCSI_REV_SPC5;
10015
10016	/*
10017	 * According to SAM-3, even if a device only supports a single
10018	 * level of LUN addressing, it should still set the HISUP bit:
10019	 *
10020	 * 4.9.1 Logical unit numbers overview
10021	 *
10022	 * All logical unit number formats described in this standard are
10023	 * hierarchical in structure even when only a single level in that
10024	 * hierarchy is used. The HISUP bit shall be set to one in the
10025	 * standard INQUIRY data (see SPC-2) when any logical unit number
10026	 * format described in this standard is used.  Non-hierarchical
10027	 * formats are outside the scope of this standard.
10028	 *
10029	 * Therefore we set the HiSup bit here.
10030	 *
10031	 * The response format is 2, per SPC-3.
10032	 */
10033	inq_ptr->response_format = SID_HiSup | 2;
10034
10035	inq_ptr->additional_length = data_len -
10036	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10037	CTL_DEBUG_PRINT(("additional_length = %d\n",
10038			 inq_ptr->additional_length));
10039
10040	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10041	if (port_type == CTL_PORT_SCSI)
10042		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10043	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10044	inq_ptr->flags = SID_CmdQue;
10045	if (port_type == CTL_PORT_SCSI)
10046		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10047
10048	/*
10049	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10050	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10051	 * name and 4 bytes for the revision.
10052	 */
10053	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10054	    "vendor")) == NULL) {
10055		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10056	} else {
10057		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10058		strncpy(inq_ptr->vendor, val,
10059		    min(sizeof(inq_ptr->vendor), strlen(val)));
10060	}
10061	if (lun == NULL) {
10062		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10063		    sizeof(inq_ptr->product));
10064	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10065		switch (lun->be_lun->lun_type) {
10066		case T_DIRECT:
10067			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10068			    sizeof(inq_ptr->product));
10069			break;
10070		case T_PROCESSOR:
10071			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10072			    sizeof(inq_ptr->product));
10073			break;
10074		case T_CDROM:
10075			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10076			    sizeof(inq_ptr->product));
10077			break;
10078		default:
10079			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10080			    sizeof(inq_ptr->product));
10081			break;
10082		}
10083	} else {
10084		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10085		strncpy(inq_ptr->product, val,
10086		    min(sizeof(inq_ptr->product), strlen(val)));
10087	}
10088
10089	/*
10090	 * XXX make this a macro somewhere so it automatically gets
10091	 * incremented when we make changes.
10092	 */
10093	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10094	    "revision")) == NULL) {
10095		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10096	} else {
10097		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10098		strncpy(inq_ptr->revision, val,
10099		    min(sizeof(inq_ptr->revision), strlen(val)));
10100	}
10101
10102	/*
10103	 * For parallel SCSI, we support double transition and single
10104	 * transition clocking.  We also support QAS (Quick Arbitration
10105	 * and Selection) and Information Unit transfers on both the
10106	 * control and array devices.
10107	 */
10108	if (port_type == CTL_PORT_SCSI)
10109		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10110				    SID_SPI_IUS;
10111
10112	/* SAM-6 (no version claimed) */
10113	scsi_ulto2b(0x00C0, inq_ptr->version1);
10114	/* SPC-5 (no version claimed) */
10115	scsi_ulto2b(0x05C0, inq_ptr->version2);
10116	if (port_type == CTL_PORT_FC) {
10117		/* FCP-2 ANSI INCITS.350:2003 */
10118		scsi_ulto2b(0x0917, inq_ptr->version3);
10119	} else if (port_type == CTL_PORT_SCSI) {
10120		/* SPI-4 ANSI INCITS.362:200x */
10121		scsi_ulto2b(0x0B56, inq_ptr->version3);
10122	} else if (port_type == CTL_PORT_ISCSI) {
10123		/* iSCSI (no version claimed) */
10124		scsi_ulto2b(0x0960, inq_ptr->version3);
10125	} else if (port_type == CTL_PORT_SAS) {
10126		/* SAS (no version claimed) */
10127		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10128	} else if (port_type == CTL_PORT_UMASS) {
10129		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10130		scsi_ulto2b(0x1730, inq_ptr->version3);
10131	}
10132
10133	if (lun == NULL) {
10134		/* SBC-4 (no version claimed) */
10135		scsi_ulto2b(0x0600, inq_ptr->version4);
10136	} else {
10137		switch (lun->be_lun->lun_type) {
10138		case T_DIRECT:
10139			/* SBC-4 (no version claimed) */
10140			scsi_ulto2b(0x0600, inq_ptr->version4);
10141			break;
10142		case T_PROCESSOR:
10143			break;
10144		case T_CDROM:
10145			/* MMC-6 (no version claimed) */
10146			scsi_ulto2b(0x04E0, inq_ptr->version4);
10147			break;
10148		default:
10149			break;
10150		}
10151	}
10152
10153	ctl_set_success(ctsio);
10154	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10155	ctsio->be_move_done = ctl_config_move_done;
10156	ctl_datamove((union ctl_io *)ctsio);
10157	return (CTL_RETVAL_COMPLETE);
10158}
10159
10160int
10161ctl_inquiry(struct ctl_scsiio *ctsio)
10162{
10163	struct scsi_inquiry *cdb;
10164	int retval;
10165
10166	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10167
10168	cdb = (struct scsi_inquiry *)ctsio->cdb;
10169	if (cdb->byte2 & SI_EVPD)
10170		retval = ctl_inquiry_evpd(ctsio);
10171	else if (cdb->page_code == 0)
10172		retval = ctl_inquiry_std(ctsio);
10173	else {
10174		ctl_set_invalid_field(ctsio,
10175				      /*sks_valid*/ 1,
10176				      /*command*/ 1,
10177				      /*field*/ 2,
10178				      /*bit_valid*/ 0,
10179				      /*bit*/ 0);
10180		ctl_done((union ctl_io *)ctsio);
10181		return (CTL_RETVAL_COMPLETE);
10182	}
10183
10184	return (retval);
10185}
10186
10187int
10188ctl_get_config(struct ctl_scsiio *ctsio)
10189{
10190	struct ctl_lun *lun = CTL_LUN(ctsio);
10191	struct scsi_get_config_header *hdr;
10192	struct scsi_get_config_feature *feature;
10193	struct scsi_get_config *cdb;
10194	uint32_t alloc_len, data_len;
10195	int rt, starting;
10196
10197	cdb = (struct scsi_get_config *)ctsio->cdb;
10198	rt = (cdb->rt & SGC_RT_MASK);
10199	starting = scsi_2btoul(cdb->starting_feature);
10200	alloc_len = scsi_2btoul(cdb->length);
10201
10202	data_len = sizeof(struct scsi_get_config_header) +
10203	    sizeof(struct scsi_get_config_feature) + 8 +
10204	    sizeof(struct scsi_get_config_feature) + 8 +
10205	    sizeof(struct scsi_get_config_feature) + 4 +
10206	    sizeof(struct scsi_get_config_feature) + 4 +
10207	    sizeof(struct scsi_get_config_feature) + 8 +
10208	    sizeof(struct scsi_get_config_feature) +
10209	    sizeof(struct scsi_get_config_feature) + 4 +
10210	    sizeof(struct scsi_get_config_feature) + 4 +
10211	    sizeof(struct scsi_get_config_feature) + 4 +
10212	    sizeof(struct scsi_get_config_feature) + 4 +
10213	    sizeof(struct scsi_get_config_feature) + 4 +
10214	    sizeof(struct scsi_get_config_feature) + 4;
10215	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10216	ctsio->kern_sg_entries = 0;
10217	ctsio->kern_rel_offset = 0;
10218
10219	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10220	if (lun->flags & CTL_LUN_NO_MEDIA)
10221		scsi_ulto2b(0x0000, hdr->current_profile);
10222	else
10223		scsi_ulto2b(0x0010, hdr->current_profile);
10224	feature = (struct scsi_get_config_feature *)(hdr + 1);
10225
10226	if (starting > 0x003b)
10227		goto done;
10228	if (starting > 0x003a)
10229		goto f3b;
10230	if (starting > 0x002b)
10231		goto f3a;
10232	if (starting > 0x002a)
10233		goto f2b;
10234	if (starting > 0x001f)
10235		goto f2a;
10236	if (starting > 0x001e)
10237		goto f1f;
10238	if (starting > 0x001d)
10239		goto f1e;
10240	if (starting > 0x0010)
10241		goto f1d;
10242	if (starting > 0x0003)
10243		goto f10;
10244	if (starting > 0x0002)
10245		goto f3;
10246	if (starting > 0x0001)
10247		goto f2;
10248	if (starting > 0x0000)
10249		goto f1;
10250
10251	/* Profile List */
10252	scsi_ulto2b(0x0000, feature->feature_code);
10253	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10254	feature->add_length = 8;
10255	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10256	feature->feature_data[2] = 0x00;
10257	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10258	feature->feature_data[6] = 0x01;
10259	feature = (struct scsi_get_config_feature *)
10260	    &feature->feature_data[feature->add_length];
10261
10262f1:	/* Core */
10263	scsi_ulto2b(0x0001, feature->feature_code);
10264	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10265	feature->add_length = 8;
10266	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10267	feature->feature_data[4] = 0x03;
10268	feature = (struct scsi_get_config_feature *)
10269	    &feature->feature_data[feature->add_length];
10270
10271f2:	/* Morphing */
10272	scsi_ulto2b(0x0002, feature->feature_code);
10273	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10274	feature->add_length = 4;
10275	feature->feature_data[0] = 0x02;
10276	feature = (struct scsi_get_config_feature *)
10277	    &feature->feature_data[feature->add_length];
10278
10279f3:	/* Removable Medium */
10280	scsi_ulto2b(0x0003, feature->feature_code);
10281	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10282	feature->add_length = 4;
10283	feature->feature_data[0] = 0x39;
10284	feature = (struct scsi_get_config_feature *)
10285	    &feature->feature_data[feature->add_length];
10286
10287	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10288		goto done;
10289
10290f10:	/* Random Read */
10291	scsi_ulto2b(0x0010, feature->feature_code);
10292	feature->flags = 0x00;
10293	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10294		feature->flags |= SGC_F_CURRENT;
10295	feature->add_length = 8;
10296	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10297	scsi_ulto2b(1, &feature->feature_data[4]);
10298	feature->feature_data[6] = 0x00;
10299	feature = (struct scsi_get_config_feature *)
10300	    &feature->feature_data[feature->add_length];
10301
10302f1d:	/* Multi-Read */
10303	scsi_ulto2b(0x001D, feature->feature_code);
10304	feature->flags = 0x00;
10305	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10306		feature->flags |= SGC_F_CURRENT;
10307	feature->add_length = 0;
10308	feature = (struct scsi_get_config_feature *)
10309	    &feature->feature_data[feature->add_length];
10310
10311f1e:	/* CD Read */
10312	scsi_ulto2b(0x001E, feature->feature_code);
10313	feature->flags = 0x00;
10314	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10315		feature->flags |= SGC_F_CURRENT;
10316	feature->add_length = 4;
10317	feature->feature_data[0] = 0x00;
10318	feature = (struct scsi_get_config_feature *)
10319	    &feature->feature_data[feature->add_length];
10320
10321f1f:	/* DVD Read */
10322	scsi_ulto2b(0x001F, feature->feature_code);
10323	feature->flags = 0x08;
10324	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10325		feature->flags |= SGC_F_CURRENT;
10326	feature->add_length = 4;
10327	feature->feature_data[0] = 0x01;
10328	feature->feature_data[2] = 0x03;
10329	feature = (struct scsi_get_config_feature *)
10330	    &feature->feature_data[feature->add_length];
10331
10332f2a:	/* DVD+RW */
10333	scsi_ulto2b(0x002A, feature->feature_code);
10334	feature->flags = 0x04;
10335	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10336		feature->flags |= SGC_F_CURRENT;
10337	feature->add_length = 4;
10338	feature->feature_data[0] = 0x00;
10339	feature->feature_data[1] = 0x00;
10340	feature = (struct scsi_get_config_feature *)
10341	    &feature->feature_data[feature->add_length];
10342
10343f2b:	/* DVD+R */
10344	scsi_ulto2b(0x002B, feature->feature_code);
10345	feature->flags = 0x00;
10346	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10347		feature->flags |= SGC_F_CURRENT;
10348	feature->add_length = 4;
10349	feature->feature_data[0] = 0x00;
10350	feature = (struct scsi_get_config_feature *)
10351	    &feature->feature_data[feature->add_length];
10352
10353f3a:	/* DVD+RW Dual Layer */
10354	scsi_ulto2b(0x003A, feature->feature_code);
10355	feature->flags = 0x00;
10356	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10357		feature->flags |= SGC_F_CURRENT;
10358	feature->add_length = 4;
10359	feature->feature_data[0] = 0x00;
10360	feature->feature_data[1] = 0x00;
10361	feature = (struct scsi_get_config_feature *)
10362	    &feature->feature_data[feature->add_length];
10363
10364f3b:	/* DVD+R Dual Layer */
10365	scsi_ulto2b(0x003B, feature->feature_code);
10366	feature->flags = 0x00;
10367	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10368		feature->flags |= SGC_F_CURRENT;
10369	feature->add_length = 4;
10370	feature->feature_data[0] = 0x00;
10371	feature = (struct scsi_get_config_feature *)
10372	    &feature->feature_data[feature->add_length];
10373
10374done:
10375	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10376	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10377		feature = (struct scsi_get_config_feature *)(hdr + 1);
10378		if (scsi_2btoul(feature->feature_code) == starting)
10379			feature = (struct scsi_get_config_feature *)
10380			    &feature->feature_data[feature->add_length];
10381		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10382	}
10383	scsi_ulto4b(data_len - 4, hdr->data_length);
10384	ctsio->kern_data_len = min(data_len, alloc_len);
10385	ctsio->kern_total_len = ctsio->kern_data_len;
10386
10387	ctl_set_success(ctsio);
10388	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10389	ctsio->be_move_done = ctl_config_move_done;
10390	ctl_datamove((union ctl_io *)ctsio);
10391	return (CTL_RETVAL_COMPLETE);
10392}
10393
10394int
10395ctl_get_event_status(struct ctl_scsiio *ctsio)
10396{
10397	struct scsi_get_event_status_header *hdr;
10398	struct scsi_get_event_status *cdb;
10399	uint32_t alloc_len, data_len;
10400	int notif_class;
10401
10402	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10403	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10404		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10405		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10406		ctl_done((union ctl_io *)ctsio);
10407		return (CTL_RETVAL_COMPLETE);
10408	}
10409	notif_class = cdb->notif_class;
10410	alloc_len = scsi_2btoul(cdb->length);
10411
10412	data_len = sizeof(struct scsi_get_event_status_header);
10413	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10414	ctsio->kern_sg_entries = 0;
10415	ctsio->kern_rel_offset = 0;
10416	ctsio->kern_data_len = min(data_len, alloc_len);
10417	ctsio->kern_total_len = ctsio->kern_data_len;
10418
10419	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10420	scsi_ulto2b(0, hdr->descr_length);
10421	hdr->nea_class = SGESN_NEA;
10422	hdr->supported_class = 0;
10423
10424	ctl_set_success(ctsio);
10425	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10426	ctsio->be_move_done = ctl_config_move_done;
10427	ctl_datamove((union ctl_io *)ctsio);
10428	return (CTL_RETVAL_COMPLETE);
10429}
10430
10431int
10432ctl_mechanism_status(struct ctl_scsiio *ctsio)
10433{
10434	struct scsi_mechanism_status_header *hdr;
10435	struct scsi_mechanism_status *cdb;
10436	uint32_t alloc_len, data_len;
10437
10438	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10439	alloc_len = scsi_2btoul(cdb->length);
10440
10441	data_len = sizeof(struct scsi_mechanism_status_header);
10442	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10443	ctsio->kern_sg_entries = 0;
10444	ctsio->kern_rel_offset = 0;
10445	ctsio->kern_data_len = min(data_len, alloc_len);
10446	ctsio->kern_total_len = ctsio->kern_data_len;
10447
10448	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10449	hdr->state1 = 0x00;
10450	hdr->state2 = 0xe0;
10451	scsi_ulto3b(0, hdr->lba);
10452	hdr->slots_num = 0;
10453	scsi_ulto2b(0, hdr->slots_length);
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
10462static void
10463ctl_ultomsf(uint32_t lba, uint8_t *buf)
10464{
10465
10466	lba += 150;
10467	buf[0] = 0;
10468	buf[1] = bin2bcd((lba / 75) / 60);
10469	buf[2] = bin2bcd((lba / 75) % 60);
10470	buf[3] = bin2bcd(lba % 75);
10471}
10472
10473int
10474ctl_read_toc(struct ctl_scsiio *ctsio)
10475{
10476	struct ctl_lun *lun = CTL_LUN(ctsio);
10477	struct scsi_read_toc_hdr *hdr;
10478	struct scsi_read_toc_type01_descr *descr;
10479	struct scsi_read_toc *cdb;
10480	uint32_t alloc_len, data_len;
10481	int format, msf;
10482
10483	cdb = (struct scsi_read_toc *)ctsio->cdb;
10484	msf = (cdb->byte2 & CD_MSF) != 0;
10485	format = cdb->format;
10486	alloc_len = scsi_2btoul(cdb->data_len);
10487
10488	data_len = sizeof(struct scsi_read_toc_hdr);
10489	if (format == 0)
10490		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10491	else
10492		data_len += sizeof(struct scsi_read_toc_type01_descr);
10493	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10494	ctsio->kern_sg_entries = 0;
10495	ctsio->kern_rel_offset = 0;
10496	ctsio->kern_data_len = min(data_len, alloc_len);
10497	ctsio->kern_total_len = ctsio->kern_data_len;
10498
10499	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10500	if (format == 0) {
10501		scsi_ulto2b(0x12, hdr->data_length);
10502		hdr->first = 1;
10503		hdr->last = 1;
10504		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10505		descr->addr_ctl = 0x14;
10506		descr->track_number = 1;
10507		if (msf)
10508			ctl_ultomsf(0, descr->track_start);
10509		else
10510			scsi_ulto4b(0, descr->track_start);
10511		descr++;
10512		descr->addr_ctl = 0x14;
10513		descr->track_number = 0xaa;
10514		if (msf)
10515			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10516		else
10517			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10518	} else {
10519		scsi_ulto2b(0x0a, hdr->data_length);
10520		hdr->first = 1;
10521		hdr->last = 1;
10522		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10523		descr->addr_ctl = 0x14;
10524		descr->track_number = 1;
10525		if (msf)
10526			ctl_ultomsf(0, descr->track_start);
10527		else
10528			scsi_ulto4b(0, descr->track_start);
10529	}
10530
10531	ctl_set_success(ctsio);
10532	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10533	ctsio->be_move_done = ctl_config_move_done;
10534	ctl_datamove((union ctl_io *)ctsio);
10535	return (CTL_RETVAL_COMPLETE);
10536}
10537
10538/*
10539 * For known CDB types, parse the LBA and length.
10540 */
10541static int
10542ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10543{
10544	if (io->io_hdr.io_type != CTL_IO_SCSI)
10545		return (1);
10546
10547	switch (io->scsiio.cdb[0]) {
10548	case COMPARE_AND_WRITE: {
10549		struct scsi_compare_and_write *cdb;
10550
10551		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10552
10553		*lba = scsi_8btou64(cdb->addr);
10554		*len = cdb->length;
10555		break;
10556	}
10557	case READ_6:
10558	case WRITE_6: {
10559		struct scsi_rw_6 *cdb;
10560
10561		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10562
10563		*lba = scsi_3btoul(cdb->addr);
10564		/* only 5 bits are valid in the most significant address byte */
10565		*lba &= 0x1fffff;
10566		*len = cdb->length;
10567		break;
10568	}
10569	case READ_10:
10570	case WRITE_10: {
10571		struct scsi_rw_10 *cdb;
10572
10573		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10574
10575		*lba = scsi_4btoul(cdb->addr);
10576		*len = scsi_2btoul(cdb->length);
10577		break;
10578	}
10579	case WRITE_VERIFY_10: {
10580		struct scsi_write_verify_10 *cdb;
10581
10582		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10583
10584		*lba = scsi_4btoul(cdb->addr);
10585		*len = scsi_2btoul(cdb->length);
10586		break;
10587	}
10588	case READ_12:
10589	case WRITE_12: {
10590		struct scsi_rw_12 *cdb;
10591
10592		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10593
10594		*lba = scsi_4btoul(cdb->addr);
10595		*len = scsi_4btoul(cdb->length);
10596		break;
10597	}
10598	case WRITE_VERIFY_12: {
10599		struct scsi_write_verify_12 *cdb;
10600
10601		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10602
10603		*lba = scsi_4btoul(cdb->addr);
10604		*len = scsi_4btoul(cdb->length);
10605		break;
10606	}
10607	case READ_16:
10608	case WRITE_16: {
10609		struct scsi_rw_16 *cdb;
10610
10611		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10612
10613		*lba = scsi_8btou64(cdb->addr);
10614		*len = scsi_4btoul(cdb->length);
10615		break;
10616	}
10617	case WRITE_ATOMIC_16: {
10618		struct scsi_write_atomic_16 *cdb;
10619
10620		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10621
10622		*lba = scsi_8btou64(cdb->addr);
10623		*len = scsi_2btoul(cdb->length);
10624		break;
10625	}
10626	case WRITE_VERIFY_16: {
10627		struct scsi_write_verify_16 *cdb;
10628
10629		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10630
10631		*lba = scsi_8btou64(cdb->addr);
10632		*len = scsi_4btoul(cdb->length);
10633		break;
10634	}
10635	case WRITE_SAME_10: {
10636		struct scsi_write_same_10 *cdb;
10637
10638		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10639
10640		*lba = scsi_4btoul(cdb->addr);
10641		*len = scsi_2btoul(cdb->length);
10642		break;
10643	}
10644	case WRITE_SAME_16: {
10645		struct scsi_write_same_16 *cdb;
10646
10647		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10648
10649		*lba = scsi_8btou64(cdb->addr);
10650		*len = scsi_4btoul(cdb->length);
10651		break;
10652	}
10653	case VERIFY_10: {
10654		struct scsi_verify_10 *cdb;
10655
10656		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10657
10658		*lba = scsi_4btoul(cdb->addr);
10659		*len = scsi_2btoul(cdb->length);
10660		break;
10661	}
10662	case VERIFY_12: {
10663		struct scsi_verify_12 *cdb;
10664
10665		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10666
10667		*lba = scsi_4btoul(cdb->addr);
10668		*len = scsi_4btoul(cdb->length);
10669		break;
10670	}
10671	case VERIFY_16: {
10672		struct scsi_verify_16 *cdb;
10673
10674		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10675
10676		*lba = scsi_8btou64(cdb->addr);
10677		*len = scsi_4btoul(cdb->length);
10678		break;
10679	}
10680	case UNMAP: {
10681		*lba = 0;
10682		*len = UINT64_MAX;
10683		break;
10684	}
10685	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10686		struct scsi_get_lba_status *cdb;
10687
10688		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10689		*lba = scsi_8btou64(cdb->addr);
10690		*len = UINT32_MAX;
10691		break;
10692	}
10693	default:
10694		return (1);
10695		break; /* NOTREACHED */
10696	}
10697
10698	return (0);
10699}
10700
10701static ctl_action
10702ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10703    bool seq)
10704{
10705	uint64_t endlba1, endlba2;
10706
10707	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10708	endlba2 = lba2 + len2 - 1;
10709
10710	if ((endlba1 < lba2) || (endlba2 < lba1))
10711		return (CTL_ACTION_PASS);
10712	else
10713		return (CTL_ACTION_BLOCK);
10714}
10715
10716static int
10717ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10718{
10719	struct ctl_ptr_len_flags *ptrlen;
10720	struct scsi_unmap_desc *buf, *end, *range;
10721	uint64_t lba;
10722	uint32_t len;
10723
10724	/* If not UNMAP -- go other way. */
10725	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10726	    io->scsiio.cdb[0] != UNMAP)
10727		return (CTL_ACTION_ERROR);
10728
10729	/* If UNMAP without data -- block and wait for data. */
10730	ptrlen = (struct ctl_ptr_len_flags *)
10731	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10732	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10733	    ptrlen->ptr == NULL)
10734		return (CTL_ACTION_BLOCK);
10735
10736	/* UNMAP with data -- check for collision. */
10737	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10738	end = buf + ptrlen->len / sizeof(*buf);
10739	for (range = buf; range < end; range++) {
10740		lba = scsi_8btou64(range->lba);
10741		len = scsi_4btoul(range->length);
10742		if ((lba < lba2 + len2) && (lba + len > lba2))
10743			return (CTL_ACTION_BLOCK);
10744	}
10745	return (CTL_ACTION_PASS);
10746}
10747
10748static ctl_action
10749ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10750{
10751	uint64_t lba1, lba2;
10752	uint64_t len1, len2;
10753	int retval;
10754
10755	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10756		return (CTL_ACTION_ERROR);
10757
10758	retval = ctl_extent_check_unmap(io1, lba2, len2);
10759	if (retval != CTL_ACTION_ERROR)
10760		return (retval);
10761
10762	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10763		return (CTL_ACTION_ERROR);
10764
10765	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10766		seq = FALSE;
10767	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10768}
10769
10770static ctl_action
10771ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10772{
10773	uint64_t lba1, lba2;
10774	uint64_t len1, len2;
10775
10776	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10777		return (CTL_ACTION_PASS);
10778	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10779		return (CTL_ACTION_ERROR);
10780	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10781		return (CTL_ACTION_ERROR);
10782
10783	if (lba1 + len1 == lba2)
10784		return (CTL_ACTION_BLOCK);
10785	return (CTL_ACTION_PASS);
10786}
10787
10788static ctl_action
10789ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10790    union ctl_io *ooa_io)
10791{
10792	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10793	const ctl_serialize_action *serialize_row;
10794
10795	/*
10796	 * The initiator attempted multiple untagged commands at the same
10797	 * time.  Can't do that.
10798	 */
10799	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10800	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10801	 && ((pending_io->io_hdr.nexus.targ_port ==
10802	      ooa_io->io_hdr.nexus.targ_port)
10803	  && (pending_io->io_hdr.nexus.initid ==
10804	      ooa_io->io_hdr.nexus.initid))
10805	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10806	      CTL_FLAG_STATUS_SENT)) == 0))
10807		return (CTL_ACTION_OVERLAP);
10808
10809	/*
10810	 * The initiator attempted to send multiple tagged commands with
10811	 * the same ID.  (It's fine if different initiators have the same
10812	 * tag ID.)
10813	 *
10814	 * Even if all of those conditions are true, we don't kill the I/O
10815	 * if the command ahead of us has been aborted.  We won't end up
10816	 * sending it to the FETD, and it's perfectly legal to resend a
10817	 * command with the same tag number as long as the previous
10818	 * instance of this tag number has been aborted somehow.
10819	 */
10820	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10821	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10822	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10823	 && ((pending_io->io_hdr.nexus.targ_port ==
10824	      ooa_io->io_hdr.nexus.targ_port)
10825	  && (pending_io->io_hdr.nexus.initid ==
10826	      ooa_io->io_hdr.nexus.initid))
10827	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10828	      CTL_FLAG_STATUS_SENT)) == 0))
10829		return (CTL_ACTION_OVERLAP_TAG);
10830
10831	/*
10832	 * If we get a head of queue tag, SAM-3 says that we should
10833	 * immediately execute it.
10834	 *
10835	 * What happens if this command would normally block for some other
10836	 * reason?  e.g. a request sense with a head of queue tag
10837	 * immediately after a write.  Normally that would block, but this
10838	 * will result in its getting executed immediately...
10839	 *
10840	 * We currently return "pass" instead of "skip", so we'll end up
10841	 * going through the rest of the queue to check for overlapped tags.
10842	 *
10843	 * XXX KDM check for other types of blockage first??
10844	 */
10845	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10846		return (CTL_ACTION_PASS);
10847
10848	/*
10849	 * Ordered tags have to block until all items ahead of them
10850	 * have completed.  If we get called with an ordered tag, we always
10851	 * block, if something else is ahead of us in the queue.
10852	 */
10853	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10854		return (CTL_ACTION_BLOCK);
10855
10856	/*
10857	 * Simple tags get blocked until all head of queue and ordered tags
10858	 * ahead of them have completed.  I'm lumping untagged commands in
10859	 * with simple tags here.  XXX KDM is that the right thing to do?
10860	 */
10861	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10862	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10863	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10864	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10865		return (CTL_ACTION_BLOCK);
10866
10867	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10868	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
10869	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
10870	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
10871	     pending_io->scsiio.cdb[1], pending_io));
10872	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10873	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
10874		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
10875	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
10876	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
10877	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
10878	     ooa_io->scsiio.cdb[1], ooa_io));
10879
10880	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10881
10882	switch (serialize_row[pending_entry->seridx]) {
10883	case CTL_SER_BLOCK:
10884		return (CTL_ACTION_BLOCK);
10885	case CTL_SER_EXTENT:
10886		return (ctl_extent_check(ooa_io, pending_io,
10887		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10888	case CTL_SER_EXTENTOPT:
10889		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10890		    SCP_QUEUE_ALG_UNRESTRICTED)
10891			return (ctl_extent_check(ooa_io, pending_io,
10892			    (lun->be_lun &&
10893			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10894		return (CTL_ACTION_PASS);
10895	case CTL_SER_EXTENTSEQ:
10896		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10897			return (ctl_extent_check_seq(ooa_io, pending_io));
10898		return (CTL_ACTION_PASS);
10899	case CTL_SER_PASS:
10900		return (CTL_ACTION_PASS);
10901	case CTL_SER_BLOCKOPT:
10902		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10903		    SCP_QUEUE_ALG_UNRESTRICTED)
10904			return (CTL_ACTION_BLOCK);
10905		return (CTL_ACTION_PASS);
10906	case CTL_SER_SKIP:
10907		return (CTL_ACTION_SKIP);
10908	default:
10909		panic("%s: Invalid serialization value %d for %d => %d",
10910		    __func__, serialize_row[pending_entry->seridx],
10911		    pending_entry->seridx, ooa_entry->seridx);
10912	}
10913
10914	return (CTL_ACTION_ERROR);
10915}
10916
10917/*
10918 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10919 * Assumptions:
10920 * - pending_io is generally either incoming, or on the blocked queue
10921 * - starting I/O is the I/O we want to start the check with.
10922 */
10923static ctl_action
10924ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10925	      union ctl_io *starting_io)
10926{
10927	union ctl_io *ooa_io;
10928	ctl_action action;
10929
10930	mtx_assert(&lun->lun_lock, MA_OWNED);
10931
10932	/*
10933	 * Run back along the OOA queue, starting with the current
10934	 * blocked I/O and going through every I/O before it on the
10935	 * queue.  If starting_io is NULL, we'll just end up returning
10936	 * CTL_ACTION_PASS.
10937	 */
10938	for (ooa_io = starting_io; ooa_io != NULL;
10939	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10940	     ooa_links)){
10941
10942		/*
10943		 * This routine just checks to see whether
10944		 * cur_blocked is blocked by ooa_io, which is ahead
10945		 * of it in the queue.  It doesn't queue/dequeue
10946		 * cur_blocked.
10947		 */
10948		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10949		switch (action) {
10950		case CTL_ACTION_BLOCK:
10951		case CTL_ACTION_OVERLAP:
10952		case CTL_ACTION_OVERLAP_TAG:
10953		case CTL_ACTION_SKIP:
10954		case CTL_ACTION_ERROR:
10955			return (action);
10956			break; /* NOTREACHED */
10957		case CTL_ACTION_PASS:
10958			break;
10959		default:
10960			panic("%s: Invalid action %d\n", __func__, action);
10961		}
10962	}
10963
10964	return (CTL_ACTION_PASS);
10965}
10966
10967/*
10968 * Assumptions:
10969 * - An I/O has just completed, and has been removed from the per-LUN OOA
10970 *   queue, so some items on the blocked queue may now be unblocked.
10971 */
10972static int
10973ctl_check_blocked(struct ctl_lun *lun)
10974{
10975	struct ctl_softc *softc = lun->ctl_softc;
10976	union ctl_io *cur_blocked, *next_blocked;
10977
10978	mtx_assert(&lun->lun_lock, MA_OWNED);
10979
10980	/*
10981	 * Run forward from the head of the blocked queue, checking each
10982	 * entry against the I/Os prior to it on the OOA queue to see if
10983	 * there is still any blockage.
10984	 *
10985	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10986	 * with our removing a variable on it while it is traversing the
10987	 * list.
10988	 */
10989	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10990	     cur_blocked != NULL; cur_blocked = next_blocked) {
10991		union ctl_io *prev_ooa;
10992		ctl_action action;
10993
10994		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10995							  blocked_links);
10996
10997		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10998						      ctl_ooaq, ooa_links);
10999
11000		/*
11001		 * If cur_blocked happens to be the first item in the OOA
11002		 * queue now, prev_ooa will be NULL, and the action
11003		 * returned will just be CTL_ACTION_PASS.
11004		 */
11005		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11006
11007		switch (action) {
11008		case CTL_ACTION_BLOCK:
11009			/* Nothing to do here, still blocked */
11010			break;
11011		case CTL_ACTION_OVERLAP:
11012		case CTL_ACTION_OVERLAP_TAG:
11013			/*
11014			 * This shouldn't happen!  In theory we've already
11015			 * checked this command for overlap...
11016			 */
11017			break;
11018		case CTL_ACTION_PASS:
11019		case CTL_ACTION_SKIP: {
11020			const struct ctl_cmd_entry *entry;
11021
11022			/*
11023			 * The skip case shouldn't happen, this transaction
11024			 * should have never made it onto the blocked queue.
11025			 */
11026			/*
11027			 * This I/O is no longer blocked, we can remove it
11028			 * from the blocked queue.  Since this is a TAILQ
11029			 * (doubly linked list), we can do O(1) removals
11030			 * from any place on the list.
11031			 */
11032			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11033				     blocked_links);
11034			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11035
11036			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11037			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11038				/*
11039				 * Need to send IO back to original side to
11040				 * run
11041				 */
11042				union ctl_ha_msg msg_info;
11043
11044				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11045				msg_info.hdr.original_sc =
11046					cur_blocked->io_hdr.remote_io;
11047				msg_info.hdr.serializing_sc = cur_blocked;
11048				msg_info.hdr.msg_type = CTL_MSG_R2R;
11049				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11050				    sizeof(msg_info.hdr), M_NOWAIT);
11051				break;
11052			}
11053			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11054
11055			/*
11056			 * Check this I/O for LUN state changes that may
11057			 * have happened while this command was blocked.
11058			 * The LUN state may have been changed by a command
11059			 * ahead of us in the queue, so we need to re-check
11060			 * for any states that can be caused by SCSI
11061			 * commands.
11062			 */
11063			if (ctl_scsiio_lun_check(lun, entry,
11064						 &cur_blocked->scsiio) == 0) {
11065				cur_blocked->io_hdr.flags |=
11066				                      CTL_FLAG_IS_WAS_ON_RTR;
11067				ctl_enqueue_rtr(cur_blocked);
11068			} else
11069				ctl_done(cur_blocked);
11070			break;
11071		}
11072		default:
11073			/*
11074			 * This probably shouldn't happen -- we shouldn't
11075			 * get CTL_ACTION_ERROR, or anything else.
11076			 */
11077			break;
11078		}
11079	}
11080
11081	return (CTL_RETVAL_COMPLETE);
11082}
11083
11084/*
11085 * This routine (with one exception) checks LUN flags that can be set by
11086 * commands ahead of us in the OOA queue.  These flags have to be checked
11087 * when a command initially comes in, and when we pull a command off the
11088 * blocked queue and are preparing to execute it.  The reason we have to
11089 * check these flags for commands on the blocked queue is that the LUN
11090 * state may have been changed by a command ahead of us while we're on the
11091 * blocked queue.
11092 *
11093 * Ordering is somewhat important with these checks, so please pay
11094 * careful attention to the placement of any new checks.
11095 */
11096static int
11097ctl_scsiio_lun_check(struct ctl_lun *lun,
11098    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11099{
11100	struct ctl_softc *softc = lun->ctl_softc;
11101	int retval;
11102	uint32_t residx;
11103
11104	retval = 0;
11105
11106	mtx_assert(&lun->lun_lock, MA_OWNED);
11107
11108	/*
11109	 * If this shelf is a secondary shelf controller, we may have to
11110	 * reject some commands disallowed by HA mode and link state.
11111	 */
11112	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11113		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11114		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11115			ctl_set_lun_unavail(ctsio);
11116			retval = 1;
11117			goto bailout;
11118		}
11119		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11120		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11121			ctl_set_lun_transit(ctsio);
11122			retval = 1;
11123			goto bailout;
11124		}
11125		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11126		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11127			ctl_set_lun_standby(ctsio);
11128			retval = 1;
11129			goto bailout;
11130		}
11131
11132		/* The rest of checks are only done on executing side */
11133		if (softc->ha_mode == CTL_HA_MODE_XFER)
11134			goto bailout;
11135	}
11136
11137	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11138		if (lun->be_lun &&
11139		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11140			ctl_set_hw_write_protected(ctsio);
11141			retval = 1;
11142			goto bailout;
11143		}
11144		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11145			ctl_set_sense(ctsio, /*current_error*/ 1,
11146			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11147			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11148			retval = 1;
11149			goto bailout;
11150		}
11151	}
11152
11153	/*
11154	 * Check for a reservation conflict.  If this command isn't allowed
11155	 * even on reserved LUNs, and if this initiator isn't the one who
11156	 * reserved us, reject the command with a reservation conflict.
11157	 */
11158	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11159	if ((lun->flags & CTL_LUN_RESERVED)
11160	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11161		if (lun->res_idx != residx) {
11162			ctl_set_reservation_conflict(ctsio);
11163			retval = 1;
11164			goto bailout;
11165		}
11166	}
11167
11168	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11169	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11170		/* No reservation or command is allowed. */;
11171	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11172	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11173	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11174	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11175		/* The command is allowed for Write Exclusive resv. */;
11176	} else {
11177		/*
11178		 * if we aren't registered or it's a res holder type
11179		 * reservation and this isn't the res holder then set a
11180		 * conflict.
11181		 */
11182		if (ctl_get_prkey(lun, residx) == 0 ||
11183		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11184			ctl_set_reservation_conflict(ctsio);
11185			retval = 1;
11186			goto bailout;
11187		}
11188	}
11189
11190	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11191		if (lun->flags & CTL_LUN_EJECTED)
11192			ctl_set_lun_ejected(ctsio);
11193		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11194			if (lun->flags & CTL_LUN_REMOVABLE)
11195				ctl_set_lun_no_media(ctsio);
11196			else
11197				ctl_set_lun_int_reqd(ctsio);
11198		} else if (lun->flags & CTL_LUN_STOPPED)
11199			ctl_set_lun_stopped(ctsio);
11200		else
11201			goto bailout;
11202		retval = 1;
11203		goto bailout;
11204	}
11205
11206bailout:
11207	return (retval);
11208}
11209
11210static void
11211ctl_failover_io(union ctl_io *io, int have_lock)
11212{
11213	ctl_set_busy(&io->scsiio);
11214	ctl_done(io);
11215}
11216
11217static void
11218ctl_failover_lun(union ctl_io *rio)
11219{
11220	struct ctl_softc *softc = CTL_SOFTC(rio);
11221	struct ctl_lun *lun;
11222	struct ctl_io_hdr *io, *next_io;
11223	uint32_t targ_lun;
11224
11225	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11226	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11227
11228	/* Find and lock the LUN. */
11229	mtx_lock(&softc->ctl_lock);
11230	if (targ_lun > ctl_max_luns ||
11231	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11232		mtx_unlock(&softc->ctl_lock);
11233		return;
11234	}
11235	mtx_lock(&lun->lun_lock);
11236	mtx_unlock(&softc->ctl_lock);
11237	if (lun->flags & CTL_LUN_DISABLED) {
11238		mtx_unlock(&lun->lun_lock);
11239		return;
11240	}
11241
11242	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11243		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11244			/* We are master */
11245			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11246				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11247					io->flags |= CTL_FLAG_ABORT;
11248					io->flags |= CTL_FLAG_FAILOVER;
11249				} else { /* This can be only due to DATAMOVE */
11250					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11251					io->flags &= ~CTL_FLAG_DMA_INPROG;
11252					io->flags |= CTL_FLAG_IO_ACTIVE;
11253					io->port_status = 31340;
11254					ctl_enqueue_isc((union ctl_io *)io);
11255				}
11256			}
11257			/* We are slave */
11258			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11259				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11260				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11261					io->flags |= CTL_FLAG_FAILOVER;
11262				} else {
11263					ctl_set_busy(&((union ctl_io *)io)->
11264					    scsiio);
11265					ctl_done((union ctl_io *)io);
11266				}
11267			}
11268		}
11269	} else { /* SERIALIZE modes */
11270		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11271		    next_io) {
11272			/* We are master */
11273			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11274				TAILQ_REMOVE(&lun->blocked_queue, io,
11275				    blocked_links);
11276				io->flags &= ~CTL_FLAG_BLOCKED;
11277				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11278				ctl_free_io((union ctl_io *)io);
11279			}
11280		}
11281		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11282			/* We are master */
11283			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11284				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11285				ctl_free_io((union ctl_io *)io);
11286			}
11287			/* We are slave */
11288			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11289				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11290				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11291					ctl_set_busy(&((union ctl_io *)io)->
11292					    scsiio);
11293					ctl_done((union ctl_io *)io);
11294				}
11295			}
11296		}
11297		ctl_check_blocked(lun);
11298	}
11299	mtx_unlock(&lun->lun_lock);
11300}
11301
11302static int
11303ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11304{
11305	struct ctl_lun *lun;
11306	const struct ctl_cmd_entry *entry;
11307	uint32_t initidx, targ_lun;
11308	int retval = 0;
11309
11310	lun = NULL;
11311	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11312	if (targ_lun < ctl_max_luns)
11313		lun = softc->ctl_luns[targ_lun];
11314	if (lun) {
11315		/*
11316		 * If the LUN is invalid, pretend that it doesn't exist.
11317		 * It will go away as soon as all pending I/O has been
11318		 * completed.
11319		 */
11320		mtx_lock(&lun->lun_lock);
11321		if (lun->flags & CTL_LUN_DISABLED) {
11322			mtx_unlock(&lun->lun_lock);
11323			lun = NULL;
11324		}
11325	}
11326	CTL_LUN(ctsio) = lun;
11327	if (lun) {
11328		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11329
11330		/*
11331		 * Every I/O goes into the OOA queue for a particular LUN,
11332		 * and stays there until completion.
11333		 */
11334#ifdef CTL_TIME_IO
11335		if (TAILQ_EMPTY(&lun->ooa_queue))
11336			lun->idle_time += getsbinuptime() - lun->last_busy;
11337#endif
11338		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11339	}
11340
11341	/* Get command entry and return error if it is unsuppotyed. */
11342	entry = ctl_validate_command(ctsio);
11343	if (entry == NULL) {
11344		if (lun)
11345			mtx_unlock(&lun->lun_lock);
11346		return (retval);
11347	}
11348
11349	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11350	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11351
11352	/*
11353	 * Check to see whether we can send this command to LUNs that don't
11354	 * exist.  This should pretty much only be the case for inquiry
11355	 * and request sense.  Further checks, below, really require having
11356	 * a LUN, so we can't really check the command anymore.  Just put
11357	 * it on the rtr queue.
11358	 */
11359	if (lun == NULL) {
11360		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11361			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11362			ctl_enqueue_rtr((union ctl_io *)ctsio);
11363			return (retval);
11364		}
11365
11366		ctl_set_unsupported_lun(ctsio);
11367		ctl_done((union ctl_io *)ctsio);
11368		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11369		return (retval);
11370	} else {
11371		/*
11372		 * Make sure we support this particular command on this LUN.
11373		 * e.g., we don't support writes to the control LUN.
11374		 */
11375		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11376			mtx_unlock(&lun->lun_lock);
11377			ctl_set_invalid_opcode(ctsio);
11378			ctl_done((union ctl_io *)ctsio);
11379			return (retval);
11380		}
11381	}
11382
11383	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11384
11385	/*
11386	 * If we've got a request sense, it'll clear the contingent
11387	 * allegiance condition.  Otherwise, if we have a CA condition for
11388	 * this initiator, clear it, because it sent down a command other
11389	 * than request sense.
11390	 */
11391	if (ctsio->cdb[0] != REQUEST_SENSE) {
11392		struct scsi_sense_data *ps;
11393
11394		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11395		if (ps != NULL)
11396			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11397	}
11398
11399	/*
11400	 * If the command has this flag set, it handles its own unit
11401	 * attention reporting, we shouldn't do anything.  Otherwise we
11402	 * check for any pending unit attentions, and send them back to the
11403	 * initiator.  We only do this when a command initially comes in,
11404	 * not when we pull it off the blocked queue.
11405	 *
11406	 * According to SAM-3, section 5.3.2, the order that things get
11407	 * presented back to the host is basically unit attentions caused
11408	 * by some sort of reset event, busy status, reservation conflicts
11409	 * or task set full, and finally any other status.
11410	 *
11411	 * One issue here is that some of the unit attentions we report
11412	 * don't fall into the "reset" category (e.g. "reported luns data
11413	 * has changed").  So reporting it here, before the reservation
11414	 * check, may be technically wrong.  I guess the only thing to do
11415	 * would be to check for and report the reset events here, and then
11416	 * check for the other unit attention types after we check for a
11417	 * reservation conflict.
11418	 *
11419	 * XXX KDM need to fix this
11420	 */
11421	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11422		ctl_ua_type ua_type;
11423		u_int sense_len = 0;
11424
11425		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11426		    &sense_len, SSD_TYPE_NONE);
11427		if (ua_type != CTL_UA_NONE) {
11428			mtx_unlock(&lun->lun_lock);
11429			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11430			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11431			ctsio->sense_len = sense_len;
11432			ctl_done((union ctl_io *)ctsio);
11433			return (retval);
11434		}
11435	}
11436
11437
11438	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11439		mtx_unlock(&lun->lun_lock);
11440		ctl_done((union ctl_io *)ctsio);
11441		return (retval);
11442	}
11443
11444	/*
11445	 * XXX CHD this is where we want to send IO to other side if
11446	 * this LUN is secondary on this SC. We will need to make a copy
11447	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11448	 * the copy we send as FROM_OTHER.
11449	 * We also need to stuff the address of the original IO so we can
11450	 * find it easily. Something similar will need be done on the other
11451	 * side so when we are done we can find the copy.
11452	 */
11453	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11454	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11455	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11456		union ctl_ha_msg msg_info;
11457		int isc_retval;
11458
11459		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11460		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11461		mtx_unlock(&lun->lun_lock);
11462
11463		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11464		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11465		msg_info.hdr.serializing_sc = NULL;
11466		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11467		msg_info.scsi.tag_num = ctsio->tag_num;
11468		msg_info.scsi.tag_type = ctsio->tag_type;
11469		msg_info.scsi.cdb_len = ctsio->cdb_len;
11470		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11471
11472		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11473		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11474		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11475			ctl_set_busy(ctsio);
11476			ctl_done((union ctl_io *)ctsio);
11477			return (retval);
11478		}
11479		return (retval);
11480	}
11481
11482	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11483			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11484			      ctl_ooaq, ooa_links))) {
11485	case CTL_ACTION_BLOCK:
11486		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11487		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11488				  blocked_links);
11489		mtx_unlock(&lun->lun_lock);
11490		return (retval);
11491	case CTL_ACTION_PASS:
11492	case CTL_ACTION_SKIP:
11493		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11494		mtx_unlock(&lun->lun_lock);
11495		ctl_enqueue_rtr((union ctl_io *)ctsio);
11496		break;
11497	case CTL_ACTION_OVERLAP:
11498		mtx_unlock(&lun->lun_lock);
11499		ctl_set_overlapped_cmd(ctsio);
11500		ctl_done((union ctl_io *)ctsio);
11501		break;
11502	case CTL_ACTION_OVERLAP_TAG:
11503		mtx_unlock(&lun->lun_lock);
11504		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11505		ctl_done((union ctl_io *)ctsio);
11506		break;
11507	case CTL_ACTION_ERROR:
11508	default:
11509		mtx_unlock(&lun->lun_lock);
11510		ctl_set_internal_failure(ctsio,
11511					 /*sks_valid*/ 0,
11512					 /*retry_count*/ 0);
11513		ctl_done((union ctl_io *)ctsio);
11514		break;
11515	}
11516	return (retval);
11517}
11518
11519const struct ctl_cmd_entry *
11520ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11521{
11522	const struct ctl_cmd_entry *entry;
11523	int service_action;
11524
11525	entry = &ctl_cmd_table[ctsio->cdb[0]];
11526	if (sa)
11527		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11528	if (entry->flags & CTL_CMD_FLAG_SA5) {
11529		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11530		entry = &((const struct ctl_cmd_entry *)
11531		    entry->execute)[service_action];
11532	}
11533	return (entry);
11534}
11535
11536const struct ctl_cmd_entry *
11537ctl_validate_command(struct ctl_scsiio *ctsio)
11538{
11539	const struct ctl_cmd_entry *entry;
11540	int i, sa;
11541	uint8_t diff;
11542
11543	entry = ctl_get_cmd_entry(ctsio, &sa);
11544	if (entry->execute == NULL) {
11545		if (sa)
11546			ctl_set_invalid_field(ctsio,
11547					      /*sks_valid*/ 1,
11548					      /*command*/ 1,
11549					      /*field*/ 1,
11550					      /*bit_valid*/ 1,
11551					      /*bit*/ 4);
11552		else
11553			ctl_set_invalid_opcode(ctsio);
11554		ctl_done((union ctl_io *)ctsio);
11555		return (NULL);
11556	}
11557	KASSERT(entry->length > 0,
11558	    ("Not defined length for command 0x%02x/0x%02x",
11559	     ctsio->cdb[0], ctsio->cdb[1]));
11560	for (i = 1; i < entry->length; i++) {
11561		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11562		if (diff == 0)
11563			continue;
11564		ctl_set_invalid_field(ctsio,
11565				      /*sks_valid*/ 1,
11566				      /*command*/ 1,
11567				      /*field*/ i,
11568				      /*bit_valid*/ 1,
11569				      /*bit*/ fls(diff) - 1);
11570		ctl_done((union ctl_io *)ctsio);
11571		return (NULL);
11572	}
11573	return (entry);
11574}
11575
11576static int
11577ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11578{
11579
11580	switch (lun_type) {
11581	case T_DIRECT:
11582		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11583			return (0);
11584		break;
11585	case T_PROCESSOR:
11586		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11587			return (0);
11588		break;
11589	case T_CDROM:
11590		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11591			return (0);
11592		break;
11593	default:
11594		return (0);
11595	}
11596	return (1);
11597}
11598
11599static int
11600ctl_scsiio(struct ctl_scsiio *ctsio)
11601{
11602	int retval;
11603	const struct ctl_cmd_entry *entry;
11604
11605	retval = CTL_RETVAL_COMPLETE;
11606
11607	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11608
11609	entry = ctl_get_cmd_entry(ctsio, NULL);
11610
11611	/*
11612	 * If this I/O has been aborted, just send it straight to
11613	 * ctl_done() without executing it.
11614	 */
11615	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11616		ctl_done((union ctl_io *)ctsio);
11617		goto bailout;
11618	}
11619
11620	/*
11621	 * All the checks should have been handled by ctl_scsiio_precheck().
11622	 * We should be clear now to just execute the I/O.
11623	 */
11624	retval = entry->execute(ctsio);
11625
11626bailout:
11627	return (retval);
11628}
11629
11630static int
11631ctl_target_reset(union ctl_io *io)
11632{
11633	struct ctl_softc *softc = CTL_SOFTC(io);
11634	struct ctl_port *port = CTL_PORT(io);
11635	struct ctl_lun *lun;
11636	uint32_t initidx;
11637	ctl_ua_type ua_type;
11638
11639	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11640		union ctl_ha_msg msg_info;
11641
11642		msg_info.hdr.nexus = io->io_hdr.nexus;
11643		msg_info.task.task_action = io->taskio.task_action;
11644		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11645		msg_info.hdr.original_sc = NULL;
11646		msg_info.hdr.serializing_sc = NULL;
11647		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11648		    sizeof(msg_info.task), M_WAITOK);
11649	}
11650
11651	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11652	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11653		ua_type = CTL_UA_TARG_RESET;
11654	else
11655		ua_type = CTL_UA_BUS_RESET;
11656	mtx_lock(&softc->ctl_lock);
11657	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11658		if (port != NULL &&
11659		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11660			continue;
11661		ctl_do_lun_reset(lun, initidx, ua_type);
11662	}
11663	mtx_unlock(&softc->ctl_lock);
11664	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11665	return (0);
11666}
11667
11668/*
11669 * The LUN should always be set.  The I/O is optional, and is used to
11670 * distinguish between I/Os sent by this initiator, and by other
11671 * initiators.  We set unit attention for initiators other than this one.
11672 * SAM-3 is vague on this point.  It does say that a unit attention should
11673 * be established for other initiators when a LUN is reset (see section
11674 * 5.7.3), but it doesn't specifically say that the unit attention should
11675 * be established for this particular initiator when a LUN is reset.  Here
11676 * is the relevant text, from SAM-3 rev 8:
11677 *
11678 * 5.7.2 When a SCSI initiator port aborts its own tasks
11679 *
11680 * When a SCSI initiator port causes its own task(s) to be aborted, no
11681 * notification that the task(s) have been aborted shall be returned to
11682 * the SCSI initiator port other than the completion response for the
11683 * command or task management function action that caused the task(s) to
11684 * be aborted and notification(s) associated with related effects of the
11685 * action (e.g., a reset unit attention condition).
11686 *
11687 * XXX KDM for now, we're setting unit attention for all initiators.
11688 */
11689static void
11690ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11691{
11692	union ctl_io *xio;
11693	int i;
11694
11695	mtx_lock(&lun->lun_lock);
11696	/* Abort tasks. */
11697	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11698	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11699		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11700	}
11701	/* Clear CA. */
11702	for (i = 0; i < ctl_max_ports; i++) {
11703		free(lun->pending_sense[i], M_CTL);
11704		lun->pending_sense[i] = NULL;
11705	}
11706	/* Clear reservation. */
11707	lun->flags &= ~CTL_LUN_RESERVED;
11708	/* Clear prevent media removal. */
11709	if (lun->prevent) {
11710		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11711			ctl_clear_mask(lun->prevent, i);
11712		lun->prevent_count = 0;
11713	}
11714	/* Clear TPC status */
11715	ctl_tpc_lun_clear(lun, -1);
11716	/* Establish UA. */
11717#if 0
11718	ctl_est_ua_all(lun, initidx, ua_type);
11719#else
11720	ctl_est_ua_all(lun, -1, ua_type);
11721#endif
11722	mtx_unlock(&lun->lun_lock);
11723}
11724
11725static int
11726ctl_lun_reset(union ctl_io *io)
11727{
11728	struct ctl_softc *softc = CTL_SOFTC(io);
11729	struct ctl_lun *lun;
11730	uint32_t targ_lun, initidx;
11731
11732	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11733	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11734	mtx_lock(&softc->ctl_lock);
11735	if (targ_lun >= ctl_max_luns ||
11736	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11737		mtx_unlock(&softc->ctl_lock);
11738		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11739		return (1);
11740	}
11741	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11742	mtx_unlock(&softc->ctl_lock);
11743	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11744
11745	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11746		union ctl_ha_msg msg_info;
11747
11748		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11749		msg_info.hdr.nexus = io->io_hdr.nexus;
11750		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11751		msg_info.hdr.original_sc = NULL;
11752		msg_info.hdr.serializing_sc = NULL;
11753		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11754		    sizeof(msg_info.task), M_WAITOK);
11755	}
11756	return (0);
11757}
11758
11759static void
11760ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11761    int other_sc)
11762{
11763	union ctl_io *xio;
11764
11765	mtx_assert(&lun->lun_lock, MA_OWNED);
11766
11767	/*
11768	 * Run through the OOA queue and attempt to find the given I/O.
11769	 * The target port, initiator ID, tag type and tag number have to
11770	 * match the values that we got from the initiator.  If we have an
11771	 * untagged command to abort, simply abort the first untagged command
11772	 * we come to.  We only allow one untagged command at a time of course.
11773	 */
11774	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11775	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11776
11777		if ((targ_port == UINT32_MAX ||
11778		     targ_port == xio->io_hdr.nexus.targ_port) &&
11779		    (init_id == UINT32_MAX ||
11780		     init_id == xio->io_hdr.nexus.initid)) {
11781			if (targ_port != xio->io_hdr.nexus.targ_port ||
11782			    init_id != xio->io_hdr.nexus.initid)
11783				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11784			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11785			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11786				union ctl_ha_msg msg_info;
11787
11788				msg_info.hdr.nexus = xio->io_hdr.nexus;
11789				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11790				msg_info.task.tag_num = xio->scsiio.tag_num;
11791				msg_info.task.tag_type = xio->scsiio.tag_type;
11792				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11793				msg_info.hdr.original_sc = NULL;
11794				msg_info.hdr.serializing_sc = NULL;
11795				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11796				    sizeof(msg_info.task), M_NOWAIT);
11797			}
11798		}
11799	}
11800}
11801
11802static int
11803ctl_abort_task_set(union ctl_io *io)
11804{
11805	struct ctl_softc *softc = CTL_SOFTC(io);
11806	struct ctl_lun *lun;
11807	uint32_t targ_lun;
11808
11809	/*
11810	 * Look up the LUN.
11811	 */
11812	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11813	mtx_lock(&softc->ctl_lock);
11814	if (targ_lun >= ctl_max_luns ||
11815	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11816		mtx_unlock(&softc->ctl_lock);
11817		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11818		return (1);
11819	}
11820
11821	mtx_lock(&lun->lun_lock);
11822	mtx_unlock(&softc->ctl_lock);
11823	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11824		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11825		    io->io_hdr.nexus.initid,
11826		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11827	} else { /* CTL_TASK_CLEAR_TASK_SET */
11828		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11829		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11830	}
11831	mtx_unlock(&lun->lun_lock);
11832	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11833	return (0);
11834}
11835
11836static void
11837ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11838    ctl_ua_type ua_type)
11839{
11840	struct ctl_lun *lun;
11841	struct scsi_sense_data *ps;
11842	uint32_t p, i;
11843
11844	p = initidx / CTL_MAX_INIT_PER_PORT;
11845	i = initidx % CTL_MAX_INIT_PER_PORT;
11846	mtx_lock(&softc->ctl_lock);
11847	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11848		mtx_lock(&lun->lun_lock);
11849		/* Abort tasks. */
11850		ctl_abort_tasks_lun(lun, p, i, 1);
11851		/* Clear CA. */
11852		ps = lun->pending_sense[p];
11853		if (ps != NULL)
11854			ps[i].error_code = 0;
11855		/* Clear reservation. */
11856		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11857			lun->flags &= ~CTL_LUN_RESERVED;
11858		/* Clear prevent media removal. */
11859		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11860			ctl_clear_mask(lun->prevent, initidx);
11861			lun->prevent_count--;
11862		}
11863		/* Clear TPC status */
11864		ctl_tpc_lun_clear(lun, initidx);
11865		/* Establish UA. */
11866		ctl_est_ua(lun, initidx, ua_type);
11867		mtx_unlock(&lun->lun_lock);
11868	}
11869	mtx_unlock(&softc->ctl_lock);
11870}
11871
11872static int
11873ctl_i_t_nexus_reset(union ctl_io *io)
11874{
11875	struct ctl_softc *softc = CTL_SOFTC(io);
11876	uint32_t initidx;
11877
11878	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11879		union ctl_ha_msg msg_info;
11880
11881		msg_info.hdr.nexus = io->io_hdr.nexus;
11882		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11883		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11884		msg_info.hdr.original_sc = NULL;
11885		msg_info.hdr.serializing_sc = NULL;
11886		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11887		    sizeof(msg_info.task), M_WAITOK);
11888	}
11889
11890	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11891	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
11892	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11893	return (0);
11894}
11895
11896static int
11897ctl_abort_task(union ctl_io *io)
11898{
11899	struct ctl_softc *softc = CTL_SOFTC(io);
11900	union ctl_io *xio;
11901	struct ctl_lun *lun;
11902	uint32_t targ_lun;
11903
11904	/*
11905	 * Look up the LUN.
11906	 */
11907	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11908	mtx_lock(&softc->ctl_lock);
11909	if (targ_lun >= ctl_max_luns ||
11910	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11911		mtx_unlock(&softc->ctl_lock);
11912		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11913		return (1);
11914	}
11915
11916	mtx_lock(&lun->lun_lock);
11917	mtx_unlock(&softc->ctl_lock);
11918	/*
11919	 * Run through the OOA queue and attempt to find the given I/O.
11920	 * The target port, initiator ID, tag type and tag number have to
11921	 * match the values that we got from the initiator.  If we have an
11922	 * untagged command to abort, simply abort the first untagged command
11923	 * we come to.  We only allow one untagged command at a time of course.
11924	 */
11925	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11926	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11927
11928		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11929		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11930		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11931			continue;
11932
11933		/*
11934		 * If the abort says that the task is untagged, the
11935		 * task in the queue must be untagged.  Otherwise,
11936		 * we just check to see whether the tag numbers
11937		 * match.  This is because the QLogic firmware
11938		 * doesn't pass back the tag type in an abort
11939		 * request.
11940		 */
11941#if 0
11942		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11943		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11944		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11945#else
11946		/*
11947		 * XXX KDM we've got problems with FC, because it
11948		 * doesn't send down a tag type with aborts.  So we
11949		 * can only really go by the tag number...
11950		 * This may cause problems with parallel SCSI.
11951		 * Need to figure that out!!
11952		 */
11953		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11954#endif
11955			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11956			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11957			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11958				union ctl_ha_msg msg_info;
11959
11960				msg_info.hdr.nexus = io->io_hdr.nexus;
11961				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11962				msg_info.task.tag_num = io->taskio.tag_num;
11963				msg_info.task.tag_type = io->taskio.tag_type;
11964				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11965				msg_info.hdr.original_sc = NULL;
11966				msg_info.hdr.serializing_sc = NULL;
11967				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11968				    sizeof(msg_info.task), M_NOWAIT);
11969			}
11970		}
11971	}
11972	mtx_unlock(&lun->lun_lock);
11973	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11974	return (0);
11975}
11976
11977static int
11978ctl_query_task(union ctl_io *io, int task_set)
11979{
11980	struct ctl_softc *softc = CTL_SOFTC(io);
11981	union ctl_io *xio;
11982	struct ctl_lun *lun;
11983	int found = 0;
11984	uint32_t targ_lun;
11985
11986	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11987	mtx_lock(&softc->ctl_lock);
11988	if (targ_lun >= ctl_max_luns ||
11989	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11990		mtx_unlock(&softc->ctl_lock);
11991		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11992		return (1);
11993	}
11994	mtx_lock(&lun->lun_lock);
11995	mtx_unlock(&softc->ctl_lock);
11996	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11997	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11998
11999		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12000		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12001		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12002			continue;
12003
12004		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12005			found = 1;
12006			break;
12007		}
12008	}
12009	mtx_unlock(&lun->lun_lock);
12010	if (found)
12011		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12012	else
12013		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12014	return (0);
12015}
12016
12017static int
12018ctl_query_async_event(union ctl_io *io)
12019{
12020	struct ctl_softc *softc = CTL_SOFTC(io);
12021	struct ctl_lun *lun;
12022	ctl_ua_type ua;
12023	uint32_t targ_lun, initidx;
12024
12025	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12026	mtx_lock(&softc->ctl_lock);
12027	if (targ_lun >= ctl_max_luns ||
12028	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12029		mtx_unlock(&softc->ctl_lock);
12030		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12031		return (1);
12032	}
12033	mtx_lock(&lun->lun_lock);
12034	mtx_unlock(&softc->ctl_lock);
12035	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12036	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12037	mtx_unlock(&lun->lun_lock);
12038	if (ua != CTL_UA_NONE)
12039		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12040	else
12041		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12042	return (0);
12043}
12044
12045static void
12046ctl_run_task(union ctl_io *io)
12047{
12048	int retval = 1;
12049
12050	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12051	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12052	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12053	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12054	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12055	switch (io->taskio.task_action) {
12056	case CTL_TASK_ABORT_TASK:
12057		retval = ctl_abort_task(io);
12058		break;
12059	case CTL_TASK_ABORT_TASK_SET:
12060	case CTL_TASK_CLEAR_TASK_SET:
12061		retval = ctl_abort_task_set(io);
12062		break;
12063	case CTL_TASK_CLEAR_ACA:
12064		break;
12065	case CTL_TASK_I_T_NEXUS_RESET:
12066		retval = ctl_i_t_nexus_reset(io);
12067		break;
12068	case CTL_TASK_LUN_RESET:
12069		retval = ctl_lun_reset(io);
12070		break;
12071	case CTL_TASK_TARGET_RESET:
12072	case CTL_TASK_BUS_RESET:
12073		retval = ctl_target_reset(io);
12074		break;
12075	case CTL_TASK_PORT_LOGIN:
12076		break;
12077	case CTL_TASK_PORT_LOGOUT:
12078		break;
12079	case CTL_TASK_QUERY_TASK:
12080		retval = ctl_query_task(io, 0);
12081		break;
12082	case CTL_TASK_QUERY_TASK_SET:
12083		retval = ctl_query_task(io, 1);
12084		break;
12085	case CTL_TASK_QUERY_ASYNC_EVENT:
12086		retval = ctl_query_async_event(io);
12087		break;
12088	default:
12089		printf("%s: got unknown task management event %d\n",
12090		       __func__, io->taskio.task_action);
12091		break;
12092	}
12093	if (retval == 0)
12094		io->io_hdr.status = CTL_SUCCESS;
12095	else
12096		io->io_hdr.status = CTL_ERROR;
12097	ctl_done(io);
12098}
12099
12100/*
12101 * For HA operation.  Handle commands that come in from the other
12102 * controller.
12103 */
12104static void
12105ctl_handle_isc(union ctl_io *io)
12106{
12107	struct ctl_softc *softc = CTL_SOFTC(io);
12108	struct ctl_lun *lun;
12109	const struct ctl_cmd_entry *entry;
12110	uint32_t targ_lun;
12111
12112	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12113	switch (io->io_hdr.msg_type) {
12114	case CTL_MSG_SERIALIZE:
12115		ctl_serialize_other_sc_cmd(&io->scsiio);
12116		break;
12117	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12118		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12119		if (targ_lun >= ctl_max_luns ||
12120		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12121			ctl_done(io);
12122			break;
12123		}
12124		mtx_lock(&lun->lun_lock);
12125		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12126			mtx_unlock(&lun->lun_lock);
12127			ctl_done(io);
12128			break;
12129		}
12130		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12131		mtx_unlock(&lun->lun_lock);
12132		ctl_enqueue_rtr(io);
12133		break;
12134	case CTL_MSG_FINISH_IO:
12135		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12136			ctl_done(io);
12137			break;
12138		}
12139		if (targ_lun >= ctl_max_luns ||
12140		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12141			ctl_free_io(io);
12142			break;
12143		}
12144		mtx_lock(&lun->lun_lock);
12145		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12146		ctl_check_blocked(lun);
12147		mtx_unlock(&lun->lun_lock);
12148		ctl_free_io(io);
12149		break;
12150	case CTL_MSG_PERS_ACTION:
12151		ctl_hndl_per_res_out_on_other_sc(io);
12152		ctl_free_io(io);
12153		break;
12154	case CTL_MSG_BAD_JUJU:
12155		ctl_done(io);
12156		break;
12157	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12158		ctl_datamove_remote(io);
12159		break;
12160	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12161		io->scsiio.be_move_done(io);
12162		break;
12163	case CTL_MSG_FAILOVER:
12164		ctl_failover_lun(io);
12165		ctl_free_io(io);
12166		break;
12167	default:
12168		printf("%s: Invalid message type %d\n",
12169		       __func__, io->io_hdr.msg_type);
12170		ctl_free_io(io);
12171		break;
12172	}
12173
12174}
12175
12176
12177/*
12178 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12179 * there is no match.
12180 */
12181static ctl_lun_error_pattern
12182ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12183{
12184	const struct ctl_cmd_entry *entry;
12185	ctl_lun_error_pattern filtered_pattern, pattern;
12186
12187	pattern = desc->error_pattern;
12188
12189	/*
12190	 * XXX KDM we need more data passed into this function to match a
12191	 * custom pattern, and we actually need to implement custom pattern
12192	 * matching.
12193	 */
12194	if (pattern & CTL_LUN_PAT_CMD)
12195		return (CTL_LUN_PAT_CMD);
12196
12197	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12198		return (CTL_LUN_PAT_ANY);
12199
12200	entry = ctl_get_cmd_entry(ctsio, NULL);
12201
12202	filtered_pattern = entry->pattern & pattern;
12203
12204	/*
12205	 * If the user requested specific flags in the pattern (e.g.
12206	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12207	 * flags.
12208	 *
12209	 * If the user did not specify any flags, it doesn't matter whether
12210	 * or not the command supports the flags.
12211	 */
12212	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12213	     (pattern & ~CTL_LUN_PAT_MASK))
12214		return (CTL_LUN_PAT_NONE);
12215
12216	/*
12217	 * If the user asked for a range check, see if the requested LBA
12218	 * range overlaps with this command's LBA range.
12219	 */
12220	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12221		uint64_t lba1;
12222		uint64_t len1;
12223		ctl_action action;
12224		int retval;
12225
12226		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12227		if (retval != 0)
12228			return (CTL_LUN_PAT_NONE);
12229
12230		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12231					      desc->lba_range.len, FALSE);
12232		/*
12233		 * A "pass" means that the LBA ranges don't overlap, so
12234		 * this doesn't match the user's range criteria.
12235		 */
12236		if (action == CTL_ACTION_PASS)
12237			return (CTL_LUN_PAT_NONE);
12238	}
12239
12240	return (filtered_pattern);
12241}
12242
12243static void
12244ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12245{
12246	struct ctl_error_desc *desc, *desc2;
12247
12248	mtx_assert(&lun->lun_lock, MA_OWNED);
12249
12250	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12251		ctl_lun_error_pattern pattern;
12252		/*
12253		 * Check to see whether this particular command matches
12254		 * the pattern in the descriptor.
12255		 */
12256		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12257		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12258			continue;
12259
12260		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12261		case CTL_LUN_INJ_ABORTED:
12262			ctl_set_aborted(&io->scsiio);
12263			break;
12264		case CTL_LUN_INJ_MEDIUM_ERR:
12265			ctl_set_medium_error(&io->scsiio,
12266			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12267			     CTL_FLAG_DATA_OUT);
12268			break;
12269		case CTL_LUN_INJ_UA:
12270			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12271			 * OCCURRED */
12272			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12273			break;
12274		case CTL_LUN_INJ_CUSTOM:
12275			/*
12276			 * We're assuming the user knows what he is doing.
12277			 * Just copy the sense information without doing
12278			 * checks.
12279			 */
12280			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12281			      MIN(sizeof(desc->custom_sense),
12282				  sizeof(io->scsiio.sense_data)));
12283			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12284			io->scsiio.sense_len = SSD_FULL_SIZE;
12285			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12286			break;
12287		case CTL_LUN_INJ_NONE:
12288		default:
12289			/*
12290			 * If this is an error injection type we don't know
12291			 * about, clear the continuous flag (if it is set)
12292			 * so it will get deleted below.
12293			 */
12294			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12295			break;
12296		}
12297		/*
12298		 * By default, each error injection action is a one-shot
12299		 */
12300		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12301			continue;
12302
12303		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12304
12305		free(desc, M_CTL);
12306	}
12307}
12308
12309#ifdef CTL_IO_DELAY
12310static void
12311ctl_datamove_timer_wakeup(void *arg)
12312{
12313	union ctl_io *io;
12314
12315	io = (union ctl_io *)arg;
12316
12317	ctl_datamove(io);
12318}
12319#endif /* CTL_IO_DELAY */
12320
12321void
12322ctl_datamove(union ctl_io *io)
12323{
12324	void (*fe_datamove)(union ctl_io *io);
12325
12326	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12327
12328	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12329
12330	/* No data transferred yet.  Frontend must update this when done. */
12331	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12332
12333#ifdef CTL_TIME_IO
12334	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12335		char str[256];
12336		char path_str[64];
12337		struct sbuf sb;
12338
12339		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12340		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12341
12342		sbuf_cat(&sb, path_str);
12343		switch (io->io_hdr.io_type) {
12344		case CTL_IO_SCSI:
12345			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12346			sbuf_printf(&sb, "\n");
12347			sbuf_cat(&sb, path_str);
12348			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12349				    io->scsiio.tag_num, io->scsiio.tag_type);
12350			break;
12351		case CTL_IO_TASK:
12352			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12353				    "Tag Type: %d\n", io->taskio.task_action,
12354				    io->taskio.tag_num, io->taskio.tag_type);
12355			break;
12356		default:
12357			panic("%s: Invalid CTL I/O type %d\n",
12358			    __func__, io->io_hdr.io_type);
12359		}
12360		sbuf_cat(&sb, path_str);
12361		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12362			    (intmax_t)time_uptime - io->io_hdr.start_time);
12363		sbuf_finish(&sb);
12364		printf("%s", sbuf_data(&sb));
12365	}
12366#endif /* CTL_TIME_IO */
12367
12368#ifdef CTL_IO_DELAY
12369	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12370		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12371	} else {
12372		struct ctl_lun *lun;
12373
12374		lun = CTL_LUN(io);
12375		if ((lun != NULL)
12376		 && (lun->delay_info.datamove_delay > 0)) {
12377
12378			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12379			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12380			callout_reset(&io->io_hdr.delay_callout,
12381				      lun->delay_info.datamove_delay * hz,
12382				      ctl_datamove_timer_wakeup, io);
12383			if (lun->delay_info.datamove_type ==
12384			    CTL_DELAY_TYPE_ONESHOT)
12385				lun->delay_info.datamove_delay = 0;
12386			return;
12387		}
12388	}
12389#endif
12390
12391	/*
12392	 * This command has been aborted.  Set the port status, so we fail
12393	 * the data move.
12394	 */
12395	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12396		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12397		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12398		       io->io_hdr.nexus.targ_port,
12399		       io->io_hdr.nexus.targ_lun);
12400		io->io_hdr.port_status = 31337;
12401		/*
12402		 * Note that the backend, in this case, will get the
12403		 * callback in its context.  In other cases it may get
12404		 * called in the frontend's interrupt thread context.
12405		 */
12406		io->scsiio.be_move_done(io);
12407		return;
12408	}
12409
12410	/* Don't confuse frontend with zero length data move. */
12411	if (io->scsiio.kern_data_len == 0) {
12412		io->scsiio.be_move_done(io);
12413		return;
12414	}
12415
12416	fe_datamove = CTL_PORT(io)->fe_datamove;
12417	fe_datamove(io);
12418}
12419
12420static void
12421ctl_send_datamove_done(union ctl_io *io, int have_lock)
12422{
12423	union ctl_ha_msg msg;
12424#ifdef CTL_TIME_IO
12425	struct bintime cur_bt;
12426#endif
12427
12428	memset(&msg, 0, sizeof(msg));
12429	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12430	msg.hdr.original_sc = io;
12431	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12432	msg.hdr.nexus = io->io_hdr.nexus;
12433	msg.hdr.status = io->io_hdr.status;
12434	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12435	msg.scsi.tag_num = io->scsiio.tag_num;
12436	msg.scsi.tag_type = io->scsiio.tag_type;
12437	msg.scsi.scsi_status = io->scsiio.scsi_status;
12438	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12439	       io->scsiio.sense_len);
12440	msg.scsi.sense_len = io->scsiio.sense_len;
12441	msg.scsi.port_status = io->io_hdr.port_status;
12442	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12443	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12444		ctl_failover_io(io, /*have_lock*/ have_lock);
12445		return;
12446	}
12447	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12448	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12449	    msg.scsi.sense_len, M_WAITOK);
12450
12451#ifdef CTL_TIME_IO
12452	getbinuptime(&cur_bt);
12453	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12454	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12455#endif
12456	io->io_hdr.num_dmas++;
12457}
12458
12459/*
12460 * The DMA to the remote side is done, now we need to tell the other side
12461 * we're done so it can continue with its data movement.
12462 */
12463static void
12464ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12465{
12466	union ctl_io *io;
12467	uint32_t i;
12468
12469	io = rq->context;
12470
12471	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12472		printf("%s: ISC DMA write failed with error %d", __func__,
12473		       rq->ret);
12474		ctl_set_internal_failure(&io->scsiio,
12475					 /*sks_valid*/ 1,
12476					 /*retry_count*/ rq->ret);
12477	}
12478
12479	ctl_dt_req_free(rq);
12480
12481	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12482		free(CTL_LSGLT(io)[i].addr, M_CTL);
12483	free(CTL_RSGL(io), M_CTL);
12484	CTL_RSGL(io) = NULL;
12485	CTL_LSGL(io) = NULL;
12486
12487	/*
12488	 * The data is in local and remote memory, so now we need to send
12489	 * status (good or back) back to the other side.
12490	 */
12491	ctl_send_datamove_done(io, /*have_lock*/ 0);
12492}
12493
12494/*
12495 * We've moved the data from the host/controller into local memory.  Now we
12496 * need to push it over to the remote controller's memory.
12497 */
12498static int
12499ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12500{
12501	int retval;
12502
12503	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12504					  ctl_datamove_remote_write_cb);
12505	return (retval);
12506}
12507
12508static void
12509ctl_datamove_remote_write(union ctl_io *io)
12510{
12511	int retval;
12512	void (*fe_datamove)(union ctl_io *io);
12513
12514	/*
12515	 * - Get the data from the host/HBA into local memory.
12516	 * - DMA memory from the local controller to the remote controller.
12517	 * - Send status back to the remote controller.
12518	 */
12519
12520	retval = ctl_datamove_remote_sgl_setup(io);
12521	if (retval != 0)
12522		return;
12523
12524	/* Switch the pointer over so the FETD knows what to do */
12525	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12526
12527	/*
12528	 * Use a custom move done callback, since we need to send completion
12529	 * back to the other controller, not to the backend on this side.
12530	 */
12531	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12532
12533	fe_datamove = CTL_PORT(io)->fe_datamove;
12534	fe_datamove(io);
12535}
12536
12537static int
12538ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12539{
12540	uint32_t i;
12541
12542	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12543		free(CTL_LSGLT(io)[i].addr, M_CTL);
12544	free(CTL_RSGL(io), M_CTL);
12545	CTL_RSGL(io) = NULL;
12546	CTL_LSGL(io) = NULL;
12547
12548	/*
12549	 * The read is done, now we need to send status (good or bad) back
12550	 * to the other side.
12551	 */
12552	ctl_send_datamove_done(io, /*have_lock*/ 0);
12553
12554	return (0);
12555}
12556
12557static void
12558ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12559{
12560	union ctl_io *io;
12561	void (*fe_datamove)(union ctl_io *io);
12562
12563	io = rq->context;
12564
12565	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12566		printf("%s: ISC DMA read failed with error %d\n", __func__,
12567		       rq->ret);
12568		ctl_set_internal_failure(&io->scsiio,
12569					 /*sks_valid*/ 1,
12570					 /*retry_count*/ rq->ret);
12571	}
12572
12573	ctl_dt_req_free(rq);
12574
12575	/* Switch the pointer over so the FETD knows what to do */
12576	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12577
12578	/*
12579	 * Use a custom move done callback, since we need to send completion
12580	 * back to the other controller, not to the backend on this side.
12581	 */
12582	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12583
12584	/* XXX KDM add checks like the ones in ctl_datamove? */
12585
12586	fe_datamove = CTL_PORT(io)->fe_datamove;
12587	fe_datamove(io);
12588}
12589
12590static int
12591ctl_datamove_remote_sgl_setup(union ctl_io *io)
12592{
12593	struct ctl_sg_entry *local_sglist;
12594	uint32_t len_to_go;
12595	int retval;
12596	int i;
12597
12598	retval = 0;
12599	local_sglist = CTL_LSGL(io);
12600	len_to_go = io->scsiio.kern_data_len;
12601
12602	/*
12603	 * The difficult thing here is that the size of the various
12604	 * S/G segments may be different than the size from the
12605	 * remote controller.  That'll make it harder when DMAing
12606	 * the data back to the other side.
12607	 */
12608	for (i = 0; len_to_go > 0; i++) {
12609		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12610		local_sglist[i].addr =
12611		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12612
12613		len_to_go -= local_sglist[i].len;
12614	}
12615	/*
12616	 * Reset the number of S/G entries accordingly.  The original
12617	 * number of S/G entries is available in rem_sg_entries.
12618	 */
12619	io->scsiio.kern_sg_entries = i;
12620
12621	return (retval);
12622}
12623
12624static int
12625ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12626			 ctl_ha_dt_cb callback)
12627{
12628	struct ctl_ha_dt_req *rq;
12629	struct ctl_sg_entry *remote_sglist, *local_sglist;
12630	uint32_t local_used, remote_used, total_used;
12631	int i, j, isc_ret;
12632
12633	rq = ctl_dt_req_alloc();
12634
12635	/*
12636	 * If we failed to allocate the request, and if the DMA didn't fail
12637	 * anyway, set busy status.  This is just a resource allocation
12638	 * failure.
12639	 */
12640	if ((rq == NULL)
12641	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12642	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12643		ctl_set_busy(&io->scsiio);
12644
12645	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12646	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12647
12648		if (rq != NULL)
12649			ctl_dt_req_free(rq);
12650
12651		/*
12652		 * The data move failed.  We need to return status back
12653		 * to the other controller.  No point in trying to DMA
12654		 * data to the remote controller.
12655		 */
12656
12657		ctl_send_datamove_done(io, /*have_lock*/ 0);
12658
12659		return (1);
12660	}
12661
12662	local_sglist = CTL_LSGL(io);
12663	remote_sglist = CTL_RSGL(io);
12664	local_used = 0;
12665	remote_used = 0;
12666	total_used = 0;
12667
12668	/*
12669	 * Pull/push the data over the wire from/to the other controller.
12670	 * This takes into account the possibility that the local and
12671	 * remote sglists may not be identical in terms of the size of
12672	 * the elements and the number of elements.
12673	 *
12674	 * One fundamental assumption here is that the length allocated for
12675	 * both the local and remote sglists is identical.  Otherwise, we've
12676	 * essentially got a coding error of some sort.
12677	 */
12678	isc_ret = CTL_HA_STATUS_SUCCESS;
12679	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12680		uint32_t cur_len;
12681		uint8_t *tmp_ptr;
12682
12683		rq->command = command;
12684		rq->context = io;
12685
12686		/*
12687		 * Both pointers should be aligned.  But it is possible
12688		 * that the allocation length is not.  They should both
12689		 * also have enough slack left over at the end, though,
12690		 * to round up to the next 8 byte boundary.
12691		 */
12692		cur_len = MIN(local_sglist[i].len - local_used,
12693			      remote_sglist[j].len - remote_used);
12694		rq->size = cur_len;
12695
12696		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12697		tmp_ptr += local_used;
12698
12699#if 0
12700		/* Use physical addresses when talking to ISC hardware */
12701		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12702			/* XXX KDM use busdma */
12703			rq->local = vtophys(tmp_ptr);
12704		} else
12705			rq->local = tmp_ptr;
12706#else
12707		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12708		    ("HA does not support BUS_ADDR"));
12709		rq->local = tmp_ptr;
12710#endif
12711
12712		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12713		tmp_ptr += remote_used;
12714		rq->remote = tmp_ptr;
12715
12716		rq->callback = NULL;
12717
12718		local_used += cur_len;
12719		if (local_used >= local_sglist[i].len) {
12720			i++;
12721			local_used = 0;
12722		}
12723
12724		remote_used += cur_len;
12725		if (remote_used >= remote_sglist[j].len) {
12726			j++;
12727			remote_used = 0;
12728		}
12729		total_used += cur_len;
12730
12731		if (total_used >= io->scsiio.kern_data_len)
12732			rq->callback = callback;
12733
12734		isc_ret = ctl_dt_single(rq);
12735		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12736			break;
12737	}
12738	if (isc_ret != CTL_HA_STATUS_WAIT) {
12739		rq->ret = isc_ret;
12740		callback(rq);
12741	}
12742
12743	return (0);
12744}
12745
12746static void
12747ctl_datamove_remote_read(union ctl_io *io)
12748{
12749	int retval;
12750	uint32_t i;
12751
12752	/*
12753	 * This will send an error to the other controller in the case of a
12754	 * failure.
12755	 */
12756	retval = ctl_datamove_remote_sgl_setup(io);
12757	if (retval != 0)
12758		return;
12759
12760	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12761					  ctl_datamove_remote_read_cb);
12762	if (retval != 0) {
12763		/*
12764		 * Make sure we free memory if there was an error..  The
12765		 * ctl_datamove_remote_xfer() function will send the
12766		 * datamove done message, or call the callback with an
12767		 * error if there is a problem.
12768		 */
12769		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12770			free(CTL_LSGLT(io)[i].addr, M_CTL);
12771		free(CTL_RSGL(io), M_CTL);
12772		CTL_RSGL(io) = NULL;
12773		CTL_LSGL(io) = NULL;
12774	}
12775}
12776
12777/*
12778 * Process a datamove request from the other controller.  This is used for
12779 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12780 * first.  Once that is complete, the data gets DMAed into the remote
12781 * controller's memory.  For reads, we DMA from the remote controller's
12782 * memory into our memory first, and then move it out to the FETD.
12783 */
12784static void
12785ctl_datamove_remote(union ctl_io *io)
12786{
12787
12788	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12789
12790	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12791		ctl_failover_io(io, /*have_lock*/ 0);
12792		return;
12793	}
12794
12795	/*
12796	 * Note that we look for an aborted I/O here, but don't do some of
12797	 * the other checks that ctl_datamove() normally does.
12798	 * We don't need to run the datamove delay code, since that should
12799	 * have been done if need be on the other controller.
12800	 */
12801	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12802		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12803		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12804		       io->io_hdr.nexus.targ_port,
12805		       io->io_hdr.nexus.targ_lun);
12806		io->io_hdr.port_status = 31338;
12807		ctl_send_datamove_done(io, /*have_lock*/ 0);
12808		return;
12809	}
12810
12811	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12812		ctl_datamove_remote_write(io);
12813	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12814		ctl_datamove_remote_read(io);
12815	else {
12816		io->io_hdr.port_status = 31339;
12817		ctl_send_datamove_done(io, /*have_lock*/ 0);
12818	}
12819}
12820
12821static void
12822ctl_process_done(union ctl_io *io)
12823{
12824	struct ctl_softc *softc = CTL_SOFTC(io);
12825	struct ctl_port *port = CTL_PORT(io);
12826	struct ctl_lun *lun = CTL_LUN(io);
12827	void (*fe_done)(union ctl_io *io);
12828	union ctl_ha_msg msg;
12829
12830	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12831	fe_done = port->fe_done;
12832
12833#ifdef CTL_TIME_IO
12834	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12835		char str[256];
12836		char path_str[64];
12837		struct sbuf sb;
12838
12839		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12840		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12841
12842		sbuf_cat(&sb, path_str);
12843		switch (io->io_hdr.io_type) {
12844		case CTL_IO_SCSI:
12845			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12846			sbuf_printf(&sb, "\n");
12847			sbuf_cat(&sb, path_str);
12848			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12849				    io->scsiio.tag_num, io->scsiio.tag_type);
12850			break;
12851		case CTL_IO_TASK:
12852			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12853				    "Tag Type: %d\n", io->taskio.task_action,
12854				    io->taskio.tag_num, io->taskio.tag_type);
12855			break;
12856		default:
12857			panic("%s: Invalid CTL I/O type %d\n",
12858			    __func__, io->io_hdr.io_type);
12859		}
12860		sbuf_cat(&sb, path_str);
12861		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12862			    (intmax_t)time_uptime - io->io_hdr.start_time);
12863		sbuf_finish(&sb);
12864		printf("%s", sbuf_data(&sb));
12865	}
12866#endif /* CTL_TIME_IO */
12867
12868	switch (io->io_hdr.io_type) {
12869	case CTL_IO_SCSI:
12870		break;
12871	case CTL_IO_TASK:
12872		if (ctl_debug & CTL_DEBUG_INFO)
12873			ctl_io_error_print(io, NULL);
12874		fe_done(io);
12875		return;
12876	default:
12877		panic("%s: Invalid CTL I/O type %d\n",
12878		    __func__, io->io_hdr.io_type);
12879	}
12880
12881	if (lun == NULL) {
12882		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12883				 io->io_hdr.nexus.targ_mapped_lun));
12884		goto bailout;
12885	}
12886
12887	mtx_lock(&lun->lun_lock);
12888
12889	/*
12890	 * Check to see if we have any informational exception and status
12891	 * of this command can be modified to report it in form of either
12892	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
12893	 */
12894	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
12895	    io->io_hdr.status == CTL_SUCCESS &&
12896	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
12897		uint8_t mrie = lun->MODE_IE.mrie;
12898		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
12899		    (lun->MODE_VER.byte3 & SMS_VER_PER));
12900		if (((mrie == SIEP_MRIE_REC_COND && per) ||
12901		     mrie == SIEP_MRIE_REC_UNCOND ||
12902		     mrie == SIEP_MRIE_NO_SENSE) &&
12903		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
12904		     CTL_CMD_FLAG_NO_SENSE) == 0) {
12905			ctl_set_sense(&io->scsiio,
12906			      /*current_error*/ 1,
12907			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
12908			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
12909			      /*asc*/ lun->ie_asc,
12910			      /*ascq*/ lun->ie_ascq,
12911			      SSD_ELEM_NONE);
12912			lun->ie_reported = 1;
12913		}
12914	} else if (lun->ie_reported < 0)
12915		lun->ie_reported = 0;
12916
12917	/*
12918	 * Check to see if we have any errors to inject here.  We only
12919	 * inject errors for commands that don't already have errors set.
12920	 */
12921	if (!STAILQ_EMPTY(&lun->error_list) &&
12922	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12923	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12924		ctl_inject_error(lun, io);
12925
12926	/*
12927	 * XXX KDM how do we treat commands that aren't completed
12928	 * successfully?
12929	 *
12930	 * XXX KDM should we also track I/O latency?
12931	 */
12932	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12933	    io->io_hdr.io_type == CTL_IO_SCSI) {
12934		int type;
12935#ifdef CTL_TIME_IO
12936		struct bintime bt;
12937
12938		getbinuptime(&bt);
12939		bintime_sub(&bt, &io->io_hdr.start_bt);
12940#endif
12941		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12942		    CTL_FLAG_DATA_IN)
12943			type = CTL_STATS_READ;
12944		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12945		    CTL_FLAG_DATA_OUT)
12946			type = CTL_STATS_WRITE;
12947		else
12948			type = CTL_STATS_NO_IO;
12949
12950#ifdef CTL_LEGACY_STATS
12951		uint32_t targ_port = port->targ_port;
12952		lun->legacy_stats.ports[targ_port].bytes[type] +=
12953		    io->scsiio.kern_total_len;
12954		lun->legacy_stats.ports[targ_port].operations[type] ++;
12955		lun->legacy_stats.ports[targ_port].num_dmas[type] +=
12956		    io->io_hdr.num_dmas;
12957#ifdef CTL_TIME_IO
12958		bintime_add(&lun->legacy_stats.ports[targ_port].dma_time[type],
12959		   &io->io_hdr.dma_bt);
12960		bintime_add(&lun->legacy_stats.ports[targ_port].time[type],
12961		    &bt);
12962#endif
12963#endif /* CTL_LEGACY_STATS */
12964
12965		lun->stats.bytes[type] += io->scsiio.kern_total_len;
12966		lun->stats.operations[type] ++;
12967		lun->stats.dmas[type] += io->io_hdr.num_dmas;
12968#ifdef CTL_TIME_IO
12969		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
12970		bintime_add(&lun->stats.time[type], &bt);
12971#endif
12972
12973		mtx_lock(&port->port_lock);
12974		port->stats.bytes[type] += io->scsiio.kern_total_len;
12975		port->stats.operations[type] ++;
12976		port->stats.dmas[type] += io->io_hdr.num_dmas;
12977#ifdef CTL_TIME_IO
12978		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
12979		bintime_add(&port->stats.time[type], &bt);
12980#endif
12981		mtx_unlock(&port->port_lock);
12982	}
12983
12984	/*
12985	 * Remove this from the OOA queue.
12986	 */
12987	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12988#ifdef CTL_TIME_IO
12989	if (TAILQ_EMPTY(&lun->ooa_queue))
12990		lun->last_busy = getsbinuptime();
12991#endif
12992
12993	/*
12994	 * Run through the blocked queue on this LUN and see if anything
12995	 * has become unblocked, now that this transaction is done.
12996	 */
12997	ctl_check_blocked(lun);
12998
12999	/*
13000	 * If the LUN has been invalidated, free it if there is nothing
13001	 * left on its OOA queue.
13002	 */
13003	if ((lun->flags & CTL_LUN_INVALID)
13004	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13005		mtx_unlock(&lun->lun_lock);
13006		ctl_free_lun(lun);
13007	} else
13008		mtx_unlock(&lun->lun_lock);
13009
13010bailout:
13011
13012	/*
13013	 * If this command has been aborted, make sure we set the status
13014	 * properly.  The FETD is responsible for freeing the I/O and doing
13015	 * whatever it needs to do to clean up its state.
13016	 */
13017	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13018		ctl_set_task_aborted(&io->scsiio);
13019
13020	/*
13021	 * If enabled, print command error status.
13022	 */
13023	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13024	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13025		ctl_io_error_print(io, NULL);
13026
13027	/*
13028	 * Tell the FETD or the other shelf controller we're done with this
13029	 * command.  Note that only SCSI commands get to this point.  Task
13030	 * management commands are completed above.
13031	 */
13032	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13033	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13034		memset(&msg, 0, sizeof(msg));
13035		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13036		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13037		msg.hdr.nexus = io->io_hdr.nexus;
13038		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13039		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13040		    M_WAITOK);
13041	}
13042
13043	fe_done(io);
13044}
13045
13046/*
13047 * Front end should call this if it doesn't do autosense.  When the request
13048 * sense comes back in from the initiator, we'll dequeue this and send it.
13049 */
13050int
13051ctl_queue_sense(union ctl_io *io)
13052{
13053	struct ctl_softc *softc = CTL_SOFTC(io);
13054	struct ctl_port *port = CTL_PORT(io);
13055	struct ctl_lun *lun;
13056	struct scsi_sense_data *ps;
13057	uint32_t initidx, p, targ_lun;
13058
13059	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13060
13061	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13062
13063	/*
13064	 * LUN lookup will likely move to the ctl_work_thread() once we
13065	 * have our new queueing infrastructure (that doesn't put things on
13066	 * a per-LUN queue initially).  That is so that we can handle
13067	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13068	 * can't deal with that right now.
13069	 * If we don't have a LUN for this, just toss the sense information.
13070	 */
13071	mtx_lock(&softc->ctl_lock);
13072	if (targ_lun >= ctl_max_luns ||
13073	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13074		mtx_unlock(&softc->ctl_lock);
13075		goto bailout;
13076	}
13077	mtx_lock(&lun->lun_lock);
13078	mtx_unlock(&softc->ctl_lock);
13079
13080	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13081	p = initidx / CTL_MAX_INIT_PER_PORT;
13082	if (lun->pending_sense[p] == NULL) {
13083		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13084		    M_CTL, M_NOWAIT | M_ZERO);
13085	}
13086	if ((ps = lun->pending_sense[p]) != NULL) {
13087		ps += initidx % CTL_MAX_INIT_PER_PORT;
13088		memset(ps, 0, sizeof(*ps));
13089		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13090	}
13091	mtx_unlock(&lun->lun_lock);
13092
13093bailout:
13094	ctl_free_io(io);
13095	return (CTL_RETVAL_COMPLETE);
13096}
13097
13098/*
13099 * Primary command inlet from frontend ports.  All SCSI and task I/O
13100 * requests must go through this function.
13101 */
13102int
13103ctl_queue(union ctl_io *io)
13104{
13105	struct ctl_port *port = CTL_PORT(io);
13106
13107	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13108
13109#ifdef CTL_TIME_IO
13110	io->io_hdr.start_time = time_uptime;
13111	getbinuptime(&io->io_hdr.start_bt);
13112#endif /* CTL_TIME_IO */
13113
13114	/* Map FE-specific LUN ID into global one. */
13115	io->io_hdr.nexus.targ_mapped_lun =
13116	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13117
13118	switch (io->io_hdr.io_type) {
13119	case CTL_IO_SCSI:
13120	case CTL_IO_TASK:
13121		if (ctl_debug & CTL_DEBUG_CDB)
13122			ctl_io_print(io);
13123		ctl_enqueue_incoming(io);
13124		break;
13125	default:
13126		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13127		return (EINVAL);
13128	}
13129
13130	return (CTL_RETVAL_COMPLETE);
13131}
13132
13133#ifdef CTL_IO_DELAY
13134static void
13135ctl_done_timer_wakeup(void *arg)
13136{
13137	union ctl_io *io;
13138
13139	io = (union ctl_io *)arg;
13140	ctl_done(io);
13141}
13142#endif /* CTL_IO_DELAY */
13143
13144void
13145ctl_serseq_done(union ctl_io *io)
13146{
13147	struct ctl_lun *lun = CTL_LUN(io);;
13148
13149	if (lun->be_lun == NULL ||
13150	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13151		return;
13152	mtx_lock(&lun->lun_lock);
13153	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13154	ctl_check_blocked(lun);
13155	mtx_unlock(&lun->lun_lock);
13156}
13157
13158void
13159ctl_done(union ctl_io *io)
13160{
13161
13162	/*
13163	 * Enable this to catch duplicate completion issues.
13164	 */
13165#if 0
13166	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13167		printf("%s: type %d msg %d cdb %x iptl: "
13168		       "%u:%u:%u tag 0x%04x "
13169		       "flag %#x status %x\n",
13170			__func__,
13171			io->io_hdr.io_type,
13172			io->io_hdr.msg_type,
13173			io->scsiio.cdb[0],
13174			io->io_hdr.nexus.initid,
13175			io->io_hdr.nexus.targ_port,
13176			io->io_hdr.nexus.targ_lun,
13177			(io->io_hdr.io_type ==
13178			CTL_IO_TASK) ?
13179			io->taskio.tag_num :
13180			io->scsiio.tag_num,
13181		        io->io_hdr.flags,
13182			io->io_hdr.status);
13183	} else
13184		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13185#endif
13186
13187	/*
13188	 * This is an internal copy of an I/O, and should not go through
13189	 * the normal done processing logic.
13190	 */
13191	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13192		return;
13193
13194#ifdef CTL_IO_DELAY
13195	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13196		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13197	} else {
13198		struct ctl_lun *lun = CTL_LUN(io);
13199
13200		if ((lun != NULL)
13201		 && (lun->delay_info.done_delay > 0)) {
13202
13203			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13204			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13205			callout_reset(&io->io_hdr.delay_callout,
13206				      lun->delay_info.done_delay * hz,
13207				      ctl_done_timer_wakeup, io);
13208			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13209				lun->delay_info.done_delay = 0;
13210			return;
13211		}
13212	}
13213#endif /* CTL_IO_DELAY */
13214
13215	ctl_enqueue_done(io);
13216}
13217
13218static void
13219ctl_work_thread(void *arg)
13220{
13221	struct ctl_thread *thr = (struct ctl_thread *)arg;
13222	struct ctl_softc *softc = thr->ctl_softc;
13223	union ctl_io *io;
13224	int retval;
13225
13226	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13227	thread_lock(curthread);
13228	sched_prio(curthread, PUSER - 1);
13229	thread_unlock(curthread);
13230
13231	while (!softc->shutdown) {
13232		/*
13233		 * We handle the queues in this order:
13234		 * - ISC
13235		 * - done queue (to free up resources, unblock other commands)
13236		 * - RtR queue
13237		 * - incoming queue
13238		 *
13239		 * If those queues are empty, we break out of the loop and
13240		 * go to sleep.
13241		 */
13242		mtx_lock(&thr->queue_lock);
13243		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13244		if (io != NULL) {
13245			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13246			mtx_unlock(&thr->queue_lock);
13247			ctl_handle_isc(io);
13248			continue;
13249		}
13250		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13251		if (io != NULL) {
13252			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13253			/* clear any blocked commands, call fe_done */
13254			mtx_unlock(&thr->queue_lock);
13255			ctl_process_done(io);
13256			continue;
13257		}
13258		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13259		if (io != NULL) {
13260			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13261			mtx_unlock(&thr->queue_lock);
13262			if (io->io_hdr.io_type == CTL_IO_TASK)
13263				ctl_run_task(io);
13264			else
13265				ctl_scsiio_precheck(softc, &io->scsiio);
13266			continue;
13267		}
13268		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13269		if (io != NULL) {
13270			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13271			mtx_unlock(&thr->queue_lock);
13272			retval = ctl_scsiio(&io->scsiio);
13273			if (retval != CTL_RETVAL_COMPLETE)
13274				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13275			continue;
13276		}
13277
13278		/* Sleep until we have something to do. */
13279		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13280	}
13281	thr->thread = NULL;
13282	kthread_exit();
13283}
13284
13285static void
13286ctl_lun_thread(void *arg)
13287{
13288	struct ctl_softc *softc = (struct ctl_softc *)arg;
13289	struct ctl_be_lun *be_lun;
13290
13291	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13292	thread_lock(curthread);
13293	sched_prio(curthread, PUSER - 1);
13294	thread_unlock(curthread);
13295
13296	while (!softc->shutdown) {
13297		mtx_lock(&softc->ctl_lock);
13298		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13299		if (be_lun != NULL) {
13300			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13301			mtx_unlock(&softc->ctl_lock);
13302			ctl_create_lun(be_lun);
13303			continue;
13304		}
13305
13306		/* Sleep until we have something to do. */
13307		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13308		    PDROP, "-", 0);
13309	}
13310	softc->lun_thread = NULL;
13311	kthread_exit();
13312}
13313
13314static void
13315ctl_thresh_thread(void *arg)
13316{
13317	struct ctl_softc *softc = (struct ctl_softc *)arg;
13318	struct ctl_lun *lun;
13319	struct ctl_logical_block_provisioning_page *page;
13320	const char *attr;
13321	union ctl_ha_msg msg;
13322	uint64_t thres, val;
13323	int i, e, set;
13324
13325	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13326	thread_lock(curthread);
13327	sched_prio(curthread, PUSER - 1);
13328	thread_unlock(curthread);
13329
13330	while (!softc->shutdown) {
13331		mtx_lock(&softc->ctl_lock);
13332		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13333			if ((lun->flags & CTL_LUN_DISABLED) ||
13334			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13335			    lun->backend->lun_attr == NULL)
13336				continue;
13337			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13338			    softc->ha_mode == CTL_HA_MODE_XFER)
13339				continue;
13340			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13341				continue;
13342			e = 0;
13343			page = &lun->MODE_LBP;
13344			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13345				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13346					continue;
13347				thres = scsi_4btoul(page->descr[i].count);
13348				thres <<= CTL_LBP_EXPONENT;
13349				switch (page->descr[i].resource) {
13350				case 0x01:
13351					attr = "blocksavail";
13352					break;
13353				case 0x02:
13354					attr = "blocksused";
13355					break;
13356				case 0xf1:
13357					attr = "poolblocksavail";
13358					break;
13359				case 0xf2:
13360					attr = "poolblocksused";
13361					break;
13362				default:
13363					continue;
13364				}
13365				mtx_unlock(&softc->ctl_lock); // XXX
13366				val = lun->backend->lun_attr(
13367				    lun->be_lun->be_lun, attr);
13368				mtx_lock(&softc->ctl_lock);
13369				if (val == UINT64_MAX)
13370					continue;
13371				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13372				    == SLBPPD_ARMING_INC)
13373					e = (val >= thres);
13374				else
13375					e = (val <= thres);
13376				if (e)
13377					break;
13378			}
13379			mtx_lock(&lun->lun_lock);
13380			if (e) {
13381				scsi_u64to8b((uint8_t *)&page->descr[i] -
13382				    (uint8_t *)page, lun->ua_tpt_info);
13383				if (lun->lasttpt == 0 ||
13384				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13385					lun->lasttpt = time_uptime;
13386					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13387					set = 1;
13388				} else
13389					set = 0;
13390			} else {
13391				lun->lasttpt = 0;
13392				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13393				set = -1;
13394			}
13395			mtx_unlock(&lun->lun_lock);
13396			if (set != 0 &&
13397			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13398				/* Send msg to other side. */
13399				bzero(&msg.ua, sizeof(msg.ua));
13400				msg.hdr.msg_type = CTL_MSG_UA;
13401				msg.hdr.nexus.initid = -1;
13402				msg.hdr.nexus.targ_port = -1;
13403				msg.hdr.nexus.targ_lun = lun->lun;
13404				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13405				msg.ua.ua_all = 1;
13406				msg.ua.ua_set = (set > 0);
13407				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13408				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13409				mtx_unlock(&softc->ctl_lock); // XXX
13410				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13411				    sizeof(msg.ua), M_WAITOK);
13412				mtx_lock(&softc->ctl_lock);
13413			}
13414		}
13415		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13416		    PDROP, "-", CTL_LBP_PERIOD * hz);
13417	}
13418	softc->thresh_thread = NULL;
13419	kthread_exit();
13420}
13421
13422static void
13423ctl_enqueue_incoming(union ctl_io *io)
13424{
13425	struct ctl_softc *softc = CTL_SOFTC(io);
13426	struct ctl_thread *thr;
13427	u_int idx;
13428
13429	idx = (io->io_hdr.nexus.targ_port * 127 +
13430	       io->io_hdr.nexus.initid) % worker_threads;
13431	thr = &softc->threads[idx];
13432	mtx_lock(&thr->queue_lock);
13433	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13434	mtx_unlock(&thr->queue_lock);
13435	wakeup(thr);
13436}
13437
13438static void
13439ctl_enqueue_rtr(union ctl_io *io)
13440{
13441	struct ctl_softc *softc = CTL_SOFTC(io);
13442	struct ctl_thread *thr;
13443
13444	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13445	mtx_lock(&thr->queue_lock);
13446	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13447	mtx_unlock(&thr->queue_lock);
13448	wakeup(thr);
13449}
13450
13451static void
13452ctl_enqueue_done(union ctl_io *io)
13453{
13454	struct ctl_softc *softc = CTL_SOFTC(io);
13455	struct ctl_thread *thr;
13456
13457	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13458	mtx_lock(&thr->queue_lock);
13459	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13460	mtx_unlock(&thr->queue_lock);
13461	wakeup(thr);
13462}
13463
13464static void
13465ctl_enqueue_isc(union ctl_io *io)
13466{
13467	struct ctl_softc *softc = CTL_SOFTC(io);
13468	struct ctl_thread *thr;
13469
13470	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13471	mtx_lock(&thr->queue_lock);
13472	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13473	mtx_unlock(&thr->queue_lock);
13474	wakeup(thr);
13475}
13476
13477/*
13478 *  vim: ts=8
13479 */
13480