ctl.c revision 312843
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#define _CTL_C
44
45#include <sys/cdefs.h>
46__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 312843 2017-01-26 21:02:06Z mav $");
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/ctype.h>
51#include <sys/kernel.h>
52#include <sys/types.h>
53#include <sys/kthread.h>
54#include <sys/bio.h>
55#include <sys/fcntl.h>
56#include <sys/lock.h>
57#include <sys/module.h>
58#include <sys/mutex.h>
59#include <sys/condvar.h>
60#include <sys/malloc.h>
61#include <sys/conf.h>
62#include <sys/ioccom.h>
63#include <sys/queue.h>
64#include <sys/sbuf.h>
65#include <sys/smp.h>
66#include <sys/endian.h>
67#include <sys/sysctl.h>
68#include <vm/uma.h>
69
70#include <cam/cam.h>
71#include <cam/scsi/scsi_all.h>
72#include <cam/scsi/scsi_cd.h>
73#include <cam/scsi/scsi_da.h>
74#include <cam/ctl/ctl_io.h>
75#include <cam/ctl/ctl.h>
76#include <cam/ctl/ctl_frontend.h>
77#include <cam/ctl/ctl_util.h>
78#include <cam/ctl/ctl_backend.h>
79#include <cam/ctl/ctl_ioctl.h>
80#include <cam/ctl/ctl_ha.h>
81#include <cam/ctl/ctl_private.h>
82#include <cam/ctl/ctl_debug.h>
83#include <cam/ctl/ctl_scsi_all.h>
84#include <cam/ctl/ctl_error.h>
85
86struct ctl_softc *control_softc = NULL;
87
88/*
89 * Template mode pages.
90 */
91
92/*
93 * Note that these are default values only.  The actual values will be
94 * filled in when the user does a mode sense.
95 */
96const static struct 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;
405TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407    &worker_threads, 1, "Number of worker threads");
408static int ctl_debug = CTL_DEBUG_NONE;
409TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411    &ctl_debug, 0, "Enabled debug flags");
412static int ctl_lun_map_size = 1024;
413SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
414    &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
415
416/*
417 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
418 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
419 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
420 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
421 */
422#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
423
424static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
425				  int param);
426static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
427static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
428static int ctl_init(void);
429void ctl_shutdown(void);
430static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
431static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
432static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
433static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
434			      struct ctl_ooa *ooa_hdr,
435			      struct ctl_ooa_entry *kern_entries);
436static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
437		     struct thread *td);
438static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
439			 struct ctl_be_lun *be_lun);
440static int ctl_free_lun(struct ctl_lun *lun);
441static void ctl_create_lun(struct ctl_be_lun *be_lun);
442
443static int ctl_do_mode_select(union ctl_io *io);
444static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
445			   uint64_t res_key, uint64_t sa_res_key,
446			   uint8_t type, uint32_t residx,
447			   struct ctl_scsiio *ctsio,
448			   struct scsi_per_res_out *cdb,
449			   struct scsi_per_res_out_parms* param);
450static void ctl_pro_preempt_other(struct ctl_lun *lun,
451				  union ctl_ha_msg *msg);
452static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
453static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
455static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
456static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
457static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
458static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
459					 int alloc_len);
460static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
461					 int alloc_len);
462static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
463static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
464static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
465static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
466static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
467static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
468    bool seq);
469static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
470static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
471    union ctl_io *pending_io, union ctl_io *ooa_io);
472static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
473				union ctl_io *starting_io);
474static int ctl_check_blocked(struct ctl_lun *lun);
475static int ctl_scsiio_lun_check(struct ctl_lun *lun,
476				const struct ctl_cmd_entry *entry,
477				struct ctl_scsiio *ctsio);
478static void ctl_failover_lun(union ctl_io *io);
479static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
480			       struct ctl_scsiio *ctsio);
481static int ctl_scsiio(struct ctl_scsiio *ctsio);
482
483static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
484static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
485			    ctl_ua_type ua_type);
486static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
487			 ctl_ua_type ua_type);
488static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
489static int ctl_abort_task(union ctl_io *io);
490static int ctl_abort_task_set(union ctl_io *io);
491static int ctl_query_task(union ctl_io *io, int task_set);
492static int ctl_i_t_nexus_reset(union ctl_io *io);
493static int ctl_query_async_event(union ctl_io *io);
494static void ctl_run_task(union ctl_io *io);
495#ifdef CTL_IO_DELAY
496static void ctl_datamove_timer_wakeup(void *arg);
497static void ctl_done_timer_wakeup(void *arg);
498#endif /* CTL_IO_DELAY */
499
500static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
501static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
502static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
503static void ctl_datamove_remote_write(union ctl_io *io);
504static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
505static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
506static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
507static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
508				    ctl_ha_dt_cb callback);
509static void ctl_datamove_remote_read(union ctl_io *io);
510static void ctl_datamove_remote(union ctl_io *io);
511static void ctl_process_done(union ctl_io *io);
512static void ctl_lun_thread(void *arg);
513static void ctl_thresh_thread(void *arg);
514static void ctl_work_thread(void *arg);
515static void ctl_enqueue_incoming(union ctl_io *io);
516static void ctl_enqueue_rtr(union ctl_io *io);
517static void ctl_enqueue_done(union ctl_io *io);
518static void ctl_enqueue_isc(union ctl_io *io);
519static const struct ctl_cmd_entry *
520    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
521static const struct ctl_cmd_entry *
522    ctl_validate_command(struct ctl_scsiio *ctsio);
523static int ctl_cmd_applicable(uint8_t lun_type,
524    const struct ctl_cmd_entry *entry);
525
526static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
527static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
528static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
529static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
530
531/*
532 * Load the serialization table.  This isn't very pretty, but is probably
533 * the easiest way to do it.
534 */
535#include "ctl_ser_table.c"
536
537/*
538 * We only need to define open, close and ioctl routines for this driver.
539 */
540static struct cdevsw ctl_cdevsw = {
541	.d_version =	D_VERSION,
542	.d_flags =	0,
543	.d_open =	ctl_open,
544	.d_close =	ctl_close,
545	.d_ioctl =	ctl_ioctl,
546	.d_name =	"ctl",
547};
548
549
550MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
551
552static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
553
554static moduledata_t ctl_moduledata = {
555	"ctl",
556	ctl_module_event_handler,
557	NULL
558};
559
560DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
561MODULE_VERSION(ctl, 1);
562
563static struct ctl_frontend ha_frontend =
564{
565	.name = "ha",
566};
567
568static void
569ctl_ha_datamove(union ctl_io *io)
570{
571	struct ctl_lun *lun = CTL_LUN(io);
572	struct ctl_sg_entry *sgl;
573	union ctl_ha_msg msg;
574	uint32_t sg_entries_sent;
575	int do_sg_copy, i, j;
576
577	memset(&msg.dt, 0, sizeof(msg.dt));
578	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
579	msg.hdr.original_sc = io->io_hdr.original_sc;
580	msg.hdr.serializing_sc = io;
581	msg.hdr.nexus = io->io_hdr.nexus;
582	msg.hdr.status = io->io_hdr.status;
583	msg.dt.flags = io->io_hdr.flags;
584
585	/*
586	 * We convert everything into a S/G list here.  We can't
587	 * pass by reference, only by value between controllers.
588	 * So we can't pass a pointer to the S/G list, only as many
589	 * S/G entries as we can fit in here.  If it's possible for
590	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
591	 * then we need to break this up into multiple transfers.
592	 */
593	if (io->scsiio.kern_sg_entries == 0) {
594		msg.dt.kern_sg_entries = 1;
595#if 0
596		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
597			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
598		} else {
599			/* XXX KDM use busdma here! */
600			msg.dt.sg_list[0].addr =
601			    (void *)vtophys(io->scsiio.kern_data_ptr);
602		}
603#else
604		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
605		    ("HA does not support BUS_ADDR"));
606		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
607#endif
608		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
609		do_sg_copy = 0;
610	} else {
611		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
612		do_sg_copy = 1;
613	}
614
615	msg.dt.kern_data_len = io->scsiio.kern_data_len;
616	msg.dt.kern_total_len = io->scsiio.kern_total_len;
617	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
618	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
619	msg.dt.sg_sequence = 0;
620
621	/*
622	 * Loop until we've sent all of the S/G entries.  On the
623	 * other end, we'll recompose these S/G entries into one
624	 * contiguous list before processing.
625	 */
626	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
627	    msg.dt.sg_sequence++) {
628		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
629		    sizeof(msg.dt.sg_list[0])),
630		    msg.dt.kern_sg_entries - sg_entries_sent);
631		if (do_sg_copy != 0) {
632			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
633			for (i = sg_entries_sent, j = 0;
634			     i < msg.dt.cur_sg_entries; i++, j++) {
635#if 0
636				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
637					msg.dt.sg_list[j].addr = sgl[i].addr;
638				} else {
639					/* XXX KDM use busdma here! */
640					msg.dt.sg_list[j].addr =
641					    (void *)vtophys(sgl[i].addr);
642				}
643#else
644				KASSERT((io->io_hdr.flags &
645				    CTL_FLAG_BUS_ADDR) == 0,
646				    ("HA does not support BUS_ADDR"));
647				msg.dt.sg_list[j].addr = sgl[i].addr;
648#endif
649				msg.dt.sg_list[j].len = sgl[i].len;
650			}
651		}
652
653		sg_entries_sent += msg.dt.cur_sg_entries;
654		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
655		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
656		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
657		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
658		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
659			io->io_hdr.port_status = 31341;
660			io->scsiio.be_move_done(io);
661			return;
662		}
663		msg.dt.sent_sg_entries = sg_entries_sent;
664	}
665
666	/*
667	 * Officially handover the request from us to peer.
668	 * If failover has just happened, then we must return error.
669	 * If failover happen just after, then it is not our problem.
670	 */
671	if (lun)
672		mtx_lock(&lun->lun_lock);
673	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
674		if (lun)
675			mtx_unlock(&lun->lun_lock);
676		io->io_hdr.port_status = 31342;
677		io->scsiio.be_move_done(io);
678		return;
679	}
680	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
681	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
682	if (lun)
683		mtx_unlock(&lun->lun_lock);
684}
685
686static void
687ctl_ha_done(union ctl_io *io)
688{
689	union ctl_ha_msg msg;
690
691	if (io->io_hdr.io_type == CTL_IO_SCSI) {
692		memset(&msg, 0, sizeof(msg));
693		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
694		msg.hdr.original_sc = io->io_hdr.original_sc;
695		msg.hdr.nexus = io->io_hdr.nexus;
696		msg.hdr.status = io->io_hdr.status;
697		msg.scsi.scsi_status = io->scsiio.scsi_status;
698		msg.scsi.tag_num = io->scsiio.tag_num;
699		msg.scsi.tag_type = io->scsiio.tag_type;
700		msg.scsi.sense_len = io->scsiio.sense_len;
701		msg.scsi.sense_residual = io->scsiio.sense_residual;
702		msg.scsi.residual = io->scsiio.residual;
703		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
704		    io->scsiio.sense_len);
705		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
706		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
707		    msg.scsi.sense_len, M_WAITOK);
708	}
709	ctl_free_io(io);
710}
711
712static void
713ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
714			    union ctl_ha_msg *msg_info)
715{
716	struct ctl_scsiio *ctsio;
717
718	if (msg_info->hdr.original_sc == NULL) {
719		printf("%s: original_sc == NULL!\n", __func__);
720		/* XXX KDM now what? */
721		return;
722	}
723
724	ctsio = &msg_info->hdr.original_sc->scsiio;
725	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
726	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
727	ctsio->io_hdr.status = msg_info->hdr.status;
728	ctsio->scsi_status = msg_info->scsi.scsi_status;
729	ctsio->sense_len = msg_info->scsi.sense_len;
730	ctsio->sense_residual = msg_info->scsi.sense_residual;
731	ctsio->residual = msg_info->scsi.residual;
732	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
733	       msg_info->scsi.sense_len);
734	ctl_enqueue_isc((union ctl_io *)ctsio);
735}
736
737static void
738ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
739				union ctl_ha_msg *msg_info)
740{
741	struct ctl_scsiio *ctsio;
742
743	if (msg_info->hdr.serializing_sc == NULL) {
744		printf("%s: serializing_sc == NULL!\n", __func__);
745		/* XXX KDM now what? */
746		return;
747	}
748
749	ctsio = &msg_info->hdr.serializing_sc->scsiio;
750	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
751	ctl_enqueue_isc((union ctl_io *)ctsio);
752}
753
754void
755ctl_isc_announce_lun(struct ctl_lun *lun)
756{
757	struct ctl_softc *softc = lun->ctl_softc;
758	union ctl_ha_msg *msg;
759	struct ctl_ha_msg_lun_pr_key pr_key;
760	int i, k;
761
762	if (softc->ha_link != CTL_HA_LINK_ONLINE)
763		return;
764	mtx_lock(&lun->lun_lock);
765	i = sizeof(msg->lun);
766	if (lun->lun_devid)
767		i += lun->lun_devid->len;
768	i += sizeof(pr_key) * lun->pr_key_count;
769alloc:
770	mtx_unlock(&lun->lun_lock);
771	msg = malloc(i, M_CTL, M_WAITOK);
772	mtx_lock(&lun->lun_lock);
773	k = sizeof(msg->lun);
774	if (lun->lun_devid)
775		k += lun->lun_devid->len;
776	k += sizeof(pr_key) * lun->pr_key_count;
777	if (i < k) {
778		free(msg, M_CTL);
779		i = k;
780		goto alloc;
781	}
782	bzero(&msg->lun, sizeof(msg->lun));
783	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
784	msg->hdr.nexus.targ_lun = lun->lun;
785	msg->hdr.nexus.targ_mapped_lun = lun->lun;
786	msg->lun.flags = lun->flags;
787	msg->lun.pr_generation = lun->pr_generation;
788	msg->lun.pr_res_idx = lun->pr_res_idx;
789	msg->lun.pr_res_type = lun->pr_res_type;
790	msg->lun.pr_key_count = lun->pr_key_count;
791	i = 0;
792	if (lun->lun_devid) {
793		msg->lun.lun_devid_len = lun->lun_devid->len;
794		memcpy(&msg->lun.data[i], lun->lun_devid->data,
795		    msg->lun.lun_devid_len);
796		i += msg->lun.lun_devid_len;
797	}
798	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
799		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
800			continue;
801		pr_key.pr_iid = k;
802		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
803		i += sizeof(pr_key);
804	}
805	mtx_unlock(&lun->lun_lock);
806	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
807	    M_WAITOK);
808	free(msg, M_CTL);
809
810	if (lun->flags & CTL_LUN_PRIMARY_SC) {
811		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
812			ctl_isc_announce_mode(lun, -1,
813			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
814			    lun->mode_pages.index[i].subpage);
815		}
816	}
817}
818
819void
820ctl_isc_announce_port(struct ctl_port *port)
821{
822	struct ctl_softc *softc = port->ctl_softc;
823	union ctl_ha_msg *msg;
824	int i;
825
826	if (port->targ_port < softc->port_min ||
827	    port->targ_port >= softc->port_max ||
828	    softc->ha_link != CTL_HA_LINK_ONLINE)
829		return;
830	i = sizeof(msg->port) + strlen(port->port_name) + 1;
831	if (port->lun_map)
832		i += port->lun_map_size * sizeof(uint32_t);
833	if (port->port_devid)
834		i += port->port_devid->len;
835	if (port->target_devid)
836		i += port->target_devid->len;
837	if (port->init_devid)
838		i += port->init_devid->len;
839	msg = malloc(i, M_CTL, M_WAITOK);
840	bzero(&msg->port, sizeof(msg->port));
841	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
842	msg->hdr.nexus.targ_port = port->targ_port;
843	msg->port.port_type = port->port_type;
844	msg->port.physical_port = port->physical_port;
845	msg->port.virtual_port = port->virtual_port;
846	msg->port.status = port->status;
847	i = 0;
848	msg->port.name_len = sprintf(&msg->port.data[i],
849	    "%d:%s", softc->ha_id, port->port_name) + 1;
850	i += msg->port.name_len;
851	if (port->lun_map) {
852		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
853		memcpy(&msg->port.data[i], port->lun_map,
854		    msg->port.lun_map_len);
855		i += msg->port.lun_map_len;
856	}
857	if (port->port_devid) {
858		msg->port.port_devid_len = port->port_devid->len;
859		memcpy(&msg->port.data[i], port->port_devid->data,
860		    msg->port.port_devid_len);
861		i += msg->port.port_devid_len;
862	}
863	if (port->target_devid) {
864		msg->port.target_devid_len = port->target_devid->len;
865		memcpy(&msg->port.data[i], port->target_devid->data,
866		    msg->port.target_devid_len);
867		i += msg->port.target_devid_len;
868	}
869	if (port->init_devid) {
870		msg->port.init_devid_len = port->init_devid->len;
871		memcpy(&msg->port.data[i], port->init_devid->data,
872		    msg->port.init_devid_len);
873		i += msg->port.init_devid_len;
874	}
875	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
876	    M_WAITOK);
877	free(msg, M_CTL);
878}
879
880void
881ctl_isc_announce_iid(struct ctl_port *port, int iid)
882{
883	struct ctl_softc *softc = port->ctl_softc;
884	union ctl_ha_msg *msg;
885	int i, l;
886
887	if (port->targ_port < softc->port_min ||
888	    port->targ_port >= softc->port_max ||
889	    softc->ha_link != CTL_HA_LINK_ONLINE)
890		return;
891	mtx_lock(&softc->ctl_lock);
892	i = sizeof(msg->iid);
893	l = 0;
894	if (port->wwpn_iid[iid].name)
895		l = strlen(port->wwpn_iid[iid].name) + 1;
896	i += l;
897	msg = malloc(i, M_CTL, M_NOWAIT);
898	if (msg == NULL) {
899		mtx_unlock(&softc->ctl_lock);
900		return;
901	}
902	bzero(&msg->iid, sizeof(msg->iid));
903	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
904	msg->hdr.nexus.targ_port = port->targ_port;
905	msg->hdr.nexus.initid = iid;
906	msg->iid.in_use = port->wwpn_iid[iid].in_use;
907	msg->iid.name_len = l;
908	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
909	if (port->wwpn_iid[iid].name)
910		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
911	mtx_unlock(&softc->ctl_lock);
912	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
913	free(msg, M_CTL);
914}
915
916void
917ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
918    uint8_t page, uint8_t subpage)
919{
920	struct ctl_softc *softc = lun->ctl_softc;
921	union ctl_ha_msg msg;
922	u_int i;
923
924	if (softc->ha_link != CTL_HA_LINK_ONLINE)
925		return;
926	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
927		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
928		    page && lun->mode_pages.index[i].subpage == subpage)
929			break;
930	}
931	if (i == CTL_NUM_MODE_PAGES)
932		return;
933
934	/* Don't try to replicate pages not present on this device. */
935	if (lun->mode_pages.index[i].page_data == NULL)
936		return;
937
938	bzero(&msg.mode, sizeof(msg.mode));
939	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
940	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
941	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
942	msg.hdr.nexus.targ_lun = lun->lun;
943	msg.hdr.nexus.targ_mapped_lun = lun->lun;
944	msg.mode.page_code = page;
945	msg.mode.subpage = subpage;
946	msg.mode.page_len = lun->mode_pages.index[i].page_len;
947	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
948	    msg.mode.page_len);
949	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
950	    M_WAITOK);
951}
952
953static void
954ctl_isc_ha_link_up(struct ctl_softc *softc)
955{
956	struct ctl_port *port;
957	struct ctl_lun *lun;
958	union ctl_ha_msg msg;
959	int i;
960
961	/* Announce this node parameters to peer for validation. */
962	msg.login.msg_type = CTL_MSG_LOGIN;
963	msg.login.version = CTL_HA_VERSION;
964	msg.login.ha_mode = softc->ha_mode;
965	msg.login.ha_id = softc->ha_id;
966	msg.login.max_luns = CTL_MAX_LUNS;
967	msg.login.max_ports = CTL_MAX_PORTS;
968	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
969	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
970	    M_WAITOK);
971
972	STAILQ_FOREACH(port, &softc->port_list, links) {
973		ctl_isc_announce_port(port);
974		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
975			if (port->wwpn_iid[i].in_use)
976				ctl_isc_announce_iid(port, i);
977		}
978	}
979	STAILQ_FOREACH(lun, &softc->lun_list, links)
980		ctl_isc_announce_lun(lun);
981}
982
983static void
984ctl_isc_ha_link_down(struct ctl_softc *softc)
985{
986	struct ctl_port *port;
987	struct ctl_lun *lun;
988	union ctl_io *io;
989	int i;
990
991	mtx_lock(&softc->ctl_lock);
992	STAILQ_FOREACH(lun, &softc->lun_list, links) {
993		mtx_lock(&lun->lun_lock);
994		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
995			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
996			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
997		}
998		mtx_unlock(&lun->lun_lock);
999
1000		mtx_unlock(&softc->ctl_lock);
1001		io = ctl_alloc_io(softc->othersc_pool);
1002		mtx_lock(&softc->ctl_lock);
1003		ctl_zero_io(io);
1004		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1005		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1006		ctl_enqueue_isc(io);
1007	}
1008
1009	STAILQ_FOREACH(port, &softc->port_list, links) {
1010		if (port->targ_port >= softc->port_min &&
1011		    port->targ_port < softc->port_max)
1012			continue;
1013		port->status &= ~CTL_PORT_STATUS_ONLINE;
1014		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1015			port->wwpn_iid[i].in_use = 0;
1016			free(port->wwpn_iid[i].name, M_CTL);
1017			port->wwpn_iid[i].name = NULL;
1018		}
1019	}
1020	mtx_unlock(&softc->ctl_lock);
1021}
1022
1023static void
1024ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1025{
1026	struct ctl_lun *lun;
1027	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1028
1029	mtx_lock(&softc->ctl_lock);
1030	if (msg->hdr.nexus.targ_mapped_lun >= CTL_MAX_LUNS ||
1031	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1032		mtx_unlock(&softc->ctl_lock);
1033		return;
1034	}
1035	mtx_lock(&lun->lun_lock);
1036	mtx_unlock(&softc->ctl_lock);
1037	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1038		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1039	if (msg->ua.ua_all) {
1040		if (msg->ua.ua_set)
1041			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1042		else
1043			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1044	} else {
1045		if (msg->ua.ua_set)
1046			ctl_est_ua(lun, iid, msg->ua.ua_type);
1047		else
1048			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1049	}
1050	mtx_unlock(&lun->lun_lock);
1051}
1052
1053static void
1054ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1055{
1056	struct ctl_lun *lun;
1057	struct ctl_ha_msg_lun_pr_key pr_key;
1058	int i, k;
1059	ctl_lun_flags oflags;
1060	uint32_t targ_lun;
1061
1062	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1063	mtx_lock(&softc->ctl_lock);
1064	if (targ_lun >= CTL_MAX_LUNS ||
1065	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1066		mtx_unlock(&softc->ctl_lock);
1067		return;
1068	}
1069	mtx_lock(&lun->lun_lock);
1070	mtx_unlock(&softc->ctl_lock);
1071	if (lun->flags & CTL_LUN_DISABLED) {
1072		mtx_unlock(&lun->lun_lock);
1073		return;
1074	}
1075	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1076	if (msg->lun.lun_devid_len != i || (i > 0 &&
1077	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1078		mtx_unlock(&lun->lun_lock);
1079		printf("%s: Received conflicting HA LUN %d\n",
1080		    __func__, targ_lun);
1081		return;
1082	} else {
1083		/* Record whether peer is primary. */
1084		oflags = lun->flags;
1085		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1086		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1087			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1088		else
1089			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1090		if (oflags != lun->flags)
1091			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1092
1093		/* If peer is primary and we are not -- use data */
1094		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1095		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1096			lun->pr_generation = msg->lun.pr_generation;
1097			lun->pr_res_idx = msg->lun.pr_res_idx;
1098			lun->pr_res_type = msg->lun.pr_res_type;
1099			lun->pr_key_count = msg->lun.pr_key_count;
1100			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1101				ctl_clr_prkey(lun, k);
1102			for (k = 0; k < msg->lun.pr_key_count; k++) {
1103				memcpy(&pr_key, &msg->lun.data[i],
1104				    sizeof(pr_key));
1105				ctl_alloc_prkey(lun, pr_key.pr_iid);
1106				ctl_set_prkey(lun, pr_key.pr_iid,
1107				    pr_key.pr_key);
1108				i += sizeof(pr_key);
1109			}
1110		}
1111
1112		mtx_unlock(&lun->lun_lock);
1113		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1114		    __func__, targ_lun,
1115		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1116		    "primary" : "secondary"));
1117
1118		/* If we are primary but peer doesn't know -- notify */
1119		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1120		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1121			ctl_isc_announce_lun(lun);
1122	}
1123}
1124
1125static void
1126ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1127{
1128	struct ctl_port *port;
1129	struct ctl_lun *lun;
1130	int i, new;
1131
1132	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1133	if (port == NULL) {
1134		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1135		    msg->hdr.nexus.targ_port));
1136		new = 1;
1137		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1138		port->frontend = &ha_frontend;
1139		port->targ_port = msg->hdr.nexus.targ_port;
1140		port->fe_datamove = ctl_ha_datamove;
1141		port->fe_done = ctl_ha_done;
1142	} else if (port->frontend == &ha_frontend) {
1143		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1144		    msg->hdr.nexus.targ_port));
1145		new = 0;
1146	} else {
1147		printf("%s: Received conflicting HA port %d\n",
1148		    __func__, msg->hdr.nexus.targ_port);
1149		return;
1150	}
1151	port->port_type = msg->port.port_type;
1152	port->physical_port = msg->port.physical_port;
1153	port->virtual_port = msg->port.virtual_port;
1154	port->status = msg->port.status;
1155	i = 0;
1156	free(port->port_name, M_CTL);
1157	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1158	    M_CTL);
1159	i += msg->port.name_len;
1160	if (msg->port.lun_map_len != 0) {
1161		if (port->lun_map == NULL ||
1162		    port->lun_map_size * sizeof(uint32_t) <
1163		    msg->port.lun_map_len) {
1164			port->lun_map_size = 0;
1165			free(port->lun_map, M_CTL);
1166			port->lun_map = malloc(msg->port.lun_map_len,
1167			    M_CTL, M_WAITOK);
1168		}
1169		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1170		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1171		i += msg->port.lun_map_len;
1172	} else {
1173		port->lun_map_size = 0;
1174		free(port->lun_map, M_CTL);
1175		port->lun_map = NULL;
1176	}
1177	if (msg->port.port_devid_len != 0) {
1178		if (port->port_devid == NULL ||
1179		    port->port_devid->len < msg->port.port_devid_len) {
1180			free(port->port_devid, M_CTL);
1181			port->port_devid = malloc(sizeof(struct ctl_devid) +
1182			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1183		}
1184		memcpy(port->port_devid->data, &msg->port.data[i],
1185		    msg->port.port_devid_len);
1186		port->port_devid->len = msg->port.port_devid_len;
1187		i += msg->port.port_devid_len;
1188	} else {
1189		free(port->port_devid, M_CTL);
1190		port->port_devid = NULL;
1191	}
1192	if (msg->port.target_devid_len != 0) {
1193		if (port->target_devid == NULL ||
1194		    port->target_devid->len < msg->port.target_devid_len) {
1195			free(port->target_devid, M_CTL);
1196			port->target_devid = malloc(sizeof(struct ctl_devid) +
1197			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1198		}
1199		memcpy(port->target_devid->data, &msg->port.data[i],
1200		    msg->port.target_devid_len);
1201		port->target_devid->len = msg->port.target_devid_len;
1202		i += msg->port.target_devid_len;
1203	} else {
1204		free(port->target_devid, M_CTL);
1205		port->target_devid = NULL;
1206	}
1207	if (msg->port.init_devid_len != 0) {
1208		if (port->init_devid == NULL ||
1209		    port->init_devid->len < msg->port.init_devid_len) {
1210			free(port->init_devid, M_CTL);
1211			port->init_devid = malloc(sizeof(struct ctl_devid) +
1212			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1213		}
1214		memcpy(port->init_devid->data, &msg->port.data[i],
1215		    msg->port.init_devid_len);
1216		port->init_devid->len = msg->port.init_devid_len;
1217		i += msg->port.init_devid_len;
1218	} else {
1219		free(port->init_devid, M_CTL);
1220		port->init_devid = NULL;
1221	}
1222	if (new) {
1223		if (ctl_port_register(port) != 0) {
1224			printf("%s: ctl_port_register() failed with error\n",
1225			    __func__);
1226		}
1227	}
1228	mtx_lock(&softc->ctl_lock);
1229	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1230		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1231			continue;
1232		mtx_lock(&lun->lun_lock);
1233		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1234		mtx_unlock(&lun->lun_lock);
1235	}
1236	mtx_unlock(&softc->ctl_lock);
1237}
1238
1239static void
1240ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1241{
1242	struct ctl_port *port;
1243	int iid;
1244
1245	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1246	if (port == NULL) {
1247		printf("%s: Received IID for unknown port %d\n",
1248		    __func__, msg->hdr.nexus.targ_port);
1249		return;
1250	}
1251	iid = msg->hdr.nexus.initid;
1252	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1253	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1254	free(port->wwpn_iid[iid].name, M_CTL);
1255	if (msg->iid.name_len) {
1256		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1257		    msg->iid.name_len, M_CTL);
1258	} else
1259		port->wwpn_iid[iid].name = NULL;
1260}
1261
1262static void
1263ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1264{
1265
1266	if (msg->login.version != CTL_HA_VERSION) {
1267		printf("CTL HA peers have different versions %d != %d\n",
1268		    msg->login.version, CTL_HA_VERSION);
1269		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1270		return;
1271	}
1272	if (msg->login.ha_mode != softc->ha_mode) {
1273		printf("CTL HA peers have different ha_mode %d != %d\n",
1274		    msg->login.ha_mode, softc->ha_mode);
1275		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1276		return;
1277	}
1278	if (msg->login.ha_id == softc->ha_id) {
1279		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1280		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1281		return;
1282	}
1283	if (msg->login.max_luns != CTL_MAX_LUNS ||
1284	    msg->login.max_ports != CTL_MAX_PORTS ||
1285	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1286		printf("CTL HA peers have different limits\n");
1287		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1288		return;
1289	}
1290}
1291
1292static void
1293ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1294{
1295	struct ctl_lun *lun;
1296	u_int i;
1297	uint32_t initidx, targ_lun;
1298
1299	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1300	mtx_lock(&softc->ctl_lock);
1301	if (targ_lun >= CTL_MAX_LUNS ||
1302	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1303		mtx_unlock(&softc->ctl_lock);
1304		return;
1305	}
1306	mtx_lock(&lun->lun_lock);
1307	mtx_unlock(&softc->ctl_lock);
1308	if (lun->flags & CTL_LUN_DISABLED) {
1309		mtx_unlock(&lun->lun_lock);
1310		return;
1311	}
1312	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1313		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1314		    msg->mode.page_code &&
1315		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1316			break;
1317	}
1318	if (i == CTL_NUM_MODE_PAGES) {
1319		mtx_unlock(&lun->lun_lock);
1320		return;
1321	}
1322	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1323	    lun->mode_pages.index[i].page_len);
1324	initidx = ctl_get_initindex(&msg->hdr.nexus);
1325	if (initidx != -1)
1326		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1327	mtx_unlock(&lun->lun_lock);
1328}
1329
1330/*
1331 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1332 * subsystem come in here.
1333 */
1334static void
1335ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1336{
1337	struct ctl_softc *softc = control_softc;
1338	union ctl_io *io;
1339	struct ctl_prio *presio;
1340	ctl_ha_status isc_status;
1341
1342	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1343	if (event == CTL_HA_EVT_MSG_RECV) {
1344		union ctl_ha_msg *msg, msgbuf;
1345
1346		if (param > sizeof(msgbuf))
1347			msg = malloc(param, M_CTL, M_WAITOK);
1348		else
1349			msg = &msgbuf;
1350		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1351		    M_WAITOK);
1352		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1353			printf("%s: Error receiving message: %d\n",
1354			    __func__, isc_status);
1355			if (msg != &msgbuf)
1356				free(msg, M_CTL);
1357			return;
1358		}
1359
1360		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1361		switch (msg->hdr.msg_type) {
1362		case CTL_MSG_SERIALIZE:
1363			io = ctl_alloc_io(softc->othersc_pool);
1364			ctl_zero_io(io);
1365			// populate ctsio from msg
1366			io->io_hdr.io_type = CTL_IO_SCSI;
1367			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1368			io->io_hdr.original_sc = msg->hdr.original_sc;
1369			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1370					    CTL_FLAG_IO_ACTIVE;
1371			/*
1372			 * If we're in serialization-only mode, we don't
1373			 * want to go through full done processing.  Thus
1374			 * the COPY flag.
1375			 *
1376			 * XXX KDM add another flag that is more specific.
1377			 */
1378			if (softc->ha_mode != CTL_HA_MODE_XFER)
1379				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1380			io->io_hdr.nexus = msg->hdr.nexus;
1381#if 0
1382			printf("port %u, iid %u, lun %u\n",
1383			       io->io_hdr.nexus.targ_port,
1384			       io->io_hdr.nexus.initid,
1385			       io->io_hdr.nexus.targ_lun);
1386#endif
1387			io->scsiio.tag_num = msg->scsi.tag_num;
1388			io->scsiio.tag_type = msg->scsi.tag_type;
1389#ifdef CTL_TIME_IO
1390			io->io_hdr.start_time = time_uptime;
1391			getbinuptime(&io->io_hdr.start_bt);
1392#endif /* CTL_TIME_IO */
1393			io->scsiio.cdb_len = msg->scsi.cdb_len;
1394			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1395			       CTL_MAX_CDBLEN);
1396			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1397				const struct ctl_cmd_entry *entry;
1398
1399				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1400				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1401				io->io_hdr.flags |=
1402					entry->flags & CTL_FLAG_DATA_MASK;
1403			}
1404			ctl_enqueue_isc(io);
1405			break;
1406
1407		/* Performed on the Originating SC, XFER mode only */
1408		case CTL_MSG_DATAMOVE: {
1409			struct ctl_sg_entry *sgl;
1410			int i, j;
1411
1412			io = msg->hdr.original_sc;
1413			if (io == NULL) {
1414				printf("%s: original_sc == NULL!\n", __func__);
1415				/* XXX KDM do something here */
1416				break;
1417			}
1418			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1419			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1420			/*
1421			 * Keep track of this, we need to send it back over
1422			 * when the datamove is complete.
1423			 */
1424			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1425			if (msg->hdr.status == CTL_SUCCESS)
1426				io->io_hdr.status = msg->hdr.status;
1427
1428			if (msg->dt.sg_sequence == 0) {
1429#ifdef CTL_TIME_IO
1430				getbinuptime(&io->io_hdr.dma_start_bt);
1431#endif
1432				i = msg->dt.kern_sg_entries +
1433				    msg->dt.kern_data_len /
1434				    CTL_HA_DATAMOVE_SEGMENT + 1;
1435				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1436				    M_WAITOK | M_ZERO);
1437				io->io_hdr.remote_sglist = sgl;
1438				io->io_hdr.local_sglist =
1439				    &sgl[msg->dt.kern_sg_entries];
1440
1441				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1442
1443				io->scsiio.kern_sg_entries =
1444					msg->dt.kern_sg_entries;
1445				io->scsiio.rem_sg_entries =
1446					msg->dt.kern_sg_entries;
1447				io->scsiio.kern_data_len =
1448					msg->dt.kern_data_len;
1449				io->scsiio.kern_total_len =
1450					msg->dt.kern_total_len;
1451				io->scsiio.kern_data_resid =
1452					msg->dt.kern_data_resid;
1453				io->scsiio.kern_rel_offset =
1454					msg->dt.kern_rel_offset;
1455				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1456				io->io_hdr.flags |= msg->dt.flags &
1457				    CTL_FLAG_BUS_ADDR;
1458			} else
1459				sgl = (struct ctl_sg_entry *)
1460					io->scsiio.kern_data_ptr;
1461
1462			for (i = msg->dt.sent_sg_entries, j = 0;
1463			     i < (msg->dt.sent_sg_entries +
1464			     msg->dt.cur_sg_entries); i++, j++) {
1465				sgl[i].addr = msg->dt.sg_list[j].addr;
1466				sgl[i].len = msg->dt.sg_list[j].len;
1467
1468#if 0
1469				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1470				    __func__, sgl[i].addr, sgl[i].len, j, i);
1471#endif
1472			}
1473
1474			/*
1475			 * If this is the last piece of the I/O, we've got
1476			 * the full S/G list.  Queue processing in the thread.
1477			 * Otherwise wait for the next piece.
1478			 */
1479			if (msg->dt.sg_last != 0)
1480				ctl_enqueue_isc(io);
1481			break;
1482		}
1483		/* Performed on the Serializing (primary) SC, XFER mode only */
1484		case CTL_MSG_DATAMOVE_DONE: {
1485			if (msg->hdr.serializing_sc == NULL) {
1486				printf("%s: serializing_sc == NULL!\n",
1487				       __func__);
1488				/* XXX KDM now what? */
1489				break;
1490			}
1491			/*
1492			 * We grab the sense information here in case
1493			 * there was a failure, so we can return status
1494			 * back to the initiator.
1495			 */
1496			io = msg->hdr.serializing_sc;
1497			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1498			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1499			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1500			io->io_hdr.port_status = msg->scsi.fetd_status;
1501			io->scsiio.residual = msg->scsi.residual;
1502			if (msg->hdr.status != CTL_STATUS_NONE) {
1503				io->io_hdr.status = msg->hdr.status;
1504				io->scsiio.scsi_status = msg->scsi.scsi_status;
1505				io->scsiio.sense_len = msg->scsi.sense_len;
1506				io->scsiio.sense_residual =msg->scsi.sense_residual;
1507				memcpy(&io->scsiio.sense_data,
1508				    &msg->scsi.sense_data,
1509				    msg->scsi.sense_len);
1510				if (msg->hdr.status == CTL_SUCCESS)
1511					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1512			}
1513			ctl_enqueue_isc(io);
1514			break;
1515		}
1516
1517		/* Preformed on Originating SC, SER_ONLY mode */
1518		case CTL_MSG_R2R:
1519			io = msg->hdr.original_sc;
1520			if (io == NULL) {
1521				printf("%s: original_sc == NULL!\n",
1522				    __func__);
1523				break;
1524			}
1525			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1526			io->io_hdr.msg_type = CTL_MSG_R2R;
1527			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1528			ctl_enqueue_isc(io);
1529			break;
1530
1531		/*
1532		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1533		 * mode.
1534		 * Performed on the Originating (i.e. secondary) SC in XFER
1535		 * mode
1536		 */
1537		case CTL_MSG_FINISH_IO:
1538			if (softc->ha_mode == CTL_HA_MODE_XFER)
1539				ctl_isc_handler_finish_xfer(softc, msg);
1540			else
1541				ctl_isc_handler_finish_ser_only(softc, msg);
1542			break;
1543
1544		/* Preformed on Originating SC */
1545		case CTL_MSG_BAD_JUJU:
1546			io = msg->hdr.original_sc;
1547			if (io == NULL) {
1548				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1549				       __func__);
1550				break;
1551			}
1552			ctl_copy_sense_data(msg, io);
1553			/*
1554			 * IO should have already been cleaned up on other
1555			 * SC so clear this flag so we won't send a message
1556			 * back to finish the IO there.
1557			 */
1558			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1559			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1560
1561			/* io = msg->hdr.serializing_sc; */
1562			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1563			ctl_enqueue_isc(io);
1564			break;
1565
1566		/* Handle resets sent from the other side */
1567		case CTL_MSG_MANAGE_TASKS: {
1568			struct ctl_taskio *taskio;
1569			taskio = (struct ctl_taskio *)ctl_alloc_io(
1570			    softc->othersc_pool);
1571			ctl_zero_io((union ctl_io *)taskio);
1572			taskio->io_hdr.io_type = CTL_IO_TASK;
1573			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1574			taskio->io_hdr.nexus = msg->hdr.nexus;
1575			taskio->task_action = msg->task.task_action;
1576			taskio->tag_num = msg->task.tag_num;
1577			taskio->tag_type = msg->task.tag_type;
1578#ifdef CTL_TIME_IO
1579			taskio->io_hdr.start_time = time_uptime;
1580			getbinuptime(&taskio->io_hdr.start_bt);
1581#endif /* CTL_TIME_IO */
1582			ctl_run_task((union ctl_io *)taskio);
1583			break;
1584		}
1585		/* Persistent Reserve action which needs attention */
1586		case CTL_MSG_PERS_ACTION:
1587			presio = (struct ctl_prio *)ctl_alloc_io(
1588			    softc->othersc_pool);
1589			ctl_zero_io((union ctl_io *)presio);
1590			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1591			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1592			presio->io_hdr.nexus = msg->hdr.nexus;
1593			presio->pr_msg = msg->pr;
1594			ctl_enqueue_isc((union ctl_io *)presio);
1595			break;
1596		case CTL_MSG_UA:
1597			ctl_isc_ua(softc, msg, param);
1598			break;
1599		case CTL_MSG_PORT_SYNC:
1600			ctl_isc_port_sync(softc, msg, param);
1601			break;
1602		case CTL_MSG_LUN_SYNC:
1603			ctl_isc_lun_sync(softc, msg, param);
1604			break;
1605		case CTL_MSG_IID_SYNC:
1606			ctl_isc_iid_sync(softc, msg, param);
1607			break;
1608		case CTL_MSG_LOGIN:
1609			ctl_isc_login(softc, msg, param);
1610			break;
1611		case CTL_MSG_MODE_SYNC:
1612			ctl_isc_mode_sync(softc, msg, param);
1613			break;
1614		default:
1615			printf("Received HA message of unknown type %d\n",
1616			    msg->hdr.msg_type);
1617			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1618			break;
1619		}
1620		if (msg != &msgbuf)
1621			free(msg, M_CTL);
1622	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1623		printf("CTL: HA link status changed from %d to %d\n",
1624		    softc->ha_link, param);
1625		if (param == softc->ha_link)
1626			return;
1627		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1628			softc->ha_link = param;
1629			ctl_isc_ha_link_down(softc);
1630		} else {
1631			softc->ha_link = param;
1632			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1633				ctl_isc_ha_link_up(softc);
1634		}
1635		return;
1636	} else {
1637		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1638		return;
1639	}
1640}
1641
1642static void
1643ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1644{
1645
1646	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1647	    src->scsi.sense_len);
1648	dest->scsiio.scsi_status = src->scsi.scsi_status;
1649	dest->scsiio.sense_len = src->scsi.sense_len;
1650	dest->io_hdr.status = src->hdr.status;
1651}
1652
1653static void
1654ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1655{
1656
1657	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1658	    src->scsiio.sense_len);
1659	dest->scsi.scsi_status = src->scsiio.scsi_status;
1660	dest->scsi.sense_len = src->scsiio.sense_len;
1661	dest->hdr.status = src->io_hdr.status;
1662}
1663
1664void
1665ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1666{
1667	struct ctl_softc *softc = lun->ctl_softc;
1668	ctl_ua_type *pu;
1669
1670	if (initidx < softc->init_min || initidx >= softc->init_max)
1671		return;
1672	mtx_assert(&lun->lun_lock, MA_OWNED);
1673	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1674	if (pu == NULL)
1675		return;
1676	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1677}
1678
1679void
1680ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1681{
1682	int i;
1683
1684	mtx_assert(&lun->lun_lock, MA_OWNED);
1685	if (lun->pending_ua[port] == NULL)
1686		return;
1687	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1688		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1689			continue;
1690		lun->pending_ua[port][i] |= ua;
1691	}
1692}
1693
1694void
1695ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1696{
1697	struct ctl_softc *softc = lun->ctl_softc;
1698	int i;
1699
1700	mtx_assert(&lun->lun_lock, MA_OWNED);
1701	for (i = softc->port_min; i < softc->port_max; i++)
1702		ctl_est_ua_port(lun, i, except, ua);
1703}
1704
1705void
1706ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1707{
1708	struct ctl_softc *softc = lun->ctl_softc;
1709	ctl_ua_type *pu;
1710
1711	if (initidx < softc->init_min || initidx >= softc->init_max)
1712		return;
1713	mtx_assert(&lun->lun_lock, MA_OWNED);
1714	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1715	if (pu == NULL)
1716		return;
1717	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1718}
1719
1720void
1721ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1722{
1723	struct ctl_softc *softc = lun->ctl_softc;
1724	int i, j;
1725
1726	mtx_assert(&lun->lun_lock, MA_OWNED);
1727	for (i = softc->port_min; i < softc->port_max; i++) {
1728		if (lun->pending_ua[i] == NULL)
1729			continue;
1730		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1731			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1732				continue;
1733			lun->pending_ua[i][j] &= ~ua;
1734		}
1735	}
1736}
1737
1738void
1739ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1740    ctl_ua_type ua_type)
1741{
1742	struct ctl_lun *lun;
1743
1744	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1745	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1746		mtx_lock(&lun->lun_lock);
1747		ctl_clr_ua(lun, initidx, ua_type);
1748		mtx_unlock(&lun->lun_lock);
1749	}
1750}
1751
1752static int
1753ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1754{
1755	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1756	struct ctl_lun *lun;
1757	struct ctl_lun_req ireq;
1758	int error, value;
1759
1760	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1761	error = sysctl_handle_int(oidp, &value, 0, req);
1762	if ((error != 0) || (req->newptr == NULL))
1763		return (error);
1764
1765	mtx_lock(&softc->ctl_lock);
1766	if (value == 0)
1767		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1768	else
1769		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1770	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1771		mtx_unlock(&softc->ctl_lock);
1772		bzero(&ireq, sizeof(ireq));
1773		ireq.reqtype = CTL_LUNREQ_MODIFY;
1774		ireq.reqdata.modify.lun_id = lun->lun;
1775		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1776		    curthread);
1777		if (ireq.status != CTL_LUN_OK) {
1778			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1779			    __func__, ireq.status, ireq.error_str);
1780		}
1781		mtx_lock(&softc->ctl_lock);
1782	}
1783	mtx_unlock(&softc->ctl_lock);
1784	return (0);
1785}
1786
1787static int
1788ctl_init(void)
1789{
1790	struct make_dev_args args;
1791	struct ctl_softc *softc;
1792	void *other_pool;
1793	int i, error;
1794
1795	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1796			       M_WAITOK | M_ZERO);
1797
1798	make_dev_args_init(&args);
1799	args.mda_devsw = &ctl_cdevsw;
1800	args.mda_uid = UID_ROOT;
1801	args.mda_gid = GID_OPERATOR;
1802	args.mda_mode = 0600;
1803	args.mda_si_drv1 = softc;
1804	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1805	if (error != 0) {
1806		free(softc, M_DEVBUF);
1807		control_softc = NULL;
1808		return (error);
1809	}
1810
1811	sysctl_ctx_init(&softc->sysctl_ctx);
1812	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1813		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1814		CTLFLAG_RD, 0, "CAM Target Layer");
1815
1816	if (softc->sysctl_tree == NULL) {
1817		printf("%s: unable to allocate sysctl tree\n", __func__);
1818		destroy_dev(softc->dev);
1819		free(softc, M_DEVBUF);
1820		control_softc = NULL;
1821		return (ENOMEM);
1822	}
1823
1824	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1825	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1826	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1827	softc->flags = 0;
1828
1829	TUNABLE_INT_FETCH("kern.cam.ctl.ha_mode", (int *)&softc->ha_mode);
1830	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1831	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1832	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1833
1834	/*
1835	 * In Copan's HA scheme, the "master" and "slave" roles are
1836	 * figured out through the slot the controller is in.  Although it
1837	 * is an active/active system, someone has to be in charge.
1838	 */
1839	TUNABLE_INT_FETCH("kern.cam.ctl.ha_id", &softc->ha_id);
1840	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1841	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1842	    "HA head ID (0 - no HA)");
1843	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1844		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1845		softc->is_single = 1;
1846		softc->port_cnt = CTL_MAX_PORTS;
1847		softc->port_min = 0;
1848	} else {
1849		softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1850		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1851	}
1852	softc->port_max = softc->port_min + softc->port_cnt;
1853	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1854	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1855
1856	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1857	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1858	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1859
1860	STAILQ_INIT(&softc->lun_list);
1861	STAILQ_INIT(&softc->pending_lun_queue);
1862	STAILQ_INIT(&softc->fe_list);
1863	STAILQ_INIT(&softc->port_list);
1864	STAILQ_INIT(&softc->be_list);
1865	ctl_tpc_init(softc);
1866
1867	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1868	                    &other_pool) != 0)
1869	{
1870		printf("ctl: can't allocate %d entry other SC pool, "
1871		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1872		return (ENOMEM);
1873	}
1874	softc->othersc_pool = other_pool;
1875
1876	if (worker_threads <= 0)
1877		worker_threads = max(1, mp_ncpus / 4);
1878	if (worker_threads > CTL_MAX_THREADS)
1879		worker_threads = CTL_MAX_THREADS;
1880
1881	for (i = 0; i < worker_threads; i++) {
1882		struct ctl_thread *thr = &softc->threads[i];
1883
1884		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1885		thr->ctl_softc = softc;
1886		STAILQ_INIT(&thr->incoming_queue);
1887		STAILQ_INIT(&thr->rtr_queue);
1888		STAILQ_INIT(&thr->done_queue);
1889		STAILQ_INIT(&thr->isc_queue);
1890
1891		error = kproc_kthread_add(ctl_work_thread, thr,
1892		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1893		if (error != 0) {
1894			printf("error creating CTL work thread!\n");
1895			ctl_pool_free(other_pool);
1896			return (error);
1897		}
1898	}
1899	error = kproc_kthread_add(ctl_lun_thread, softc,
1900	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1901	if (error != 0) {
1902		printf("error creating CTL lun thread!\n");
1903		ctl_pool_free(other_pool);
1904		return (error);
1905	}
1906	error = kproc_kthread_add(ctl_thresh_thread, softc,
1907	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1908	if (error != 0) {
1909		printf("error creating CTL threshold thread!\n");
1910		ctl_pool_free(other_pool);
1911		return (error);
1912	}
1913
1914	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1915	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1916	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1917
1918	if (softc->is_single == 0) {
1919		ctl_frontend_register(&ha_frontend);
1920		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1921			printf("ctl_init: ctl_ha_msg_init failed.\n");
1922			softc->is_single = 1;
1923		} else
1924		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1925		    != CTL_HA_STATUS_SUCCESS) {
1926			printf("ctl_init: ctl_ha_msg_register failed.\n");
1927			softc->is_single = 1;
1928		}
1929	}
1930	return (0);
1931}
1932
1933void
1934ctl_shutdown(void)
1935{
1936	struct ctl_softc *softc = control_softc;
1937	struct ctl_lun *lun, *next_lun;
1938
1939	if (softc->is_single == 0) {
1940		ctl_ha_msg_shutdown(softc);
1941		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1942		    != CTL_HA_STATUS_SUCCESS)
1943			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1944		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1945			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1946		ctl_frontend_deregister(&ha_frontend);
1947	}
1948
1949	mtx_lock(&softc->ctl_lock);
1950
1951	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1952		ctl_free_lun(lun);
1953
1954	mtx_unlock(&softc->ctl_lock);
1955
1956#if 0
1957	ctl_shutdown_thread(softc->work_thread);
1958	mtx_destroy(&softc->queue_lock);
1959#endif
1960
1961	ctl_tpc_shutdown(softc);
1962	uma_zdestroy(softc->io_zone);
1963	mtx_destroy(&softc->ctl_lock);
1964
1965	destroy_dev(softc->dev);
1966
1967	sysctl_ctx_free(&softc->sysctl_ctx);
1968
1969	free(softc, M_DEVBUF);
1970	control_softc = NULL;
1971}
1972
1973static int
1974ctl_module_event_handler(module_t mod, int what, void *arg)
1975{
1976
1977	switch (what) {
1978	case MOD_LOAD:
1979		return (ctl_init());
1980	case MOD_UNLOAD:
1981		return (EBUSY);
1982	default:
1983		return (EOPNOTSUPP);
1984	}
1985}
1986
1987/*
1988 * XXX KDM should we do some access checks here?  Bump a reference count to
1989 * prevent a CTL module from being unloaded while someone has it open?
1990 */
1991static int
1992ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1993{
1994	return (0);
1995}
1996
1997static int
1998ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1999{
2000	return (0);
2001}
2002
2003/*
2004 * Remove an initiator by port number and initiator ID.
2005 * Returns 0 for success, -1 for failure.
2006 */
2007int
2008ctl_remove_initiator(struct ctl_port *port, int iid)
2009{
2010	struct ctl_softc *softc = port->ctl_softc;
2011
2012	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2013
2014	if (iid > CTL_MAX_INIT_PER_PORT) {
2015		printf("%s: initiator ID %u > maximun %u!\n",
2016		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2017		return (-1);
2018	}
2019
2020	mtx_lock(&softc->ctl_lock);
2021	port->wwpn_iid[iid].in_use--;
2022	port->wwpn_iid[iid].last_use = time_uptime;
2023	mtx_unlock(&softc->ctl_lock);
2024	ctl_isc_announce_iid(port, iid);
2025
2026	return (0);
2027}
2028
2029/*
2030 * Add an initiator to the initiator map.
2031 * Returns iid for success, < 0 for failure.
2032 */
2033int
2034ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2035{
2036	struct ctl_softc *softc = port->ctl_softc;
2037	time_t best_time;
2038	int i, best;
2039
2040	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2041
2042	if (iid >= CTL_MAX_INIT_PER_PORT) {
2043		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2044		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2045		free(name, M_CTL);
2046		return (-1);
2047	}
2048
2049	mtx_lock(&softc->ctl_lock);
2050
2051	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2052		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2053			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2054				iid = i;
2055				break;
2056			}
2057			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2058			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2059				iid = i;
2060				break;
2061			}
2062		}
2063	}
2064
2065	if (iid < 0) {
2066		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2067			if (port->wwpn_iid[i].in_use == 0 &&
2068			    port->wwpn_iid[i].wwpn == 0 &&
2069			    port->wwpn_iid[i].name == NULL) {
2070				iid = i;
2071				break;
2072			}
2073		}
2074	}
2075
2076	if (iid < 0) {
2077		best = -1;
2078		best_time = INT32_MAX;
2079		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2080			if (port->wwpn_iid[i].in_use == 0) {
2081				if (port->wwpn_iid[i].last_use < best_time) {
2082					best = i;
2083					best_time = port->wwpn_iid[i].last_use;
2084				}
2085			}
2086		}
2087		iid = best;
2088	}
2089
2090	if (iid < 0) {
2091		mtx_unlock(&softc->ctl_lock);
2092		free(name, M_CTL);
2093		return (-2);
2094	}
2095
2096	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2097		/*
2098		 * This is not an error yet.
2099		 */
2100		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2101#if 0
2102			printf("%s: port %d iid %u WWPN %#jx arrived"
2103			    " again\n", __func__, port->targ_port,
2104			    iid, (uintmax_t)wwpn);
2105#endif
2106			goto take;
2107		}
2108		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2109		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2110#if 0
2111			printf("%s: port %d iid %u name '%s' arrived"
2112			    " again\n", __func__, port->targ_port,
2113			    iid, name);
2114#endif
2115			goto take;
2116		}
2117
2118		/*
2119		 * This is an error, but what do we do about it?  The
2120		 * driver is telling us we have a new WWPN for this
2121		 * initiator ID, so we pretty much need to use it.
2122		 */
2123		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2124		    " but WWPN %#jx '%s' is still at that address\n",
2125		    __func__, port->targ_port, iid, wwpn, name,
2126		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2127		    port->wwpn_iid[iid].name);
2128
2129		/*
2130		 * XXX KDM clear have_ca and ua_pending on each LUN for
2131		 * this initiator.
2132		 */
2133	}
2134take:
2135	free(port->wwpn_iid[iid].name, M_CTL);
2136	port->wwpn_iid[iid].name = name;
2137	port->wwpn_iid[iid].wwpn = wwpn;
2138	port->wwpn_iid[iid].in_use++;
2139	mtx_unlock(&softc->ctl_lock);
2140	ctl_isc_announce_iid(port, iid);
2141
2142	return (iid);
2143}
2144
2145static int
2146ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2147{
2148	int len;
2149
2150	switch (port->port_type) {
2151	case CTL_PORT_FC:
2152	{
2153		struct scsi_transportid_fcp *id =
2154		    (struct scsi_transportid_fcp *)buf;
2155		if (port->wwpn_iid[iid].wwpn == 0)
2156			return (0);
2157		memset(id, 0, sizeof(*id));
2158		id->format_protocol = SCSI_PROTO_FC;
2159		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2160		return (sizeof(*id));
2161	}
2162	case CTL_PORT_ISCSI:
2163	{
2164		struct scsi_transportid_iscsi_port *id =
2165		    (struct scsi_transportid_iscsi_port *)buf;
2166		if (port->wwpn_iid[iid].name == NULL)
2167			return (0);
2168		memset(id, 0, 256);
2169		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2170		    SCSI_PROTO_ISCSI;
2171		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2172		len = roundup2(min(len, 252), 4);
2173		scsi_ulto2b(len, id->additional_length);
2174		return (sizeof(*id) + len);
2175	}
2176	case CTL_PORT_SAS:
2177	{
2178		struct scsi_transportid_sas *id =
2179		    (struct scsi_transportid_sas *)buf;
2180		if (port->wwpn_iid[iid].wwpn == 0)
2181			return (0);
2182		memset(id, 0, sizeof(*id));
2183		id->format_protocol = SCSI_PROTO_SAS;
2184		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2185		return (sizeof(*id));
2186	}
2187	default:
2188	{
2189		struct scsi_transportid_spi *id =
2190		    (struct scsi_transportid_spi *)buf;
2191		memset(id, 0, sizeof(*id));
2192		id->format_protocol = SCSI_PROTO_SPI;
2193		scsi_ulto2b(iid, id->scsi_addr);
2194		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2195		return (sizeof(*id));
2196	}
2197	}
2198}
2199
2200/*
2201 * Serialize a command that went down the "wrong" side, and so was sent to
2202 * this controller for execution.  The logic is a little different than the
2203 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2204 * sent back to the other side, but in the success case, we execute the
2205 * command on this side (XFER mode) or tell the other side to execute it
2206 * (SER_ONLY mode).
2207 */
2208static void
2209ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2210{
2211	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2212	struct ctl_port *port = CTL_PORT(ctsio);
2213	union ctl_ha_msg msg_info;
2214	struct ctl_lun *lun;
2215	const struct ctl_cmd_entry *entry;
2216	uint32_t targ_lun;
2217
2218	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2219
2220	/* Make sure that we know about this port. */
2221	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2222		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2223					 /*retry_count*/ 1);
2224		goto badjuju;
2225	}
2226
2227	/* Make sure that we know about this LUN. */
2228	mtx_lock(&softc->ctl_lock);
2229	if (targ_lun >= CTL_MAX_LUNS ||
2230	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2231		mtx_unlock(&softc->ctl_lock);
2232
2233		/*
2234		 * The other node would not send this request to us unless
2235		 * received announce that we are primary node for this LUN.
2236		 * If this LUN does not exist now, it is probably result of
2237		 * a race, so respond to initiator in the most opaque way.
2238		 */
2239		ctl_set_busy(ctsio);
2240		goto badjuju;
2241	}
2242	mtx_lock(&lun->lun_lock);
2243	mtx_unlock(&softc->ctl_lock);
2244
2245	/*
2246	 * If the LUN is invalid, pretend that it doesn't exist.
2247	 * It will go away as soon as all pending I/Os completed.
2248	 */
2249	if (lun->flags & CTL_LUN_DISABLED) {
2250		mtx_unlock(&lun->lun_lock);
2251		ctl_set_busy(ctsio);
2252		goto badjuju;
2253	}
2254
2255	entry = ctl_get_cmd_entry(ctsio, NULL);
2256	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2257		mtx_unlock(&lun->lun_lock);
2258		goto badjuju;
2259	}
2260
2261	CTL_LUN(ctsio) = lun;
2262	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2263
2264	/*
2265	 * Every I/O goes into the OOA queue for a
2266	 * particular LUN, and stays there until completion.
2267	 */
2268#ifdef CTL_TIME_IO
2269	if (TAILQ_EMPTY(&lun->ooa_queue))
2270		lun->idle_time += getsbinuptime() - lun->last_busy;
2271#endif
2272	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2273
2274	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2275		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2276		 ooa_links))) {
2277	case CTL_ACTION_BLOCK:
2278		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2279		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2280				  blocked_links);
2281		mtx_unlock(&lun->lun_lock);
2282		break;
2283	case CTL_ACTION_PASS:
2284	case CTL_ACTION_SKIP:
2285		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2286			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2287			ctl_enqueue_rtr((union ctl_io *)ctsio);
2288			mtx_unlock(&lun->lun_lock);
2289		} else {
2290			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2291			mtx_unlock(&lun->lun_lock);
2292
2293			/* send msg back to other side */
2294			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2295			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2296			msg_info.hdr.msg_type = CTL_MSG_R2R;
2297			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2298			    sizeof(msg_info.hdr), M_WAITOK);
2299		}
2300		break;
2301	case CTL_ACTION_OVERLAP:
2302		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2303		mtx_unlock(&lun->lun_lock);
2304		ctl_set_overlapped_cmd(ctsio);
2305		goto badjuju;
2306	case CTL_ACTION_OVERLAP_TAG:
2307		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2308		mtx_unlock(&lun->lun_lock);
2309		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2310		goto badjuju;
2311	case CTL_ACTION_ERROR:
2312	default:
2313		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2314		mtx_unlock(&lun->lun_lock);
2315
2316		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2317					 /*retry_count*/ 0);
2318badjuju:
2319		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2320		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2321		msg_info.hdr.serializing_sc = NULL;
2322		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2323		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2324		    sizeof(msg_info.scsi), M_WAITOK);
2325		ctl_free_io((union ctl_io *)ctsio);
2326		break;
2327	}
2328}
2329
2330/*
2331 * Returns 0 for success, errno for failure.
2332 */
2333static void
2334ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2335		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2336{
2337	union ctl_io *io;
2338
2339	mtx_lock(&lun->lun_lock);
2340	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2341	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2342	     ooa_links)) {
2343		struct ctl_ooa_entry *entry;
2344
2345		/*
2346		 * If we've got more than we can fit, just count the
2347		 * remaining entries.
2348		 */
2349		if (*cur_fill_num >= ooa_hdr->alloc_num)
2350			continue;
2351
2352		entry = &kern_entries[*cur_fill_num];
2353
2354		entry->tag_num = io->scsiio.tag_num;
2355		entry->lun_num = lun->lun;
2356#ifdef CTL_TIME_IO
2357		entry->start_bt = io->io_hdr.start_bt;
2358#endif
2359		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2360		entry->cdb_len = io->scsiio.cdb_len;
2361		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2362			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2363
2364		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2365			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2366
2367		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2368			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2369
2370		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2371			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2372
2373		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2374			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2375	}
2376	mtx_unlock(&lun->lun_lock);
2377}
2378
2379static void *
2380ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2381		 size_t error_str_len)
2382{
2383	void *kptr;
2384
2385	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2386
2387	if (copyin(user_addr, kptr, len) != 0) {
2388		snprintf(error_str, error_str_len, "Error copying %d bytes "
2389			 "from user address %p to kernel address %p", len,
2390			 user_addr, kptr);
2391		free(kptr, M_CTL);
2392		return (NULL);
2393	}
2394
2395	return (kptr);
2396}
2397
2398static void
2399ctl_free_args(int num_args, struct ctl_be_arg *args)
2400{
2401	int i;
2402
2403	if (args == NULL)
2404		return;
2405
2406	for (i = 0; i < num_args; i++) {
2407		free(args[i].kname, M_CTL);
2408		free(args[i].kvalue, M_CTL);
2409	}
2410
2411	free(args, M_CTL);
2412}
2413
2414static struct ctl_be_arg *
2415ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2416		char *error_str, size_t error_str_len)
2417{
2418	struct ctl_be_arg *args;
2419	int i;
2420
2421	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2422				error_str, error_str_len);
2423
2424	if (args == NULL)
2425		goto bailout;
2426
2427	for (i = 0; i < num_args; i++) {
2428		args[i].kname = NULL;
2429		args[i].kvalue = NULL;
2430	}
2431
2432	for (i = 0; i < num_args; i++) {
2433		uint8_t *tmpptr;
2434
2435		args[i].kname = ctl_copyin_alloc(args[i].name,
2436			args[i].namelen, error_str, error_str_len);
2437		if (args[i].kname == NULL)
2438			goto bailout;
2439
2440		if (args[i].kname[args[i].namelen - 1] != '\0') {
2441			snprintf(error_str, error_str_len, "Argument %d "
2442				 "name is not NUL-terminated", i);
2443			goto bailout;
2444		}
2445
2446		if (args[i].flags & CTL_BEARG_RD) {
2447			tmpptr = ctl_copyin_alloc(args[i].value,
2448				args[i].vallen, error_str, error_str_len);
2449			if (tmpptr == NULL)
2450				goto bailout;
2451			if ((args[i].flags & CTL_BEARG_ASCII)
2452			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2453				snprintf(error_str, error_str_len, "Argument "
2454				    "%d value is not NUL-terminated", i);
2455				free(tmpptr, M_CTL);
2456				goto bailout;
2457			}
2458			args[i].kvalue = tmpptr;
2459		} else {
2460			args[i].kvalue = malloc(args[i].vallen,
2461			    M_CTL, M_WAITOK | M_ZERO);
2462		}
2463	}
2464
2465	return (args);
2466bailout:
2467
2468	ctl_free_args(num_args, args);
2469
2470	return (NULL);
2471}
2472
2473static void
2474ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2475{
2476	int i;
2477
2478	for (i = 0; i < num_args; i++) {
2479		if (args[i].flags & CTL_BEARG_WR)
2480			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2481	}
2482}
2483
2484/*
2485 * Escape characters that are illegal or not recommended in XML.
2486 */
2487int
2488ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2489{
2490	char *end = str + size;
2491	int retval;
2492
2493	retval = 0;
2494
2495	for (; *str && str < end; str++) {
2496		switch (*str) {
2497		case '&':
2498			retval = sbuf_printf(sb, "&amp;");
2499			break;
2500		case '>':
2501			retval = sbuf_printf(sb, "&gt;");
2502			break;
2503		case '<':
2504			retval = sbuf_printf(sb, "&lt;");
2505			break;
2506		default:
2507			retval = sbuf_putc(sb, *str);
2508			break;
2509		}
2510
2511		if (retval != 0)
2512			break;
2513
2514	}
2515
2516	return (retval);
2517}
2518
2519static void
2520ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2521{
2522	struct scsi_vpd_id_descriptor *desc;
2523	int i;
2524
2525	if (id == NULL || id->len < 4)
2526		return;
2527	desc = (struct scsi_vpd_id_descriptor *)id->data;
2528	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2529	case SVPD_ID_TYPE_T10:
2530		sbuf_printf(sb, "t10.");
2531		break;
2532	case SVPD_ID_TYPE_EUI64:
2533		sbuf_printf(sb, "eui.");
2534		break;
2535	case SVPD_ID_TYPE_NAA:
2536		sbuf_printf(sb, "naa.");
2537		break;
2538	case SVPD_ID_TYPE_SCSI_NAME:
2539		break;
2540	}
2541	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2542	case SVPD_ID_CODESET_BINARY:
2543		for (i = 0; i < desc->length; i++)
2544			sbuf_printf(sb, "%02x", desc->identifier[i]);
2545		break;
2546	case SVPD_ID_CODESET_ASCII:
2547		sbuf_printf(sb, "%.*s", (int)desc->length,
2548		    (char *)desc->identifier);
2549		break;
2550	case SVPD_ID_CODESET_UTF8:
2551		sbuf_printf(sb, "%s", (char *)desc->identifier);
2552		break;
2553	}
2554}
2555
2556static int
2557ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2558	  struct thread *td)
2559{
2560	struct ctl_softc *softc = dev->si_drv1;
2561	struct ctl_port *port;
2562	struct ctl_lun *lun;
2563	int retval;
2564
2565	retval = 0;
2566
2567	switch (cmd) {
2568	case CTL_IO:
2569		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2570		break;
2571	case CTL_ENABLE_PORT:
2572	case CTL_DISABLE_PORT:
2573	case CTL_SET_PORT_WWNS: {
2574		struct ctl_port *port;
2575		struct ctl_port_entry *entry;
2576
2577		entry = (struct ctl_port_entry *)addr;
2578
2579		mtx_lock(&softc->ctl_lock);
2580		STAILQ_FOREACH(port, &softc->port_list, links) {
2581			int action, done;
2582
2583			if (port->targ_port < softc->port_min ||
2584			    port->targ_port >= softc->port_max)
2585				continue;
2586
2587			action = 0;
2588			done = 0;
2589			if ((entry->port_type == CTL_PORT_NONE)
2590			 && (entry->targ_port == port->targ_port)) {
2591				/*
2592				 * If the user only wants to enable or
2593				 * disable or set WWNs on a specific port,
2594				 * do the operation and we're done.
2595				 */
2596				action = 1;
2597				done = 1;
2598			} else if (entry->port_type & port->port_type) {
2599				/*
2600				 * Compare the user's type mask with the
2601				 * particular frontend type to see if we
2602				 * have a match.
2603				 */
2604				action = 1;
2605				done = 0;
2606
2607				/*
2608				 * Make sure the user isn't trying to set
2609				 * WWNs on multiple ports at the same time.
2610				 */
2611				if (cmd == CTL_SET_PORT_WWNS) {
2612					printf("%s: Can't set WWNs on "
2613					       "multiple ports\n", __func__);
2614					retval = EINVAL;
2615					break;
2616				}
2617			}
2618			if (action == 0)
2619				continue;
2620
2621			/*
2622			 * XXX KDM we have to drop the lock here, because
2623			 * the online/offline operations can potentially
2624			 * block.  We need to reference count the frontends
2625			 * so they can't go away,
2626			 */
2627			if (cmd == CTL_ENABLE_PORT) {
2628				mtx_unlock(&softc->ctl_lock);
2629				ctl_port_online(port);
2630				mtx_lock(&softc->ctl_lock);
2631			} else if (cmd == CTL_DISABLE_PORT) {
2632				mtx_unlock(&softc->ctl_lock);
2633				ctl_port_offline(port);
2634				mtx_lock(&softc->ctl_lock);
2635			} else if (cmd == CTL_SET_PORT_WWNS) {
2636				ctl_port_set_wwns(port,
2637				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2638				    1 : 0, entry->wwnn,
2639				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2640				    1 : 0, entry->wwpn);
2641			}
2642			if (done != 0)
2643				break;
2644		}
2645		mtx_unlock(&softc->ctl_lock);
2646		break;
2647	}
2648	case CTL_GET_OOA: {
2649		struct ctl_ooa *ooa_hdr;
2650		struct ctl_ooa_entry *entries;
2651		uint32_t cur_fill_num;
2652
2653		ooa_hdr = (struct ctl_ooa *)addr;
2654
2655		if ((ooa_hdr->alloc_len == 0)
2656		 || (ooa_hdr->alloc_num == 0)) {
2657			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2658			       "must be non-zero\n", __func__,
2659			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2660			retval = EINVAL;
2661			break;
2662		}
2663
2664		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2665		    sizeof(struct ctl_ooa_entry))) {
2666			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2667			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2668			       __func__, ooa_hdr->alloc_len,
2669			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2670			retval = EINVAL;
2671			break;
2672		}
2673
2674		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2675		if (entries == NULL) {
2676			printf("%s: could not allocate %d bytes for OOA "
2677			       "dump\n", __func__, ooa_hdr->alloc_len);
2678			retval = ENOMEM;
2679			break;
2680		}
2681
2682		mtx_lock(&softc->ctl_lock);
2683		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2684		    (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2685		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2686			mtx_unlock(&softc->ctl_lock);
2687			free(entries, M_CTL);
2688			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2689			       __func__, (uintmax_t)ooa_hdr->lun_num);
2690			retval = EINVAL;
2691			break;
2692		}
2693
2694		cur_fill_num = 0;
2695
2696		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2697			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2698				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2699				    ooa_hdr, entries);
2700			}
2701		} else {
2702			lun = softc->ctl_luns[ooa_hdr->lun_num];
2703			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2704			    entries);
2705		}
2706		mtx_unlock(&softc->ctl_lock);
2707
2708		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2709		ooa_hdr->fill_len = ooa_hdr->fill_num *
2710			sizeof(struct ctl_ooa_entry);
2711		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2712		if (retval != 0) {
2713			printf("%s: error copying out %d bytes for OOA dump\n",
2714			       __func__, ooa_hdr->fill_len);
2715		}
2716
2717		getbinuptime(&ooa_hdr->cur_bt);
2718
2719		if (cur_fill_num > ooa_hdr->alloc_num) {
2720			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2721			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2722		} else {
2723			ooa_hdr->dropped_num = 0;
2724			ooa_hdr->status = CTL_OOA_OK;
2725		}
2726
2727		free(entries, M_CTL);
2728		break;
2729	}
2730	case CTL_DELAY_IO: {
2731		struct ctl_io_delay_info *delay_info;
2732
2733		delay_info = (struct ctl_io_delay_info *)addr;
2734
2735#ifdef CTL_IO_DELAY
2736		mtx_lock(&softc->ctl_lock);
2737		if (delay_info->lun_id >= CTL_MAX_LUNS ||
2738		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2739			mtx_unlock(&softc->ctl_lock);
2740			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2741			break;
2742		}
2743		mtx_lock(&lun->lun_lock);
2744		mtx_unlock(&softc->ctl_lock);
2745		delay_info->status = CTL_DELAY_STATUS_OK;
2746		switch (delay_info->delay_type) {
2747		case CTL_DELAY_TYPE_CONT:
2748		case CTL_DELAY_TYPE_ONESHOT:
2749			break;
2750		default:
2751			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2752			break;
2753		}
2754		switch (delay_info->delay_loc) {
2755		case CTL_DELAY_LOC_DATAMOVE:
2756			lun->delay_info.datamove_type = delay_info->delay_type;
2757			lun->delay_info.datamove_delay = delay_info->delay_secs;
2758			break;
2759		case CTL_DELAY_LOC_DONE:
2760			lun->delay_info.done_type = delay_info->delay_type;
2761			lun->delay_info.done_delay = delay_info->delay_secs;
2762			break;
2763		default:
2764			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2765			break;
2766		}
2767		mtx_unlock(&lun->lun_lock);
2768#else
2769		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2770#endif /* CTL_IO_DELAY */
2771		break;
2772	}
2773#ifdef CTL_LEGACY_STATS
2774	case CTL_GETSTATS: {
2775		struct ctl_stats *stats = (struct ctl_stats *)addr;
2776		int i;
2777
2778		/*
2779		 * XXX KDM no locking here.  If the LUN list changes,
2780		 * things can blow up.
2781		 */
2782		i = 0;
2783		stats->status = CTL_SS_OK;
2784		stats->fill_len = 0;
2785		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2786			if (stats->fill_len + sizeof(lun->legacy_stats) >
2787			    stats->alloc_len) {
2788				stats->status = CTL_SS_NEED_MORE_SPACE;
2789				break;
2790			}
2791			retval = copyout(&lun->legacy_stats, &stats->lun_stats[i++],
2792					 sizeof(lun->legacy_stats));
2793			if (retval != 0)
2794				break;
2795			stats->fill_len += sizeof(lun->legacy_stats);
2796		}
2797		stats->num_luns = softc->num_luns;
2798		stats->flags = CTL_STATS_FLAG_NONE;
2799#ifdef CTL_TIME_IO
2800		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
2801#endif
2802		getnanouptime(&stats->timestamp);
2803		break;
2804	}
2805#endif /* CTL_LEGACY_STATS */
2806	case CTL_ERROR_INJECT: {
2807		struct ctl_error_desc *err_desc, *new_err_desc;
2808
2809		err_desc = (struct ctl_error_desc *)addr;
2810
2811		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2812				      M_WAITOK | M_ZERO);
2813		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2814
2815		mtx_lock(&softc->ctl_lock);
2816		if (err_desc->lun_id >= CTL_MAX_LUNS ||
2817		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2818			mtx_unlock(&softc->ctl_lock);
2819			free(new_err_desc, M_CTL);
2820			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2821			       __func__, (uintmax_t)err_desc->lun_id);
2822			retval = EINVAL;
2823			break;
2824		}
2825		mtx_lock(&lun->lun_lock);
2826		mtx_unlock(&softc->ctl_lock);
2827
2828		/*
2829		 * We could do some checking here to verify the validity
2830		 * of the request, but given the complexity of error
2831		 * injection requests, the checking logic would be fairly
2832		 * complex.
2833		 *
2834		 * For now, if the request is invalid, it just won't get
2835		 * executed and might get deleted.
2836		 */
2837		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2838
2839		/*
2840		 * XXX KDM check to make sure the serial number is unique,
2841		 * in case we somehow manage to wrap.  That shouldn't
2842		 * happen for a very long time, but it's the right thing to
2843		 * do.
2844		 */
2845		new_err_desc->serial = lun->error_serial;
2846		err_desc->serial = lun->error_serial;
2847		lun->error_serial++;
2848
2849		mtx_unlock(&lun->lun_lock);
2850		break;
2851	}
2852	case CTL_ERROR_INJECT_DELETE: {
2853		struct ctl_error_desc *delete_desc, *desc, *desc2;
2854		int delete_done;
2855
2856		delete_desc = (struct ctl_error_desc *)addr;
2857		delete_done = 0;
2858
2859		mtx_lock(&softc->ctl_lock);
2860		if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2861		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2862			mtx_unlock(&softc->ctl_lock);
2863			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2864			       __func__, (uintmax_t)delete_desc->lun_id);
2865			retval = EINVAL;
2866			break;
2867		}
2868		mtx_lock(&lun->lun_lock);
2869		mtx_unlock(&softc->ctl_lock);
2870		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2871			if (desc->serial != delete_desc->serial)
2872				continue;
2873
2874			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2875				      links);
2876			free(desc, M_CTL);
2877			delete_done = 1;
2878		}
2879		mtx_unlock(&lun->lun_lock);
2880		if (delete_done == 0) {
2881			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2882			       "error serial %ju on LUN %u\n", __func__,
2883			       delete_desc->serial, delete_desc->lun_id);
2884			retval = EINVAL;
2885			break;
2886		}
2887		break;
2888	}
2889	case CTL_DUMP_STRUCTS: {
2890		int j, k;
2891		struct ctl_port *port;
2892		struct ctl_frontend *fe;
2893
2894		mtx_lock(&softc->ctl_lock);
2895		printf("CTL Persistent Reservation information start:\n");
2896		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2897			mtx_lock(&lun->lun_lock);
2898			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2899				mtx_unlock(&lun->lun_lock);
2900				continue;
2901			}
2902
2903			for (j = 0; j < CTL_MAX_PORTS; j++) {
2904				if (lun->pr_keys[j] == NULL)
2905					continue;
2906				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2907					if (lun->pr_keys[j][k] == 0)
2908						continue;
2909					printf("  LUN %ju port %d iid %d key "
2910					       "%#jx\n", lun->lun, j, k,
2911					       (uintmax_t)lun->pr_keys[j][k]);
2912				}
2913			}
2914			mtx_unlock(&lun->lun_lock);
2915		}
2916		printf("CTL Persistent Reservation information end\n");
2917		printf("CTL Ports:\n");
2918		STAILQ_FOREACH(port, &softc->port_list, links) {
2919			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2920			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2921			       port->frontend->name, port->port_type,
2922			       port->physical_port, port->virtual_port,
2923			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2924			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2925				if (port->wwpn_iid[j].in_use == 0 &&
2926				    port->wwpn_iid[j].wwpn == 0 &&
2927				    port->wwpn_iid[j].name == NULL)
2928					continue;
2929
2930				printf("    iid %u use %d WWPN %#jx '%s'\n",
2931				    j, port->wwpn_iid[j].in_use,
2932				    (uintmax_t)port->wwpn_iid[j].wwpn,
2933				    port->wwpn_iid[j].name);
2934			}
2935		}
2936		printf("CTL Port information end\n");
2937		mtx_unlock(&softc->ctl_lock);
2938		/*
2939		 * XXX KDM calling this without a lock.  We'd likely want
2940		 * to drop the lock before calling the frontend's dump
2941		 * routine anyway.
2942		 */
2943		printf("CTL Frontends:\n");
2944		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2945			printf("  Frontend '%s'\n", fe->name);
2946			if (fe->fe_dump != NULL)
2947				fe->fe_dump();
2948		}
2949		printf("CTL Frontend information end\n");
2950		break;
2951	}
2952	case CTL_LUN_REQ: {
2953		struct ctl_lun_req *lun_req;
2954		struct ctl_backend_driver *backend;
2955
2956		lun_req = (struct ctl_lun_req *)addr;
2957
2958		backend = ctl_backend_find(lun_req->backend);
2959		if (backend == NULL) {
2960			lun_req->status = CTL_LUN_ERROR;
2961			snprintf(lun_req->error_str,
2962				 sizeof(lun_req->error_str),
2963				 "Backend \"%s\" not found.",
2964				 lun_req->backend);
2965			break;
2966		}
2967		if (lun_req->num_be_args > 0) {
2968			lun_req->kern_be_args = ctl_copyin_args(
2969				lun_req->num_be_args,
2970				lun_req->be_args,
2971				lun_req->error_str,
2972				sizeof(lun_req->error_str));
2973			if (lun_req->kern_be_args == NULL) {
2974				lun_req->status = CTL_LUN_ERROR;
2975				break;
2976			}
2977		}
2978
2979		retval = backend->ioctl(dev, cmd, addr, flag, td);
2980
2981		if (lun_req->num_be_args > 0) {
2982			ctl_copyout_args(lun_req->num_be_args,
2983				      lun_req->kern_be_args);
2984			ctl_free_args(lun_req->num_be_args,
2985				      lun_req->kern_be_args);
2986		}
2987		break;
2988	}
2989	case CTL_LUN_LIST: {
2990		struct sbuf *sb;
2991		struct ctl_lun_list *list;
2992		struct ctl_option *opt;
2993
2994		list = (struct ctl_lun_list *)addr;
2995
2996		/*
2997		 * Allocate a fixed length sbuf here, based on the length
2998		 * of the user's buffer.  We could allocate an auto-extending
2999		 * buffer, and then tell the user how much larger our
3000		 * amount of data is than his buffer, but that presents
3001		 * some problems:
3002		 *
3003		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3004		 *     we can't hold a lock while calling them with an
3005		 *     auto-extending buffer.
3006 		 *
3007		 * 2.  There is not currently a LUN reference counting
3008		 *     mechanism, outside of outstanding transactions on
3009		 *     the LUN's OOA queue.  So a LUN could go away on us
3010		 *     while we're getting the LUN number, backend-specific
3011		 *     information, etc.  Thus, given the way things
3012		 *     currently work, we need to hold the CTL lock while
3013		 *     grabbing LUN information.
3014		 *
3015		 * So, from the user's standpoint, the best thing to do is
3016		 * allocate what he thinks is a reasonable buffer length,
3017		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3018		 * double the buffer length and try again.  (And repeat
3019		 * that until he succeeds.)
3020		 */
3021		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3022		if (sb == NULL) {
3023			list->status = CTL_LUN_LIST_ERROR;
3024			snprintf(list->error_str, sizeof(list->error_str),
3025				 "Unable to allocate %d bytes for LUN list",
3026				 list->alloc_len);
3027			break;
3028		}
3029
3030		sbuf_printf(sb, "<ctllunlist>\n");
3031
3032		mtx_lock(&softc->ctl_lock);
3033		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3034			mtx_lock(&lun->lun_lock);
3035			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3036					     (uintmax_t)lun->lun);
3037
3038			/*
3039			 * Bail out as soon as we see that we've overfilled
3040			 * the buffer.
3041			 */
3042			if (retval != 0)
3043				break;
3044
3045			retval = sbuf_printf(sb, "\t<backend_type>%s"
3046					     "</backend_type>\n",
3047					     (lun->backend == NULL) ?  "none" :
3048					     lun->backend->name);
3049
3050			if (retval != 0)
3051				break;
3052
3053			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3054					     lun->be_lun->lun_type);
3055
3056			if (retval != 0)
3057				break;
3058
3059			if (lun->backend == NULL) {
3060				retval = sbuf_printf(sb, "</lun>\n");
3061				if (retval != 0)
3062					break;
3063				continue;
3064			}
3065
3066			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3067					     (lun->be_lun->maxlba > 0) ?
3068					     lun->be_lun->maxlba + 1 : 0);
3069
3070			if (retval != 0)
3071				break;
3072
3073			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3074					     lun->be_lun->blocksize);
3075
3076			if (retval != 0)
3077				break;
3078
3079			retval = sbuf_printf(sb, "\t<serial_number>");
3080
3081			if (retval != 0)
3082				break;
3083
3084			retval = ctl_sbuf_printf_esc(sb,
3085			    lun->be_lun->serial_num,
3086			    sizeof(lun->be_lun->serial_num));
3087
3088			if (retval != 0)
3089				break;
3090
3091			retval = sbuf_printf(sb, "</serial_number>\n");
3092
3093			if (retval != 0)
3094				break;
3095
3096			retval = sbuf_printf(sb, "\t<device_id>");
3097
3098			if (retval != 0)
3099				break;
3100
3101			retval = ctl_sbuf_printf_esc(sb,
3102			    lun->be_lun->device_id,
3103			    sizeof(lun->be_lun->device_id));
3104
3105			if (retval != 0)
3106				break;
3107
3108			retval = sbuf_printf(sb, "</device_id>\n");
3109
3110			if (retval != 0)
3111				break;
3112
3113			if (lun->backend->lun_info != NULL) {
3114				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3115				if (retval != 0)
3116					break;
3117			}
3118			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3119				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3120				    opt->name, opt->value, opt->name);
3121				if (retval != 0)
3122					break;
3123			}
3124
3125			retval = sbuf_printf(sb, "</lun>\n");
3126
3127			if (retval != 0)
3128				break;
3129			mtx_unlock(&lun->lun_lock);
3130		}
3131		if (lun != NULL)
3132			mtx_unlock(&lun->lun_lock);
3133		mtx_unlock(&softc->ctl_lock);
3134
3135		if ((retval != 0)
3136		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3137			retval = 0;
3138			sbuf_delete(sb);
3139			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3140			snprintf(list->error_str, sizeof(list->error_str),
3141				 "Out of space, %d bytes is too small",
3142				 list->alloc_len);
3143			break;
3144		}
3145
3146		sbuf_finish(sb);
3147
3148		retval = copyout(sbuf_data(sb), list->lun_xml,
3149				 sbuf_len(sb) + 1);
3150
3151		list->fill_len = sbuf_len(sb) + 1;
3152		list->status = CTL_LUN_LIST_OK;
3153		sbuf_delete(sb);
3154		break;
3155	}
3156	case CTL_ISCSI: {
3157		struct ctl_iscsi *ci;
3158		struct ctl_frontend *fe;
3159
3160		ci = (struct ctl_iscsi *)addr;
3161
3162		fe = ctl_frontend_find("iscsi");
3163		if (fe == NULL) {
3164			ci->status = CTL_ISCSI_ERROR;
3165			snprintf(ci->error_str, sizeof(ci->error_str),
3166			    "Frontend \"iscsi\" not found.");
3167			break;
3168		}
3169
3170		retval = fe->ioctl(dev, cmd, addr, flag, td);
3171		break;
3172	}
3173	case CTL_PORT_REQ: {
3174		struct ctl_req *req;
3175		struct ctl_frontend *fe;
3176
3177		req = (struct ctl_req *)addr;
3178
3179		fe = ctl_frontend_find(req->driver);
3180		if (fe == NULL) {
3181			req->status = CTL_LUN_ERROR;
3182			snprintf(req->error_str, sizeof(req->error_str),
3183			    "Frontend \"%s\" not found.", req->driver);
3184			break;
3185		}
3186		if (req->num_args > 0) {
3187			req->kern_args = ctl_copyin_args(req->num_args,
3188			    req->args, req->error_str, sizeof(req->error_str));
3189			if (req->kern_args == NULL) {
3190				req->status = CTL_LUN_ERROR;
3191				break;
3192			}
3193		}
3194
3195		if (fe->ioctl)
3196			retval = fe->ioctl(dev, cmd, addr, flag, td);
3197		else
3198			retval = ENODEV;
3199
3200		if (req->num_args > 0) {
3201			ctl_copyout_args(req->num_args, req->kern_args);
3202			ctl_free_args(req->num_args, req->kern_args);
3203		}
3204		break;
3205	}
3206	case CTL_PORT_LIST: {
3207		struct sbuf *sb;
3208		struct ctl_port *port;
3209		struct ctl_lun_list *list;
3210		struct ctl_option *opt;
3211		int j;
3212		uint32_t plun;
3213
3214		list = (struct ctl_lun_list *)addr;
3215
3216		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3217		if (sb == NULL) {
3218			list->status = CTL_LUN_LIST_ERROR;
3219			snprintf(list->error_str, sizeof(list->error_str),
3220				 "Unable to allocate %d bytes for LUN list",
3221				 list->alloc_len);
3222			break;
3223		}
3224
3225		sbuf_printf(sb, "<ctlportlist>\n");
3226
3227		mtx_lock(&softc->ctl_lock);
3228		STAILQ_FOREACH(port, &softc->port_list, links) {
3229			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3230					     (uintmax_t)port->targ_port);
3231
3232			/*
3233			 * Bail out as soon as we see that we've overfilled
3234			 * the buffer.
3235			 */
3236			if (retval != 0)
3237				break;
3238
3239			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3240			    "</frontend_type>\n", port->frontend->name);
3241			if (retval != 0)
3242				break;
3243
3244			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3245					     port->port_type);
3246			if (retval != 0)
3247				break;
3248
3249			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3250			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3251			if (retval != 0)
3252				break;
3253
3254			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3255			    port->port_name);
3256			if (retval != 0)
3257				break;
3258
3259			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3260			    port->physical_port);
3261			if (retval != 0)
3262				break;
3263
3264			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3265			    port->virtual_port);
3266			if (retval != 0)
3267				break;
3268
3269			if (port->target_devid != NULL) {
3270				sbuf_printf(sb, "\t<target>");
3271				ctl_id_sbuf(port->target_devid, sb);
3272				sbuf_printf(sb, "</target>\n");
3273			}
3274
3275			if (port->port_devid != NULL) {
3276				sbuf_printf(sb, "\t<port>");
3277				ctl_id_sbuf(port->port_devid, sb);
3278				sbuf_printf(sb, "</port>\n");
3279			}
3280
3281			if (port->port_info != NULL) {
3282				retval = port->port_info(port->onoff_arg, sb);
3283				if (retval != 0)
3284					break;
3285			}
3286			STAILQ_FOREACH(opt, &port->options, links) {
3287				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3288				    opt->name, opt->value, opt->name);
3289				if (retval != 0)
3290					break;
3291			}
3292
3293			if (port->lun_map != NULL) {
3294				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3295				for (j = 0; j < port->lun_map_size; j++) {
3296					plun = ctl_lun_map_from_port(port, j);
3297					if (plun == UINT32_MAX)
3298						continue;
3299					sbuf_printf(sb,
3300					    "\t<lun id=\"%u\">%u</lun>\n",
3301					    j, plun);
3302				}
3303			}
3304
3305			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3306				if (port->wwpn_iid[j].in_use == 0 ||
3307				    (port->wwpn_iid[j].wwpn == 0 &&
3308				     port->wwpn_iid[j].name == NULL))
3309					continue;
3310
3311				if (port->wwpn_iid[j].name != NULL)
3312					retval = sbuf_printf(sb,
3313					    "\t<initiator id=\"%u\">%s</initiator>\n",
3314					    j, port->wwpn_iid[j].name);
3315				else
3316					retval = sbuf_printf(sb,
3317					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3318					    j, port->wwpn_iid[j].wwpn);
3319				if (retval != 0)
3320					break;
3321			}
3322			if (retval != 0)
3323				break;
3324
3325			retval = sbuf_printf(sb, "</targ_port>\n");
3326			if (retval != 0)
3327				break;
3328		}
3329		mtx_unlock(&softc->ctl_lock);
3330
3331		if ((retval != 0)
3332		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3333			retval = 0;
3334			sbuf_delete(sb);
3335			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3336			snprintf(list->error_str, sizeof(list->error_str),
3337				 "Out of space, %d bytes is too small",
3338				 list->alloc_len);
3339			break;
3340		}
3341
3342		sbuf_finish(sb);
3343
3344		retval = copyout(sbuf_data(sb), list->lun_xml,
3345				 sbuf_len(sb) + 1);
3346
3347		list->fill_len = sbuf_len(sb) + 1;
3348		list->status = CTL_LUN_LIST_OK;
3349		sbuf_delete(sb);
3350		break;
3351	}
3352	case CTL_LUN_MAP: {
3353		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3354		struct ctl_port *port;
3355
3356		mtx_lock(&softc->ctl_lock);
3357		if (lm->port < softc->port_min ||
3358		    lm->port >= softc->port_max ||
3359		    (port = softc->ctl_ports[lm->port]) == NULL) {
3360			mtx_unlock(&softc->ctl_lock);
3361			return (ENXIO);
3362		}
3363		if (port->status & CTL_PORT_STATUS_ONLINE) {
3364			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3365				if (ctl_lun_map_to_port(port, lun->lun) ==
3366				    UINT32_MAX)
3367					continue;
3368				mtx_lock(&lun->lun_lock);
3369				ctl_est_ua_port(lun, lm->port, -1,
3370				    CTL_UA_LUN_CHANGE);
3371				mtx_unlock(&lun->lun_lock);
3372			}
3373		}
3374		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3375		if (lm->plun != UINT32_MAX) {
3376			if (lm->lun == UINT32_MAX)
3377				retval = ctl_lun_map_unset(port, lm->plun);
3378			else if (lm->lun < CTL_MAX_LUNS &&
3379			    softc->ctl_luns[lm->lun] != NULL)
3380				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3381			else
3382				return (ENXIO);
3383		} else {
3384			if (lm->lun == UINT32_MAX)
3385				retval = ctl_lun_map_deinit(port);
3386			else
3387				retval = ctl_lun_map_init(port);
3388		}
3389		if (port->status & CTL_PORT_STATUS_ONLINE)
3390			ctl_isc_announce_port(port);
3391		break;
3392	}
3393	case CTL_GET_LUN_STATS: {
3394		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3395		int i;
3396
3397		/*
3398		 * XXX KDM no locking here.  If the LUN list changes,
3399		 * things can blow up.
3400		 */
3401		i = 0;
3402		stats->status = CTL_SS_OK;
3403		stats->fill_len = 0;
3404		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3405			if (lun->lun < stats->first_item)
3406				continue;
3407			if (stats->fill_len + sizeof(lun->stats) >
3408			    stats->alloc_len) {
3409				stats->status = CTL_SS_NEED_MORE_SPACE;
3410				break;
3411			}
3412			retval = copyout(&lun->stats, &stats->stats[i++],
3413					 sizeof(lun->stats));
3414			if (retval != 0)
3415				break;
3416			stats->fill_len += sizeof(lun->stats);
3417		}
3418		stats->num_items = softc->num_luns;
3419		stats->flags = CTL_STATS_FLAG_NONE;
3420#ifdef CTL_TIME_IO
3421		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3422#endif
3423		getnanouptime(&stats->timestamp);
3424		break;
3425	}
3426	case CTL_GET_PORT_STATS: {
3427		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3428		int i;
3429
3430		/*
3431		 * XXX KDM no locking here.  If the LUN list changes,
3432		 * things can blow up.
3433		 */
3434		i = 0;
3435		stats->status = CTL_SS_OK;
3436		stats->fill_len = 0;
3437		STAILQ_FOREACH(port, &softc->port_list, links) {
3438			if (port->targ_port < stats->first_item)
3439				continue;
3440			if (stats->fill_len + sizeof(port->stats) >
3441			    stats->alloc_len) {
3442				stats->status = CTL_SS_NEED_MORE_SPACE;
3443				break;
3444			}
3445			retval = copyout(&port->stats, &stats->stats[i++],
3446					 sizeof(port->stats));
3447			if (retval != 0)
3448				break;
3449			stats->fill_len += sizeof(port->stats);
3450		}
3451		stats->num_items = softc->num_ports;
3452		stats->flags = CTL_STATS_FLAG_NONE;
3453#ifdef CTL_TIME_IO
3454		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3455#endif
3456		getnanouptime(&stats->timestamp);
3457		break;
3458	}
3459	default: {
3460		/* XXX KDM should we fix this? */
3461#if 0
3462		struct ctl_backend_driver *backend;
3463		unsigned int type;
3464		int found;
3465
3466		found = 0;
3467
3468		/*
3469		 * We encode the backend type as the ioctl type for backend
3470		 * ioctls.  So parse it out here, and then search for a
3471		 * backend of this type.
3472		 */
3473		type = _IOC_TYPE(cmd);
3474
3475		STAILQ_FOREACH(backend, &softc->be_list, links) {
3476			if (backend->type == type) {
3477				found = 1;
3478				break;
3479			}
3480		}
3481		if (found == 0) {
3482			printf("ctl: unknown ioctl command %#lx or backend "
3483			       "%d\n", cmd, type);
3484			retval = EINVAL;
3485			break;
3486		}
3487		retval = backend->ioctl(dev, cmd, addr, flag, td);
3488#endif
3489		retval = ENOTTY;
3490		break;
3491	}
3492	}
3493	return (retval);
3494}
3495
3496uint32_t
3497ctl_get_initindex(struct ctl_nexus *nexus)
3498{
3499	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3500}
3501
3502int
3503ctl_lun_map_init(struct ctl_port *port)
3504{
3505	struct ctl_softc *softc = port->ctl_softc;
3506	struct ctl_lun *lun;
3507	int size = ctl_lun_map_size;
3508	uint32_t i;
3509
3510	if (port->lun_map == NULL || port->lun_map_size < size) {
3511		port->lun_map_size = 0;
3512		free(port->lun_map, M_CTL);
3513		port->lun_map = malloc(size * sizeof(uint32_t),
3514		    M_CTL, M_NOWAIT);
3515	}
3516	if (port->lun_map == NULL)
3517		return (ENOMEM);
3518	for (i = 0; i < size; i++)
3519		port->lun_map[i] = UINT32_MAX;
3520	port->lun_map_size = size;
3521	if (port->status & CTL_PORT_STATUS_ONLINE) {
3522		if (port->lun_disable != NULL) {
3523			STAILQ_FOREACH(lun, &softc->lun_list, links)
3524				port->lun_disable(port->targ_lun_arg, lun->lun);
3525		}
3526		ctl_isc_announce_port(port);
3527	}
3528	return (0);
3529}
3530
3531int
3532ctl_lun_map_deinit(struct ctl_port *port)
3533{
3534	struct ctl_softc *softc = port->ctl_softc;
3535	struct ctl_lun *lun;
3536
3537	if (port->lun_map == NULL)
3538		return (0);
3539	port->lun_map_size = 0;
3540	free(port->lun_map, M_CTL);
3541	port->lun_map = NULL;
3542	if (port->status & CTL_PORT_STATUS_ONLINE) {
3543		if (port->lun_enable != NULL) {
3544			STAILQ_FOREACH(lun, &softc->lun_list, links)
3545				port->lun_enable(port->targ_lun_arg, lun->lun);
3546		}
3547		ctl_isc_announce_port(port);
3548	}
3549	return (0);
3550}
3551
3552int
3553ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3554{
3555	int status;
3556	uint32_t old;
3557
3558	if (port->lun_map == NULL) {
3559		status = ctl_lun_map_init(port);
3560		if (status != 0)
3561			return (status);
3562	}
3563	if (plun >= port->lun_map_size)
3564		return (EINVAL);
3565	old = port->lun_map[plun];
3566	port->lun_map[plun] = glun;
3567	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3568		if (port->lun_enable != NULL)
3569			port->lun_enable(port->targ_lun_arg, plun);
3570		ctl_isc_announce_port(port);
3571	}
3572	return (0);
3573}
3574
3575int
3576ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3577{
3578	uint32_t old;
3579
3580	if (port->lun_map == NULL || plun >= port->lun_map_size)
3581		return (0);
3582	old = port->lun_map[plun];
3583	port->lun_map[plun] = UINT32_MAX;
3584	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3585		if (port->lun_disable != NULL)
3586			port->lun_disable(port->targ_lun_arg, plun);
3587		ctl_isc_announce_port(port);
3588	}
3589	return (0);
3590}
3591
3592uint32_t
3593ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3594{
3595
3596	if (port == NULL)
3597		return (UINT32_MAX);
3598	if (port->lun_map == NULL)
3599		return (lun_id);
3600	if (lun_id > port->lun_map_size)
3601		return (UINT32_MAX);
3602	return (port->lun_map[lun_id]);
3603}
3604
3605uint32_t
3606ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3607{
3608	uint32_t i;
3609
3610	if (port == NULL)
3611		return (UINT32_MAX);
3612	if (port->lun_map == NULL)
3613		return (lun_id);
3614	for (i = 0; i < port->lun_map_size; i++) {
3615		if (port->lun_map[i] == lun_id)
3616			return (i);
3617	}
3618	return (UINT32_MAX);
3619}
3620
3621uint32_t
3622ctl_decode_lun(uint64_t encoded)
3623{
3624	uint8_t lun[8];
3625	uint32_t result = 0xffffffff;
3626
3627	be64enc(lun, encoded);
3628	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3629	case RPL_LUNDATA_ATYP_PERIPH:
3630		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3631		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3632			result = lun[1];
3633		break;
3634	case RPL_LUNDATA_ATYP_FLAT:
3635		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3636		    lun[6] == 0 && lun[7] == 0)
3637			result = ((lun[0] & 0x3f) << 8) + lun[1];
3638		break;
3639	case RPL_LUNDATA_ATYP_EXTLUN:
3640		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3641		case 0x02:
3642			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3643			case 0x00:
3644				result = lun[1];
3645				break;
3646			case 0x10:
3647				result = (lun[1] << 16) + (lun[2] << 8) +
3648				    lun[3];
3649				break;
3650			case 0x20:
3651				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3652					result = (lun[2] << 24) +
3653					    (lun[3] << 16) + (lun[4] << 8) +
3654					    lun[5];
3655				break;
3656			}
3657			break;
3658		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3659			result = 0xffffffff;
3660			break;
3661		}
3662		break;
3663	}
3664	return (result);
3665}
3666
3667uint64_t
3668ctl_encode_lun(uint32_t decoded)
3669{
3670	uint64_t l = decoded;
3671
3672	if (l <= 0xff)
3673		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3674	if (l <= 0x3fff)
3675		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3676	if (l <= 0xffffff)
3677		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3678		    (l << 32));
3679	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3680}
3681
3682int
3683ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3684{
3685	int i;
3686
3687	for (i = first; i < last; i++) {
3688		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3689			return (i);
3690	}
3691	return (-1);
3692}
3693
3694int
3695ctl_set_mask(uint32_t *mask, uint32_t bit)
3696{
3697	uint32_t chunk, piece;
3698
3699	chunk = bit >> 5;
3700	piece = bit % (sizeof(uint32_t) * 8);
3701
3702	if ((mask[chunk] & (1 << piece)) != 0)
3703		return (-1);
3704	else
3705		mask[chunk] |= (1 << piece);
3706
3707	return (0);
3708}
3709
3710int
3711ctl_clear_mask(uint32_t *mask, uint32_t bit)
3712{
3713	uint32_t chunk, piece;
3714
3715	chunk = bit >> 5;
3716	piece = bit % (sizeof(uint32_t) * 8);
3717
3718	if ((mask[chunk] & (1 << piece)) == 0)
3719		return (-1);
3720	else
3721		mask[chunk] &= ~(1 << piece);
3722
3723	return (0);
3724}
3725
3726int
3727ctl_is_set(uint32_t *mask, uint32_t bit)
3728{
3729	uint32_t chunk, piece;
3730
3731	chunk = bit >> 5;
3732	piece = bit % (sizeof(uint32_t) * 8);
3733
3734	if ((mask[chunk] & (1 << piece)) == 0)
3735		return (0);
3736	else
3737		return (1);
3738}
3739
3740static uint64_t
3741ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3742{
3743	uint64_t *t;
3744
3745	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3746	if (t == NULL)
3747		return (0);
3748	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3749}
3750
3751static void
3752ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3753{
3754	uint64_t *t;
3755
3756	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3757	if (t == NULL)
3758		return;
3759	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3760}
3761
3762static void
3763ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3764{
3765	uint64_t *p;
3766	u_int i;
3767
3768	i = residx/CTL_MAX_INIT_PER_PORT;
3769	if (lun->pr_keys[i] != NULL)
3770		return;
3771	mtx_unlock(&lun->lun_lock);
3772	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3773	    M_WAITOK | M_ZERO);
3774	mtx_lock(&lun->lun_lock);
3775	if (lun->pr_keys[i] == NULL)
3776		lun->pr_keys[i] = p;
3777	else
3778		free(p, M_CTL);
3779}
3780
3781static void
3782ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3783{
3784	uint64_t *t;
3785
3786	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3787	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3788	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3789}
3790
3791/*
3792 * ctl_softc, pool_name, total_ctl_io are passed in.
3793 * npool is passed out.
3794 */
3795int
3796ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3797		uint32_t total_ctl_io, void **npool)
3798{
3799	struct ctl_io_pool *pool;
3800
3801	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3802					    M_NOWAIT | M_ZERO);
3803	if (pool == NULL)
3804		return (ENOMEM);
3805
3806	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3807	pool->ctl_softc = ctl_softc;
3808#ifdef IO_POOLS
3809	pool->zone = uma_zsecond_create(pool->name, NULL,
3810	    NULL, NULL, NULL, ctl_softc->io_zone);
3811	/* uma_prealloc(pool->zone, total_ctl_io); */
3812#else
3813	pool->zone = ctl_softc->io_zone;
3814#endif
3815
3816	*npool = pool;
3817	return (0);
3818}
3819
3820void
3821ctl_pool_free(struct ctl_io_pool *pool)
3822{
3823
3824	if (pool == NULL)
3825		return;
3826
3827#ifdef IO_POOLS
3828	uma_zdestroy(pool->zone);
3829#endif
3830	free(pool, M_CTL);
3831}
3832
3833union ctl_io *
3834ctl_alloc_io(void *pool_ref)
3835{
3836	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3837	union ctl_io *io;
3838
3839	io = uma_zalloc(pool->zone, M_WAITOK);
3840	if (io != NULL) {
3841		io->io_hdr.pool = pool_ref;
3842		CTL_SOFTC(io) = pool->ctl_softc;
3843	}
3844	return (io);
3845}
3846
3847union ctl_io *
3848ctl_alloc_io_nowait(void *pool_ref)
3849{
3850	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3851	union ctl_io *io;
3852
3853	io = uma_zalloc(pool->zone, M_NOWAIT);
3854	if (io != NULL) {
3855		io->io_hdr.pool = pool_ref;
3856		CTL_SOFTC(io) = pool->ctl_softc;
3857	}
3858	return (io);
3859}
3860
3861void
3862ctl_free_io(union ctl_io *io)
3863{
3864	struct ctl_io_pool *pool;
3865
3866	if (io == NULL)
3867		return;
3868
3869	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3870	uma_zfree(pool->zone, io);
3871}
3872
3873void
3874ctl_zero_io(union ctl_io *io)
3875{
3876	struct ctl_io_pool *pool;
3877
3878	if (io == NULL)
3879		return;
3880
3881	/*
3882	 * May need to preserve linked list pointers at some point too.
3883	 */
3884	pool = io->io_hdr.pool;
3885	memset(io, 0, sizeof(*io));
3886	io->io_hdr.pool = pool;
3887	CTL_SOFTC(io) = pool->ctl_softc;
3888}
3889
3890int
3891ctl_expand_number(const char *buf, uint64_t *num)
3892{
3893	char *endptr;
3894	uint64_t number;
3895	unsigned shift;
3896
3897	number = strtoq(buf, &endptr, 0);
3898
3899	switch (tolower((unsigned char)*endptr)) {
3900	case 'e':
3901		shift = 60;
3902		break;
3903	case 'p':
3904		shift = 50;
3905		break;
3906	case 't':
3907		shift = 40;
3908		break;
3909	case 'g':
3910		shift = 30;
3911		break;
3912	case 'm':
3913		shift = 20;
3914		break;
3915	case 'k':
3916		shift = 10;
3917		break;
3918	case 'b':
3919	case '\0': /* No unit. */
3920		*num = number;
3921		return (0);
3922	default:
3923		/* Unrecognized unit. */
3924		return (-1);
3925	}
3926
3927	if ((number << shift) >> shift != number) {
3928		/* Overflow */
3929		return (-1);
3930	}
3931	*num = number << shift;
3932	return (0);
3933}
3934
3935
3936/*
3937 * This routine could be used in the future to load default and/or saved
3938 * mode page parameters for a particuar lun.
3939 */
3940static int
3941ctl_init_page_index(struct ctl_lun *lun)
3942{
3943	int i, page_code;
3944	struct ctl_page_index *page_index;
3945	const char *value;
3946	uint64_t ival;
3947
3948	memcpy(&lun->mode_pages.index, page_index_template,
3949	       sizeof(page_index_template));
3950
3951	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3952
3953		page_index = &lun->mode_pages.index[i];
3954		if (lun->be_lun->lun_type == T_DIRECT &&
3955		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3956			continue;
3957		if (lun->be_lun->lun_type == T_PROCESSOR &&
3958		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3959			continue;
3960		if (lun->be_lun->lun_type == T_CDROM &&
3961		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3962			continue;
3963
3964		page_code = page_index->page_code & SMPH_PC_MASK;
3965		switch (page_code) {
3966		case SMS_RW_ERROR_RECOVERY_PAGE: {
3967			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3968			    ("subpage %#x for page %#x is incorrect!",
3969			    page_index->subpage, page_code));
3970			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3971			       &rw_er_page_default,
3972			       sizeof(rw_er_page_default));
3973			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3974			       &rw_er_page_changeable,
3975			       sizeof(rw_er_page_changeable));
3976			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3977			       &rw_er_page_default,
3978			       sizeof(rw_er_page_default));
3979			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3980			       &rw_er_page_default,
3981			       sizeof(rw_er_page_default));
3982			page_index->page_data =
3983				(uint8_t *)lun->mode_pages.rw_er_page;
3984			break;
3985		}
3986		case SMS_FORMAT_DEVICE_PAGE: {
3987			struct scsi_format_page *format_page;
3988
3989			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3990			    ("subpage %#x for page %#x is incorrect!",
3991			    page_index->subpage, page_code));
3992
3993			/*
3994			 * Sectors per track are set above.  Bytes per
3995			 * sector need to be set here on a per-LUN basis.
3996			 */
3997			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3998			       &format_page_default,
3999			       sizeof(format_page_default));
4000			memcpy(&lun->mode_pages.format_page[
4001			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4002			       sizeof(format_page_changeable));
4003			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4004			       &format_page_default,
4005			       sizeof(format_page_default));
4006			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4007			       &format_page_default,
4008			       sizeof(format_page_default));
4009
4010			format_page = &lun->mode_pages.format_page[
4011				CTL_PAGE_CURRENT];
4012			scsi_ulto2b(lun->be_lun->blocksize,
4013				    format_page->bytes_per_sector);
4014
4015			format_page = &lun->mode_pages.format_page[
4016				CTL_PAGE_DEFAULT];
4017			scsi_ulto2b(lun->be_lun->blocksize,
4018				    format_page->bytes_per_sector);
4019
4020			format_page = &lun->mode_pages.format_page[
4021				CTL_PAGE_SAVED];
4022			scsi_ulto2b(lun->be_lun->blocksize,
4023				    format_page->bytes_per_sector);
4024
4025			page_index->page_data =
4026				(uint8_t *)lun->mode_pages.format_page;
4027			break;
4028		}
4029		case SMS_RIGID_DISK_PAGE: {
4030			struct scsi_rigid_disk_page *rigid_disk_page;
4031			uint32_t sectors_per_cylinder;
4032			uint64_t cylinders;
4033#ifndef	__XSCALE__
4034			int shift;
4035#endif /* !__XSCALE__ */
4036
4037			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4038			    ("subpage %#x for page %#x is incorrect!",
4039			    page_index->subpage, page_code));
4040
4041			/*
4042			 * Rotation rate and sectors per track are set
4043			 * above.  We calculate the cylinders here based on
4044			 * capacity.  Due to the number of heads and
4045			 * sectors per track we're using, smaller arrays
4046			 * may turn out to have 0 cylinders.  Linux and
4047			 * FreeBSD don't pay attention to these mode pages
4048			 * to figure out capacity, but Solaris does.  It
4049			 * seems to deal with 0 cylinders just fine, and
4050			 * works out a fake geometry based on the capacity.
4051			 */
4052			memcpy(&lun->mode_pages.rigid_disk_page[
4053			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4054			       sizeof(rigid_disk_page_default));
4055			memcpy(&lun->mode_pages.rigid_disk_page[
4056			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4057			       sizeof(rigid_disk_page_changeable));
4058
4059			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4060				CTL_DEFAULT_HEADS;
4061
4062			/*
4063			 * The divide method here will be more accurate,
4064			 * probably, but results in floating point being
4065			 * used in the kernel on i386 (__udivdi3()).  On the
4066			 * XScale, though, __udivdi3() is implemented in
4067			 * software.
4068			 *
4069			 * The shift method for cylinder calculation is
4070			 * accurate if sectors_per_cylinder is a power of
4071			 * 2.  Otherwise it might be slightly off -- you
4072			 * might have a bit of a truncation problem.
4073			 */
4074#ifdef	__XSCALE__
4075			cylinders = (lun->be_lun->maxlba + 1) /
4076				sectors_per_cylinder;
4077#else
4078			for (shift = 31; shift > 0; shift--) {
4079				if (sectors_per_cylinder & (1 << shift))
4080					break;
4081			}
4082			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4083#endif
4084
4085			/*
4086			 * We've basically got 3 bytes, or 24 bits for the
4087			 * cylinder size in the mode page.  If we're over,
4088			 * just round down to 2^24.
4089			 */
4090			if (cylinders > 0xffffff)
4091				cylinders = 0xffffff;
4092
4093			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4094				CTL_PAGE_DEFAULT];
4095			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4096
4097			if ((value = ctl_get_opt(&lun->be_lun->options,
4098			    "rpm")) != NULL) {
4099				scsi_ulto2b(strtol(value, NULL, 0),
4100				     rigid_disk_page->rotation_rate);
4101			}
4102
4103			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4104			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4105			       sizeof(rigid_disk_page_default));
4106			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4107			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4108			       sizeof(rigid_disk_page_default));
4109
4110			page_index->page_data =
4111				(uint8_t *)lun->mode_pages.rigid_disk_page;
4112			break;
4113		}
4114		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4115			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4116			    ("subpage %#x for page %#x is incorrect!",
4117			    page_index->subpage, page_code));
4118			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4119			       &verify_er_page_default,
4120			       sizeof(verify_er_page_default));
4121			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4122			       &verify_er_page_changeable,
4123			       sizeof(verify_er_page_changeable));
4124			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4125			       &verify_er_page_default,
4126			       sizeof(verify_er_page_default));
4127			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4128			       &verify_er_page_default,
4129			       sizeof(verify_er_page_default));
4130			page_index->page_data =
4131				(uint8_t *)lun->mode_pages.verify_er_page;
4132			break;
4133		}
4134		case SMS_CACHING_PAGE: {
4135			struct scsi_caching_page *caching_page;
4136
4137			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4138			    ("subpage %#x for page %#x is incorrect!",
4139			    page_index->subpage, page_code));
4140			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4141			       &caching_page_default,
4142			       sizeof(caching_page_default));
4143			memcpy(&lun->mode_pages.caching_page[
4144			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4145			       sizeof(caching_page_changeable));
4146			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4147			       &caching_page_default,
4148			       sizeof(caching_page_default));
4149			caching_page = &lun->mode_pages.caching_page[
4150			    CTL_PAGE_SAVED];
4151			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4152			if (value != NULL && strcmp(value, "off") == 0)
4153				caching_page->flags1 &= ~SCP_WCE;
4154			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4155			if (value != NULL && strcmp(value, "off") == 0)
4156				caching_page->flags1 |= SCP_RCD;
4157			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4158			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4159			       sizeof(caching_page_default));
4160			page_index->page_data =
4161				(uint8_t *)lun->mode_pages.caching_page;
4162			break;
4163		}
4164		case SMS_CONTROL_MODE_PAGE: {
4165			switch (page_index->subpage) {
4166			case SMS_SUBPAGE_PAGE_0: {
4167				struct scsi_control_page *control_page;
4168
4169				memcpy(&lun->mode_pages.control_page[
4170				    CTL_PAGE_DEFAULT],
4171				       &control_page_default,
4172				       sizeof(control_page_default));
4173				memcpy(&lun->mode_pages.control_page[
4174				    CTL_PAGE_CHANGEABLE],
4175				       &control_page_changeable,
4176				       sizeof(control_page_changeable));
4177				memcpy(&lun->mode_pages.control_page[
4178				    CTL_PAGE_SAVED],
4179				       &control_page_default,
4180				       sizeof(control_page_default));
4181				control_page = &lun->mode_pages.control_page[
4182				    CTL_PAGE_SAVED];
4183				value = ctl_get_opt(&lun->be_lun->options,
4184				    "reordering");
4185				if (value != NULL &&
4186				    strcmp(value, "unrestricted") == 0) {
4187					control_page->queue_flags &=
4188					    ~SCP_QUEUE_ALG_MASK;
4189					control_page->queue_flags |=
4190					    SCP_QUEUE_ALG_UNRESTRICTED;
4191				}
4192				memcpy(&lun->mode_pages.control_page[
4193				    CTL_PAGE_CURRENT],
4194				       &lun->mode_pages.control_page[
4195				    CTL_PAGE_SAVED],
4196				       sizeof(control_page_default));
4197				page_index->page_data =
4198				    (uint8_t *)lun->mode_pages.control_page;
4199				break;
4200			}
4201			case 0x01:
4202				memcpy(&lun->mode_pages.control_ext_page[
4203				    CTL_PAGE_DEFAULT],
4204				       &control_ext_page_default,
4205				       sizeof(control_ext_page_default));
4206				memcpy(&lun->mode_pages.control_ext_page[
4207				    CTL_PAGE_CHANGEABLE],
4208				       &control_ext_page_changeable,
4209				       sizeof(control_ext_page_changeable));
4210				memcpy(&lun->mode_pages.control_ext_page[
4211				    CTL_PAGE_SAVED],
4212				       &control_ext_page_default,
4213				       sizeof(control_ext_page_default));
4214				memcpy(&lun->mode_pages.control_ext_page[
4215				    CTL_PAGE_CURRENT],
4216				       &lun->mode_pages.control_ext_page[
4217				    CTL_PAGE_SAVED],
4218				       sizeof(control_ext_page_default));
4219				page_index->page_data =
4220				    (uint8_t *)lun->mode_pages.control_ext_page;
4221				break;
4222			default:
4223				panic("subpage %#x for page %#x is incorrect!",
4224				      page_index->subpage, page_code);
4225			}
4226			break;
4227		}
4228		case SMS_INFO_EXCEPTIONS_PAGE: {
4229			switch (page_index->subpage) {
4230			case SMS_SUBPAGE_PAGE_0:
4231				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4232				       &ie_page_default,
4233				       sizeof(ie_page_default));
4234				memcpy(&lun->mode_pages.ie_page[
4235				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4236				       sizeof(ie_page_changeable));
4237				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4238				       &ie_page_default,
4239				       sizeof(ie_page_default));
4240				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4241				       &ie_page_default,
4242				       sizeof(ie_page_default));
4243				page_index->page_data =
4244					(uint8_t *)lun->mode_pages.ie_page;
4245				break;
4246			case 0x02: {
4247				struct ctl_logical_block_provisioning_page *page;
4248
4249				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4250				       &lbp_page_default,
4251				       sizeof(lbp_page_default));
4252				memcpy(&lun->mode_pages.lbp_page[
4253				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4254				       sizeof(lbp_page_changeable));
4255				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4256				       &lbp_page_default,
4257				       sizeof(lbp_page_default));
4258				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4259				value = ctl_get_opt(&lun->be_lun->options,
4260				    "avail-threshold");
4261				if (value != NULL &&
4262				    ctl_expand_number(value, &ival) == 0) {
4263					page->descr[0].flags |= SLBPPD_ENABLED |
4264					    SLBPPD_ARMING_DEC;
4265					if (lun->be_lun->blocksize)
4266						ival /= lun->be_lun->blocksize;
4267					else
4268						ival /= 512;
4269					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4270					    page->descr[0].count);
4271				}
4272				value = ctl_get_opt(&lun->be_lun->options,
4273				    "used-threshold");
4274				if (value != NULL &&
4275				    ctl_expand_number(value, &ival) == 0) {
4276					page->descr[1].flags |= SLBPPD_ENABLED |
4277					    SLBPPD_ARMING_INC;
4278					if (lun->be_lun->blocksize)
4279						ival /= lun->be_lun->blocksize;
4280					else
4281						ival /= 512;
4282					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4283					    page->descr[1].count);
4284				}
4285				value = ctl_get_opt(&lun->be_lun->options,
4286				    "pool-avail-threshold");
4287				if (value != NULL &&
4288				    ctl_expand_number(value, &ival) == 0) {
4289					page->descr[2].flags |= SLBPPD_ENABLED |
4290					    SLBPPD_ARMING_DEC;
4291					if (lun->be_lun->blocksize)
4292						ival /= lun->be_lun->blocksize;
4293					else
4294						ival /= 512;
4295					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4296					    page->descr[2].count);
4297				}
4298				value = ctl_get_opt(&lun->be_lun->options,
4299				    "pool-used-threshold");
4300				if (value != NULL &&
4301				    ctl_expand_number(value, &ival) == 0) {
4302					page->descr[3].flags |= SLBPPD_ENABLED |
4303					    SLBPPD_ARMING_INC;
4304					if (lun->be_lun->blocksize)
4305						ival /= lun->be_lun->blocksize;
4306					else
4307						ival /= 512;
4308					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4309					    page->descr[3].count);
4310				}
4311				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4312				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4313				       sizeof(lbp_page_default));
4314				page_index->page_data =
4315					(uint8_t *)lun->mode_pages.lbp_page;
4316				break;
4317			}
4318			default:
4319				panic("subpage %#x for page %#x is incorrect!",
4320				      page_index->subpage, page_code);
4321			}
4322			break;
4323		}
4324		case SMS_CDDVD_CAPS_PAGE:{
4325			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4326			    ("subpage %#x for page %#x is incorrect!",
4327			    page_index->subpage, page_code));
4328			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4329			       &cddvd_page_default,
4330			       sizeof(cddvd_page_default));
4331			memcpy(&lun->mode_pages.cddvd_page[
4332			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4333			       sizeof(cddvd_page_changeable));
4334			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4335			       &cddvd_page_default,
4336			       sizeof(cddvd_page_default));
4337			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4338			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4339			       sizeof(cddvd_page_default));
4340			page_index->page_data =
4341				(uint8_t *)lun->mode_pages.cddvd_page;
4342			break;
4343		}
4344		default:
4345			panic("invalid page code value %#x", page_code);
4346		}
4347	}
4348
4349	return (CTL_RETVAL_COMPLETE);
4350}
4351
4352static int
4353ctl_init_log_page_index(struct ctl_lun *lun)
4354{
4355	struct ctl_page_index *page_index;
4356	int i, j, k, prev;
4357
4358	memcpy(&lun->log_pages.index, log_page_index_template,
4359	       sizeof(log_page_index_template));
4360
4361	prev = -1;
4362	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4363
4364		page_index = &lun->log_pages.index[i];
4365		if (lun->be_lun->lun_type == T_DIRECT &&
4366		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4367			continue;
4368		if (lun->be_lun->lun_type == T_PROCESSOR &&
4369		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4370			continue;
4371		if (lun->be_lun->lun_type == T_CDROM &&
4372		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4373			continue;
4374
4375		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4376		    lun->backend->lun_attr == NULL)
4377			continue;
4378
4379		if (page_index->page_code != prev) {
4380			lun->log_pages.pages_page[j] = page_index->page_code;
4381			prev = page_index->page_code;
4382			j++;
4383		}
4384		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4385		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4386		k++;
4387	}
4388	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4389	lun->log_pages.index[0].page_len = j;
4390	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4391	lun->log_pages.index[1].page_len = k * 2;
4392	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4393	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4394	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4395	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4396	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4397	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4398
4399	return (CTL_RETVAL_COMPLETE);
4400}
4401
4402static int
4403hex2bin(const char *str, uint8_t *buf, int buf_size)
4404{
4405	int i;
4406	u_char c;
4407
4408	memset(buf, 0, buf_size);
4409	while (isspace(str[0]))
4410		str++;
4411	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4412		str += 2;
4413	buf_size *= 2;
4414	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4415		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4416			str++;
4417		c = str[i];
4418		if (isdigit(c))
4419			c -= '0';
4420		else if (isalpha(c))
4421			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4422		else
4423			break;
4424		if (c >= 16)
4425			break;
4426		if ((i & 1) == 0)
4427			buf[i / 2] |= (c << 4);
4428		else
4429			buf[i / 2] |= c;
4430	}
4431	return ((i + 1) / 2);
4432}
4433
4434/*
4435 * LUN allocation.
4436 *
4437 * Requirements:
4438 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4439 *   wants us to allocate the LUN and he can block.
4440 * - ctl_softc is always set
4441 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4442 *
4443 * Returns 0 for success, non-zero (errno) for failure.
4444 */
4445static int
4446ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4447	      struct ctl_be_lun *const be_lun)
4448{
4449	struct ctl_lun *nlun, *lun;
4450	struct scsi_vpd_id_descriptor *desc;
4451	struct scsi_vpd_id_t10 *t10id;
4452	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4453	int lun_number, lun_malloced;
4454	int devidlen, idlen1, idlen2 = 0, len;
4455
4456	if (be_lun == NULL)
4457		return (EINVAL);
4458
4459	/*
4460	 * We currently only support Direct Access or Processor LUN types.
4461	 */
4462	switch (be_lun->lun_type) {
4463	case T_DIRECT:
4464	case T_PROCESSOR:
4465	case T_CDROM:
4466		break;
4467	case T_SEQUENTIAL:
4468	case T_CHANGER:
4469	default:
4470		be_lun->lun_config_status(be_lun->be_lun,
4471					  CTL_LUN_CONFIG_FAILURE);
4472		break;
4473	}
4474	if (ctl_lun == NULL) {
4475		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4476		lun_malloced = 1;
4477	} else {
4478		lun_malloced = 0;
4479		lun = ctl_lun;
4480	}
4481
4482	memset(lun, 0, sizeof(*lun));
4483	if (lun_malloced)
4484		lun->flags = CTL_LUN_MALLOCED;
4485
4486	/* Generate LUN ID. */
4487	devidlen = max(CTL_DEVID_MIN_LEN,
4488	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4489	idlen1 = sizeof(*t10id) + devidlen;
4490	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4491	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4492	if (scsiname != NULL) {
4493		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4494		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4495	}
4496	eui = ctl_get_opt(&be_lun->options, "eui");
4497	if (eui != NULL) {
4498		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4499	}
4500	naa = ctl_get_opt(&be_lun->options, "naa");
4501	if (naa != NULL) {
4502		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4503	}
4504	uuid = ctl_get_opt(&be_lun->options, "uuid");
4505	if (uuid != NULL) {
4506		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4507	}
4508	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4509	    M_CTL, M_WAITOK | M_ZERO);
4510	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4511	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4512	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4513	desc->length = idlen1;
4514	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4515	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4516	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4517		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4518	} else {
4519		strncpy(t10id->vendor, vendor,
4520		    min(sizeof(t10id->vendor), strlen(vendor)));
4521	}
4522	strncpy((char *)t10id->vendor_spec_id,
4523	    (char *)be_lun->device_id, devidlen);
4524	if (scsiname != NULL) {
4525		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4526		    desc->length);
4527		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4528		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4529		    SVPD_ID_TYPE_SCSI_NAME;
4530		desc->length = idlen2;
4531		strlcpy(desc->identifier, scsiname, idlen2);
4532	}
4533	if (eui != NULL) {
4534		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4535		    desc->length);
4536		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4537		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4538		    SVPD_ID_TYPE_EUI64;
4539		desc->length = hex2bin(eui, desc->identifier, 16);
4540		desc->length = desc->length > 12 ? 16 :
4541		    (desc->length > 8 ? 12 : 8);
4542		len -= 16 - desc->length;
4543	}
4544	if (naa != NULL) {
4545		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4546		    desc->length);
4547		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4548		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4549		    SVPD_ID_TYPE_NAA;
4550		desc->length = hex2bin(naa, desc->identifier, 16);
4551		desc->length = desc->length > 8 ? 16 : 8;
4552		len -= 16 - desc->length;
4553	}
4554	if (uuid != NULL) {
4555		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4556		    desc->length);
4557		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4558		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4559		    SVPD_ID_TYPE_UUID;
4560		desc->identifier[0] = 0x10;
4561		hex2bin(uuid, &desc->identifier[2], 16);
4562		desc->length = 18;
4563	}
4564	lun->lun_devid->len = len;
4565
4566	mtx_lock(&ctl_softc->ctl_lock);
4567	/*
4568	 * See if the caller requested a particular LUN number.  If so, see
4569	 * if it is available.  Otherwise, allocate the first available LUN.
4570	 */
4571	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4572		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4573		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4574			mtx_unlock(&ctl_softc->ctl_lock);
4575			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4576				printf("ctl: requested LUN ID %d is higher "
4577				       "than CTL_MAX_LUNS - 1 (%d)\n",
4578				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4579			} else {
4580				/*
4581				 * XXX KDM return an error, or just assign
4582				 * another LUN ID in this case??
4583				 */
4584				printf("ctl: requested LUN ID %d is already "
4585				       "in use\n", be_lun->req_lun_id);
4586			}
4587fail:
4588			free(lun->lun_devid, M_CTL);
4589			if (lun->flags & CTL_LUN_MALLOCED)
4590				free(lun, M_CTL);
4591			be_lun->lun_config_status(be_lun->be_lun,
4592						  CTL_LUN_CONFIG_FAILURE);
4593			return (ENOSPC);
4594		}
4595		lun_number = be_lun->req_lun_id;
4596	} else {
4597		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4598		if (lun_number == -1) {
4599			mtx_unlock(&ctl_softc->ctl_lock);
4600			printf("ctl: can't allocate LUN, out of LUNs\n");
4601			goto fail;
4602		}
4603	}
4604	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4605	mtx_unlock(&ctl_softc->ctl_lock);
4606
4607	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4608	lun->lun = lun_number;
4609	lun->be_lun = be_lun;
4610	/*
4611	 * The processor LUN is always enabled.  Disk LUNs come on line
4612	 * disabled, and must be enabled by the backend.
4613	 */
4614	lun->flags |= CTL_LUN_DISABLED;
4615	lun->backend = be_lun->be;
4616	be_lun->ctl_lun = lun;
4617	be_lun->lun_id = lun_number;
4618	atomic_add_int(&be_lun->be->num_luns, 1);
4619	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4620		lun->flags |= CTL_LUN_EJECTED;
4621	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4622		lun->flags |= CTL_LUN_NO_MEDIA;
4623	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4624		lun->flags |= CTL_LUN_STOPPED;
4625
4626	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4627		lun->flags |= CTL_LUN_PRIMARY_SC;
4628
4629	value = ctl_get_opt(&be_lun->options, "removable");
4630	if (value != NULL) {
4631		if (strcmp(value, "on") == 0)
4632			lun->flags |= CTL_LUN_REMOVABLE;
4633	} else if (be_lun->lun_type == T_CDROM)
4634		lun->flags |= CTL_LUN_REMOVABLE;
4635
4636	lun->ctl_softc = ctl_softc;
4637#ifdef CTL_TIME_IO
4638	lun->last_busy = getsbinuptime();
4639#endif
4640	TAILQ_INIT(&lun->ooa_queue);
4641	TAILQ_INIT(&lun->blocked_queue);
4642	STAILQ_INIT(&lun->error_list);
4643	lun->ie_reported = 1;
4644	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4645	ctl_tpc_lun_init(lun);
4646	if (lun->flags & CTL_LUN_REMOVABLE) {
4647		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4648		    M_CTL, M_WAITOK);
4649	}
4650
4651	/*
4652	 * Initialize the mode and log page index.
4653	 */
4654	ctl_init_page_index(lun);
4655	ctl_init_log_page_index(lun);
4656
4657	/* Setup statistics gathering */
4658#ifdef CTL_LEGACY_STATS
4659	lun->legacy_stats.device_type = be_lun->lun_type;
4660	lun->legacy_stats.lun_number = lun_number;
4661	lun->legacy_stats.blocksize = be_lun->blocksize;
4662	if (be_lun->blocksize == 0)
4663		lun->legacy_stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4664	for (len = 0; len < CTL_MAX_PORTS; len++)
4665		lun->legacy_stats.ports[len].targ_port = len;
4666#endif /* CTL_LEGACY_STATS */
4667	lun->stats.item = lun_number;
4668
4669	/*
4670	 * Now, before we insert this lun on the lun list, set the lun
4671	 * inventory changed UA for all other luns.
4672	 */
4673	mtx_lock(&ctl_softc->ctl_lock);
4674	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4675		mtx_lock(&nlun->lun_lock);
4676		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4677		mtx_unlock(&nlun->lun_lock);
4678	}
4679	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4680	ctl_softc->ctl_luns[lun_number] = lun;
4681	ctl_softc->num_luns++;
4682	mtx_unlock(&ctl_softc->ctl_lock);
4683
4684	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4685	return (0);
4686}
4687
4688/*
4689 * Delete a LUN.
4690 * Assumptions:
4691 * - LUN has already been marked invalid and any pending I/O has been taken
4692 *   care of.
4693 */
4694static int
4695ctl_free_lun(struct ctl_lun *lun)
4696{
4697	struct ctl_softc *softc = lun->ctl_softc;
4698	struct ctl_lun *nlun;
4699	int i;
4700
4701	mtx_assert(&softc->ctl_lock, MA_OWNED);
4702
4703	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4704
4705	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4706
4707	softc->ctl_luns[lun->lun] = NULL;
4708
4709	if (!TAILQ_EMPTY(&lun->ooa_queue))
4710		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4711
4712	softc->num_luns--;
4713
4714	/*
4715	 * Tell the backend to free resources, if this LUN has a backend.
4716	 */
4717	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4718	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4719
4720	lun->ie_reportcnt = UINT32_MAX;
4721	callout_drain(&lun->ie_callout);
4722
4723	ctl_tpc_lun_shutdown(lun);
4724	mtx_destroy(&lun->lun_lock);
4725	free(lun->lun_devid, M_CTL);
4726	for (i = 0; i < CTL_MAX_PORTS; i++)
4727		free(lun->pending_ua[i], M_CTL);
4728	for (i = 0; i < CTL_MAX_PORTS; i++)
4729		free(lun->pr_keys[i], M_CTL);
4730	free(lun->write_buffer, M_CTL);
4731	free(lun->prevent, M_CTL);
4732	if (lun->flags & CTL_LUN_MALLOCED)
4733		free(lun, M_CTL);
4734
4735	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4736		mtx_lock(&nlun->lun_lock);
4737		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4738		mtx_unlock(&nlun->lun_lock);
4739	}
4740
4741	return (0);
4742}
4743
4744static void
4745ctl_create_lun(struct ctl_be_lun *be_lun)
4746{
4747
4748	/*
4749	 * ctl_alloc_lun() should handle all potential failure cases.
4750	 */
4751	ctl_alloc_lun(control_softc, NULL, be_lun);
4752}
4753
4754int
4755ctl_add_lun(struct ctl_be_lun *be_lun)
4756{
4757	struct ctl_softc *softc = control_softc;
4758
4759	mtx_lock(&softc->ctl_lock);
4760	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4761	mtx_unlock(&softc->ctl_lock);
4762	wakeup(&softc->pending_lun_queue);
4763
4764	return (0);
4765}
4766
4767int
4768ctl_enable_lun(struct ctl_be_lun *be_lun)
4769{
4770	struct ctl_softc *softc;
4771	struct ctl_port *port, *nport;
4772	struct ctl_lun *lun;
4773	int retval;
4774
4775	lun = (struct ctl_lun *)be_lun->ctl_lun;
4776	softc = lun->ctl_softc;
4777
4778	mtx_lock(&softc->ctl_lock);
4779	mtx_lock(&lun->lun_lock);
4780	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4781		/*
4782		 * eh?  Why did we get called if the LUN is already
4783		 * enabled?
4784		 */
4785		mtx_unlock(&lun->lun_lock);
4786		mtx_unlock(&softc->ctl_lock);
4787		return (0);
4788	}
4789	lun->flags &= ~CTL_LUN_DISABLED;
4790	mtx_unlock(&lun->lun_lock);
4791
4792	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4793		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4794		    port->lun_map != NULL || port->lun_enable == NULL)
4795			continue;
4796
4797		/*
4798		 * Drop the lock while we call the FETD's enable routine.
4799		 * This can lead to a callback into CTL (at least in the
4800		 * case of the internal initiator frontend.
4801		 */
4802		mtx_unlock(&softc->ctl_lock);
4803		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4804		mtx_lock(&softc->ctl_lock);
4805		if (retval != 0) {
4806			printf("%s: FETD %s port %d returned error "
4807			       "%d for lun_enable on lun %jd\n",
4808			       __func__, port->port_name, port->targ_port,
4809			       retval, (intmax_t)lun->lun);
4810		}
4811	}
4812
4813	mtx_unlock(&softc->ctl_lock);
4814	ctl_isc_announce_lun(lun);
4815
4816	return (0);
4817}
4818
4819int
4820ctl_disable_lun(struct ctl_be_lun *be_lun)
4821{
4822	struct ctl_softc *softc;
4823	struct ctl_port *port;
4824	struct ctl_lun *lun;
4825	int retval;
4826
4827	lun = (struct ctl_lun *)be_lun->ctl_lun;
4828	softc = lun->ctl_softc;
4829
4830	mtx_lock(&softc->ctl_lock);
4831	mtx_lock(&lun->lun_lock);
4832	if (lun->flags & CTL_LUN_DISABLED) {
4833		mtx_unlock(&lun->lun_lock);
4834		mtx_unlock(&softc->ctl_lock);
4835		return (0);
4836	}
4837	lun->flags |= CTL_LUN_DISABLED;
4838	mtx_unlock(&lun->lun_lock);
4839
4840	STAILQ_FOREACH(port, &softc->port_list, links) {
4841		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4842		    port->lun_map != NULL || port->lun_disable == NULL)
4843			continue;
4844
4845		/*
4846		 * Drop the lock before we call the frontend's disable
4847		 * routine, to avoid lock order reversals.
4848		 *
4849		 * XXX KDM what happens if the frontend list changes while
4850		 * we're traversing it?  It's unlikely, but should be handled.
4851		 */
4852		mtx_unlock(&softc->ctl_lock);
4853		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4854		mtx_lock(&softc->ctl_lock);
4855		if (retval != 0) {
4856			printf("%s: FETD %s port %d returned error "
4857			       "%d for lun_disable on lun %jd\n",
4858			       __func__, port->port_name, port->targ_port,
4859			       retval, (intmax_t)lun->lun);
4860		}
4861	}
4862
4863	mtx_unlock(&softc->ctl_lock);
4864	ctl_isc_announce_lun(lun);
4865
4866	return (0);
4867}
4868
4869int
4870ctl_start_lun(struct ctl_be_lun *be_lun)
4871{
4872	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4873
4874	mtx_lock(&lun->lun_lock);
4875	lun->flags &= ~CTL_LUN_STOPPED;
4876	mtx_unlock(&lun->lun_lock);
4877	return (0);
4878}
4879
4880int
4881ctl_stop_lun(struct ctl_be_lun *be_lun)
4882{
4883	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4884
4885	mtx_lock(&lun->lun_lock);
4886	lun->flags |= CTL_LUN_STOPPED;
4887	mtx_unlock(&lun->lun_lock);
4888	return (0);
4889}
4890
4891int
4892ctl_lun_no_media(struct ctl_be_lun *be_lun)
4893{
4894	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4895
4896	mtx_lock(&lun->lun_lock);
4897	lun->flags |= CTL_LUN_NO_MEDIA;
4898	mtx_unlock(&lun->lun_lock);
4899	return (0);
4900}
4901
4902int
4903ctl_lun_has_media(struct ctl_be_lun *be_lun)
4904{
4905	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4906	union ctl_ha_msg msg;
4907
4908	mtx_lock(&lun->lun_lock);
4909	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4910	if (lun->flags & CTL_LUN_REMOVABLE)
4911		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4912	mtx_unlock(&lun->lun_lock);
4913	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4914	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4915		bzero(&msg.ua, sizeof(msg.ua));
4916		msg.hdr.msg_type = CTL_MSG_UA;
4917		msg.hdr.nexus.initid = -1;
4918		msg.hdr.nexus.targ_port = -1;
4919		msg.hdr.nexus.targ_lun = lun->lun;
4920		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4921		msg.ua.ua_all = 1;
4922		msg.ua.ua_set = 1;
4923		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4924		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4925		    M_WAITOK);
4926	}
4927	return (0);
4928}
4929
4930int
4931ctl_lun_ejected(struct ctl_be_lun *be_lun)
4932{
4933	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4934
4935	mtx_lock(&lun->lun_lock);
4936	lun->flags |= CTL_LUN_EJECTED;
4937	mtx_unlock(&lun->lun_lock);
4938	return (0);
4939}
4940
4941int
4942ctl_lun_primary(struct ctl_be_lun *be_lun)
4943{
4944	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4945
4946	mtx_lock(&lun->lun_lock);
4947	lun->flags |= CTL_LUN_PRIMARY_SC;
4948	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4949	mtx_unlock(&lun->lun_lock);
4950	ctl_isc_announce_lun(lun);
4951	return (0);
4952}
4953
4954int
4955ctl_lun_secondary(struct ctl_be_lun *be_lun)
4956{
4957	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4958
4959	mtx_lock(&lun->lun_lock);
4960	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4961	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4962	mtx_unlock(&lun->lun_lock);
4963	ctl_isc_announce_lun(lun);
4964	return (0);
4965}
4966
4967int
4968ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4969{
4970	struct ctl_softc *softc;
4971	struct ctl_lun *lun;
4972
4973	lun = (struct ctl_lun *)be_lun->ctl_lun;
4974	softc = lun->ctl_softc;
4975
4976	mtx_lock(&lun->lun_lock);
4977
4978	/*
4979	 * The LUN needs to be disabled before it can be marked invalid.
4980	 */
4981	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4982		mtx_unlock(&lun->lun_lock);
4983		return (-1);
4984	}
4985	/*
4986	 * Mark the LUN invalid.
4987	 */
4988	lun->flags |= CTL_LUN_INVALID;
4989
4990	/*
4991	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4992	 * If we have something in the OOA queue, we'll free it when the
4993	 * last I/O completes.
4994	 */
4995	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4996		mtx_unlock(&lun->lun_lock);
4997		mtx_lock(&softc->ctl_lock);
4998		ctl_free_lun(lun);
4999		mtx_unlock(&softc->ctl_lock);
5000	} else
5001		mtx_unlock(&lun->lun_lock);
5002
5003	return (0);
5004}
5005
5006void
5007ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5008{
5009	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5010	union ctl_ha_msg msg;
5011
5012	mtx_lock(&lun->lun_lock);
5013	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5014	mtx_unlock(&lun->lun_lock);
5015	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5016		/* Send msg to other side. */
5017		bzero(&msg.ua, sizeof(msg.ua));
5018		msg.hdr.msg_type = CTL_MSG_UA;
5019		msg.hdr.nexus.initid = -1;
5020		msg.hdr.nexus.targ_port = -1;
5021		msg.hdr.nexus.targ_lun = lun->lun;
5022		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5023		msg.ua.ua_all = 1;
5024		msg.ua.ua_set = 1;
5025		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5026		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5027		    M_WAITOK);
5028	}
5029}
5030
5031/*
5032 * Backend "memory move is complete" callback for requests that never
5033 * make it down to say RAIDCore's configuration code.
5034 */
5035int
5036ctl_config_move_done(union ctl_io *io)
5037{
5038	int retval;
5039
5040	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5041	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5042	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5043
5044	if ((io->io_hdr.port_status != 0) &&
5045	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5046	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5047		/*
5048		 * For hardware error sense keys, the sense key
5049		 * specific value is defined to be a retry count,
5050		 * but we use it to pass back an internal FETD
5051		 * error code.  XXX KDM  Hopefully the FETD is only
5052		 * using 16 bits for an error code, since that's
5053		 * all the space we have in the sks field.
5054		 */
5055		ctl_set_internal_failure(&io->scsiio,
5056					 /*sks_valid*/ 1,
5057					 /*retry_count*/
5058					 io->io_hdr.port_status);
5059	}
5060
5061	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5062		ctl_data_print(io);
5063	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5064	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5065	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5066	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5067		/*
5068		 * XXX KDM just assuming a single pointer here, and not a
5069		 * S/G list.  If we start using S/G lists for config data,
5070		 * we'll need to know how to clean them up here as well.
5071		 */
5072		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5073			free(io->scsiio.kern_data_ptr, M_CTL);
5074		ctl_done(io);
5075		retval = CTL_RETVAL_COMPLETE;
5076	} else {
5077		/*
5078		 * XXX KDM now we need to continue data movement.  Some
5079		 * options:
5080		 * - call ctl_scsiio() again?  We don't do this for data
5081		 *   writes, because for those at least we know ahead of
5082		 *   time where the write will go and how long it is.  For
5083		 *   config writes, though, that information is largely
5084		 *   contained within the write itself, thus we need to
5085		 *   parse out the data again.
5086		 *
5087		 * - Call some other function once the data is in?
5088		 */
5089
5090		/*
5091		 * XXX KDM call ctl_scsiio() again for now, and check flag
5092		 * bits to see whether we're allocated or not.
5093		 */
5094		retval = ctl_scsiio(&io->scsiio);
5095	}
5096	return (retval);
5097}
5098
5099/*
5100 * This gets called by a backend driver when it is done with a
5101 * data_submit method.
5102 */
5103void
5104ctl_data_submit_done(union ctl_io *io)
5105{
5106	/*
5107	 * If the IO_CONT flag is set, we need to call the supplied
5108	 * function to continue processing the I/O, instead of completing
5109	 * the I/O just yet.
5110	 *
5111	 * If there is an error, though, we don't want to keep processing.
5112	 * Instead, just send status back to the initiator.
5113	 */
5114	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5115	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5116	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5117	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5118		io->scsiio.io_cont(io);
5119		return;
5120	}
5121	ctl_done(io);
5122}
5123
5124/*
5125 * This gets called by a backend driver when it is done with a
5126 * configuration write.
5127 */
5128void
5129ctl_config_write_done(union ctl_io *io)
5130{
5131	uint8_t *buf;
5132
5133	/*
5134	 * If the IO_CONT flag is set, we need to call the supplied
5135	 * function to continue processing the I/O, instead of completing
5136	 * the I/O just yet.
5137	 *
5138	 * If there is an error, though, we don't want to keep processing.
5139	 * Instead, just send status back to the initiator.
5140	 */
5141	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5142	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5143	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5144	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5145		io->scsiio.io_cont(io);
5146		return;
5147	}
5148	/*
5149	 * Since a configuration write can be done for commands that actually
5150	 * have data allocated, like write buffer, and commands that have
5151	 * no data, like start/stop unit, we need to check here.
5152	 */
5153	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5154		buf = io->scsiio.kern_data_ptr;
5155	else
5156		buf = NULL;
5157	ctl_done(io);
5158	if (buf)
5159		free(buf, M_CTL);
5160}
5161
5162void
5163ctl_config_read_done(union ctl_io *io)
5164{
5165	uint8_t *buf;
5166
5167	/*
5168	 * If there is some error -- we are done, skip data transfer.
5169	 */
5170	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5171	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5172	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5173		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5174			buf = io->scsiio.kern_data_ptr;
5175		else
5176			buf = NULL;
5177		ctl_done(io);
5178		if (buf)
5179			free(buf, M_CTL);
5180		return;
5181	}
5182
5183	/*
5184	 * If the IO_CONT flag is set, we need to call the supplied
5185	 * function to continue processing the I/O, instead of completing
5186	 * the I/O just yet.
5187	 */
5188	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5189		io->scsiio.io_cont(io);
5190		return;
5191	}
5192
5193	ctl_datamove(io);
5194}
5195
5196/*
5197 * SCSI release command.
5198 */
5199int
5200ctl_scsi_release(struct ctl_scsiio *ctsio)
5201{
5202	struct ctl_lun *lun = CTL_LUN(ctsio);
5203	uint32_t residx;
5204
5205	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5206
5207	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5208
5209	/*
5210	 * XXX KDM right now, we only support LUN reservation.  We don't
5211	 * support 3rd party reservations, or extent reservations, which
5212	 * might actually need the parameter list.  If we've gotten this
5213	 * far, we've got a LUN reservation.  Anything else got kicked out
5214	 * above.  So, according to SPC, ignore the length.
5215	 */
5216
5217	mtx_lock(&lun->lun_lock);
5218
5219	/*
5220	 * According to SPC, it is not an error for an intiator to attempt
5221	 * to release a reservation on a LUN that isn't reserved, or that
5222	 * is reserved by another initiator.  The reservation can only be
5223	 * released, though, by the initiator who made it or by one of
5224	 * several reset type events.
5225	 */
5226	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5227			lun->flags &= ~CTL_LUN_RESERVED;
5228
5229	mtx_unlock(&lun->lun_lock);
5230
5231	ctl_set_success(ctsio);
5232	ctl_done((union ctl_io *)ctsio);
5233	return (CTL_RETVAL_COMPLETE);
5234}
5235
5236int
5237ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5238{
5239	struct ctl_lun *lun = CTL_LUN(ctsio);
5240	uint32_t residx;
5241
5242	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5243
5244	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5245
5246	/*
5247	 * XXX KDM right now, we only support LUN reservation.  We don't
5248	 * support 3rd party reservations, or extent reservations, which
5249	 * might actually need the parameter list.  If we've gotten this
5250	 * far, we've got a LUN reservation.  Anything else got kicked out
5251	 * above.  So, according to SPC, ignore the length.
5252	 */
5253
5254	mtx_lock(&lun->lun_lock);
5255	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5256		ctl_set_reservation_conflict(ctsio);
5257		goto bailout;
5258	}
5259
5260	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5261	if (lun->flags & CTL_LUN_PR_RESERVED) {
5262		ctl_set_success(ctsio);
5263		goto bailout;
5264	}
5265
5266	lun->flags |= CTL_LUN_RESERVED;
5267	lun->res_idx = residx;
5268	ctl_set_success(ctsio);
5269
5270bailout:
5271	mtx_unlock(&lun->lun_lock);
5272	ctl_done((union ctl_io *)ctsio);
5273	return (CTL_RETVAL_COMPLETE);
5274}
5275
5276int
5277ctl_start_stop(struct ctl_scsiio *ctsio)
5278{
5279	struct ctl_lun *lun = CTL_LUN(ctsio);
5280	struct scsi_start_stop_unit *cdb;
5281	int retval;
5282
5283	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5284
5285	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5286
5287	if ((cdb->how & SSS_PC_MASK) == 0) {
5288		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5289		    (cdb->how & SSS_START) == 0) {
5290			uint32_t residx;
5291
5292			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5293			if (ctl_get_prkey(lun, residx) == 0 ||
5294			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5295
5296				ctl_set_reservation_conflict(ctsio);
5297				ctl_done((union ctl_io *)ctsio);
5298				return (CTL_RETVAL_COMPLETE);
5299			}
5300		}
5301
5302		if ((cdb->how & SSS_LOEJ) &&
5303		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5304			ctl_set_invalid_field(ctsio,
5305					      /*sks_valid*/ 1,
5306					      /*command*/ 1,
5307					      /*field*/ 4,
5308					      /*bit_valid*/ 1,
5309					      /*bit*/ 1);
5310			ctl_done((union ctl_io *)ctsio);
5311			return (CTL_RETVAL_COMPLETE);
5312		}
5313
5314		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5315		    lun->prevent_count > 0) {
5316			/* "Medium removal prevented" */
5317			ctl_set_sense(ctsio, /*current_error*/ 1,
5318			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5319			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5320			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5321			ctl_done((union ctl_io *)ctsio);
5322			return (CTL_RETVAL_COMPLETE);
5323		}
5324	}
5325
5326	retval = lun->backend->config_write((union ctl_io *)ctsio);
5327	return (retval);
5328}
5329
5330int
5331ctl_prevent_allow(struct ctl_scsiio *ctsio)
5332{
5333	struct ctl_lun *lun = CTL_LUN(ctsio);
5334	struct scsi_prevent *cdb;
5335	int retval;
5336	uint32_t initidx;
5337
5338	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5339
5340	cdb = (struct scsi_prevent *)ctsio->cdb;
5341
5342	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5343		ctl_set_invalid_opcode(ctsio);
5344		ctl_done((union ctl_io *)ctsio);
5345		return (CTL_RETVAL_COMPLETE);
5346	}
5347
5348	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5349	mtx_lock(&lun->lun_lock);
5350	if ((cdb->how & PR_PREVENT) &&
5351	    ctl_is_set(lun->prevent, initidx) == 0) {
5352		ctl_set_mask(lun->prevent, initidx);
5353		lun->prevent_count++;
5354	} else if ((cdb->how & PR_PREVENT) == 0 &&
5355	    ctl_is_set(lun->prevent, initidx)) {
5356		ctl_clear_mask(lun->prevent, initidx);
5357		lun->prevent_count--;
5358	}
5359	mtx_unlock(&lun->lun_lock);
5360	retval = lun->backend->config_write((union ctl_io *)ctsio);
5361	return (retval);
5362}
5363
5364/*
5365 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5366 * we don't really do anything with the LBA and length fields if the user
5367 * passes them in.  Instead we'll just flush out the cache for the entire
5368 * LUN.
5369 */
5370int
5371ctl_sync_cache(struct ctl_scsiio *ctsio)
5372{
5373	struct ctl_lun *lun = CTL_LUN(ctsio);
5374	struct ctl_lba_len_flags *lbalen;
5375	uint64_t starting_lba;
5376	uint32_t block_count;
5377	int retval;
5378	uint8_t byte2;
5379
5380	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5381
5382	retval = 0;
5383
5384	switch (ctsio->cdb[0]) {
5385	case SYNCHRONIZE_CACHE: {
5386		struct scsi_sync_cache *cdb;
5387		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5388
5389		starting_lba = scsi_4btoul(cdb->begin_lba);
5390		block_count = scsi_2btoul(cdb->lb_count);
5391		byte2 = cdb->byte2;
5392		break;
5393	}
5394	case SYNCHRONIZE_CACHE_16: {
5395		struct scsi_sync_cache_16 *cdb;
5396		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5397
5398		starting_lba = scsi_8btou64(cdb->begin_lba);
5399		block_count = scsi_4btoul(cdb->lb_count);
5400		byte2 = cdb->byte2;
5401		break;
5402	}
5403	default:
5404		ctl_set_invalid_opcode(ctsio);
5405		ctl_done((union ctl_io *)ctsio);
5406		goto bailout;
5407		break; /* NOTREACHED */
5408	}
5409
5410	/*
5411	 * We check the LBA and length, but don't do anything with them.
5412	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5413	 * get flushed.  This check will just help satisfy anyone who wants
5414	 * to see an error for an out of range LBA.
5415	 */
5416	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5417		ctl_set_lba_out_of_range(ctsio,
5418		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5419		ctl_done((union ctl_io *)ctsio);
5420		goto bailout;
5421	}
5422
5423	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5424	lbalen->lba = starting_lba;
5425	lbalen->len = block_count;
5426	lbalen->flags = byte2;
5427	retval = lun->backend->config_write((union ctl_io *)ctsio);
5428
5429bailout:
5430	return (retval);
5431}
5432
5433int
5434ctl_format(struct ctl_scsiio *ctsio)
5435{
5436	struct scsi_format *cdb;
5437	int length, defect_list_len;
5438
5439	CTL_DEBUG_PRINT(("ctl_format\n"));
5440
5441	cdb = (struct scsi_format *)ctsio->cdb;
5442
5443	length = 0;
5444	if (cdb->byte2 & SF_FMTDATA) {
5445		if (cdb->byte2 & SF_LONGLIST)
5446			length = sizeof(struct scsi_format_header_long);
5447		else
5448			length = sizeof(struct scsi_format_header_short);
5449	}
5450
5451	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5452	 && (length > 0)) {
5453		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5454		ctsio->kern_data_len = length;
5455		ctsio->kern_total_len = length;
5456		ctsio->kern_data_resid = 0;
5457		ctsio->kern_rel_offset = 0;
5458		ctsio->kern_sg_entries = 0;
5459		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5460		ctsio->be_move_done = ctl_config_move_done;
5461		ctl_datamove((union ctl_io *)ctsio);
5462
5463		return (CTL_RETVAL_COMPLETE);
5464	}
5465
5466	defect_list_len = 0;
5467
5468	if (cdb->byte2 & SF_FMTDATA) {
5469		if (cdb->byte2 & SF_LONGLIST) {
5470			struct scsi_format_header_long *header;
5471
5472			header = (struct scsi_format_header_long *)
5473				ctsio->kern_data_ptr;
5474
5475			defect_list_len = scsi_4btoul(header->defect_list_len);
5476			if (defect_list_len != 0) {
5477				ctl_set_invalid_field(ctsio,
5478						      /*sks_valid*/ 1,
5479						      /*command*/ 0,
5480						      /*field*/ 2,
5481						      /*bit_valid*/ 0,
5482						      /*bit*/ 0);
5483				goto bailout;
5484			}
5485		} else {
5486			struct scsi_format_header_short *header;
5487
5488			header = (struct scsi_format_header_short *)
5489				ctsio->kern_data_ptr;
5490
5491			defect_list_len = scsi_2btoul(header->defect_list_len);
5492			if (defect_list_len != 0) {
5493				ctl_set_invalid_field(ctsio,
5494						      /*sks_valid*/ 1,
5495						      /*command*/ 0,
5496						      /*field*/ 2,
5497						      /*bit_valid*/ 0,
5498						      /*bit*/ 0);
5499				goto bailout;
5500			}
5501		}
5502	}
5503
5504	ctl_set_success(ctsio);
5505bailout:
5506
5507	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5508		free(ctsio->kern_data_ptr, M_CTL);
5509		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5510	}
5511
5512	ctl_done((union ctl_io *)ctsio);
5513	return (CTL_RETVAL_COMPLETE);
5514}
5515
5516int
5517ctl_read_buffer(struct ctl_scsiio *ctsio)
5518{
5519	struct ctl_lun *lun = CTL_LUN(ctsio);
5520	uint64_t buffer_offset;
5521	uint32_t len;
5522	uint8_t byte2;
5523	static uint8_t descr[4];
5524	static uint8_t echo_descr[4] = { 0 };
5525
5526	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5527
5528	switch (ctsio->cdb[0]) {
5529	case READ_BUFFER: {
5530		struct scsi_read_buffer *cdb;
5531
5532		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5533		buffer_offset = scsi_3btoul(cdb->offset);
5534		len = scsi_3btoul(cdb->length);
5535		byte2 = cdb->byte2;
5536		break;
5537	}
5538	case READ_BUFFER_16: {
5539		struct scsi_read_buffer_16 *cdb;
5540
5541		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5542		buffer_offset = scsi_8btou64(cdb->offset);
5543		len = scsi_4btoul(cdb->length);
5544		byte2 = cdb->byte2;
5545		break;
5546	}
5547	default: /* This shouldn't happen. */
5548		ctl_set_invalid_opcode(ctsio);
5549		ctl_done((union ctl_io *)ctsio);
5550		return (CTL_RETVAL_COMPLETE);
5551	}
5552
5553	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5554	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5555		ctl_set_invalid_field(ctsio,
5556				      /*sks_valid*/ 1,
5557				      /*command*/ 1,
5558				      /*field*/ 6,
5559				      /*bit_valid*/ 0,
5560				      /*bit*/ 0);
5561		ctl_done((union ctl_io *)ctsio);
5562		return (CTL_RETVAL_COMPLETE);
5563	}
5564
5565	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5566		descr[0] = 0;
5567		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5568		ctsio->kern_data_ptr = descr;
5569		len = min(len, sizeof(descr));
5570	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5571		ctsio->kern_data_ptr = echo_descr;
5572		len = min(len, sizeof(echo_descr));
5573	} else {
5574		if (lun->write_buffer == NULL) {
5575			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5576			    M_CTL, M_WAITOK);
5577		}
5578		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5579	}
5580	ctsio->kern_data_len = len;
5581	ctsio->kern_total_len = len;
5582	ctsio->kern_data_resid = 0;
5583	ctsio->kern_rel_offset = 0;
5584	ctsio->kern_sg_entries = 0;
5585	ctl_set_success(ctsio);
5586	ctsio->be_move_done = ctl_config_move_done;
5587	ctl_datamove((union ctl_io *)ctsio);
5588	return (CTL_RETVAL_COMPLETE);
5589}
5590
5591int
5592ctl_write_buffer(struct ctl_scsiio *ctsio)
5593{
5594	struct ctl_lun *lun = CTL_LUN(ctsio);
5595	struct scsi_write_buffer *cdb;
5596	int buffer_offset, len;
5597
5598	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5599
5600	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5601
5602	len = scsi_3btoul(cdb->length);
5603	buffer_offset = scsi_3btoul(cdb->offset);
5604
5605	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5606		ctl_set_invalid_field(ctsio,
5607				      /*sks_valid*/ 1,
5608				      /*command*/ 1,
5609				      /*field*/ 6,
5610				      /*bit_valid*/ 0,
5611				      /*bit*/ 0);
5612		ctl_done((union ctl_io *)ctsio);
5613		return (CTL_RETVAL_COMPLETE);
5614	}
5615
5616	/*
5617	 * If we've got a kernel request that hasn't been malloced yet,
5618	 * malloc it and tell the caller the data buffer is here.
5619	 */
5620	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5621		if (lun->write_buffer == NULL) {
5622			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5623			    M_CTL, M_WAITOK);
5624		}
5625		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5626		ctsio->kern_data_len = len;
5627		ctsio->kern_total_len = len;
5628		ctsio->kern_data_resid = 0;
5629		ctsio->kern_rel_offset = 0;
5630		ctsio->kern_sg_entries = 0;
5631		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5632		ctsio->be_move_done = ctl_config_move_done;
5633		ctl_datamove((union ctl_io *)ctsio);
5634
5635		return (CTL_RETVAL_COMPLETE);
5636	}
5637
5638	ctl_set_success(ctsio);
5639	ctl_done((union ctl_io *)ctsio);
5640	return (CTL_RETVAL_COMPLETE);
5641}
5642
5643int
5644ctl_write_same(struct ctl_scsiio *ctsio)
5645{
5646	struct ctl_lun *lun = CTL_LUN(ctsio);
5647	struct ctl_lba_len_flags *lbalen;
5648	uint64_t lba;
5649	uint32_t num_blocks;
5650	int len, retval;
5651	uint8_t byte2;
5652
5653	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5654
5655	switch (ctsio->cdb[0]) {
5656	case WRITE_SAME_10: {
5657		struct scsi_write_same_10 *cdb;
5658
5659		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5660
5661		lba = scsi_4btoul(cdb->addr);
5662		num_blocks = scsi_2btoul(cdb->length);
5663		byte2 = cdb->byte2;
5664		break;
5665	}
5666	case WRITE_SAME_16: {
5667		struct scsi_write_same_16 *cdb;
5668
5669		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5670
5671		lba = scsi_8btou64(cdb->addr);
5672		num_blocks = scsi_4btoul(cdb->length);
5673		byte2 = cdb->byte2;
5674		break;
5675	}
5676	default:
5677		/*
5678		 * We got a command we don't support.  This shouldn't
5679		 * happen, commands should be filtered out above us.
5680		 */
5681		ctl_set_invalid_opcode(ctsio);
5682		ctl_done((union ctl_io *)ctsio);
5683
5684		return (CTL_RETVAL_COMPLETE);
5685		break; /* NOTREACHED */
5686	}
5687
5688	/* ANCHOR flag can be used only together with UNMAP */
5689	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5690		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5691		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5692		ctl_done((union ctl_io *)ctsio);
5693		return (CTL_RETVAL_COMPLETE);
5694	}
5695
5696	/*
5697	 * The first check is to make sure we're in bounds, the second
5698	 * check is to catch wrap-around problems.  If the lba + num blocks
5699	 * is less than the lba, then we've wrapped around and the block
5700	 * range is invalid anyway.
5701	 */
5702	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5703	 || ((lba + num_blocks) < lba)) {
5704		ctl_set_lba_out_of_range(ctsio,
5705		    MAX(lba, lun->be_lun->maxlba + 1));
5706		ctl_done((union ctl_io *)ctsio);
5707		return (CTL_RETVAL_COMPLETE);
5708	}
5709
5710	/* Zero number of blocks means "to the last logical block" */
5711	if (num_blocks == 0) {
5712		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5713			ctl_set_invalid_field(ctsio,
5714					      /*sks_valid*/ 0,
5715					      /*command*/ 1,
5716					      /*field*/ 0,
5717					      /*bit_valid*/ 0,
5718					      /*bit*/ 0);
5719			ctl_done((union ctl_io *)ctsio);
5720			return (CTL_RETVAL_COMPLETE);
5721		}
5722		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5723	}
5724
5725	len = lun->be_lun->blocksize;
5726
5727	/*
5728	 * If we've got a kernel request that hasn't been malloced yet,
5729	 * malloc it and tell the caller the data buffer is here.
5730	 */
5731	if ((byte2 & SWS_NDOB) == 0 &&
5732	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5733		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5734		ctsio->kern_data_len = len;
5735		ctsio->kern_total_len = len;
5736		ctsio->kern_data_resid = 0;
5737		ctsio->kern_rel_offset = 0;
5738		ctsio->kern_sg_entries = 0;
5739		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5740		ctsio->be_move_done = ctl_config_move_done;
5741		ctl_datamove((union ctl_io *)ctsio);
5742
5743		return (CTL_RETVAL_COMPLETE);
5744	}
5745
5746	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5747	lbalen->lba = lba;
5748	lbalen->len = num_blocks;
5749	lbalen->flags = byte2;
5750	retval = lun->backend->config_write((union ctl_io *)ctsio);
5751
5752	return (retval);
5753}
5754
5755int
5756ctl_unmap(struct ctl_scsiio *ctsio)
5757{
5758	struct ctl_lun *lun = CTL_LUN(ctsio);
5759	struct scsi_unmap *cdb;
5760	struct ctl_ptr_len_flags *ptrlen;
5761	struct scsi_unmap_header *hdr;
5762	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5763	uint64_t lba;
5764	uint32_t num_blocks;
5765	int len, retval;
5766	uint8_t byte2;
5767
5768	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5769
5770	cdb = (struct scsi_unmap *)ctsio->cdb;
5771	len = scsi_2btoul(cdb->length);
5772	byte2 = cdb->byte2;
5773
5774	/*
5775	 * If we've got a kernel request that hasn't been malloced yet,
5776	 * malloc it and tell the caller the data buffer is here.
5777	 */
5778	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5779		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5780		ctsio->kern_data_len = len;
5781		ctsio->kern_total_len = len;
5782		ctsio->kern_data_resid = 0;
5783		ctsio->kern_rel_offset = 0;
5784		ctsio->kern_sg_entries = 0;
5785		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5786		ctsio->be_move_done = ctl_config_move_done;
5787		ctl_datamove((union ctl_io *)ctsio);
5788
5789		return (CTL_RETVAL_COMPLETE);
5790	}
5791
5792	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5793	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5794	if (len < sizeof (*hdr) ||
5795	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5796	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5797	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5798		ctl_set_invalid_field(ctsio,
5799				      /*sks_valid*/ 0,
5800				      /*command*/ 0,
5801				      /*field*/ 0,
5802				      /*bit_valid*/ 0,
5803				      /*bit*/ 0);
5804		goto done;
5805	}
5806	len = scsi_2btoul(hdr->desc_length);
5807	buf = (struct scsi_unmap_desc *)(hdr + 1);
5808	end = buf + len / sizeof(*buf);
5809
5810	endnz = buf;
5811	for (range = buf; range < end; range++) {
5812		lba = scsi_8btou64(range->lba);
5813		num_blocks = scsi_4btoul(range->length);
5814		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5815		 || ((lba + num_blocks) < lba)) {
5816			ctl_set_lba_out_of_range(ctsio,
5817			    MAX(lba, lun->be_lun->maxlba + 1));
5818			ctl_done((union ctl_io *)ctsio);
5819			return (CTL_RETVAL_COMPLETE);
5820		}
5821		if (num_blocks != 0)
5822			endnz = range + 1;
5823	}
5824
5825	/*
5826	 * Block backend can not handle zero last range.
5827	 * Filter it out and return if there is nothing left.
5828	 */
5829	len = (uint8_t *)endnz - (uint8_t *)buf;
5830	if (len == 0) {
5831		ctl_set_success(ctsio);
5832		goto done;
5833	}
5834
5835	mtx_lock(&lun->lun_lock);
5836	ptrlen = (struct ctl_ptr_len_flags *)
5837	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5838	ptrlen->ptr = (void *)buf;
5839	ptrlen->len = len;
5840	ptrlen->flags = byte2;
5841	ctl_check_blocked(lun);
5842	mtx_unlock(&lun->lun_lock);
5843
5844	retval = lun->backend->config_write((union ctl_io *)ctsio);
5845	return (retval);
5846
5847done:
5848	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5849		free(ctsio->kern_data_ptr, M_CTL);
5850		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5851	}
5852	ctl_done((union ctl_io *)ctsio);
5853	return (CTL_RETVAL_COMPLETE);
5854}
5855
5856int
5857ctl_default_page_handler(struct ctl_scsiio *ctsio,
5858			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5859{
5860	struct ctl_lun *lun = CTL_LUN(ctsio);
5861	uint8_t *current_cp;
5862	int set_ua;
5863	uint32_t initidx;
5864
5865	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5866	set_ua = 0;
5867
5868	current_cp = (page_index->page_data + (page_index->page_len *
5869	    CTL_PAGE_CURRENT));
5870
5871	mtx_lock(&lun->lun_lock);
5872	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5873		memcpy(current_cp, page_ptr, page_index->page_len);
5874		set_ua = 1;
5875	}
5876	if (set_ua != 0)
5877		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5878	mtx_unlock(&lun->lun_lock);
5879	if (set_ua) {
5880		ctl_isc_announce_mode(lun,
5881		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5882		    page_index->page_code, page_index->subpage);
5883	}
5884	return (CTL_RETVAL_COMPLETE);
5885}
5886
5887static void
5888ctl_ie_timer(void *arg)
5889{
5890	struct ctl_lun *lun = arg;
5891	uint64_t t;
5892
5893	if (lun->ie_asc == 0)
5894		return;
5895
5896	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5897		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5898	else
5899		lun->ie_reported = 0;
5900
5901	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5902		lun->ie_reportcnt++;
5903		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5904		if (t == 0 || t == UINT32_MAX)
5905			t = 3000;  /* 5 min */
5906		callout_schedule(&lun->ie_callout, t * hz / 10);
5907	}
5908}
5909
5910int
5911ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5912			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5913{
5914	struct ctl_lun *lun = CTL_LUN(ctsio);
5915	struct scsi_info_exceptions_page *pg;
5916	uint64_t t;
5917
5918	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5919
5920	pg = (struct scsi_info_exceptions_page *)page_ptr;
5921	mtx_lock(&lun->lun_lock);
5922	if (pg->info_flags & SIEP_FLAGS_TEST) {
5923		lun->ie_asc = 0x5d;
5924		lun->ie_ascq = 0xff;
5925		if (pg->mrie == SIEP_MRIE_UA) {
5926			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5927			lun->ie_reported = 1;
5928		} else {
5929			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5930			lun->ie_reported = -1;
5931		}
5932		lun->ie_reportcnt = 1;
5933		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5934			lun->ie_reportcnt++;
5935			t = scsi_4btoul(pg->interval_timer);
5936			if (t == 0 || t == UINT32_MAX)
5937				t = 3000;  /* 5 min */
5938			callout_reset(&lun->ie_callout, t * hz / 10,
5939			    ctl_ie_timer, lun);
5940		}
5941	} else {
5942		lun->ie_asc = 0;
5943		lun->ie_ascq = 0;
5944		lun->ie_reported = 1;
5945		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5946		lun->ie_reportcnt = UINT32_MAX;
5947		callout_stop(&lun->ie_callout);
5948	}
5949	mtx_unlock(&lun->lun_lock);
5950	return (CTL_RETVAL_COMPLETE);
5951}
5952
5953static int
5954ctl_do_mode_select(union ctl_io *io)
5955{
5956	struct ctl_lun *lun = CTL_LUN(io);
5957	struct scsi_mode_page_header *page_header;
5958	struct ctl_page_index *page_index;
5959	struct ctl_scsiio *ctsio;
5960	int page_len, page_len_offset, page_len_size;
5961	union ctl_modepage_info *modepage_info;
5962	uint16_t *len_left, *len_used;
5963	int retval, i;
5964
5965	ctsio = &io->scsiio;
5966	page_index = NULL;
5967	page_len = 0;
5968
5969	modepage_info = (union ctl_modepage_info *)
5970		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5971	len_left = &modepage_info->header.len_left;
5972	len_used = &modepage_info->header.len_used;
5973
5974do_next_page:
5975
5976	page_header = (struct scsi_mode_page_header *)
5977		(ctsio->kern_data_ptr + *len_used);
5978
5979	if (*len_left == 0) {
5980		free(ctsio->kern_data_ptr, M_CTL);
5981		ctl_set_success(ctsio);
5982		ctl_done((union ctl_io *)ctsio);
5983		return (CTL_RETVAL_COMPLETE);
5984	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5985
5986		free(ctsio->kern_data_ptr, M_CTL);
5987		ctl_set_param_len_error(ctsio);
5988		ctl_done((union ctl_io *)ctsio);
5989		return (CTL_RETVAL_COMPLETE);
5990
5991	} else if ((page_header->page_code & SMPH_SPF)
5992		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5993
5994		free(ctsio->kern_data_ptr, M_CTL);
5995		ctl_set_param_len_error(ctsio);
5996		ctl_done((union ctl_io *)ctsio);
5997		return (CTL_RETVAL_COMPLETE);
5998	}
5999
6000
6001	/*
6002	 * XXX KDM should we do something with the block descriptor?
6003	 */
6004	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6005		page_index = &lun->mode_pages.index[i];
6006		if (lun->be_lun->lun_type == T_DIRECT &&
6007		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6008			continue;
6009		if (lun->be_lun->lun_type == T_PROCESSOR &&
6010		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6011			continue;
6012		if (lun->be_lun->lun_type == T_CDROM &&
6013		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6014			continue;
6015
6016		if ((page_index->page_code & SMPH_PC_MASK) !=
6017		    (page_header->page_code & SMPH_PC_MASK))
6018			continue;
6019
6020		/*
6021		 * If neither page has a subpage code, then we've got a
6022		 * match.
6023		 */
6024		if (((page_index->page_code & SMPH_SPF) == 0)
6025		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6026			page_len = page_header->page_length;
6027			break;
6028		}
6029
6030		/*
6031		 * If both pages have subpages, then the subpage numbers
6032		 * have to match.
6033		 */
6034		if ((page_index->page_code & SMPH_SPF)
6035		  && (page_header->page_code & SMPH_SPF)) {
6036			struct scsi_mode_page_header_sp *sph;
6037
6038			sph = (struct scsi_mode_page_header_sp *)page_header;
6039			if (page_index->subpage == sph->subpage) {
6040				page_len = scsi_2btoul(sph->page_length);
6041				break;
6042			}
6043		}
6044	}
6045
6046	/*
6047	 * If we couldn't find the page, or if we don't have a mode select
6048	 * handler for it, send back an error to the user.
6049	 */
6050	if ((i >= CTL_NUM_MODE_PAGES)
6051	 || (page_index->select_handler == NULL)) {
6052		ctl_set_invalid_field(ctsio,
6053				      /*sks_valid*/ 1,
6054				      /*command*/ 0,
6055				      /*field*/ *len_used,
6056				      /*bit_valid*/ 0,
6057				      /*bit*/ 0);
6058		free(ctsio->kern_data_ptr, M_CTL);
6059		ctl_done((union ctl_io *)ctsio);
6060		return (CTL_RETVAL_COMPLETE);
6061	}
6062
6063	if (page_index->page_code & SMPH_SPF) {
6064		page_len_offset = 2;
6065		page_len_size = 2;
6066	} else {
6067		page_len_size = 1;
6068		page_len_offset = 1;
6069	}
6070
6071	/*
6072	 * If the length the initiator gives us isn't the one we specify in
6073	 * the mode page header, or if they didn't specify enough data in
6074	 * the CDB to avoid truncating this page, kick out the request.
6075	 */
6076	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6077		ctl_set_invalid_field(ctsio,
6078				      /*sks_valid*/ 1,
6079				      /*command*/ 0,
6080				      /*field*/ *len_used + page_len_offset,
6081				      /*bit_valid*/ 0,
6082				      /*bit*/ 0);
6083		free(ctsio->kern_data_ptr, M_CTL);
6084		ctl_done((union ctl_io *)ctsio);
6085		return (CTL_RETVAL_COMPLETE);
6086	}
6087	if (*len_left < page_index->page_len) {
6088		free(ctsio->kern_data_ptr, M_CTL);
6089		ctl_set_param_len_error(ctsio);
6090		ctl_done((union ctl_io *)ctsio);
6091		return (CTL_RETVAL_COMPLETE);
6092	}
6093
6094	/*
6095	 * Run through the mode page, checking to make sure that the bits
6096	 * the user changed are actually legal for him to change.
6097	 */
6098	for (i = 0; i < page_index->page_len; i++) {
6099		uint8_t *user_byte, *change_mask, *current_byte;
6100		int bad_bit;
6101		int j;
6102
6103		user_byte = (uint8_t *)page_header + i;
6104		change_mask = page_index->page_data +
6105			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6106		current_byte = page_index->page_data +
6107			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6108
6109		/*
6110		 * Check to see whether the user set any bits in this byte
6111		 * that he is not allowed to set.
6112		 */
6113		if ((*user_byte & ~(*change_mask)) ==
6114		    (*current_byte & ~(*change_mask)))
6115			continue;
6116
6117		/*
6118		 * Go through bit by bit to determine which one is illegal.
6119		 */
6120		bad_bit = 0;
6121		for (j = 7; j >= 0; j--) {
6122			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6123			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6124				bad_bit = i;
6125				break;
6126			}
6127		}
6128		ctl_set_invalid_field(ctsio,
6129				      /*sks_valid*/ 1,
6130				      /*command*/ 0,
6131				      /*field*/ *len_used + i,
6132				      /*bit_valid*/ 1,
6133				      /*bit*/ bad_bit);
6134		free(ctsio->kern_data_ptr, M_CTL);
6135		ctl_done((union ctl_io *)ctsio);
6136		return (CTL_RETVAL_COMPLETE);
6137	}
6138
6139	/*
6140	 * Decrement these before we call the page handler, since we may
6141	 * end up getting called back one way or another before the handler
6142	 * returns to this context.
6143	 */
6144	*len_left -= page_index->page_len;
6145	*len_used += page_index->page_len;
6146
6147	retval = page_index->select_handler(ctsio, page_index,
6148					    (uint8_t *)page_header);
6149
6150	/*
6151	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6152	 * wait until this queued command completes to finish processing
6153	 * the mode page.  If it returns anything other than
6154	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6155	 * already set the sense information, freed the data pointer, and
6156	 * completed the io for us.
6157	 */
6158	if (retval != CTL_RETVAL_COMPLETE)
6159		goto bailout_no_done;
6160
6161	/*
6162	 * If the initiator sent us more than one page, parse the next one.
6163	 */
6164	if (*len_left > 0)
6165		goto do_next_page;
6166
6167	ctl_set_success(ctsio);
6168	free(ctsio->kern_data_ptr, M_CTL);
6169	ctl_done((union ctl_io *)ctsio);
6170
6171bailout_no_done:
6172
6173	return (CTL_RETVAL_COMPLETE);
6174
6175}
6176
6177int
6178ctl_mode_select(struct ctl_scsiio *ctsio)
6179{
6180	struct ctl_lun *lun = CTL_LUN(ctsio);
6181	union ctl_modepage_info *modepage_info;
6182	int bd_len, i, header_size, param_len, pf, rtd, sp;
6183	uint32_t initidx;
6184
6185	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6186	switch (ctsio->cdb[0]) {
6187	case MODE_SELECT_6: {
6188		struct scsi_mode_select_6 *cdb;
6189
6190		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6191
6192		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6193		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6194		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6195		param_len = cdb->length;
6196		header_size = sizeof(struct scsi_mode_header_6);
6197		break;
6198	}
6199	case MODE_SELECT_10: {
6200		struct scsi_mode_select_10 *cdb;
6201
6202		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6203
6204		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6205		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6206		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6207		param_len = scsi_2btoul(cdb->length);
6208		header_size = sizeof(struct scsi_mode_header_10);
6209		break;
6210	}
6211	default:
6212		ctl_set_invalid_opcode(ctsio);
6213		ctl_done((union ctl_io *)ctsio);
6214		return (CTL_RETVAL_COMPLETE);
6215	}
6216
6217	if (rtd) {
6218		if (param_len != 0) {
6219			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6220			    /*command*/ 1, /*field*/ 0,
6221			    /*bit_valid*/ 0, /*bit*/ 0);
6222			ctl_done((union ctl_io *)ctsio);
6223			return (CTL_RETVAL_COMPLETE);
6224		}
6225
6226		/* Revert to defaults. */
6227		ctl_init_page_index(lun);
6228		mtx_lock(&lun->lun_lock);
6229		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6230		mtx_unlock(&lun->lun_lock);
6231		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6232			ctl_isc_announce_mode(lun, -1,
6233			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6234			    lun->mode_pages.index[i].subpage);
6235		}
6236		ctl_set_success(ctsio);
6237		ctl_done((union ctl_io *)ctsio);
6238		return (CTL_RETVAL_COMPLETE);
6239	}
6240
6241	/*
6242	 * From SPC-3:
6243	 * "A parameter list length of zero indicates that the Data-Out Buffer
6244	 * shall be empty. This condition shall not be considered as an error."
6245	 */
6246	if (param_len == 0) {
6247		ctl_set_success(ctsio);
6248		ctl_done((union ctl_io *)ctsio);
6249		return (CTL_RETVAL_COMPLETE);
6250	}
6251
6252	/*
6253	 * Since we'll hit this the first time through, prior to
6254	 * allocation, we don't need to free a data buffer here.
6255	 */
6256	if (param_len < header_size) {
6257		ctl_set_param_len_error(ctsio);
6258		ctl_done((union ctl_io *)ctsio);
6259		return (CTL_RETVAL_COMPLETE);
6260	}
6261
6262	/*
6263	 * Allocate the data buffer and grab the user's data.  In theory,
6264	 * we shouldn't have to sanity check the parameter list length here
6265	 * because the maximum size is 64K.  We should be able to malloc
6266	 * that much without too many problems.
6267	 */
6268	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6269		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6270		ctsio->kern_data_len = param_len;
6271		ctsio->kern_total_len = param_len;
6272		ctsio->kern_data_resid = 0;
6273		ctsio->kern_rel_offset = 0;
6274		ctsio->kern_sg_entries = 0;
6275		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6276		ctsio->be_move_done = ctl_config_move_done;
6277		ctl_datamove((union ctl_io *)ctsio);
6278
6279		return (CTL_RETVAL_COMPLETE);
6280	}
6281
6282	switch (ctsio->cdb[0]) {
6283	case MODE_SELECT_6: {
6284		struct scsi_mode_header_6 *mh6;
6285
6286		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6287		bd_len = mh6->blk_desc_len;
6288		break;
6289	}
6290	case MODE_SELECT_10: {
6291		struct scsi_mode_header_10 *mh10;
6292
6293		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6294		bd_len = scsi_2btoul(mh10->blk_desc_len);
6295		break;
6296	}
6297	default:
6298		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6299	}
6300
6301	if (param_len < (header_size + bd_len)) {
6302		free(ctsio->kern_data_ptr, M_CTL);
6303		ctl_set_param_len_error(ctsio);
6304		ctl_done((union ctl_io *)ctsio);
6305		return (CTL_RETVAL_COMPLETE);
6306	}
6307
6308	/*
6309	 * Set the IO_CONT flag, so that if this I/O gets passed to
6310	 * ctl_config_write_done(), it'll get passed back to
6311	 * ctl_do_mode_select() for further processing, or completion if
6312	 * we're all done.
6313	 */
6314	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6315	ctsio->io_cont = ctl_do_mode_select;
6316
6317	modepage_info = (union ctl_modepage_info *)
6318		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6319	memset(modepage_info, 0, sizeof(*modepage_info));
6320	modepage_info->header.len_left = param_len - header_size - bd_len;
6321	modepage_info->header.len_used = header_size + bd_len;
6322
6323	return (ctl_do_mode_select((union ctl_io *)ctsio));
6324}
6325
6326int
6327ctl_mode_sense(struct ctl_scsiio *ctsio)
6328{
6329	struct ctl_lun *lun = CTL_LUN(ctsio);
6330	int pc, page_code, dbd, llba, subpage;
6331	int alloc_len, page_len, header_len, total_len;
6332	struct scsi_mode_block_descr *block_desc;
6333	struct ctl_page_index *page_index;
6334
6335	dbd = 0;
6336	llba = 0;
6337	block_desc = NULL;
6338
6339	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6340
6341	switch (ctsio->cdb[0]) {
6342	case MODE_SENSE_6: {
6343		struct scsi_mode_sense_6 *cdb;
6344
6345		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6346
6347		header_len = sizeof(struct scsi_mode_hdr_6);
6348		if (cdb->byte2 & SMS_DBD)
6349			dbd = 1;
6350		else
6351			header_len += sizeof(struct scsi_mode_block_descr);
6352
6353		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6354		page_code = cdb->page & SMS_PAGE_CODE;
6355		subpage = cdb->subpage;
6356		alloc_len = cdb->length;
6357		break;
6358	}
6359	case MODE_SENSE_10: {
6360		struct scsi_mode_sense_10 *cdb;
6361
6362		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6363
6364		header_len = sizeof(struct scsi_mode_hdr_10);
6365
6366		if (cdb->byte2 & SMS_DBD)
6367			dbd = 1;
6368		else
6369			header_len += sizeof(struct scsi_mode_block_descr);
6370		if (cdb->byte2 & SMS10_LLBAA)
6371			llba = 1;
6372		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6373		page_code = cdb->page & SMS_PAGE_CODE;
6374		subpage = cdb->subpage;
6375		alloc_len = scsi_2btoul(cdb->length);
6376		break;
6377	}
6378	default:
6379		ctl_set_invalid_opcode(ctsio);
6380		ctl_done((union ctl_io *)ctsio);
6381		return (CTL_RETVAL_COMPLETE);
6382		break; /* NOTREACHED */
6383	}
6384
6385	/*
6386	 * We have to make a first pass through to calculate the size of
6387	 * the pages that match the user's query.  Then we allocate enough
6388	 * memory to hold it, and actually copy the data into the buffer.
6389	 */
6390	switch (page_code) {
6391	case SMS_ALL_PAGES_PAGE: {
6392		u_int i;
6393
6394		page_len = 0;
6395
6396		/*
6397		 * At the moment, values other than 0 and 0xff here are
6398		 * reserved according to SPC-3.
6399		 */
6400		if ((subpage != SMS_SUBPAGE_PAGE_0)
6401		 && (subpage != SMS_SUBPAGE_ALL)) {
6402			ctl_set_invalid_field(ctsio,
6403					      /*sks_valid*/ 1,
6404					      /*command*/ 1,
6405					      /*field*/ 3,
6406					      /*bit_valid*/ 0,
6407					      /*bit*/ 0);
6408			ctl_done((union ctl_io *)ctsio);
6409			return (CTL_RETVAL_COMPLETE);
6410		}
6411
6412		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6413			page_index = &lun->mode_pages.index[i];
6414
6415			/* Make sure the page is supported for this dev type */
6416			if (lun->be_lun->lun_type == T_DIRECT &&
6417			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6418				continue;
6419			if (lun->be_lun->lun_type == T_PROCESSOR &&
6420			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6421				continue;
6422			if (lun->be_lun->lun_type == T_CDROM &&
6423			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6424				continue;
6425
6426			/*
6427			 * We don't use this subpage if the user didn't
6428			 * request all subpages.
6429			 */
6430			if ((page_index->subpage != 0)
6431			 && (subpage == SMS_SUBPAGE_PAGE_0))
6432				continue;
6433
6434#if 0
6435			printf("found page %#x len %d\n",
6436			       page_index->page_code & SMPH_PC_MASK,
6437			       page_index->page_len);
6438#endif
6439			page_len += page_index->page_len;
6440		}
6441		break;
6442	}
6443	default: {
6444		u_int i;
6445
6446		page_len = 0;
6447
6448		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6449			page_index = &lun->mode_pages.index[i];
6450
6451			/* Make sure the page is supported for this dev type */
6452			if (lun->be_lun->lun_type == T_DIRECT &&
6453			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6454				continue;
6455			if (lun->be_lun->lun_type == T_PROCESSOR &&
6456			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6457				continue;
6458			if (lun->be_lun->lun_type == T_CDROM &&
6459			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6460				continue;
6461
6462			/* Look for the right page code */
6463			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6464				continue;
6465
6466			/* Look for the right subpage or the subpage wildcard*/
6467			if ((page_index->subpage != subpage)
6468			 && (subpage != SMS_SUBPAGE_ALL))
6469				continue;
6470
6471#if 0
6472			printf("found page %#x len %d\n",
6473			       page_index->page_code & SMPH_PC_MASK,
6474			       page_index->page_len);
6475#endif
6476
6477			page_len += page_index->page_len;
6478		}
6479
6480		if (page_len == 0) {
6481			ctl_set_invalid_field(ctsio,
6482					      /*sks_valid*/ 1,
6483					      /*command*/ 1,
6484					      /*field*/ 2,
6485					      /*bit_valid*/ 1,
6486					      /*bit*/ 5);
6487			ctl_done((union ctl_io *)ctsio);
6488			return (CTL_RETVAL_COMPLETE);
6489		}
6490		break;
6491	}
6492	}
6493
6494	total_len = header_len + page_len;
6495#if 0
6496	printf("header_len = %d, page_len = %d, total_len = %d\n",
6497	       header_len, page_len, total_len);
6498#endif
6499
6500	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6501	ctsio->kern_sg_entries = 0;
6502	ctsio->kern_data_resid = 0;
6503	ctsio->kern_rel_offset = 0;
6504	if (total_len < alloc_len) {
6505		ctsio->residual = alloc_len - total_len;
6506		ctsio->kern_data_len = total_len;
6507		ctsio->kern_total_len = total_len;
6508	} else {
6509		ctsio->residual = 0;
6510		ctsio->kern_data_len = alloc_len;
6511		ctsio->kern_total_len = alloc_len;
6512	}
6513
6514	switch (ctsio->cdb[0]) {
6515	case MODE_SENSE_6: {
6516		struct scsi_mode_hdr_6 *header;
6517
6518		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6519
6520		header->datalen = MIN(total_len - 1, 254);
6521		if (lun->be_lun->lun_type == T_DIRECT) {
6522			header->dev_specific = 0x10; /* DPOFUA */
6523			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6524			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6525				header->dev_specific |= 0x80; /* WP */
6526		}
6527		if (dbd)
6528			header->block_descr_len = 0;
6529		else
6530			header->block_descr_len =
6531				sizeof(struct scsi_mode_block_descr);
6532		block_desc = (struct scsi_mode_block_descr *)&header[1];
6533		break;
6534	}
6535	case MODE_SENSE_10: {
6536		struct scsi_mode_hdr_10 *header;
6537		int datalen;
6538
6539		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6540
6541		datalen = MIN(total_len - 2, 65533);
6542		scsi_ulto2b(datalen, header->datalen);
6543		if (lun->be_lun->lun_type == T_DIRECT) {
6544			header->dev_specific = 0x10; /* DPOFUA */
6545			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6546			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6547				header->dev_specific |= 0x80; /* WP */
6548		}
6549		if (dbd)
6550			scsi_ulto2b(0, header->block_descr_len);
6551		else
6552			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6553				    header->block_descr_len);
6554		block_desc = (struct scsi_mode_block_descr *)&header[1];
6555		break;
6556	}
6557	default:
6558		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6559	}
6560
6561	/*
6562	 * If we've got a disk, use its blocksize in the block
6563	 * descriptor.  Otherwise, just set it to 0.
6564	 */
6565	if (dbd == 0) {
6566		if (lun->be_lun->lun_type == T_DIRECT)
6567			scsi_ulto3b(lun->be_lun->blocksize,
6568				    block_desc->block_len);
6569		else
6570			scsi_ulto3b(0, block_desc->block_len);
6571	}
6572
6573	switch (page_code) {
6574	case SMS_ALL_PAGES_PAGE: {
6575		int i, data_used;
6576
6577		data_used = header_len;
6578		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6579			struct ctl_page_index *page_index;
6580
6581			page_index = &lun->mode_pages.index[i];
6582			if (lun->be_lun->lun_type == T_DIRECT &&
6583			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6584				continue;
6585			if (lun->be_lun->lun_type == T_PROCESSOR &&
6586			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6587				continue;
6588			if (lun->be_lun->lun_type == T_CDROM &&
6589			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6590				continue;
6591
6592			/*
6593			 * We don't use this subpage if the user didn't
6594			 * request all subpages.  We already checked (above)
6595			 * to make sure the user only specified a subpage
6596			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6597			 */
6598			if ((page_index->subpage != 0)
6599			 && (subpage == SMS_SUBPAGE_PAGE_0))
6600				continue;
6601
6602			/*
6603			 * Call the handler, if it exists, to update the
6604			 * page to the latest values.
6605			 */
6606			if (page_index->sense_handler != NULL)
6607				page_index->sense_handler(ctsio, page_index,pc);
6608
6609			memcpy(ctsio->kern_data_ptr + data_used,
6610			       page_index->page_data +
6611			       (page_index->page_len * pc),
6612			       page_index->page_len);
6613			data_used += page_index->page_len;
6614		}
6615		break;
6616	}
6617	default: {
6618		int i, data_used;
6619
6620		data_used = header_len;
6621
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
6627			/* Look for the right page code */
6628			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6629				continue;
6630
6631			/* Look for the right subpage or the subpage wildcard*/
6632			if ((page_index->subpage != subpage)
6633			 && (subpage != SMS_SUBPAGE_ALL))
6634				continue;
6635
6636			/* Make sure the page is supported for this dev type */
6637			if (lun->be_lun->lun_type == T_DIRECT &&
6638			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6639				continue;
6640			if (lun->be_lun->lun_type == T_PROCESSOR &&
6641			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6642				continue;
6643			if (lun->be_lun->lun_type == T_CDROM &&
6644			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6645				continue;
6646
6647			/*
6648			 * Call the handler, if it exists, to update the
6649			 * page to the latest values.
6650			 */
6651			if (page_index->sense_handler != NULL)
6652				page_index->sense_handler(ctsio, page_index,pc);
6653
6654			memcpy(ctsio->kern_data_ptr + data_used,
6655			       page_index->page_data +
6656			       (page_index->page_len * pc),
6657			       page_index->page_len);
6658			data_used += page_index->page_len;
6659		}
6660		break;
6661	}
6662	}
6663
6664	ctl_set_success(ctsio);
6665	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6666	ctsio->be_move_done = ctl_config_move_done;
6667	ctl_datamove((union ctl_io *)ctsio);
6668	return (CTL_RETVAL_COMPLETE);
6669}
6670
6671int
6672ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6673			       struct ctl_page_index *page_index,
6674			       int pc)
6675{
6676	struct ctl_lun *lun = CTL_LUN(ctsio);
6677	struct scsi_log_param_header *phdr;
6678	uint8_t *data;
6679	uint64_t val;
6680
6681	data = page_index->page_data;
6682
6683	if (lun->backend->lun_attr != NULL &&
6684	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6685	     != UINT64_MAX) {
6686		phdr = (struct scsi_log_param_header *)data;
6687		scsi_ulto2b(0x0001, phdr->param_code);
6688		phdr->param_control = SLP_LBIN | SLP_LP;
6689		phdr->param_len = 8;
6690		data = (uint8_t *)(phdr + 1);
6691		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6692		data[4] = 0x02; /* per-pool */
6693		data += phdr->param_len;
6694	}
6695
6696	if (lun->backend->lun_attr != NULL &&
6697	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6698	     != UINT64_MAX) {
6699		phdr = (struct scsi_log_param_header *)data;
6700		scsi_ulto2b(0x0002, phdr->param_code);
6701		phdr->param_control = SLP_LBIN | SLP_LP;
6702		phdr->param_len = 8;
6703		data = (uint8_t *)(phdr + 1);
6704		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6705		data[4] = 0x01; /* per-LUN */
6706		data += phdr->param_len;
6707	}
6708
6709	if (lun->backend->lun_attr != NULL &&
6710	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6711	     != UINT64_MAX) {
6712		phdr = (struct scsi_log_param_header *)data;
6713		scsi_ulto2b(0x00f1, phdr->param_code);
6714		phdr->param_control = SLP_LBIN | SLP_LP;
6715		phdr->param_len = 8;
6716		data = (uint8_t *)(phdr + 1);
6717		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6718		data[4] = 0x02; /* per-pool */
6719		data += phdr->param_len;
6720	}
6721
6722	if (lun->backend->lun_attr != NULL &&
6723	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6724	     != UINT64_MAX) {
6725		phdr = (struct scsi_log_param_header *)data;
6726		scsi_ulto2b(0x00f2, phdr->param_code);
6727		phdr->param_control = SLP_LBIN | SLP_LP;
6728		phdr->param_len = 8;
6729		data = (uint8_t *)(phdr + 1);
6730		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6731		data[4] = 0x02; /* per-pool */
6732		data += phdr->param_len;
6733	}
6734
6735	page_index->page_len = data - page_index->page_data;
6736	return (0);
6737}
6738
6739int
6740ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6741			       struct ctl_page_index *page_index,
6742			       int pc)
6743{
6744	struct ctl_lun *lun = CTL_LUN(ctsio);
6745	struct stat_page *data;
6746	struct bintime *t;
6747
6748	data = (struct stat_page *)page_index->page_data;
6749
6750	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6751	data->sap.hdr.param_control = SLP_LBIN;
6752	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6753	    sizeof(struct scsi_log_param_header);
6754	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6755	    data->sap.read_num);
6756	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6757	    data->sap.write_num);
6758	if (lun->be_lun->blocksize > 0) {
6759		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6760		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6761		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6762		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6763	}
6764	t = &lun->stats.time[CTL_STATS_READ];
6765	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6766	    data->sap.read_int);
6767	t = &lun->stats.time[CTL_STATS_WRITE];
6768	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6769	    data->sap.write_int);
6770	scsi_u64to8b(0, data->sap.weighted_num);
6771	scsi_u64to8b(0, data->sap.weighted_int);
6772	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6773	data->it.hdr.param_control = SLP_LBIN;
6774	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6775	    sizeof(struct scsi_log_param_header);
6776#ifdef CTL_TIME_IO
6777	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6778#endif
6779	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6780	data->it.hdr.param_control = SLP_LBIN;
6781	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6782	    sizeof(struct scsi_log_param_header);
6783	scsi_ulto4b(3, data->ti.exponent);
6784	scsi_ulto4b(1, data->ti.integer);
6785	return (0);
6786}
6787
6788int
6789ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6790			       struct ctl_page_index *page_index,
6791			       int pc)
6792{
6793	struct ctl_lun *lun = CTL_LUN(ctsio);
6794	struct scsi_log_informational_exceptions *data;
6795
6796	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6797
6798	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6799	data->hdr.param_control = SLP_LBIN;
6800	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6801	    sizeof(struct scsi_log_param_header);
6802	data->ie_asc = lun->ie_asc;
6803	data->ie_ascq = lun->ie_ascq;
6804	data->temperature = 0xff;
6805	return (0);
6806}
6807
6808int
6809ctl_log_sense(struct ctl_scsiio *ctsio)
6810{
6811	struct ctl_lun *lun = CTL_LUN(ctsio);
6812	int i, pc, page_code, subpage;
6813	int alloc_len, total_len;
6814	struct ctl_page_index *page_index;
6815	struct scsi_log_sense *cdb;
6816	struct scsi_log_header *header;
6817
6818	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6819
6820	cdb = (struct scsi_log_sense *)ctsio->cdb;
6821	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6822	page_code = cdb->page & SLS_PAGE_CODE;
6823	subpage = cdb->subpage;
6824	alloc_len = scsi_2btoul(cdb->length);
6825
6826	page_index = NULL;
6827	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6828		page_index = &lun->log_pages.index[i];
6829
6830		/* Look for the right page code */
6831		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6832			continue;
6833
6834		/* Look for the right subpage or the subpage wildcard*/
6835		if (page_index->subpage != subpage)
6836			continue;
6837
6838		break;
6839	}
6840	if (i >= CTL_NUM_LOG_PAGES) {
6841		ctl_set_invalid_field(ctsio,
6842				      /*sks_valid*/ 1,
6843				      /*command*/ 1,
6844				      /*field*/ 2,
6845				      /*bit_valid*/ 0,
6846				      /*bit*/ 0);
6847		ctl_done((union ctl_io *)ctsio);
6848		return (CTL_RETVAL_COMPLETE);
6849	}
6850
6851	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6852
6853	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6854	ctsio->kern_sg_entries = 0;
6855	ctsio->kern_data_resid = 0;
6856	ctsio->kern_rel_offset = 0;
6857	if (total_len < alloc_len) {
6858		ctsio->residual = alloc_len - total_len;
6859		ctsio->kern_data_len = total_len;
6860		ctsio->kern_total_len = total_len;
6861	} else {
6862		ctsio->residual = 0;
6863		ctsio->kern_data_len = alloc_len;
6864		ctsio->kern_total_len = alloc_len;
6865	}
6866
6867	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6868	header->page = page_index->page_code;
6869	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6870		header->page |= SL_DS;
6871	if (page_index->subpage) {
6872		header->page |= SL_SPF;
6873		header->subpage = page_index->subpage;
6874	}
6875	scsi_ulto2b(page_index->page_len, header->datalen);
6876
6877	/*
6878	 * Call the handler, if it exists, to update the
6879	 * page to the latest values.
6880	 */
6881	if (page_index->sense_handler != NULL)
6882		page_index->sense_handler(ctsio, page_index, pc);
6883
6884	memcpy(header + 1, page_index->page_data, page_index->page_len);
6885
6886	ctl_set_success(ctsio);
6887	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6888	ctsio->be_move_done = ctl_config_move_done;
6889	ctl_datamove((union ctl_io *)ctsio);
6890	return (CTL_RETVAL_COMPLETE);
6891}
6892
6893int
6894ctl_read_capacity(struct ctl_scsiio *ctsio)
6895{
6896	struct ctl_lun *lun = CTL_LUN(ctsio);
6897	struct scsi_read_capacity *cdb;
6898	struct scsi_read_capacity_data *data;
6899	uint32_t lba;
6900
6901	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6902
6903	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6904
6905	lba = scsi_4btoul(cdb->addr);
6906	if (((cdb->pmi & SRC_PMI) == 0)
6907	 && (lba != 0)) {
6908		ctl_set_invalid_field(/*ctsio*/ ctsio,
6909				      /*sks_valid*/ 1,
6910				      /*command*/ 1,
6911				      /*field*/ 2,
6912				      /*bit_valid*/ 0,
6913				      /*bit*/ 0);
6914		ctl_done((union ctl_io *)ctsio);
6915		return (CTL_RETVAL_COMPLETE);
6916	}
6917
6918	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6919	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6920	ctsio->residual = 0;
6921	ctsio->kern_data_len = sizeof(*data);
6922	ctsio->kern_total_len = sizeof(*data);
6923	ctsio->kern_data_resid = 0;
6924	ctsio->kern_rel_offset = 0;
6925	ctsio->kern_sg_entries = 0;
6926
6927	/*
6928	 * If the maximum LBA is greater than 0xfffffffe, the user must
6929	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6930	 * serivce action set.
6931	 */
6932	if (lun->be_lun->maxlba > 0xfffffffe)
6933		scsi_ulto4b(0xffffffff, data->addr);
6934	else
6935		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6936
6937	/*
6938	 * XXX KDM this may not be 512 bytes...
6939	 */
6940	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6941
6942	ctl_set_success(ctsio);
6943	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6944	ctsio->be_move_done = ctl_config_move_done;
6945	ctl_datamove((union ctl_io *)ctsio);
6946	return (CTL_RETVAL_COMPLETE);
6947}
6948
6949int
6950ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6951{
6952	struct ctl_lun *lun = CTL_LUN(ctsio);
6953	struct scsi_read_capacity_16 *cdb;
6954	struct scsi_read_capacity_data_long *data;
6955	uint64_t lba;
6956	uint32_t alloc_len;
6957
6958	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6959
6960	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6961
6962	alloc_len = scsi_4btoul(cdb->alloc_len);
6963	lba = scsi_8btou64(cdb->addr);
6964
6965	if ((cdb->reladr & SRC16_PMI)
6966	 && (lba != 0)) {
6967		ctl_set_invalid_field(/*ctsio*/ ctsio,
6968				      /*sks_valid*/ 1,
6969				      /*command*/ 1,
6970				      /*field*/ 2,
6971				      /*bit_valid*/ 0,
6972				      /*bit*/ 0);
6973		ctl_done((union ctl_io *)ctsio);
6974		return (CTL_RETVAL_COMPLETE);
6975	}
6976
6977	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6978	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6979
6980	if (sizeof(*data) < alloc_len) {
6981		ctsio->residual = alloc_len - sizeof(*data);
6982		ctsio->kern_data_len = sizeof(*data);
6983		ctsio->kern_total_len = sizeof(*data);
6984	} else {
6985		ctsio->residual = 0;
6986		ctsio->kern_data_len = alloc_len;
6987		ctsio->kern_total_len = alloc_len;
6988	}
6989	ctsio->kern_data_resid = 0;
6990	ctsio->kern_rel_offset = 0;
6991	ctsio->kern_sg_entries = 0;
6992
6993	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6994	/* XXX KDM this may not be 512 bytes... */
6995	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6996	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6997	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6998	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6999		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7000
7001	ctl_set_success(ctsio);
7002	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7003	ctsio->be_move_done = ctl_config_move_done;
7004	ctl_datamove((union ctl_io *)ctsio);
7005	return (CTL_RETVAL_COMPLETE);
7006}
7007
7008int
7009ctl_get_lba_status(struct ctl_scsiio *ctsio)
7010{
7011	struct ctl_lun *lun = CTL_LUN(ctsio);
7012	struct scsi_get_lba_status *cdb;
7013	struct scsi_get_lba_status_data *data;
7014	struct ctl_lba_len_flags *lbalen;
7015	uint64_t lba;
7016	uint32_t alloc_len, total_len;
7017	int retval;
7018
7019	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7020
7021	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7022	lba = scsi_8btou64(cdb->addr);
7023	alloc_len = scsi_4btoul(cdb->alloc_len);
7024
7025	if (lba > lun->be_lun->maxlba) {
7026		ctl_set_lba_out_of_range(ctsio, lba);
7027		ctl_done((union ctl_io *)ctsio);
7028		return (CTL_RETVAL_COMPLETE);
7029	}
7030
7031	total_len = sizeof(*data) + sizeof(data->descr[0]);
7032	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7033	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7034
7035	if (total_len < alloc_len) {
7036		ctsio->residual = alloc_len - total_len;
7037		ctsio->kern_data_len = total_len;
7038		ctsio->kern_total_len = total_len;
7039	} else {
7040		ctsio->residual = 0;
7041		ctsio->kern_data_len = alloc_len;
7042		ctsio->kern_total_len = alloc_len;
7043	}
7044	ctsio->kern_data_resid = 0;
7045	ctsio->kern_rel_offset = 0;
7046	ctsio->kern_sg_entries = 0;
7047
7048	/* Fill dummy data in case backend can't tell anything. */
7049	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7050	scsi_u64to8b(lba, data->descr[0].addr);
7051	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7052	    data->descr[0].length);
7053	data->descr[0].status = 0; /* Mapped or unknown. */
7054
7055	ctl_set_success(ctsio);
7056	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7057	ctsio->be_move_done = ctl_config_move_done;
7058
7059	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7060	lbalen->lba = lba;
7061	lbalen->len = total_len;
7062	lbalen->flags = 0;
7063	retval = lun->backend->config_read((union ctl_io *)ctsio);
7064	return (CTL_RETVAL_COMPLETE);
7065}
7066
7067int
7068ctl_read_defect(struct ctl_scsiio *ctsio)
7069{
7070	struct scsi_read_defect_data_10 *ccb10;
7071	struct scsi_read_defect_data_12 *ccb12;
7072	struct scsi_read_defect_data_hdr_10 *data10;
7073	struct scsi_read_defect_data_hdr_12 *data12;
7074	uint32_t alloc_len, data_len;
7075	uint8_t format;
7076
7077	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7078
7079	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7080		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7081		format = ccb10->format;
7082		alloc_len = scsi_2btoul(ccb10->alloc_length);
7083		data_len = sizeof(*data10);
7084	} else {
7085		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7086		format = ccb12->format;
7087		alloc_len = scsi_4btoul(ccb12->alloc_length);
7088		data_len = sizeof(*data12);
7089	}
7090	if (alloc_len == 0) {
7091		ctl_set_success(ctsio);
7092		ctl_done((union ctl_io *)ctsio);
7093		return (CTL_RETVAL_COMPLETE);
7094	}
7095
7096	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7097	if (data_len < alloc_len) {
7098		ctsio->residual = alloc_len - data_len;
7099		ctsio->kern_data_len = data_len;
7100		ctsio->kern_total_len = data_len;
7101	} else {
7102		ctsio->residual = 0;
7103		ctsio->kern_data_len = alloc_len;
7104		ctsio->kern_total_len = alloc_len;
7105	}
7106	ctsio->kern_data_resid = 0;
7107	ctsio->kern_rel_offset = 0;
7108	ctsio->kern_sg_entries = 0;
7109
7110	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7111		data10 = (struct scsi_read_defect_data_hdr_10 *)
7112		    ctsio->kern_data_ptr;
7113		data10->format = format;
7114		scsi_ulto2b(0, data10->length);
7115	} else {
7116		data12 = (struct scsi_read_defect_data_hdr_12 *)
7117		    ctsio->kern_data_ptr;
7118		data12->format = format;
7119		scsi_ulto2b(0, data12->generation);
7120		scsi_ulto4b(0, data12->length);
7121	}
7122
7123	ctl_set_success(ctsio);
7124	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7125	ctsio->be_move_done = ctl_config_move_done;
7126	ctl_datamove((union ctl_io *)ctsio);
7127	return (CTL_RETVAL_COMPLETE);
7128}
7129
7130int
7131ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7132{
7133	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7134	struct ctl_lun *lun = CTL_LUN(ctsio);
7135	struct scsi_maintenance_in *cdb;
7136	int retval;
7137	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7138	int num_ha_groups, num_target_ports, shared_group;
7139	struct ctl_port *port;
7140	struct scsi_target_group_data *rtg_ptr;
7141	struct scsi_target_group_data_extended *rtg_ext_ptr;
7142	struct scsi_target_port_group_descriptor *tpg_desc;
7143
7144	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7145
7146	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7147	retval = CTL_RETVAL_COMPLETE;
7148
7149	switch (cdb->byte2 & STG_PDF_MASK) {
7150	case STG_PDF_LENGTH:
7151		ext = 0;
7152		break;
7153	case STG_PDF_EXTENDED:
7154		ext = 1;
7155		break;
7156	default:
7157		ctl_set_invalid_field(/*ctsio*/ ctsio,
7158				      /*sks_valid*/ 1,
7159				      /*command*/ 1,
7160				      /*field*/ 2,
7161				      /*bit_valid*/ 1,
7162				      /*bit*/ 5);
7163		ctl_done((union ctl_io *)ctsio);
7164		return(retval);
7165	}
7166
7167	num_target_ports = 0;
7168	shared_group = (softc->is_single != 0);
7169	mtx_lock(&softc->ctl_lock);
7170	STAILQ_FOREACH(port, &softc->port_list, links) {
7171		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7172			continue;
7173		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7174			continue;
7175		num_target_ports++;
7176		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7177			shared_group = 1;
7178	}
7179	mtx_unlock(&softc->ctl_lock);
7180	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7181
7182	if (ext)
7183		total_len = sizeof(struct scsi_target_group_data_extended);
7184	else
7185		total_len = sizeof(struct scsi_target_group_data);
7186	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7187		(shared_group + num_ha_groups) +
7188	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7189
7190	alloc_len = scsi_4btoul(cdb->length);
7191
7192	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7193
7194	ctsio->kern_sg_entries = 0;
7195
7196	if (total_len < alloc_len) {
7197		ctsio->residual = alloc_len - total_len;
7198		ctsio->kern_data_len = total_len;
7199		ctsio->kern_total_len = total_len;
7200	} else {
7201		ctsio->residual = 0;
7202		ctsio->kern_data_len = alloc_len;
7203		ctsio->kern_total_len = alloc_len;
7204	}
7205	ctsio->kern_data_resid = 0;
7206	ctsio->kern_rel_offset = 0;
7207
7208	if (ext) {
7209		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7210		    ctsio->kern_data_ptr;
7211		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7212		rtg_ext_ptr->format_type = 0x10;
7213		rtg_ext_ptr->implicit_transition_time = 0;
7214		tpg_desc = &rtg_ext_ptr->groups[0];
7215	} else {
7216		rtg_ptr = (struct scsi_target_group_data *)
7217		    ctsio->kern_data_ptr;
7218		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7219		tpg_desc = &rtg_ptr->groups[0];
7220	}
7221
7222	mtx_lock(&softc->ctl_lock);
7223	pg = softc->port_min / softc->port_cnt;
7224	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7225		/* Some shelf is known to be primary. */
7226		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7227			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7228		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7229			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7230		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7231			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7232		else
7233			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7234		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7235			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7236		} else {
7237			ts = os;
7238			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7239		}
7240	} else {
7241		/* No known primary shelf. */
7242		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7243			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7244			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7245		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7246			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7247			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7248		} else {
7249			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7250		}
7251	}
7252	if (shared_group) {
7253		tpg_desc->pref_state = ts;
7254		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7255		    TPG_U_SUP | TPG_T_SUP;
7256		scsi_ulto2b(1, tpg_desc->target_port_group);
7257		tpg_desc->status = TPG_IMPLICIT;
7258		pc = 0;
7259		STAILQ_FOREACH(port, &softc->port_list, links) {
7260			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7261				continue;
7262			if (!softc->is_single &&
7263			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7264				continue;
7265			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7266				continue;
7267			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7268			    relative_target_port_identifier);
7269			pc++;
7270		}
7271		tpg_desc->target_port_count = pc;
7272		tpg_desc = (struct scsi_target_port_group_descriptor *)
7273		    &tpg_desc->descriptors[pc];
7274	}
7275	for (g = 0; g < num_ha_groups; g++) {
7276		tpg_desc->pref_state = (g == pg) ? ts : os;
7277		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7278		    TPG_U_SUP | TPG_T_SUP;
7279		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7280		tpg_desc->status = TPG_IMPLICIT;
7281		pc = 0;
7282		STAILQ_FOREACH(port, &softc->port_list, links) {
7283			if (port->targ_port < g * softc->port_cnt ||
7284			    port->targ_port >= (g + 1) * softc->port_cnt)
7285				continue;
7286			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7287				continue;
7288			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7289				continue;
7290			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7291				continue;
7292			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7293			    relative_target_port_identifier);
7294			pc++;
7295		}
7296		tpg_desc->target_port_count = pc;
7297		tpg_desc = (struct scsi_target_port_group_descriptor *)
7298		    &tpg_desc->descriptors[pc];
7299	}
7300	mtx_unlock(&softc->ctl_lock);
7301
7302	ctl_set_success(ctsio);
7303	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7304	ctsio->be_move_done = ctl_config_move_done;
7305	ctl_datamove((union ctl_io *)ctsio);
7306	return(retval);
7307}
7308
7309int
7310ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7311{
7312	struct ctl_lun *lun = CTL_LUN(ctsio);
7313	struct scsi_report_supported_opcodes *cdb;
7314	const struct ctl_cmd_entry *entry, *sentry;
7315	struct scsi_report_supported_opcodes_all *all;
7316	struct scsi_report_supported_opcodes_descr *descr;
7317	struct scsi_report_supported_opcodes_one *one;
7318	int retval;
7319	int alloc_len, total_len;
7320	int opcode, service_action, i, j, num;
7321
7322	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7323
7324	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7325	retval = CTL_RETVAL_COMPLETE;
7326
7327	opcode = cdb->requested_opcode;
7328	service_action = scsi_2btoul(cdb->requested_service_action);
7329	switch (cdb->options & RSO_OPTIONS_MASK) {
7330	case RSO_OPTIONS_ALL:
7331		num = 0;
7332		for (i = 0; i < 256; i++) {
7333			entry = &ctl_cmd_table[i];
7334			if (entry->flags & CTL_CMD_FLAG_SA5) {
7335				for (j = 0; j < 32; j++) {
7336					sentry = &((const struct ctl_cmd_entry *)
7337					    entry->execute)[j];
7338					if (ctl_cmd_applicable(
7339					    lun->be_lun->lun_type, sentry))
7340						num++;
7341				}
7342			} else {
7343				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7344				    entry))
7345					num++;
7346			}
7347		}
7348		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7349		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7350		break;
7351	case RSO_OPTIONS_OC:
7352		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7353			ctl_set_invalid_field(/*ctsio*/ ctsio,
7354					      /*sks_valid*/ 1,
7355					      /*command*/ 1,
7356					      /*field*/ 2,
7357					      /*bit_valid*/ 1,
7358					      /*bit*/ 2);
7359			ctl_done((union ctl_io *)ctsio);
7360			return (CTL_RETVAL_COMPLETE);
7361		}
7362		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7363		break;
7364	case RSO_OPTIONS_OC_SA:
7365		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7366		    service_action >= 32) {
7367			ctl_set_invalid_field(/*ctsio*/ ctsio,
7368					      /*sks_valid*/ 1,
7369					      /*command*/ 1,
7370					      /*field*/ 2,
7371					      /*bit_valid*/ 1,
7372					      /*bit*/ 2);
7373			ctl_done((union ctl_io *)ctsio);
7374			return (CTL_RETVAL_COMPLETE);
7375		}
7376		/* FALLTHROUGH */
7377	case RSO_OPTIONS_OC_ASA:
7378		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7379		break;
7380	default:
7381		ctl_set_invalid_field(/*ctsio*/ ctsio,
7382				      /*sks_valid*/ 1,
7383				      /*command*/ 1,
7384				      /*field*/ 2,
7385				      /*bit_valid*/ 1,
7386				      /*bit*/ 2);
7387		ctl_done((union ctl_io *)ctsio);
7388		return (CTL_RETVAL_COMPLETE);
7389	}
7390
7391	alloc_len = scsi_4btoul(cdb->length);
7392
7393	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7394
7395	ctsio->kern_sg_entries = 0;
7396
7397	if (total_len < alloc_len) {
7398		ctsio->residual = alloc_len - total_len;
7399		ctsio->kern_data_len = total_len;
7400		ctsio->kern_total_len = total_len;
7401	} else {
7402		ctsio->residual = 0;
7403		ctsio->kern_data_len = alloc_len;
7404		ctsio->kern_total_len = alloc_len;
7405	}
7406	ctsio->kern_data_resid = 0;
7407	ctsio->kern_rel_offset = 0;
7408
7409	switch (cdb->options & RSO_OPTIONS_MASK) {
7410	case RSO_OPTIONS_ALL:
7411		all = (struct scsi_report_supported_opcodes_all *)
7412		    ctsio->kern_data_ptr;
7413		num = 0;
7414		for (i = 0; i < 256; i++) {
7415			entry = &ctl_cmd_table[i];
7416			if (entry->flags & CTL_CMD_FLAG_SA5) {
7417				for (j = 0; j < 32; j++) {
7418					sentry = &((const struct ctl_cmd_entry *)
7419					    entry->execute)[j];
7420					if (!ctl_cmd_applicable(
7421					    lun->be_lun->lun_type, sentry))
7422						continue;
7423					descr = &all->descr[num++];
7424					descr->opcode = i;
7425					scsi_ulto2b(j, descr->service_action);
7426					descr->flags = RSO_SERVACTV;
7427					scsi_ulto2b(sentry->length,
7428					    descr->cdb_length);
7429				}
7430			} else {
7431				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7432				    entry))
7433					continue;
7434				descr = &all->descr[num++];
7435				descr->opcode = i;
7436				scsi_ulto2b(0, descr->service_action);
7437				descr->flags = 0;
7438				scsi_ulto2b(entry->length, descr->cdb_length);
7439			}
7440		}
7441		scsi_ulto4b(
7442		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7443		    all->length);
7444		break;
7445	case RSO_OPTIONS_OC:
7446		one = (struct scsi_report_supported_opcodes_one *)
7447		    ctsio->kern_data_ptr;
7448		entry = &ctl_cmd_table[opcode];
7449		goto fill_one;
7450	case RSO_OPTIONS_OC_SA:
7451		one = (struct scsi_report_supported_opcodes_one *)
7452		    ctsio->kern_data_ptr;
7453		entry = &ctl_cmd_table[opcode];
7454		entry = &((const struct ctl_cmd_entry *)
7455		    entry->execute)[service_action];
7456fill_one:
7457		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7458			one->support = 3;
7459			scsi_ulto2b(entry->length, one->cdb_length);
7460			one->cdb_usage[0] = opcode;
7461			memcpy(&one->cdb_usage[1], entry->usage,
7462			    entry->length - 1);
7463		} else
7464			one->support = 1;
7465		break;
7466	case RSO_OPTIONS_OC_ASA:
7467		one = (struct scsi_report_supported_opcodes_one *)
7468		    ctsio->kern_data_ptr;
7469		entry = &ctl_cmd_table[opcode];
7470		if (entry->flags & CTL_CMD_FLAG_SA5) {
7471			entry = &((const struct ctl_cmd_entry *)
7472			    entry->execute)[service_action];
7473		} else if (service_action != 0) {
7474			one->support = 1;
7475			break;
7476		}
7477		goto fill_one;
7478	}
7479
7480	ctl_set_success(ctsio);
7481	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7482	ctsio->be_move_done = ctl_config_move_done;
7483	ctl_datamove((union ctl_io *)ctsio);
7484	return(retval);
7485}
7486
7487int
7488ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7489{
7490	struct scsi_report_supported_tmf *cdb;
7491	struct scsi_report_supported_tmf_ext_data *data;
7492	int retval;
7493	int alloc_len, total_len;
7494
7495	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7496
7497	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7498
7499	retval = CTL_RETVAL_COMPLETE;
7500
7501	if (cdb->options & RST_REPD)
7502		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7503	else
7504		total_len = sizeof(struct scsi_report_supported_tmf_data);
7505	alloc_len = scsi_4btoul(cdb->length);
7506
7507	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7508
7509	ctsio->kern_sg_entries = 0;
7510
7511	if (total_len < alloc_len) {
7512		ctsio->residual = alloc_len - total_len;
7513		ctsio->kern_data_len = total_len;
7514		ctsio->kern_total_len = total_len;
7515	} else {
7516		ctsio->residual = 0;
7517		ctsio->kern_data_len = alloc_len;
7518		ctsio->kern_total_len = alloc_len;
7519	}
7520	ctsio->kern_data_resid = 0;
7521	ctsio->kern_rel_offset = 0;
7522
7523	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7524	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7525	    RST_TRS;
7526	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7527	data->length = total_len - 4;
7528
7529	ctl_set_success(ctsio);
7530	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7531	ctsio->be_move_done = ctl_config_move_done;
7532	ctl_datamove((union ctl_io *)ctsio);
7533	return (retval);
7534}
7535
7536int
7537ctl_report_timestamp(struct ctl_scsiio *ctsio)
7538{
7539	struct scsi_report_timestamp *cdb;
7540	struct scsi_report_timestamp_data *data;
7541	struct timeval tv;
7542	int64_t timestamp;
7543	int retval;
7544	int alloc_len, total_len;
7545
7546	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7547
7548	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7549
7550	retval = CTL_RETVAL_COMPLETE;
7551
7552	total_len = sizeof(struct scsi_report_timestamp_data);
7553	alloc_len = scsi_4btoul(cdb->length);
7554
7555	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7556
7557	ctsio->kern_sg_entries = 0;
7558
7559	if (total_len < alloc_len) {
7560		ctsio->residual = alloc_len - total_len;
7561		ctsio->kern_data_len = total_len;
7562		ctsio->kern_total_len = total_len;
7563	} else {
7564		ctsio->residual = 0;
7565		ctsio->kern_data_len = alloc_len;
7566		ctsio->kern_total_len = alloc_len;
7567	}
7568	ctsio->kern_data_resid = 0;
7569	ctsio->kern_rel_offset = 0;
7570
7571	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7572	scsi_ulto2b(sizeof(*data) - 2, data->length);
7573	data->origin = RTS_ORIG_OUTSIDE;
7574	getmicrotime(&tv);
7575	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7576	scsi_ulto4b(timestamp >> 16, data->timestamp);
7577	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7578
7579	ctl_set_success(ctsio);
7580	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7581	ctsio->be_move_done = ctl_config_move_done;
7582	ctl_datamove((union ctl_io *)ctsio);
7583	return (retval);
7584}
7585
7586int
7587ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7588{
7589	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7590	struct ctl_lun *lun = CTL_LUN(ctsio);
7591	struct scsi_per_res_in *cdb;
7592	int alloc_len, total_len = 0;
7593	/* struct scsi_per_res_in_rsrv in_data; */
7594	uint64_t key;
7595
7596	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7597
7598	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7599
7600	alloc_len = scsi_2btoul(cdb->length);
7601
7602retry:
7603	mtx_lock(&lun->lun_lock);
7604	switch (cdb->action) {
7605	case SPRI_RK: /* read keys */
7606		total_len = sizeof(struct scsi_per_res_in_keys) +
7607			lun->pr_key_count *
7608			sizeof(struct scsi_per_res_key);
7609		break;
7610	case SPRI_RR: /* read reservation */
7611		if (lun->flags & CTL_LUN_PR_RESERVED)
7612			total_len = sizeof(struct scsi_per_res_in_rsrv);
7613		else
7614			total_len = sizeof(struct scsi_per_res_in_header);
7615		break;
7616	case SPRI_RC: /* report capabilities */
7617		total_len = sizeof(struct scsi_per_res_cap);
7618		break;
7619	case SPRI_RS: /* read full status */
7620		total_len = sizeof(struct scsi_per_res_in_header) +
7621		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7622		    lun->pr_key_count;
7623		break;
7624	default:
7625		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7626	}
7627	mtx_unlock(&lun->lun_lock);
7628
7629	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7630
7631	if (total_len < alloc_len) {
7632		ctsio->residual = alloc_len - total_len;
7633		ctsio->kern_data_len = total_len;
7634		ctsio->kern_total_len = total_len;
7635	} else {
7636		ctsio->residual = 0;
7637		ctsio->kern_data_len = alloc_len;
7638		ctsio->kern_total_len = alloc_len;
7639	}
7640
7641	ctsio->kern_data_resid = 0;
7642	ctsio->kern_rel_offset = 0;
7643	ctsio->kern_sg_entries = 0;
7644
7645	mtx_lock(&lun->lun_lock);
7646	switch (cdb->action) {
7647	case SPRI_RK: { // read keys
7648        struct scsi_per_res_in_keys *res_keys;
7649		int i, key_count;
7650
7651		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7652
7653		/*
7654		 * We had to drop the lock to allocate our buffer, which
7655		 * leaves time for someone to come in with another
7656		 * persistent reservation.  (That is unlikely, though,
7657		 * since this should be the only persistent reservation
7658		 * command active right now.)
7659		 */
7660		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7661		    (lun->pr_key_count *
7662		     sizeof(struct scsi_per_res_key)))){
7663			mtx_unlock(&lun->lun_lock);
7664			free(ctsio->kern_data_ptr, M_CTL);
7665			printf("%s: reservation length changed, retrying\n",
7666			       __func__);
7667			goto retry;
7668		}
7669
7670		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7671
7672		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7673			     lun->pr_key_count, res_keys->header.length);
7674
7675		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7676			if ((key = ctl_get_prkey(lun, i)) == 0)
7677				continue;
7678
7679			/*
7680			 * We used lun->pr_key_count to calculate the
7681			 * size to allocate.  If it turns out the number of
7682			 * initiators with the registered flag set is
7683			 * larger than that (i.e. they haven't been kept in
7684			 * sync), we've got a problem.
7685			 */
7686			if (key_count >= lun->pr_key_count) {
7687				key_count++;
7688				continue;
7689			}
7690			scsi_u64to8b(key, res_keys->keys[key_count].key);
7691			key_count++;
7692		}
7693		break;
7694	}
7695	case SPRI_RR: { // read reservation
7696		struct scsi_per_res_in_rsrv *res;
7697		int tmp_len, header_only;
7698
7699		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7700
7701		scsi_ulto4b(lun->pr_generation, res->header.generation);
7702
7703		if (lun->flags & CTL_LUN_PR_RESERVED)
7704		{
7705			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7706			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7707				    res->header.length);
7708			header_only = 0;
7709		} else {
7710			tmp_len = sizeof(struct scsi_per_res_in_header);
7711			scsi_ulto4b(0, res->header.length);
7712			header_only = 1;
7713		}
7714
7715		/*
7716		 * We had to drop the lock to allocate our buffer, which
7717		 * leaves time for someone to come in with another
7718		 * persistent reservation.  (That is unlikely, though,
7719		 * since this should be the only persistent reservation
7720		 * command active right now.)
7721		 */
7722		if (tmp_len != total_len) {
7723			mtx_unlock(&lun->lun_lock);
7724			free(ctsio->kern_data_ptr, M_CTL);
7725			printf("%s: reservation status changed, retrying\n",
7726			       __func__);
7727			goto retry;
7728		}
7729
7730		/*
7731		 * No reservation held, so we're done.
7732		 */
7733		if (header_only != 0)
7734			break;
7735
7736		/*
7737		 * If the registration is an All Registrants type, the key
7738		 * is 0, since it doesn't really matter.
7739		 */
7740		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7741			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7742			    res->data.reservation);
7743		}
7744		res->data.scopetype = lun->pr_res_type;
7745		break;
7746	}
7747	case SPRI_RC:     //report capabilities
7748	{
7749		struct scsi_per_res_cap *res_cap;
7750		uint16_t type_mask;
7751
7752		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7753		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7754		res_cap->flags1 = SPRI_CRH;
7755		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7756		type_mask = SPRI_TM_WR_EX_AR |
7757			    SPRI_TM_EX_AC_RO |
7758			    SPRI_TM_WR_EX_RO |
7759			    SPRI_TM_EX_AC |
7760			    SPRI_TM_WR_EX |
7761			    SPRI_TM_EX_AC_AR;
7762		scsi_ulto2b(type_mask, res_cap->type_mask);
7763		break;
7764	}
7765	case SPRI_RS: { // read full status
7766		struct scsi_per_res_in_full *res_status;
7767		struct scsi_per_res_in_full_desc *res_desc;
7768		struct ctl_port *port;
7769		int i, len;
7770
7771		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7772
7773		/*
7774		 * We had to drop the lock to allocate our buffer, which
7775		 * leaves time for someone to come in with another
7776		 * persistent reservation.  (That is unlikely, though,
7777		 * since this should be the only persistent reservation
7778		 * command active right now.)
7779		 */
7780		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7781		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7782		     lun->pr_key_count)){
7783			mtx_unlock(&lun->lun_lock);
7784			free(ctsio->kern_data_ptr, M_CTL);
7785			printf("%s: reservation length changed, retrying\n",
7786			       __func__);
7787			goto retry;
7788		}
7789
7790		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7791
7792		res_desc = &res_status->desc[0];
7793		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7794			if ((key = ctl_get_prkey(lun, i)) == 0)
7795				continue;
7796
7797			scsi_u64to8b(key, res_desc->res_key.key);
7798			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7799			    (lun->pr_res_idx == i ||
7800			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7801				res_desc->flags = SPRI_FULL_R_HOLDER;
7802				res_desc->scopetype = lun->pr_res_type;
7803			}
7804			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7805			    res_desc->rel_trgt_port_id);
7806			len = 0;
7807			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7808			if (port != NULL)
7809				len = ctl_create_iid(port,
7810				    i % CTL_MAX_INIT_PER_PORT,
7811				    res_desc->transport_id);
7812			scsi_ulto4b(len, res_desc->additional_length);
7813			res_desc = (struct scsi_per_res_in_full_desc *)
7814			    &res_desc->transport_id[len];
7815		}
7816		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7817		    res_status->header.length);
7818		break;
7819	}
7820	default:
7821		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7822	}
7823	mtx_unlock(&lun->lun_lock);
7824
7825	ctl_set_success(ctsio);
7826	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7827	ctsio->be_move_done = ctl_config_move_done;
7828	ctl_datamove((union ctl_io *)ctsio);
7829	return (CTL_RETVAL_COMPLETE);
7830}
7831
7832/*
7833 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7834 * it should return.
7835 */
7836static int
7837ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7838		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7839		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7840		struct scsi_per_res_out_parms* param)
7841{
7842	union ctl_ha_msg persis_io;
7843	int i;
7844
7845	mtx_lock(&lun->lun_lock);
7846	if (sa_res_key == 0) {
7847		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7848			/* validate scope and type */
7849			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7850			     SPR_LU_SCOPE) {
7851				mtx_unlock(&lun->lun_lock);
7852				ctl_set_invalid_field(/*ctsio*/ ctsio,
7853						      /*sks_valid*/ 1,
7854						      /*command*/ 1,
7855						      /*field*/ 2,
7856						      /*bit_valid*/ 1,
7857						      /*bit*/ 4);
7858				ctl_done((union ctl_io *)ctsio);
7859				return (1);
7860			}
7861
7862		        if (type>8 || type==2 || type==4 || type==0) {
7863				mtx_unlock(&lun->lun_lock);
7864				ctl_set_invalid_field(/*ctsio*/ ctsio,
7865       	           				      /*sks_valid*/ 1,
7866						      /*command*/ 1,
7867						      /*field*/ 2,
7868						      /*bit_valid*/ 1,
7869						      /*bit*/ 0);
7870				ctl_done((union ctl_io *)ctsio);
7871				return (1);
7872		        }
7873
7874			/*
7875			 * Unregister everybody else and build UA for
7876			 * them
7877			 */
7878			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7879				if (i == residx || ctl_get_prkey(lun, i) == 0)
7880					continue;
7881
7882				ctl_clr_prkey(lun, i);
7883				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7884			}
7885			lun->pr_key_count = 1;
7886			lun->pr_res_type = type;
7887			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7888			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7889				lun->pr_res_idx = residx;
7890			lun->pr_generation++;
7891			mtx_unlock(&lun->lun_lock);
7892
7893			/* send msg to other side */
7894			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7895			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7896			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7897			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7898			persis_io.pr.pr_info.res_type = type;
7899			memcpy(persis_io.pr.pr_info.sa_res_key,
7900			       param->serv_act_res_key,
7901			       sizeof(param->serv_act_res_key));
7902			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7903			    sizeof(persis_io.pr), M_WAITOK);
7904		} else {
7905			/* not all registrants */
7906			mtx_unlock(&lun->lun_lock);
7907			free(ctsio->kern_data_ptr, M_CTL);
7908			ctl_set_invalid_field(ctsio,
7909					      /*sks_valid*/ 1,
7910					      /*command*/ 0,
7911					      /*field*/ 8,
7912					      /*bit_valid*/ 0,
7913					      /*bit*/ 0);
7914			ctl_done((union ctl_io *)ctsio);
7915			return (1);
7916		}
7917	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7918		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7919		int found = 0;
7920
7921		if (res_key == sa_res_key) {
7922			/* special case */
7923			/*
7924			 * The spec implies this is not good but doesn't
7925			 * say what to do. There are two choices either
7926			 * generate a res conflict or check condition
7927			 * with illegal field in parameter data. Since
7928			 * that is what is done when the sa_res_key is
7929			 * zero I'll take that approach since this has
7930			 * to do with the sa_res_key.
7931			 */
7932			mtx_unlock(&lun->lun_lock);
7933			free(ctsio->kern_data_ptr, M_CTL);
7934			ctl_set_invalid_field(ctsio,
7935					      /*sks_valid*/ 1,
7936					      /*command*/ 0,
7937					      /*field*/ 8,
7938					      /*bit_valid*/ 0,
7939					      /*bit*/ 0);
7940			ctl_done((union ctl_io *)ctsio);
7941			return (1);
7942		}
7943
7944		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7945			if (ctl_get_prkey(lun, i) != sa_res_key)
7946				continue;
7947
7948			found = 1;
7949			ctl_clr_prkey(lun, i);
7950			lun->pr_key_count--;
7951			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7952		}
7953		if (!found) {
7954			mtx_unlock(&lun->lun_lock);
7955			free(ctsio->kern_data_ptr, M_CTL);
7956			ctl_set_reservation_conflict(ctsio);
7957			ctl_done((union ctl_io *)ctsio);
7958			return (CTL_RETVAL_COMPLETE);
7959		}
7960		lun->pr_generation++;
7961		mtx_unlock(&lun->lun_lock);
7962
7963		/* send msg to other side */
7964		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7965		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7966		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7967		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7968		persis_io.pr.pr_info.res_type = type;
7969		memcpy(persis_io.pr.pr_info.sa_res_key,
7970		       param->serv_act_res_key,
7971		       sizeof(param->serv_act_res_key));
7972		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7973		    sizeof(persis_io.pr), M_WAITOK);
7974	} else {
7975		/* Reserved but not all registrants */
7976		/* sa_res_key is res holder */
7977		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7978			/* validate scope and type */
7979			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7980			     SPR_LU_SCOPE) {
7981				mtx_unlock(&lun->lun_lock);
7982				ctl_set_invalid_field(/*ctsio*/ ctsio,
7983						      /*sks_valid*/ 1,
7984						      /*command*/ 1,
7985						      /*field*/ 2,
7986						      /*bit_valid*/ 1,
7987						      /*bit*/ 4);
7988				ctl_done((union ctl_io *)ctsio);
7989				return (1);
7990			}
7991
7992			if (type>8 || type==2 || type==4 || type==0) {
7993				mtx_unlock(&lun->lun_lock);
7994				ctl_set_invalid_field(/*ctsio*/ ctsio,
7995						      /*sks_valid*/ 1,
7996						      /*command*/ 1,
7997						      /*field*/ 2,
7998						      /*bit_valid*/ 1,
7999						      /*bit*/ 0);
8000				ctl_done((union ctl_io *)ctsio);
8001				return (1);
8002			}
8003
8004			/*
8005			 * Do the following:
8006			 * if sa_res_key != res_key remove all
8007			 * registrants w/sa_res_key and generate UA
8008			 * for these registrants(Registrations
8009			 * Preempted) if it wasn't an exclusive
8010			 * reservation generate UA(Reservations
8011			 * Preempted) for all other registered nexuses
8012			 * if the type has changed. Establish the new
8013			 * reservation and holder. If res_key and
8014			 * sa_res_key are the same do the above
8015			 * except don't unregister the res holder.
8016			 */
8017
8018			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8019				if (i == residx || ctl_get_prkey(lun, i) == 0)
8020					continue;
8021
8022				if (sa_res_key == ctl_get_prkey(lun, i)) {
8023					ctl_clr_prkey(lun, i);
8024					lun->pr_key_count--;
8025					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8026				} else if (type != lun->pr_res_type &&
8027				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8028				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8029					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8030				}
8031			}
8032			lun->pr_res_type = type;
8033			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8034			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8035				lun->pr_res_idx = residx;
8036			else
8037				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8038			lun->pr_generation++;
8039			mtx_unlock(&lun->lun_lock);
8040
8041			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8042			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8043			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8044			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8045			persis_io.pr.pr_info.res_type = type;
8046			memcpy(persis_io.pr.pr_info.sa_res_key,
8047			       param->serv_act_res_key,
8048			       sizeof(param->serv_act_res_key));
8049			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8050			    sizeof(persis_io.pr), M_WAITOK);
8051		} else {
8052			/*
8053			 * sa_res_key is not the res holder just
8054			 * remove registrants
8055			 */
8056			int found=0;
8057
8058			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8059				if (sa_res_key != ctl_get_prkey(lun, i))
8060					continue;
8061
8062				found = 1;
8063				ctl_clr_prkey(lun, i);
8064				lun->pr_key_count--;
8065				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8066			}
8067
8068			if (!found) {
8069				mtx_unlock(&lun->lun_lock);
8070				free(ctsio->kern_data_ptr, M_CTL);
8071				ctl_set_reservation_conflict(ctsio);
8072				ctl_done((union ctl_io *)ctsio);
8073		        	return (1);
8074			}
8075			lun->pr_generation++;
8076			mtx_unlock(&lun->lun_lock);
8077
8078			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8079			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8080			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8081			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8082			persis_io.pr.pr_info.res_type = type;
8083			memcpy(persis_io.pr.pr_info.sa_res_key,
8084			       param->serv_act_res_key,
8085			       sizeof(param->serv_act_res_key));
8086			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8087			    sizeof(persis_io.pr), M_WAITOK);
8088		}
8089	}
8090	return (0);
8091}
8092
8093static void
8094ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8095{
8096	uint64_t sa_res_key;
8097	int i;
8098
8099	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8100
8101	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8102	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8103	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8104		if (sa_res_key == 0) {
8105			/*
8106			 * Unregister everybody else and build UA for
8107			 * them
8108			 */
8109			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8110				if (i == msg->pr.pr_info.residx ||
8111				    ctl_get_prkey(lun, i) == 0)
8112					continue;
8113
8114				ctl_clr_prkey(lun, i);
8115				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8116			}
8117
8118			lun->pr_key_count = 1;
8119			lun->pr_res_type = msg->pr.pr_info.res_type;
8120			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8121			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8122				lun->pr_res_idx = msg->pr.pr_info.residx;
8123		} else {
8124		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8125				if (sa_res_key == ctl_get_prkey(lun, i))
8126					continue;
8127
8128				ctl_clr_prkey(lun, i);
8129				lun->pr_key_count--;
8130				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8131			}
8132		}
8133	} else {
8134		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8135			if (i == msg->pr.pr_info.residx ||
8136			    ctl_get_prkey(lun, i) == 0)
8137				continue;
8138
8139			if (sa_res_key == ctl_get_prkey(lun, i)) {
8140				ctl_clr_prkey(lun, i);
8141				lun->pr_key_count--;
8142				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8143			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8144			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8145			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8146				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8147			}
8148		}
8149		lun->pr_res_type = msg->pr.pr_info.res_type;
8150		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8151		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8152			lun->pr_res_idx = msg->pr.pr_info.residx;
8153		else
8154			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8155	}
8156	lun->pr_generation++;
8157
8158}
8159
8160
8161int
8162ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8163{
8164	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8165	struct ctl_lun *lun = CTL_LUN(ctsio);
8166	int retval;
8167	u_int32_t param_len;
8168	struct scsi_per_res_out *cdb;
8169	struct scsi_per_res_out_parms* param;
8170	uint32_t residx;
8171	uint64_t res_key, sa_res_key, key;
8172	uint8_t type;
8173	union ctl_ha_msg persis_io;
8174	int    i;
8175
8176	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8177
8178	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8179	retval = CTL_RETVAL_COMPLETE;
8180
8181	/*
8182	 * We only support whole-LUN scope.  The scope & type are ignored for
8183	 * register, register and ignore existing key and clear.
8184	 * We sometimes ignore scope and type on preempts too!!
8185	 * Verify reservation type here as well.
8186	 */
8187	type = cdb->scope_type & SPR_TYPE_MASK;
8188	if ((cdb->action == SPRO_RESERVE)
8189	 || (cdb->action == SPRO_RELEASE)) {
8190		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8191			ctl_set_invalid_field(/*ctsio*/ ctsio,
8192					      /*sks_valid*/ 1,
8193					      /*command*/ 1,
8194					      /*field*/ 2,
8195					      /*bit_valid*/ 1,
8196					      /*bit*/ 4);
8197			ctl_done((union ctl_io *)ctsio);
8198			return (CTL_RETVAL_COMPLETE);
8199		}
8200
8201		if (type>8 || type==2 || type==4 || type==0) {
8202			ctl_set_invalid_field(/*ctsio*/ ctsio,
8203					      /*sks_valid*/ 1,
8204					      /*command*/ 1,
8205					      /*field*/ 2,
8206					      /*bit_valid*/ 1,
8207					      /*bit*/ 0);
8208			ctl_done((union ctl_io *)ctsio);
8209			return (CTL_RETVAL_COMPLETE);
8210		}
8211	}
8212
8213	param_len = scsi_4btoul(cdb->length);
8214
8215	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8216		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8217		ctsio->kern_data_len = param_len;
8218		ctsio->kern_total_len = param_len;
8219		ctsio->kern_data_resid = 0;
8220		ctsio->kern_rel_offset = 0;
8221		ctsio->kern_sg_entries = 0;
8222		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8223		ctsio->be_move_done = ctl_config_move_done;
8224		ctl_datamove((union ctl_io *)ctsio);
8225
8226		return (CTL_RETVAL_COMPLETE);
8227	}
8228
8229	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8230
8231	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8232	res_key = scsi_8btou64(param->res_key.key);
8233	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8234
8235	/*
8236	 * Validate the reservation key here except for SPRO_REG_IGNO
8237	 * This must be done for all other service actions
8238	 */
8239	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8240		mtx_lock(&lun->lun_lock);
8241		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8242			if (res_key != key) {
8243				/*
8244				 * The current key passed in doesn't match
8245				 * the one the initiator previously
8246				 * registered.
8247				 */
8248				mtx_unlock(&lun->lun_lock);
8249				free(ctsio->kern_data_ptr, M_CTL);
8250				ctl_set_reservation_conflict(ctsio);
8251				ctl_done((union ctl_io *)ctsio);
8252				return (CTL_RETVAL_COMPLETE);
8253			}
8254		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8255			/*
8256			 * We are not registered
8257			 */
8258			mtx_unlock(&lun->lun_lock);
8259			free(ctsio->kern_data_ptr, M_CTL);
8260			ctl_set_reservation_conflict(ctsio);
8261			ctl_done((union ctl_io *)ctsio);
8262			return (CTL_RETVAL_COMPLETE);
8263		} else if (res_key != 0) {
8264			/*
8265			 * We are not registered and trying to register but
8266			 * the register key isn't zero.
8267			 */
8268			mtx_unlock(&lun->lun_lock);
8269			free(ctsio->kern_data_ptr, M_CTL);
8270			ctl_set_reservation_conflict(ctsio);
8271			ctl_done((union ctl_io *)ctsio);
8272			return (CTL_RETVAL_COMPLETE);
8273		}
8274		mtx_unlock(&lun->lun_lock);
8275	}
8276
8277	switch (cdb->action & SPRO_ACTION_MASK) {
8278	case SPRO_REGISTER:
8279	case SPRO_REG_IGNO: {
8280
8281#if 0
8282		printf("Registration received\n");
8283#endif
8284
8285		/*
8286		 * We don't support any of these options, as we report in
8287		 * the read capabilities request (see
8288		 * ctl_persistent_reserve_in(), above).
8289		 */
8290		if ((param->flags & SPR_SPEC_I_PT)
8291		 || (param->flags & SPR_ALL_TG_PT)
8292		 || (param->flags & SPR_APTPL)) {
8293			int bit_ptr;
8294
8295			if (param->flags & SPR_APTPL)
8296				bit_ptr = 0;
8297			else if (param->flags & SPR_ALL_TG_PT)
8298				bit_ptr = 2;
8299			else /* SPR_SPEC_I_PT */
8300				bit_ptr = 3;
8301
8302			free(ctsio->kern_data_ptr, M_CTL);
8303			ctl_set_invalid_field(ctsio,
8304					      /*sks_valid*/ 1,
8305					      /*command*/ 0,
8306					      /*field*/ 20,
8307					      /*bit_valid*/ 1,
8308					      /*bit*/ bit_ptr);
8309			ctl_done((union ctl_io *)ctsio);
8310			return (CTL_RETVAL_COMPLETE);
8311		}
8312
8313		mtx_lock(&lun->lun_lock);
8314
8315		/*
8316		 * The initiator wants to clear the
8317		 * key/unregister.
8318		 */
8319		if (sa_res_key == 0) {
8320			if ((res_key == 0
8321			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8322			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8323			  && ctl_get_prkey(lun, residx) == 0)) {
8324				mtx_unlock(&lun->lun_lock);
8325				goto done;
8326			}
8327
8328			ctl_clr_prkey(lun, residx);
8329			lun->pr_key_count--;
8330
8331			if (residx == lun->pr_res_idx) {
8332				lun->flags &= ~CTL_LUN_PR_RESERVED;
8333				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8334
8335				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8336				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8337				    lun->pr_key_count) {
8338					/*
8339					 * If the reservation is a registrants
8340					 * only type we need to generate a UA
8341					 * for other registered inits.  The
8342					 * sense code should be RESERVATIONS
8343					 * RELEASED
8344					 */
8345
8346					for (i = softc->init_min; i < softc->init_max; i++){
8347						if (ctl_get_prkey(lun, i) == 0)
8348							continue;
8349						ctl_est_ua(lun, i,
8350						    CTL_UA_RES_RELEASE);
8351					}
8352				}
8353				lun->pr_res_type = 0;
8354			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8355				if (lun->pr_key_count==0) {
8356					lun->flags &= ~CTL_LUN_PR_RESERVED;
8357					lun->pr_res_type = 0;
8358					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8359				}
8360			}
8361			lun->pr_generation++;
8362			mtx_unlock(&lun->lun_lock);
8363
8364			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8365			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8366			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8367			persis_io.pr.pr_info.residx = residx;
8368			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8369			    sizeof(persis_io.pr), M_WAITOK);
8370		} else /* sa_res_key != 0 */ {
8371
8372			/*
8373			 * If we aren't registered currently then increment
8374			 * the key count and set the registered flag.
8375			 */
8376			ctl_alloc_prkey(lun, residx);
8377			if (ctl_get_prkey(lun, residx) == 0)
8378				lun->pr_key_count++;
8379			ctl_set_prkey(lun, residx, sa_res_key);
8380			lun->pr_generation++;
8381			mtx_unlock(&lun->lun_lock);
8382
8383			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8384			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8385			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8386			persis_io.pr.pr_info.residx = residx;
8387			memcpy(persis_io.pr.pr_info.sa_res_key,
8388			       param->serv_act_res_key,
8389			       sizeof(param->serv_act_res_key));
8390			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8391			    sizeof(persis_io.pr), M_WAITOK);
8392		}
8393
8394		break;
8395	}
8396	case SPRO_RESERVE:
8397#if 0
8398                printf("Reserve executed type %d\n", type);
8399#endif
8400		mtx_lock(&lun->lun_lock);
8401		if (lun->flags & CTL_LUN_PR_RESERVED) {
8402			/*
8403			 * if this isn't the reservation holder and it's
8404			 * not a "all registrants" type or if the type is
8405			 * different then we have a conflict
8406			 */
8407			if ((lun->pr_res_idx != residx
8408			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8409			 || lun->pr_res_type != type) {
8410				mtx_unlock(&lun->lun_lock);
8411				free(ctsio->kern_data_ptr, M_CTL);
8412				ctl_set_reservation_conflict(ctsio);
8413				ctl_done((union ctl_io *)ctsio);
8414				return (CTL_RETVAL_COMPLETE);
8415			}
8416			mtx_unlock(&lun->lun_lock);
8417		} else /* create a reservation */ {
8418			/*
8419			 * If it's not an "all registrants" type record
8420			 * reservation holder
8421			 */
8422			if (type != SPR_TYPE_WR_EX_AR
8423			 && type != SPR_TYPE_EX_AC_AR)
8424				lun->pr_res_idx = residx; /* Res holder */
8425			else
8426				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8427
8428			lun->flags |= CTL_LUN_PR_RESERVED;
8429			lun->pr_res_type = type;
8430
8431			mtx_unlock(&lun->lun_lock);
8432
8433			/* send msg to other side */
8434			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8435			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8436			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8437			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8438			persis_io.pr.pr_info.res_type = type;
8439			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8440			    sizeof(persis_io.pr), M_WAITOK);
8441		}
8442		break;
8443
8444	case SPRO_RELEASE:
8445		mtx_lock(&lun->lun_lock);
8446		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8447			/* No reservation exists return good status */
8448			mtx_unlock(&lun->lun_lock);
8449			goto done;
8450		}
8451		/*
8452		 * Is this nexus a reservation holder?
8453		 */
8454		if (lun->pr_res_idx != residx
8455		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8456			/*
8457			 * not a res holder return good status but
8458			 * do nothing
8459			 */
8460			mtx_unlock(&lun->lun_lock);
8461			goto done;
8462		}
8463
8464		if (lun->pr_res_type != type) {
8465			mtx_unlock(&lun->lun_lock);
8466			free(ctsio->kern_data_ptr, M_CTL);
8467			ctl_set_illegal_pr_release(ctsio);
8468			ctl_done((union ctl_io *)ctsio);
8469			return (CTL_RETVAL_COMPLETE);
8470		}
8471
8472		/* okay to release */
8473		lun->flags &= ~CTL_LUN_PR_RESERVED;
8474		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8475		lun->pr_res_type = 0;
8476
8477		/*
8478		 * If this isn't an exclusive access reservation and NUAR
8479		 * is not set, generate UA for all other registrants.
8480		 */
8481		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8482		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8483			for (i = softc->init_min; i < softc->init_max; i++) {
8484				if (i == residx || ctl_get_prkey(lun, i) == 0)
8485					continue;
8486				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8487			}
8488		}
8489		mtx_unlock(&lun->lun_lock);
8490
8491		/* Send msg to other side */
8492		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8493		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8494		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8495		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8496		     sizeof(persis_io.pr), M_WAITOK);
8497		break;
8498
8499	case SPRO_CLEAR:
8500		/* send msg to other side */
8501
8502		mtx_lock(&lun->lun_lock);
8503		lun->flags &= ~CTL_LUN_PR_RESERVED;
8504		lun->pr_res_type = 0;
8505		lun->pr_key_count = 0;
8506		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8507
8508		ctl_clr_prkey(lun, residx);
8509		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8510			if (ctl_get_prkey(lun, i) != 0) {
8511				ctl_clr_prkey(lun, i);
8512				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8513			}
8514		lun->pr_generation++;
8515		mtx_unlock(&lun->lun_lock);
8516
8517		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8518		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8519		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8520		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8521		     sizeof(persis_io.pr), M_WAITOK);
8522		break;
8523
8524	case SPRO_PREEMPT:
8525	case SPRO_PRE_ABO: {
8526		int nretval;
8527
8528		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8529					  residx, ctsio, cdb, param);
8530		if (nretval != 0)
8531			return (CTL_RETVAL_COMPLETE);
8532		break;
8533	}
8534	default:
8535		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8536	}
8537
8538done:
8539	free(ctsio->kern_data_ptr, M_CTL);
8540	ctl_set_success(ctsio);
8541	ctl_done((union ctl_io *)ctsio);
8542
8543	return (retval);
8544}
8545
8546/*
8547 * This routine is for handling a message from the other SC pertaining to
8548 * persistent reserve out. All the error checking will have been done
8549 * so only perorming the action need be done here to keep the two
8550 * in sync.
8551 */
8552static void
8553ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8554{
8555	struct ctl_softc *softc = CTL_SOFTC(io);
8556	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8557	struct ctl_lun *lun;
8558	int i;
8559	uint32_t residx, targ_lun;
8560
8561	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8562	mtx_lock(&softc->ctl_lock);
8563	if (targ_lun >= CTL_MAX_LUNS ||
8564	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8565		mtx_unlock(&softc->ctl_lock);
8566		return;
8567	}
8568	mtx_lock(&lun->lun_lock);
8569	mtx_unlock(&softc->ctl_lock);
8570	if (lun->flags & CTL_LUN_DISABLED) {
8571		mtx_unlock(&lun->lun_lock);
8572		return;
8573	}
8574	residx = ctl_get_initindex(&msg->hdr.nexus);
8575	switch(msg->pr.pr_info.action) {
8576	case CTL_PR_REG_KEY:
8577		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8578		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8579			lun->pr_key_count++;
8580		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8581		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8582		lun->pr_generation++;
8583		break;
8584
8585	case CTL_PR_UNREG_KEY:
8586		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8587		lun->pr_key_count--;
8588
8589		/* XXX Need to see if the reservation has been released */
8590		/* if so do we need to generate UA? */
8591		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8592			lun->flags &= ~CTL_LUN_PR_RESERVED;
8593			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8594
8595			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8596			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8597			    lun->pr_key_count) {
8598				/*
8599				 * If the reservation is a registrants
8600				 * only type we need to generate a UA
8601				 * for other registered inits.  The
8602				 * sense code should be RESERVATIONS
8603				 * RELEASED
8604				 */
8605
8606				for (i = softc->init_min; i < softc->init_max; i++) {
8607					if (ctl_get_prkey(lun, i) == 0)
8608						continue;
8609
8610					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8611				}
8612			}
8613			lun->pr_res_type = 0;
8614		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8615			if (lun->pr_key_count==0) {
8616				lun->flags &= ~CTL_LUN_PR_RESERVED;
8617				lun->pr_res_type = 0;
8618				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8619			}
8620		}
8621		lun->pr_generation++;
8622		break;
8623
8624	case CTL_PR_RESERVE:
8625		lun->flags |= CTL_LUN_PR_RESERVED;
8626		lun->pr_res_type = msg->pr.pr_info.res_type;
8627		lun->pr_res_idx = msg->pr.pr_info.residx;
8628
8629		break;
8630
8631	case CTL_PR_RELEASE:
8632		/*
8633		 * If this isn't an exclusive access reservation and NUAR
8634		 * is not set, generate UA for all other registrants.
8635		 */
8636		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8637		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8638		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8639			for (i = softc->init_min; i < softc->init_max; i++)
8640				if (i == residx || ctl_get_prkey(lun, i) == 0)
8641					continue;
8642				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8643		}
8644
8645		lun->flags &= ~CTL_LUN_PR_RESERVED;
8646		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8647		lun->pr_res_type = 0;
8648		break;
8649
8650	case CTL_PR_PREEMPT:
8651		ctl_pro_preempt_other(lun, msg);
8652		break;
8653	case CTL_PR_CLEAR:
8654		lun->flags &= ~CTL_LUN_PR_RESERVED;
8655		lun->pr_res_type = 0;
8656		lun->pr_key_count = 0;
8657		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8658
8659		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8660			if (ctl_get_prkey(lun, i) == 0)
8661				continue;
8662			ctl_clr_prkey(lun, i);
8663			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8664		}
8665		lun->pr_generation++;
8666		break;
8667	}
8668
8669	mtx_unlock(&lun->lun_lock);
8670}
8671
8672int
8673ctl_read_write(struct ctl_scsiio *ctsio)
8674{
8675	struct ctl_lun *lun = CTL_LUN(ctsio);
8676	struct ctl_lba_len_flags *lbalen;
8677	uint64_t lba;
8678	uint32_t num_blocks;
8679	int flags, retval;
8680	int isread;
8681
8682	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8683
8684	flags = 0;
8685	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8686	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8687	switch (ctsio->cdb[0]) {
8688	case READ_6:
8689	case WRITE_6: {
8690		struct scsi_rw_6 *cdb;
8691
8692		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8693
8694		lba = scsi_3btoul(cdb->addr);
8695		/* only 5 bits are valid in the most significant address byte */
8696		lba &= 0x1fffff;
8697		num_blocks = cdb->length;
8698		/*
8699		 * This is correct according to SBC-2.
8700		 */
8701		if (num_blocks == 0)
8702			num_blocks = 256;
8703		break;
8704	}
8705	case READ_10:
8706	case WRITE_10: {
8707		struct scsi_rw_10 *cdb;
8708
8709		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8710		if (cdb->byte2 & SRW10_FUA)
8711			flags |= CTL_LLF_FUA;
8712		if (cdb->byte2 & SRW10_DPO)
8713			flags |= CTL_LLF_DPO;
8714		lba = scsi_4btoul(cdb->addr);
8715		num_blocks = scsi_2btoul(cdb->length);
8716		break;
8717	}
8718	case WRITE_VERIFY_10: {
8719		struct scsi_write_verify_10 *cdb;
8720
8721		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8722		flags |= CTL_LLF_FUA;
8723		if (cdb->byte2 & SWV_DPO)
8724			flags |= CTL_LLF_DPO;
8725		lba = scsi_4btoul(cdb->addr);
8726		num_blocks = scsi_2btoul(cdb->length);
8727		break;
8728	}
8729	case READ_12:
8730	case WRITE_12: {
8731		struct scsi_rw_12 *cdb;
8732
8733		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8734		if (cdb->byte2 & SRW12_FUA)
8735			flags |= CTL_LLF_FUA;
8736		if (cdb->byte2 & SRW12_DPO)
8737			flags |= CTL_LLF_DPO;
8738		lba = scsi_4btoul(cdb->addr);
8739		num_blocks = scsi_4btoul(cdb->length);
8740		break;
8741	}
8742	case WRITE_VERIFY_12: {
8743		struct scsi_write_verify_12 *cdb;
8744
8745		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8746		flags |= CTL_LLF_FUA;
8747		if (cdb->byte2 & SWV_DPO)
8748			flags |= CTL_LLF_DPO;
8749		lba = scsi_4btoul(cdb->addr);
8750		num_blocks = scsi_4btoul(cdb->length);
8751		break;
8752	}
8753	case READ_16:
8754	case WRITE_16: {
8755		struct scsi_rw_16 *cdb;
8756
8757		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8758		if (cdb->byte2 & SRW12_FUA)
8759			flags |= CTL_LLF_FUA;
8760		if (cdb->byte2 & SRW12_DPO)
8761			flags |= CTL_LLF_DPO;
8762		lba = scsi_8btou64(cdb->addr);
8763		num_blocks = scsi_4btoul(cdb->length);
8764		break;
8765	}
8766	case WRITE_ATOMIC_16: {
8767		struct scsi_write_atomic_16 *cdb;
8768
8769		if (lun->be_lun->atomicblock == 0) {
8770			ctl_set_invalid_opcode(ctsio);
8771			ctl_done((union ctl_io *)ctsio);
8772			return (CTL_RETVAL_COMPLETE);
8773		}
8774
8775		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8776		if (cdb->byte2 & SRW12_FUA)
8777			flags |= CTL_LLF_FUA;
8778		if (cdb->byte2 & SRW12_DPO)
8779			flags |= CTL_LLF_DPO;
8780		lba = scsi_8btou64(cdb->addr);
8781		num_blocks = scsi_2btoul(cdb->length);
8782		if (num_blocks > lun->be_lun->atomicblock) {
8783			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8784			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8785			    /*bit*/ 0);
8786			ctl_done((union ctl_io *)ctsio);
8787			return (CTL_RETVAL_COMPLETE);
8788		}
8789		break;
8790	}
8791	case WRITE_VERIFY_16: {
8792		struct scsi_write_verify_16 *cdb;
8793
8794		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8795		flags |= CTL_LLF_FUA;
8796		if (cdb->byte2 & SWV_DPO)
8797			flags |= CTL_LLF_DPO;
8798		lba = scsi_8btou64(cdb->addr);
8799		num_blocks = scsi_4btoul(cdb->length);
8800		break;
8801	}
8802	default:
8803		/*
8804		 * We got a command we don't support.  This shouldn't
8805		 * happen, commands should be filtered out above us.
8806		 */
8807		ctl_set_invalid_opcode(ctsio);
8808		ctl_done((union ctl_io *)ctsio);
8809
8810		return (CTL_RETVAL_COMPLETE);
8811		break; /* NOTREACHED */
8812	}
8813
8814	/*
8815	 * The first check is to make sure we're in bounds, the second
8816	 * check is to catch wrap-around problems.  If the lba + num blocks
8817	 * is less than the lba, then we've wrapped around and the block
8818	 * range is invalid anyway.
8819	 */
8820	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8821	 || ((lba + num_blocks) < lba)) {
8822		ctl_set_lba_out_of_range(ctsio,
8823		    MAX(lba, lun->be_lun->maxlba + 1));
8824		ctl_done((union ctl_io *)ctsio);
8825		return (CTL_RETVAL_COMPLETE);
8826	}
8827
8828	/*
8829	 * According to SBC-3, a transfer length of 0 is not an error.
8830	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8831	 * translates to 256 blocks for those commands.
8832	 */
8833	if (num_blocks == 0) {
8834		ctl_set_success(ctsio);
8835		ctl_done((union ctl_io *)ctsio);
8836		return (CTL_RETVAL_COMPLETE);
8837	}
8838
8839	/* Set FUA and/or DPO if caches are disabled. */
8840	if (isread) {
8841		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8842			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8843	} else {
8844		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8845			flags |= CTL_LLF_FUA;
8846	}
8847
8848	lbalen = (struct ctl_lba_len_flags *)
8849	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8850	lbalen->lba = lba;
8851	lbalen->len = num_blocks;
8852	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8853
8854	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8855	ctsio->kern_rel_offset = 0;
8856
8857	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8858
8859	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8860	return (retval);
8861}
8862
8863static int
8864ctl_cnw_cont(union ctl_io *io)
8865{
8866	struct ctl_lun *lun = CTL_LUN(io);
8867	struct ctl_scsiio *ctsio;
8868	struct ctl_lba_len_flags *lbalen;
8869	int retval;
8870
8871	ctsio = &io->scsiio;
8872	ctsio->io_hdr.status = CTL_STATUS_NONE;
8873	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8874	lbalen = (struct ctl_lba_len_flags *)
8875	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8876	lbalen->flags &= ~CTL_LLF_COMPARE;
8877	lbalen->flags |= CTL_LLF_WRITE;
8878
8879	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8880	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8881	return (retval);
8882}
8883
8884int
8885ctl_cnw(struct ctl_scsiio *ctsio)
8886{
8887	struct ctl_lun *lun = CTL_LUN(ctsio);
8888	struct ctl_lba_len_flags *lbalen;
8889	uint64_t lba;
8890	uint32_t num_blocks;
8891	int flags, retval;
8892
8893	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8894
8895	flags = 0;
8896	switch (ctsio->cdb[0]) {
8897	case COMPARE_AND_WRITE: {
8898		struct scsi_compare_and_write *cdb;
8899
8900		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8901		if (cdb->byte2 & SRW10_FUA)
8902			flags |= CTL_LLF_FUA;
8903		if (cdb->byte2 & SRW10_DPO)
8904			flags |= CTL_LLF_DPO;
8905		lba = scsi_8btou64(cdb->addr);
8906		num_blocks = cdb->length;
8907		break;
8908	}
8909	default:
8910		/*
8911		 * We got a command we don't support.  This shouldn't
8912		 * happen, commands should be filtered out above us.
8913		 */
8914		ctl_set_invalid_opcode(ctsio);
8915		ctl_done((union ctl_io *)ctsio);
8916
8917		return (CTL_RETVAL_COMPLETE);
8918		break; /* NOTREACHED */
8919	}
8920
8921	/*
8922	 * The first check is to make sure we're in bounds, the second
8923	 * check is to catch wrap-around problems.  If the lba + num blocks
8924	 * is less than the lba, then we've wrapped around and the block
8925	 * range is invalid anyway.
8926	 */
8927	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8928	 || ((lba + num_blocks) < lba)) {
8929		ctl_set_lba_out_of_range(ctsio,
8930		    MAX(lba, lun->be_lun->maxlba + 1));
8931		ctl_done((union ctl_io *)ctsio);
8932		return (CTL_RETVAL_COMPLETE);
8933	}
8934
8935	/*
8936	 * According to SBC-3, a transfer length of 0 is not an error.
8937	 */
8938	if (num_blocks == 0) {
8939		ctl_set_success(ctsio);
8940		ctl_done((union ctl_io *)ctsio);
8941		return (CTL_RETVAL_COMPLETE);
8942	}
8943
8944	/* Set FUA if write cache is disabled. */
8945	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8946		flags |= CTL_LLF_FUA;
8947
8948	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8949	ctsio->kern_rel_offset = 0;
8950
8951	/*
8952	 * Set the IO_CONT flag, so that if this I/O gets passed to
8953	 * ctl_data_submit_done(), it'll get passed back to
8954	 * ctl_ctl_cnw_cont() for further processing.
8955	 */
8956	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8957	ctsio->io_cont = ctl_cnw_cont;
8958
8959	lbalen = (struct ctl_lba_len_flags *)
8960	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8961	lbalen->lba = lba;
8962	lbalen->len = num_blocks;
8963	lbalen->flags = CTL_LLF_COMPARE | flags;
8964
8965	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8966	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8967	return (retval);
8968}
8969
8970int
8971ctl_verify(struct ctl_scsiio *ctsio)
8972{
8973	struct ctl_lun *lun = CTL_LUN(ctsio);
8974	struct ctl_lba_len_flags *lbalen;
8975	uint64_t lba;
8976	uint32_t num_blocks;
8977	int bytchk, flags;
8978	int retval;
8979
8980	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8981
8982	bytchk = 0;
8983	flags = CTL_LLF_FUA;
8984	switch (ctsio->cdb[0]) {
8985	case VERIFY_10: {
8986		struct scsi_verify_10 *cdb;
8987
8988		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8989		if (cdb->byte2 & SVFY_BYTCHK)
8990			bytchk = 1;
8991		if (cdb->byte2 & SVFY_DPO)
8992			flags |= CTL_LLF_DPO;
8993		lba = scsi_4btoul(cdb->addr);
8994		num_blocks = scsi_2btoul(cdb->length);
8995		break;
8996	}
8997	case VERIFY_12: {
8998		struct scsi_verify_12 *cdb;
8999
9000		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9001		if (cdb->byte2 & SVFY_BYTCHK)
9002			bytchk = 1;
9003		if (cdb->byte2 & SVFY_DPO)
9004			flags |= CTL_LLF_DPO;
9005		lba = scsi_4btoul(cdb->addr);
9006		num_blocks = scsi_4btoul(cdb->length);
9007		break;
9008	}
9009	case VERIFY_16: {
9010		struct scsi_rw_16 *cdb;
9011
9012		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9013		if (cdb->byte2 & SVFY_BYTCHK)
9014			bytchk = 1;
9015		if (cdb->byte2 & SVFY_DPO)
9016			flags |= CTL_LLF_DPO;
9017		lba = scsi_8btou64(cdb->addr);
9018		num_blocks = scsi_4btoul(cdb->length);
9019		break;
9020	}
9021	default:
9022		/*
9023		 * We got a command we don't support.  This shouldn't
9024		 * happen, commands should be filtered out above us.
9025		 */
9026		ctl_set_invalid_opcode(ctsio);
9027		ctl_done((union ctl_io *)ctsio);
9028		return (CTL_RETVAL_COMPLETE);
9029	}
9030
9031	/*
9032	 * The first check is to make sure we're in bounds, the second
9033	 * check is to catch wrap-around problems.  If the lba + num blocks
9034	 * is less than the lba, then we've wrapped around and the block
9035	 * range is invalid anyway.
9036	 */
9037	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9038	 || ((lba + num_blocks) < lba)) {
9039		ctl_set_lba_out_of_range(ctsio,
9040		    MAX(lba, lun->be_lun->maxlba + 1));
9041		ctl_done((union ctl_io *)ctsio);
9042		return (CTL_RETVAL_COMPLETE);
9043	}
9044
9045	/*
9046	 * According to SBC-3, a transfer length of 0 is not an error.
9047	 */
9048	if (num_blocks == 0) {
9049		ctl_set_success(ctsio);
9050		ctl_done((union ctl_io *)ctsio);
9051		return (CTL_RETVAL_COMPLETE);
9052	}
9053
9054	lbalen = (struct ctl_lba_len_flags *)
9055	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9056	lbalen->lba = lba;
9057	lbalen->len = num_blocks;
9058	if (bytchk) {
9059		lbalen->flags = CTL_LLF_COMPARE | flags;
9060		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9061	} else {
9062		lbalen->flags = CTL_LLF_VERIFY | flags;
9063		ctsio->kern_total_len = 0;
9064	}
9065	ctsio->kern_rel_offset = 0;
9066
9067	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9068	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9069	return (retval);
9070}
9071
9072int
9073ctl_report_luns(struct ctl_scsiio *ctsio)
9074{
9075	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9076	struct ctl_port *port = CTL_PORT(ctsio);
9077	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9078	struct scsi_report_luns *cdb;
9079	struct scsi_report_luns_data *lun_data;
9080	int num_filled, num_luns, num_port_luns, retval;
9081	uint32_t alloc_len, lun_datalen;
9082	uint32_t initidx, targ_lun_id, lun_id;
9083
9084	retval = CTL_RETVAL_COMPLETE;
9085	cdb = (struct scsi_report_luns *)ctsio->cdb;
9086
9087	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9088
9089	num_luns = 0;
9090	num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9091	mtx_lock(&softc->ctl_lock);
9092	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9093		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9094			num_luns++;
9095	}
9096	mtx_unlock(&softc->ctl_lock);
9097
9098	switch (cdb->select_report) {
9099	case RPL_REPORT_DEFAULT:
9100	case RPL_REPORT_ALL:
9101	case RPL_REPORT_NONSUBSID:
9102		break;
9103	case RPL_REPORT_WELLKNOWN:
9104	case RPL_REPORT_ADMIN:
9105	case RPL_REPORT_CONGLOM:
9106		num_luns = 0;
9107		break;
9108	default:
9109		ctl_set_invalid_field(ctsio,
9110				      /*sks_valid*/ 1,
9111				      /*command*/ 1,
9112				      /*field*/ 2,
9113				      /*bit_valid*/ 0,
9114				      /*bit*/ 0);
9115		ctl_done((union ctl_io *)ctsio);
9116		return (retval);
9117		break; /* NOTREACHED */
9118	}
9119
9120	alloc_len = scsi_4btoul(cdb->length);
9121	/*
9122	 * The initiator has to allocate at least 16 bytes for this request,
9123	 * so he can at least get the header and the first LUN.  Otherwise
9124	 * we reject the request (per SPC-3 rev 14, section 6.21).
9125	 */
9126	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9127	    sizeof(struct scsi_report_luns_lundata))) {
9128		ctl_set_invalid_field(ctsio,
9129				      /*sks_valid*/ 1,
9130				      /*command*/ 1,
9131				      /*field*/ 6,
9132				      /*bit_valid*/ 0,
9133				      /*bit*/ 0);
9134		ctl_done((union ctl_io *)ctsio);
9135		return (retval);
9136	}
9137
9138	lun_datalen = sizeof(*lun_data) +
9139		(num_luns * sizeof(struct scsi_report_luns_lundata));
9140
9141	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9142	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9143	ctsio->kern_sg_entries = 0;
9144
9145	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9146
9147	mtx_lock(&softc->ctl_lock);
9148	for (targ_lun_id = 0, num_filled = 0;
9149	    targ_lun_id < num_port_luns && num_filled < num_luns;
9150	    targ_lun_id++) {
9151		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9152		if (lun_id == UINT32_MAX)
9153			continue;
9154		lun = softc->ctl_luns[lun_id];
9155		if (lun == NULL)
9156			continue;
9157
9158		be64enc(lun_data->luns[num_filled++].lundata,
9159		    ctl_encode_lun(targ_lun_id));
9160
9161		/*
9162		 * According to SPC-3, rev 14 section 6.21:
9163		 *
9164		 * "The execution of a REPORT LUNS command to any valid and
9165		 * installed logical unit shall clear the REPORTED LUNS DATA
9166		 * HAS CHANGED unit attention condition for all logical
9167		 * units of that target with respect to the requesting
9168		 * initiator. A valid and installed logical unit is one
9169		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9170		 * INQUIRY data (see 6.4.2)."
9171		 *
9172		 * If request_lun is NULL, the LUN this report luns command
9173		 * was issued to is either disabled or doesn't exist. In that
9174		 * case, we shouldn't clear any pending lun change unit
9175		 * attention.
9176		 */
9177		if (request_lun != NULL) {
9178			mtx_lock(&lun->lun_lock);
9179			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9180			mtx_unlock(&lun->lun_lock);
9181		}
9182	}
9183	mtx_unlock(&softc->ctl_lock);
9184
9185	/*
9186	 * It's quite possible that we've returned fewer LUNs than we allocated
9187	 * space for.  Trim it.
9188	 */
9189	lun_datalen = sizeof(*lun_data) +
9190		(num_filled * sizeof(struct scsi_report_luns_lundata));
9191
9192	if (lun_datalen < alloc_len) {
9193		ctsio->residual = alloc_len - lun_datalen;
9194		ctsio->kern_data_len = lun_datalen;
9195		ctsio->kern_total_len = lun_datalen;
9196	} else {
9197		ctsio->residual = 0;
9198		ctsio->kern_data_len = alloc_len;
9199		ctsio->kern_total_len = alloc_len;
9200	}
9201	ctsio->kern_data_resid = 0;
9202	ctsio->kern_rel_offset = 0;
9203	ctsio->kern_sg_entries = 0;
9204
9205	/*
9206	 * We set this to the actual data length, regardless of how much
9207	 * space we actually have to return results.  If the user looks at
9208	 * this value, he'll know whether or not he allocated enough space
9209	 * and reissue the command if necessary.  We don't support well
9210	 * known logical units, so if the user asks for that, return none.
9211	 */
9212	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9213
9214	/*
9215	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9216	 * this request.
9217	 */
9218	ctl_set_success(ctsio);
9219	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9220	ctsio->be_move_done = ctl_config_move_done;
9221	ctl_datamove((union ctl_io *)ctsio);
9222	return (retval);
9223}
9224
9225int
9226ctl_request_sense(struct ctl_scsiio *ctsio)
9227{
9228	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9229	struct ctl_lun *lun = CTL_LUN(ctsio);
9230	struct scsi_request_sense *cdb;
9231	struct scsi_sense_data *sense_ptr;
9232	uint32_t initidx;
9233	int have_error;
9234	u_int sense_len = SSD_FULL_SIZE;
9235	scsi_sense_data_type sense_format;
9236	ctl_ua_type ua_type;
9237	uint8_t asc = 0, ascq = 0;
9238
9239	cdb = (struct scsi_request_sense *)ctsio->cdb;
9240
9241	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9242
9243	/*
9244	 * Determine which sense format the user wants.
9245	 */
9246	if (cdb->byte2 & SRS_DESC)
9247		sense_format = SSD_TYPE_DESC;
9248	else
9249		sense_format = SSD_TYPE_FIXED;
9250
9251	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9252	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9253	ctsio->kern_sg_entries = 0;
9254
9255	/*
9256	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9257	 * larger than the largest allowed value for the length field in the
9258	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9259	 */
9260	ctsio->residual = 0;
9261	ctsio->kern_data_len = cdb->length;
9262	ctsio->kern_total_len = cdb->length;
9263
9264	ctsio->kern_data_resid = 0;
9265	ctsio->kern_rel_offset = 0;
9266	ctsio->kern_sg_entries = 0;
9267
9268	/*
9269	 * If we don't have a LUN, we don't have any pending sense.
9270	 */
9271	if (lun == NULL ||
9272	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9273	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9274		/* "Logical unit not supported" */
9275		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9276		    /*current_error*/ 1,
9277		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9278		    /*asc*/ 0x25,
9279		    /*ascq*/ 0x00,
9280		    SSD_ELEM_NONE);
9281		goto send;
9282	}
9283
9284	have_error = 0;
9285	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9286	/*
9287	 * Check for pending sense, and then for pending unit attentions.
9288	 * Pending sense gets returned first, then pending unit attentions.
9289	 */
9290	mtx_lock(&lun->lun_lock);
9291#ifdef CTL_WITH_CA
9292	if (ctl_is_set(lun->have_ca, initidx)) {
9293		scsi_sense_data_type stored_format;
9294
9295		/*
9296		 * Check to see which sense format was used for the stored
9297		 * sense data.
9298		 */
9299		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9300
9301		/*
9302		 * If the user requested a different sense format than the
9303		 * one we stored, then we need to convert it to the other
9304		 * format.  If we're going from descriptor to fixed format
9305		 * sense data, we may lose things in translation, depending
9306		 * on what options were used.
9307		 *
9308		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9309		 * for some reason we'll just copy it out as-is.
9310		 */
9311		if ((stored_format == SSD_TYPE_FIXED)
9312		 && (sense_format == SSD_TYPE_DESC))
9313			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9314			    &lun->pending_sense[initidx],
9315			    (struct scsi_sense_data_desc *)sense_ptr);
9316		else if ((stored_format == SSD_TYPE_DESC)
9317		      && (sense_format == SSD_TYPE_FIXED))
9318			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9319			    &lun->pending_sense[initidx],
9320			    (struct scsi_sense_data_fixed *)sense_ptr);
9321		else
9322			memcpy(sense_ptr, &lun->pending_sense[initidx],
9323			       MIN(sizeof(*sense_ptr),
9324			       sizeof(lun->pending_sense[initidx])));
9325
9326		ctl_clear_mask(lun->have_ca, initidx);
9327		have_error = 1;
9328	} else
9329#endif
9330	if (have_error == 0) {
9331		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9332		    sense_format);
9333		if (ua_type != CTL_UA_NONE)
9334			have_error = 1;
9335	}
9336	if (have_error == 0) {
9337		/*
9338		 * Report informational exception if have one and allowed.
9339		 */
9340		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9341			asc = lun->ie_asc;
9342			ascq = lun->ie_ascq;
9343		}
9344		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9345		    /*current_error*/ 1,
9346		    /*sense_key*/ SSD_KEY_NO_SENSE,
9347		    /*asc*/ asc,
9348		    /*ascq*/ ascq,
9349		    SSD_ELEM_NONE);
9350	}
9351	mtx_unlock(&lun->lun_lock);
9352
9353send:
9354	/*
9355	 * We report the SCSI status as OK, since the status of the command
9356	 * itself is OK.  We're reporting sense as parameter data.
9357	 */
9358	ctl_set_success(ctsio);
9359	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9360	ctsio->be_move_done = ctl_config_move_done;
9361	ctl_datamove((union ctl_io *)ctsio);
9362	return (CTL_RETVAL_COMPLETE);
9363}
9364
9365int
9366ctl_tur(struct ctl_scsiio *ctsio)
9367{
9368
9369	CTL_DEBUG_PRINT(("ctl_tur\n"));
9370
9371	ctl_set_success(ctsio);
9372	ctl_done((union ctl_io *)ctsio);
9373
9374	return (CTL_RETVAL_COMPLETE);
9375}
9376
9377/*
9378 * SCSI VPD page 0x00, the Supported VPD Pages page.
9379 */
9380static int
9381ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9382{
9383	struct ctl_lun *lun = CTL_LUN(ctsio);
9384	struct scsi_vpd_supported_pages *pages;
9385	int sup_page_size;
9386	int p;
9387
9388	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9389	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9390	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9391	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9392	ctsio->kern_sg_entries = 0;
9393
9394	if (sup_page_size < alloc_len) {
9395		ctsio->residual = alloc_len - sup_page_size;
9396		ctsio->kern_data_len = sup_page_size;
9397		ctsio->kern_total_len = sup_page_size;
9398	} else {
9399		ctsio->residual = 0;
9400		ctsio->kern_data_len = alloc_len;
9401		ctsio->kern_total_len = alloc_len;
9402	}
9403	ctsio->kern_data_resid = 0;
9404	ctsio->kern_rel_offset = 0;
9405	ctsio->kern_sg_entries = 0;
9406
9407	/*
9408	 * The control device is always connected.  The disk device, on the
9409	 * other hand, may not be online all the time.  Need to change this
9410	 * to figure out whether the disk device is actually online or not.
9411	 */
9412	if (lun != NULL)
9413		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9414				lun->be_lun->lun_type;
9415	else
9416		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9417
9418	p = 0;
9419	/* Supported VPD pages */
9420	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9421	/* Serial Number */
9422	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9423	/* Device Identification */
9424	pages->page_list[p++] = SVPD_DEVICE_ID;
9425	/* Extended INQUIRY Data */
9426	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9427	/* Mode Page Policy */
9428	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9429	/* SCSI Ports */
9430	pages->page_list[p++] = SVPD_SCSI_PORTS;
9431	/* Third-party Copy */
9432	pages->page_list[p++] = SVPD_SCSI_TPC;
9433	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9434		/* Block limits */
9435		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9436		/* Block Device Characteristics */
9437		pages->page_list[p++] = SVPD_BDC;
9438		/* Logical Block Provisioning */
9439		pages->page_list[p++] = SVPD_LBP;
9440	}
9441	pages->length = p;
9442
9443	ctl_set_success(ctsio);
9444	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9445	ctsio->be_move_done = ctl_config_move_done;
9446	ctl_datamove((union ctl_io *)ctsio);
9447	return (CTL_RETVAL_COMPLETE);
9448}
9449
9450/*
9451 * SCSI VPD page 0x80, the Unit Serial Number page.
9452 */
9453static int
9454ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9455{
9456	struct ctl_lun *lun = CTL_LUN(ctsio);
9457	struct scsi_vpd_unit_serial_number *sn_ptr;
9458	int data_len;
9459
9460	data_len = 4 + CTL_SN_LEN;
9461	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9462	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9463	if (data_len < alloc_len) {
9464		ctsio->residual = alloc_len - data_len;
9465		ctsio->kern_data_len = data_len;
9466		ctsio->kern_total_len = data_len;
9467	} else {
9468		ctsio->residual = 0;
9469		ctsio->kern_data_len = alloc_len;
9470		ctsio->kern_total_len = alloc_len;
9471	}
9472	ctsio->kern_data_resid = 0;
9473	ctsio->kern_rel_offset = 0;
9474	ctsio->kern_sg_entries = 0;
9475
9476	/*
9477	 * The control device is always connected.  The disk device, on the
9478	 * other hand, may not be online all the time.  Need to change this
9479	 * to figure out whether the disk device is actually online or not.
9480	 */
9481	if (lun != NULL)
9482		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9483				  lun->be_lun->lun_type;
9484	else
9485		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9486
9487	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9488	sn_ptr->length = CTL_SN_LEN;
9489	/*
9490	 * If we don't have a LUN, we just leave the serial number as
9491	 * all spaces.
9492	 */
9493	if (lun != NULL) {
9494		strncpy((char *)sn_ptr->serial_num,
9495			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9496	} else
9497		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9498
9499	ctl_set_success(ctsio);
9500	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9501	ctsio->be_move_done = ctl_config_move_done;
9502	ctl_datamove((union ctl_io *)ctsio);
9503	return (CTL_RETVAL_COMPLETE);
9504}
9505
9506
9507/*
9508 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9509 */
9510static int
9511ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9512{
9513	struct ctl_lun *lun = CTL_LUN(ctsio);
9514	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9515	int data_len;
9516
9517	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9518	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9519	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9520	ctsio->kern_sg_entries = 0;
9521
9522	if (data_len < alloc_len) {
9523		ctsio->residual = alloc_len - data_len;
9524		ctsio->kern_data_len = data_len;
9525		ctsio->kern_total_len = data_len;
9526	} else {
9527		ctsio->residual = 0;
9528		ctsio->kern_data_len = alloc_len;
9529		ctsio->kern_total_len = alloc_len;
9530	}
9531	ctsio->kern_data_resid = 0;
9532	ctsio->kern_rel_offset = 0;
9533	ctsio->kern_sg_entries = 0;
9534
9535	/*
9536	 * The control device is always connected.  The disk device, on the
9537	 * other hand, may not be online all the time.
9538	 */
9539	if (lun != NULL)
9540		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9541				     lun->be_lun->lun_type;
9542	else
9543		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9544	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9545	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9546	/*
9547	 * We support head of queue, ordered and simple tags.
9548	 */
9549	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9550	/*
9551	 * Volatile cache supported.
9552	 */
9553	eid_ptr->flags3 = SVPD_EID_V_SUP;
9554
9555	/*
9556	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9557	 * attention for a particular IT nexus on all LUNs once we report
9558	 * it to that nexus once.  This bit is required as of SPC-4.
9559	 */
9560	eid_ptr->flags4 = SVPD_EID_LUICLR;
9561
9562	/*
9563	 * We support revert to defaults (RTD) bit in MODE SELECT.
9564	 */
9565	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9566
9567	/*
9568	 * XXX KDM in order to correctly answer this, we would need
9569	 * information from the SIM to determine how much sense data it
9570	 * can send.  So this would really be a path inquiry field, most
9571	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9572	 * but the hardware may or may not be able to support that much.
9573	 * 0 just means that the maximum sense data length is not reported.
9574	 */
9575	eid_ptr->max_sense_length = 0;
9576
9577	ctl_set_success(ctsio);
9578	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9579	ctsio->be_move_done = ctl_config_move_done;
9580	ctl_datamove((union ctl_io *)ctsio);
9581	return (CTL_RETVAL_COMPLETE);
9582}
9583
9584static int
9585ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9586{
9587	struct ctl_lun *lun = CTL_LUN(ctsio);
9588	struct scsi_vpd_mode_page_policy *mpp_ptr;
9589	int data_len;
9590
9591	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9592	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9593
9594	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9595	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9596	ctsio->kern_sg_entries = 0;
9597
9598	if (data_len < alloc_len) {
9599		ctsio->residual = alloc_len - data_len;
9600		ctsio->kern_data_len = data_len;
9601		ctsio->kern_total_len = data_len;
9602	} else {
9603		ctsio->residual = 0;
9604		ctsio->kern_data_len = alloc_len;
9605		ctsio->kern_total_len = alloc_len;
9606	}
9607	ctsio->kern_data_resid = 0;
9608	ctsio->kern_rel_offset = 0;
9609	ctsio->kern_sg_entries = 0;
9610
9611	/*
9612	 * The control device is always connected.  The disk device, on the
9613	 * other hand, may not be online all the time.
9614	 */
9615	if (lun != NULL)
9616		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9617				     lun->be_lun->lun_type;
9618	else
9619		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9620	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9621	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9622	mpp_ptr->descr[0].page_code = 0x3f;
9623	mpp_ptr->descr[0].subpage_code = 0xff;
9624	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9625
9626	ctl_set_success(ctsio);
9627	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9628	ctsio->be_move_done = ctl_config_move_done;
9629	ctl_datamove((union ctl_io *)ctsio);
9630	return (CTL_RETVAL_COMPLETE);
9631}
9632
9633/*
9634 * SCSI VPD page 0x83, the Device Identification page.
9635 */
9636static int
9637ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9638{
9639	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9640	struct ctl_port *port = CTL_PORT(ctsio);
9641	struct ctl_lun *lun = CTL_LUN(ctsio);
9642	struct scsi_vpd_device_id *devid_ptr;
9643	struct scsi_vpd_id_descriptor *desc;
9644	int data_len, g;
9645	uint8_t proto;
9646
9647	data_len = sizeof(struct scsi_vpd_device_id) +
9648	    sizeof(struct scsi_vpd_id_descriptor) +
9649		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9650	    sizeof(struct scsi_vpd_id_descriptor) +
9651		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9652	if (lun && lun->lun_devid)
9653		data_len += lun->lun_devid->len;
9654	if (port && port->port_devid)
9655		data_len += port->port_devid->len;
9656	if (port && port->target_devid)
9657		data_len += port->target_devid->len;
9658
9659	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9660	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9661	ctsio->kern_sg_entries = 0;
9662
9663	if (data_len < alloc_len) {
9664		ctsio->residual = alloc_len - data_len;
9665		ctsio->kern_data_len = data_len;
9666		ctsio->kern_total_len = data_len;
9667	} else {
9668		ctsio->residual = 0;
9669		ctsio->kern_data_len = alloc_len;
9670		ctsio->kern_total_len = alloc_len;
9671	}
9672	ctsio->kern_data_resid = 0;
9673	ctsio->kern_rel_offset = 0;
9674	ctsio->kern_sg_entries = 0;
9675
9676	/*
9677	 * The control device is always connected.  The disk device, on the
9678	 * other hand, may not be online all the time.
9679	 */
9680	if (lun != NULL)
9681		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9682				     lun->be_lun->lun_type;
9683	else
9684		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9685	devid_ptr->page_code = SVPD_DEVICE_ID;
9686	scsi_ulto2b(data_len - 4, devid_ptr->length);
9687
9688	if (port && port->port_type == CTL_PORT_FC)
9689		proto = SCSI_PROTO_FC << 4;
9690	else if (port && port->port_type == CTL_PORT_ISCSI)
9691		proto = SCSI_PROTO_ISCSI << 4;
9692	else
9693		proto = SCSI_PROTO_SPI << 4;
9694	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9695
9696	/*
9697	 * We're using a LUN association here.  i.e., this device ID is a
9698	 * per-LUN identifier.
9699	 */
9700	if (lun && lun->lun_devid) {
9701		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9702		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9703		    lun->lun_devid->len);
9704	}
9705
9706	/*
9707	 * This is for the WWPN which is a port association.
9708	 */
9709	if (port && port->port_devid) {
9710		memcpy(desc, port->port_devid->data, port->port_devid->len);
9711		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9712		    port->port_devid->len);
9713	}
9714
9715	/*
9716	 * This is for the Relative Target Port(type 4h) identifier
9717	 */
9718	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9719	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9720	    SVPD_ID_TYPE_RELTARG;
9721	desc->length = 4;
9722	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9723	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9724	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9725
9726	/*
9727	 * This is for the Target Port Group(type 5h) identifier
9728	 */
9729	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9730	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9731	    SVPD_ID_TYPE_TPORTGRP;
9732	desc->length = 4;
9733	if (softc->is_single ||
9734	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9735		g = 1;
9736	else
9737		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9738	scsi_ulto2b(g, &desc->identifier[2]);
9739	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9740	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9741
9742	/*
9743	 * This is for the Target identifier
9744	 */
9745	if (port && port->target_devid) {
9746		memcpy(desc, port->target_devid->data, port->target_devid->len);
9747	}
9748
9749	ctl_set_success(ctsio);
9750	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9751	ctsio->be_move_done = ctl_config_move_done;
9752	ctl_datamove((union ctl_io *)ctsio);
9753	return (CTL_RETVAL_COMPLETE);
9754}
9755
9756static int
9757ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9758{
9759	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9760	struct ctl_lun *lun = CTL_LUN(ctsio);
9761	struct scsi_vpd_scsi_ports *sp;
9762	struct scsi_vpd_port_designation *pd;
9763	struct scsi_vpd_port_designation_cont *pdc;
9764	struct ctl_port *port;
9765	int data_len, num_target_ports, iid_len, id_len;
9766
9767	num_target_ports = 0;
9768	iid_len = 0;
9769	id_len = 0;
9770	mtx_lock(&softc->ctl_lock);
9771	STAILQ_FOREACH(port, &softc->port_list, links) {
9772		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9773			continue;
9774		if (lun != NULL &&
9775		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9776			continue;
9777		num_target_ports++;
9778		if (port->init_devid)
9779			iid_len += port->init_devid->len;
9780		if (port->port_devid)
9781			id_len += port->port_devid->len;
9782	}
9783	mtx_unlock(&softc->ctl_lock);
9784
9785	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9786	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9787	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9788	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9789	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9790	ctsio->kern_sg_entries = 0;
9791
9792	if (data_len < alloc_len) {
9793		ctsio->residual = alloc_len - data_len;
9794		ctsio->kern_data_len = data_len;
9795		ctsio->kern_total_len = data_len;
9796	} else {
9797		ctsio->residual = 0;
9798		ctsio->kern_data_len = alloc_len;
9799		ctsio->kern_total_len = alloc_len;
9800	}
9801	ctsio->kern_data_resid = 0;
9802	ctsio->kern_rel_offset = 0;
9803	ctsio->kern_sg_entries = 0;
9804
9805	/*
9806	 * The control device is always connected.  The disk device, on the
9807	 * other hand, may not be online all the time.  Need to change this
9808	 * to figure out whether the disk device is actually online or not.
9809	 */
9810	if (lun != NULL)
9811		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9812				  lun->be_lun->lun_type;
9813	else
9814		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9815
9816	sp->page_code = SVPD_SCSI_PORTS;
9817	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9818	    sp->page_length);
9819	pd = &sp->design[0];
9820
9821	mtx_lock(&softc->ctl_lock);
9822	STAILQ_FOREACH(port, &softc->port_list, links) {
9823		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9824			continue;
9825		if (lun != NULL &&
9826		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9827			continue;
9828		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9829		if (port->init_devid) {
9830			iid_len = port->init_devid->len;
9831			memcpy(pd->initiator_transportid,
9832			    port->init_devid->data, port->init_devid->len);
9833		} else
9834			iid_len = 0;
9835		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9836		pdc = (struct scsi_vpd_port_designation_cont *)
9837		    (&pd->initiator_transportid[iid_len]);
9838		if (port->port_devid) {
9839			id_len = port->port_devid->len;
9840			memcpy(pdc->target_port_descriptors,
9841			    port->port_devid->data, port->port_devid->len);
9842		} else
9843			id_len = 0;
9844		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9845		pd = (struct scsi_vpd_port_designation *)
9846		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9847	}
9848	mtx_unlock(&softc->ctl_lock);
9849
9850	ctl_set_success(ctsio);
9851	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9852	ctsio->be_move_done = ctl_config_move_done;
9853	ctl_datamove((union ctl_io *)ctsio);
9854	return (CTL_RETVAL_COMPLETE);
9855}
9856
9857static int
9858ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9859{
9860	struct ctl_lun *lun = CTL_LUN(ctsio);
9861	struct scsi_vpd_block_limits *bl_ptr;
9862	uint64_t ival;
9863
9864	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9865	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9866	ctsio->kern_sg_entries = 0;
9867
9868	if (sizeof(*bl_ptr) < alloc_len) {
9869		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9870		ctsio->kern_data_len = sizeof(*bl_ptr);
9871		ctsio->kern_total_len = sizeof(*bl_ptr);
9872	} else {
9873		ctsio->residual = 0;
9874		ctsio->kern_data_len = alloc_len;
9875		ctsio->kern_total_len = alloc_len;
9876	}
9877	ctsio->kern_data_resid = 0;
9878	ctsio->kern_rel_offset = 0;
9879	ctsio->kern_sg_entries = 0;
9880
9881	/*
9882	 * The control device is always connected.  The disk device, on the
9883	 * other hand, may not be online all the time.  Need to change this
9884	 * to figure out whether the disk device is actually online or not.
9885	 */
9886	if (lun != NULL)
9887		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9888				  lun->be_lun->lun_type;
9889	else
9890		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9891
9892	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9893	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9894	bl_ptr->max_cmp_write_len = 0xff;
9895	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9896	if (lun != NULL) {
9897		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9898		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9899			ival = 0xffffffff;
9900			ctl_get_opt_number(&lun->be_lun->options,
9901			    "unmap_max_lba", &ival);
9902			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9903			ival = 0xffffffff;
9904			ctl_get_opt_number(&lun->be_lun->options,
9905			    "unmap_max_descr", &ival);
9906			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9907			if (lun->be_lun->ublockexp != 0) {
9908				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9909				    bl_ptr->opt_unmap_grain);
9910				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9911				    bl_ptr->unmap_grain_align);
9912			}
9913		}
9914		scsi_ulto4b(lun->be_lun->atomicblock,
9915		    bl_ptr->max_atomic_transfer_length);
9916		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9917		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9918		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9919		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9920		ival = UINT64_MAX;
9921		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9922		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9923	}
9924
9925	ctl_set_success(ctsio);
9926	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9927	ctsio->be_move_done = ctl_config_move_done;
9928	ctl_datamove((union ctl_io *)ctsio);
9929	return (CTL_RETVAL_COMPLETE);
9930}
9931
9932static int
9933ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9934{
9935	struct ctl_lun *lun = CTL_LUN(ctsio);
9936	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9937	const char *value;
9938	u_int i;
9939
9940	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9941	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9942	ctsio->kern_sg_entries = 0;
9943
9944	if (sizeof(*bdc_ptr) < alloc_len) {
9945		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9946		ctsio->kern_data_len = sizeof(*bdc_ptr);
9947		ctsio->kern_total_len = sizeof(*bdc_ptr);
9948	} else {
9949		ctsio->residual = 0;
9950		ctsio->kern_data_len = alloc_len;
9951		ctsio->kern_total_len = alloc_len;
9952	}
9953	ctsio->kern_data_resid = 0;
9954	ctsio->kern_rel_offset = 0;
9955	ctsio->kern_sg_entries = 0;
9956
9957	/*
9958	 * The control device is always connected.  The disk device, on the
9959	 * other hand, may not be online all the time.  Need to change this
9960	 * to figure out whether the disk device is actually online or not.
9961	 */
9962	if (lun != NULL)
9963		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9964				  lun->be_lun->lun_type;
9965	else
9966		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9967	bdc_ptr->page_code = SVPD_BDC;
9968	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9969	if (lun != NULL &&
9970	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9971		i = strtol(value, NULL, 0);
9972	else
9973		i = CTL_DEFAULT_ROTATION_RATE;
9974	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9975	if (lun != NULL &&
9976	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9977		i = strtol(value, NULL, 0);
9978	else
9979		i = 0;
9980	bdc_ptr->wab_wac_ff = (i & 0x0f);
9981	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9982
9983	ctl_set_success(ctsio);
9984	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9985	ctsio->be_move_done = ctl_config_move_done;
9986	ctl_datamove((union ctl_io *)ctsio);
9987	return (CTL_RETVAL_COMPLETE);
9988}
9989
9990static int
9991ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9992{
9993	struct ctl_lun *lun = CTL_LUN(ctsio);
9994	struct scsi_vpd_logical_block_prov *lbp_ptr;
9995	const char *value;
9996
9997	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9998	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9999	ctsio->kern_sg_entries = 0;
10000
10001	if (sizeof(*lbp_ptr) < alloc_len) {
10002		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10003		ctsio->kern_data_len = sizeof(*lbp_ptr);
10004		ctsio->kern_total_len = sizeof(*lbp_ptr);
10005	} else {
10006		ctsio->residual = 0;
10007		ctsio->kern_data_len = alloc_len;
10008		ctsio->kern_total_len = alloc_len;
10009	}
10010	ctsio->kern_data_resid = 0;
10011	ctsio->kern_rel_offset = 0;
10012	ctsio->kern_sg_entries = 0;
10013
10014	/*
10015	 * The control device is always connected.  The disk device, on the
10016	 * other hand, may not be online all the time.  Need to change this
10017	 * to figure out whether the disk device is actually online or not.
10018	 */
10019	if (lun != NULL)
10020		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10021				  lun->be_lun->lun_type;
10022	else
10023		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10024
10025	lbp_ptr->page_code = SVPD_LBP;
10026	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10027	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10028	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10029		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10030		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10031		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10032		if (value != NULL) {
10033			if (strcmp(value, "resource") == 0)
10034				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10035			else if (strcmp(value, "thin") == 0)
10036				lbp_ptr->prov_type = SVPD_LBP_THIN;
10037		} else
10038			lbp_ptr->prov_type = SVPD_LBP_THIN;
10039	}
10040
10041	ctl_set_success(ctsio);
10042	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10043	ctsio->be_move_done = ctl_config_move_done;
10044	ctl_datamove((union ctl_io *)ctsio);
10045	return (CTL_RETVAL_COMPLETE);
10046}
10047
10048/*
10049 * INQUIRY with the EVPD bit set.
10050 */
10051static int
10052ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10053{
10054	struct ctl_lun *lun = CTL_LUN(ctsio);
10055	struct scsi_inquiry *cdb;
10056	int alloc_len, retval;
10057
10058	cdb = (struct scsi_inquiry *)ctsio->cdb;
10059	alloc_len = scsi_2btoul(cdb->length);
10060
10061	switch (cdb->page_code) {
10062	case SVPD_SUPPORTED_PAGES:
10063		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10064		break;
10065	case SVPD_UNIT_SERIAL_NUMBER:
10066		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10067		break;
10068	case SVPD_DEVICE_ID:
10069		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10070		break;
10071	case SVPD_EXTENDED_INQUIRY_DATA:
10072		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10073		break;
10074	case SVPD_MODE_PAGE_POLICY:
10075		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10076		break;
10077	case SVPD_SCSI_PORTS:
10078		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10079		break;
10080	case SVPD_SCSI_TPC:
10081		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10082		break;
10083	case SVPD_BLOCK_LIMITS:
10084		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10085			goto err;
10086		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10087		break;
10088	case SVPD_BDC:
10089		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10090			goto err;
10091		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10092		break;
10093	case SVPD_LBP:
10094		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10095			goto err;
10096		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10097		break;
10098	default:
10099err:
10100		ctl_set_invalid_field(ctsio,
10101				      /*sks_valid*/ 1,
10102				      /*command*/ 1,
10103				      /*field*/ 2,
10104				      /*bit_valid*/ 0,
10105				      /*bit*/ 0);
10106		ctl_done((union ctl_io *)ctsio);
10107		retval = CTL_RETVAL_COMPLETE;
10108		break;
10109	}
10110
10111	return (retval);
10112}
10113
10114/*
10115 * Standard INQUIRY data.
10116 */
10117static int
10118ctl_inquiry_std(struct ctl_scsiio *ctsio)
10119{
10120	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10121	struct ctl_port *port = CTL_PORT(ctsio);
10122	struct ctl_lun *lun = CTL_LUN(ctsio);
10123	struct scsi_inquiry_data *inq_ptr;
10124	struct scsi_inquiry *cdb;
10125	char *val;
10126	uint32_t alloc_len, data_len;
10127	ctl_port_type port_type;
10128
10129	port_type = port->port_type;
10130	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10131		port_type = CTL_PORT_SCSI;
10132
10133	cdb = (struct scsi_inquiry *)ctsio->cdb;
10134	alloc_len = scsi_2btoul(cdb->length);
10135
10136	/*
10137	 * We malloc the full inquiry data size here and fill it
10138	 * in.  If the user only asks for less, we'll give him
10139	 * that much.
10140	 */
10141	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10142	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10143	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10144	ctsio->kern_sg_entries = 0;
10145	ctsio->kern_data_resid = 0;
10146	ctsio->kern_rel_offset = 0;
10147
10148	if (data_len < alloc_len) {
10149		ctsio->residual = alloc_len - data_len;
10150		ctsio->kern_data_len = data_len;
10151		ctsio->kern_total_len = data_len;
10152	} else {
10153		ctsio->residual = 0;
10154		ctsio->kern_data_len = alloc_len;
10155		ctsio->kern_total_len = alloc_len;
10156	}
10157
10158	if (lun != NULL) {
10159		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10160		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10161			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10162			    lun->be_lun->lun_type;
10163		} else {
10164			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10165			    lun->be_lun->lun_type;
10166		}
10167		if (lun->flags & CTL_LUN_REMOVABLE)
10168			inq_ptr->dev_qual2 |= SID_RMB;
10169	} else
10170		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10171
10172	/* RMB in byte 2 is 0 */
10173	inq_ptr->version = SCSI_REV_SPC5;
10174
10175	/*
10176	 * According to SAM-3, even if a device only supports a single
10177	 * level of LUN addressing, it should still set the HISUP bit:
10178	 *
10179	 * 4.9.1 Logical unit numbers overview
10180	 *
10181	 * All logical unit number formats described in this standard are
10182	 * hierarchical in structure even when only a single level in that
10183	 * hierarchy is used. The HISUP bit shall be set to one in the
10184	 * standard INQUIRY data (see SPC-2) when any logical unit number
10185	 * format described in this standard is used.  Non-hierarchical
10186	 * formats are outside the scope of this standard.
10187	 *
10188	 * Therefore we set the HiSup bit here.
10189	 *
10190	 * The response format is 2, per SPC-3.
10191	 */
10192	inq_ptr->response_format = SID_HiSup | 2;
10193
10194	inq_ptr->additional_length = data_len -
10195	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10196	CTL_DEBUG_PRINT(("additional_length = %d\n",
10197			 inq_ptr->additional_length));
10198
10199	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10200	if (port_type == CTL_PORT_SCSI)
10201		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10202	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10203	inq_ptr->flags = SID_CmdQue;
10204	if (port_type == CTL_PORT_SCSI)
10205		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10206
10207	/*
10208	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10209	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10210	 * name and 4 bytes for the revision.
10211	 */
10212	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10213	    "vendor")) == NULL) {
10214		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10215	} else {
10216		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10217		strncpy(inq_ptr->vendor, val,
10218		    min(sizeof(inq_ptr->vendor), strlen(val)));
10219	}
10220	if (lun == NULL) {
10221		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10222		    sizeof(inq_ptr->product));
10223	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10224		switch (lun->be_lun->lun_type) {
10225		case T_DIRECT:
10226			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10227			    sizeof(inq_ptr->product));
10228			break;
10229		case T_PROCESSOR:
10230			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10231			    sizeof(inq_ptr->product));
10232			break;
10233		case T_CDROM:
10234			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10235			    sizeof(inq_ptr->product));
10236			break;
10237		default:
10238			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10239			    sizeof(inq_ptr->product));
10240			break;
10241		}
10242	} else {
10243		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10244		strncpy(inq_ptr->product, val,
10245		    min(sizeof(inq_ptr->product), strlen(val)));
10246	}
10247
10248	/*
10249	 * XXX make this a macro somewhere so it automatically gets
10250	 * incremented when we make changes.
10251	 */
10252	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10253	    "revision")) == NULL) {
10254		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10255	} else {
10256		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10257		strncpy(inq_ptr->revision, val,
10258		    min(sizeof(inq_ptr->revision), strlen(val)));
10259	}
10260
10261	/*
10262	 * For parallel SCSI, we support double transition and single
10263	 * transition clocking.  We also support QAS (Quick Arbitration
10264	 * and Selection) and Information Unit transfers on both the
10265	 * control and array devices.
10266	 */
10267	if (port_type == CTL_PORT_SCSI)
10268		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10269				    SID_SPI_IUS;
10270
10271	/* SAM-6 (no version claimed) */
10272	scsi_ulto2b(0x00C0, inq_ptr->version1);
10273	/* SPC-5 (no version claimed) */
10274	scsi_ulto2b(0x05C0, inq_ptr->version2);
10275	if (port_type == CTL_PORT_FC) {
10276		/* FCP-2 ANSI INCITS.350:2003 */
10277		scsi_ulto2b(0x0917, inq_ptr->version3);
10278	} else if (port_type == CTL_PORT_SCSI) {
10279		/* SPI-4 ANSI INCITS.362:200x */
10280		scsi_ulto2b(0x0B56, inq_ptr->version3);
10281	} else if (port_type == CTL_PORT_ISCSI) {
10282		/* iSCSI (no version claimed) */
10283		scsi_ulto2b(0x0960, inq_ptr->version3);
10284	} else if (port_type == CTL_PORT_SAS) {
10285		/* SAS (no version claimed) */
10286		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10287	}
10288
10289	if (lun == NULL) {
10290		/* SBC-4 (no version claimed) */
10291		scsi_ulto2b(0x0600, inq_ptr->version4);
10292	} else {
10293		switch (lun->be_lun->lun_type) {
10294		case T_DIRECT:
10295			/* SBC-4 (no version claimed) */
10296			scsi_ulto2b(0x0600, inq_ptr->version4);
10297			break;
10298		case T_PROCESSOR:
10299			break;
10300		case T_CDROM:
10301			/* MMC-6 (no version claimed) */
10302			scsi_ulto2b(0x04E0, inq_ptr->version4);
10303			break;
10304		default:
10305			break;
10306		}
10307	}
10308
10309	ctl_set_success(ctsio);
10310	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10311	ctsio->be_move_done = ctl_config_move_done;
10312	ctl_datamove((union ctl_io *)ctsio);
10313	return (CTL_RETVAL_COMPLETE);
10314}
10315
10316int
10317ctl_inquiry(struct ctl_scsiio *ctsio)
10318{
10319	struct scsi_inquiry *cdb;
10320	int retval;
10321
10322	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10323
10324	cdb = (struct scsi_inquiry *)ctsio->cdb;
10325	if (cdb->byte2 & SI_EVPD)
10326		retval = ctl_inquiry_evpd(ctsio);
10327	else if (cdb->page_code == 0)
10328		retval = ctl_inquiry_std(ctsio);
10329	else {
10330		ctl_set_invalid_field(ctsio,
10331				      /*sks_valid*/ 1,
10332				      /*command*/ 1,
10333				      /*field*/ 2,
10334				      /*bit_valid*/ 0,
10335				      /*bit*/ 0);
10336		ctl_done((union ctl_io *)ctsio);
10337		return (CTL_RETVAL_COMPLETE);
10338	}
10339
10340	return (retval);
10341}
10342
10343int
10344ctl_get_config(struct ctl_scsiio *ctsio)
10345{
10346	struct ctl_lun *lun = CTL_LUN(ctsio);
10347	struct scsi_get_config_header *hdr;
10348	struct scsi_get_config_feature *feature;
10349	struct scsi_get_config *cdb;
10350	uint32_t alloc_len, data_len;
10351	int rt, starting;
10352
10353	cdb = (struct scsi_get_config *)ctsio->cdb;
10354	rt = (cdb->rt & SGC_RT_MASK);
10355	starting = scsi_2btoul(cdb->starting_feature);
10356	alloc_len = scsi_2btoul(cdb->length);
10357
10358	data_len = sizeof(struct scsi_get_config_header) +
10359	    sizeof(struct scsi_get_config_feature) + 8 +
10360	    sizeof(struct scsi_get_config_feature) + 8 +
10361	    sizeof(struct scsi_get_config_feature) + 4 +
10362	    sizeof(struct scsi_get_config_feature) + 4 +
10363	    sizeof(struct scsi_get_config_feature) + 8 +
10364	    sizeof(struct scsi_get_config_feature) +
10365	    sizeof(struct scsi_get_config_feature) + 4 +
10366	    sizeof(struct scsi_get_config_feature) + 4 +
10367	    sizeof(struct scsi_get_config_feature) + 4 +
10368	    sizeof(struct scsi_get_config_feature) + 4 +
10369	    sizeof(struct scsi_get_config_feature) + 4 +
10370	    sizeof(struct scsi_get_config_feature) + 4;
10371	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10372	ctsio->kern_sg_entries = 0;
10373	ctsio->kern_data_resid = 0;
10374	ctsio->kern_rel_offset = 0;
10375
10376	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10377	if (lun->flags & CTL_LUN_NO_MEDIA)
10378		scsi_ulto2b(0x0000, hdr->current_profile);
10379	else
10380		scsi_ulto2b(0x0010, hdr->current_profile);
10381	feature = (struct scsi_get_config_feature *)(hdr + 1);
10382
10383	if (starting > 0x003b)
10384		goto done;
10385	if (starting > 0x003a)
10386		goto f3b;
10387	if (starting > 0x002b)
10388		goto f3a;
10389	if (starting > 0x002a)
10390		goto f2b;
10391	if (starting > 0x001f)
10392		goto f2a;
10393	if (starting > 0x001e)
10394		goto f1f;
10395	if (starting > 0x001d)
10396		goto f1e;
10397	if (starting > 0x0010)
10398		goto f1d;
10399	if (starting > 0x0003)
10400		goto f10;
10401	if (starting > 0x0002)
10402		goto f3;
10403	if (starting > 0x0001)
10404		goto f2;
10405	if (starting > 0x0000)
10406		goto f1;
10407
10408	/* Profile List */
10409	scsi_ulto2b(0x0000, feature->feature_code);
10410	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10411	feature->add_length = 8;
10412	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10413	feature->feature_data[2] = 0x00;
10414	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10415	feature->feature_data[6] = 0x01;
10416	feature = (struct scsi_get_config_feature *)
10417	    &feature->feature_data[feature->add_length];
10418
10419f1:	/* Core */
10420	scsi_ulto2b(0x0001, feature->feature_code);
10421	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10422	feature->add_length = 8;
10423	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10424	feature->feature_data[4] = 0x03;
10425	feature = (struct scsi_get_config_feature *)
10426	    &feature->feature_data[feature->add_length];
10427
10428f2:	/* Morphing */
10429	scsi_ulto2b(0x0002, feature->feature_code);
10430	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10431	feature->add_length = 4;
10432	feature->feature_data[0] = 0x02;
10433	feature = (struct scsi_get_config_feature *)
10434	    &feature->feature_data[feature->add_length];
10435
10436f3:	/* Removable Medium */
10437	scsi_ulto2b(0x0003, feature->feature_code);
10438	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10439	feature->add_length = 4;
10440	feature->feature_data[0] = 0x39;
10441	feature = (struct scsi_get_config_feature *)
10442	    &feature->feature_data[feature->add_length];
10443
10444	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10445		goto done;
10446
10447f10:	/* Random Read */
10448	scsi_ulto2b(0x0010, feature->feature_code);
10449	feature->flags = 0x00;
10450	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10451		feature->flags |= SGC_F_CURRENT;
10452	feature->add_length = 8;
10453	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10454	scsi_ulto2b(1, &feature->feature_data[4]);
10455	feature->feature_data[6] = 0x00;
10456	feature = (struct scsi_get_config_feature *)
10457	    &feature->feature_data[feature->add_length];
10458
10459f1d:	/* Multi-Read */
10460	scsi_ulto2b(0x001D, feature->feature_code);
10461	feature->flags = 0x00;
10462	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10463		feature->flags |= SGC_F_CURRENT;
10464	feature->add_length = 0;
10465	feature = (struct scsi_get_config_feature *)
10466	    &feature->feature_data[feature->add_length];
10467
10468f1e:	/* CD Read */
10469	scsi_ulto2b(0x001E, feature->feature_code);
10470	feature->flags = 0x00;
10471	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10472		feature->flags |= SGC_F_CURRENT;
10473	feature->add_length = 4;
10474	feature->feature_data[0] = 0x00;
10475	feature = (struct scsi_get_config_feature *)
10476	    &feature->feature_data[feature->add_length];
10477
10478f1f:	/* DVD Read */
10479	scsi_ulto2b(0x001F, feature->feature_code);
10480	feature->flags = 0x08;
10481	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10482		feature->flags |= SGC_F_CURRENT;
10483	feature->add_length = 4;
10484	feature->feature_data[0] = 0x01;
10485	feature->feature_data[2] = 0x03;
10486	feature = (struct scsi_get_config_feature *)
10487	    &feature->feature_data[feature->add_length];
10488
10489f2a:	/* DVD+RW */
10490	scsi_ulto2b(0x002A, feature->feature_code);
10491	feature->flags = 0x04;
10492	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10493		feature->flags |= SGC_F_CURRENT;
10494	feature->add_length = 4;
10495	feature->feature_data[0] = 0x00;
10496	feature->feature_data[1] = 0x00;
10497	feature = (struct scsi_get_config_feature *)
10498	    &feature->feature_data[feature->add_length];
10499
10500f2b:	/* DVD+R */
10501	scsi_ulto2b(0x002B, feature->feature_code);
10502	feature->flags = 0x00;
10503	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10504		feature->flags |= SGC_F_CURRENT;
10505	feature->add_length = 4;
10506	feature->feature_data[0] = 0x00;
10507	feature = (struct scsi_get_config_feature *)
10508	    &feature->feature_data[feature->add_length];
10509
10510f3a:	/* DVD+RW Dual Layer */
10511	scsi_ulto2b(0x003A, feature->feature_code);
10512	feature->flags = 0x00;
10513	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10514		feature->flags |= SGC_F_CURRENT;
10515	feature->add_length = 4;
10516	feature->feature_data[0] = 0x00;
10517	feature->feature_data[1] = 0x00;
10518	feature = (struct scsi_get_config_feature *)
10519	    &feature->feature_data[feature->add_length];
10520
10521f3b:	/* DVD+R Dual Layer */
10522	scsi_ulto2b(0x003B, feature->feature_code);
10523	feature->flags = 0x00;
10524	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10525		feature->flags |= SGC_F_CURRENT;
10526	feature->add_length = 4;
10527	feature->feature_data[0] = 0x00;
10528	feature = (struct scsi_get_config_feature *)
10529	    &feature->feature_data[feature->add_length];
10530
10531done:
10532	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10533	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10534		feature = (struct scsi_get_config_feature *)(hdr + 1);
10535		if (scsi_2btoul(feature->feature_code) == starting)
10536			feature = (struct scsi_get_config_feature *)
10537			    &feature->feature_data[feature->add_length];
10538		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10539	}
10540	scsi_ulto4b(data_len - 4, hdr->data_length);
10541	if (data_len < alloc_len) {
10542		ctsio->residual = alloc_len - data_len;
10543		ctsio->kern_data_len = data_len;
10544		ctsio->kern_total_len = data_len;
10545	} else {
10546		ctsio->residual = 0;
10547		ctsio->kern_data_len = alloc_len;
10548		ctsio->kern_total_len = alloc_len;
10549	}
10550
10551	ctl_set_success(ctsio);
10552	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10553	ctsio->be_move_done = ctl_config_move_done;
10554	ctl_datamove((union ctl_io *)ctsio);
10555	return (CTL_RETVAL_COMPLETE);
10556}
10557
10558int
10559ctl_get_event_status(struct ctl_scsiio *ctsio)
10560{
10561	struct scsi_get_event_status_header *hdr;
10562	struct scsi_get_event_status *cdb;
10563	uint32_t alloc_len, data_len;
10564	int notif_class;
10565
10566	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10567	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10568		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10569		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10570		ctl_done((union ctl_io *)ctsio);
10571		return (CTL_RETVAL_COMPLETE);
10572	}
10573	notif_class = cdb->notif_class;
10574	alloc_len = scsi_2btoul(cdb->length);
10575
10576	data_len = sizeof(struct scsi_get_event_status_header);
10577	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10578	ctsio->kern_sg_entries = 0;
10579	ctsio->kern_data_resid = 0;
10580	ctsio->kern_rel_offset = 0;
10581
10582	if (data_len < alloc_len) {
10583		ctsio->residual = alloc_len - data_len;
10584		ctsio->kern_data_len = data_len;
10585		ctsio->kern_total_len = data_len;
10586	} else {
10587		ctsio->residual = 0;
10588		ctsio->kern_data_len = alloc_len;
10589		ctsio->kern_total_len = alloc_len;
10590	}
10591
10592	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10593	scsi_ulto2b(0, hdr->descr_length);
10594	hdr->nea_class = SGESN_NEA;
10595	hdr->supported_class = 0;
10596
10597	ctl_set_success(ctsio);
10598	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10599	ctsio->be_move_done = ctl_config_move_done;
10600	ctl_datamove((union ctl_io *)ctsio);
10601	return (CTL_RETVAL_COMPLETE);
10602}
10603
10604int
10605ctl_mechanism_status(struct ctl_scsiio *ctsio)
10606{
10607	struct scsi_mechanism_status_header *hdr;
10608	struct scsi_mechanism_status *cdb;
10609	uint32_t alloc_len, data_len;
10610
10611	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10612	alloc_len = scsi_2btoul(cdb->length);
10613
10614	data_len = sizeof(struct scsi_mechanism_status_header);
10615	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10616	ctsio->kern_sg_entries = 0;
10617	ctsio->kern_data_resid = 0;
10618	ctsio->kern_rel_offset = 0;
10619
10620	if (data_len < alloc_len) {
10621		ctsio->residual = alloc_len - data_len;
10622		ctsio->kern_data_len = data_len;
10623		ctsio->kern_total_len = data_len;
10624	} else {
10625		ctsio->residual = 0;
10626		ctsio->kern_data_len = alloc_len;
10627		ctsio->kern_total_len = alloc_len;
10628	}
10629
10630	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10631	hdr->state1 = 0x00;
10632	hdr->state2 = 0xe0;
10633	scsi_ulto3b(0, hdr->lba);
10634	hdr->slots_num = 0;
10635	scsi_ulto2b(0, hdr->slots_length);
10636
10637	ctl_set_success(ctsio);
10638	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10639	ctsio->be_move_done = ctl_config_move_done;
10640	ctl_datamove((union ctl_io *)ctsio);
10641	return (CTL_RETVAL_COMPLETE);
10642}
10643
10644static void
10645ctl_ultomsf(uint32_t lba, uint8_t *buf)
10646{
10647
10648	lba += 150;
10649	buf[0] = 0;
10650	buf[1] = bin2bcd((lba / 75) / 60);
10651	buf[2] = bin2bcd((lba / 75) % 60);
10652	buf[3] = bin2bcd(lba % 75);
10653}
10654
10655int
10656ctl_read_toc(struct ctl_scsiio *ctsio)
10657{
10658	struct ctl_lun *lun = CTL_LUN(ctsio);
10659	struct scsi_read_toc_hdr *hdr;
10660	struct scsi_read_toc_type01_descr *descr;
10661	struct scsi_read_toc *cdb;
10662	uint32_t alloc_len, data_len;
10663	int format, msf;
10664
10665	cdb = (struct scsi_read_toc *)ctsio->cdb;
10666	msf = (cdb->byte2 & CD_MSF) != 0;
10667	format = cdb->format;
10668	alloc_len = scsi_2btoul(cdb->data_len);
10669
10670	data_len = sizeof(struct scsi_read_toc_hdr);
10671	if (format == 0)
10672		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10673	else
10674		data_len += sizeof(struct scsi_read_toc_type01_descr);
10675	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10676	ctsio->kern_sg_entries = 0;
10677	ctsio->kern_data_resid = 0;
10678	ctsio->kern_rel_offset = 0;
10679
10680	if (data_len < alloc_len) {
10681		ctsio->residual = alloc_len - data_len;
10682		ctsio->kern_data_len = data_len;
10683		ctsio->kern_total_len = data_len;
10684	} else {
10685		ctsio->residual = 0;
10686		ctsio->kern_data_len = alloc_len;
10687		ctsio->kern_total_len = alloc_len;
10688	}
10689
10690	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10691	if (format == 0) {
10692		scsi_ulto2b(0x12, hdr->data_length);
10693		hdr->first = 1;
10694		hdr->last = 1;
10695		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10696		descr->addr_ctl = 0x14;
10697		descr->track_number = 1;
10698		if (msf)
10699			ctl_ultomsf(0, descr->track_start);
10700		else
10701			scsi_ulto4b(0, descr->track_start);
10702		descr++;
10703		descr->addr_ctl = 0x14;
10704		descr->track_number = 0xaa;
10705		if (msf)
10706			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10707		else
10708			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10709	} else {
10710		scsi_ulto2b(0x0a, hdr->data_length);
10711		hdr->first = 1;
10712		hdr->last = 1;
10713		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10714		descr->addr_ctl = 0x14;
10715		descr->track_number = 1;
10716		if (msf)
10717			ctl_ultomsf(0, descr->track_start);
10718		else
10719			scsi_ulto4b(0, descr->track_start);
10720	}
10721
10722	ctl_set_success(ctsio);
10723	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10724	ctsio->be_move_done = ctl_config_move_done;
10725	ctl_datamove((union ctl_io *)ctsio);
10726	return (CTL_RETVAL_COMPLETE);
10727}
10728
10729/*
10730 * For known CDB types, parse the LBA and length.
10731 */
10732static int
10733ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10734{
10735	if (io->io_hdr.io_type != CTL_IO_SCSI)
10736		return (1);
10737
10738	switch (io->scsiio.cdb[0]) {
10739	case COMPARE_AND_WRITE: {
10740		struct scsi_compare_and_write *cdb;
10741
10742		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10743
10744		*lba = scsi_8btou64(cdb->addr);
10745		*len = cdb->length;
10746		break;
10747	}
10748	case READ_6:
10749	case WRITE_6: {
10750		struct scsi_rw_6 *cdb;
10751
10752		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10753
10754		*lba = scsi_3btoul(cdb->addr);
10755		/* only 5 bits are valid in the most significant address byte */
10756		*lba &= 0x1fffff;
10757		*len = cdb->length;
10758		break;
10759	}
10760	case READ_10:
10761	case WRITE_10: {
10762		struct scsi_rw_10 *cdb;
10763
10764		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10765
10766		*lba = scsi_4btoul(cdb->addr);
10767		*len = scsi_2btoul(cdb->length);
10768		break;
10769	}
10770	case WRITE_VERIFY_10: {
10771		struct scsi_write_verify_10 *cdb;
10772
10773		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10774
10775		*lba = scsi_4btoul(cdb->addr);
10776		*len = scsi_2btoul(cdb->length);
10777		break;
10778	}
10779	case READ_12:
10780	case WRITE_12: {
10781		struct scsi_rw_12 *cdb;
10782
10783		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10784
10785		*lba = scsi_4btoul(cdb->addr);
10786		*len = scsi_4btoul(cdb->length);
10787		break;
10788	}
10789	case WRITE_VERIFY_12: {
10790		struct scsi_write_verify_12 *cdb;
10791
10792		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10793
10794		*lba = scsi_4btoul(cdb->addr);
10795		*len = scsi_4btoul(cdb->length);
10796		break;
10797	}
10798	case READ_16:
10799	case WRITE_16: {
10800		struct scsi_rw_16 *cdb;
10801
10802		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10803
10804		*lba = scsi_8btou64(cdb->addr);
10805		*len = scsi_4btoul(cdb->length);
10806		break;
10807	}
10808	case WRITE_ATOMIC_16: {
10809		struct scsi_write_atomic_16 *cdb;
10810
10811		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10812
10813		*lba = scsi_8btou64(cdb->addr);
10814		*len = scsi_2btoul(cdb->length);
10815		break;
10816	}
10817	case WRITE_VERIFY_16: {
10818		struct scsi_write_verify_16 *cdb;
10819
10820		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10821
10822		*lba = scsi_8btou64(cdb->addr);
10823		*len = scsi_4btoul(cdb->length);
10824		break;
10825	}
10826	case WRITE_SAME_10: {
10827		struct scsi_write_same_10 *cdb;
10828
10829		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10830
10831		*lba = scsi_4btoul(cdb->addr);
10832		*len = scsi_2btoul(cdb->length);
10833		break;
10834	}
10835	case WRITE_SAME_16: {
10836		struct scsi_write_same_16 *cdb;
10837
10838		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10839
10840		*lba = scsi_8btou64(cdb->addr);
10841		*len = scsi_4btoul(cdb->length);
10842		break;
10843	}
10844	case VERIFY_10: {
10845		struct scsi_verify_10 *cdb;
10846
10847		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10848
10849		*lba = scsi_4btoul(cdb->addr);
10850		*len = scsi_2btoul(cdb->length);
10851		break;
10852	}
10853	case VERIFY_12: {
10854		struct scsi_verify_12 *cdb;
10855
10856		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10857
10858		*lba = scsi_4btoul(cdb->addr);
10859		*len = scsi_4btoul(cdb->length);
10860		break;
10861	}
10862	case VERIFY_16: {
10863		struct scsi_verify_16 *cdb;
10864
10865		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10866
10867		*lba = scsi_8btou64(cdb->addr);
10868		*len = scsi_4btoul(cdb->length);
10869		break;
10870	}
10871	case UNMAP: {
10872		*lba = 0;
10873		*len = UINT64_MAX;
10874		break;
10875	}
10876	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10877		struct scsi_get_lba_status *cdb;
10878
10879		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10880		*lba = scsi_8btou64(cdb->addr);
10881		*len = UINT32_MAX;
10882		break;
10883	}
10884	default:
10885		return (1);
10886		break; /* NOTREACHED */
10887	}
10888
10889	return (0);
10890}
10891
10892static ctl_action
10893ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10894    bool seq)
10895{
10896	uint64_t endlba1, endlba2;
10897
10898	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10899	endlba2 = lba2 + len2 - 1;
10900
10901	if ((endlba1 < lba2) || (endlba2 < lba1))
10902		return (CTL_ACTION_PASS);
10903	else
10904		return (CTL_ACTION_BLOCK);
10905}
10906
10907static int
10908ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10909{
10910	struct ctl_ptr_len_flags *ptrlen;
10911	struct scsi_unmap_desc *buf, *end, *range;
10912	uint64_t lba;
10913	uint32_t len;
10914
10915	/* If not UNMAP -- go other way. */
10916	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10917	    io->scsiio.cdb[0] != UNMAP)
10918		return (CTL_ACTION_ERROR);
10919
10920	/* If UNMAP without data -- block and wait for data. */
10921	ptrlen = (struct ctl_ptr_len_flags *)
10922	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10923	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10924	    ptrlen->ptr == NULL)
10925		return (CTL_ACTION_BLOCK);
10926
10927	/* UNMAP with data -- check for collision. */
10928	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10929	end = buf + ptrlen->len / sizeof(*buf);
10930	for (range = buf; range < end; range++) {
10931		lba = scsi_8btou64(range->lba);
10932		len = scsi_4btoul(range->length);
10933		if ((lba < lba2 + len2) && (lba + len > lba2))
10934			return (CTL_ACTION_BLOCK);
10935	}
10936	return (CTL_ACTION_PASS);
10937}
10938
10939static ctl_action
10940ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10941{
10942	uint64_t lba1, lba2;
10943	uint64_t len1, len2;
10944	int retval;
10945
10946	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10947		return (CTL_ACTION_ERROR);
10948
10949	retval = ctl_extent_check_unmap(io1, lba2, len2);
10950	if (retval != CTL_ACTION_ERROR)
10951		return (retval);
10952
10953	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10954		return (CTL_ACTION_ERROR);
10955
10956	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10957		seq = FALSE;
10958	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10959}
10960
10961static ctl_action
10962ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10963{
10964	uint64_t lba1, lba2;
10965	uint64_t len1, len2;
10966
10967	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10968		return (CTL_ACTION_PASS);
10969	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10970		return (CTL_ACTION_ERROR);
10971	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10972		return (CTL_ACTION_ERROR);
10973
10974	if (lba1 + len1 == lba2)
10975		return (CTL_ACTION_BLOCK);
10976	return (CTL_ACTION_PASS);
10977}
10978
10979static ctl_action
10980ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10981    union ctl_io *ooa_io)
10982{
10983	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10984	const ctl_serialize_action *serialize_row;
10985
10986	/*
10987	 * The initiator attempted multiple untagged commands at the same
10988	 * time.  Can't do that.
10989	 */
10990	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10991	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10992	 && ((pending_io->io_hdr.nexus.targ_port ==
10993	      ooa_io->io_hdr.nexus.targ_port)
10994	  && (pending_io->io_hdr.nexus.initid ==
10995	      ooa_io->io_hdr.nexus.initid))
10996	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10997	      CTL_FLAG_STATUS_SENT)) == 0))
10998		return (CTL_ACTION_OVERLAP);
10999
11000	/*
11001	 * The initiator attempted to send multiple tagged commands with
11002	 * the same ID.  (It's fine if different initiators have the same
11003	 * tag ID.)
11004	 *
11005	 * Even if all of those conditions are true, we don't kill the I/O
11006	 * if the command ahead of us has been aborted.  We won't end up
11007	 * sending it to the FETD, and it's perfectly legal to resend a
11008	 * command with the same tag number as long as the previous
11009	 * instance of this tag number has been aborted somehow.
11010	 */
11011	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11012	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11013	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11014	 && ((pending_io->io_hdr.nexus.targ_port ==
11015	      ooa_io->io_hdr.nexus.targ_port)
11016	  && (pending_io->io_hdr.nexus.initid ==
11017	      ooa_io->io_hdr.nexus.initid))
11018	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11019	      CTL_FLAG_STATUS_SENT)) == 0))
11020		return (CTL_ACTION_OVERLAP_TAG);
11021
11022	/*
11023	 * If we get a head of queue tag, SAM-3 says that we should
11024	 * immediately execute it.
11025	 *
11026	 * What happens if this command would normally block for some other
11027	 * reason?  e.g. a request sense with a head of queue tag
11028	 * immediately after a write.  Normally that would block, but this
11029	 * will result in its getting executed immediately...
11030	 *
11031	 * We currently return "pass" instead of "skip", so we'll end up
11032	 * going through the rest of the queue to check for overlapped tags.
11033	 *
11034	 * XXX KDM check for other types of blockage first??
11035	 */
11036	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11037		return (CTL_ACTION_PASS);
11038
11039	/*
11040	 * Ordered tags have to block until all items ahead of them
11041	 * have completed.  If we get called with an ordered tag, we always
11042	 * block, if something else is ahead of us in the queue.
11043	 */
11044	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11045		return (CTL_ACTION_BLOCK);
11046
11047	/*
11048	 * Simple tags get blocked until all head of queue and ordered tags
11049	 * ahead of them have completed.  I'm lumping untagged commands in
11050	 * with simple tags here.  XXX KDM is that the right thing to do?
11051	 */
11052	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11053	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11054	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11055	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11056		return (CTL_ACTION_BLOCK);
11057
11058	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11059	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11060	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11061	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11062	     pending_io->scsiio.cdb[1], pending_io));
11063	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11064	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11065		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11066	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11067	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11068	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11069	     ooa_io->scsiio.cdb[1], ooa_io));
11070
11071	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11072
11073	switch (serialize_row[pending_entry->seridx]) {
11074	case CTL_SER_BLOCK:
11075		return (CTL_ACTION_BLOCK);
11076	case CTL_SER_EXTENT:
11077		return (ctl_extent_check(ooa_io, pending_io,
11078		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11079	case CTL_SER_EXTENTOPT:
11080		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11081		    SCP_QUEUE_ALG_UNRESTRICTED)
11082			return (ctl_extent_check(ooa_io, pending_io,
11083			    (lun->be_lun &&
11084			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11085		return (CTL_ACTION_PASS);
11086	case CTL_SER_EXTENTSEQ:
11087		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11088			return (ctl_extent_check_seq(ooa_io, pending_io));
11089		return (CTL_ACTION_PASS);
11090	case CTL_SER_PASS:
11091		return (CTL_ACTION_PASS);
11092	case CTL_SER_BLOCKOPT:
11093		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11094		    SCP_QUEUE_ALG_UNRESTRICTED)
11095			return (CTL_ACTION_BLOCK);
11096		return (CTL_ACTION_PASS);
11097	case CTL_SER_SKIP:
11098		return (CTL_ACTION_SKIP);
11099	default:
11100		panic("%s: Invalid serialization value %d for %d => %d",
11101		    __func__, serialize_row[pending_entry->seridx],
11102		    pending_entry->seridx, ooa_entry->seridx);
11103	}
11104
11105	return (CTL_ACTION_ERROR);
11106}
11107
11108/*
11109 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11110 * Assumptions:
11111 * - pending_io is generally either incoming, or on the blocked queue
11112 * - starting I/O is the I/O we want to start the check with.
11113 */
11114static ctl_action
11115ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11116	      union ctl_io *starting_io)
11117{
11118	union ctl_io *ooa_io;
11119	ctl_action action;
11120
11121	mtx_assert(&lun->lun_lock, MA_OWNED);
11122
11123	/*
11124	 * Run back along the OOA queue, starting with the current
11125	 * blocked I/O and going through every I/O before it on the
11126	 * queue.  If starting_io is NULL, we'll just end up returning
11127	 * CTL_ACTION_PASS.
11128	 */
11129	for (ooa_io = starting_io; ooa_io != NULL;
11130	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11131	     ooa_links)){
11132
11133		/*
11134		 * This routine just checks to see whether
11135		 * cur_blocked is blocked by ooa_io, which is ahead
11136		 * of it in the queue.  It doesn't queue/dequeue
11137		 * cur_blocked.
11138		 */
11139		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11140		switch (action) {
11141		case CTL_ACTION_BLOCK:
11142		case CTL_ACTION_OVERLAP:
11143		case CTL_ACTION_OVERLAP_TAG:
11144		case CTL_ACTION_SKIP:
11145		case CTL_ACTION_ERROR:
11146			return (action);
11147			break; /* NOTREACHED */
11148		case CTL_ACTION_PASS:
11149			break;
11150		default:
11151			panic("%s: Invalid action %d\n", __func__, action);
11152		}
11153	}
11154
11155	return (CTL_ACTION_PASS);
11156}
11157
11158/*
11159 * Assumptions:
11160 * - An I/O has just completed, and has been removed from the per-LUN OOA
11161 *   queue, so some items on the blocked queue may now be unblocked.
11162 */
11163static int
11164ctl_check_blocked(struct ctl_lun *lun)
11165{
11166	struct ctl_softc *softc = lun->ctl_softc;
11167	union ctl_io *cur_blocked, *next_blocked;
11168
11169	mtx_assert(&lun->lun_lock, MA_OWNED);
11170
11171	/*
11172	 * Run forward from the head of the blocked queue, checking each
11173	 * entry against the I/Os prior to it on the OOA queue to see if
11174	 * there is still any blockage.
11175	 *
11176	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11177	 * with our removing a variable on it while it is traversing the
11178	 * list.
11179	 */
11180	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11181	     cur_blocked != NULL; cur_blocked = next_blocked) {
11182		union ctl_io *prev_ooa;
11183		ctl_action action;
11184
11185		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11186							  blocked_links);
11187
11188		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11189						      ctl_ooaq, ooa_links);
11190
11191		/*
11192		 * If cur_blocked happens to be the first item in the OOA
11193		 * queue now, prev_ooa will be NULL, and the action
11194		 * returned will just be CTL_ACTION_PASS.
11195		 */
11196		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11197
11198		switch (action) {
11199		case CTL_ACTION_BLOCK:
11200			/* Nothing to do here, still blocked */
11201			break;
11202		case CTL_ACTION_OVERLAP:
11203		case CTL_ACTION_OVERLAP_TAG:
11204			/*
11205			 * This shouldn't happen!  In theory we've already
11206			 * checked this command for overlap...
11207			 */
11208			break;
11209		case CTL_ACTION_PASS:
11210		case CTL_ACTION_SKIP: {
11211			const struct ctl_cmd_entry *entry;
11212
11213			/*
11214			 * The skip case shouldn't happen, this transaction
11215			 * should have never made it onto the blocked queue.
11216			 */
11217			/*
11218			 * This I/O is no longer blocked, we can remove it
11219			 * from the blocked queue.  Since this is a TAILQ
11220			 * (doubly linked list), we can do O(1) removals
11221			 * from any place on the list.
11222			 */
11223			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11224				     blocked_links);
11225			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11226
11227			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11228			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11229				/*
11230				 * Need to send IO back to original side to
11231				 * run
11232				 */
11233				union ctl_ha_msg msg_info;
11234
11235				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11236				msg_info.hdr.original_sc =
11237					cur_blocked->io_hdr.original_sc;
11238				msg_info.hdr.serializing_sc = cur_blocked;
11239				msg_info.hdr.msg_type = CTL_MSG_R2R;
11240				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11241				    sizeof(msg_info.hdr), M_NOWAIT);
11242				break;
11243			}
11244			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11245
11246			/*
11247			 * Check this I/O for LUN state changes that may
11248			 * have happened while this command was blocked.
11249			 * The LUN state may have been changed by a command
11250			 * ahead of us in the queue, so we need to re-check
11251			 * for any states that can be caused by SCSI
11252			 * commands.
11253			 */
11254			if (ctl_scsiio_lun_check(lun, entry,
11255						 &cur_blocked->scsiio) == 0) {
11256				cur_blocked->io_hdr.flags |=
11257				                      CTL_FLAG_IS_WAS_ON_RTR;
11258				ctl_enqueue_rtr(cur_blocked);
11259			} else
11260				ctl_done(cur_blocked);
11261			break;
11262		}
11263		default:
11264			/*
11265			 * This probably shouldn't happen -- we shouldn't
11266			 * get CTL_ACTION_ERROR, or anything else.
11267			 */
11268			break;
11269		}
11270	}
11271
11272	return (CTL_RETVAL_COMPLETE);
11273}
11274
11275/*
11276 * This routine (with one exception) checks LUN flags that can be set by
11277 * commands ahead of us in the OOA queue.  These flags have to be checked
11278 * when a command initially comes in, and when we pull a command off the
11279 * blocked queue and are preparing to execute it.  The reason we have to
11280 * check these flags for commands on the blocked queue is that the LUN
11281 * state may have been changed by a command ahead of us while we're on the
11282 * blocked queue.
11283 *
11284 * Ordering is somewhat important with these checks, so please pay
11285 * careful attention to the placement of any new checks.
11286 */
11287static int
11288ctl_scsiio_lun_check(struct ctl_lun *lun,
11289    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11290{
11291	struct ctl_softc *softc = lun->ctl_softc;
11292	int retval;
11293	uint32_t residx;
11294
11295	retval = 0;
11296
11297	mtx_assert(&lun->lun_lock, MA_OWNED);
11298
11299	/*
11300	 * If this shelf is a secondary shelf controller, we may have to
11301	 * reject some commands disallowed by HA mode and link state.
11302	 */
11303	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11304		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11305		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11306			ctl_set_lun_unavail(ctsio);
11307			retval = 1;
11308			goto bailout;
11309		}
11310		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11311		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11312			ctl_set_lun_transit(ctsio);
11313			retval = 1;
11314			goto bailout;
11315		}
11316		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11317		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11318			ctl_set_lun_standby(ctsio);
11319			retval = 1;
11320			goto bailout;
11321		}
11322
11323		/* The rest of checks are only done on executing side */
11324		if (softc->ha_mode == CTL_HA_MODE_XFER)
11325			goto bailout;
11326	}
11327
11328	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11329		if (lun->be_lun &&
11330		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11331			ctl_set_hw_write_protected(ctsio);
11332			retval = 1;
11333			goto bailout;
11334		}
11335		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11336			ctl_set_sense(ctsio, /*current_error*/ 1,
11337			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11338			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11339			retval = 1;
11340			goto bailout;
11341		}
11342	}
11343
11344	/*
11345	 * Check for a reservation conflict.  If this command isn't allowed
11346	 * even on reserved LUNs, and if this initiator isn't the one who
11347	 * reserved us, reject the command with a reservation conflict.
11348	 */
11349	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11350	if ((lun->flags & CTL_LUN_RESERVED)
11351	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11352		if (lun->res_idx != residx) {
11353			ctl_set_reservation_conflict(ctsio);
11354			retval = 1;
11355			goto bailout;
11356		}
11357	}
11358
11359	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11360	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11361		/* No reservation or command is allowed. */;
11362	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11363	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11364	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11365	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11366		/* The command is allowed for Write Exclusive resv. */;
11367	} else {
11368		/*
11369		 * if we aren't registered or it's a res holder type
11370		 * reservation and this isn't the res holder then set a
11371		 * conflict.
11372		 */
11373		if (ctl_get_prkey(lun, residx) == 0 ||
11374		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11375			ctl_set_reservation_conflict(ctsio);
11376			retval = 1;
11377			goto bailout;
11378		}
11379	}
11380
11381	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11382		if (lun->flags & CTL_LUN_EJECTED)
11383			ctl_set_lun_ejected(ctsio);
11384		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11385			if (lun->flags & CTL_LUN_REMOVABLE)
11386				ctl_set_lun_no_media(ctsio);
11387			else
11388				ctl_set_lun_int_reqd(ctsio);
11389		} else if (lun->flags & CTL_LUN_STOPPED)
11390			ctl_set_lun_stopped(ctsio);
11391		else
11392			goto bailout;
11393		retval = 1;
11394		goto bailout;
11395	}
11396
11397bailout:
11398	return (retval);
11399}
11400
11401static void
11402ctl_failover_io(union ctl_io *io, int have_lock)
11403{
11404	ctl_set_busy(&io->scsiio);
11405	ctl_done(io);
11406}
11407
11408static void
11409ctl_failover_lun(union ctl_io *rio)
11410{
11411	struct ctl_softc *softc = CTL_SOFTC(rio);
11412	struct ctl_lun *lun;
11413	struct ctl_io_hdr *io, *next_io;
11414	uint32_t targ_lun;
11415
11416	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11417	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11418
11419	/* Find and lock the LUN. */
11420	mtx_lock(&softc->ctl_lock);
11421	if (targ_lun > CTL_MAX_LUNS ||
11422	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11423		mtx_unlock(&softc->ctl_lock);
11424		return;
11425	}
11426	mtx_lock(&lun->lun_lock);
11427	mtx_unlock(&softc->ctl_lock);
11428	if (lun->flags & CTL_LUN_DISABLED) {
11429		mtx_unlock(&lun->lun_lock);
11430		return;
11431	}
11432
11433	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11434		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11435			/* We are master */
11436			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11437				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11438					io->flags |= CTL_FLAG_ABORT;
11439					io->flags |= CTL_FLAG_FAILOVER;
11440				} else { /* This can be only due to DATAMOVE */
11441					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11442					io->flags &= ~CTL_FLAG_DMA_INPROG;
11443					io->flags |= CTL_FLAG_IO_ACTIVE;
11444					io->port_status = 31340;
11445					ctl_enqueue_isc((union ctl_io *)io);
11446				}
11447			}
11448			/* We are slave */
11449			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11450				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11451				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11452					io->flags |= CTL_FLAG_FAILOVER;
11453				} else {
11454					ctl_set_busy(&((union ctl_io *)io)->
11455					    scsiio);
11456					ctl_done((union ctl_io *)io);
11457				}
11458			}
11459		}
11460	} else { /* SERIALIZE modes */
11461		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11462		    next_io) {
11463			/* We are master */
11464			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11465				TAILQ_REMOVE(&lun->blocked_queue, io,
11466				    blocked_links);
11467				io->flags &= ~CTL_FLAG_BLOCKED;
11468				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11469				ctl_free_io((union ctl_io *)io);
11470			}
11471		}
11472		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11473			/* We are master */
11474			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11475				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11476				ctl_free_io((union ctl_io *)io);
11477			}
11478			/* We are slave */
11479			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11480				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11481				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11482					ctl_set_busy(&((union ctl_io *)io)->
11483					    scsiio);
11484					ctl_done((union ctl_io *)io);
11485				}
11486			}
11487		}
11488		ctl_check_blocked(lun);
11489	}
11490	mtx_unlock(&lun->lun_lock);
11491}
11492
11493static int
11494ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11495{
11496	struct ctl_lun *lun;
11497	const struct ctl_cmd_entry *entry;
11498	uint32_t initidx, targ_lun;
11499	int retval = 0;
11500
11501	lun = NULL;
11502	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11503	if (targ_lun < CTL_MAX_LUNS)
11504		lun = softc->ctl_luns[targ_lun];
11505	if (lun) {
11506		/*
11507		 * If the LUN is invalid, pretend that it doesn't exist.
11508		 * It will go away as soon as all pending I/O has been
11509		 * completed.
11510		 */
11511		mtx_lock(&lun->lun_lock);
11512		if (lun->flags & CTL_LUN_DISABLED) {
11513			mtx_unlock(&lun->lun_lock);
11514			lun = NULL;
11515		}
11516	}
11517	CTL_LUN(ctsio) = lun;
11518	if (lun) {
11519		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11520
11521		/*
11522		 * Every I/O goes into the OOA queue for a particular LUN,
11523		 * and stays there until completion.
11524		 */
11525#ifdef CTL_TIME_IO
11526		if (TAILQ_EMPTY(&lun->ooa_queue))
11527			lun->idle_time += getsbinuptime() - lun->last_busy;
11528#endif
11529		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11530	}
11531
11532	/* Get command entry and return error if it is unsuppotyed. */
11533	entry = ctl_validate_command(ctsio);
11534	if (entry == NULL) {
11535		if (lun)
11536			mtx_unlock(&lun->lun_lock);
11537		return (retval);
11538	}
11539
11540	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11541	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11542
11543	/*
11544	 * Check to see whether we can send this command to LUNs that don't
11545	 * exist.  This should pretty much only be the case for inquiry
11546	 * and request sense.  Further checks, below, really require having
11547	 * a LUN, so we can't really check the command anymore.  Just put
11548	 * it on the rtr queue.
11549	 */
11550	if (lun == NULL) {
11551		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11552			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11553			ctl_enqueue_rtr((union ctl_io *)ctsio);
11554			return (retval);
11555		}
11556
11557		ctl_set_unsupported_lun(ctsio);
11558		ctl_done((union ctl_io *)ctsio);
11559		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11560		return (retval);
11561	} else {
11562		/*
11563		 * Make sure we support this particular command on this LUN.
11564		 * e.g., we don't support writes to the control LUN.
11565		 */
11566		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11567			mtx_unlock(&lun->lun_lock);
11568			ctl_set_invalid_opcode(ctsio);
11569			ctl_done((union ctl_io *)ctsio);
11570			return (retval);
11571		}
11572	}
11573
11574	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11575
11576#ifdef CTL_WITH_CA
11577	/*
11578	 * If we've got a request sense, it'll clear the contingent
11579	 * allegiance condition.  Otherwise, if we have a CA condition for
11580	 * this initiator, clear it, because it sent down a command other
11581	 * than request sense.
11582	 */
11583	if ((ctsio->cdb[0] != REQUEST_SENSE)
11584	 && (ctl_is_set(lun->have_ca, initidx)))
11585		ctl_clear_mask(lun->have_ca, initidx);
11586#endif
11587
11588	/*
11589	 * If the command has this flag set, it handles its own unit
11590	 * attention reporting, we shouldn't do anything.  Otherwise we
11591	 * check for any pending unit attentions, and send them back to the
11592	 * initiator.  We only do this when a command initially comes in,
11593	 * not when we pull it off the blocked queue.
11594	 *
11595	 * According to SAM-3, section 5.3.2, the order that things get
11596	 * presented back to the host is basically unit attentions caused
11597	 * by some sort of reset event, busy status, reservation conflicts
11598	 * or task set full, and finally any other status.
11599	 *
11600	 * One issue here is that some of the unit attentions we report
11601	 * don't fall into the "reset" category (e.g. "reported luns data
11602	 * has changed").  So reporting it here, before the reservation
11603	 * check, may be technically wrong.  I guess the only thing to do
11604	 * would be to check for and report the reset events here, and then
11605	 * check for the other unit attention types after we check for a
11606	 * reservation conflict.
11607	 *
11608	 * XXX KDM need to fix this
11609	 */
11610	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11611		ctl_ua_type ua_type;
11612		u_int sense_len = 0;
11613
11614		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11615		    &sense_len, SSD_TYPE_NONE);
11616		if (ua_type != CTL_UA_NONE) {
11617			mtx_unlock(&lun->lun_lock);
11618			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11619			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11620			ctsio->sense_len = sense_len;
11621			ctl_done((union ctl_io *)ctsio);
11622			return (retval);
11623		}
11624	}
11625
11626
11627	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11628		mtx_unlock(&lun->lun_lock);
11629		ctl_done((union ctl_io *)ctsio);
11630		return (retval);
11631	}
11632
11633	/*
11634	 * XXX CHD this is where we want to send IO to other side if
11635	 * this LUN is secondary on this SC. We will need to make a copy
11636	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11637	 * the copy we send as FROM_OTHER.
11638	 * We also need to stuff the address of the original IO so we can
11639	 * find it easily. Something similar will need be done on the other
11640	 * side so when we are done we can find the copy.
11641	 */
11642	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11643	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11644	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11645		union ctl_ha_msg msg_info;
11646		int isc_retval;
11647
11648		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11649		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11650		mtx_unlock(&lun->lun_lock);
11651
11652		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11653		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11654		msg_info.hdr.serializing_sc = NULL;
11655		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11656		msg_info.scsi.tag_num = ctsio->tag_num;
11657		msg_info.scsi.tag_type = ctsio->tag_type;
11658		msg_info.scsi.cdb_len = ctsio->cdb_len;
11659		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11660
11661		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11662		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11663		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11664			ctl_set_busy(ctsio);
11665			ctl_done((union ctl_io *)ctsio);
11666			return (retval);
11667		}
11668		return (retval);
11669	}
11670
11671	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11672			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11673			      ctl_ooaq, ooa_links))) {
11674	case CTL_ACTION_BLOCK:
11675		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11676		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11677				  blocked_links);
11678		mtx_unlock(&lun->lun_lock);
11679		return (retval);
11680	case CTL_ACTION_PASS:
11681	case CTL_ACTION_SKIP:
11682		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11683		mtx_unlock(&lun->lun_lock);
11684		ctl_enqueue_rtr((union ctl_io *)ctsio);
11685		break;
11686	case CTL_ACTION_OVERLAP:
11687		mtx_unlock(&lun->lun_lock);
11688		ctl_set_overlapped_cmd(ctsio);
11689		ctl_done((union ctl_io *)ctsio);
11690		break;
11691	case CTL_ACTION_OVERLAP_TAG:
11692		mtx_unlock(&lun->lun_lock);
11693		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11694		ctl_done((union ctl_io *)ctsio);
11695		break;
11696	case CTL_ACTION_ERROR:
11697	default:
11698		mtx_unlock(&lun->lun_lock);
11699		ctl_set_internal_failure(ctsio,
11700					 /*sks_valid*/ 0,
11701					 /*retry_count*/ 0);
11702		ctl_done((union ctl_io *)ctsio);
11703		break;
11704	}
11705	return (retval);
11706}
11707
11708const struct ctl_cmd_entry *
11709ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11710{
11711	const struct ctl_cmd_entry *entry;
11712	int service_action;
11713
11714	entry = &ctl_cmd_table[ctsio->cdb[0]];
11715	if (sa)
11716		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11717	if (entry->flags & CTL_CMD_FLAG_SA5) {
11718		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11719		entry = &((const struct ctl_cmd_entry *)
11720		    entry->execute)[service_action];
11721	}
11722	return (entry);
11723}
11724
11725const struct ctl_cmd_entry *
11726ctl_validate_command(struct ctl_scsiio *ctsio)
11727{
11728	const struct ctl_cmd_entry *entry;
11729	int i, sa;
11730	uint8_t diff;
11731
11732	entry = ctl_get_cmd_entry(ctsio, &sa);
11733	if (entry->execute == NULL) {
11734		if (sa)
11735			ctl_set_invalid_field(ctsio,
11736					      /*sks_valid*/ 1,
11737					      /*command*/ 1,
11738					      /*field*/ 1,
11739					      /*bit_valid*/ 1,
11740					      /*bit*/ 4);
11741		else
11742			ctl_set_invalid_opcode(ctsio);
11743		ctl_done((union ctl_io *)ctsio);
11744		return (NULL);
11745	}
11746	KASSERT(entry->length > 0,
11747	    ("Not defined length for command 0x%02x/0x%02x",
11748	     ctsio->cdb[0], ctsio->cdb[1]));
11749	for (i = 1; i < entry->length; i++) {
11750		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11751		if (diff == 0)
11752			continue;
11753		ctl_set_invalid_field(ctsio,
11754				      /*sks_valid*/ 1,
11755				      /*command*/ 1,
11756				      /*field*/ i,
11757				      /*bit_valid*/ 1,
11758				      /*bit*/ fls(diff) - 1);
11759		ctl_done((union ctl_io *)ctsio);
11760		return (NULL);
11761	}
11762	return (entry);
11763}
11764
11765static int
11766ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11767{
11768
11769	switch (lun_type) {
11770	case T_DIRECT:
11771		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11772			return (0);
11773		break;
11774	case T_PROCESSOR:
11775		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11776			return (0);
11777		break;
11778	case T_CDROM:
11779		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11780			return (0);
11781		break;
11782	default:
11783		return (0);
11784	}
11785	return (1);
11786}
11787
11788static int
11789ctl_scsiio(struct ctl_scsiio *ctsio)
11790{
11791	int retval;
11792	const struct ctl_cmd_entry *entry;
11793
11794	retval = CTL_RETVAL_COMPLETE;
11795
11796	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11797
11798	entry = ctl_get_cmd_entry(ctsio, NULL);
11799
11800	/*
11801	 * If this I/O has been aborted, just send it straight to
11802	 * ctl_done() without executing it.
11803	 */
11804	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11805		ctl_done((union ctl_io *)ctsio);
11806		goto bailout;
11807	}
11808
11809	/*
11810	 * All the checks should have been handled by ctl_scsiio_precheck().
11811	 * We should be clear now to just execute the I/O.
11812	 */
11813	retval = entry->execute(ctsio);
11814
11815bailout:
11816	return (retval);
11817}
11818
11819/*
11820 * Since we only implement one target right now, a bus reset simply resets
11821 * our single target.
11822 */
11823static int
11824ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11825{
11826	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11827}
11828
11829static int
11830ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11831		 ctl_ua_type ua_type)
11832{
11833	struct ctl_port *port = CTL_PORT(io);
11834	struct ctl_lun *lun;
11835	int retval;
11836
11837	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11838		union ctl_ha_msg msg_info;
11839
11840		msg_info.hdr.nexus = io->io_hdr.nexus;
11841		if (ua_type==CTL_UA_TARG_RESET)
11842			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11843		else
11844			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11845		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11846		msg_info.hdr.original_sc = NULL;
11847		msg_info.hdr.serializing_sc = NULL;
11848		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11849		    sizeof(msg_info.task), M_WAITOK);
11850	}
11851	retval = 0;
11852
11853	mtx_lock(&softc->ctl_lock);
11854	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11855		if (port != NULL &&
11856		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11857			continue;
11858		retval += ctl_do_lun_reset(lun, io, ua_type);
11859	}
11860	mtx_unlock(&softc->ctl_lock);
11861	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11862	return (retval);
11863}
11864
11865/*
11866 * The LUN should always be set.  The I/O is optional, and is used to
11867 * distinguish between I/Os sent by this initiator, and by other
11868 * initiators.  We set unit attention for initiators other than this one.
11869 * SAM-3 is vague on this point.  It does say that a unit attention should
11870 * be established for other initiators when a LUN is reset (see section
11871 * 5.7.3), but it doesn't specifically say that the unit attention should
11872 * be established for this particular initiator when a LUN is reset.  Here
11873 * is the relevant text, from SAM-3 rev 8:
11874 *
11875 * 5.7.2 When a SCSI initiator port aborts its own tasks
11876 *
11877 * When a SCSI initiator port causes its own task(s) to be aborted, no
11878 * notification that the task(s) have been aborted shall be returned to
11879 * the SCSI initiator port other than the completion response for the
11880 * command or task management function action that caused the task(s) to
11881 * be aborted and notification(s) associated with related effects of the
11882 * action (e.g., a reset unit attention condition).
11883 *
11884 * XXX KDM for now, we're setting unit attention for all initiators.
11885 */
11886static int
11887ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11888{
11889	union ctl_io *xio;
11890#if 0
11891	uint32_t initidx;
11892#endif
11893	int i;
11894
11895	mtx_lock(&lun->lun_lock);
11896	/*
11897	 * Run through the OOA queue and abort each I/O.
11898	 */
11899	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11900	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11901		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11902	}
11903
11904	/*
11905	 * This version sets unit attention for every
11906	 */
11907#if 0
11908	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11909	ctl_est_ua_all(lun, initidx, ua_type);
11910#else
11911	ctl_est_ua_all(lun, -1, ua_type);
11912#endif
11913
11914	/*
11915	 * A reset (any kind, really) clears reservations established with
11916	 * RESERVE/RELEASE.  It does not clear reservations established
11917	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11918	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11919	 * reservations made with the RESERVE/RELEASE commands, because
11920	 * those commands are obsolete in SPC-3.
11921	 */
11922	lun->flags &= ~CTL_LUN_RESERVED;
11923
11924#ifdef CTL_WITH_CA
11925	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11926		ctl_clear_mask(lun->have_ca, i);
11927#endif
11928	lun->prevent_count = 0;
11929	if (lun->prevent) {
11930		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11931			ctl_clear_mask(lun->prevent, i);
11932	}
11933	mtx_unlock(&lun->lun_lock);
11934
11935	return (0);
11936}
11937
11938static int
11939ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11940{
11941	struct ctl_lun *lun;
11942	uint32_t targ_lun;
11943	int retval;
11944
11945	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11946	mtx_lock(&softc->ctl_lock);
11947	if (targ_lun >= CTL_MAX_LUNS ||
11948	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11949		mtx_unlock(&softc->ctl_lock);
11950		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11951		return (1);
11952	}
11953	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11954	mtx_unlock(&softc->ctl_lock);
11955	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11956
11957	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11958		union ctl_ha_msg msg_info;
11959
11960		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11961		msg_info.hdr.nexus = io->io_hdr.nexus;
11962		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11963		msg_info.hdr.original_sc = NULL;
11964		msg_info.hdr.serializing_sc = NULL;
11965		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11966		    sizeof(msg_info.task), M_WAITOK);
11967	}
11968	return (retval);
11969}
11970
11971static void
11972ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11973    int other_sc)
11974{
11975	union ctl_io *xio;
11976
11977	mtx_assert(&lun->lun_lock, MA_OWNED);
11978
11979	/*
11980	 * Run through the OOA queue and attempt to find the given I/O.
11981	 * The target port, initiator ID, tag type and tag number have to
11982	 * match the values that we got from the initiator.  If we have an
11983	 * untagged command to abort, simply abort the first untagged command
11984	 * we come to.  We only allow one untagged command at a time of course.
11985	 */
11986	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11987	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11988
11989		if ((targ_port == UINT32_MAX ||
11990		     targ_port == xio->io_hdr.nexus.targ_port) &&
11991		    (init_id == UINT32_MAX ||
11992		     init_id == xio->io_hdr.nexus.initid)) {
11993			if (targ_port != xio->io_hdr.nexus.targ_port ||
11994			    init_id != xio->io_hdr.nexus.initid)
11995				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11996			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11997			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11998				union ctl_ha_msg msg_info;
11999
12000				msg_info.hdr.nexus = xio->io_hdr.nexus;
12001				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12002				msg_info.task.tag_num = xio->scsiio.tag_num;
12003				msg_info.task.tag_type = xio->scsiio.tag_type;
12004				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12005				msg_info.hdr.original_sc = NULL;
12006				msg_info.hdr.serializing_sc = NULL;
12007				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12008				    sizeof(msg_info.task), M_NOWAIT);
12009			}
12010		}
12011	}
12012}
12013
12014static int
12015ctl_abort_task_set(union ctl_io *io)
12016{
12017	struct ctl_softc *softc = CTL_SOFTC(io);
12018	struct ctl_lun *lun;
12019	uint32_t targ_lun;
12020
12021	/*
12022	 * Look up the LUN.
12023	 */
12024	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12025	mtx_lock(&softc->ctl_lock);
12026	if (targ_lun >= CTL_MAX_LUNS ||
12027	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12028		mtx_unlock(&softc->ctl_lock);
12029		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12030		return (1);
12031	}
12032
12033	mtx_lock(&lun->lun_lock);
12034	mtx_unlock(&softc->ctl_lock);
12035	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12036		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12037		    io->io_hdr.nexus.initid,
12038		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12039	} else { /* CTL_TASK_CLEAR_TASK_SET */
12040		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12041		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12042	}
12043	mtx_unlock(&lun->lun_lock);
12044	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12045	return (0);
12046}
12047
12048static int
12049ctl_i_t_nexus_reset(union ctl_io *io)
12050{
12051	struct ctl_softc *softc = CTL_SOFTC(io);
12052	struct ctl_lun *lun;
12053	uint32_t initidx;
12054
12055	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12056		union ctl_ha_msg msg_info;
12057
12058		msg_info.hdr.nexus = io->io_hdr.nexus;
12059		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12060		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12061		msg_info.hdr.original_sc = NULL;
12062		msg_info.hdr.serializing_sc = NULL;
12063		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12064		    sizeof(msg_info.task), M_WAITOK);
12065	}
12066
12067	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12068	mtx_lock(&softc->ctl_lock);
12069	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12070		mtx_lock(&lun->lun_lock);
12071		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12072		    io->io_hdr.nexus.initid, 1);
12073#ifdef CTL_WITH_CA
12074		ctl_clear_mask(lun->have_ca, initidx);
12075#endif
12076		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12077			lun->flags &= ~CTL_LUN_RESERVED;
12078		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12079			ctl_clear_mask(lun->prevent, initidx);
12080			lun->prevent_count--;
12081		}
12082		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12083		mtx_unlock(&lun->lun_lock);
12084	}
12085	mtx_unlock(&softc->ctl_lock);
12086	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12087	return (0);
12088}
12089
12090static int
12091ctl_abort_task(union ctl_io *io)
12092{
12093	struct ctl_softc *softc = CTL_SOFTC(io);
12094	union ctl_io *xio;
12095	struct ctl_lun *lun;
12096#if 0
12097	struct sbuf sb;
12098	char printbuf[128];
12099#endif
12100	int found;
12101	uint32_t targ_lun;
12102
12103	found = 0;
12104
12105	/*
12106	 * Look up the LUN.
12107	 */
12108	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12109	mtx_lock(&softc->ctl_lock);
12110	if (targ_lun >= CTL_MAX_LUNS ||
12111	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12112		mtx_unlock(&softc->ctl_lock);
12113		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12114		return (1);
12115	}
12116
12117#if 0
12118	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12119	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12120#endif
12121
12122	mtx_lock(&lun->lun_lock);
12123	mtx_unlock(&softc->ctl_lock);
12124	/*
12125	 * Run through the OOA queue and attempt to find the given I/O.
12126	 * The target port, initiator ID, tag type and tag number have to
12127	 * match the values that we got from the initiator.  If we have an
12128	 * untagged command to abort, simply abort the first untagged command
12129	 * we come to.  We only allow one untagged command at a time of course.
12130	 */
12131	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12132	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12133#if 0
12134		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12135
12136		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12137			    lun->lun, xio->scsiio.tag_num,
12138			    xio->scsiio.tag_type,
12139			    (xio->io_hdr.blocked_links.tqe_prev
12140			    == NULL) ? "" : " BLOCKED",
12141			    (xio->io_hdr.flags &
12142			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12143			    (xio->io_hdr.flags &
12144			    CTL_FLAG_ABORT) ? " ABORT" : "",
12145			    (xio->io_hdr.flags &
12146			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12147		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12148		sbuf_finish(&sb);
12149		printf("%s\n", sbuf_data(&sb));
12150#endif
12151
12152		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12153		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12154		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12155			continue;
12156
12157		/*
12158		 * If the abort says that the task is untagged, the
12159		 * task in the queue must be untagged.  Otherwise,
12160		 * we just check to see whether the tag numbers
12161		 * match.  This is because the QLogic firmware
12162		 * doesn't pass back the tag type in an abort
12163		 * request.
12164		 */
12165#if 0
12166		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12167		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12168		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12169#endif
12170		/*
12171		 * XXX KDM we've got problems with FC, because it
12172		 * doesn't send down a tag type with aborts.  So we
12173		 * can only really go by the tag number...
12174		 * This may cause problems with parallel SCSI.
12175		 * Need to figure that out!!
12176		 */
12177		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12178			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12179			found = 1;
12180			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12181			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12182				union ctl_ha_msg msg_info;
12183
12184				msg_info.hdr.nexus = io->io_hdr.nexus;
12185				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12186				msg_info.task.tag_num = io->taskio.tag_num;
12187				msg_info.task.tag_type = io->taskio.tag_type;
12188				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12189				msg_info.hdr.original_sc = NULL;
12190				msg_info.hdr.serializing_sc = NULL;
12191#if 0
12192				printf("Sent Abort to other side\n");
12193#endif
12194				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12195				    sizeof(msg_info.task), M_NOWAIT);
12196			}
12197#if 0
12198			printf("ctl_abort_task: found I/O to abort\n");
12199#endif
12200		}
12201	}
12202	mtx_unlock(&lun->lun_lock);
12203
12204	if (found == 0) {
12205		/*
12206		 * This isn't really an error.  It's entirely possible for
12207		 * the abort and command completion to cross on the wire.
12208		 * This is more of an informative/diagnostic error.
12209		 */
12210#if 0
12211		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12212		       "%u:%u:%u tag %d type %d\n",
12213		       io->io_hdr.nexus.initid,
12214		       io->io_hdr.nexus.targ_port,
12215		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12216		       io->taskio.tag_type);
12217#endif
12218	}
12219	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12220	return (0);
12221}
12222
12223static int
12224ctl_query_task(union ctl_io *io, int task_set)
12225{
12226	struct ctl_softc *softc = CTL_SOFTC(io);
12227	union ctl_io *xio;
12228	struct ctl_lun *lun;
12229	int found = 0;
12230	uint32_t targ_lun;
12231
12232	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12233	mtx_lock(&softc->ctl_lock);
12234	if (targ_lun >= CTL_MAX_LUNS ||
12235	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12236		mtx_unlock(&softc->ctl_lock);
12237		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12238		return (1);
12239	}
12240	mtx_lock(&lun->lun_lock);
12241	mtx_unlock(&softc->ctl_lock);
12242	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12243	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12244
12245		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12246		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12247		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12248			continue;
12249
12250		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12251			found = 1;
12252			break;
12253		}
12254	}
12255	mtx_unlock(&lun->lun_lock);
12256	if (found)
12257		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12258	else
12259		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12260	return (0);
12261}
12262
12263static int
12264ctl_query_async_event(union ctl_io *io)
12265{
12266	struct ctl_softc *softc = CTL_SOFTC(io);
12267	struct ctl_lun *lun;
12268	ctl_ua_type ua;
12269	uint32_t targ_lun, initidx;
12270
12271	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12272	mtx_lock(&softc->ctl_lock);
12273	if (targ_lun >= CTL_MAX_LUNS ||
12274	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12275		mtx_unlock(&softc->ctl_lock);
12276		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12277		return (1);
12278	}
12279	mtx_lock(&lun->lun_lock);
12280	mtx_unlock(&softc->ctl_lock);
12281	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12282	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12283	mtx_unlock(&lun->lun_lock);
12284	if (ua != CTL_UA_NONE)
12285		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12286	else
12287		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12288	return (0);
12289}
12290
12291static void
12292ctl_run_task(union ctl_io *io)
12293{
12294	struct ctl_softc *softc = CTL_SOFTC(io);
12295	int retval = 1;
12296
12297	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12298	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12299	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12300	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12301	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12302	switch (io->taskio.task_action) {
12303	case CTL_TASK_ABORT_TASK:
12304		retval = ctl_abort_task(io);
12305		break;
12306	case CTL_TASK_ABORT_TASK_SET:
12307	case CTL_TASK_CLEAR_TASK_SET:
12308		retval = ctl_abort_task_set(io);
12309		break;
12310	case CTL_TASK_CLEAR_ACA:
12311		break;
12312	case CTL_TASK_I_T_NEXUS_RESET:
12313		retval = ctl_i_t_nexus_reset(io);
12314		break;
12315	case CTL_TASK_LUN_RESET:
12316		retval = ctl_lun_reset(softc, io);
12317		break;
12318	case CTL_TASK_TARGET_RESET:
12319		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12320		break;
12321	case CTL_TASK_BUS_RESET:
12322		retval = ctl_bus_reset(softc, io);
12323		break;
12324	case CTL_TASK_PORT_LOGIN:
12325		break;
12326	case CTL_TASK_PORT_LOGOUT:
12327		break;
12328	case CTL_TASK_QUERY_TASK:
12329		retval = ctl_query_task(io, 0);
12330		break;
12331	case CTL_TASK_QUERY_TASK_SET:
12332		retval = ctl_query_task(io, 1);
12333		break;
12334	case CTL_TASK_QUERY_ASYNC_EVENT:
12335		retval = ctl_query_async_event(io);
12336		break;
12337	default:
12338		printf("%s: got unknown task management event %d\n",
12339		       __func__, io->taskio.task_action);
12340		break;
12341	}
12342	if (retval == 0)
12343		io->io_hdr.status = CTL_SUCCESS;
12344	else
12345		io->io_hdr.status = CTL_ERROR;
12346	ctl_done(io);
12347}
12348
12349/*
12350 * For HA operation.  Handle commands that come in from the other
12351 * controller.
12352 */
12353static void
12354ctl_handle_isc(union ctl_io *io)
12355{
12356	struct ctl_softc *softc = CTL_SOFTC(io);
12357	struct ctl_lun *lun;
12358	const struct ctl_cmd_entry *entry;
12359	uint32_t targ_lun;
12360
12361	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12362	switch (io->io_hdr.msg_type) {
12363	case CTL_MSG_SERIALIZE:
12364		ctl_serialize_other_sc_cmd(&io->scsiio);
12365		break;
12366	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12367		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12368		if (targ_lun >= CTL_MAX_LUNS ||
12369		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12370			ctl_done(io);
12371			break;
12372		}
12373		mtx_lock(&lun->lun_lock);
12374		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12375			mtx_unlock(&lun->lun_lock);
12376			ctl_done(io);
12377			break;
12378		}
12379		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12380		mtx_unlock(&lun->lun_lock);
12381		ctl_enqueue_rtr(io);
12382		break;
12383	case CTL_MSG_FINISH_IO:
12384		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12385			ctl_done(io);
12386			break;
12387		}
12388		if (targ_lun >= CTL_MAX_LUNS ||
12389		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12390			ctl_free_io(io);
12391			break;
12392		}
12393		mtx_lock(&lun->lun_lock);
12394		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12395		ctl_check_blocked(lun);
12396		mtx_unlock(&lun->lun_lock);
12397		ctl_free_io(io);
12398		break;
12399	case CTL_MSG_PERS_ACTION:
12400		ctl_hndl_per_res_out_on_other_sc(io);
12401		ctl_free_io(io);
12402		break;
12403	case CTL_MSG_BAD_JUJU:
12404		ctl_done(io);
12405		break;
12406	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12407		ctl_datamove_remote(io);
12408		break;
12409	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12410		io->scsiio.be_move_done(io);
12411		break;
12412	case CTL_MSG_FAILOVER:
12413		ctl_failover_lun(io);
12414		ctl_free_io(io);
12415		break;
12416	default:
12417		printf("%s: Invalid message type %d\n",
12418		       __func__, io->io_hdr.msg_type);
12419		ctl_free_io(io);
12420		break;
12421	}
12422
12423}
12424
12425
12426/*
12427 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12428 * there is no match.
12429 */
12430static ctl_lun_error_pattern
12431ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12432{
12433	const struct ctl_cmd_entry *entry;
12434	ctl_lun_error_pattern filtered_pattern, pattern;
12435
12436	pattern = desc->error_pattern;
12437
12438	/*
12439	 * XXX KDM we need more data passed into this function to match a
12440	 * custom pattern, and we actually need to implement custom pattern
12441	 * matching.
12442	 */
12443	if (pattern & CTL_LUN_PAT_CMD)
12444		return (CTL_LUN_PAT_CMD);
12445
12446	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12447		return (CTL_LUN_PAT_ANY);
12448
12449	entry = ctl_get_cmd_entry(ctsio, NULL);
12450
12451	filtered_pattern = entry->pattern & pattern;
12452
12453	/*
12454	 * If the user requested specific flags in the pattern (e.g.
12455	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12456	 * flags.
12457	 *
12458	 * If the user did not specify any flags, it doesn't matter whether
12459	 * or not the command supports the flags.
12460	 */
12461	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12462	     (pattern & ~CTL_LUN_PAT_MASK))
12463		return (CTL_LUN_PAT_NONE);
12464
12465	/*
12466	 * If the user asked for a range check, see if the requested LBA
12467	 * range overlaps with this command's LBA range.
12468	 */
12469	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12470		uint64_t lba1;
12471		uint64_t len1;
12472		ctl_action action;
12473		int retval;
12474
12475		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12476		if (retval != 0)
12477			return (CTL_LUN_PAT_NONE);
12478
12479		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12480					      desc->lba_range.len, FALSE);
12481		/*
12482		 * A "pass" means that the LBA ranges don't overlap, so
12483		 * this doesn't match the user's range criteria.
12484		 */
12485		if (action == CTL_ACTION_PASS)
12486			return (CTL_LUN_PAT_NONE);
12487	}
12488
12489	return (filtered_pattern);
12490}
12491
12492static void
12493ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12494{
12495	struct ctl_error_desc *desc, *desc2;
12496
12497	mtx_assert(&lun->lun_lock, MA_OWNED);
12498
12499	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12500		ctl_lun_error_pattern pattern;
12501		/*
12502		 * Check to see whether this particular command matches
12503		 * the pattern in the descriptor.
12504		 */
12505		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12506		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12507			continue;
12508
12509		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12510		case CTL_LUN_INJ_ABORTED:
12511			ctl_set_aborted(&io->scsiio);
12512			break;
12513		case CTL_LUN_INJ_MEDIUM_ERR:
12514			ctl_set_medium_error(&io->scsiio,
12515			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12516			     CTL_FLAG_DATA_OUT);
12517			break;
12518		case CTL_LUN_INJ_UA:
12519			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12520			 * OCCURRED */
12521			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12522			break;
12523		case CTL_LUN_INJ_CUSTOM:
12524			/*
12525			 * We're assuming the user knows what he is doing.
12526			 * Just copy the sense information without doing
12527			 * checks.
12528			 */
12529			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12530			      MIN(sizeof(desc->custom_sense),
12531				  sizeof(io->scsiio.sense_data)));
12532			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12533			io->scsiio.sense_len = SSD_FULL_SIZE;
12534			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12535			break;
12536		case CTL_LUN_INJ_NONE:
12537		default:
12538			/*
12539			 * If this is an error injection type we don't know
12540			 * about, clear the continuous flag (if it is set)
12541			 * so it will get deleted below.
12542			 */
12543			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12544			break;
12545		}
12546		/*
12547		 * By default, each error injection action is a one-shot
12548		 */
12549		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12550			continue;
12551
12552		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12553
12554		free(desc, M_CTL);
12555	}
12556}
12557
12558#ifdef CTL_IO_DELAY
12559static void
12560ctl_datamove_timer_wakeup(void *arg)
12561{
12562	union ctl_io *io;
12563
12564	io = (union ctl_io *)arg;
12565
12566	ctl_datamove(io);
12567}
12568#endif /* CTL_IO_DELAY */
12569
12570void
12571ctl_datamove(union ctl_io *io)
12572{
12573	void (*fe_datamove)(union ctl_io *io);
12574
12575	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12576
12577	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12578
12579#ifdef CTL_TIME_IO
12580	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12581		char str[256];
12582		char path_str[64];
12583		struct sbuf sb;
12584
12585		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12586		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12587
12588		sbuf_cat(&sb, path_str);
12589		switch (io->io_hdr.io_type) {
12590		case CTL_IO_SCSI:
12591			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12592			sbuf_printf(&sb, "\n");
12593			sbuf_cat(&sb, path_str);
12594			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12595				    io->scsiio.tag_num, io->scsiio.tag_type);
12596			break;
12597		case CTL_IO_TASK:
12598			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12599				    "Tag Type: %d\n", io->taskio.task_action,
12600				    io->taskio.tag_num, io->taskio.tag_type);
12601			break;
12602		default:
12603			panic("%s: Invalid CTL I/O type %d\n",
12604			    __func__, io->io_hdr.io_type);
12605		}
12606		sbuf_cat(&sb, path_str);
12607		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12608			    (intmax_t)time_uptime - io->io_hdr.start_time);
12609		sbuf_finish(&sb);
12610		printf("%s", sbuf_data(&sb));
12611	}
12612#endif /* CTL_TIME_IO */
12613
12614#ifdef CTL_IO_DELAY
12615	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12616		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12617	} else {
12618		if ((lun != NULL)
12619		 && (lun->delay_info.datamove_delay > 0)) {
12620
12621			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12622			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12623			callout_reset(&io->io_hdr.delay_callout,
12624				      lun->delay_info.datamove_delay * hz,
12625				      ctl_datamove_timer_wakeup, io);
12626			if (lun->delay_info.datamove_type ==
12627			    CTL_DELAY_TYPE_ONESHOT)
12628				lun->delay_info.datamove_delay = 0;
12629			return;
12630		}
12631	}
12632#endif
12633
12634	/*
12635	 * This command has been aborted.  Set the port status, so we fail
12636	 * the data move.
12637	 */
12638	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12639		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12640		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12641		       io->io_hdr.nexus.targ_port,
12642		       io->io_hdr.nexus.targ_lun);
12643		io->io_hdr.port_status = 31337;
12644		/*
12645		 * Note that the backend, in this case, will get the
12646		 * callback in its context.  In other cases it may get
12647		 * called in the frontend's interrupt thread context.
12648		 */
12649		io->scsiio.be_move_done(io);
12650		return;
12651	}
12652
12653	/* Don't confuse frontend with zero length data move. */
12654	if (io->scsiio.kern_data_len == 0) {
12655		io->scsiio.be_move_done(io);
12656		return;
12657	}
12658
12659	fe_datamove = CTL_PORT(io)->fe_datamove;
12660	fe_datamove(io);
12661}
12662
12663static void
12664ctl_send_datamove_done(union ctl_io *io, int have_lock)
12665{
12666	union ctl_ha_msg msg;
12667#ifdef CTL_TIME_IO
12668	struct bintime cur_bt;
12669#endif
12670
12671	memset(&msg, 0, sizeof(msg));
12672	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12673	msg.hdr.original_sc = io;
12674	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12675	msg.hdr.nexus = io->io_hdr.nexus;
12676	msg.hdr.status = io->io_hdr.status;
12677	msg.scsi.tag_num = io->scsiio.tag_num;
12678	msg.scsi.tag_type = io->scsiio.tag_type;
12679	msg.scsi.scsi_status = io->scsiio.scsi_status;
12680	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12681	       io->scsiio.sense_len);
12682	msg.scsi.sense_len = io->scsiio.sense_len;
12683	msg.scsi.sense_residual = io->scsiio.sense_residual;
12684	msg.scsi.fetd_status = io->io_hdr.port_status;
12685	msg.scsi.residual = io->scsiio.residual;
12686	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12687	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12688		ctl_failover_io(io, /*have_lock*/ have_lock);
12689		return;
12690	}
12691	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12692	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12693	    msg.scsi.sense_len, M_WAITOK);
12694
12695#ifdef CTL_TIME_IO
12696	getbinuptime(&cur_bt);
12697	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12698	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12699#endif
12700	io->io_hdr.num_dmas++;
12701}
12702
12703/*
12704 * The DMA to the remote side is done, now we need to tell the other side
12705 * we're done so it can continue with its data movement.
12706 */
12707static void
12708ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12709{
12710	union ctl_io *io;
12711	uint32_t i;
12712
12713	io = rq->context;
12714
12715	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12716		printf("%s: ISC DMA write failed with error %d", __func__,
12717		       rq->ret);
12718		ctl_set_internal_failure(&io->scsiio,
12719					 /*sks_valid*/ 1,
12720					 /*retry_count*/ rq->ret);
12721	}
12722
12723	ctl_dt_req_free(rq);
12724
12725	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12726		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12727	free(io->io_hdr.remote_sglist, M_CTL);
12728	io->io_hdr.remote_sglist = NULL;
12729	io->io_hdr.local_sglist = NULL;
12730
12731	/*
12732	 * The data is in local and remote memory, so now we need to send
12733	 * status (good or back) back to the other side.
12734	 */
12735	ctl_send_datamove_done(io, /*have_lock*/ 0);
12736}
12737
12738/*
12739 * We've moved the data from the host/controller into local memory.  Now we
12740 * need to push it over to the remote controller's memory.
12741 */
12742static int
12743ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12744{
12745	int retval;
12746
12747	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12748					  ctl_datamove_remote_write_cb);
12749	return (retval);
12750}
12751
12752static void
12753ctl_datamove_remote_write(union ctl_io *io)
12754{
12755	int retval;
12756	void (*fe_datamove)(union ctl_io *io);
12757
12758	/*
12759	 * - Get the data from the host/HBA into local memory.
12760	 * - DMA memory from the local controller to the remote controller.
12761	 * - Send status back to the remote controller.
12762	 */
12763
12764	retval = ctl_datamove_remote_sgl_setup(io);
12765	if (retval != 0)
12766		return;
12767
12768	/* Switch the pointer over so the FETD knows what to do */
12769	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12770
12771	/*
12772	 * Use a custom move done callback, since we need to send completion
12773	 * back to the other controller, not to the backend on this side.
12774	 */
12775	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12776
12777	fe_datamove = CTL_PORT(io)->fe_datamove;
12778	fe_datamove(io);
12779}
12780
12781static int
12782ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12783{
12784#if 0
12785	char str[256];
12786	char path_str[64];
12787	struct sbuf sb;
12788#endif
12789	uint32_t i;
12790
12791	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12792		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12793	free(io->io_hdr.remote_sglist, M_CTL);
12794	io->io_hdr.remote_sglist = NULL;
12795	io->io_hdr.local_sglist = NULL;
12796
12797#if 0
12798	scsi_path_string(io, path_str, sizeof(path_str));
12799	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12800	sbuf_cat(&sb, path_str);
12801	scsi_command_string(&io->scsiio, NULL, &sb);
12802	sbuf_printf(&sb, "\n");
12803	sbuf_cat(&sb, path_str);
12804	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12805		    io->scsiio.tag_num, io->scsiio.tag_type);
12806	sbuf_cat(&sb, path_str);
12807	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12808		    io->io_hdr.flags, io->io_hdr.status);
12809	sbuf_finish(&sb);
12810	printk("%s", sbuf_data(&sb));
12811#endif
12812
12813
12814	/*
12815	 * The read is done, now we need to send status (good or bad) back
12816	 * to the other side.
12817	 */
12818	ctl_send_datamove_done(io, /*have_lock*/ 0);
12819
12820	return (0);
12821}
12822
12823static void
12824ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12825{
12826	union ctl_io *io;
12827	void (*fe_datamove)(union ctl_io *io);
12828
12829	io = rq->context;
12830
12831	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12832		printf("%s: ISC DMA read failed with error %d\n", __func__,
12833		       rq->ret);
12834		ctl_set_internal_failure(&io->scsiio,
12835					 /*sks_valid*/ 1,
12836					 /*retry_count*/ rq->ret);
12837	}
12838
12839	ctl_dt_req_free(rq);
12840
12841	/* Switch the pointer over so the FETD knows what to do */
12842	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12843
12844	/*
12845	 * Use a custom move done callback, since we need to send completion
12846	 * back to the other controller, not to the backend on this side.
12847	 */
12848	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12849
12850	/* XXX KDM add checks like the ones in ctl_datamove? */
12851
12852	fe_datamove = CTL_PORT(io)->fe_datamove;
12853	fe_datamove(io);
12854}
12855
12856static int
12857ctl_datamove_remote_sgl_setup(union ctl_io *io)
12858{
12859	struct ctl_sg_entry *local_sglist;
12860	uint32_t len_to_go;
12861	int retval;
12862	int i;
12863
12864	retval = 0;
12865	local_sglist = io->io_hdr.local_sglist;
12866	len_to_go = io->scsiio.kern_data_len;
12867
12868	/*
12869	 * The difficult thing here is that the size of the various
12870	 * S/G segments may be different than the size from the
12871	 * remote controller.  That'll make it harder when DMAing
12872	 * the data back to the other side.
12873	 */
12874	for (i = 0; len_to_go > 0; i++) {
12875		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12876		local_sglist[i].addr =
12877		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12878
12879		len_to_go -= local_sglist[i].len;
12880	}
12881	/*
12882	 * Reset the number of S/G entries accordingly.  The original
12883	 * number of S/G entries is available in rem_sg_entries.
12884	 */
12885	io->scsiio.kern_sg_entries = i;
12886
12887#if 0
12888	printf("%s: kern_sg_entries = %d\n", __func__,
12889	       io->scsiio.kern_sg_entries);
12890	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12891		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12892		       local_sglist[i].addr, local_sglist[i].len);
12893#endif
12894
12895	return (retval);
12896}
12897
12898static int
12899ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12900			 ctl_ha_dt_cb callback)
12901{
12902	struct ctl_ha_dt_req *rq;
12903	struct ctl_sg_entry *remote_sglist, *local_sglist;
12904	uint32_t local_used, remote_used, total_used;
12905	int i, j, isc_ret;
12906
12907	rq = ctl_dt_req_alloc();
12908
12909	/*
12910	 * If we failed to allocate the request, and if the DMA didn't fail
12911	 * anyway, set busy status.  This is just a resource allocation
12912	 * failure.
12913	 */
12914	if ((rq == NULL)
12915	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12916	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12917		ctl_set_busy(&io->scsiio);
12918
12919	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12920	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12921
12922		if (rq != NULL)
12923			ctl_dt_req_free(rq);
12924
12925		/*
12926		 * The data move failed.  We need to return status back
12927		 * to the other controller.  No point in trying to DMA
12928		 * data to the remote controller.
12929		 */
12930
12931		ctl_send_datamove_done(io, /*have_lock*/ 0);
12932
12933		return (1);
12934	}
12935
12936	local_sglist = io->io_hdr.local_sglist;
12937	remote_sglist = io->io_hdr.remote_sglist;
12938	local_used = 0;
12939	remote_used = 0;
12940	total_used = 0;
12941
12942	/*
12943	 * Pull/push the data over the wire from/to the other controller.
12944	 * This takes into account the possibility that the local and
12945	 * remote sglists may not be identical in terms of the size of
12946	 * the elements and the number of elements.
12947	 *
12948	 * One fundamental assumption here is that the length allocated for
12949	 * both the local and remote sglists is identical.  Otherwise, we've
12950	 * essentially got a coding error of some sort.
12951	 */
12952	isc_ret = CTL_HA_STATUS_SUCCESS;
12953	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12954		uint32_t cur_len;
12955		uint8_t *tmp_ptr;
12956
12957		rq->command = command;
12958		rq->context = io;
12959
12960		/*
12961		 * Both pointers should be aligned.  But it is possible
12962		 * that the allocation length is not.  They should both
12963		 * also have enough slack left over at the end, though,
12964		 * to round up to the next 8 byte boundary.
12965		 */
12966		cur_len = MIN(local_sglist[i].len - local_used,
12967			      remote_sglist[j].len - remote_used);
12968		rq->size = cur_len;
12969
12970		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12971		tmp_ptr += local_used;
12972
12973#if 0
12974		/* Use physical addresses when talking to ISC hardware */
12975		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12976			/* XXX KDM use busdma */
12977			rq->local = vtophys(tmp_ptr);
12978		} else
12979			rq->local = tmp_ptr;
12980#else
12981		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12982		    ("HA does not support BUS_ADDR"));
12983		rq->local = tmp_ptr;
12984#endif
12985
12986		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12987		tmp_ptr += remote_used;
12988		rq->remote = tmp_ptr;
12989
12990		rq->callback = NULL;
12991
12992		local_used += cur_len;
12993		if (local_used >= local_sglist[i].len) {
12994			i++;
12995			local_used = 0;
12996		}
12997
12998		remote_used += cur_len;
12999		if (remote_used >= remote_sglist[j].len) {
13000			j++;
13001			remote_used = 0;
13002		}
13003		total_used += cur_len;
13004
13005		if (total_used >= io->scsiio.kern_data_len)
13006			rq->callback = callback;
13007
13008#if 0
13009		printf("%s: %s: local %p remote %p size %d\n", __func__,
13010		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13011		       rq->local, rq->remote, rq->size);
13012#endif
13013
13014		isc_ret = ctl_dt_single(rq);
13015		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13016			break;
13017	}
13018	if (isc_ret != CTL_HA_STATUS_WAIT) {
13019		rq->ret = isc_ret;
13020		callback(rq);
13021	}
13022
13023	return (0);
13024}
13025
13026static void
13027ctl_datamove_remote_read(union ctl_io *io)
13028{
13029	int retval;
13030	uint32_t i;
13031
13032	/*
13033	 * This will send an error to the other controller in the case of a
13034	 * failure.
13035	 */
13036	retval = ctl_datamove_remote_sgl_setup(io);
13037	if (retval != 0)
13038		return;
13039
13040	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13041					  ctl_datamove_remote_read_cb);
13042	if (retval != 0) {
13043		/*
13044		 * Make sure we free memory if there was an error..  The
13045		 * ctl_datamove_remote_xfer() function will send the
13046		 * datamove done message, or call the callback with an
13047		 * error if there is a problem.
13048		 */
13049		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13050			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13051		free(io->io_hdr.remote_sglist, M_CTL);
13052		io->io_hdr.remote_sglist = NULL;
13053		io->io_hdr.local_sglist = NULL;
13054	}
13055}
13056
13057/*
13058 * Process a datamove request from the other controller.  This is used for
13059 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13060 * first.  Once that is complete, the data gets DMAed into the remote
13061 * controller's memory.  For reads, we DMA from the remote controller's
13062 * memory into our memory first, and then move it out to the FETD.
13063 */
13064static void
13065ctl_datamove_remote(union ctl_io *io)
13066{
13067
13068	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
13069
13070	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13071		ctl_failover_io(io, /*have_lock*/ 0);
13072		return;
13073	}
13074
13075	/*
13076	 * Note that we look for an aborted I/O here, but don't do some of
13077	 * the other checks that ctl_datamove() normally does.
13078	 * We don't need to run the datamove delay code, since that should
13079	 * have been done if need be on the other controller.
13080	 */
13081	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13082		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13083		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13084		       io->io_hdr.nexus.targ_port,
13085		       io->io_hdr.nexus.targ_lun);
13086		io->io_hdr.port_status = 31338;
13087		ctl_send_datamove_done(io, /*have_lock*/ 0);
13088		return;
13089	}
13090
13091	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13092		ctl_datamove_remote_write(io);
13093	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13094		ctl_datamove_remote_read(io);
13095	else {
13096		io->io_hdr.port_status = 31339;
13097		ctl_send_datamove_done(io, /*have_lock*/ 0);
13098	}
13099}
13100
13101static void
13102ctl_process_done(union ctl_io *io)
13103{
13104	struct ctl_softc *softc = CTL_SOFTC(io);
13105	struct ctl_port *port = CTL_PORT(io);
13106	struct ctl_lun *lun = CTL_LUN(io);
13107	void (*fe_done)(union ctl_io *io);
13108	union ctl_ha_msg msg;
13109
13110	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13111	fe_done = port->fe_done;
13112
13113#ifdef CTL_TIME_IO
13114	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13115		char str[256];
13116		char path_str[64];
13117		struct sbuf sb;
13118
13119		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13120		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13121
13122		sbuf_cat(&sb, path_str);
13123		switch (io->io_hdr.io_type) {
13124		case CTL_IO_SCSI:
13125			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13126			sbuf_printf(&sb, "\n");
13127			sbuf_cat(&sb, path_str);
13128			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13129				    io->scsiio.tag_num, io->scsiio.tag_type);
13130			break;
13131		case CTL_IO_TASK:
13132			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13133				    "Tag Type: %d\n", io->taskio.task_action,
13134				    io->taskio.tag_num, io->taskio.tag_type);
13135			break;
13136		default:
13137			panic("%s: Invalid CTL I/O type %d\n",
13138			    __func__, io->io_hdr.io_type);
13139		}
13140		sbuf_cat(&sb, path_str);
13141		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13142			    (intmax_t)time_uptime - io->io_hdr.start_time);
13143		sbuf_finish(&sb);
13144		printf("%s", sbuf_data(&sb));
13145	}
13146#endif /* CTL_TIME_IO */
13147
13148	switch (io->io_hdr.io_type) {
13149	case CTL_IO_SCSI:
13150		break;
13151	case CTL_IO_TASK:
13152		if (ctl_debug & CTL_DEBUG_INFO)
13153			ctl_io_error_print(io, NULL);
13154		fe_done(io);
13155		return;
13156	default:
13157		panic("%s: Invalid CTL I/O type %d\n",
13158		    __func__, io->io_hdr.io_type);
13159	}
13160
13161	if (lun == NULL) {
13162		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13163				 io->io_hdr.nexus.targ_mapped_lun));
13164		goto bailout;
13165	}
13166
13167	mtx_lock(&lun->lun_lock);
13168
13169	/*
13170	 * Check to see if we have any informational exception and status
13171	 * of this command can be modified to report it in form of either
13172	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13173	 */
13174	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13175	    io->io_hdr.status == CTL_SUCCESS &&
13176	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13177		uint8_t mrie = lun->MODE_IE.mrie;
13178		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13179		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13180		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13181		     mrie == SIEP_MRIE_REC_UNCOND ||
13182		     mrie == SIEP_MRIE_NO_SENSE) &&
13183		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13184		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13185			ctl_set_sense(&io->scsiio,
13186			      /*current_error*/ 1,
13187			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13188			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13189			      /*asc*/ lun->ie_asc,
13190			      /*ascq*/ lun->ie_ascq,
13191			      SSD_ELEM_NONE);
13192			lun->ie_reported = 1;
13193		}
13194	} else if (lun->ie_reported < 0)
13195		lun->ie_reported = 0;
13196
13197	/*
13198	 * Check to see if we have any errors to inject here.  We only
13199	 * inject errors for commands that don't already have errors set.
13200	 */
13201	if (!STAILQ_EMPTY(&lun->error_list) &&
13202	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13203	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13204		ctl_inject_error(lun, io);
13205
13206	/*
13207	 * XXX KDM how do we treat commands that aren't completed
13208	 * successfully?
13209	 *
13210	 * XXX KDM should we also track I/O latency?
13211	 */
13212	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13213	    io->io_hdr.io_type == CTL_IO_SCSI) {
13214		int type;
13215#ifdef CTL_TIME_IO
13216		struct bintime bt;
13217
13218		getbinuptime(&bt);
13219		bintime_sub(&bt, &io->io_hdr.start_bt);
13220#endif
13221		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13222		    CTL_FLAG_DATA_IN)
13223			type = CTL_STATS_READ;
13224		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13225		    CTL_FLAG_DATA_OUT)
13226			type = CTL_STATS_WRITE;
13227		else
13228			type = CTL_STATS_NO_IO;
13229
13230#ifdef CTL_LEGACY_STATS
13231		uint32_t targ_port = port->targ_port;
13232		lun->legacy_stats.ports[targ_port].bytes[type] +=
13233		    io->scsiio.kern_total_len;
13234		lun->legacy_stats.ports[targ_port].operations[type] ++;
13235		lun->legacy_stats.ports[targ_port].num_dmas[type] +=
13236		    io->io_hdr.num_dmas;
13237#ifdef CTL_TIME_IO
13238		bintime_add(&lun->legacy_stats.ports[targ_port].dma_time[type],
13239		   &io->io_hdr.dma_bt);
13240		bintime_add(&lun->legacy_stats.ports[targ_port].time[type],
13241		    &bt);
13242#endif
13243#endif /* CTL_LEGACY_STATS */
13244
13245		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13246		lun->stats.operations[type] ++;
13247		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13248#ifdef CTL_TIME_IO
13249		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13250		bintime_add(&lun->stats.time[type], &bt);
13251#endif
13252
13253		mtx_lock(&port->port_lock);
13254		port->stats.bytes[type] += io->scsiio.kern_total_len;
13255		port->stats.operations[type] ++;
13256		port->stats.dmas[type] += io->io_hdr.num_dmas;
13257#ifdef CTL_TIME_IO
13258		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13259		bintime_add(&port->stats.time[type], &bt);
13260#endif
13261		mtx_unlock(&port->port_lock);
13262	}
13263
13264	/*
13265	 * Remove this from the OOA queue.
13266	 */
13267	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13268#ifdef CTL_TIME_IO
13269	if (TAILQ_EMPTY(&lun->ooa_queue))
13270		lun->last_busy = getsbinuptime();
13271#endif
13272
13273	/*
13274	 * Run through the blocked queue on this LUN and see if anything
13275	 * has become unblocked, now that this transaction is done.
13276	 */
13277	ctl_check_blocked(lun);
13278
13279	/*
13280	 * If the LUN has been invalidated, free it if there is nothing
13281	 * left on its OOA queue.
13282	 */
13283	if ((lun->flags & CTL_LUN_INVALID)
13284	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13285		mtx_unlock(&lun->lun_lock);
13286		mtx_lock(&softc->ctl_lock);
13287		ctl_free_lun(lun);
13288		mtx_unlock(&softc->ctl_lock);
13289	} else
13290		mtx_unlock(&lun->lun_lock);
13291
13292bailout:
13293
13294	/*
13295	 * If this command has been aborted, make sure we set the status
13296	 * properly.  The FETD is responsible for freeing the I/O and doing
13297	 * whatever it needs to do to clean up its state.
13298	 */
13299	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13300		ctl_set_task_aborted(&io->scsiio);
13301
13302	/*
13303	 * If enabled, print command error status.
13304	 */
13305	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13306	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13307		ctl_io_error_print(io, NULL);
13308
13309	/*
13310	 * Tell the FETD or the other shelf controller we're done with this
13311	 * command.  Note that only SCSI commands get to this point.  Task
13312	 * management commands are completed above.
13313	 */
13314	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13315	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13316		memset(&msg, 0, sizeof(msg));
13317		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13318		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13319		msg.hdr.nexus = io->io_hdr.nexus;
13320		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13321		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13322		    M_WAITOK);
13323	}
13324
13325	fe_done(io);
13326}
13327
13328#ifdef CTL_WITH_CA
13329/*
13330 * Front end should call this if it doesn't do autosense.  When the request
13331 * sense comes back in from the initiator, we'll dequeue this and send it.
13332 */
13333int
13334ctl_queue_sense(union ctl_io *io)
13335{
13336	struct ctl_softc *softc = CTL_SOFTC(io);
13337	struct ctl_port *port = CTL_PORT(io);
13338	struct ctl_lun *lun;
13339	uint32_t initidx, targ_lun;
13340
13341	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13342
13343	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13344
13345	/*
13346	 * LUN lookup will likely move to the ctl_work_thread() once we
13347	 * have our new queueing infrastructure (that doesn't put things on
13348	 * a per-LUN queue initially).  That is so that we can handle
13349	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13350	 * can't deal with that right now.
13351	 * If we don't have a LUN for this, just toss the sense information.
13352	 */
13353	mtx_lock(&softc->ctl_lock);
13354	if (targ_lun >= CTL_MAX_LUNS ||
13355	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13356		mtx_unlock(&softc->ctl_lock);
13357		goto bailout;
13358	}
13359	mtx_lock(&lun->lun_lock);
13360	mtx_unlock(&softc->ctl_lock);
13361
13362	/*
13363	 * Already have CA set for this LUN...toss the sense information.
13364	 */
13365	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13366	if (ctl_is_set(lun->have_ca, initidx)) {
13367		mtx_unlock(&lun->lun_lock);
13368		goto bailout;
13369	}
13370
13371	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13372	       MIN(sizeof(lun->pending_sense[initidx]),
13373	       sizeof(io->scsiio.sense_data)));
13374	ctl_set_mask(lun->have_ca, initidx);
13375	mtx_unlock(&lun->lun_lock);
13376
13377bailout:
13378	ctl_free_io(io);
13379	return (CTL_RETVAL_COMPLETE);
13380}
13381#endif
13382
13383/*
13384 * Primary command inlet from frontend ports.  All SCSI and task I/O
13385 * requests must go through this function.
13386 */
13387int
13388ctl_queue(union ctl_io *io)
13389{
13390	struct ctl_port *port = CTL_PORT(io);
13391
13392	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13393
13394#ifdef CTL_TIME_IO
13395	io->io_hdr.start_time = time_uptime;
13396	getbinuptime(&io->io_hdr.start_bt);
13397#endif /* CTL_TIME_IO */
13398
13399	/* Map FE-specific LUN ID into global one. */
13400	io->io_hdr.nexus.targ_mapped_lun =
13401	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13402
13403	switch (io->io_hdr.io_type) {
13404	case CTL_IO_SCSI:
13405	case CTL_IO_TASK:
13406		if (ctl_debug & CTL_DEBUG_CDB)
13407			ctl_io_print(io);
13408		ctl_enqueue_incoming(io);
13409		break;
13410	default:
13411		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13412		return (EINVAL);
13413	}
13414
13415	return (CTL_RETVAL_COMPLETE);
13416}
13417
13418#ifdef CTL_IO_DELAY
13419static void
13420ctl_done_timer_wakeup(void *arg)
13421{
13422	union ctl_io *io;
13423
13424	io = (union ctl_io *)arg;
13425	ctl_done(io);
13426}
13427#endif /* CTL_IO_DELAY */
13428
13429void
13430ctl_serseq_done(union ctl_io *io)
13431{
13432	struct ctl_lun *lun = CTL_LUN(io);;
13433
13434	if (lun->be_lun == NULL ||
13435	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13436		return;
13437	mtx_lock(&lun->lun_lock);
13438	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13439	ctl_check_blocked(lun);
13440	mtx_unlock(&lun->lun_lock);
13441}
13442
13443void
13444ctl_done(union ctl_io *io)
13445{
13446
13447	/*
13448	 * Enable this to catch duplicate completion issues.
13449	 */
13450#if 0
13451	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13452		printf("%s: type %d msg %d cdb %x iptl: "
13453		       "%u:%u:%u tag 0x%04x "
13454		       "flag %#x status %x\n",
13455			__func__,
13456			io->io_hdr.io_type,
13457			io->io_hdr.msg_type,
13458			io->scsiio.cdb[0],
13459			io->io_hdr.nexus.initid,
13460			io->io_hdr.nexus.targ_port,
13461			io->io_hdr.nexus.targ_lun,
13462			(io->io_hdr.io_type ==
13463			CTL_IO_TASK) ?
13464			io->taskio.tag_num :
13465			io->scsiio.tag_num,
13466		        io->io_hdr.flags,
13467			io->io_hdr.status);
13468	} else
13469		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13470#endif
13471
13472	/*
13473	 * This is an internal copy of an I/O, and should not go through
13474	 * the normal done processing logic.
13475	 */
13476	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13477		return;
13478
13479#ifdef CTL_IO_DELAY
13480	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13481		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13482	} else {
13483		struct ctl_lun *lun = CTL_LUN(io);
13484
13485		if ((lun != NULL)
13486		 && (lun->delay_info.done_delay > 0)) {
13487
13488			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13489			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13490			callout_reset(&io->io_hdr.delay_callout,
13491				      lun->delay_info.done_delay * hz,
13492				      ctl_done_timer_wakeup, io);
13493			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13494				lun->delay_info.done_delay = 0;
13495			return;
13496		}
13497	}
13498#endif /* CTL_IO_DELAY */
13499
13500	ctl_enqueue_done(io);
13501}
13502
13503static void
13504ctl_work_thread(void *arg)
13505{
13506	struct ctl_thread *thr = (struct ctl_thread *)arg;
13507	struct ctl_softc *softc = thr->ctl_softc;
13508	union ctl_io *io;
13509	int retval;
13510
13511	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13512
13513	for (;;) {
13514		/*
13515		 * We handle the queues in this order:
13516		 * - ISC
13517		 * - done queue (to free up resources, unblock other commands)
13518		 * - RtR queue
13519		 * - incoming queue
13520		 *
13521		 * If those queues are empty, we break out of the loop and
13522		 * go to sleep.
13523		 */
13524		mtx_lock(&thr->queue_lock);
13525		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13526		if (io != NULL) {
13527			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13528			mtx_unlock(&thr->queue_lock);
13529			ctl_handle_isc(io);
13530			continue;
13531		}
13532		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13533		if (io != NULL) {
13534			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13535			/* clear any blocked commands, call fe_done */
13536			mtx_unlock(&thr->queue_lock);
13537			ctl_process_done(io);
13538			continue;
13539		}
13540		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13541		if (io != NULL) {
13542			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13543			mtx_unlock(&thr->queue_lock);
13544			if (io->io_hdr.io_type == CTL_IO_TASK)
13545				ctl_run_task(io);
13546			else
13547				ctl_scsiio_precheck(softc, &io->scsiio);
13548			continue;
13549		}
13550		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13551		if (io != NULL) {
13552			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13553			mtx_unlock(&thr->queue_lock);
13554			retval = ctl_scsiio(&io->scsiio);
13555			if (retval != CTL_RETVAL_COMPLETE)
13556				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13557			continue;
13558		}
13559
13560		/* Sleep until we have something to do. */
13561		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13562	}
13563}
13564
13565static void
13566ctl_lun_thread(void *arg)
13567{
13568	struct ctl_softc *softc = (struct ctl_softc *)arg;
13569	struct ctl_be_lun *be_lun;
13570
13571	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13572
13573	for (;;) {
13574		mtx_lock(&softc->ctl_lock);
13575		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13576		if (be_lun != NULL) {
13577			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13578			mtx_unlock(&softc->ctl_lock);
13579			ctl_create_lun(be_lun);
13580			continue;
13581		}
13582
13583		/* Sleep until we have something to do. */
13584		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13585		    PDROP | PRIBIO, "-", 0);
13586	}
13587}
13588
13589static void
13590ctl_thresh_thread(void *arg)
13591{
13592	struct ctl_softc *softc = (struct ctl_softc *)arg;
13593	struct ctl_lun *lun;
13594	struct ctl_logical_block_provisioning_page *page;
13595	const char *attr;
13596	union ctl_ha_msg msg;
13597	uint64_t thres, val;
13598	int i, e, set;
13599
13600	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13601
13602	for (;;) {
13603		mtx_lock(&softc->ctl_lock);
13604		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13605			if ((lun->flags & CTL_LUN_DISABLED) ||
13606			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13607			    lun->backend->lun_attr == NULL)
13608				continue;
13609			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13610			    softc->ha_mode == CTL_HA_MODE_XFER)
13611				continue;
13612			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13613				continue;
13614			e = 0;
13615			page = &lun->MODE_LBP;
13616			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13617				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13618					continue;
13619				thres = scsi_4btoul(page->descr[i].count);
13620				thres <<= CTL_LBP_EXPONENT;
13621				switch (page->descr[i].resource) {
13622				case 0x01:
13623					attr = "blocksavail";
13624					break;
13625				case 0x02:
13626					attr = "blocksused";
13627					break;
13628				case 0xf1:
13629					attr = "poolblocksavail";
13630					break;
13631				case 0xf2:
13632					attr = "poolblocksused";
13633					break;
13634				default:
13635					continue;
13636				}
13637				mtx_unlock(&softc->ctl_lock); // XXX
13638				val = lun->backend->lun_attr(
13639				    lun->be_lun->be_lun, attr);
13640				mtx_lock(&softc->ctl_lock);
13641				if (val == UINT64_MAX)
13642					continue;
13643				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13644				    == SLBPPD_ARMING_INC)
13645					e = (val >= thres);
13646				else
13647					e = (val <= thres);
13648				if (e)
13649					break;
13650			}
13651			mtx_lock(&lun->lun_lock);
13652			if (e) {
13653				scsi_u64to8b((uint8_t *)&page->descr[i] -
13654				    (uint8_t *)page, lun->ua_tpt_info);
13655				if (lun->lasttpt == 0 ||
13656				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13657					lun->lasttpt = time_uptime;
13658					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13659					set = 1;
13660				} else
13661					set = 0;
13662			} else {
13663				lun->lasttpt = 0;
13664				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13665				set = -1;
13666			}
13667			mtx_unlock(&lun->lun_lock);
13668			if (set != 0 &&
13669			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13670				/* Send msg to other side. */
13671				bzero(&msg.ua, sizeof(msg.ua));
13672				msg.hdr.msg_type = CTL_MSG_UA;
13673				msg.hdr.nexus.initid = -1;
13674				msg.hdr.nexus.targ_port = -1;
13675				msg.hdr.nexus.targ_lun = lun->lun;
13676				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13677				msg.ua.ua_all = 1;
13678				msg.ua.ua_set = (set > 0);
13679				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13680				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13681				mtx_unlock(&softc->ctl_lock); // XXX
13682				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13683				    sizeof(msg.ua), M_WAITOK);
13684				mtx_lock(&softc->ctl_lock);
13685			}
13686		}
13687		mtx_unlock(&softc->ctl_lock);
13688		pause("-", CTL_LBP_PERIOD * hz);
13689	}
13690}
13691
13692static void
13693ctl_enqueue_incoming(union ctl_io *io)
13694{
13695	struct ctl_softc *softc = CTL_SOFTC(io);
13696	struct ctl_thread *thr;
13697	u_int idx;
13698
13699	idx = (io->io_hdr.nexus.targ_port * 127 +
13700	       io->io_hdr.nexus.initid) % worker_threads;
13701	thr = &softc->threads[idx];
13702	mtx_lock(&thr->queue_lock);
13703	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13704	mtx_unlock(&thr->queue_lock);
13705	wakeup(thr);
13706}
13707
13708static void
13709ctl_enqueue_rtr(union ctl_io *io)
13710{
13711	struct ctl_softc *softc = CTL_SOFTC(io);
13712	struct ctl_thread *thr;
13713
13714	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13715	mtx_lock(&thr->queue_lock);
13716	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13717	mtx_unlock(&thr->queue_lock);
13718	wakeup(thr);
13719}
13720
13721static void
13722ctl_enqueue_done(union ctl_io *io)
13723{
13724	struct ctl_softc *softc = CTL_SOFTC(io);
13725	struct ctl_thread *thr;
13726
13727	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13728	mtx_lock(&thr->queue_lock);
13729	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13730	mtx_unlock(&thr->queue_lock);
13731	wakeup(thr);
13732}
13733
13734static void
13735ctl_enqueue_isc(union ctl_io *io)
13736{
13737	struct ctl_softc *softc = CTL_SOFTC(io);
13738	struct ctl_thread *thr;
13739
13740	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13741	mtx_lock(&thr->queue_lock);
13742	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13743	mtx_unlock(&thr->queue_lock);
13744	wakeup(thr);
13745}
13746
13747/*
13748 *  vim: ts=8
13749 */
13750