ctl.c revision 311421
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Portions of this software were developed by Edward Tomasz Napierala
8 * under sponsorship from the FreeBSD Foundation.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions, and the following disclaimer,
15 *    without modification.
16 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17 *    substantially similar to the "NO WARRANTY" disclaimer below
18 *    ("Disclaimer") and any redistribution must be conditioned upon
19 *    including a substantially similar Disclaimer requirement for further
20 *    binary redistribution.
21 *
22 * NO WARRANTY
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGES.
34 *
35 * $Id$
36 */
37/*
38 * CAM Target Layer, a SCSI device emulation subsystem.
39 *
40 * Author: Ken Merry <ken@FreeBSD.org>
41 */
42
43#define _CTL_C
44
45#include <sys/cdefs.h>
46__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 311421 2017-01-05 11:39:54Z 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*/0
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*/0,
336	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337	/*descr*/{}},
338	{{/*flags*/0,
339	  /*resource*/0,
340	  /*reserved*/{0, 0},
341	  /*count*/{0, 0, 0, 0}},
342	 {/*flags*/0,
343	  /*resource*/0,
344	  /*reserved*/{0, 0},
345	  /*count*/{0, 0, 0, 0}},
346	 {/*flags*/0,
347	  /*resource*/0,
348	  /*reserved*/{0, 0},
349	  /*count*/{0, 0, 0, 0}},
350	 {/*flags*/0,
351	  /*resource*/0,
352	  /*reserved*/{0, 0},
353	  /*count*/{0, 0, 0, 0}}
354	}
355};
356
357const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358	/*page_code*/SMS_CDDVD_CAPS_PAGE,
359	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360	/*caps1*/0x3f,
361	/*caps2*/0x00,
362	/*caps3*/0xf0,
363	/*caps4*/0x00,
364	/*caps5*/0x29,
365	/*caps6*/0x00,
366	/*obsolete*/{0, 0},
367	/*nvol_levels*/{0, 0},
368	/*buffer_size*/{8, 0},
369	/*obsolete2*/{0, 0},
370	/*reserved*/0,
371	/*digital*/0,
372	/*obsolete3*/0,
373	/*copy_management*/0,
374	/*reserved2*/0,
375	/*rotation_control*/0,
376	/*cur_write_speed*/0,
377	/*num_speed_descr*/0,
378};
379
380const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381	/*page_code*/SMS_CDDVD_CAPS_PAGE,
382	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383	/*caps1*/0,
384	/*caps2*/0,
385	/*caps3*/0,
386	/*caps4*/0,
387	/*caps5*/0,
388	/*caps6*/0,
389	/*obsolete*/{0, 0},
390	/*nvol_levels*/{0, 0},
391	/*buffer_size*/{0, 0},
392	/*obsolete2*/{0, 0},
393	/*reserved*/0,
394	/*digital*/0,
395	/*obsolete3*/0,
396	/*copy_management*/0,
397	/*reserved2*/0,
398	/*rotation_control*/0,
399	/*cur_write_speed*/0,
400	/*num_speed_descr*/0,
401};
402
403SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404static int worker_threads = -1;
405TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407    &worker_threads, 1, "Number of worker threads");
408static int ctl_debug = CTL_DEBUG_NONE;
409TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411    &ctl_debug, 0, "Enabled debug flags");
412
413/*
414 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
415 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
416 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
417 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
418 */
419#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
420
421static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
422				  int param);
423static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
424static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
425static int ctl_init(void);
426void ctl_shutdown(void);
427static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
428static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
429static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
430static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
431			      struct ctl_ooa *ooa_hdr,
432			      struct ctl_ooa_entry *kern_entries);
433static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
434		     struct thread *td);
435static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
436			 struct ctl_be_lun *be_lun);
437static int ctl_free_lun(struct ctl_lun *lun);
438static void ctl_create_lun(struct ctl_be_lun *be_lun);
439static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
440
441static int ctl_do_mode_select(union ctl_io *io);
442static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443			   uint64_t res_key, uint64_t sa_res_key,
444			   uint8_t type, uint32_t residx,
445			   struct ctl_scsiio *ctsio,
446			   struct scsi_per_res_out *cdb,
447			   struct scsi_per_res_out_parms* param);
448static void ctl_pro_preempt_other(struct ctl_lun *lun,
449				  union ctl_ha_msg *msg);
450static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
451static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457					 int alloc_len);
458static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459					 int alloc_len);
460static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466    bool seq);
467static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469    union ctl_io *pending_io, union ctl_io *ooa_io);
470static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471				union ctl_io *starting_io);
472static int ctl_check_blocked(struct ctl_lun *lun);
473static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474				const struct ctl_cmd_entry *entry,
475				struct ctl_scsiio *ctsio);
476static void ctl_failover_lun(union ctl_io *io);
477static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478			       struct ctl_scsiio *ctsio);
479static int ctl_scsiio(struct ctl_scsiio *ctsio);
480
481static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
482static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
483			    ctl_ua_type ua_type);
484static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
485			 ctl_ua_type ua_type);
486static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
487static int ctl_abort_task(union ctl_io *io);
488static int ctl_abort_task_set(union ctl_io *io);
489static int ctl_query_task(union ctl_io *io, int task_set);
490static int ctl_i_t_nexus_reset(union ctl_io *io);
491static int ctl_query_async_event(union ctl_io *io);
492static void ctl_run_task(union ctl_io *io);
493#ifdef CTL_IO_DELAY
494static void ctl_datamove_timer_wakeup(void *arg);
495static void ctl_done_timer_wakeup(void *arg);
496#endif /* CTL_IO_DELAY */
497
498static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501static void ctl_datamove_remote_write(union ctl_io *io);
502static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506				    ctl_ha_dt_cb callback);
507static void ctl_datamove_remote_read(union ctl_io *io);
508static void ctl_datamove_remote(union ctl_io *io);
509static void ctl_process_done(union ctl_io *io);
510static void ctl_lun_thread(void *arg);
511static void ctl_thresh_thread(void *arg);
512static void ctl_work_thread(void *arg);
513static void ctl_enqueue_incoming(union ctl_io *io);
514static void ctl_enqueue_rtr(union ctl_io *io);
515static void ctl_enqueue_done(union ctl_io *io);
516static void ctl_enqueue_isc(union ctl_io *io);
517static const struct ctl_cmd_entry *
518    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519static const struct ctl_cmd_entry *
520    ctl_validate_command(struct ctl_scsiio *ctsio);
521static int ctl_cmd_applicable(uint8_t lun_type,
522    const struct ctl_cmd_entry *entry);
523
524static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
525static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
526static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
527static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
528
529/*
530 * Load the serialization table.  This isn't very pretty, but is probably
531 * the easiest way to do it.
532 */
533#include "ctl_ser_table.c"
534
535/*
536 * We only need to define open, close and ioctl routines for this driver.
537 */
538static struct cdevsw ctl_cdevsw = {
539	.d_version =	D_VERSION,
540	.d_flags =	0,
541	.d_open =	ctl_open,
542	.d_close =	ctl_close,
543	.d_ioctl =	ctl_ioctl,
544	.d_name =	"ctl",
545};
546
547
548MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
549
550static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
551
552static moduledata_t ctl_moduledata = {
553	"ctl",
554	ctl_module_event_handler,
555	NULL
556};
557
558DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
559MODULE_VERSION(ctl, 1);
560
561static struct ctl_frontend ha_frontend =
562{
563	.name = "ha",
564};
565
566static void
567ctl_ha_datamove(union ctl_io *io)
568{
569	struct ctl_lun *lun;
570	struct ctl_sg_entry *sgl;
571	union ctl_ha_msg msg;
572	uint32_t sg_entries_sent;
573	int do_sg_copy, i, j;
574
575	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
576	memset(&msg.dt, 0, sizeof(msg.dt));
577	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
578	msg.hdr.original_sc = io->io_hdr.original_sc;
579	msg.hdr.serializing_sc = io;
580	msg.hdr.nexus = io->io_hdr.nexus;
581	msg.hdr.status = io->io_hdr.status;
582	msg.dt.flags = io->io_hdr.flags;
583
584	/*
585	 * We convert everything into a S/G list here.  We can't
586	 * pass by reference, only by value between controllers.
587	 * So we can't pass a pointer to the S/G list, only as many
588	 * S/G entries as we can fit in here.  If it's possible for
589	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
590	 * then we need to break this up into multiple transfers.
591	 */
592	if (io->scsiio.kern_sg_entries == 0) {
593		msg.dt.kern_sg_entries = 1;
594#if 0
595		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
596			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
597		} else {
598			/* XXX KDM use busdma here! */
599			msg.dt.sg_list[0].addr =
600			    (void *)vtophys(io->scsiio.kern_data_ptr);
601		}
602#else
603		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
604		    ("HA does not support BUS_ADDR"));
605		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
606#endif
607		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
608		do_sg_copy = 0;
609	} else {
610		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
611		do_sg_copy = 1;
612	}
613
614	msg.dt.kern_data_len = io->scsiio.kern_data_len;
615	msg.dt.kern_total_len = io->scsiio.kern_total_len;
616	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
617	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
618	msg.dt.sg_sequence = 0;
619
620	/*
621	 * Loop until we've sent all of the S/G entries.  On the
622	 * other end, we'll recompose these S/G entries into one
623	 * contiguous list before processing.
624	 */
625	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
626	    msg.dt.sg_sequence++) {
627		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
628		    sizeof(msg.dt.sg_list[0])),
629		    msg.dt.kern_sg_entries - sg_entries_sent);
630		if (do_sg_copy != 0) {
631			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
632			for (i = sg_entries_sent, j = 0;
633			     i < msg.dt.cur_sg_entries; i++, j++) {
634#if 0
635				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
636					msg.dt.sg_list[j].addr = sgl[i].addr;
637				} else {
638					/* XXX KDM use busdma here! */
639					msg.dt.sg_list[j].addr =
640					    (void *)vtophys(sgl[i].addr);
641				}
642#else
643				KASSERT((io->io_hdr.flags &
644				    CTL_FLAG_BUS_ADDR) == 0,
645				    ("HA does not support BUS_ADDR"));
646				msg.dt.sg_list[j].addr = sgl[i].addr;
647#endif
648				msg.dt.sg_list[j].len = sgl[i].len;
649			}
650		}
651
652		sg_entries_sent += msg.dt.cur_sg_entries;
653		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
654		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
655		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
656		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
657		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
658			io->io_hdr.port_status = 31341;
659			io->scsiio.be_move_done(io);
660			return;
661		}
662		msg.dt.sent_sg_entries = sg_entries_sent;
663	}
664
665	/*
666	 * Officially handover the request from us to peer.
667	 * If failover has just happened, then we must return error.
668	 * If failover happen just after, then it is not our problem.
669	 */
670	if (lun)
671		mtx_lock(&lun->lun_lock);
672	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
673		if (lun)
674			mtx_unlock(&lun->lun_lock);
675		io->io_hdr.port_status = 31342;
676		io->scsiio.be_move_done(io);
677		return;
678	}
679	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
680	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
681	if (lun)
682		mtx_unlock(&lun->lun_lock);
683}
684
685static void
686ctl_ha_done(union ctl_io *io)
687{
688	union ctl_ha_msg msg;
689
690	if (io->io_hdr.io_type == CTL_IO_SCSI) {
691		memset(&msg, 0, sizeof(msg));
692		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
693		msg.hdr.original_sc = io->io_hdr.original_sc;
694		msg.hdr.nexus = io->io_hdr.nexus;
695		msg.hdr.status = io->io_hdr.status;
696		msg.scsi.scsi_status = io->scsiio.scsi_status;
697		msg.scsi.tag_num = io->scsiio.tag_num;
698		msg.scsi.tag_type = io->scsiio.tag_type;
699		msg.scsi.sense_len = io->scsiio.sense_len;
700		msg.scsi.sense_residual = io->scsiio.sense_residual;
701		msg.scsi.residual = io->scsiio.residual;
702		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
703		    io->scsiio.sense_len);
704		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
705		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
706		    msg.scsi.sense_len, M_WAITOK);
707	}
708	ctl_free_io(io);
709}
710
711static void
712ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
713			    union ctl_ha_msg *msg_info)
714{
715	struct ctl_scsiio *ctsio;
716
717	if (msg_info->hdr.original_sc == NULL) {
718		printf("%s: original_sc == NULL!\n", __func__);
719		/* XXX KDM now what? */
720		return;
721	}
722
723	ctsio = &msg_info->hdr.original_sc->scsiio;
724	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
725	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
726	ctsio->io_hdr.status = msg_info->hdr.status;
727	ctsio->scsi_status = msg_info->scsi.scsi_status;
728	ctsio->sense_len = msg_info->scsi.sense_len;
729	ctsio->sense_residual = msg_info->scsi.sense_residual;
730	ctsio->residual = msg_info->scsi.residual;
731	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
732	       msg_info->scsi.sense_len);
733	ctl_enqueue_isc((union ctl_io *)ctsio);
734}
735
736static void
737ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
738				union ctl_ha_msg *msg_info)
739{
740	struct ctl_scsiio *ctsio;
741
742	if (msg_info->hdr.serializing_sc == NULL) {
743		printf("%s: serializing_sc == NULL!\n", __func__);
744		/* XXX KDM now what? */
745		return;
746	}
747
748	ctsio = &msg_info->hdr.serializing_sc->scsiio;
749	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
750	ctl_enqueue_isc((union ctl_io *)ctsio);
751}
752
753void
754ctl_isc_announce_lun(struct ctl_lun *lun)
755{
756	struct ctl_softc *softc = lun->ctl_softc;
757	union ctl_ha_msg *msg;
758	struct ctl_ha_msg_lun_pr_key pr_key;
759	int i, k;
760
761	if (softc->ha_link != CTL_HA_LINK_ONLINE)
762		return;
763	mtx_lock(&lun->lun_lock);
764	i = sizeof(msg->lun);
765	if (lun->lun_devid)
766		i += lun->lun_devid->len;
767	i += sizeof(pr_key) * lun->pr_key_count;
768alloc:
769	mtx_unlock(&lun->lun_lock);
770	msg = malloc(i, M_CTL, M_WAITOK);
771	mtx_lock(&lun->lun_lock);
772	k = sizeof(msg->lun);
773	if (lun->lun_devid)
774		k += lun->lun_devid->len;
775	k += sizeof(pr_key) * lun->pr_key_count;
776	if (i < k) {
777		free(msg, M_CTL);
778		i = k;
779		goto alloc;
780	}
781	bzero(&msg->lun, sizeof(msg->lun));
782	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
783	msg->hdr.nexus.targ_lun = lun->lun;
784	msg->hdr.nexus.targ_mapped_lun = lun->lun;
785	msg->lun.flags = lun->flags;
786	msg->lun.pr_generation = lun->pr_generation;
787	msg->lun.pr_res_idx = lun->pr_res_idx;
788	msg->lun.pr_res_type = lun->pr_res_type;
789	msg->lun.pr_key_count = lun->pr_key_count;
790	i = 0;
791	if (lun->lun_devid) {
792		msg->lun.lun_devid_len = lun->lun_devid->len;
793		memcpy(&msg->lun.data[i], lun->lun_devid->data,
794		    msg->lun.lun_devid_len);
795		i += msg->lun.lun_devid_len;
796	}
797	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
798		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
799			continue;
800		pr_key.pr_iid = k;
801		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
802		i += sizeof(pr_key);
803	}
804	mtx_unlock(&lun->lun_lock);
805	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
806	    M_WAITOK);
807	free(msg, M_CTL);
808
809	if (lun->flags & CTL_LUN_PRIMARY_SC) {
810		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
811			ctl_isc_announce_mode(lun, -1,
812			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
813			    lun->mode_pages.index[i].subpage);
814		}
815	}
816}
817
818void
819ctl_isc_announce_port(struct ctl_port *port)
820{
821	struct ctl_softc *softc = port->ctl_softc;
822	union ctl_ha_msg *msg;
823	int i;
824
825	if (port->targ_port < softc->port_min ||
826	    port->targ_port >= softc->port_max ||
827	    softc->ha_link != CTL_HA_LINK_ONLINE)
828		return;
829	i = sizeof(msg->port) + strlen(port->port_name) + 1;
830	if (port->lun_map)
831		i += sizeof(uint32_t) * CTL_MAX_LUNS;
832	if (port->port_devid)
833		i += port->port_devid->len;
834	if (port->target_devid)
835		i += port->target_devid->len;
836	if (port->init_devid)
837		i += port->init_devid->len;
838	msg = malloc(i, M_CTL, M_WAITOK);
839	bzero(&msg->port, sizeof(msg->port));
840	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
841	msg->hdr.nexus.targ_port = port->targ_port;
842	msg->port.port_type = port->port_type;
843	msg->port.physical_port = port->physical_port;
844	msg->port.virtual_port = port->virtual_port;
845	msg->port.status = port->status;
846	i = 0;
847	msg->port.name_len = sprintf(&msg->port.data[i],
848	    "%d:%s", softc->ha_id, port->port_name) + 1;
849	i += msg->port.name_len;
850	if (port->lun_map) {
851		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
852		memcpy(&msg->port.data[i], port->lun_map,
853		    msg->port.lun_map_len);
854		i += msg->port.lun_map_len;
855	}
856	if (port->port_devid) {
857		msg->port.port_devid_len = port->port_devid->len;
858		memcpy(&msg->port.data[i], port->port_devid->data,
859		    msg->port.port_devid_len);
860		i += msg->port.port_devid_len;
861	}
862	if (port->target_devid) {
863		msg->port.target_devid_len = port->target_devid->len;
864		memcpy(&msg->port.data[i], port->target_devid->data,
865		    msg->port.target_devid_len);
866		i += msg->port.target_devid_len;
867	}
868	if (port->init_devid) {
869		msg->port.init_devid_len = port->init_devid->len;
870		memcpy(&msg->port.data[i], port->init_devid->data,
871		    msg->port.init_devid_len);
872		i += msg->port.init_devid_len;
873	}
874	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
875	    M_WAITOK);
876	free(msg, M_CTL);
877}
878
879void
880ctl_isc_announce_iid(struct ctl_port *port, int iid)
881{
882	struct ctl_softc *softc = port->ctl_softc;
883	union ctl_ha_msg *msg;
884	int i, l;
885
886	if (port->targ_port < softc->port_min ||
887	    port->targ_port >= softc->port_max ||
888	    softc->ha_link != CTL_HA_LINK_ONLINE)
889		return;
890	mtx_lock(&softc->ctl_lock);
891	i = sizeof(msg->iid);
892	l = 0;
893	if (port->wwpn_iid[iid].name)
894		l = strlen(port->wwpn_iid[iid].name) + 1;
895	i += l;
896	msg = malloc(i, M_CTL, M_NOWAIT);
897	if (msg == NULL) {
898		mtx_unlock(&softc->ctl_lock);
899		return;
900	}
901	bzero(&msg->iid, sizeof(msg->iid));
902	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
903	msg->hdr.nexus.targ_port = port->targ_port;
904	msg->hdr.nexus.initid = iid;
905	msg->iid.in_use = port->wwpn_iid[iid].in_use;
906	msg->iid.name_len = l;
907	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
908	if (port->wwpn_iid[iid].name)
909		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
910	mtx_unlock(&softc->ctl_lock);
911	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
912	free(msg, M_CTL);
913}
914
915void
916ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
917    uint8_t page, uint8_t subpage)
918{
919	struct ctl_softc *softc = lun->ctl_softc;
920	union ctl_ha_msg msg;
921	u_int i;
922
923	if (softc->ha_link != CTL_HA_LINK_ONLINE)
924		return;
925	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
926		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
927		    page && lun->mode_pages.index[i].subpage == subpage)
928			break;
929	}
930	if (i == CTL_NUM_MODE_PAGES)
931		return;
932
933	/* Don't try to replicate pages not present on this device. */
934	if (lun->mode_pages.index[i].page_data == NULL)
935		return;
936
937	bzero(&msg.mode, sizeof(msg.mode));
938	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
939	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
940	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
941	msg.hdr.nexus.targ_lun = lun->lun;
942	msg.hdr.nexus.targ_mapped_lun = lun->lun;
943	msg.mode.page_code = page;
944	msg.mode.subpage = subpage;
945	msg.mode.page_len = lun->mode_pages.index[i].page_len;
946	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
947	    msg.mode.page_len);
948	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
949	    M_WAITOK);
950}
951
952static void
953ctl_isc_ha_link_up(struct ctl_softc *softc)
954{
955	struct ctl_port *port;
956	struct ctl_lun *lun;
957	union ctl_ha_msg msg;
958	int i;
959
960	/* Announce this node parameters to peer for validation. */
961	msg.login.msg_type = CTL_MSG_LOGIN;
962	msg.login.version = CTL_HA_VERSION;
963	msg.login.ha_mode = softc->ha_mode;
964	msg.login.ha_id = softc->ha_id;
965	msg.login.max_luns = CTL_MAX_LUNS;
966	msg.login.max_ports = CTL_MAX_PORTS;
967	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
968	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
969	    M_WAITOK);
970
971	STAILQ_FOREACH(port, &softc->port_list, links) {
972		ctl_isc_announce_port(port);
973		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
974			if (port->wwpn_iid[i].in_use)
975				ctl_isc_announce_iid(port, i);
976		}
977	}
978	STAILQ_FOREACH(lun, &softc->lun_list, links)
979		ctl_isc_announce_lun(lun);
980}
981
982static void
983ctl_isc_ha_link_down(struct ctl_softc *softc)
984{
985	struct ctl_port *port;
986	struct ctl_lun *lun;
987	union ctl_io *io;
988	int i;
989
990	mtx_lock(&softc->ctl_lock);
991	STAILQ_FOREACH(lun, &softc->lun_list, links) {
992		mtx_lock(&lun->lun_lock);
993		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
994			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
995			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
996		}
997		mtx_unlock(&lun->lun_lock);
998
999		mtx_unlock(&softc->ctl_lock);
1000		io = ctl_alloc_io(softc->othersc_pool);
1001		mtx_lock(&softc->ctl_lock);
1002		ctl_zero_io(io);
1003		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1004		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1005		ctl_enqueue_isc(io);
1006	}
1007
1008	STAILQ_FOREACH(port, &softc->port_list, links) {
1009		if (port->targ_port >= softc->port_min &&
1010		    port->targ_port < softc->port_max)
1011			continue;
1012		port->status &= ~CTL_PORT_STATUS_ONLINE;
1013		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1014			port->wwpn_iid[i].in_use = 0;
1015			free(port->wwpn_iid[i].name, M_CTL);
1016			port->wwpn_iid[i].name = NULL;
1017		}
1018	}
1019	mtx_unlock(&softc->ctl_lock);
1020}
1021
1022static void
1023ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1024{
1025	struct ctl_lun *lun;
1026	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1027
1028	mtx_lock(&softc->ctl_lock);
1029	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1030	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1031		mtx_lock(&lun->lun_lock);
1032		mtx_unlock(&softc->ctl_lock);
1033		if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1034		    msg->ua.ua_set)
1035			memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1036		if (msg->ua.ua_all) {
1037			if (msg->ua.ua_set)
1038				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1039			else
1040				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1041		} else {
1042			if (msg->ua.ua_set)
1043				ctl_est_ua(lun, iid, msg->ua.ua_type);
1044			else
1045				ctl_clr_ua(lun, iid, msg->ua.ua_type);
1046		}
1047		mtx_unlock(&lun->lun_lock);
1048	} else
1049		mtx_unlock(&softc->ctl_lock);
1050}
1051
1052static void
1053ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1054{
1055	struct ctl_lun *lun;
1056	struct ctl_ha_msg_lun_pr_key pr_key;
1057	int i, k;
1058	ctl_lun_flags oflags;
1059	uint32_t targ_lun;
1060
1061	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1062	mtx_lock(&softc->ctl_lock);
1063	if ((targ_lun >= CTL_MAX_LUNS) ||
1064	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1065		mtx_unlock(&softc->ctl_lock);
1066		return;
1067	}
1068	mtx_lock(&lun->lun_lock);
1069	mtx_unlock(&softc->ctl_lock);
1070	if (lun->flags & CTL_LUN_DISABLED) {
1071		mtx_unlock(&lun->lun_lock);
1072		return;
1073	}
1074	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1075	if (msg->lun.lun_devid_len != i || (i > 0 &&
1076	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1077		mtx_unlock(&lun->lun_lock);
1078		printf("%s: Received conflicting HA LUN %d\n",
1079		    __func__, msg->hdr.nexus.targ_lun);
1080		return;
1081	} else {
1082		/* Record whether peer is primary. */
1083		oflags = lun->flags;
1084		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1085		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1086			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1087		else
1088			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1089		if (oflags != lun->flags)
1090			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1091
1092		/* If peer is primary and we are not -- use data */
1093		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1094		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1095			lun->pr_generation = msg->lun.pr_generation;
1096			lun->pr_res_idx = msg->lun.pr_res_idx;
1097			lun->pr_res_type = msg->lun.pr_res_type;
1098			lun->pr_key_count = msg->lun.pr_key_count;
1099			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1100				ctl_clr_prkey(lun, k);
1101			for (k = 0; k < msg->lun.pr_key_count; k++) {
1102				memcpy(&pr_key, &msg->lun.data[i],
1103				    sizeof(pr_key));
1104				ctl_alloc_prkey(lun, pr_key.pr_iid);
1105				ctl_set_prkey(lun, pr_key.pr_iid,
1106				    pr_key.pr_key);
1107				i += sizeof(pr_key);
1108			}
1109		}
1110
1111		mtx_unlock(&lun->lun_lock);
1112		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1113		    __func__, msg->hdr.nexus.targ_lun,
1114		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1115		    "primary" : "secondary"));
1116
1117		/* If we are primary but peer doesn't know -- notify */
1118		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1119		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1120			ctl_isc_announce_lun(lun);
1121	}
1122}
1123
1124static void
1125ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1126{
1127	struct ctl_port *port;
1128	struct ctl_lun *lun;
1129	int i, new;
1130
1131	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1132	if (port == NULL) {
1133		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1134		    msg->hdr.nexus.targ_port));
1135		new = 1;
1136		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1137		port->frontend = &ha_frontend;
1138		port->targ_port = msg->hdr.nexus.targ_port;
1139		port->fe_datamove = ctl_ha_datamove;
1140		port->fe_done = ctl_ha_done;
1141	} else if (port->frontend == &ha_frontend) {
1142		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1143		    msg->hdr.nexus.targ_port));
1144		new = 0;
1145	} else {
1146		printf("%s: Received conflicting HA port %d\n",
1147		    __func__, msg->hdr.nexus.targ_port);
1148		return;
1149	}
1150	port->port_type = msg->port.port_type;
1151	port->physical_port = msg->port.physical_port;
1152	port->virtual_port = msg->port.virtual_port;
1153	port->status = msg->port.status;
1154	i = 0;
1155	free(port->port_name, M_CTL);
1156	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1157	    M_CTL);
1158	i += msg->port.name_len;
1159	if (msg->port.lun_map_len != 0) {
1160		if (port->lun_map == NULL)
1161			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1162			    M_CTL, M_WAITOK);
1163		memcpy(port->lun_map, &msg->port.data[i],
1164		    sizeof(uint32_t) * CTL_MAX_LUNS);
1165		i += msg->port.lun_map_len;
1166	} else {
1167		free(port->lun_map, M_CTL);
1168		port->lun_map = NULL;
1169	}
1170	if (msg->port.port_devid_len != 0) {
1171		if (port->port_devid == NULL ||
1172		    port->port_devid->len != msg->port.port_devid_len) {
1173			free(port->port_devid, M_CTL);
1174			port->port_devid = malloc(sizeof(struct ctl_devid) +
1175			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1176		}
1177		memcpy(port->port_devid->data, &msg->port.data[i],
1178		    msg->port.port_devid_len);
1179		port->port_devid->len = msg->port.port_devid_len;
1180		i += msg->port.port_devid_len;
1181	} else {
1182		free(port->port_devid, M_CTL);
1183		port->port_devid = NULL;
1184	}
1185	if (msg->port.target_devid_len != 0) {
1186		if (port->target_devid == NULL ||
1187		    port->target_devid->len != msg->port.target_devid_len) {
1188			free(port->target_devid, M_CTL);
1189			port->target_devid = malloc(sizeof(struct ctl_devid) +
1190			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1191		}
1192		memcpy(port->target_devid->data, &msg->port.data[i],
1193		    msg->port.target_devid_len);
1194		port->target_devid->len = msg->port.target_devid_len;
1195		i += msg->port.target_devid_len;
1196	} else {
1197		free(port->target_devid, M_CTL);
1198		port->target_devid = NULL;
1199	}
1200	if (msg->port.init_devid_len != 0) {
1201		if (port->init_devid == NULL ||
1202		    port->init_devid->len != msg->port.init_devid_len) {
1203			free(port->init_devid, M_CTL);
1204			port->init_devid = malloc(sizeof(struct ctl_devid) +
1205			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1206		}
1207		memcpy(port->init_devid->data, &msg->port.data[i],
1208		    msg->port.init_devid_len);
1209		port->init_devid->len = msg->port.init_devid_len;
1210		i += msg->port.init_devid_len;
1211	} else {
1212		free(port->init_devid, M_CTL);
1213		port->init_devid = NULL;
1214	}
1215	if (new) {
1216		if (ctl_port_register(port) != 0) {
1217			printf("%s: ctl_port_register() failed with error\n",
1218			    __func__);
1219		}
1220	}
1221	mtx_lock(&softc->ctl_lock);
1222	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1223		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1224			continue;
1225		mtx_lock(&lun->lun_lock);
1226		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1227		mtx_unlock(&lun->lun_lock);
1228	}
1229	mtx_unlock(&softc->ctl_lock);
1230}
1231
1232static void
1233ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1234{
1235	struct ctl_port *port;
1236	int iid;
1237
1238	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1239	if (port == NULL) {
1240		printf("%s: Received IID for unknown port %d\n",
1241		    __func__, msg->hdr.nexus.targ_port);
1242		return;
1243	}
1244	iid = msg->hdr.nexus.initid;
1245	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1246	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1247	free(port->wwpn_iid[iid].name, M_CTL);
1248	if (msg->iid.name_len) {
1249		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1250		    msg->iid.name_len, M_CTL);
1251	} else
1252		port->wwpn_iid[iid].name = NULL;
1253}
1254
1255static void
1256ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1257{
1258
1259	if (msg->login.version != CTL_HA_VERSION) {
1260		printf("CTL HA peers have different versions %d != %d\n",
1261		    msg->login.version, CTL_HA_VERSION);
1262		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1263		return;
1264	}
1265	if (msg->login.ha_mode != softc->ha_mode) {
1266		printf("CTL HA peers have different ha_mode %d != %d\n",
1267		    msg->login.ha_mode, softc->ha_mode);
1268		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1269		return;
1270	}
1271	if (msg->login.ha_id == softc->ha_id) {
1272		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1273		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1274		return;
1275	}
1276	if (msg->login.max_luns != CTL_MAX_LUNS ||
1277	    msg->login.max_ports != CTL_MAX_PORTS ||
1278	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1279		printf("CTL HA peers have different limits\n");
1280		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1281		return;
1282	}
1283}
1284
1285static void
1286ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1287{
1288	struct ctl_lun *lun;
1289	u_int i;
1290	uint32_t initidx, targ_lun;
1291
1292	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1293	mtx_lock(&softc->ctl_lock);
1294	if ((targ_lun >= CTL_MAX_LUNS) ||
1295	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1296		mtx_unlock(&softc->ctl_lock);
1297		return;
1298	}
1299	mtx_lock(&lun->lun_lock);
1300	mtx_unlock(&softc->ctl_lock);
1301	if (lun->flags & CTL_LUN_DISABLED) {
1302		mtx_unlock(&lun->lun_lock);
1303		return;
1304	}
1305	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1306		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1307		    msg->mode.page_code &&
1308		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1309			break;
1310	}
1311	if (i == CTL_NUM_MODE_PAGES) {
1312		mtx_unlock(&lun->lun_lock);
1313		return;
1314	}
1315	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1316	    lun->mode_pages.index[i].page_len);
1317	initidx = ctl_get_initindex(&msg->hdr.nexus);
1318	if (initidx != -1)
1319		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1320	mtx_unlock(&lun->lun_lock);
1321}
1322
1323/*
1324 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1325 * subsystem come in here.
1326 */
1327static void
1328ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1329{
1330	struct ctl_softc *softc = control_softc;
1331	union ctl_io *io;
1332	struct ctl_prio *presio;
1333	ctl_ha_status isc_status;
1334
1335	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1336	if (event == CTL_HA_EVT_MSG_RECV) {
1337		union ctl_ha_msg *msg, msgbuf;
1338
1339		if (param > sizeof(msgbuf))
1340			msg = malloc(param, M_CTL, M_WAITOK);
1341		else
1342			msg = &msgbuf;
1343		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1344		    M_WAITOK);
1345		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1346			printf("%s: Error receiving message: %d\n",
1347			    __func__, isc_status);
1348			if (msg != &msgbuf)
1349				free(msg, M_CTL);
1350			return;
1351		}
1352
1353		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1354		switch (msg->hdr.msg_type) {
1355		case CTL_MSG_SERIALIZE:
1356			io = ctl_alloc_io(softc->othersc_pool);
1357			ctl_zero_io(io);
1358			// populate ctsio from msg
1359			io->io_hdr.io_type = CTL_IO_SCSI;
1360			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1361			io->io_hdr.original_sc = msg->hdr.original_sc;
1362			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1363					    CTL_FLAG_IO_ACTIVE;
1364			/*
1365			 * If we're in serialization-only mode, we don't
1366			 * want to go through full done processing.  Thus
1367			 * the COPY flag.
1368			 *
1369			 * XXX KDM add another flag that is more specific.
1370			 */
1371			if (softc->ha_mode != CTL_HA_MODE_XFER)
1372				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1373			io->io_hdr.nexus = msg->hdr.nexus;
1374#if 0
1375			printf("port %u, iid %u, lun %u\n",
1376			       io->io_hdr.nexus.targ_port,
1377			       io->io_hdr.nexus.initid,
1378			       io->io_hdr.nexus.targ_lun);
1379#endif
1380			io->scsiio.tag_num = msg->scsi.tag_num;
1381			io->scsiio.tag_type = msg->scsi.tag_type;
1382#ifdef CTL_TIME_IO
1383			io->io_hdr.start_time = time_uptime;
1384			getbinuptime(&io->io_hdr.start_bt);
1385#endif /* CTL_TIME_IO */
1386			io->scsiio.cdb_len = msg->scsi.cdb_len;
1387			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1388			       CTL_MAX_CDBLEN);
1389			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1390				const struct ctl_cmd_entry *entry;
1391
1392				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1393				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1394				io->io_hdr.flags |=
1395					entry->flags & CTL_FLAG_DATA_MASK;
1396			}
1397			ctl_enqueue_isc(io);
1398			break;
1399
1400		/* Performed on the Originating SC, XFER mode only */
1401		case CTL_MSG_DATAMOVE: {
1402			struct ctl_sg_entry *sgl;
1403			int i, j;
1404
1405			io = msg->hdr.original_sc;
1406			if (io == NULL) {
1407				printf("%s: original_sc == NULL!\n", __func__);
1408				/* XXX KDM do something here */
1409				break;
1410			}
1411			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1412			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1413			/*
1414			 * Keep track of this, we need to send it back over
1415			 * when the datamove is complete.
1416			 */
1417			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1418			if (msg->hdr.status == CTL_SUCCESS)
1419				io->io_hdr.status = msg->hdr.status;
1420
1421			if (msg->dt.sg_sequence == 0) {
1422#ifdef CTL_TIME_IO
1423				getbinuptime(&io->io_hdr.dma_start_bt);
1424#endif
1425				i = msg->dt.kern_sg_entries +
1426				    msg->dt.kern_data_len /
1427				    CTL_HA_DATAMOVE_SEGMENT + 1;
1428				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1429				    M_WAITOK | M_ZERO);
1430				io->io_hdr.remote_sglist = sgl;
1431				io->io_hdr.local_sglist =
1432				    &sgl[msg->dt.kern_sg_entries];
1433
1434				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1435
1436				io->scsiio.kern_sg_entries =
1437					msg->dt.kern_sg_entries;
1438				io->scsiio.rem_sg_entries =
1439					msg->dt.kern_sg_entries;
1440				io->scsiio.kern_data_len =
1441					msg->dt.kern_data_len;
1442				io->scsiio.kern_total_len =
1443					msg->dt.kern_total_len;
1444				io->scsiio.kern_data_resid =
1445					msg->dt.kern_data_resid;
1446				io->scsiio.kern_rel_offset =
1447					msg->dt.kern_rel_offset;
1448				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1449				io->io_hdr.flags |= msg->dt.flags &
1450				    CTL_FLAG_BUS_ADDR;
1451			} else
1452				sgl = (struct ctl_sg_entry *)
1453					io->scsiio.kern_data_ptr;
1454
1455			for (i = msg->dt.sent_sg_entries, j = 0;
1456			     i < (msg->dt.sent_sg_entries +
1457			     msg->dt.cur_sg_entries); i++, j++) {
1458				sgl[i].addr = msg->dt.sg_list[j].addr;
1459				sgl[i].len = msg->dt.sg_list[j].len;
1460
1461#if 0
1462				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1463				    __func__, sgl[i].addr, sgl[i].len, j, i);
1464#endif
1465			}
1466
1467			/*
1468			 * If this is the last piece of the I/O, we've got
1469			 * the full S/G list.  Queue processing in the thread.
1470			 * Otherwise wait for the next piece.
1471			 */
1472			if (msg->dt.sg_last != 0)
1473				ctl_enqueue_isc(io);
1474			break;
1475		}
1476		/* Performed on the Serializing (primary) SC, XFER mode only */
1477		case CTL_MSG_DATAMOVE_DONE: {
1478			if (msg->hdr.serializing_sc == NULL) {
1479				printf("%s: serializing_sc == NULL!\n",
1480				       __func__);
1481				/* XXX KDM now what? */
1482				break;
1483			}
1484			/*
1485			 * We grab the sense information here in case
1486			 * there was a failure, so we can return status
1487			 * back to the initiator.
1488			 */
1489			io = msg->hdr.serializing_sc;
1490			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1491			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1492			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1493			io->io_hdr.port_status = msg->scsi.fetd_status;
1494			io->scsiio.residual = msg->scsi.residual;
1495			if (msg->hdr.status != CTL_STATUS_NONE) {
1496				io->io_hdr.status = msg->hdr.status;
1497				io->scsiio.scsi_status = msg->scsi.scsi_status;
1498				io->scsiio.sense_len = msg->scsi.sense_len;
1499				io->scsiio.sense_residual =msg->scsi.sense_residual;
1500				memcpy(&io->scsiio.sense_data,
1501				    &msg->scsi.sense_data,
1502				    msg->scsi.sense_len);
1503				if (msg->hdr.status == CTL_SUCCESS)
1504					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1505			}
1506			ctl_enqueue_isc(io);
1507			break;
1508		}
1509
1510		/* Preformed on Originating SC, SER_ONLY mode */
1511		case CTL_MSG_R2R:
1512			io = msg->hdr.original_sc;
1513			if (io == NULL) {
1514				printf("%s: original_sc == NULL!\n",
1515				    __func__);
1516				break;
1517			}
1518			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1519			io->io_hdr.msg_type = CTL_MSG_R2R;
1520			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1521			ctl_enqueue_isc(io);
1522			break;
1523
1524		/*
1525		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1526		 * mode.
1527		 * Performed on the Originating (i.e. secondary) SC in XFER
1528		 * mode
1529		 */
1530		case CTL_MSG_FINISH_IO:
1531			if (softc->ha_mode == CTL_HA_MODE_XFER)
1532				ctl_isc_handler_finish_xfer(softc, msg);
1533			else
1534				ctl_isc_handler_finish_ser_only(softc, msg);
1535			break;
1536
1537		/* Preformed on Originating SC */
1538		case CTL_MSG_BAD_JUJU:
1539			io = msg->hdr.original_sc;
1540			if (io == NULL) {
1541				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1542				       __func__);
1543				break;
1544			}
1545			ctl_copy_sense_data(msg, io);
1546			/*
1547			 * IO should have already been cleaned up on other
1548			 * SC so clear this flag so we won't send a message
1549			 * back to finish the IO there.
1550			 */
1551			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1552			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1553
1554			/* io = msg->hdr.serializing_sc; */
1555			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1556			ctl_enqueue_isc(io);
1557			break;
1558
1559		/* Handle resets sent from the other side */
1560		case CTL_MSG_MANAGE_TASKS: {
1561			struct ctl_taskio *taskio;
1562			taskio = (struct ctl_taskio *)ctl_alloc_io(
1563			    softc->othersc_pool);
1564			ctl_zero_io((union ctl_io *)taskio);
1565			taskio->io_hdr.io_type = CTL_IO_TASK;
1566			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1567			taskio->io_hdr.nexus = msg->hdr.nexus;
1568			taskio->task_action = msg->task.task_action;
1569			taskio->tag_num = msg->task.tag_num;
1570			taskio->tag_type = msg->task.tag_type;
1571#ifdef CTL_TIME_IO
1572			taskio->io_hdr.start_time = time_uptime;
1573			getbinuptime(&taskio->io_hdr.start_bt);
1574#endif /* CTL_TIME_IO */
1575			ctl_run_task((union ctl_io *)taskio);
1576			break;
1577		}
1578		/* Persistent Reserve action which needs attention */
1579		case CTL_MSG_PERS_ACTION:
1580			presio = (struct ctl_prio *)ctl_alloc_io(
1581			    softc->othersc_pool);
1582			ctl_zero_io((union ctl_io *)presio);
1583			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1584			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1585			presio->io_hdr.nexus = msg->hdr.nexus;
1586			presio->pr_msg = msg->pr;
1587			ctl_enqueue_isc((union ctl_io *)presio);
1588			break;
1589		case CTL_MSG_UA:
1590			ctl_isc_ua(softc, msg, param);
1591			break;
1592		case CTL_MSG_PORT_SYNC:
1593			ctl_isc_port_sync(softc, msg, param);
1594			break;
1595		case CTL_MSG_LUN_SYNC:
1596			ctl_isc_lun_sync(softc, msg, param);
1597			break;
1598		case CTL_MSG_IID_SYNC:
1599			ctl_isc_iid_sync(softc, msg, param);
1600			break;
1601		case CTL_MSG_LOGIN:
1602			ctl_isc_login(softc, msg, param);
1603			break;
1604		case CTL_MSG_MODE_SYNC:
1605			ctl_isc_mode_sync(softc, msg, param);
1606			break;
1607		default:
1608			printf("Received HA message of unknown type %d\n",
1609			    msg->hdr.msg_type);
1610			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1611			break;
1612		}
1613		if (msg != &msgbuf)
1614			free(msg, M_CTL);
1615	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1616		printf("CTL: HA link status changed from %d to %d\n",
1617		    softc->ha_link, param);
1618		if (param == softc->ha_link)
1619			return;
1620		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1621			softc->ha_link = param;
1622			ctl_isc_ha_link_down(softc);
1623		} else {
1624			softc->ha_link = param;
1625			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1626				ctl_isc_ha_link_up(softc);
1627		}
1628		return;
1629	} else {
1630		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1631		return;
1632	}
1633}
1634
1635static void
1636ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1637{
1638
1639	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1640	    src->scsi.sense_len);
1641	dest->scsiio.scsi_status = src->scsi.scsi_status;
1642	dest->scsiio.sense_len = src->scsi.sense_len;
1643	dest->io_hdr.status = src->hdr.status;
1644}
1645
1646static void
1647ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1648{
1649
1650	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1651	    src->scsiio.sense_len);
1652	dest->scsi.scsi_status = src->scsiio.scsi_status;
1653	dest->scsi.sense_len = src->scsiio.sense_len;
1654	dest->hdr.status = src->io_hdr.status;
1655}
1656
1657void
1658ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1659{
1660	struct ctl_softc *softc = lun->ctl_softc;
1661	ctl_ua_type *pu;
1662
1663	if (initidx < softc->init_min || initidx >= softc->init_max)
1664		return;
1665	mtx_assert(&lun->lun_lock, MA_OWNED);
1666	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1667	if (pu == NULL)
1668		return;
1669	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1670}
1671
1672void
1673ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1674{
1675	int i;
1676
1677	mtx_assert(&lun->lun_lock, MA_OWNED);
1678	if (lun->pending_ua[port] == NULL)
1679		return;
1680	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1681		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1682			continue;
1683		lun->pending_ua[port][i] |= ua;
1684	}
1685}
1686
1687void
1688ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1689{
1690	struct ctl_softc *softc = lun->ctl_softc;
1691	int i;
1692
1693	mtx_assert(&lun->lun_lock, MA_OWNED);
1694	for (i = softc->port_min; i < softc->port_max; i++)
1695		ctl_est_ua_port(lun, i, except, ua);
1696}
1697
1698void
1699ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1700{
1701	struct ctl_softc *softc = lun->ctl_softc;
1702	ctl_ua_type *pu;
1703
1704	if (initidx < softc->init_min || initidx >= softc->init_max)
1705		return;
1706	mtx_assert(&lun->lun_lock, MA_OWNED);
1707	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1708	if (pu == NULL)
1709		return;
1710	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1711}
1712
1713void
1714ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1715{
1716	struct ctl_softc *softc = lun->ctl_softc;
1717	int i, j;
1718
1719	mtx_assert(&lun->lun_lock, MA_OWNED);
1720	for (i = softc->port_min; i < softc->port_max; i++) {
1721		if (lun->pending_ua[i] == NULL)
1722			continue;
1723		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1724			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1725				continue;
1726			lun->pending_ua[i][j] &= ~ua;
1727		}
1728	}
1729}
1730
1731void
1732ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1733    ctl_ua_type ua_type)
1734{
1735	struct ctl_lun *lun;
1736
1737	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1738	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1739		mtx_lock(&lun->lun_lock);
1740		ctl_clr_ua(lun, initidx, ua_type);
1741		mtx_unlock(&lun->lun_lock);
1742	}
1743}
1744
1745static int
1746ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1747{
1748	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1749	struct ctl_lun *lun;
1750	struct ctl_lun_req ireq;
1751	int error, value;
1752
1753	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1754	error = sysctl_handle_int(oidp, &value, 0, req);
1755	if ((error != 0) || (req->newptr == NULL))
1756		return (error);
1757
1758	mtx_lock(&softc->ctl_lock);
1759	if (value == 0)
1760		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1761	else
1762		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1763	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1764		mtx_unlock(&softc->ctl_lock);
1765		bzero(&ireq, sizeof(ireq));
1766		ireq.reqtype = CTL_LUNREQ_MODIFY;
1767		ireq.reqdata.modify.lun_id = lun->lun;
1768		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1769		    curthread);
1770		if (ireq.status != CTL_LUN_OK) {
1771			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1772			    __func__, ireq.status, ireq.error_str);
1773		}
1774		mtx_lock(&softc->ctl_lock);
1775	}
1776	mtx_unlock(&softc->ctl_lock);
1777	return (0);
1778}
1779
1780static int
1781ctl_init(void)
1782{
1783	struct make_dev_args args;
1784	struct ctl_softc *softc;
1785	void *other_pool;
1786	int i, error;
1787
1788	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1789			       M_WAITOK | M_ZERO);
1790
1791	make_dev_args_init(&args);
1792	args.mda_devsw = &ctl_cdevsw;
1793	args.mda_uid = UID_ROOT;
1794	args.mda_gid = GID_OPERATOR;
1795	args.mda_mode = 0600;
1796	args.mda_si_drv1 = softc;
1797	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1798	if (error != 0) {
1799		free(control_softc, M_DEVBUF);
1800		return (error);
1801	}
1802
1803	sysctl_ctx_init(&softc->sysctl_ctx);
1804	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1805		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1806		CTLFLAG_RD, 0, "CAM Target Layer");
1807
1808	if (softc->sysctl_tree == NULL) {
1809		printf("%s: unable to allocate sysctl tree\n", __func__);
1810		destroy_dev(softc->dev);
1811		free(control_softc, M_DEVBUF);
1812		control_softc = NULL;
1813		return (ENOMEM);
1814	}
1815
1816	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1817	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1818	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1819	softc->flags = 0;
1820
1821	TUNABLE_INT_FETCH("kern.cam.ctl.ha_mode", (int *)&softc->ha_mode);
1822	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1823	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1824	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1825
1826	/*
1827	 * In Copan's HA scheme, the "master" and "slave" roles are
1828	 * figured out through the slot the controller is in.  Although it
1829	 * is an active/active system, someone has to be in charge.
1830	 */
1831	TUNABLE_INT_FETCH("kern.cam.ctl.ha_id", &softc->ha_id);
1832	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1833	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1834	    "HA head ID (0 - no HA)");
1835	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1836		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1837		softc->is_single = 1;
1838		softc->port_cnt = CTL_MAX_PORTS;
1839		softc->port_min = 0;
1840	} else {
1841		softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1842		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1843	}
1844	softc->port_max = softc->port_min + softc->port_cnt;
1845	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1846	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1847
1848	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1849	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1850	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1851
1852	STAILQ_INIT(&softc->lun_list);
1853	STAILQ_INIT(&softc->pending_lun_queue);
1854	STAILQ_INIT(&softc->fe_list);
1855	STAILQ_INIT(&softc->port_list);
1856	STAILQ_INIT(&softc->be_list);
1857	ctl_tpc_init(softc);
1858
1859	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1860	                    &other_pool) != 0)
1861	{
1862		printf("ctl: can't allocate %d entry other SC pool, "
1863		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1864		return (ENOMEM);
1865	}
1866	softc->othersc_pool = other_pool;
1867
1868	if (worker_threads <= 0)
1869		worker_threads = max(1, mp_ncpus / 4);
1870	if (worker_threads > CTL_MAX_THREADS)
1871		worker_threads = CTL_MAX_THREADS;
1872
1873	for (i = 0; i < worker_threads; i++) {
1874		struct ctl_thread *thr = &softc->threads[i];
1875
1876		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1877		thr->ctl_softc = softc;
1878		STAILQ_INIT(&thr->incoming_queue);
1879		STAILQ_INIT(&thr->rtr_queue);
1880		STAILQ_INIT(&thr->done_queue);
1881		STAILQ_INIT(&thr->isc_queue);
1882
1883		error = kproc_kthread_add(ctl_work_thread, thr,
1884		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1885		if (error != 0) {
1886			printf("error creating CTL work thread!\n");
1887			ctl_pool_free(other_pool);
1888			return (error);
1889		}
1890	}
1891	error = kproc_kthread_add(ctl_lun_thread, softc,
1892	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1893	if (error != 0) {
1894		printf("error creating CTL lun thread!\n");
1895		ctl_pool_free(other_pool);
1896		return (error);
1897	}
1898	error = kproc_kthread_add(ctl_thresh_thread, softc,
1899	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1900	if (error != 0) {
1901		printf("error creating CTL threshold thread!\n");
1902		ctl_pool_free(other_pool);
1903		return (error);
1904	}
1905
1906	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1907	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1908	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1909
1910	if (softc->is_single == 0) {
1911		ctl_frontend_register(&ha_frontend);
1912		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1913			printf("ctl_init: ctl_ha_msg_init failed.\n");
1914			softc->is_single = 1;
1915		} else
1916		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1917		    != CTL_HA_STATUS_SUCCESS) {
1918			printf("ctl_init: ctl_ha_msg_register failed.\n");
1919			softc->is_single = 1;
1920		}
1921	}
1922	return (0);
1923}
1924
1925void
1926ctl_shutdown(void)
1927{
1928	struct ctl_softc *softc = control_softc;
1929	struct ctl_lun *lun, *next_lun;
1930
1931	if (softc->is_single == 0) {
1932		ctl_ha_msg_shutdown(softc);
1933		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1934		    != CTL_HA_STATUS_SUCCESS)
1935			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1936		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1937			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1938		ctl_frontend_deregister(&ha_frontend);
1939	}
1940
1941	mtx_lock(&softc->ctl_lock);
1942
1943	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1944		ctl_free_lun(lun);
1945
1946	mtx_unlock(&softc->ctl_lock);
1947
1948#if 0
1949	ctl_shutdown_thread(softc->work_thread);
1950	mtx_destroy(&softc->queue_lock);
1951#endif
1952
1953	ctl_tpc_shutdown(softc);
1954	uma_zdestroy(softc->io_zone);
1955	mtx_destroy(&softc->ctl_lock);
1956
1957	destroy_dev(softc->dev);
1958
1959	sysctl_ctx_free(&softc->sysctl_ctx);
1960
1961	free(control_softc, M_DEVBUF);
1962	control_softc = NULL;
1963}
1964
1965static int
1966ctl_module_event_handler(module_t mod, int what, void *arg)
1967{
1968
1969	switch (what) {
1970	case MOD_LOAD:
1971		return (ctl_init());
1972	case MOD_UNLOAD:
1973		return (EBUSY);
1974	default:
1975		return (EOPNOTSUPP);
1976	}
1977}
1978
1979/*
1980 * XXX KDM should we do some access checks here?  Bump a reference count to
1981 * prevent a CTL module from being unloaded while someone has it open?
1982 */
1983static int
1984ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1985{
1986	return (0);
1987}
1988
1989static int
1990ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1991{
1992	return (0);
1993}
1994
1995/*
1996 * Remove an initiator by port number and initiator ID.
1997 * Returns 0 for success, -1 for failure.
1998 */
1999int
2000ctl_remove_initiator(struct ctl_port *port, int iid)
2001{
2002	struct ctl_softc *softc = port->ctl_softc;
2003
2004	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2005
2006	if (iid > CTL_MAX_INIT_PER_PORT) {
2007		printf("%s: initiator ID %u > maximun %u!\n",
2008		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2009		return (-1);
2010	}
2011
2012	mtx_lock(&softc->ctl_lock);
2013	port->wwpn_iid[iid].in_use--;
2014	port->wwpn_iid[iid].last_use = time_uptime;
2015	mtx_unlock(&softc->ctl_lock);
2016	ctl_isc_announce_iid(port, iid);
2017
2018	return (0);
2019}
2020
2021/*
2022 * Add an initiator to the initiator map.
2023 * Returns iid for success, < 0 for failure.
2024 */
2025int
2026ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2027{
2028	struct ctl_softc *softc = port->ctl_softc;
2029	time_t best_time;
2030	int i, best;
2031
2032	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2033
2034	if (iid >= CTL_MAX_INIT_PER_PORT) {
2035		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2036		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2037		free(name, M_CTL);
2038		return (-1);
2039	}
2040
2041	mtx_lock(&softc->ctl_lock);
2042
2043	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2044		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2045			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2046				iid = i;
2047				break;
2048			}
2049			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2050			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2051				iid = i;
2052				break;
2053			}
2054		}
2055	}
2056
2057	if (iid < 0) {
2058		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2059			if (port->wwpn_iid[i].in_use == 0 &&
2060			    port->wwpn_iid[i].wwpn == 0 &&
2061			    port->wwpn_iid[i].name == NULL) {
2062				iid = i;
2063				break;
2064			}
2065		}
2066	}
2067
2068	if (iid < 0) {
2069		best = -1;
2070		best_time = INT32_MAX;
2071		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2072			if (port->wwpn_iid[i].in_use == 0) {
2073				if (port->wwpn_iid[i].last_use < best_time) {
2074					best = i;
2075					best_time = port->wwpn_iid[i].last_use;
2076				}
2077			}
2078		}
2079		iid = best;
2080	}
2081
2082	if (iid < 0) {
2083		mtx_unlock(&softc->ctl_lock);
2084		free(name, M_CTL);
2085		return (-2);
2086	}
2087
2088	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2089		/*
2090		 * This is not an error yet.
2091		 */
2092		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2093#if 0
2094			printf("%s: port %d iid %u WWPN %#jx arrived"
2095			    " again\n", __func__, port->targ_port,
2096			    iid, (uintmax_t)wwpn);
2097#endif
2098			goto take;
2099		}
2100		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2101		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2102#if 0
2103			printf("%s: port %d iid %u name '%s' arrived"
2104			    " again\n", __func__, port->targ_port,
2105			    iid, name);
2106#endif
2107			goto take;
2108		}
2109
2110		/*
2111		 * This is an error, but what do we do about it?  The
2112		 * driver is telling us we have a new WWPN for this
2113		 * initiator ID, so we pretty much need to use it.
2114		 */
2115		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2116		    " but WWPN %#jx '%s' is still at that address\n",
2117		    __func__, port->targ_port, iid, wwpn, name,
2118		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2119		    port->wwpn_iid[iid].name);
2120
2121		/*
2122		 * XXX KDM clear have_ca and ua_pending on each LUN for
2123		 * this initiator.
2124		 */
2125	}
2126take:
2127	free(port->wwpn_iid[iid].name, M_CTL);
2128	port->wwpn_iid[iid].name = name;
2129	port->wwpn_iid[iid].wwpn = wwpn;
2130	port->wwpn_iid[iid].in_use++;
2131	mtx_unlock(&softc->ctl_lock);
2132	ctl_isc_announce_iid(port, iid);
2133
2134	return (iid);
2135}
2136
2137static int
2138ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2139{
2140	int len;
2141
2142	switch (port->port_type) {
2143	case CTL_PORT_FC:
2144	{
2145		struct scsi_transportid_fcp *id =
2146		    (struct scsi_transportid_fcp *)buf;
2147		if (port->wwpn_iid[iid].wwpn == 0)
2148			return (0);
2149		memset(id, 0, sizeof(*id));
2150		id->format_protocol = SCSI_PROTO_FC;
2151		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2152		return (sizeof(*id));
2153	}
2154	case CTL_PORT_ISCSI:
2155	{
2156		struct scsi_transportid_iscsi_port *id =
2157		    (struct scsi_transportid_iscsi_port *)buf;
2158		if (port->wwpn_iid[iid].name == NULL)
2159			return (0);
2160		memset(id, 0, 256);
2161		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2162		    SCSI_PROTO_ISCSI;
2163		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2164		len = roundup2(min(len, 252), 4);
2165		scsi_ulto2b(len, id->additional_length);
2166		return (sizeof(*id) + len);
2167	}
2168	case CTL_PORT_SAS:
2169	{
2170		struct scsi_transportid_sas *id =
2171		    (struct scsi_transportid_sas *)buf;
2172		if (port->wwpn_iid[iid].wwpn == 0)
2173			return (0);
2174		memset(id, 0, sizeof(*id));
2175		id->format_protocol = SCSI_PROTO_SAS;
2176		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2177		return (sizeof(*id));
2178	}
2179	default:
2180	{
2181		struct scsi_transportid_spi *id =
2182		    (struct scsi_transportid_spi *)buf;
2183		memset(id, 0, sizeof(*id));
2184		id->format_protocol = SCSI_PROTO_SPI;
2185		scsi_ulto2b(iid, id->scsi_addr);
2186		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2187		return (sizeof(*id));
2188	}
2189	}
2190}
2191
2192/*
2193 * Serialize a command that went down the "wrong" side, and so was sent to
2194 * this controller for execution.  The logic is a little different than the
2195 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2196 * sent back to the other side, but in the success case, we execute the
2197 * command on this side (XFER mode) or tell the other side to execute it
2198 * (SER_ONLY mode).
2199 */
2200static int
2201ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2202{
2203	struct ctl_softc *softc = control_softc;
2204	union ctl_ha_msg msg_info;
2205	struct ctl_port *port;
2206	struct ctl_lun *lun;
2207	const struct ctl_cmd_entry *entry;
2208	int retval = 0;
2209	uint32_t targ_lun;
2210
2211	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2212	mtx_lock(&softc->ctl_lock);
2213
2214	/* Make sure that we know about this port. */
2215	port = ctl_io_port(&ctsio->io_hdr);
2216	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2217		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2218					 /*retry_count*/ 1);
2219		goto badjuju;
2220	}
2221
2222	/* Make sure that we know about this LUN. */
2223	if ((targ_lun < CTL_MAX_LUNS) &&
2224	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2225		mtx_lock(&lun->lun_lock);
2226		mtx_unlock(&softc->ctl_lock);
2227		/*
2228		 * If the LUN is invalid, pretend that it doesn't exist.
2229		 * It will go away as soon as all pending I/O has been
2230		 * completed.
2231		 */
2232		if (lun->flags & CTL_LUN_DISABLED) {
2233			mtx_unlock(&lun->lun_lock);
2234			lun = NULL;
2235		}
2236	} else {
2237		mtx_unlock(&softc->ctl_lock);
2238		lun = NULL;
2239	}
2240	if (lun == NULL) {
2241		/*
2242		 * The other node would not send this request to us unless
2243		 * received announce that we are primary node for this LUN.
2244		 * If this LUN does not exist now, it is probably result of
2245		 * a race, so respond to initiator in the most opaque way.
2246		 */
2247		ctl_set_busy(ctsio);
2248		goto badjuju;
2249	}
2250
2251	entry = ctl_get_cmd_entry(ctsio, NULL);
2252	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2253		mtx_unlock(&lun->lun_lock);
2254		goto badjuju;
2255	}
2256
2257	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2258	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2259
2260	/*
2261	 * Every I/O goes into the OOA queue for a
2262	 * particular LUN, and stays there until completion.
2263	 */
2264#ifdef CTL_TIME_IO
2265	if (TAILQ_EMPTY(&lun->ooa_queue))
2266		lun->idle_time += getsbinuptime() - lun->last_busy;
2267#endif
2268	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2269
2270	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2271		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2272		 ooa_links))) {
2273	case CTL_ACTION_BLOCK:
2274		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2275		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2276				  blocked_links);
2277		mtx_unlock(&lun->lun_lock);
2278		break;
2279	case CTL_ACTION_PASS:
2280	case CTL_ACTION_SKIP:
2281		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2282			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2283			ctl_enqueue_rtr((union ctl_io *)ctsio);
2284			mtx_unlock(&lun->lun_lock);
2285		} else {
2286			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2287			mtx_unlock(&lun->lun_lock);
2288
2289			/* send msg back to other side */
2290			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2291			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2292			msg_info.hdr.msg_type = CTL_MSG_R2R;
2293			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2294			    sizeof(msg_info.hdr), M_WAITOK);
2295		}
2296		break;
2297	case CTL_ACTION_OVERLAP:
2298		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2299		mtx_unlock(&lun->lun_lock);
2300		ctl_set_overlapped_cmd(ctsio);
2301		goto badjuju;
2302	case CTL_ACTION_OVERLAP_TAG:
2303		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2304		mtx_unlock(&lun->lun_lock);
2305		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2306		goto badjuju;
2307	case CTL_ACTION_ERROR:
2308	default:
2309		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2310		mtx_unlock(&lun->lun_lock);
2311
2312		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2313					 /*retry_count*/ 0);
2314badjuju:
2315		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2316		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2317		msg_info.hdr.serializing_sc = NULL;
2318		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2319		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2320		    sizeof(msg_info.scsi), M_WAITOK);
2321		retval = 1;
2322		break;
2323	}
2324	return (retval);
2325}
2326
2327/*
2328 * Returns 0 for success, errno for failure.
2329 */
2330static void
2331ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2332		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2333{
2334	union ctl_io *io;
2335
2336	mtx_lock(&lun->lun_lock);
2337	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2338	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2339	     ooa_links)) {
2340		struct ctl_ooa_entry *entry;
2341
2342		/*
2343		 * If we've got more than we can fit, just count the
2344		 * remaining entries.
2345		 */
2346		if (*cur_fill_num >= ooa_hdr->alloc_num)
2347			continue;
2348
2349		entry = &kern_entries[*cur_fill_num];
2350
2351		entry->tag_num = io->scsiio.tag_num;
2352		entry->lun_num = lun->lun;
2353#ifdef CTL_TIME_IO
2354		entry->start_bt = io->io_hdr.start_bt;
2355#endif
2356		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2357		entry->cdb_len = io->scsiio.cdb_len;
2358		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2359			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2360
2361		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2362			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2363
2364		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2365			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2366
2367		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2368			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2369
2370		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2371			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2372	}
2373	mtx_unlock(&lun->lun_lock);
2374}
2375
2376static void *
2377ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2378		 size_t error_str_len)
2379{
2380	void *kptr;
2381
2382	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2383
2384	if (copyin(user_addr, kptr, len) != 0) {
2385		snprintf(error_str, error_str_len, "Error copying %d bytes "
2386			 "from user address %p to kernel address %p", len,
2387			 user_addr, kptr);
2388		free(kptr, M_CTL);
2389		return (NULL);
2390	}
2391
2392	return (kptr);
2393}
2394
2395static void
2396ctl_free_args(int num_args, struct ctl_be_arg *args)
2397{
2398	int i;
2399
2400	if (args == NULL)
2401		return;
2402
2403	for (i = 0; i < num_args; i++) {
2404		free(args[i].kname, M_CTL);
2405		free(args[i].kvalue, M_CTL);
2406	}
2407
2408	free(args, M_CTL);
2409}
2410
2411static struct ctl_be_arg *
2412ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2413		char *error_str, size_t error_str_len)
2414{
2415	struct ctl_be_arg *args;
2416	int i;
2417
2418	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2419				error_str, error_str_len);
2420
2421	if (args == NULL)
2422		goto bailout;
2423
2424	for (i = 0; i < num_args; i++) {
2425		args[i].kname = NULL;
2426		args[i].kvalue = NULL;
2427	}
2428
2429	for (i = 0; i < num_args; i++) {
2430		uint8_t *tmpptr;
2431
2432		args[i].kname = ctl_copyin_alloc(args[i].name,
2433			args[i].namelen, error_str, error_str_len);
2434		if (args[i].kname == NULL)
2435			goto bailout;
2436
2437		if (args[i].kname[args[i].namelen - 1] != '\0') {
2438			snprintf(error_str, error_str_len, "Argument %d "
2439				 "name is not NUL-terminated", i);
2440			goto bailout;
2441		}
2442
2443		if (args[i].flags & CTL_BEARG_RD) {
2444			tmpptr = ctl_copyin_alloc(args[i].value,
2445				args[i].vallen, error_str, error_str_len);
2446			if (tmpptr == NULL)
2447				goto bailout;
2448			if ((args[i].flags & CTL_BEARG_ASCII)
2449			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2450				snprintf(error_str, error_str_len, "Argument "
2451				    "%d value is not NUL-terminated", i);
2452				free(tmpptr, M_CTL);
2453				goto bailout;
2454			}
2455			args[i].kvalue = tmpptr;
2456		} else {
2457			args[i].kvalue = malloc(args[i].vallen,
2458			    M_CTL, M_WAITOK | M_ZERO);
2459		}
2460	}
2461
2462	return (args);
2463bailout:
2464
2465	ctl_free_args(num_args, args);
2466
2467	return (NULL);
2468}
2469
2470static void
2471ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2472{
2473	int i;
2474
2475	for (i = 0; i < num_args; i++) {
2476		if (args[i].flags & CTL_BEARG_WR)
2477			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2478	}
2479}
2480
2481/*
2482 * Escape characters that are illegal or not recommended in XML.
2483 */
2484int
2485ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2486{
2487	char *end = str + size;
2488	int retval;
2489
2490	retval = 0;
2491
2492	for (; *str && str < end; str++) {
2493		switch (*str) {
2494		case '&':
2495			retval = sbuf_printf(sb, "&amp;");
2496			break;
2497		case '>':
2498			retval = sbuf_printf(sb, "&gt;");
2499			break;
2500		case '<':
2501			retval = sbuf_printf(sb, "&lt;");
2502			break;
2503		default:
2504			retval = sbuf_putc(sb, *str);
2505			break;
2506		}
2507
2508		if (retval != 0)
2509			break;
2510
2511	}
2512
2513	return (retval);
2514}
2515
2516static void
2517ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2518{
2519	struct scsi_vpd_id_descriptor *desc;
2520	int i;
2521
2522	if (id == NULL || id->len < 4)
2523		return;
2524	desc = (struct scsi_vpd_id_descriptor *)id->data;
2525	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2526	case SVPD_ID_TYPE_T10:
2527		sbuf_printf(sb, "t10.");
2528		break;
2529	case SVPD_ID_TYPE_EUI64:
2530		sbuf_printf(sb, "eui.");
2531		break;
2532	case SVPD_ID_TYPE_NAA:
2533		sbuf_printf(sb, "naa.");
2534		break;
2535	case SVPD_ID_TYPE_SCSI_NAME:
2536		break;
2537	}
2538	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2539	case SVPD_ID_CODESET_BINARY:
2540		for (i = 0; i < desc->length; i++)
2541			sbuf_printf(sb, "%02x", desc->identifier[i]);
2542		break;
2543	case SVPD_ID_CODESET_ASCII:
2544		sbuf_printf(sb, "%.*s", (int)desc->length,
2545		    (char *)desc->identifier);
2546		break;
2547	case SVPD_ID_CODESET_UTF8:
2548		sbuf_printf(sb, "%s", (char *)desc->identifier);
2549		break;
2550	}
2551}
2552
2553static int
2554ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2555	  struct thread *td)
2556{
2557	struct ctl_softc *softc = dev->si_drv1;
2558	struct ctl_lun *lun;
2559	int retval;
2560
2561	retval = 0;
2562
2563	switch (cmd) {
2564	case CTL_IO:
2565		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2566		break;
2567	case CTL_ENABLE_PORT:
2568	case CTL_DISABLE_PORT:
2569	case CTL_SET_PORT_WWNS: {
2570		struct ctl_port *port;
2571		struct ctl_port_entry *entry;
2572
2573		entry = (struct ctl_port_entry *)addr;
2574
2575		mtx_lock(&softc->ctl_lock);
2576		STAILQ_FOREACH(port, &softc->port_list, links) {
2577			int action, done;
2578
2579			if (port->targ_port < softc->port_min ||
2580			    port->targ_port >= softc->port_max)
2581				continue;
2582
2583			action = 0;
2584			done = 0;
2585			if ((entry->port_type == CTL_PORT_NONE)
2586			 && (entry->targ_port == port->targ_port)) {
2587				/*
2588				 * If the user only wants to enable or
2589				 * disable or set WWNs on a specific port,
2590				 * do the operation and we're done.
2591				 */
2592				action = 1;
2593				done = 1;
2594			} else if (entry->port_type & port->port_type) {
2595				/*
2596				 * Compare the user's type mask with the
2597				 * particular frontend type to see if we
2598				 * have a match.
2599				 */
2600				action = 1;
2601				done = 0;
2602
2603				/*
2604				 * Make sure the user isn't trying to set
2605				 * WWNs on multiple ports at the same time.
2606				 */
2607				if (cmd == CTL_SET_PORT_WWNS) {
2608					printf("%s: Can't set WWNs on "
2609					       "multiple ports\n", __func__);
2610					retval = EINVAL;
2611					break;
2612				}
2613			}
2614			if (action == 0)
2615				continue;
2616
2617			/*
2618			 * XXX KDM we have to drop the lock here, because
2619			 * the online/offline operations can potentially
2620			 * block.  We need to reference count the frontends
2621			 * so they can't go away,
2622			 */
2623			if (cmd == CTL_ENABLE_PORT) {
2624				mtx_unlock(&softc->ctl_lock);
2625				ctl_port_online(port);
2626				mtx_lock(&softc->ctl_lock);
2627			} else if (cmd == CTL_DISABLE_PORT) {
2628				mtx_unlock(&softc->ctl_lock);
2629				ctl_port_offline(port);
2630				mtx_lock(&softc->ctl_lock);
2631			} else if (cmd == CTL_SET_PORT_WWNS) {
2632				ctl_port_set_wwns(port,
2633				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2634				    1 : 0, entry->wwnn,
2635				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2636				    1 : 0, entry->wwpn);
2637			}
2638			if (done != 0)
2639				break;
2640		}
2641		mtx_unlock(&softc->ctl_lock);
2642		break;
2643	}
2644	case CTL_GET_OOA: {
2645		struct ctl_ooa *ooa_hdr;
2646		struct ctl_ooa_entry *entries;
2647		uint32_t cur_fill_num;
2648
2649		ooa_hdr = (struct ctl_ooa *)addr;
2650
2651		if ((ooa_hdr->alloc_len == 0)
2652		 || (ooa_hdr->alloc_num == 0)) {
2653			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2654			       "must be non-zero\n", __func__,
2655			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2656			retval = EINVAL;
2657			break;
2658		}
2659
2660		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2661		    sizeof(struct ctl_ooa_entry))) {
2662			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2663			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2664			       __func__, ooa_hdr->alloc_len,
2665			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2666			retval = EINVAL;
2667			break;
2668		}
2669
2670		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2671		if (entries == NULL) {
2672			printf("%s: could not allocate %d bytes for OOA "
2673			       "dump\n", __func__, ooa_hdr->alloc_len);
2674			retval = ENOMEM;
2675			break;
2676		}
2677
2678		mtx_lock(&softc->ctl_lock);
2679		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2680		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2681		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2682			mtx_unlock(&softc->ctl_lock);
2683			free(entries, M_CTL);
2684			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2685			       __func__, (uintmax_t)ooa_hdr->lun_num);
2686			retval = EINVAL;
2687			break;
2688		}
2689
2690		cur_fill_num = 0;
2691
2692		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2693			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2694				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2695				    ooa_hdr, entries);
2696			}
2697		} else {
2698			lun = softc->ctl_luns[ooa_hdr->lun_num];
2699			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2700			    entries);
2701		}
2702		mtx_unlock(&softc->ctl_lock);
2703
2704		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2705		ooa_hdr->fill_len = ooa_hdr->fill_num *
2706			sizeof(struct ctl_ooa_entry);
2707		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2708		if (retval != 0) {
2709			printf("%s: error copying out %d bytes for OOA dump\n",
2710			       __func__, ooa_hdr->fill_len);
2711		}
2712
2713		getbinuptime(&ooa_hdr->cur_bt);
2714
2715		if (cur_fill_num > ooa_hdr->alloc_num) {
2716			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2717			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2718		} else {
2719			ooa_hdr->dropped_num = 0;
2720			ooa_hdr->status = CTL_OOA_OK;
2721		}
2722
2723		free(entries, M_CTL);
2724		break;
2725	}
2726	case CTL_DELAY_IO: {
2727		struct ctl_io_delay_info *delay_info;
2728
2729		delay_info = (struct ctl_io_delay_info *)addr;
2730
2731#ifdef CTL_IO_DELAY
2732		mtx_lock(&softc->ctl_lock);
2733
2734		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2735		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2736			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2737		} else {
2738			lun = softc->ctl_luns[delay_info->lun_id];
2739			mtx_lock(&lun->lun_lock);
2740
2741			delay_info->status = CTL_DELAY_STATUS_OK;
2742
2743			switch (delay_info->delay_type) {
2744			case CTL_DELAY_TYPE_CONT:
2745				break;
2746			case CTL_DELAY_TYPE_ONESHOT:
2747				break;
2748			default:
2749				delay_info->status =
2750					CTL_DELAY_STATUS_INVALID_TYPE;
2751				break;
2752			}
2753
2754			switch (delay_info->delay_loc) {
2755			case CTL_DELAY_LOC_DATAMOVE:
2756				lun->delay_info.datamove_type =
2757					delay_info->delay_type;
2758				lun->delay_info.datamove_delay =
2759					delay_info->delay_secs;
2760				break;
2761			case CTL_DELAY_LOC_DONE:
2762				lun->delay_info.done_type =
2763					delay_info->delay_type;
2764				lun->delay_info.done_delay =
2765					delay_info->delay_secs;
2766				break;
2767			default:
2768				delay_info->status =
2769					CTL_DELAY_STATUS_INVALID_LOC;
2770				break;
2771			}
2772			mtx_unlock(&lun->lun_lock);
2773		}
2774
2775		mtx_unlock(&softc->ctl_lock);
2776#else
2777		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2778#endif /* CTL_IO_DELAY */
2779		break;
2780	}
2781	case CTL_GETSTATS: {
2782		struct ctl_stats *stats;
2783		int i;
2784
2785		stats = (struct ctl_stats *)addr;
2786
2787		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2788		     stats->alloc_len) {
2789			stats->status = CTL_SS_NEED_MORE_SPACE;
2790			stats->num_luns = softc->num_luns;
2791			break;
2792		}
2793		/*
2794		 * XXX KDM no locking here.  If the LUN list changes,
2795		 * things can blow up.
2796		 */
2797		i = 0;
2798		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2799			retval = copyout(&lun->stats, &stats->lun_stats[i++],
2800					 sizeof(lun->stats));
2801			if (retval != 0)
2802				break;
2803		}
2804		stats->num_luns = softc->num_luns;
2805		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2806				 softc->num_luns;
2807		stats->status = CTL_SS_OK;
2808#ifdef CTL_TIME_IO
2809		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2810#else
2811		stats->flags = CTL_STATS_FLAG_NONE;
2812#endif
2813		getnanouptime(&stats->timestamp);
2814		break;
2815	}
2816	case CTL_ERROR_INJECT: {
2817		struct ctl_error_desc *err_desc, *new_err_desc;
2818
2819		err_desc = (struct ctl_error_desc *)addr;
2820
2821		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2822				      M_WAITOK | M_ZERO);
2823		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2824
2825		mtx_lock(&softc->ctl_lock);
2826		lun = softc->ctl_luns[err_desc->lun_id];
2827		if (lun == NULL) {
2828			mtx_unlock(&softc->ctl_lock);
2829			free(new_err_desc, M_CTL);
2830			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2831			       __func__, (uintmax_t)err_desc->lun_id);
2832			retval = EINVAL;
2833			break;
2834		}
2835		mtx_lock(&lun->lun_lock);
2836		mtx_unlock(&softc->ctl_lock);
2837
2838		/*
2839		 * We could do some checking here to verify the validity
2840		 * of the request, but given the complexity of error
2841		 * injection requests, the checking logic would be fairly
2842		 * complex.
2843		 *
2844		 * For now, if the request is invalid, it just won't get
2845		 * executed and might get deleted.
2846		 */
2847		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2848
2849		/*
2850		 * XXX KDM check to make sure the serial number is unique,
2851		 * in case we somehow manage to wrap.  That shouldn't
2852		 * happen for a very long time, but it's the right thing to
2853		 * do.
2854		 */
2855		new_err_desc->serial = lun->error_serial;
2856		err_desc->serial = lun->error_serial;
2857		lun->error_serial++;
2858
2859		mtx_unlock(&lun->lun_lock);
2860		break;
2861	}
2862	case CTL_ERROR_INJECT_DELETE: {
2863		struct ctl_error_desc *delete_desc, *desc, *desc2;
2864		int delete_done;
2865
2866		delete_desc = (struct ctl_error_desc *)addr;
2867		delete_done = 0;
2868
2869		mtx_lock(&softc->ctl_lock);
2870		lun = softc->ctl_luns[delete_desc->lun_id];
2871		if (lun == NULL) {
2872			mtx_unlock(&softc->ctl_lock);
2873			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2874			       __func__, (uintmax_t)delete_desc->lun_id);
2875			retval = EINVAL;
2876			break;
2877		}
2878		mtx_lock(&lun->lun_lock);
2879		mtx_unlock(&softc->ctl_lock);
2880		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2881			if (desc->serial != delete_desc->serial)
2882				continue;
2883
2884			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2885				      links);
2886			free(desc, M_CTL);
2887			delete_done = 1;
2888		}
2889		mtx_unlock(&lun->lun_lock);
2890		if (delete_done == 0) {
2891			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2892			       "error serial %ju on LUN %u\n", __func__,
2893			       delete_desc->serial, delete_desc->lun_id);
2894			retval = EINVAL;
2895			break;
2896		}
2897		break;
2898	}
2899	case CTL_DUMP_STRUCTS: {
2900		int i, j, k;
2901		struct ctl_port *port;
2902		struct ctl_frontend *fe;
2903
2904		mtx_lock(&softc->ctl_lock);
2905		printf("CTL Persistent Reservation information start:\n");
2906		for (i = 0; i < CTL_MAX_LUNS; i++) {
2907			lun = softc->ctl_luns[i];
2908
2909			if ((lun == NULL)
2910			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2911				continue;
2912
2913			for (j = 0; j < CTL_MAX_PORTS; j++) {
2914				if (lun->pr_keys[j] == NULL)
2915					continue;
2916				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2917					if (lun->pr_keys[j][k] == 0)
2918						continue;
2919					printf("  LUN %d port %d iid %d key "
2920					       "%#jx\n", i, j, k,
2921					       (uintmax_t)lun->pr_keys[j][k]);
2922				}
2923			}
2924		}
2925		printf("CTL Persistent Reservation information end\n");
2926		printf("CTL Ports:\n");
2927		STAILQ_FOREACH(port, &softc->port_list, links) {
2928			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2929			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2930			       port->frontend->name, port->port_type,
2931			       port->physical_port, port->virtual_port,
2932			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2933			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2934				if (port->wwpn_iid[j].in_use == 0 &&
2935				    port->wwpn_iid[j].wwpn == 0 &&
2936				    port->wwpn_iid[j].name == NULL)
2937					continue;
2938
2939				printf("    iid %u use %d WWPN %#jx '%s'\n",
2940				    j, port->wwpn_iid[j].in_use,
2941				    (uintmax_t)port->wwpn_iid[j].wwpn,
2942				    port->wwpn_iid[j].name);
2943			}
2944		}
2945		printf("CTL Port information end\n");
2946		mtx_unlock(&softc->ctl_lock);
2947		/*
2948		 * XXX KDM calling this without a lock.  We'd likely want
2949		 * to drop the lock before calling the frontend's dump
2950		 * routine anyway.
2951		 */
2952		printf("CTL Frontends:\n");
2953		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2954			printf("  Frontend '%s'\n", fe->name);
2955			if (fe->fe_dump != NULL)
2956				fe->fe_dump();
2957		}
2958		printf("CTL Frontend information end\n");
2959		break;
2960	}
2961	case CTL_LUN_REQ: {
2962		struct ctl_lun_req *lun_req;
2963		struct ctl_backend_driver *backend;
2964
2965		lun_req = (struct ctl_lun_req *)addr;
2966
2967		backend = ctl_backend_find(lun_req->backend);
2968		if (backend == NULL) {
2969			lun_req->status = CTL_LUN_ERROR;
2970			snprintf(lun_req->error_str,
2971				 sizeof(lun_req->error_str),
2972				 "Backend \"%s\" not found.",
2973				 lun_req->backend);
2974			break;
2975		}
2976		if (lun_req->num_be_args > 0) {
2977			lun_req->kern_be_args = ctl_copyin_args(
2978				lun_req->num_be_args,
2979				lun_req->be_args,
2980				lun_req->error_str,
2981				sizeof(lun_req->error_str));
2982			if (lun_req->kern_be_args == NULL) {
2983				lun_req->status = CTL_LUN_ERROR;
2984				break;
2985			}
2986		}
2987
2988		retval = backend->ioctl(dev, cmd, addr, flag, td);
2989
2990		if (lun_req->num_be_args > 0) {
2991			ctl_copyout_args(lun_req->num_be_args,
2992				      lun_req->kern_be_args);
2993			ctl_free_args(lun_req->num_be_args,
2994				      lun_req->kern_be_args);
2995		}
2996		break;
2997	}
2998	case CTL_LUN_LIST: {
2999		struct sbuf *sb;
3000		struct ctl_lun_list *list;
3001		struct ctl_option *opt;
3002
3003		list = (struct ctl_lun_list *)addr;
3004
3005		/*
3006		 * Allocate a fixed length sbuf here, based on the length
3007		 * of the user's buffer.  We could allocate an auto-extending
3008		 * buffer, and then tell the user how much larger our
3009		 * amount of data is than his buffer, but that presents
3010		 * some problems:
3011		 *
3012		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3013		 *     we can't hold a lock while calling them with an
3014		 *     auto-extending buffer.
3015 		 *
3016		 * 2.  There is not currently a LUN reference counting
3017		 *     mechanism, outside of outstanding transactions on
3018		 *     the LUN's OOA queue.  So a LUN could go away on us
3019		 *     while we're getting the LUN number, backend-specific
3020		 *     information, etc.  Thus, given the way things
3021		 *     currently work, we need to hold the CTL lock while
3022		 *     grabbing LUN information.
3023		 *
3024		 * So, from the user's standpoint, the best thing to do is
3025		 * allocate what he thinks is a reasonable buffer length,
3026		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3027		 * double the buffer length and try again.  (And repeat
3028		 * that until he succeeds.)
3029		 */
3030		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3031		if (sb == NULL) {
3032			list->status = CTL_LUN_LIST_ERROR;
3033			snprintf(list->error_str, sizeof(list->error_str),
3034				 "Unable to allocate %d bytes for LUN list",
3035				 list->alloc_len);
3036			break;
3037		}
3038
3039		sbuf_printf(sb, "<ctllunlist>\n");
3040
3041		mtx_lock(&softc->ctl_lock);
3042		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3043			mtx_lock(&lun->lun_lock);
3044			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3045					     (uintmax_t)lun->lun);
3046
3047			/*
3048			 * Bail out as soon as we see that we've overfilled
3049			 * the buffer.
3050			 */
3051			if (retval != 0)
3052				break;
3053
3054			retval = sbuf_printf(sb, "\t<backend_type>%s"
3055					     "</backend_type>\n",
3056					     (lun->backend == NULL) ?  "none" :
3057					     lun->backend->name);
3058
3059			if (retval != 0)
3060				break;
3061
3062			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3063					     lun->be_lun->lun_type);
3064
3065			if (retval != 0)
3066				break;
3067
3068			if (lun->backend == NULL) {
3069				retval = sbuf_printf(sb, "</lun>\n");
3070				if (retval != 0)
3071					break;
3072				continue;
3073			}
3074
3075			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3076					     (lun->be_lun->maxlba > 0) ?
3077					     lun->be_lun->maxlba + 1 : 0);
3078
3079			if (retval != 0)
3080				break;
3081
3082			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3083					     lun->be_lun->blocksize);
3084
3085			if (retval != 0)
3086				break;
3087
3088			retval = sbuf_printf(sb, "\t<serial_number>");
3089
3090			if (retval != 0)
3091				break;
3092
3093			retval = ctl_sbuf_printf_esc(sb,
3094			    lun->be_lun->serial_num,
3095			    sizeof(lun->be_lun->serial_num));
3096
3097			if (retval != 0)
3098				break;
3099
3100			retval = sbuf_printf(sb, "</serial_number>\n");
3101
3102			if (retval != 0)
3103				break;
3104
3105			retval = sbuf_printf(sb, "\t<device_id>");
3106
3107			if (retval != 0)
3108				break;
3109
3110			retval = ctl_sbuf_printf_esc(sb,
3111			    lun->be_lun->device_id,
3112			    sizeof(lun->be_lun->device_id));
3113
3114			if (retval != 0)
3115				break;
3116
3117			retval = sbuf_printf(sb, "</device_id>\n");
3118
3119			if (retval != 0)
3120				break;
3121
3122			if (lun->backend->lun_info != NULL) {
3123				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3124				if (retval != 0)
3125					break;
3126			}
3127			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3128				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3129				    opt->name, opt->value, opt->name);
3130				if (retval != 0)
3131					break;
3132			}
3133
3134			retval = sbuf_printf(sb, "</lun>\n");
3135
3136			if (retval != 0)
3137				break;
3138			mtx_unlock(&lun->lun_lock);
3139		}
3140		if (lun != NULL)
3141			mtx_unlock(&lun->lun_lock);
3142		mtx_unlock(&softc->ctl_lock);
3143
3144		if ((retval != 0)
3145		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3146			retval = 0;
3147			sbuf_delete(sb);
3148			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3149			snprintf(list->error_str, sizeof(list->error_str),
3150				 "Out of space, %d bytes is too small",
3151				 list->alloc_len);
3152			break;
3153		}
3154
3155		sbuf_finish(sb);
3156
3157		retval = copyout(sbuf_data(sb), list->lun_xml,
3158				 sbuf_len(sb) + 1);
3159
3160		list->fill_len = sbuf_len(sb) + 1;
3161		list->status = CTL_LUN_LIST_OK;
3162		sbuf_delete(sb);
3163		break;
3164	}
3165	case CTL_ISCSI: {
3166		struct ctl_iscsi *ci;
3167		struct ctl_frontend *fe;
3168
3169		ci = (struct ctl_iscsi *)addr;
3170
3171		fe = ctl_frontend_find("iscsi");
3172		if (fe == NULL) {
3173			ci->status = CTL_ISCSI_ERROR;
3174			snprintf(ci->error_str, sizeof(ci->error_str),
3175			    "Frontend \"iscsi\" not found.");
3176			break;
3177		}
3178
3179		retval = fe->ioctl(dev, cmd, addr, flag, td);
3180		break;
3181	}
3182	case CTL_PORT_REQ: {
3183		struct ctl_req *req;
3184		struct ctl_frontend *fe;
3185
3186		req = (struct ctl_req *)addr;
3187
3188		fe = ctl_frontend_find(req->driver);
3189		if (fe == NULL) {
3190			req->status = CTL_LUN_ERROR;
3191			snprintf(req->error_str, sizeof(req->error_str),
3192			    "Frontend \"%s\" not found.", req->driver);
3193			break;
3194		}
3195		if (req->num_args > 0) {
3196			req->kern_args = ctl_copyin_args(req->num_args,
3197			    req->args, req->error_str, sizeof(req->error_str));
3198			if (req->kern_args == NULL) {
3199				req->status = CTL_LUN_ERROR;
3200				break;
3201			}
3202		}
3203
3204		if (fe->ioctl)
3205			retval = fe->ioctl(dev, cmd, addr, flag, td);
3206		else
3207			retval = ENODEV;
3208
3209		if (req->num_args > 0) {
3210			ctl_copyout_args(req->num_args, req->kern_args);
3211			ctl_free_args(req->num_args, req->kern_args);
3212		}
3213		break;
3214	}
3215	case CTL_PORT_LIST: {
3216		struct sbuf *sb;
3217		struct ctl_port *port;
3218		struct ctl_lun_list *list;
3219		struct ctl_option *opt;
3220		int j;
3221		uint32_t plun;
3222
3223		list = (struct ctl_lun_list *)addr;
3224
3225		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3226		if (sb == NULL) {
3227			list->status = CTL_LUN_LIST_ERROR;
3228			snprintf(list->error_str, sizeof(list->error_str),
3229				 "Unable to allocate %d bytes for LUN list",
3230				 list->alloc_len);
3231			break;
3232		}
3233
3234		sbuf_printf(sb, "<ctlportlist>\n");
3235
3236		mtx_lock(&softc->ctl_lock);
3237		STAILQ_FOREACH(port, &softc->port_list, links) {
3238			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3239					     (uintmax_t)port->targ_port);
3240
3241			/*
3242			 * Bail out as soon as we see that we've overfilled
3243			 * the buffer.
3244			 */
3245			if (retval != 0)
3246				break;
3247
3248			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3249			    "</frontend_type>\n", port->frontend->name);
3250			if (retval != 0)
3251				break;
3252
3253			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3254					     port->port_type);
3255			if (retval != 0)
3256				break;
3257
3258			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3259			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3260			if (retval != 0)
3261				break;
3262
3263			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3264			    port->port_name);
3265			if (retval != 0)
3266				break;
3267
3268			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3269			    port->physical_port);
3270			if (retval != 0)
3271				break;
3272
3273			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3274			    port->virtual_port);
3275			if (retval != 0)
3276				break;
3277
3278			if (port->target_devid != NULL) {
3279				sbuf_printf(sb, "\t<target>");
3280				ctl_id_sbuf(port->target_devid, sb);
3281				sbuf_printf(sb, "</target>\n");
3282			}
3283
3284			if (port->port_devid != NULL) {
3285				sbuf_printf(sb, "\t<port>");
3286				ctl_id_sbuf(port->port_devid, sb);
3287				sbuf_printf(sb, "</port>\n");
3288			}
3289
3290			if (port->port_info != NULL) {
3291				retval = port->port_info(port->onoff_arg, sb);
3292				if (retval != 0)
3293					break;
3294			}
3295			STAILQ_FOREACH(opt, &port->options, links) {
3296				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3297				    opt->name, opt->value, opt->name);
3298				if (retval != 0)
3299					break;
3300			}
3301
3302			if (port->lun_map != NULL) {
3303				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3304				for (j = 0; j < CTL_MAX_LUNS; j++) {
3305					plun = ctl_lun_map_from_port(port, j);
3306					if (plun >= CTL_MAX_LUNS)
3307						continue;
3308					sbuf_printf(sb,
3309					    "\t<lun id=\"%u\">%u</lun>\n",
3310					    j, plun);
3311				}
3312			}
3313
3314			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3315				if (port->wwpn_iid[j].in_use == 0 ||
3316				    (port->wwpn_iid[j].wwpn == 0 &&
3317				     port->wwpn_iid[j].name == NULL))
3318					continue;
3319
3320				if (port->wwpn_iid[j].name != NULL)
3321					retval = sbuf_printf(sb,
3322					    "\t<initiator id=\"%u\">%s</initiator>\n",
3323					    j, port->wwpn_iid[j].name);
3324				else
3325					retval = sbuf_printf(sb,
3326					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3327					    j, port->wwpn_iid[j].wwpn);
3328				if (retval != 0)
3329					break;
3330			}
3331			if (retval != 0)
3332				break;
3333
3334			retval = sbuf_printf(sb, "</targ_port>\n");
3335			if (retval != 0)
3336				break;
3337		}
3338		mtx_unlock(&softc->ctl_lock);
3339
3340		if ((retval != 0)
3341		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3342			retval = 0;
3343			sbuf_delete(sb);
3344			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3345			snprintf(list->error_str, sizeof(list->error_str),
3346				 "Out of space, %d bytes is too small",
3347				 list->alloc_len);
3348			break;
3349		}
3350
3351		sbuf_finish(sb);
3352
3353		retval = copyout(sbuf_data(sb), list->lun_xml,
3354				 sbuf_len(sb) + 1);
3355
3356		list->fill_len = sbuf_len(sb) + 1;
3357		list->status = CTL_LUN_LIST_OK;
3358		sbuf_delete(sb);
3359		break;
3360	}
3361	case CTL_LUN_MAP: {
3362		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3363		struct ctl_port *port;
3364
3365		mtx_lock(&softc->ctl_lock);
3366		if (lm->port < softc->port_min ||
3367		    lm->port >= softc->port_max ||
3368		    (port = softc->ctl_ports[lm->port]) == NULL) {
3369			mtx_unlock(&softc->ctl_lock);
3370			return (ENXIO);
3371		}
3372		if (port->status & CTL_PORT_STATUS_ONLINE) {
3373			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3374				if (ctl_lun_map_to_port(port, lun->lun) >=
3375				    CTL_MAX_LUNS)
3376					continue;
3377				mtx_lock(&lun->lun_lock);
3378				ctl_est_ua_port(lun, lm->port, -1,
3379				    CTL_UA_LUN_CHANGE);
3380				mtx_unlock(&lun->lun_lock);
3381			}
3382		}
3383		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3384		if (lm->plun < CTL_MAX_LUNS) {
3385			if (lm->lun == UINT32_MAX)
3386				retval = ctl_lun_map_unset(port, lm->plun);
3387			else if (lm->lun < CTL_MAX_LUNS &&
3388			    softc->ctl_luns[lm->lun] != NULL)
3389				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3390			else
3391				return (ENXIO);
3392		} else if (lm->plun == UINT32_MAX) {
3393			if (lm->lun == UINT32_MAX)
3394				retval = ctl_lun_map_deinit(port);
3395			else
3396				retval = ctl_lun_map_init(port);
3397		} else
3398			return (ENXIO);
3399		if (port->status & CTL_PORT_STATUS_ONLINE)
3400			ctl_isc_announce_port(port);
3401		break;
3402	}
3403	default: {
3404		/* XXX KDM should we fix this? */
3405#if 0
3406		struct ctl_backend_driver *backend;
3407		unsigned int type;
3408		int found;
3409
3410		found = 0;
3411
3412		/*
3413		 * We encode the backend type as the ioctl type for backend
3414		 * ioctls.  So parse it out here, and then search for a
3415		 * backend of this type.
3416		 */
3417		type = _IOC_TYPE(cmd);
3418
3419		STAILQ_FOREACH(backend, &softc->be_list, links) {
3420			if (backend->type == type) {
3421				found = 1;
3422				break;
3423			}
3424		}
3425		if (found == 0) {
3426			printf("ctl: unknown ioctl command %#lx or backend "
3427			       "%d\n", cmd, type);
3428			retval = EINVAL;
3429			break;
3430		}
3431		retval = backend->ioctl(dev, cmd, addr, flag, td);
3432#endif
3433		retval = ENOTTY;
3434		break;
3435	}
3436	}
3437	return (retval);
3438}
3439
3440uint32_t
3441ctl_get_initindex(struct ctl_nexus *nexus)
3442{
3443	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3444}
3445
3446int
3447ctl_lun_map_init(struct ctl_port *port)
3448{
3449	struct ctl_softc *softc = port->ctl_softc;
3450	struct ctl_lun *lun;
3451	uint32_t i;
3452
3453	if (port->lun_map == NULL)
3454		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3455		    M_CTL, M_NOWAIT);
3456	if (port->lun_map == NULL)
3457		return (ENOMEM);
3458	for (i = 0; i < CTL_MAX_LUNS; i++)
3459		port->lun_map[i] = UINT32_MAX;
3460	if (port->status & CTL_PORT_STATUS_ONLINE) {
3461		if (port->lun_disable != NULL) {
3462			STAILQ_FOREACH(lun, &softc->lun_list, links)
3463				port->lun_disable(port->targ_lun_arg, lun->lun);
3464		}
3465		ctl_isc_announce_port(port);
3466	}
3467	return (0);
3468}
3469
3470int
3471ctl_lun_map_deinit(struct ctl_port *port)
3472{
3473	struct ctl_softc *softc = port->ctl_softc;
3474	struct ctl_lun *lun;
3475
3476	if (port->lun_map == NULL)
3477		return (0);
3478	free(port->lun_map, M_CTL);
3479	port->lun_map = NULL;
3480	if (port->status & CTL_PORT_STATUS_ONLINE) {
3481		if (port->lun_enable != NULL) {
3482			STAILQ_FOREACH(lun, &softc->lun_list, links)
3483				port->lun_enable(port->targ_lun_arg, lun->lun);
3484		}
3485		ctl_isc_announce_port(port);
3486	}
3487	return (0);
3488}
3489
3490int
3491ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3492{
3493	int status;
3494	uint32_t old;
3495
3496	if (port->lun_map == NULL) {
3497		status = ctl_lun_map_init(port);
3498		if (status != 0)
3499			return (status);
3500	}
3501	old = port->lun_map[plun];
3502	port->lun_map[plun] = glun;
3503	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3504		if (port->lun_enable != NULL)
3505			port->lun_enable(port->targ_lun_arg, plun);
3506		ctl_isc_announce_port(port);
3507	}
3508	return (0);
3509}
3510
3511int
3512ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3513{
3514	uint32_t old;
3515
3516	if (port->lun_map == NULL)
3517		return (0);
3518	old = port->lun_map[plun];
3519	port->lun_map[plun] = UINT32_MAX;
3520	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3521		if (port->lun_disable != NULL)
3522			port->lun_disable(port->targ_lun_arg, plun);
3523		ctl_isc_announce_port(port);
3524	}
3525	return (0);
3526}
3527
3528uint32_t
3529ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3530{
3531
3532	if (port == NULL)
3533		return (UINT32_MAX);
3534	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3535		return (lun_id);
3536	return (port->lun_map[lun_id]);
3537}
3538
3539uint32_t
3540ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3541{
3542	uint32_t i;
3543
3544	if (port == NULL)
3545		return (UINT32_MAX);
3546	if (port->lun_map == NULL)
3547		return (lun_id);
3548	for (i = 0; i < CTL_MAX_LUNS; i++) {
3549		if (port->lun_map[i] == lun_id)
3550			return (i);
3551	}
3552	return (UINT32_MAX);
3553}
3554
3555uint32_t
3556ctl_decode_lun(uint64_t encoded)
3557{
3558	uint8_t lun[8];
3559	uint32_t result = 0xffffffff;
3560
3561	be64enc(lun, encoded);
3562	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3563	case RPL_LUNDATA_ATYP_PERIPH:
3564		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3565		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3566			result = lun[1];
3567		break;
3568	case RPL_LUNDATA_ATYP_FLAT:
3569		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3570		    lun[6] == 0 && lun[7] == 0)
3571			result = ((lun[0] & 0x3f) << 8) + lun[1];
3572		break;
3573	case RPL_LUNDATA_ATYP_EXTLUN:
3574		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3575		case 0x02:
3576			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3577			case 0x00:
3578				result = lun[1];
3579				break;
3580			case 0x10:
3581				result = (lun[1] << 16) + (lun[2] << 8) +
3582				    lun[3];
3583				break;
3584			case 0x20:
3585				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3586					result = (lun[2] << 24) +
3587					    (lun[3] << 16) + (lun[4] << 8) +
3588					    lun[5];
3589				break;
3590			}
3591			break;
3592		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3593			result = 0xffffffff;
3594			break;
3595		}
3596		break;
3597	}
3598	return (result);
3599}
3600
3601uint64_t
3602ctl_encode_lun(uint32_t decoded)
3603{
3604	uint64_t l = decoded;
3605
3606	if (l <= 0xff)
3607		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3608	if (l <= 0x3fff)
3609		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3610	if (l <= 0xffffff)
3611		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3612		    (l << 32));
3613	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3614}
3615
3616static struct ctl_port *
3617ctl_io_port(struct ctl_io_hdr *io_hdr)
3618{
3619
3620	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3621}
3622
3623int
3624ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3625{
3626	int i;
3627
3628	for (i = first; i < last; i++) {
3629		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3630			return (i);
3631	}
3632	return (-1);
3633}
3634
3635int
3636ctl_set_mask(uint32_t *mask, uint32_t bit)
3637{
3638	uint32_t chunk, piece;
3639
3640	chunk = bit >> 5;
3641	piece = bit % (sizeof(uint32_t) * 8);
3642
3643	if ((mask[chunk] & (1 << piece)) != 0)
3644		return (-1);
3645	else
3646		mask[chunk] |= (1 << piece);
3647
3648	return (0);
3649}
3650
3651int
3652ctl_clear_mask(uint32_t *mask, uint32_t bit)
3653{
3654	uint32_t chunk, piece;
3655
3656	chunk = bit >> 5;
3657	piece = bit % (sizeof(uint32_t) * 8);
3658
3659	if ((mask[chunk] & (1 << piece)) == 0)
3660		return (-1);
3661	else
3662		mask[chunk] &= ~(1 << piece);
3663
3664	return (0);
3665}
3666
3667int
3668ctl_is_set(uint32_t *mask, uint32_t bit)
3669{
3670	uint32_t chunk, piece;
3671
3672	chunk = bit >> 5;
3673	piece = bit % (sizeof(uint32_t) * 8);
3674
3675	if ((mask[chunk] & (1 << piece)) == 0)
3676		return (0);
3677	else
3678		return (1);
3679}
3680
3681static uint64_t
3682ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3683{
3684	uint64_t *t;
3685
3686	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3687	if (t == NULL)
3688		return (0);
3689	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3690}
3691
3692static void
3693ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3694{
3695	uint64_t *t;
3696
3697	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3698	if (t == NULL)
3699		return;
3700	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3701}
3702
3703static void
3704ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3705{
3706	uint64_t *p;
3707	u_int i;
3708
3709	i = residx/CTL_MAX_INIT_PER_PORT;
3710	if (lun->pr_keys[i] != NULL)
3711		return;
3712	mtx_unlock(&lun->lun_lock);
3713	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3714	    M_WAITOK | M_ZERO);
3715	mtx_lock(&lun->lun_lock);
3716	if (lun->pr_keys[i] == NULL)
3717		lun->pr_keys[i] = p;
3718	else
3719		free(p, M_CTL);
3720}
3721
3722static void
3723ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3724{
3725	uint64_t *t;
3726
3727	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3728	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3729	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3730}
3731
3732/*
3733 * ctl_softc, pool_name, total_ctl_io are passed in.
3734 * npool is passed out.
3735 */
3736int
3737ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3738		uint32_t total_ctl_io, void **npool)
3739{
3740#ifdef IO_POOLS
3741	struct ctl_io_pool *pool;
3742
3743	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3744					    M_NOWAIT | M_ZERO);
3745	if (pool == NULL)
3746		return (ENOMEM);
3747
3748	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3749	pool->ctl_softc = ctl_softc;
3750	pool->zone = uma_zsecond_create(pool->name, NULL,
3751	    NULL, NULL, NULL, ctl_softc->io_zone);
3752	/* uma_prealloc(pool->zone, total_ctl_io); */
3753
3754	*npool = pool;
3755#else
3756	*npool = ctl_softc->io_zone;
3757#endif
3758	return (0);
3759}
3760
3761void
3762ctl_pool_free(struct ctl_io_pool *pool)
3763{
3764
3765	if (pool == NULL)
3766		return;
3767
3768#ifdef IO_POOLS
3769	uma_zdestroy(pool->zone);
3770	free(pool, M_CTL);
3771#endif
3772}
3773
3774union ctl_io *
3775ctl_alloc_io(void *pool_ref)
3776{
3777	union ctl_io *io;
3778#ifdef IO_POOLS
3779	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3780
3781	io = uma_zalloc(pool->zone, M_WAITOK);
3782#else
3783	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3784#endif
3785	if (io != NULL)
3786		io->io_hdr.pool = pool_ref;
3787	return (io);
3788}
3789
3790union ctl_io *
3791ctl_alloc_io_nowait(void *pool_ref)
3792{
3793	union ctl_io *io;
3794#ifdef IO_POOLS
3795	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3796
3797	io = uma_zalloc(pool->zone, M_NOWAIT);
3798#else
3799	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3800#endif
3801	if (io != NULL)
3802		io->io_hdr.pool = pool_ref;
3803	return (io);
3804}
3805
3806void
3807ctl_free_io(union ctl_io *io)
3808{
3809#ifdef IO_POOLS
3810	struct ctl_io_pool *pool;
3811#endif
3812
3813	if (io == NULL)
3814		return;
3815
3816#ifdef IO_POOLS
3817	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3818	uma_zfree(pool->zone, io);
3819#else
3820	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3821#endif
3822}
3823
3824void
3825ctl_zero_io(union ctl_io *io)
3826{
3827	void *pool_ref;
3828
3829	if (io == NULL)
3830		return;
3831
3832	/*
3833	 * May need to preserve linked list pointers at some point too.
3834	 */
3835	pool_ref = io->io_hdr.pool;
3836	memset(io, 0, sizeof(*io));
3837	io->io_hdr.pool = pool_ref;
3838}
3839
3840int
3841ctl_expand_number(const char *buf, uint64_t *num)
3842{
3843	char *endptr;
3844	uint64_t number;
3845	unsigned shift;
3846
3847	number = strtoq(buf, &endptr, 0);
3848
3849	switch (tolower((unsigned char)*endptr)) {
3850	case 'e':
3851		shift = 60;
3852		break;
3853	case 'p':
3854		shift = 50;
3855		break;
3856	case 't':
3857		shift = 40;
3858		break;
3859	case 'g':
3860		shift = 30;
3861		break;
3862	case 'm':
3863		shift = 20;
3864		break;
3865	case 'k':
3866		shift = 10;
3867		break;
3868	case 'b':
3869	case '\0': /* No unit. */
3870		*num = number;
3871		return (0);
3872	default:
3873		/* Unrecognized unit. */
3874		return (-1);
3875	}
3876
3877	if ((number << shift) >> shift != number) {
3878		/* Overflow */
3879		return (-1);
3880	}
3881	*num = number << shift;
3882	return (0);
3883}
3884
3885
3886/*
3887 * This routine could be used in the future to load default and/or saved
3888 * mode page parameters for a particuar lun.
3889 */
3890static int
3891ctl_init_page_index(struct ctl_lun *lun)
3892{
3893	int i, page_code;
3894	struct ctl_page_index *page_index;
3895	const char *value;
3896	uint64_t ival;
3897
3898	memcpy(&lun->mode_pages.index, page_index_template,
3899	       sizeof(page_index_template));
3900
3901	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3902
3903		page_index = &lun->mode_pages.index[i];
3904		if (lun->be_lun->lun_type == T_DIRECT &&
3905		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3906			continue;
3907		if (lun->be_lun->lun_type == T_PROCESSOR &&
3908		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3909			continue;
3910		if (lun->be_lun->lun_type == T_CDROM &&
3911		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3912			continue;
3913
3914		page_code = page_index->page_code & SMPH_PC_MASK;
3915		switch (page_code) {
3916		case SMS_RW_ERROR_RECOVERY_PAGE: {
3917			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3918			    ("subpage %#x for page %#x is incorrect!",
3919			    page_index->subpage, page_code));
3920			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3921			       &rw_er_page_default,
3922			       sizeof(rw_er_page_default));
3923			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3924			       &rw_er_page_changeable,
3925			       sizeof(rw_er_page_changeable));
3926			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3927			       &rw_er_page_default,
3928			       sizeof(rw_er_page_default));
3929			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3930			       &rw_er_page_default,
3931			       sizeof(rw_er_page_default));
3932			page_index->page_data =
3933				(uint8_t *)lun->mode_pages.rw_er_page;
3934			break;
3935		}
3936		case SMS_FORMAT_DEVICE_PAGE: {
3937			struct scsi_format_page *format_page;
3938
3939			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3940			    ("subpage %#x for page %#x is incorrect!",
3941			    page_index->subpage, page_code));
3942
3943			/*
3944			 * Sectors per track are set above.  Bytes per
3945			 * sector need to be set here on a per-LUN basis.
3946			 */
3947			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3948			       &format_page_default,
3949			       sizeof(format_page_default));
3950			memcpy(&lun->mode_pages.format_page[
3951			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3952			       sizeof(format_page_changeable));
3953			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3954			       &format_page_default,
3955			       sizeof(format_page_default));
3956			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3957			       &format_page_default,
3958			       sizeof(format_page_default));
3959
3960			format_page = &lun->mode_pages.format_page[
3961				CTL_PAGE_CURRENT];
3962			scsi_ulto2b(lun->be_lun->blocksize,
3963				    format_page->bytes_per_sector);
3964
3965			format_page = &lun->mode_pages.format_page[
3966				CTL_PAGE_DEFAULT];
3967			scsi_ulto2b(lun->be_lun->blocksize,
3968				    format_page->bytes_per_sector);
3969
3970			format_page = &lun->mode_pages.format_page[
3971				CTL_PAGE_SAVED];
3972			scsi_ulto2b(lun->be_lun->blocksize,
3973				    format_page->bytes_per_sector);
3974
3975			page_index->page_data =
3976				(uint8_t *)lun->mode_pages.format_page;
3977			break;
3978		}
3979		case SMS_RIGID_DISK_PAGE: {
3980			struct scsi_rigid_disk_page *rigid_disk_page;
3981			uint32_t sectors_per_cylinder;
3982			uint64_t cylinders;
3983#ifndef	__XSCALE__
3984			int shift;
3985#endif /* !__XSCALE__ */
3986
3987			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3988			    ("subpage %#x for page %#x is incorrect!",
3989			    page_index->subpage, page_code));
3990
3991			/*
3992			 * Rotation rate and sectors per track are set
3993			 * above.  We calculate the cylinders here based on
3994			 * capacity.  Due to the number of heads and
3995			 * sectors per track we're using, smaller arrays
3996			 * may turn out to have 0 cylinders.  Linux and
3997			 * FreeBSD don't pay attention to these mode pages
3998			 * to figure out capacity, but Solaris does.  It
3999			 * seems to deal with 0 cylinders just fine, and
4000			 * works out a fake geometry based on the capacity.
4001			 */
4002			memcpy(&lun->mode_pages.rigid_disk_page[
4003			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4004			       sizeof(rigid_disk_page_default));
4005			memcpy(&lun->mode_pages.rigid_disk_page[
4006			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4007			       sizeof(rigid_disk_page_changeable));
4008
4009			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4010				CTL_DEFAULT_HEADS;
4011
4012			/*
4013			 * The divide method here will be more accurate,
4014			 * probably, but results in floating point being
4015			 * used in the kernel on i386 (__udivdi3()).  On the
4016			 * XScale, though, __udivdi3() is implemented in
4017			 * software.
4018			 *
4019			 * The shift method for cylinder calculation is
4020			 * accurate if sectors_per_cylinder is a power of
4021			 * 2.  Otherwise it might be slightly off -- you
4022			 * might have a bit of a truncation problem.
4023			 */
4024#ifdef	__XSCALE__
4025			cylinders = (lun->be_lun->maxlba + 1) /
4026				sectors_per_cylinder;
4027#else
4028			for (shift = 31; shift > 0; shift--) {
4029				if (sectors_per_cylinder & (1 << shift))
4030					break;
4031			}
4032			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4033#endif
4034
4035			/*
4036			 * We've basically got 3 bytes, or 24 bits for the
4037			 * cylinder size in the mode page.  If we're over,
4038			 * just round down to 2^24.
4039			 */
4040			if (cylinders > 0xffffff)
4041				cylinders = 0xffffff;
4042
4043			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4044				CTL_PAGE_DEFAULT];
4045			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4046
4047			if ((value = ctl_get_opt(&lun->be_lun->options,
4048			    "rpm")) != NULL) {
4049				scsi_ulto2b(strtol(value, NULL, 0),
4050				     rigid_disk_page->rotation_rate);
4051			}
4052
4053			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4054			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4055			       sizeof(rigid_disk_page_default));
4056			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4057			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4058			       sizeof(rigid_disk_page_default));
4059
4060			page_index->page_data =
4061				(uint8_t *)lun->mode_pages.rigid_disk_page;
4062			break;
4063		}
4064		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4065			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4066			    ("subpage %#x for page %#x is incorrect!",
4067			    page_index->subpage, page_code));
4068			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4069			       &verify_er_page_default,
4070			       sizeof(verify_er_page_default));
4071			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4072			       &verify_er_page_changeable,
4073			       sizeof(verify_er_page_changeable));
4074			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4075			       &verify_er_page_default,
4076			       sizeof(verify_er_page_default));
4077			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4078			       &verify_er_page_default,
4079			       sizeof(verify_er_page_default));
4080			page_index->page_data =
4081				(uint8_t *)lun->mode_pages.verify_er_page;
4082			break;
4083		}
4084		case SMS_CACHING_PAGE: {
4085			struct scsi_caching_page *caching_page;
4086
4087			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4088			    ("subpage %#x for page %#x is incorrect!",
4089			    page_index->subpage, page_code));
4090			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4091			       &caching_page_default,
4092			       sizeof(caching_page_default));
4093			memcpy(&lun->mode_pages.caching_page[
4094			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4095			       sizeof(caching_page_changeable));
4096			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4097			       &caching_page_default,
4098			       sizeof(caching_page_default));
4099			caching_page = &lun->mode_pages.caching_page[
4100			    CTL_PAGE_SAVED];
4101			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4102			if (value != NULL && strcmp(value, "off") == 0)
4103				caching_page->flags1 &= ~SCP_WCE;
4104			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4105			if (value != NULL && strcmp(value, "off") == 0)
4106				caching_page->flags1 |= SCP_RCD;
4107			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4108			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4109			       sizeof(caching_page_default));
4110			page_index->page_data =
4111				(uint8_t *)lun->mode_pages.caching_page;
4112			break;
4113		}
4114		case SMS_CONTROL_MODE_PAGE: {
4115			switch (page_index->subpage) {
4116			case SMS_SUBPAGE_PAGE_0: {
4117				struct scsi_control_page *control_page;
4118
4119				memcpy(&lun->mode_pages.control_page[
4120				    CTL_PAGE_DEFAULT],
4121				       &control_page_default,
4122				       sizeof(control_page_default));
4123				memcpy(&lun->mode_pages.control_page[
4124				    CTL_PAGE_CHANGEABLE],
4125				       &control_page_changeable,
4126				       sizeof(control_page_changeable));
4127				memcpy(&lun->mode_pages.control_page[
4128				    CTL_PAGE_SAVED],
4129				       &control_page_default,
4130				       sizeof(control_page_default));
4131				control_page = &lun->mode_pages.control_page[
4132				    CTL_PAGE_SAVED];
4133				value = ctl_get_opt(&lun->be_lun->options,
4134				    "reordering");
4135				if (value != NULL &&
4136				    strcmp(value, "unrestricted") == 0) {
4137					control_page->queue_flags &=
4138					    ~SCP_QUEUE_ALG_MASK;
4139					control_page->queue_flags |=
4140					    SCP_QUEUE_ALG_UNRESTRICTED;
4141				}
4142				memcpy(&lun->mode_pages.control_page[
4143				    CTL_PAGE_CURRENT],
4144				       &lun->mode_pages.control_page[
4145				    CTL_PAGE_SAVED],
4146				       sizeof(control_page_default));
4147				page_index->page_data =
4148				    (uint8_t *)lun->mode_pages.control_page;
4149				break;
4150			}
4151			case 0x01:
4152				memcpy(&lun->mode_pages.control_ext_page[
4153				    CTL_PAGE_DEFAULT],
4154				       &control_ext_page_default,
4155				       sizeof(control_ext_page_default));
4156				memcpy(&lun->mode_pages.control_ext_page[
4157				    CTL_PAGE_CHANGEABLE],
4158				       &control_ext_page_changeable,
4159				       sizeof(control_ext_page_changeable));
4160				memcpy(&lun->mode_pages.control_ext_page[
4161				    CTL_PAGE_SAVED],
4162				       &control_ext_page_default,
4163				       sizeof(control_ext_page_default));
4164				memcpy(&lun->mode_pages.control_ext_page[
4165				    CTL_PAGE_CURRENT],
4166				       &lun->mode_pages.control_ext_page[
4167				    CTL_PAGE_SAVED],
4168				       sizeof(control_ext_page_default));
4169				page_index->page_data =
4170				    (uint8_t *)lun->mode_pages.control_ext_page;
4171				break;
4172			default:
4173				panic("subpage %#x for page %#x is incorrect!",
4174				      page_index->subpage, page_code);
4175			}
4176			break;
4177		}
4178		case SMS_INFO_EXCEPTIONS_PAGE: {
4179			switch (page_index->subpage) {
4180			case SMS_SUBPAGE_PAGE_0:
4181				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4182				       &ie_page_default,
4183				       sizeof(ie_page_default));
4184				memcpy(&lun->mode_pages.ie_page[
4185				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4186				       sizeof(ie_page_changeable));
4187				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4188				       &ie_page_default,
4189				       sizeof(ie_page_default));
4190				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4191				       &ie_page_default,
4192				       sizeof(ie_page_default));
4193				page_index->page_data =
4194					(uint8_t *)lun->mode_pages.ie_page;
4195				break;
4196			case 0x02: {
4197				struct ctl_logical_block_provisioning_page *page;
4198
4199				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4200				       &lbp_page_default,
4201				       sizeof(lbp_page_default));
4202				memcpy(&lun->mode_pages.lbp_page[
4203				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4204				       sizeof(lbp_page_changeable));
4205				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4206				       &lbp_page_default,
4207				       sizeof(lbp_page_default));
4208				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4209				value = ctl_get_opt(&lun->be_lun->options,
4210				    "avail-threshold");
4211				if (value != NULL &&
4212				    ctl_expand_number(value, &ival) == 0) {
4213					page->descr[0].flags |= SLBPPD_ENABLED |
4214					    SLBPPD_ARMING_DEC;
4215					if (lun->be_lun->blocksize)
4216						ival /= lun->be_lun->blocksize;
4217					else
4218						ival /= 512;
4219					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4220					    page->descr[0].count);
4221				}
4222				value = ctl_get_opt(&lun->be_lun->options,
4223				    "used-threshold");
4224				if (value != NULL &&
4225				    ctl_expand_number(value, &ival) == 0) {
4226					page->descr[1].flags |= SLBPPD_ENABLED |
4227					    SLBPPD_ARMING_INC;
4228					if (lun->be_lun->blocksize)
4229						ival /= lun->be_lun->blocksize;
4230					else
4231						ival /= 512;
4232					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4233					    page->descr[1].count);
4234				}
4235				value = ctl_get_opt(&lun->be_lun->options,
4236				    "pool-avail-threshold");
4237				if (value != NULL &&
4238				    ctl_expand_number(value, &ival) == 0) {
4239					page->descr[2].flags |= SLBPPD_ENABLED |
4240					    SLBPPD_ARMING_DEC;
4241					if (lun->be_lun->blocksize)
4242						ival /= lun->be_lun->blocksize;
4243					else
4244						ival /= 512;
4245					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4246					    page->descr[2].count);
4247				}
4248				value = ctl_get_opt(&lun->be_lun->options,
4249				    "pool-used-threshold");
4250				if (value != NULL &&
4251				    ctl_expand_number(value, &ival) == 0) {
4252					page->descr[3].flags |= SLBPPD_ENABLED |
4253					    SLBPPD_ARMING_INC;
4254					if (lun->be_lun->blocksize)
4255						ival /= lun->be_lun->blocksize;
4256					else
4257						ival /= 512;
4258					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4259					    page->descr[3].count);
4260				}
4261				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4262				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4263				       sizeof(lbp_page_default));
4264				page_index->page_data =
4265					(uint8_t *)lun->mode_pages.lbp_page;
4266				break;
4267			}
4268			default:
4269				panic("subpage %#x for page %#x is incorrect!",
4270				      page_index->subpage, page_code);
4271			}
4272			break;
4273		}
4274		case SMS_CDDVD_CAPS_PAGE:{
4275			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4276			    ("subpage %#x for page %#x is incorrect!",
4277			    page_index->subpage, page_code));
4278			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4279			       &cddvd_page_default,
4280			       sizeof(cddvd_page_default));
4281			memcpy(&lun->mode_pages.cddvd_page[
4282			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4283			       sizeof(cddvd_page_changeable));
4284			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4285			       &cddvd_page_default,
4286			       sizeof(cddvd_page_default));
4287			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4288			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4289			       sizeof(cddvd_page_default));
4290			page_index->page_data =
4291				(uint8_t *)lun->mode_pages.cddvd_page;
4292			break;
4293		}
4294		default:
4295			panic("invalid page code value %#x", page_code);
4296		}
4297	}
4298
4299	return (CTL_RETVAL_COMPLETE);
4300}
4301
4302static int
4303ctl_init_log_page_index(struct ctl_lun *lun)
4304{
4305	struct ctl_page_index *page_index;
4306	int i, j, k, prev;
4307
4308	memcpy(&lun->log_pages.index, log_page_index_template,
4309	       sizeof(log_page_index_template));
4310
4311	prev = -1;
4312	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4313
4314		page_index = &lun->log_pages.index[i];
4315		if (lun->be_lun->lun_type == T_DIRECT &&
4316		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4317			continue;
4318		if (lun->be_lun->lun_type == T_PROCESSOR &&
4319		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4320			continue;
4321		if (lun->be_lun->lun_type == T_CDROM &&
4322		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4323			continue;
4324
4325		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4326		    lun->backend->lun_attr == NULL)
4327			continue;
4328
4329		if (page_index->page_code != prev) {
4330			lun->log_pages.pages_page[j] = page_index->page_code;
4331			prev = page_index->page_code;
4332			j++;
4333		}
4334		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4335		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4336		k++;
4337	}
4338	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4339	lun->log_pages.index[0].page_len = j;
4340	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4341	lun->log_pages.index[1].page_len = k * 2;
4342	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4343	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4344	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4345	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4346	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4347	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4348
4349	return (CTL_RETVAL_COMPLETE);
4350}
4351
4352static int
4353hex2bin(const char *str, uint8_t *buf, int buf_size)
4354{
4355	int i;
4356	u_char c;
4357
4358	memset(buf, 0, buf_size);
4359	while (isspace(str[0]))
4360		str++;
4361	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4362		str += 2;
4363	buf_size *= 2;
4364	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4365		c = str[i];
4366		if (isdigit(c))
4367			c -= '0';
4368		else if (isalpha(c))
4369			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4370		else
4371			break;
4372		if (c >= 16)
4373			break;
4374		if ((i & 1) == 0)
4375			buf[i / 2] |= (c << 4);
4376		else
4377			buf[i / 2] |= c;
4378	}
4379	return ((i + 1) / 2);
4380}
4381
4382/*
4383 * LUN allocation.
4384 *
4385 * Requirements:
4386 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4387 *   wants us to allocate the LUN and he can block.
4388 * - ctl_softc is always set
4389 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4390 *
4391 * Returns 0 for success, non-zero (errno) for failure.
4392 */
4393static int
4394ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4395	      struct ctl_be_lun *const be_lun)
4396{
4397	struct ctl_lun *nlun, *lun;
4398	struct scsi_vpd_id_descriptor *desc;
4399	struct scsi_vpd_id_t10 *t10id;
4400	const char *eui, *naa, *scsiname, *vendor, *value;
4401	int lun_number, i, lun_malloced;
4402	int devidlen, idlen1, idlen2 = 0, len;
4403
4404	if (be_lun == NULL)
4405		return (EINVAL);
4406
4407	/*
4408	 * We currently only support Direct Access or Processor LUN types.
4409	 */
4410	switch (be_lun->lun_type) {
4411	case T_DIRECT:
4412	case T_PROCESSOR:
4413	case T_CDROM:
4414		break;
4415	case T_SEQUENTIAL:
4416	case T_CHANGER:
4417	default:
4418		be_lun->lun_config_status(be_lun->be_lun,
4419					  CTL_LUN_CONFIG_FAILURE);
4420		break;
4421	}
4422	if (ctl_lun == NULL) {
4423		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4424		lun_malloced = 1;
4425	} else {
4426		lun_malloced = 0;
4427		lun = ctl_lun;
4428	}
4429
4430	memset(lun, 0, sizeof(*lun));
4431	if (lun_malloced)
4432		lun->flags = CTL_LUN_MALLOCED;
4433
4434	/* Generate LUN ID. */
4435	devidlen = max(CTL_DEVID_MIN_LEN,
4436	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4437	idlen1 = sizeof(*t10id) + devidlen;
4438	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4439	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4440	if (scsiname != NULL) {
4441		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4442		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4443	}
4444	eui = ctl_get_opt(&be_lun->options, "eui");
4445	if (eui != NULL) {
4446		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4447	}
4448	naa = ctl_get_opt(&be_lun->options, "naa");
4449	if (naa != NULL) {
4450		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4451	}
4452	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4453	    M_CTL, M_WAITOK | M_ZERO);
4454	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4455	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4456	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4457	desc->length = idlen1;
4458	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4459	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4460	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4461		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4462	} else {
4463		strncpy(t10id->vendor, vendor,
4464		    min(sizeof(t10id->vendor), strlen(vendor)));
4465	}
4466	strncpy((char *)t10id->vendor_spec_id,
4467	    (char *)be_lun->device_id, devidlen);
4468	if (scsiname != NULL) {
4469		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4470		    desc->length);
4471		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4472		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4473		    SVPD_ID_TYPE_SCSI_NAME;
4474		desc->length = idlen2;
4475		strlcpy(desc->identifier, scsiname, idlen2);
4476	}
4477	if (eui != NULL) {
4478		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4479		    desc->length);
4480		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4481		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4482		    SVPD_ID_TYPE_EUI64;
4483		desc->length = hex2bin(eui, desc->identifier, 16);
4484		desc->length = desc->length > 12 ? 16 :
4485		    (desc->length > 8 ? 12 : 8);
4486		len -= 16 - desc->length;
4487	}
4488	if (naa != NULL) {
4489		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4490		    desc->length);
4491		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4492		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4493		    SVPD_ID_TYPE_NAA;
4494		desc->length = hex2bin(naa, desc->identifier, 16);
4495		desc->length = desc->length > 8 ? 16 : 8;
4496		len -= 16 - desc->length;
4497	}
4498	lun->lun_devid->len = len;
4499
4500	mtx_lock(&ctl_softc->ctl_lock);
4501	/*
4502	 * See if the caller requested a particular LUN number.  If so, see
4503	 * if it is available.  Otherwise, allocate the first available LUN.
4504	 */
4505	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4506		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4507		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4508			mtx_unlock(&ctl_softc->ctl_lock);
4509			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4510				printf("ctl: requested LUN ID %d is higher "
4511				       "than CTL_MAX_LUNS - 1 (%d)\n",
4512				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4513			} else {
4514				/*
4515				 * XXX KDM return an error, or just assign
4516				 * another LUN ID in this case??
4517				 */
4518				printf("ctl: requested LUN ID %d is already "
4519				       "in use\n", be_lun->req_lun_id);
4520			}
4521			if (lun->flags & CTL_LUN_MALLOCED)
4522				free(lun, M_CTL);
4523			be_lun->lun_config_status(be_lun->be_lun,
4524						  CTL_LUN_CONFIG_FAILURE);
4525			return (ENOSPC);
4526		}
4527		lun_number = be_lun->req_lun_id;
4528	} else {
4529		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4530		if (lun_number == -1) {
4531			mtx_unlock(&ctl_softc->ctl_lock);
4532			printf("ctl: can't allocate LUN, out of LUNs\n");
4533			if (lun->flags & CTL_LUN_MALLOCED)
4534				free(lun, M_CTL);
4535			be_lun->lun_config_status(be_lun->be_lun,
4536						  CTL_LUN_CONFIG_FAILURE);
4537			return (ENOSPC);
4538		}
4539	}
4540	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4541
4542	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4543	lun->lun = lun_number;
4544	lun->be_lun = be_lun;
4545	/*
4546	 * The processor LUN is always enabled.  Disk LUNs come on line
4547	 * disabled, and must be enabled by the backend.
4548	 */
4549	lun->flags |= CTL_LUN_DISABLED;
4550	lun->backend = be_lun->be;
4551	be_lun->ctl_lun = lun;
4552	be_lun->lun_id = lun_number;
4553	atomic_add_int(&be_lun->be->num_luns, 1);
4554	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4555		lun->flags |= CTL_LUN_EJECTED;
4556	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4557		lun->flags |= CTL_LUN_NO_MEDIA;
4558	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4559		lun->flags |= CTL_LUN_STOPPED;
4560
4561	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4562		lun->flags |= CTL_LUN_PRIMARY_SC;
4563
4564	value = ctl_get_opt(&be_lun->options, "removable");
4565	if (value != NULL) {
4566		if (strcmp(value, "on") == 0)
4567			lun->flags |= CTL_LUN_REMOVABLE;
4568	} else if (be_lun->lun_type == T_CDROM)
4569		lun->flags |= CTL_LUN_REMOVABLE;
4570
4571	lun->ctl_softc = ctl_softc;
4572#ifdef CTL_TIME_IO
4573	lun->last_busy = getsbinuptime();
4574#endif
4575	TAILQ_INIT(&lun->ooa_queue);
4576	TAILQ_INIT(&lun->blocked_queue);
4577	STAILQ_INIT(&lun->error_list);
4578	lun->ie_reported = 1;
4579	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4580	ctl_tpc_lun_init(lun);
4581
4582	/*
4583	 * Initialize the mode and log page index.
4584	 */
4585	ctl_init_page_index(lun);
4586	ctl_init_log_page_index(lun);
4587
4588	/*
4589	 * Now, before we insert this lun on the lun list, set the lun
4590	 * inventory changed UA for all other luns.
4591	 */
4592	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4593		mtx_lock(&nlun->lun_lock);
4594		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4595		mtx_unlock(&nlun->lun_lock);
4596	}
4597
4598	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4599
4600	ctl_softc->ctl_luns[lun_number] = lun;
4601
4602	ctl_softc->num_luns++;
4603
4604	/* Setup statistics gathering */
4605	lun->stats.device_type = be_lun->lun_type;
4606	lun->stats.lun_number = lun_number;
4607	lun->stats.blocksize = be_lun->blocksize;
4608	if (be_lun->blocksize == 0)
4609		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4610	for (i = 0;i < CTL_MAX_PORTS;i++)
4611		lun->stats.ports[i].targ_port = i;
4612
4613	mtx_unlock(&ctl_softc->ctl_lock);
4614
4615	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4616	return (0);
4617}
4618
4619/*
4620 * Delete a LUN.
4621 * Assumptions:
4622 * - LUN has already been marked invalid and any pending I/O has been taken
4623 *   care of.
4624 */
4625static int
4626ctl_free_lun(struct ctl_lun *lun)
4627{
4628	struct ctl_softc *softc;
4629	struct ctl_lun *nlun;
4630	int i;
4631
4632	softc = lun->ctl_softc;
4633
4634	mtx_assert(&softc->ctl_lock, MA_OWNED);
4635
4636	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4637
4638	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4639
4640	softc->ctl_luns[lun->lun] = NULL;
4641
4642	if (!TAILQ_EMPTY(&lun->ooa_queue))
4643		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4644
4645	softc->num_luns--;
4646
4647	/*
4648	 * Tell the backend to free resources, if this LUN has a backend.
4649	 */
4650	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4651	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4652
4653	lun->ie_reportcnt = UINT32_MAX;
4654	callout_drain(&lun->ie_callout);
4655
4656	ctl_tpc_lun_shutdown(lun);
4657	mtx_destroy(&lun->lun_lock);
4658	free(lun->lun_devid, M_CTL);
4659	for (i = 0; i < CTL_MAX_PORTS; i++)
4660		free(lun->pending_ua[i], M_CTL);
4661	for (i = 0; i < CTL_MAX_PORTS; i++)
4662		free(lun->pr_keys[i], M_CTL);
4663	free(lun->write_buffer, M_CTL);
4664	if (lun->flags & CTL_LUN_MALLOCED)
4665		free(lun, M_CTL);
4666
4667	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4668		mtx_lock(&nlun->lun_lock);
4669		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4670		mtx_unlock(&nlun->lun_lock);
4671	}
4672
4673	return (0);
4674}
4675
4676static void
4677ctl_create_lun(struct ctl_be_lun *be_lun)
4678{
4679
4680	/*
4681	 * ctl_alloc_lun() should handle all potential failure cases.
4682	 */
4683	ctl_alloc_lun(control_softc, NULL, be_lun);
4684}
4685
4686int
4687ctl_add_lun(struct ctl_be_lun *be_lun)
4688{
4689	struct ctl_softc *softc = control_softc;
4690
4691	mtx_lock(&softc->ctl_lock);
4692	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4693	mtx_unlock(&softc->ctl_lock);
4694	wakeup(&softc->pending_lun_queue);
4695
4696	return (0);
4697}
4698
4699int
4700ctl_enable_lun(struct ctl_be_lun *be_lun)
4701{
4702	struct ctl_softc *softc;
4703	struct ctl_port *port, *nport;
4704	struct ctl_lun *lun;
4705	int retval;
4706
4707	lun = (struct ctl_lun *)be_lun->ctl_lun;
4708	softc = lun->ctl_softc;
4709
4710	mtx_lock(&softc->ctl_lock);
4711	mtx_lock(&lun->lun_lock);
4712	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4713		/*
4714		 * eh?  Why did we get called if the LUN is already
4715		 * enabled?
4716		 */
4717		mtx_unlock(&lun->lun_lock);
4718		mtx_unlock(&softc->ctl_lock);
4719		return (0);
4720	}
4721	lun->flags &= ~CTL_LUN_DISABLED;
4722	mtx_unlock(&lun->lun_lock);
4723
4724	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4725		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4726		    port->lun_map != NULL || port->lun_enable == NULL)
4727			continue;
4728
4729		/*
4730		 * Drop the lock while we call the FETD's enable routine.
4731		 * This can lead to a callback into CTL (at least in the
4732		 * case of the internal initiator frontend.
4733		 */
4734		mtx_unlock(&softc->ctl_lock);
4735		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4736		mtx_lock(&softc->ctl_lock);
4737		if (retval != 0) {
4738			printf("%s: FETD %s port %d returned error "
4739			       "%d for lun_enable on lun %jd\n",
4740			       __func__, port->port_name, port->targ_port,
4741			       retval, (intmax_t)lun->lun);
4742		}
4743	}
4744
4745	mtx_unlock(&softc->ctl_lock);
4746	ctl_isc_announce_lun(lun);
4747
4748	return (0);
4749}
4750
4751int
4752ctl_disable_lun(struct ctl_be_lun *be_lun)
4753{
4754	struct ctl_softc *softc;
4755	struct ctl_port *port;
4756	struct ctl_lun *lun;
4757	int retval;
4758
4759	lun = (struct ctl_lun *)be_lun->ctl_lun;
4760	softc = lun->ctl_softc;
4761
4762	mtx_lock(&softc->ctl_lock);
4763	mtx_lock(&lun->lun_lock);
4764	if (lun->flags & CTL_LUN_DISABLED) {
4765		mtx_unlock(&lun->lun_lock);
4766		mtx_unlock(&softc->ctl_lock);
4767		return (0);
4768	}
4769	lun->flags |= CTL_LUN_DISABLED;
4770	mtx_unlock(&lun->lun_lock);
4771
4772	STAILQ_FOREACH(port, &softc->port_list, links) {
4773		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4774		    port->lun_map != NULL || port->lun_disable == NULL)
4775			continue;
4776
4777		/*
4778		 * Drop the lock before we call the frontend's disable
4779		 * routine, to avoid lock order reversals.
4780		 *
4781		 * XXX KDM what happens if the frontend list changes while
4782		 * we're traversing it?  It's unlikely, but should be handled.
4783		 */
4784		mtx_unlock(&softc->ctl_lock);
4785		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4786		mtx_lock(&softc->ctl_lock);
4787		if (retval != 0) {
4788			printf("%s: FETD %s port %d returned error "
4789			       "%d for lun_disable on lun %jd\n",
4790			       __func__, port->port_name, port->targ_port,
4791			       retval, (intmax_t)lun->lun);
4792		}
4793	}
4794
4795	mtx_unlock(&softc->ctl_lock);
4796	ctl_isc_announce_lun(lun);
4797
4798	return (0);
4799}
4800
4801int
4802ctl_start_lun(struct ctl_be_lun *be_lun)
4803{
4804	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4805
4806	mtx_lock(&lun->lun_lock);
4807	lun->flags &= ~CTL_LUN_STOPPED;
4808	mtx_unlock(&lun->lun_lock);
4809	return (0);
4810}
4811
4812int
4813ctl_stop_lun(struct ctl_be_lun *be_lun)
4814{
4815	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4816
4817	mtx_lock(&lun->lun_lock);
4818	lun->flags |= CTL_LUN_STOPPED;
4819	mtx_unlock(&lun->lun_lock);
4820	return (0);
4821}
4822
4823int
4824ctl_lun_no_media(struct ctl_be_lun *be_lun)
4825{
4826	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4827
4828	mtx_lock(&lun->lun_lock);
4829	lun->flags |= CTL_LUN_NO_MEDIA;
4830	mtx_unlock(&lun->lun_lock);
4831	return (0);
4832}
4833
4834int
4835ctl_lun_has_media(struct ctl_be_lun *be_lun)
4836{
4837	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4838	union ctl_ha_msg msg;
4839
4840	mtx_lock(&lun->lun_lock);
4841	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4842	if (lun->flags & CTL_LUN_REMOVABLE)
4843		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4844	mtx_unlock(&lun->lun_lock);
4845	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4846	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4847		bzero(&msg.ua, sizeof(msg.ua));
4848		msg.hdr.msg_type = CTL_MSG_UA;
4849		msg.hdr.nexus.initid = -1;
4850		msg.hdr.nexus.targ_port = -1;
4851		msg.hdr.nexus.targ_lun = lun->lun;
4852		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4853		msg.ua.ua_all = 1;
4854		msg.ua.ua_set = 1;
4855		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4856		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4857		    M_WAITOK);
4858	}
4859	return (0);
4860}
4861
4862int
4863ctl_lun_ejected(struct ctl_be_lun *be_lun)
4864{
4865	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4866
4867	mtx_lock(&lun->lun_lock);
4868	lun->flags |= CTL_LUN_EJECTED;
4869	mtx_unlock(&lun->lun_lock);
4870	return (0);
4871}
4872
4873int
4874ctl_lun_primary(struct ctl_be_lun *be_lun)
4875{
4876	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4877
4878	mtx_lock(&lun->lun_lock);
4879	lun->flags |= CTL_LUN_PRIMARY_SC;
4880	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4881	mtx_unlock(&lun->lun_lock);
4882	ctl_isc_announce_lun(lun);
4883	return (0);
4884}
4885
4886int
4887ctl_lun_secondary(struct ctl_be_lun *be_lun)
4888{
4889	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4890
4891	mtx_lock(&lun->lun_lock);
4892	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4893	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4894	mtx_unlock(&lun->lun_lock);
4895	ctl_isc_announce_lun(lun);
4896	return (0);
4897}
4898
4899int
4900ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4901{
4902	struct ctl_softc *softc;
4903	struct ctl_lun *lun;
4904
4905	lun = (struct ctl_lun *)be_lun->ctl_lun;
4906	softc = lun->ctl_softc;
4907
4908	mtx_lock(&lun->lun_lock);
4909
4910	/*
4911	 * The LUN needs to be disabled before it can be marked invalid.
4912	 */
4913	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4914		mtx_unlock(&lun->lun_lock);
4915		return (-1);
4916	}
4917	/*
4918	 * Mark the LUN invalid.
4919	 */
4920	lun->flags |= CTL_LUN_INVALID;
4921
4922	/*
4923	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4924	 * If we have something in the OOA queue, we'll free it when the
4925	 * last I/O completes.
4926	 */
4927	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4928		mtx_unlock(&lun->lun_lock);
4929		mtx_lock(&softc->ctl_lock);
4930		ctl_free_lun(lun);
4931		mtx_unlock(&softc->ctl_lock);
4932	} else
4933		mtx_unlock(&lun->lun_lock);
4934
4935	return (0);
4936}
4937
4938void
4939ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4940{
4941	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4942	union ctl_ha_msg msg;
4943
4944	mtx_lock(&lun->lun_lock);
4945	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4946	mtx_unlock(&lun->lun_lock);
4947	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4948		/* Send msg to other side. */
4949		bzero(&msg.ua, sizeof(msg.ua));
4950		msg.hdr.msg_type = CTL_MSG_UA;
4951		msg.hdr.nexus.initid = -1;
4952		msg.hdr.nexus.targ_port = -1;
4953		msg.hdr.nexus.targ_lun = lun->lun;
4954		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4955		msg.ua.ua_all = 1;
4956		msg.ua.ua_set = 1;
4957		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4958		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4959		    M_WAITOK);
4960	}
4961}
4962
4963/*
4964 * Backend "memory move is complete" callback for requests that never
4965 * make it down to say RAIDCore's configuration code.
4966 */
4967int
4968ctl_config_move_done(union ctl_io *io)
4969{
4970	int retval;
4971
4972	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4973	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4974	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4975
4976	if ((io->io_hdr.port_status != 0) &&
4977	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4978	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4979		/*
4980		 * For hardware error sense keys, the sense key
4981		 * specific value is defined to be a retry count,
4982		 * but we use it to pass back an internal FETD
4983		 * error code.  XXX KDM  Hopefully the FETD is only
4984		 * using 16 bits for an error code, since that's
4985		 * all the space we have in the sks field.
4986		 */
4987		ctl_set_internal_failure(&io->scsiio,
4988					 /*sks_valid*/ 1,
4989					 /*retry_count*/
4990					 io->io_hdr.port_status);
4991	}
4992
4993	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4994		ctl_data_print(io);
4995	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4996	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4997	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4998	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4999		/*
5000		 * XXX KDM just assuming a single pointer here, and not a
5001		 * S/G list.  If we start using S/G lists for config data,
5002		 * we'll need to know how to clean them up here as well.
5003		 */
5004		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5005			free(io->scsiio.kern_data_ptr, M_CTL);
5006		ctl_done(io);
5007		retval = CTL_RETVAL_COMPLETE;
5008	} else {
5009		/*
5010		 * XXX KDM now we need to continue data movement.  Some
5011		 * options:
5012		 * - call ctl_scsiio() again?  We don't do this for data
5013		 *   writes, because for those at least we know ahead of
5014		 *   time where the write will go and how long it is.  For
5015		 *   config writes, though, that information is largely
5016		 *   contained within the write itself, thus we need to
5017		 *   parse out the data again.
5018		 *
5019		 * - Call some other function once the data is in?
5020		 */
5021
5022		/*
5023		 * XXX KDM call ctl_scsiio() again for now, and check flag
5024		 * bits to see whether we're allocated or not.
5025		 */
5026		retval = ctl_scsiio(&io->scsiio);
5027	}
5028	return (retval);
5029}
5030
5031/*
5032 * This gets called by a backend driver when it is done with a
5033 * data_submit method.
5034 */
5035void
5036ctl_data_submit_done(union ctl_io *io)
5037{
5038	/*
5039	 * If the IO_CONT flag is set, we need to call the supplied
5040	 * function to continue processing the I/O, instead of completing
5041	 * the I/O just yet.
5042	 *
5043	 * If there is an error, though, we don't want to keep processing.
5044	 * Instead, just send status back to the initiator.
5045	 */
5046	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5047	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5048	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5049	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5050		io->scsiio.io_cont(io);
5051		return;
5052	}
5053	ctl_done(io);
5054}
5055
5056/*
5057 * This gets called by a backend driver when it is done with a
5058 * configuration write.
5059 */
5060void
5061ctl_config_write_done(union ctl_io *io)
5062{
5063	uint8_t *buf;
5064
5065	/*
5066	 * If the IO_CONT flag is set, we need to call the supplied
5067	 * function to continue processing the I/O, instead of completing
5068	 * the I/O just yet.
5069	 *
5070	 * If there is an error, though, we don't want to keep processing.
5071	 * Instead, just send status back to the initiator.
5072	 */
5073	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5074	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5075	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5076	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5077		io->scsiio.io_cont(io);
5078		return;
5079	}
5080	/*
5081	 * Since a configuration write can be done for commands that actually
5082	 * have data allocated, like write buffer, and commands that have
5083	 * no data, like start/stop unit, we need to check here.
5084	 */
5085	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5086		buf = io->scsiio.kern_data_ptr;
5087	else
5088		buf = NULL;
5089	ctl_done(io);
5090	if (buf)
5091		free(buf, M_CTL);
5092}
5093
5094void
5095ctl_config_read_done(union ctl_io *io)
5096{
5097	uint8_t *buf;
5098
5099	/*
5100	 * If there is some error -- we are done, skip data transfer.
5101	 */
5102	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5103	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5104	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5105		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5106			buf = io->scsiio.kern_data_ptr;
5107		else
5108			buf = NULL;
5109		ctl_done(io);
5110		if (buf)
5111			free(buf, M_CTL);
5112		return;
5113	}
5114
5115	/*
5116	 * If the IO_CONT flag is set, we need to call the supplied
5117	 * function to continue processing the I/O, instead of completing
5118	 * the I/O just yet.
5119	 */
5120	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5121		io->scsiio.io_cont(io);
5122		return;
5123	}
5124
5125	ctl_datamove(io);
5126}
5127
5128/*
5129 * SCSI release command.
5130 */
5131int
5132ctl_scsi_release(struct ctl_scsiio *ctsio)
5133{
5134	struct ctl_lun *lun;
5135	uint32_t residx;
5136
5137	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5138
5139	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5140	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5141
5142	/*
5143	 * XXX KDM right now, we only support LUN reservation.  We don't
5144	 * support 3rd party reservations, or extent reservations, which
5145	 * might actually need the parameter list.  If we've gotten this
5146	 * far, we've got a LUN reservation.  Anything else got kicked out
5147	 * above.  So, according to SPC, ignore the length.
5148	 */
5149
5150	mtx_lock(&lun->lun_lock);
5151
5152	/*
5153	 * According to SPC, it is not an error for an intiator to attempt
5154	 * to release a reservation on a LUN that isn't reserved, or that
5155	 * is reserved by another initiator.  The reservation can only be
5156	 * released, though, by the initiator who made it or by one of
5157	 * several reset type events.
5158	 */
5159	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5160			lun->flags &= ~CTL_LUN_RESERVED;
5161
5162	mtx_unlock(&lun->lun_lock);
5163
5164	ctl_set_success(ctsio);
5165	ctl_done((union ctl_io *)ctsio);
5166	return (CTL_RETVAL_COMPLETE);
5167}
5168
5169int
5170ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5171{
5172	struct ctl_lun *lun;
5173	uint32_t residx;
5174
5175	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5176
5177	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5178	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5179
5180	/*
5181	 * XXX KDM right now, we only support LUN reservation.  We don't
5182	 * support 3rd party reservations, or extent reservations, which
5183	 * might actually need the parameter list.  If we've gotten this
5184	 * far, we've got a LUN reservation.  Anything else got kicked out
5185	 * above.  So, according to SPC, ignore the length.
5186	 */
5187
5188	mtx_lock(&lun->lun_lock);
5189	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5190		ctl_set_reservation_conflict(ctsio);
5191		goto bailout;
5192	}
5193
5194	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5195	if (lun->flags & CTL_LUN_PR_RESERVED) {
5196		ctl_set_success(ctsio);
5197		goto bailout;
5198	}
5199
5200	lun->flags |= CTL_LUN_RESERVED;
5201	lun->res_idx = residx;
5202	ctl_set_success(ctsio);
5203
5204bailout:
5205	mtx_unlock(&lun->lun_lock);
5206	ctl_done((union ctl_io *)ctsio);
5207	return (CTL_RETVAL_COMPLETE);
5208}
5209
5210int
5211ctl_start_stop(struct ctl_scsiio *ctsio)
5212{
5213	struct scsi_start_stop_unit *cdb;
5214	struct ctl_lun *lun;
5215	int retval;
5216
5217	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5218
5219	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5220	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5221
5222	if ((cdb->how & SSS_PC_MASK) == 0) {
5223		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5224		    (cdb->how & SSS_START) == 0) {
5225			uint32_t residx;
5226
5227			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5228			if (ctl_get_prkey(lun, residx) == 0 ||
5229			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5230
5231				ctl_set_reservation_conflict(ctsio);
5232				ctl_done((union ctl_io *)ctsio);
5233				return (CTL_RETVAL_COMPLETE);
5234			}
5235		}
5236
5237		if ((cdb->how & SSS_LOEJ) &&
5238		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5239			ctl_set_invalid_field(ctsio,
5240					      /*sks_valid*/ 1,
5241					      /*command*/ 1,
5242					      /*field*/ 4,
5243					      /*bit_valid*/ 1,
5244					      /*bit*/ 1);
5245			ctl_done((union ctl_io *)ctsio);
5246			return (CTL_RETVAL_COMPLETE);
5247		}
5248
5249		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5250		    lun->prevent_count > 0) {
5251			/* "Medium removal prevented" */
5252			ctl_set_sense(ctsio, /*current_error*/ 1,
5253			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5254			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5255			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5256			ctl_done((union ctl_io *)ctsio);
5257			return (CTL_RETVAL_COMPLETE);
5258		}
5259	}
5260
5261	retval = lun->backend->config_write((union ctl_io *)ctsio);
5262	return (retval);
5263}
5264
5265int
5266ctl_prevent_allow(struct ctl_scsiio *ctsio)
5267{
5268	struct ctl_lun *lun;
5269	struct scsi_prevent *cdb;
5270	int retval;
5271	uint32_t initidx;
5272
5273	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5274
5275	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5276	cdb = (struct scsi_prevent *)ctsio->cdb;
5277
5278	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5279		ctl_set_invalid_opcode(ctsio);
5280		ctl_done((union ctl_io *)ctsio);
5281		return (CTL_RETVAL_COMPLETE);
5282	}
5283
5284	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5285	mtx_lock(&lun->lun_lock);
5286	if ((cdb->how & PR_PREVENT) &&
5287	    ctl_is_set(lun->prevent, initidx) == 0) {
5288		ctl_set_mask(lun->prevent, initidx);
5289		lun->prevent_count++;
5290	} else if ((cdb->how & PR_PREVENT) == 0 &&
5291	    ctl_is_set(lun->prevent, initidx)) {
5292		ctl_clear_mask(lun->prevent, initidx);
5293		lun->prevent_count--;
5294	}
5295	mtx_unlock(&lun->lun_lock);
5296	retval = lun->backend->config_write((union ctl_io *)ctsio);
5297	return (retval);
5298}
5299
5300/*
5301 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5302 * we don't really do anything with the LBA and length fields if the user
5303 * passes them in.  Instead we'll just flush out the cache for the entire
5304 * LUN.
5305 */
5306int
5307ctl_sync_cache(struct ctl_scsiio *ctsio)
5308{
5309	struct ctl_lun *lun;
5310	struct ctl_softc *softc;
5311	struct ctl_lba_len_flags *lbalen;
5312	uint64_t starting_lba;
5313	uint32_t block_count;
5314	int retval;
5315	uint8_t byte2;
5316
5317	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5318
5319	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5320	softc = lun->ctl_softc;
5321	retval = 0;
5322
5323	switch (ctsio->cdb[0]) {
5324	case SYNCHRONIZE_CACHE: {
5325		struct scsi_sync_cache *cdb;
5326		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5327
5328		starting_lba = scsi_4btoul(cdb->begin_lba);
5329		block_count = scsi_2btoul(cdb->lb_count);
5330		byte2 = cdb->byte2;
5331		break;
5332	}
5333	case SYNCHRONIZE_CACHE_16: {
5334		struct scsi_sync_cache_16 *cdb;
5335		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5336
5337		starting_lba = scsi_8btou64(cdb->begin_lba);
5338		block_count = scsi_4btoul(cdb->lb_count);
5339		byte2 = cdb->byte2;
5340		break;
5341	}
5342	default:
5343		ctl_set_invalid_opcode(ctsio);
5344		ctl_done((union ctl_io *)ctsio);
5345		goto bailout;
5346		break; /* NOTREACHED */
5347	}
5348
5349	/*
5350	 * We check the LBA and length, but don't do anything with them.
5351	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5352	 * get flushed.  This check will just help satisfy anyone who wants
5353	 * to see an error for an out of range LBA.
5354	 */
5355	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5356		ctl_set_lba_out_of_range(ctsio,
5357		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5358		ctl_done((union ctl_io *)ctsio);
5359		goto bailout;
5360	}
5361
5362	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5363	lbalen->lba = starting_lba;
5364	lbalen->len = block_count;
5365	lbalen->flags = byte2;
5366	retval = lun->backend->config_write((union ctl_io *)ctsio);
5367
5368bailout:
5369	return (retval);
5370}
5371
5372int
5373ctl_format(struct ctl_scsiio *ctsio)
5374{
5375	struct scsi_format *cdb;
5376	struct ctl_lun *lun;
5377	int length, defect_list_len;
5378
5379	CTL_DEBUG_PRINT(("ctl_format\n"));
5380
5381	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5382
5383	cdb = (struct scsi_format *)ctsio->cdb;
5384
5385	length = 0;
5386	if (cdb->byte2 & SF_FMTDATA) {
5387		if (cdb->byte2 & SF_LONGLIST)
5388			length = sizeof(struct scsi_format_header_long);
5389		else
5390			length = sizeof(struct scsi_format_header_short);
5391	}
5392
5393	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5394	 && (length > 0)) {
5395		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5396		ctsio->kern_data_len = length;
5397		ctsio->kern_total_len = length;
5398		ctsio->kern_data_resid = 0;
5399		ctsio->kern_rel_offset = 0;
5400		ctsio->kern_sg_entries = 0;
5401		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5402		ctsio->be_move_done = ctl_config_move_done;
5403		ctl_datamove((union ctl_io *)ctsio);
5404
5405		return (CTL_RETVAL_COMPLETE);
5406	}
5407
5408	defect_list_len = 0;
5409
5410	if (cdb->byte2 & SF_FMTDATA) {
5411		if (cdb->byte2 & SF_LONGLIST) {
5412			struct scsi_format_header_long *header;
5413
5414			header = (struct scsi_format_header_long *)
5415				ctsio->kern_data_ptr;
5416
5417			defect_list_len = scsi_4btoul(header->defect_list_len);
5418			if (defect_list_len != 0) {
5419				ctl_set_invalid_field(ctsio,
5420						      /*sks_valid*/ 1,
5421						      /*command*/ 0,
5422						      /*field*/ 2,
5423						      /*bit_valid*/ 0,
5424						      /*bit*/ 0);
5425				goto bailout;
5426			}
5427		} else {
5428			struct scsi_format_header_short *header;
5429
5430			header = (struct scsi_format_header_short *)
5431				ctsio->kern_data_ptr;
5432
5433			defect_list_len = scsi_2btoul(header->defect_list_len);
5434			if (defect_list_len != 0) {
5435				ctl_set_invalid_field(ctsio,
5436						      /*sks_valid*/ 1,
5437						      /*command*/ 0,
5438						      /*field*/ 2,
5439						      /*bit_valid*/ 0,
5440						      /*bit*/ 0);
5441				goto bailout;
5442			}
5443		}
5444	}
5445
5446	ctl_set_success(ctsio);
5447bailout:
5448
5449	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5450		free(ctsio->kern_data_ptr, M_CTL);
5451		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5452	}
5453
5454	ctl_done((union ctl_io *)ctsio);
5455	return (CTL_RETVAL_COMPLETE);
5456}
5457
5458int
5459ctl_read_buffer(struct ctl_scsiio *ctsio)
5460{
5461	struct ctl_lun *lun;
5462	uint64_t buffer_offset;
5463	uint32_t len;
5464	uint8_t byte2;
5465	static uint8_t descr[4];
5466	static uint8_t echo_descr[4] = { 0 };
5467
5468	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5469	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5470	switch (ctsio->cdb[0]) {
5471	case READ_BUFFER: {
5472		struct scsi_read_buffer *cdb;
5473
5474		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5475		buffer_offset = scsi_3btoul(cdb->offset);
5476		len = scsi_3btoul(cdb->length);
5477		byte2 = cdb->byte2;
5478		break;
5479	}
5480	case READ_BUFFER_16: {
5481		struct scsi_read_buffer_16 *cdb;
5482
5483		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5484		buffer_offset = scsi_8btou64(cdb->offset);
5485		len = scsi_4btoul(cdb->length);
5486		byte2 = cdb->byte2;
5487		break;
5488	}
5489	default: /* This shouldn't happen. */
5490		ctl_set_invalid_opcode(ctsio);
5491		ctl_done((union ctl_io *)ctsio);
5492		return (CTL_RETVAL_COMPLETE);
5493	}
5494
5495	if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5496	    (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5497	    (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5498		ctl_set_invalid_field(ctsio,
5499				      /*sks_valid*/ 1,
5500				      /*command*/ 1,
5501				      /*field*/ 1,
5502				      /*bit_valid*/ 1,
5503				      /*bit*/ 4);
5504		ctl_done((union ctl_io *)ctsio);
5505		return (CTL_RETVAL_COMPLETE);
5506	}
5507
5508	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5509	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5510		ctl_set_invalid_field(ctsio,
5511				      /*sks_valid*/ 1,
5512				      /*command*/ 1,
5513				      /*field*/ 6,
5514				      /*bit_valid*/ 0,
5515				      /*bit*/ 0);
5516		ctl_done((union ctl_io *)ctsio);
5517		return (CTL_RETVAL_COMPLETE);
5518	}
5519
5520	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5521		descr[0] = 0;
5522		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5523		ctsio->kern_data_ptr = descr;
5524		len = min(len, sizeof(descr));
5525	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5526		ctsio->kern_data_ptr = echo_descr;
5527		len = min(len, sizeof(echo_descr));
5528	} else {
5529		if (lun->write_buffer == NULL) {
5530			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5531			    M_CTL, M_WAITOK);
5532		}
5533		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5534	}
5535	ctsio->kern_data_len = len;
5536	ctsio->kern_total_len = len;
5537	ctsio->kern_data_resid = 0;
5538	ctsio->kern_rel_offset = 0;
5539	ctsio->kern_sg_entries = 0;
5540	ctl_set_success(ctsio);
5541	ctsio->be_move_done = ctl_config_move_done;
5542	ctl_datamove((union ctl_io *)ctsio);
5543	return (CTL_RETVAL_COMPLETE);
5544}
5545
5546int
5547ctl_write_buffer(struct ctl_scsiio *ctsio)
5548{
5549	struct scsi_write_buffer *cdb;
5550	struct ctl_lun *lun;
5551	int buffer_offset, len;
5552
5553	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5554
5555	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5556	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5557
5558	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5559		ctl_set_invalid_field(ctsio,
5560				      /*sks_valid*/ 1,
5561				      /*command*/ 1,
5562				      /*field*/ 1,
5563				      /*bit_valid*/ 1,
5564				      /*bit*/ 4);
5565		ctl_done((union ctl_io *)ctsio);
5566		return (CTL_RETVAL_COMPLETE);
5567	}
5568
5569	len = scsi_3btoul(cdb->length);
5570	buffer_offset = scsi_3btoul(cdb->offset);
5571
5572	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5573		ctl_set_invalid_field(ctsio,
5574				      /*sks_valid*/ 1,
5575				      /*command*/ 1,
5576				      /*field*/ 6,
5577				      /*bit_valid*/ 0,
5578				      /*bit*/ 0);
5579		ctl_done((union ctl_io *)ctsio);
5580		return (CTL_RETVAL_COMPLETE);
5581	}
5582
5583	/*
5584	 * If we've got a kernel request that hasn't been malloced yet,
5585	 * malloc it and tell the caller the data buffer is here.
5586	 */
5587	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5588		if (lun->write_buffer == NULL) {
5589			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5590			    M_CTL, M_WAITOK);
5591		}
5592		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5593		ctsio->kern_data_len = len;
5594		ctsio->kern_total_len = len;
5595		ctsio->kern_data_resid = 0;
5596		ctsio->kern_rel_offset = 0;
5597		ctsio->kern_sg_entries = 0;
5598		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5599		ctsio->be_move_done = ctl_config_move_done;
5600		ctl_datamove((union ctl_io *)ctsio);
5601
5602		return (CTL_RETVAL_COMPLETE);
5603	}
5604
5605	ctl_set_success(ctsio);
5606	ctl_done((union ctl_io *)ctsio);
5607	return (CTL_RETVAL_COMPLETE);
5608}
5609
5610int
5611ctl_write_same(struct ctl_scsiio *ctsio)
5612{
5613	struct ctl_lun *lun;
5614	struct ctl_lba_len_flags *lbalen;
5615	uint64_t lba;
5616	uint32_t num_blocks;
5617	int len, retval;
5618	uint8_t byte2;
5619
5620	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5621
5622	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5623
5624	switch (ctsio->cdb[0]) {
5625	case WRITE_SAME_10: {
5626		struct scsi_write_same_10 *cdb;
5627
5628		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5629
5630		lba = scsi_4btoul(cdb->addr);
5631		num_blocks = scsi_2btoul(cdb->length);
5632		byte2 = cdb->byte2;
5633		break;
5634	}
5635	case WRITE_SAME_16: {
5636		struct scsi_write_same_16 *cdb;
5637
5638		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5639
5640		lba = scsi_8btou64(cdb->addr);
5641		num_blocks = scsi_4btoul(cdb->length);
5642		byte2 = cdb->byte2;
5643		break;
5644	}
5645	default:
5646		/*
5647		 * We got a command we don't support.  This shouldn't
5648		 * happen, commands should be filtered out above us.
5649		 */
5650		ctl_set_invalid_opcode(ctsio);
5651		ctl_done((union ctl_io *)ctsio);
5652
5653		return (CTL_RETVAL_COMPLETE);
5654		break; /* NOTREACHED */
5655	}
5656
5657	/* ANCHOR flag can be used only together with UNMAP */
5658	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5659		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5660		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5661		ctl_done((union ctl_io *)ctsio);
5662		return (CTL_RETVAL_COMPLETE);
5663	}
5664
5665	/*
5666	 * The first check is to make sure we're in bounds, the second
5667	 * check is to catch wrap-around problems.  If the lba + num blocks
5668	 * is less than the lba, then we've wrapped around and the block
5669	 * range is invalid anyway.
5670	 */
5671	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5672	 || ((lba + num_blocks) < lba)) {
5673		ctl_set_lba_out_of_range(ctsio,
5674		    MAX(lba, lun->be_lun->maxlba + 1));
5675		ctl_done((union ctl_io *)ctsio);
5676		return (CTL_RETVAL_COMPLETE);
5677	}
5678
5679	/* Zero number of blocks means "to the last logical block" */
5680	if (num_blocks == 0) {
5681		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5682			ctl_set_invalid_field(ctsio,
5683					      /*sks_valid*/ 0,
5684					      /*command*/ 1,
5685					      /*field*/ 0,
5686					      /*bit_valid*/ 0,
5687					      /*bit*/ 0);
5688			ctl_done((union ctl_io *)ctsio);
5689			return (CTL_RETVAL_COMPLETE);
5690		}
5691		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5692	}
5693
5694	len = lun->be_lun->blocksize;
5695
5696	/*
5697	 * If we've got a kernel request that hasn't been malloced yet,
5698	 * malloc it and tell the caller the data buffer is here.
5699	 */
5700	if ((byte2 & SWS_NDOB) == 0 &&
5701	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5702		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5703		ctsio->kern_data_len = len;
5704		ctsio->kern_total_len = len;
5705		ctsio->kern_data_resid = 0;
5706		ctsio->kern_rel_offset = 0;
5707		ctsio->kern_sg_entries = 0;
5708		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5709		ctsio->be_move_done = ctl_config_move_done;
5710		ctl_datamove((union ctl_io *)ctsio);
5711
5712		return (CTL_RETVAL_COMPLETE);
5713	}
5714
5715	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5716	lbalen->lba = lba;
5717	lbalen->len = num_blocks;
5718	lbalen->flags = byte2;
5719	retval = lun->backend->config_write((union ctl_io *)ctsio);
5720
5721	return (retval);
5722}
5723
5724int
5725ctl_unmap(struct ctl_scsiio *ctsio)
5726{
5727	struct ctl_lun *lun;
5728	struct scsi_unmap *cdb;
5729	struct ctl_ptr_len_flags *ptrlen;
5730	struct scsi_unmap_header *hdr;
5731	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5732	uint64_t lba;
5733	uint32_t num_blocks;
5734	int len, retval;
5735	uint8_t byte2;
5736
5737	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5738
5739	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5740	cdb = (struct scsi_unmap *)ctsio->cdb;
5741
5742	len = scsi_2btoul(cdb->length);
5743	byte2 = cdb->byte2;
5744
5745	/*
5746	 * If we've got a kernel request that hasn't been malloced yet,
5747	 * malloc it and tell the caller the data buffer is here.
5748	 */
5749	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5750		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5751		ctsio->kern_data_len = len;
5752		ctsio->kern_total_len = len;
5753		ctsio->kern_data_resid = 0;
5754		ctsio->kern_rel_offset = 0;
5755		ctsio->kern_sg_entries = 0;
5756		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5757		ctsio->be_move_done = ctl_config_move_done;
5758		ctl_datamove((union ctl_io *)ctsio);
5759
5760		return (CTL_RETVAL_COMPLETE);
5761	}
5762
5763	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5764	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5765	if (len < sizeof (*hdr) ||
5766	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5767	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5768	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5769		ctl_set_invalid_field(ctsio,
5770				      /*sks_valid*/ 0,
5771				      /*command*/ 0,
5772				      /*field*/ 0,
5773				      /*bit_valid*/ 0,
5774				      /*bit*/ 0);
5775		goto done;
5776	}
5777	len = scsi_2btoul(hdr->desc_length);
5778	buf = (struct scsi_unmap_desc *)(hdr + 1);
5779	end = buf + len / sizeof(*buf);
5780
5781	endnz = buf;
5782	for (range = buf; range < end; range++) {
5783		lba = scsi_8btou64(range->lba);
5784		num_blocks = scsi_4btoul(range->length);
5785		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5786		 || ((lba + num_blocks) < lba)) {
5787			ctl_set_lba_out_of_range(ctsio,
5788			    MAX(lba, lun->be_lun->maxlba + 1));
5789			ctl_done((union ctl_io *)ctsio);
5790			return (CTL_RETVAL_COMPLETE);
5791		}
5792		if (num_blocks != 0)
5793			endnz = range + 1;
5794	}
5795
5796	/*
5797	 * Block backend can not handle zero last range.
5798	 * Filter it out and return if there is nothing left.
5799	 */
5800	len = (uint8_t *)endnz - (uint8_t *)buf;
5801	if (len == 0) {
5802		ctl_set_success(ctsio);
5803		goto done;
5804	}
5805
5806	mtx_lock(&lun->lun_lock);
5807	ptrlen = (struct ctl_ptr_len_flags *)
5808	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5809	ptrlen->ptr = (void *)buf;
5810	ptrlen->len = len;
5811	ptrlen->flags = byte2;
5812	ctl_check_blocked(lun);
5813	mtx_unlock(&lun->lun_lock);
5814
5815	retval = lun->backend->config_write((union ctl_io *)ctsio);
5816	return (retval);
5817
5818done:
5819	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5820		free(ctsio->kern_data_ptr, M_CTL);
5821		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5822	}
5823	ctl_done((union ctl_io *)ctsio);
5824	return (CTL_RETVAL_COMPLETE);
5825}
5826
5827int
5828ctl_default_page_handler(struct ctl_scsiio *ctsio,
5829			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5830{
5831	struct ctl_lun *lun;
5832	uint8_t *current_cp, *saved_cp;
5833	int set_ua;
5834	uint32_t initidx;
5835
5836	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5837	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5838	set_ua = 0;
5839
5840	current_cp = (page_index->page_data + (page_index->page_len *
5841	    CTL_PAGE_CURRENT));
5842	saved_cp = (page_index->page_data + (page_index->page_len *
5843	    CTL_PAGE_SAVED));
5844
5845	mtx_lock(&lun->lun_lock);
5846	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5847		memcpy(current_cp, page_ptr, page_index->page_len);
5848		memcpy(saved_cp, page_ptr, page_index->page_len);
5849		set_ua = 1;
5850	}
5851	if (set_ua != 0)
5852		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5853	mtx_unlock(&lun->lun_lock);
5854	if (set_ua) {
5855		ctl_isc_announce_mode(lun,
5856		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5857		    page_index->page_code, page_index->subpage);
5858	}
5859	return (CTL_RETVAL_COMPLETE);
5860}
5861
5862static void
5863ctl_ie_timer(void *arg)
5864{
5865	struct ctl_lun *lun = arg;
5866	uint64_t t;
5867
5868	if (lun->ie_asc == 0)
5869		return;
5870
5871	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5872		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5873	else
5874		lun->ie_reported = 0;
5875
5876	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5877		lun->ie_reportcnt++;
5878		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5879		if (t == 0 || t == UINT32_MAX)
5880			t = 3000;  /* 5 min */
5881		callout_schedule(&lun->ie_callout, t * hz / 10);
5882	}
5883}
5884
5885int
5886ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5887			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5888{
5889	struct scsi_info_exceptions_page *pg;
5890	struct ctl_lun *lun;
5891	uint64_t t;
5892
5893	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5894
5895	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5896	pg = (struct scsi_info_exceptions_page *)page_ptr;
5897	mtx_lock(&lun->lun_lock);
5898	if (pg->info_flags & SIEP_FLAGS_TEST) {
5899		lun->ie_asc = 0x5d;
5900		lun->ie_ascq = 0xff;
5901		if (pg->mrie == SIEP_MRIE_UA) {
5902			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5903			lun->ie_reported = 1;
5904		} else {
5905			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5906			lun->ie_reported = -1;
5907		}
5908		lun->ie_reportcnt = 1;
5909		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5910			lun->ie_reportcnt++;
5911			t = scsi_4btoul(pg->interval_timer);
5912			if (t == 0 || t == UINT32_MAX)
5913				t = 3000;  /* 5 min */
5914			callout_reset(&lun->ie_callout, t * hz / 10,
5915			    ctl_ie_timer, lun);
5916		}
5917	} else {
5918		lun->ie_asc = 0;
5919		lun->ie_ascq = 0;
5920		lun->ie_reported = 1;
5921		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5922		lun->ie_reportcnt = UINT32_MAX;
5923		callout_stop(&lun->ie_callout);
5924	}
5925	mtx_unlock(&lun->lun_lock);
5926	return (CTL_RETVAL_COMPLETE);
5927}
5928
5929static int
5930ctl_do_mode_select(union ctl_io *io)
5931{
5932	struct scsi_mode_page_header *page_header;
5933	struct ctl_page_index *page_index;
5934	struct ctl_scsiio *ctsio;
5935	int page_len, page_len_offset, page_len_size;
5936	union ctl_modepage_info *modepage_info;
5937	struct ctl_lun *lun;
5938	int *len_left, *len_used;
5939	int retval, i;
5940
5941	ctsio = &io->scsiio;
5942	page_index = NULL;
5943	page_len = 0;
5944	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5945
5946	modepage_info = (union ctl_modepage_info *)
5947		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5948	len_left = &modepage_info->header.len_left;
5949	len_used = &modepage_info->header.len_used;
5950
5951do_next_page:
5952
5953	page_header = (struct scsi_mode_page_header *)
5954		(ctsio->kern_data_ptr + *len_used);
5955
5956	if (*len_left == 0) {
5957		free(ctsio->kern_data_ptr, M_CTL);
5958		ctl_set_success(ctsio);
5959		ctl_done((union ctl_io *)ctsio);
5960		return (CTL_RETVAL_COMPLETE);
5961	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5962
5963		free(ctsio->kern_data_ptr, M_CTL);
5964		ctl_set_param_len_error(ctsio);
5965		ctl_done((union ctl_io *)ctsio);
5966		return (CTL_RETVAL_COMPLETE);
5967
5968	} else if ((page_header->page_code & SMPH_SPF)
5969		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5970
5971		free(ctsio->kern_data_ptr, M_CTL);
5972		ctl_set_param_len_error(ctsio);
5973		ctl_done((union ctl_io *)ctsio);
5974		return (CTL_RETVAL_COMPLETE);
5975	}
5976
5977
5978	/*
5979	 * XXX KDM should we do something with the block descriptor?
5980	 */
5981	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5982		page_index = &lun->mode_pages.index[i];
5983		if (lun->be_lun->lun_type == T_DIRECT &&
5984		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5985			continue;
5986		if (lun->be_lun->lun_type == T_PROCESSOR &&
5987		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5988			continue;
5989		if (lun->be_lun->lun_type == T_CDROM &&
5990		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5991			continue;
5992
5993		if ((page_index->page_code & SMPH_PC_MASK) !=
5994		    (page_header->page_code & SMPH_PC_MASK))
5995			continue;
5996
5997		/*
5998		 * If neither page has a subpage code, then we've got a
5999		 * match.
6000		 */
6001		if (((page_index->page_code & SMPH_SPF) == 0)
6002		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6003			page_len = page_header->page_length;
6004			break;
6005		}
6006
6007		/*
6008		 * If both pages have subpages, then the subpage numbers
6009		 * have to match.
6010		 */
6011		if ((page_index->page_code & SMPH_SPF)
6012		  && (page_header->page_code & SMPH_SPF)) {
6013			struct scsi_mode_page_header_sp *sph;
6014
6015			sph = (struct scsi_mode_page_header_sp *)page_header;
6016			if (page_index->subpage == sph->subpage) {
6017				page_len = scsi_2btoul(sph->page_length);
6018				break;
6019			}
6020		}
6021	}
6022
6023	/*
6024	 * If we couldn't find the page, or if we don't have a mode select
6025	 * handler for it, send back an error to the user.
6026	 */
6027	if ((i >= CTL_NUM_MODE_PAGES)
6028	 || (page_index->select_handler == NULL)) {
6029		ctl_set_invalid_field(ctsio,
6030				      /*sks_valid*/ 1,
6031				      /*command*/ 0,
6032				      /*field*/ *len_used,
6033				      /*bit_valid*/ 0,
6034				      /*bit*/ 0);
6035		free(ctsio->kern_data_ptr, M_CTL);
6036		ctl_done((union ctl_io *)ctsio);
6037		return (CTL_RETVAL_COMPLETE);
6038	}
6039
6040	if (page_index->page_code & SMPH_SPF) {
6041		page_len_offset = 2;
6042		page_len_size = 2;
6043	} else {
6044		page_len_size = 1;
6045		page_len_offset = 1;
6046	}
6047
6048	/*
6049	 * If the length the initiator gives us isn't the one we specify in
6050	 * the mode page header, or if they didn't specify enough data in
6051	 * the CDB to avoid truncating this page, kick out the request.
6052	 */
6053	if ((page_len != (page_index->page_len - page_len_offset -
6054			  page_len_size))
6055	 || (*len_left < page_index->page_len)) {
6056
6057
6058		ctl_set_invalid_field(ctsio,
6059				      /*sks_valid*/ 1,
6060				      /*command*/ 0,
6061				      /*field*/ *len_used + page_len_offset,
6062				      /*bit_valid*/ 0,
6063				      /*bit*/ 0);
6064		free(ctsio->kern_data_ptr, M_CTL);
6065		ctl_done((union ctl_io *)ctsio);
6066		return (CTL_RETVAL_COMPLETE);
6067	}
6068
6069	/*
6070	 * Run through the mode page, checking to make sure that the bits
6071	 * the user changed are actually legal for him to change.
6072	 */
6073	for (i = 0; i < page_index->page_len; i++) {
6074		uint8_t *user_byte, *change_mask, *current_byte;
6075		int bad_bit;
6076		int j;
6077
6078		user_byte = (uint8_t *)page_header + i;
6079		change_mask = page_index->page_data +
6080			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6081		current_byte = page_index->page_data +
6082			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6083
6084		/*
6085		 * Check to see whether the user set any bits in this byte
6086		 * that he is not allowed to set.
6087		 */
6088		if ((*user_byte & ~(*change_mask)) ==
6089		    (*current_byte & ~(*change_mask)))
6090			continue;
6091
6092		/*
6093		 * Go through bit by bit to determine which one is illegal.
6094		 */
6095		bad_bit = 0;
6096		for (j = 7; j >= 0; j--) {
6097			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6098			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6099				bad_bit = i;
6100				break;
6101			}
6102		}
6103		ctl_set_invalid_field(ctsio,
6104				      /*sks_valid*/ 1,
6105				      /*command*/ 0,
6106				      /*field*/ *len_used + i,
6107				      /*bit_valid*/ 1,
6108				      /*bit*/ bad_bit);
6109		free(ctsio->kern_data_ptr, M_CTL);
6110		ctl_done((union ctl_io *)ctsio);
6111		return (CTL_RETVAL_COMPLETE);
6112	}
6113
6114	/*
6115	 * Decrement these before we call the page handler, since we may
6116	 * end up getting called back one way or another before the handler
6117	 * returns to this context.
6118	 */
6119	*len_left -= page_index->page_len;
6120	*len_used += page_index->page_len;
6121
6122	retval = page_index->select_handler(ctsio, page_index,
6123					    (uint8_t *)page_header);
6124
6125	/*
6126	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6127	 * wait until this queued command completes to finish processing
6128	 * the mode page.  If it returns anything other than
6129	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6130	 * already set the sense information, freed the data pointer, and
6131	 * completed the io for us.
6132	 */
6133	if (retval != CTL_RETVAL_COMPLETE)
6134		goto bailout_no_done;
6135
6136	/*
6137	 * If the initiator sent us more than one page, parse the next one.
6138	 */
6139	if (*len_left > 0)
6140		goto do_next_page;
6141
6142	ctl_set_success(ctsio);
6143	free(ctsio->kern_data_ptr, M_CTL);
6144	ctl_done((union ctl_io *)ctsio);
6145
6146bailout_no_done:
6147
6148	return (CTL_RETVAL_COMPLETE);
6149
6150}
6151
6152int
6153ctl_mode_select(struct ctl_scsiio *ctsio)
6154{
6155	int param_len, pf, sp;
6156	int header_size, bd_len;
6157	union ctl_modepage_info *modepage_info;
6158
6159	switch (ctsio->cdb[0]) {
6160	case MODE_SELECT_6: {
6161		struct scsi_mode_select_6 *cdb;
6162
6163		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6164
6165		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6166		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6167		param_len = cdb->length;
6168		header_size = sizeof(struct scsi_mode_header_6);
6169		break;
6170	}
6171	case MODE_SELECT_10: {
6172		struct scsi_mode_select_10 *cdb;
6173
6174		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6175
6176		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6177		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6178		param_len = scsi_2btoul(cdb->length);
6179		header_size = sizeof(struct scsi_mode_header_10);
6180		break;
6181	}
6182	default:
6183		ctl_set_invalid_opcode(ctsio);
6184		ctl_done((union ctl_io *)ctsio);
6185		return (CTL_RETVAL_COMPLETE);
6186	}
6187
6188	/*
6189	 * From SPC-3:
6190	 * "A parameter list length of zero indicates that the Data-Out Buffer
6191	 * shall be empty. This condition shall not be considered as an error."
6192	 */
6193	if (param_len == 0) {
6194		ctl_set_success(ctsio);
6195		ctl_done((union ctl_io *)ctsio);
6196		return (CTL_RETVAL_COMPLETE);
6197	}
6198
6199	/*
6200	 * Since we'll hit this the first time through, prior to
6201	 * allocation, we don't need to free a data buffer here.
6202	 */
6203	if (param_len < header_size) {
6204		ctl_set_param_len_error(ctsio);
6205		ctl_done((union ctl_io *)ctsio);
6206		return (CTL_RETVAL_COMPLETE);
6207	}
6208
6209	/*
6210	 * Allocate the data buffer and grab the user's data.  In theory,
6211	 * we shouldn't have to sanity check the parameter list length here
6212	 * because the maximum size is 64K.  We should be able to malloc
6213	 * that much without too many problems.
6214	 */
6215	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6216		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6217		ctsio->kern_data_len = param_len;
6218		ctsio->kern_total_len = param_len;
6219		ctsio->kern_data_resid = 0;
6220		ctsio->kern_rel_offset = 0;
6221		ctsio->kern_sg_entries = 0;
6222		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6223		ctsio->be_move_done = ctl_config_move_done;
6224		ctl_datamove((union ctl_io *)ctsio);
6225
6226		return (CTL_RETVAL_COMPLETE);
6227	}
6228
6229	switch (ctsio->cdb[0]) {
6230	case MODE_SELECT_6: {
6231		struct scsi_mode_header_6 *mh6;
6232
6233		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6234		bd_len = mh6->blk_desc_len;
6235		break;
6236	}
6237	case MODE_SELECT_10: {
6238		struct scsi_mode_header_10 *mh10;
6239
6240		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6241		bd_len = scsi_2btoul(mh10->blk_desc_len);
6242		break;
6243	}
6244	default:
6245		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6246	}
6247
6248	if (param_len < (header_size + bd_len)) {
6249		free(ctsio->kern_data_ptr, M_CTL);
6250		ctl_set_param_len_error(ctsio);
6251		ctl_done((union ctl_io *)ctsio);
6252		return (CTL_RETVAL_COMPLETE);
6253	}
6254
6255	/*
6256	 * Set the IO_CONT flag, so that if this I/O gets passed to
6257	 * ctl_config_write_done(), it'll get passed back to
6258	 * ctl_do_mode_select() for further processing, or completion if
6259	 * we're all done.
6260	 */
6261	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6262	ctsio->io_cont = ctl_do_mode_select;
6263
6264	modepage_info = (union ctl_modepage_info *)
6265		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6266	memset(modepage_info, 0, sizeof(*modepage_info));
6267	modepage_info->header.len_left = param_len - header_size - bd_len;
6268	modepage_info->header.len_used = header_size + bd_len;
6269
6270	return (ctl_do_mode_select((union ctl_io *)ctsio));
6271}
6272
6273int
6274ctl_mode_sense(struct ctl_scsiio *ctsio)
6275{
6276	struct ctl_lun *lun;
6277	int pc, page_code, dbd, llba, subpage;
6278	int alloc_len, page_len, header_len, total_len;
6279	struct scsi_mode_block_descr *block_desc;
6280	struct ctl_page_index *page_index;
6281
6282	dbd = 0;
6283	llba = 0;
6284	block_desc = NULL;
6285
6286	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6287
6288	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6289	switch (ctsio->cdb[0]) {
6290	case MODE_SENSE_6: {
6291		struct scsi_mode_sense_6 *cdb;
6292
6293		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6294
6295		header_len = sizeof(struct scsi_mode_hdr_6);
6296		if (cdb->byte2 & SMS_DBD)
6297			dbd = 1;
6298		else
6299			header_len += sizeof(struct scsi_mode_block_descr);
6300
6301		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6302		page_code = cdb->page & SMS_PAGE_CODE;
6303		subpage = cdb->subpage;
6304		alloc_len = cdb->length;
6305		break;
6306	}
6307	case MODE_SENSE_10: {
6308		struct scsi_mode_sense_10 *cdb;
6309
6310		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6311
6312		header_len = sizeof(struct scsi_mode_hdr_10);
6313
6314		if (cdb->byte2 & SMS_DBD)
6315			dbd = 1;
6316		else
6317			header_len += sizeof(struct scsi_mode_block_descr);
6318		if (cdb->byte2 & SMS10_LLBAA)
6319			llba = 1;
6320		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6321		page_code = cdb->page & SMS_PAGE_CODE;
6322		subpage = cdb->subpage;
6323		alloc_len = scsi_2btoul(cdb->length);
6324		break;
6325	}
6326	default:
6327		ctl_set_invalid_opcode(ctsio);
6328		ctl_done((union ctl_io *)ctsio);
6329		return (CTL_RETVAL_COMPLETE);
6330		break; /* NOTREACHED */
6331	}
6332
6333	/*
6334	 * We have to make a first pass through to calculate the size of
6335	 * the pages that match the user's query.  Then we allocate enough
6336	 * memory to hold it, and actually copy the data into the buffer.
6337	 */
6338	switch (page_code) {
6339	case SMS_ALL_PAGES_PAGE: {
6340		u_int i;
6341
6342		page_len = 0;
6343
6344		/*
6345		 * At the moment, values other than 0 and 0xff here are
6346		 * reserved according to SPC-3.
6347		 */
6348		if ((subpage != SMS_SUBPAGE_PAGE_0)
6349		 && (subpage != SMS_SUBPAGE_ALL)) {
6350			ctl_set_invalid_field(ctsio,
6351					      /*sks_valid*/ 1,
6352					      /*command*/ 1,
6353					      /*field*/ 3,
6354					      /*bit_valid*/ 0,
6355					      /*bit*/ 0);
6356			ctl_done((union ctl_io *)ctsio);
6357			return (CTL_RETVAL_COMPLETE);
6358		}
6359
6360		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6361			page_index = &lun->mode_pages.index[i];
6362
6363			/* Make sure the page is supported for this dev type */
6364			if (lun->be_lun->lun_type == T_DIRECT &&
6365			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6366				continue;
6367			if (lun->be_lun->lun_type == T_PROCESSOR &&
6368			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6369				continue;
6370			if (lun->be_lun->lun_type == T_CDROM &&
6371			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6372				continue;
6373
6374			/*
6375			 * We don't use this subpage if the user didn't
6376			 * request all subpages.
6377			 */
6378			if ((page_index->subpage != 0)
6379			 && (subpage == SMS_SUBPAGE_PAGE_0))
6380				continue;
6381
6382#if 0
6383			printf("found page %#x len %d\n",
6384			       page_index->page_code & SMPH_PC_MASK,
6385			       page_index->page_len);
6386#endif
6387			page_len += page_index->page_len;
6388		}
6389		break;
6390	}
6391	default: {
6392		u_int i;
6393
6394		page_len = 0;
6395
6396		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6397			page_index = &lun->mode_pages.index[i];
6398
6399			/* Make sure the page is supported for this dev type */
6400			if (lun->be_lun->lun_type == T_DIRECT &&
6401			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6402				continue;
6403			if (lun->be_lun->lun_type == T_PROCESSOR &&
6404			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6405				continue;
6406			if (lun->be_lun->lun_type == T_CDROM &&
6407			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6408				continue;
6409
6410			/* Look for the right page code */
6411			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6412				continue;
6413
6414			/* Look for the right subpage or the subpage wildcard*/
6415			if ((page_index->subpage != subpage)
6416			 && (subpage != SMS_SUBPAGE_ALL))
6417				continue;
6418
6419#if 0
6420			printf("found page %#x len %d\n",
6421			       page_index->page_code & SMPH_PC_MASK,
6422			       page_index->page_len);
6423#endif
6424
6425			page_len += page_index->page_len;
6426		}
6427
6428		if (page_len == 0) {
6429			ctl_set_invalid_field(ctsio,
6430					      /*sks_valid*/ 1,
6431					      /*command*/ 1,
6432					      /*field*/ 2,
6433					      /*bit_valid*/ 1,
6434					      /*bit*/ 5);
6435			ctl_done((union ctl_io *)ctsio);
6436			return (CTL_RETVAL_COMPLETE);
6437		}
6438		break;
6439	}
6440	}
6441
6442	total_len = header_len + page_len;
6443#if 0
6444	printf("header_len = %d, page_len = %d, total_len = %d\n",
6445	       header_len, page_len, total_len);
6446#endif
6447
6448	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6449	ctsio->kern_sg_entries = 0;
6450	ctsio->kern_data_resid = 0;
6451	ctsio->kern_rel_offset = 0;
6452	if (total_len < alloc_len) {
6453		ctsio->residual = alloc_len - total_len;
6454		ctsio->kern_data_len = total_len;
6455		ctsio->kern_total_len = total_len;
6456	} else {
6457		ctsio->residual = 0;
6458		ctsio->kern_data_len = alloc_len;
6459		ctsio->kern_total_len = alloc_len;
6460	}
6461
6462	switch (ctsio->cdb[0]) {
6463	case MODE_SENSE_6: {
6464		struct scsi_mode_hdr_6 *header;
6465
6466		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6467
6468		header->datalen = MIN(total_len - 1, 254);
6469		if (lun->be_lun->lun_type == T_DIRECT) {
6470			header->dev_specific = 0x10; /* DPOFUA */
6471			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6472			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6473				header->dev_specific |= 0x80; /* WP */
6474		}
6475		if (dbd)
6476			header->block_descr_len = 0;
6477		else
6478			header->block_descr_len =
6479				sizeof(struct scsi_mode_block_descr);
6480		block_desc = (struct scsi_mode_block_descr *)&header[1];
6481		break;
6482	}
6483	case MODE_SENSE_10: {
6484		struct scsi_mode_hdr_10 *header;
6485		int datalen;
6486
6487		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6488
6489		datalen = MIN(total_len - 2, 65533);
6490		scsi_ulto2b(datalen, header->datalen);
6491		if (lun->be_lun->lun_type == T_DIRECT) {
6492			header->dev_specific = 0x10; /* DPOFUA */
6493			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6494			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6495				header->dev_specific |= 0x80; /* WP */
6496		}
6497		if (dbd)
6498			scsi_ulto2b(0, header->block_descr_len);
6499		else
6500			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6501				    header->block_descr_len);
6502		block_desc = (struct scsi_mode_block_descr *)&header[1];
6503		break;
6504	}
6505	default:
6506		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6507	}
6508
6509	/*
6510	 * If we've got a disk, use its blocksize in the block
6511	 * descriptor.  Otherwise, just set it to 0.
6512	 */
6513	if (dbd == 0) {
6514		if (lun->be_lun->lun_type == T_DIRECT)
6515			scsi_ulto3b(lun->be_lun->blocksize,
6516				    block_desc->block_len);
6517		else
6518			scsi_ulto3b(0, block_desc->block_len);
6519	}
6520
6521	switch (page_code) {
6522	case SMS_ALL_PAGES_PAGE: {
6523		int i, data_used;
6524
6525		data_used = header_len;
6526		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6527			struct ctl_page_index *page_index;
6528
6529			page_index = &lun->mode_pages.index[i];
6530			if (lun->be_lun->lun_type == T_DIRECT &&
6531			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6532				continue;
6533			if (lun->be_lun->lun_type == T_PROCESSOR &&
6534			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6535				continue;
6536			if (lun->be_lun->lun_type == T_CDROM &&
6537			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6538				continue;
6539
6540			/*
6541			 * We don't use this subpage if the user didn't
6542			 * request all subpages.  We already checked (above)
6543			 * to make sure the user only specified a subpage
6544			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6545			 */
6546			if ((page_index->subpage != 0)
6547			 && (subpage == SMS_SUBPAGE_PAGE_0))
6548				continue;
6549
6550			/*
6551			 * Call the handler, if it exists, to update the
6552			 * page to the latest values.
6553			 */
6554			if (page_index->sense_handler != NULL)
6555				page_index->sense_handler(ctsio, page_index,pc);
6556
6557			memcpy(ctsio->kern_data_ptr + data_used,
6558			       page_index->page_data +
6559			       (page_index->page_len * pc),
6560			       page_index->page_len);
6561			data_used += page_index->page_len;
6562		}
6563		break;
6564	}
6565	default: {
6566		int i, data_used;
6567
6568		data_used = header_len;
6569
6570		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6571			struct ctl_page_index *page_index;
6572
6573			page_index = &lun->mode_pages.index[i];
6574
6575			/* Look for the right page code */
6576			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6577				continue;
6578
6579			/* Look for the right subpage or the subpage wildcard*/
6580			if ((page_index->subpage != subpage)
6581			 && (subpage != SMS_SUBPAGE_ALL))
6582				continue;
6583
6584			/* Make sure the page is supported for this dev type */
6585			if (lun->be_lun->lun_type == T_DIRECT &&
6586			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6587				continue;
6588			if (lun->be_lun->lun_type == T_PROCESSOR &&
6589			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6590				continue;
6591			if (lun->be_lun->lun_type == T_CDROM &&
6592			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6593				continue;
6594
6595			/*
6596			 * Call the handler, if it exists, to update the
6597			 * page to the latest values.
6598			 */
6599			if (page_index->sense_handler != NULL)
6600				page_index->sense_handler(ctsio, page_index,pc);
6601
6602			memcpy(ctsio->kern_data_ptr + data_used,
6603			       page_index->page_data +
6604			       (page_index->page_len * pc),
6605			       page_index->page_len);
6606			data_used += page_index->page_len;
6607		}
6608		break;
6609	}
6610	}
6611
6612	ctl_set_success(ctsio);
6613	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6614	ctsio->be_move_done = ctl_config_move_done;
6615	ctl_datamove((union ctl_io *)ctsio);
6616	return (CTL_RETVAL_COMPLETE);
6617}
6618
6619int
6620ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6621			       struct ctl_page_index *page_index,
6622			       int pc)
6623{
6624	struct ctl_lun *lun;
6625	struct scsi_log_param_header *phdr;
6626	uint8_t *data;
6627	uint64_t val;
6628
6629	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6630	data = page_index->page_data;
6631
6632	if (lun->backend->lun_attr != NULL &&
6633	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6634	     != UINT64_MAX) {
6635		phdr = (struct scsi_log_param_header *)data;
6636		scsi_ulto2b(0x0001, phdr->param_code);
6637		phdr->param_control = SLP_LBIN | SLP_LP;
6638		phdr->param_len = 8;
6639		data = (uint8_t *)(phdr + 1);
6640		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6641		data[4] = 0x02; /* per-pool */
6642		data += phdr->param_len;
6643	}
6644
6645	if (lun->backend->lun_attr != NULL &&
6646	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6647	     != UINT64_MAX) {
6648		phdr = (struct scsi_log_param_header *)data;
6649		scsi_ulto2b(0x0002, phdr->param_code);
6650		phdr->param_control = SLP_LBIN | SLP_LP;
6651		phdr->param_len = 8;
6652		data = (uint8_t *)(phdr + 1);
6653		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6654		data[4] = 0x01; /* per-LUN */
6655		data += phdr->param_len;
6656	}
6657
6658	if (lun->backend->lun_attr != NULL &&
6659	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6660	     != UINT64_MAX) {
6661		phdr = (struct scsi_log_param_header *)data;
6662		scsi_ulto2b(0x00f1, phdr->param_code);
6663		phdr->param_control = SLP_LBIN | SLP_LP;
6664		phdr->param_len = 8;
6665		data = (uint8_t *)(phdr + 1);
6666		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6667		data[4] = 0x02; /* per-pool */
6668		data += phdr->param_len;
6669	}
6670
6671	if (lun->backend->lun_attr != NULL &&
6672	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6673	     != UINT64_MAX) {
6674		phdr = (struct scsi_log_param_header *)data;
6675		scsi_ulto2b(0x00f2, phdr->param_code);
6676		phdr->param_control = SLP_LBIN | SLP_LP;
6677		phdr->param_len = 8;
6678		data = (uint8_t *)(phdr + 1);
6679		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6680		data[4] = 0x02; /* per-pool */
6681		data += phdr->param_len;
6682	}
6683
6684	page_index->page_len = data - page_index->page_data;
6685	return (0);
6686}
6687
6688int
6689ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6690			       struct ctl_page_index *page_index,
6691			       int pc)
6692{
6693	struct ctl_lun *lun;
6694	struct stat_page *data;
6695	uint64_t rn, wn, rb, wb;
6696	struct bintime rt, wt;
6697	int i;
6698
6699	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6700	data = (struct stat_page *)page_index->page_data;
6701
6702	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6703	data->sap.hdr.param_control = SLP_LBIN;
6704	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6705	    sizeof(struct scsi_log_param_header);
6706	rn = wn = rb = wb = 0;
6707	bintime_clear(&rt);
6708	bintime_clear(&wt);
6709	for (i = 0; i < CTL_MAX_PORTS; i++) {
6710		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6711		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6712		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6713		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6714		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6715		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6716	}
6717	scsi_u64to8b(rn, data->sap.read_num);
6718	scsi_u64to8b(wn, data->sap.write_num);
6719	if (lun->stats.blocksize > 0) {
6720		scsi_u64to8b(wb / lun->stats.blocksize,
6721		    data->sap.recvieved_lba);
6722		scsi_u64to8b(rb / lun->stats.blocksize,
6723		    data->sap.transmitted_lba);
6724	}
6725	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6726	    data->sap.read_int);
6727	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6728	    data->sap.write_int);
6729	scsi_u64to8b(0, data->sap.weighted_num);
6730	scsi_u64to8b(0, data->sap.weighted_int);
6731	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6732	data->it.hdr.param_control = SLP_LBIN;
6733	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6734	    sizeof(struct scsi_log_param_header);
6735#ifdef CTL_TIME_IO
6736	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6737#endif
6738	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6739	data->it.hdr.param_control = SLP_LBIN;
6740	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6741	    sizeof(struct scsi_log_param_header);
6742	scsi_ulto4b(3, data->ti.exponent);
6743	scsi_ulto4b(1, data->ti.integer);
6744	return (0);
6745}
6746
6747int
6748ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6749			       struct ctl_page_index *page_index,
6750			       int pc)
6751{
6752	struct ctl_lun *lun;
6753	struct scsi_log_informational_exceptions *data;
6754
6755	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6756	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6757
6758	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6759	data->hdr.param_control = SLP_LBIN;
6760	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6761	    sizeof(struct scsi_log_param_header);
6762	data->ie_asc = lun->ie_asc;
6763	data->ie_ascq = lun->ie_ascq;
6764	data->temperature = 0xff;
6765	return (0);
6766}
6767
6768int
6769ctl_log_sense(struct ctl_scsiio *ctsio)
6770{
6771	struct ctl_lun *lun;
6772	int i, pc, page_code, subpage;
6773	int alloc_len, total_len;
6774	struct ctl_page_index *page_index;
6775	struct scsi_log_sense *cdb;
6776	struct scsi_log_header *header;
6777
6778	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6779
6780	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6781	cdb = (struct scsi_log_sense *)ctsio->cdb;
6782	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6783	page_code = cdb->page & SLS_PAGE_CODE;
6784	subpage = cdb->subpage;
6785	alloc_len = scsi_2btoul(cdb->length);
6786
6787	page_index = NULL;
6788	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6789		page_index = &lun->log_pages.index[i];
6790
6791		/* Look for the right page code */
6792		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6793			continue;
6794
6795		/* Look for the right subpage or the subpage wildcard*/
6796		if (page_index->subpage != subpage)
6797			continue;
6798
6799		break;
6800	}
6801	if (i >= CTL_NUM_LOG_PAGES) {
6802		ctl_set_invalid_field(ctsio,
6803				      /*sks_valid*/ 1,
6804				      /*command*/ 1,
6805				      /*field*/ 2,
6806				      /*bit_valid*/ 0,
6807				      /*bit*/ 0);
6808		ctl_done((union ctl_io *)ctsio);
6809		return (CTL_RETVAL_COMPLETE);
6810	}
6811
6812	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6813
6814	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6815	ctsio->kern_sg_entries = 0;
6816	ctsio->kern_data_resid = 0;
6817	ctsio->kern_rel_offset = 0;
6818	if (total_len < alloc_len) {
6819		ctsio->residual = alloc_len - total_len;
6820		ctsio->kern_data_len = total_len;
6821		ctsio->kern_total_len = total_len;
6822	} else {
6823		ctsio->residual = 0;
6824		ctsio->kern_data_len = alloc_len;
6825		ctsio->kern_total_len = alloc_len;
6826	}
6827
6828	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6829	header->page = page_index->page_code;
6830	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6831		header->page |= SL_DS;
6832	if (page_index->subpage) {
6833		header->page |= SL_SPF;
6834		header->subpage = page_index->subpage;
6835	}
6836	scsi_ulto2b(page_index->page_len, header->datalen);
6837
6838	/*
6839	 * Call the handler, if it exists, to update the
6840	 * page to the latest values.
6841	 */
6842	if (page_index->sense_handler != NULL)
6843		page_index->sense_handler(ctsio, page_index, pc);
6844
6845	memcpy(header + 1, page_index->page_data, page_index->page_len);
6846
6847	ctl_set_success(ctsio);
6848	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6849	ctsio->be_move_done = ctl_config_move_done;
6850	ctl_datamove((union ctl_io *)ctsio);
6851	return (CTL_RETVAL_COMPLETE);
6852}
6853
6854int
6855ctl_read_capacity(struct ctl_scsiio *ctsio)
6856{
6857	struct scsi_read_capacity *cdb;
6858	struct scsi_read_capacity_data *data;
6859	struct ctl_lun *lun;
6860	uint32_t lba;
6861
6862	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6863
6864	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6865
6866	lba = scsi_4btoul(cdb->addr);
6867	if (((cdb->pmi & SRC_PMI) == 0)
6868	 && (lba != 0)) {
6869		ctl_set_invalid_field(/*ctsio*/ ctsio,
6870				      /*sks_valid*/ 1,
6871				      /*command*/ 1,
6872				      /*field*/ 2,
6873				      /*bit_valid*/ 0,
6874				      /*bit*/ 0);
6875		ctl_done((union ctl_io *)ctsio);
6876		return (CTL_RETVAL_COMPLETE);
6877	}
6878
6879	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6880
6881	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6882	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6883	ctsio->residual = 0;
6884	ctsio->kern_data_len = sizeof(*data);
6885	ctsio->kern_total_len = sizeof(*data);
6886	ctsio->kern_data_resid = 0;
6887	ctsio->kern_rel_offset = 0;
6888	ctsio->kern_sg_entries = 0;
6889
6890	/*
6891	 * If the maximum LBA is greater than 0xfffffffe, the user must
6892	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6893	 * serivce action set.
6894	 */
6895	if (lun->be_lun->maxlba > 0xfffffffe)
6896		scsi_ulto4b(0xffffffff, data->addr);
6897	else
6898		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6899
6900	/*
6901	 * XXX KDM this may not be 512 bytes...
6902	 */
6903	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6904
6905	ctl_set_success(ctsio);
6906	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6907	ctsio->be_move_done = ctl_config_move_done;
6908	ctl_datamove((union ctl_io *)ctsio);
6909	return (CTL_RETVAL_COMPLETE);
6910}
6911
6912int
6913ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6914{
6915	struct scsi_read_capacity_16 *cdb;
6916	struct scsi_read_capacity_data_long *data;
6917	struct ctl_lun *lun;
6918	uint64_t lba;
6919	uint32_t alloc_len;
6920
6921	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6922
6923	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6924
6925	alloc_len = scsi_4btoul(cdb->alloc_len);
6926	lba = scsi_8btou64(cdb->addr);
6927
6928	if ((cdb->reladr & SRC16_PMI)
6929	 && (lba != 0)) {
6930		ctl_set_invalid_field(/*ctsio*/ ctsio,
6931				      /*sks_valid*/ 1,
6932				      /*command*/ 1,
6933				      /*field*/ 2,
6934				      /*bit_valid*/ 0,
6935				      /*bit*/ 0);
6936		ctl_done((union ctl_io *)ctsio);
6937		return (CTL_RETVAL_COMPLETE);
6938	}
6939
6940	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6941
6942	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6943	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6944
6945	if (sizeof(*data) < alloc_len) {
6946		ctsio->residual = alloc_len - sizeof(*data);
6947		ctsio->kern_data_len = sizeof(*data);
6948		ctsio->kern_total_len = sizeof(*data);
6949	} else {
6950		ctsio->residual = 0;
6951		ctsio->kern_data_len = alloc_len;
6952		ctsio->kern_total_len = alloc_len;
6953	}
6954	ctsio->kern_data_resid = 0;
6955	ctsio->kern_rel_offset = 0;
6956	ctsio->kern_sg_entries = 0;
6957
6958	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6959	/* XXX KDM this may not be 512 bytes... */
6960	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6961	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6962	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6963	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6964		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6965
6966	ctl_set_success(ctsio);
6967	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6968	ctsio->be_move_done = ctl_config_move_done;
6969	ctl_datamove((union ctl_io *)ctsio);
6970	return (CTL_RETVAL_COMPLETE);
6971}
6972
6973int
6974ctl_get_lba_status(struct ctl_scsiio *ctsio)
6975{
6976	struct scsi_get_lba_status *cdb;
6977	struct scsi_get_lba_status_data *data;
6978	struct ctl_lun *lun;
6979	struct ctl_lba_len_flags *lbalen;
6980	uint64_t lba;
6981	uint32_t alloc_len, total_len;
6982	int retval;
6983
6984	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6985
6986	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6987	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6988	lba = scsi_8btou64(cdb->addr);
6989	alloc_len = scsi_4btoul(cdb->alloc_len);
6990
6991	if (lba > lun->be_lun->maxlba) {
6992		ctl_set_lba_out_of_range(ctsio, lba);
6993		ctl_done((union ctl_io *)ctsio);
6994		return (CTL_RETVAL_COMPLETE);
6995	}
6996
6997	total_len = sizeof(*data) + sizeof(data->descr[0]);
6998	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6999	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7000
7001	if (total_len < alloc_len) {
7002		ctsio->residual = alloc_len - total_len;
7003		ctsio->kern_data_len = total_len;
7004		ctsio->kern_total_len = total_len;
7005	} else {
7006		ctsio->residual = 0;
7007		ctsio->kern_data_len = alloc_len;
7008		ctsio->kern_total_len = alloc_len;
7009	}
7010	ctsio->kern_data_resid = 0;
7011	ctsio->kern_rel_offset = 0;
7012	ctsio->kern_sg_entries = 0;
7013
7014	/* Fill dummy data in case backend can't tell anything. */
7015	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7016	scsi_u64to8b(lba, data->descr[0].addr);
7017	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7018	    data->descr[0].length);
7019	data->descr[0].status = 0; /* Mapped or unknown. */
7020
7021	ctl_set_success(ctsio);
7022	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7023	ctsio->be_move_done = ctl_config_move_done;
7024
7025	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7026	lbalen->lba = lba;
7027	lbalen->len = total_len;
7028	lbalen->flags = 0;
7029	retval = lun->backend->config_read((union ctl_io *)ctsio);
7030	return (CTL_RETVAL_COMPLETE);
7031}
7032
7033int
7034ctl_read_defect(struct ctl_scsiio *ctsio)
7035{
7036	struct scsi_read_defect_data_10 *ccb10;
7037	struct scsi_read_defect_data_12 *ccb12;
7038	struct scsi_read_defect_data_hdr_10 *data10;
7039	struct scsi_read_defect_data_hdr_12 *data12;
7040	uint32_t alloc_len, data_len;
7041	uint8_t format;
7042
7043	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7044
7045	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7046		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7047		format = ccb10->format;
7048		alloc_len = scsi_2btoul(ccb10->alloc_length);
7049		data_len = sizeof(*data10);
7050	} else {
7051		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7052		format = ccb12->format;
7053		alloc_len = scsi_4btoul(ccb12->alloc_length);
7054		data_len = sizeof(*data12);
7055	}
7056	if (alloc_len == 0) {
7057		ctl_set_success(ctsio);
7058		ctl_done((union ctl_io *)ctsio);
7059		return (CTL_RETVAL_COMPLETE);
7060	}
7061
7062	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7063	if (data_len < alloc_len) {
7064		ctsio->residual = alloc_len - data_len;
7065		ctsio->kern_data_len = data_len;
7066		ctsio->kern_total_len = data_len;
7067	} else {
7068		ctsio->residual = 0;
7069		ctsio->kern_data_len = alloc_len;
7070		ctsio->kern_total_len = alloc_len;
7071	}
7072	ctsio->kern_data_resid = 0;
7073	ctsio->kern_rel_offset = 0;
7074	ctsio->kern_sg_entries = 0;
7075
7076	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7077		data10 = (struct scsi_read_defect_data_hdr_10 *)
7078		    ctsio->kern_data_ptr;
7079		data10->format = format;
7080		scsi_ulto2b(0, data10->length);
7081	} else {
7082		data12 = (struct scsi_read_defect_data_hdr_12 *)
7083		    ctsio->kern_data_ptr;
7084		data12->format = format;
7085		scsi_ulto2b(0, data12->generation);
7086		scsi_ulto4b(0, data12->length);
7087	}
7088
7089	ctl_set_success(ctsio);
7090	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7091	ctsio->be_move_done = ctl_config_move_done;
7092	ctl_datamove((union ctl_io *)ctsio);
7093	return (CTL_RETVAL_COMPLETE);
7094}
7095
7096int
7097ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7098{
7099	struct scsi_maintenance_in *cdb;
7100	int retval;
7101	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7102	int num_ha_groups, num_target_ports, shared_group;
7103	struct ctl_lun *lun;
7104	struct ctl_softc *softc;
7105	struct ctl_port *port;
7106	struct scsi_target_group_data *rtg_ptr;
7107	struct scsi_target_group_data_extended *rtg_ext_ptr;
7108	struct scsi_target_port_group_descriptor *tpg_desc;
7109
7110	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7111
7112	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7113	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7114	softc = lun->ctl_softc;
7115
7116	retval = CTL_RETVAL_COMPLETE;
7117
7118	switch (cdb->byte2 & STG_PDF_MASK) {
7119	case STG_PDF_LENGTH:
7120		ext = 0;
7121		break;
7122	case STG_PDF_EXTENDED:
7123		ext = 1;
7124		break;
7125	default:
7126		ctl_set_invalid_field(/*ctsio*/ ctsio,
7127				      /*sks_valid*/ 1,
7128				      /*command*/ 1,
7129				      /*field*/ 2,
7130				      /*bit_valid*/ 1,
7131				      /*bit*/ 5);
7132		ctl_done((union ctl_io *)ctsio);
7133		return(retval);
7134	}
7135
7136	num_target_ports = 0;
7137	shared_group = (softc->is_single != 0);
7138	mtx_lock(&softc->ctl_lock);
7139	STAILQ_FOREACH(port, &softc->port_list, links) {
7140		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7141			continue;
7142		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7143			continue;
7144		num_target_ports++;
7145		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7146			shared_group = 1;
7147	}
7148	mtx_unlock(&softc->ctl_lock);
7149	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7150
7151	if (ext)
7152		total_len = sizeof(struct scsi_target_group_data_extended);
7153	else
7154		total_len = sizeof(struct scsi_target_group_data);
7155	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7156		(shared_group + num_ha_groups) +
7157	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7158
7159	alloc_len = scsi_4btoul(cdb->length);
7160
7161	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7162
7163	ctsio->kern_sg_entries = 0;
7164
7165	if (total_len < alloc_len) {
7166		ctsio->residual = alloc_len - total_len;
7167		ctsio->kern_data_len = total_len;
7168		ctsio->kern_total_len = total_len;
7169	} else {
7170		ctsio->residual = 0;
7171		ctsio->kern_data_len = alloc_len;
7172		ctsio->kern_total_len = alloc_len;
7173	}
7174	ctsio->kern_data_resid = 0;
7175	ctsio->kern_rel_offset = 0;
7176
7177	if (ext) {
7178		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7179		    ctsio->kern_data_ptr;
7180		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7181		rtg_ext_ptr->format_type = 0x10;
7182		rtg_ext_ptr->implicit_transition_time = 0;
7183		tpg_desc = &rtg_ext_ptr->groups[0];
7184	} else {
7185		rtg_ptr = (struct scsi_target_group_data *)
7186		    ctsio->kern_data_ptr;
7187		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7188		tpg_desc = &rtg_ptr->groups[0];
7189	}
7190
7191	mtx_lock(&softc->ctl_lock);
7192	pg = softc->port_min / softc->port_cnt;
7193	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7194		/* Some shelf is known to be primary. */
7195		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7196			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7197		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7198			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7199		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7200			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7201		else
7202			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7203		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7204			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7205		} else {
7206			ts = os;
7207			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7208		}
7209	} else {
7210		/* No known primary shelf. */
7211		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7212			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7213			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7214		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7215			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7216			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7217		} else {
7218			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7219		}
7220	}
7221	if (shared_group) {
7222		tpg_desc->pref_state = ts;
7223		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7224		    TPG_U_SUP | TPG_T_SUP;
7225		scsi_ulto2b(1, tpg_desc->target_port_group);
7226		tpg_desc->status = TPG_IMPLICIT;
7227		pc = 0;
7228		STAILQ_FOREACH(port, &softc->port_list, links) {
7229			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7230				continue;
7231			if (!softc->is_single &&
7232			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7233				continue;
7234			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7235				continue;
7236			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7237			    relative_target_port_identifier);
7238			pc++;
7239		}
7240		tpg_desc->target_port_count = pc;
7241		tpg_desc = (struct scsi_target_port_group_descriptor *)
7242		    &tpg_desc->descriptors[pc];
7243	}
7244	for (g = 0; g < num_ha_groups; g++) {
7245		tpg_desc->pref_state = (g == pg) ? ts : os;
7246		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7247		    TPG_U_SUP | TPG_T_SUP;
7248		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7249		tpg_desc->status = TPG_IMPLICIT;
7250		pc = 0;
7251		STAILQ_FOREACH(port, &softc->port_list, links) {
7252			if (port->targ_port < g * softc->port_cnt ||
7253			    port->targ_port >= (g + 1) * softc->port_cnt)
7254				continue;
7255			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7256				continue;
7257			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7258				continue;
7259			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7260				continue;
7261			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7262			    relative_target_port_identifier);
7263			pc++;
7264		}
7265		tpg_desc->target_port_count = pc;
7266		tpg_desc = (struct scsi_target_port_group_descriptor *)
7267		    &tpg_desc->descriptors[pc];
7268	}
7269	mtx_unlock(&softc->ctl_lock);
7270
7271	ctl_set_success(ctsio);
7272	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7273	ctsio->be_move_done = ctl_config_move_done;
7274	ctl_datamove((union ctl_io *)ctsio);
7275	return(retval);
7276}
7277
7278int
7279ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7280{
7281	struct ctl_lun *lun;
7282	struct scsi_report_supported_opcodes *cdb;
7283	const struct ctl_cmd_entry *entry, *sentry;
7284	struct scsi_report_supported_opcodes_all *all;
7285	struct scsi_report_supported_opcodes_descr *descr;
7286	struct scsi_report_supported_opcodes_one *one;
7287	int retval;
7288	int alloc_len, total_len;
7289	int opcode, service_action, i, j, num;
7290
7291	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7292
7293	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7294	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7295
7296	retval = CTL_RETVAL_COMPLETE;
7297
7298	opcode = cdb->requested_opcode;
7299	service_action = scsi_2btoul(cdb->requested_service_action);
7300	switch (cdb->options & RSO_OPTIONS_MASK) {
7301	case RSO_OPTIONS_ALL:
7302		num = 0;
7303		for (i = 0; i < 256; i++) {
7304			entry = &ctl_cmd_table[i];
7305			if (entry->flags & CTL_CMD_FLAG_SA5) {
7306				for (j = 0; j < 32; j++) {
7307					sentry = &((const struct ctl_cmd_entry *)
7308					    entry->execute)[j];
7309					if (ctl_cmd_applicable(
7310					    lun->be_lun->lun_type, sentry))
7311						num++;
7312				}
7313			} else {
7314				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7315				    entry))
7316					num++;
7317			}
7318		}
7319		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7320		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7321		break;
7322	case RSO_OPTIONS_OC:
7323		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7324			ctl_set_invalid_field(/*ctsio*/ ctsio,
7325					      /*sks_valid*/ 1,
7326					      /*command*/ 1,
7327					      /*field*/ 2,
7328					      /*bit_valid*/ 1,
7329					      /*bit*/ 2);
7330			ctl_done((union ctl_io *)ctsio);
7331			return (CTL_RETVAL_COMPLETE);
7332		}
7333		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7334		break;
7335	case RSO_OPTIONS_OC_SA:
7336		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7337		    service_action >= 32) {
7338			ctl_set_invalid_field(/*ctsio*/ ctsio,
7339					      /*sks_valid*/ 1,
7340					      /*command*/ 1,
7341					      /*field*/ 2,
7342					      /*bit_valid*/ 1,
7343					      /*bit*/ 2);
7344			ctl_done((union ctl_io *)ctsio);
7345			return (CTL_RETVAL_COMPLETE);
7346		}
7347		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7348		break;
7349	default:
7350		ctl_set_invalid_field(/*ctsio*/ ctsio,
7351				      /*sks_valid*/ 1,
7352				      /*command*/ 1,
7353				      /*field*/ 2,
7354				      /*bit_valid*/ 1,
7355				      /*bit*/ 2);
7356		ctl_done((union ctl_io *)ctsio);
7357		return (CTL_RETVAL_COMPLETE);
7358	}
7359
7360	alloc_len = scsi_4btoul(cdb->length);
7361
7362	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7363
7364	ctsio->kern_sg_entries = 0;
7365
7366	if (total_len < alloc_len) {
7367		ctsio->residual = alloc_len - total_len;
7368		ctsio->kern_data_len = total_len;
7369		ctsio->kern_total_len = total_len;
7370	} else {
7371		ctsio->residual = 0;
7372		ctsio->kern_data_len = alloc_len;
7373		ctsio->kern_total_len = alloc_len;
7374	}
7375	ctsio->kern_data_resid = 0;
7376	ctsio->kern_rel_offset = 0;
7377
7378	switch (cdb->options & RSO_OPTIONS_MASK) {
7379	case RSO_OPTIONS_ALL:
7380		all = (struct scsi_report_supported_opcodes_all *)
7381		    ctsio->kern_data_ptr;
7382		num = 0;
7383		for (i = 0; i < 256; i++) {
7384			entry = &ctl_cmd_table[i];
7385			if (entry->flags & CTL_CMD_FLAG_SA5) {
7386				for (j = 0; j < 32; j++) {
7387					sentry = &((const struct ctl_cmd_entry *)
7388					    entry->execute)[j];
7389					if (!ctl_cmd_applicable(
7390					    lun->be_lun->lun_type, sentry))
7391						continue;
7392					descr = &all->descr[num++];
7393					descr->opcode = i;
7394					scsi_ulto2b(j, descr->service_action);
7395					descr->flags = RSO_SERVACTV;
7396					scsi_ulto2b(sentry->length,
7397					    descr->cdb_length);
7398				}
7399			} else {
7400				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7401				    entry))
7402					continue;
7403				descr = &all->descr[num++];
7404				descr->opcode = i;
7405				scsi_ulto2b(0, descr->service_action);
7406				descr->flags = 0;
7407				scsi_ulto2b(entry->length, descr->cdb_length);
7408			}
7409		}
7410		scsi_ulto4b(
7411		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7412		    all->length);
7413		break;
7414	case RSO_OPTIONS_OC:
7415		one = (struct scsi_report_supported_opcodes_one *)
7416		    ctsio->kern_data_ptr;
7417		entry = &ctl_cmd_table[opcode];
7418		goto fill_one;
7419	case RSO_OPTIONS_OC_SA:
7420		one = (struct scsi_report_supported_opcodes_one *)
7421		    ctsio->kern_data_ptr;
7422		entry = &ctl_cmd_table[opcode];
7423		entry = &((const struct ctl_cmd_entry *)
7424		    entry->execute)[service_action];
7425fill_one:
7426		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7427			one->support = 3;
7428			scsi_ulto2b(entry->length, one->cdb_length);
7429			one->cdb_usage[0] = opcode;
7430			memcpy(&one->cdb_usage[1], entry->usage,
7431			    entry->length - 1);
7432		} else
7433			one->support = 1;
7434		break;
7435	}
7436
7437	ctl_set_success(ctsio);
7438	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7439	ctsio->be_move_done = ctl_config_move_done;
7440	ctl_datamove((union ctl_io *)ctsio);
7441	return(retval);
7442}
7443
7444int
7445ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7446{
7447	struct scsi_report_supported_tmf *cdb;
7448	struct scsi_report_supported_tmf_data *data;
7449	int retval;
7450	int alloc_len, total_len;
7451
7452	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7453
7454	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7455
7456	retval = CTL_RETVAL_COMPLETE;
7457
7458	total_len = sizeof(struct scsi_report_supported_tmf_data);
7459	alloc_len = scsi_4btoul(cdb->length);
7460
7461	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7462
7463	ctsio->kern_sg_entries = 0;
7464
7465	if (total_len < alloc_len) {
7466		ctsio->residual = alloc_len - total_len;
7467		ctsio->kern_data_len = total_len;
7468		ctsio->kern_total_len = total_len;
7469	} else {
7470		ctsio->residual = 0;
7471		ctsio->kern_data_len = alloc_len;
7472		ctsio->kern_total_len = alloc_len;
7473	}
7474	ctsio->kern_data_resid = 0;
7475	ctsio->kern_rel_offset = 0;
7476
7477	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7478	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7479	    RST_TRS;
7480	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7481
7482	ctl_set_success(ctsio);
7483	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7484	ctsio->be_move_done = ctl_config_move_done;
7485	ctl_datamove((union ctl_io *)ctsio);
7486	return (retval);
7487}
7488
7489int
7490ctl_report_timestamp(struct ctl_scsiio *ctsio)
7491{
7492	struct scsi_report_timestamp *cdb;
7493	struct scsi_report_timestamp_data *data;
7494	struct timeval tv;
7495	int64_t timestamp;
7496	int retval;
7497	int alloc_len, total_len;
7498
7499	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7500
7501	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7502
7503	retval = CTL_RETVAL_COMPLETE;
7504
7505	total_len = sizeof(struct scsi_report_timestamp_data);
7506	alloc_len = scsi_4btoul(cdb->length);
7507
7508	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7509
7510	ctsio->kern_sg_entries = 0;
7511
7512	if (total_len < alloc_len) {
7513		ctsio->residual = alloc_len - total_len;
7514		ctsio->kern_data_len = total_len;
7515		ctsio->kern_total_len = total_len;
7516	} else {
7517		ctsio->residual = 0;
7518		ctsio->kern_data_len = alloc_len;
7519		ctsio->kern_total_len = alloc_len;
7520	}
7521	ctsio->kern_data_resid = 0;
7522	ctsio->kern_rel_offset = 0;
7523
7524	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7525	scsi_ulto2b(sizeof(*data) - 2, data->length);
7526	data->origin = RTS_ORIG_OUTSIDE;
7527	getmicrotime(&tv);
7528	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7529	scsi_ulto4b(timestamp >> 16, data->timestamp);
7530	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7531
7532	ctl_set_success(ctsio);
7533	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7534	ctsio->be_move_done = ctl_config_move_done;
7535	ctl_datamove((union ctl_io *)ctsio);
7536	return (retval);
7537}
7538
7539int
7540ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7541{
7542	struct scsi_per_res_in *cdb;
7543	int alloc_len, total_len = 0;
7544	/* struct scsi_per_res_in_rsrv in_data; */
7545	struct ctl_lun *lun;
7546	struct ctl_softc *softc;
7547	uint64_t key;
7548
7549	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7550
7551	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7552
7553	alloc_len = scsi_2btoul(cdb->length);
7554
7555	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7556	softc = lun->ctl_softc;
7557
7558retry:
7559	mtx_lock(&lun->lun_lock);
7560	switch (cdb->action) {
7561	case SPRI_RK: /* read keys */
7562		total_len = sizeof(struct scsi_per_res_in_keys) +
7563			lun->pr_key_count *
7564			sizeof(struct scsi_per_res_key);
7565		break;
7566	case SPRI_RR: /* read reservation */
7567		if (lun->flags & CTL_LUN_PR_RESERVED)
7568			total_len = sizeof(struct scsi_per_res_in_rsrv);
7569		else
7570			total_len = sizeof(struct scsi_per_res_in_header);
7571		break;
7572	case SPRI_RC: /* report capabilities */
7573		total_len = sizeof(struct scsi_per_res_cap);
7574		break;
7575	case SPRI_RS: /* read full status */
7576		total_len = sizeof(struct scsi_per_res_in_header) +
7577		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7578		    lun->pr_key_count;
7579		break;
7580	default:
7581		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7582	}
7583	mtx_unlock(&lun->lun_lock);
7584
7585	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7586
7587	if (total_len < alloc_len) {
7588		ctsio->residual = alloc_len - total_len;
7589		ctsio->kern_data_len = total_len;
7590		ctsio->kern_total_len = total_len;
7591	} else {
7592		ctsio->residual = 0;
7593		ctsio->kern_data_len = alloc_len;
7594		ctsio->kern_total_len = alloc_len;
7595	}
7596
7597	ctsio->kern_data_resid = 0;
7598	ctsio->kern_rel_offset = 0;
7599	ctsio->kern_sg_entries = 0;
7600
7601	mtx_lock(&lun->lun_lock);
7602	switch (cdb->action) {
7603	case SPRI_RK: { // read keys
7604        struct scsi_per_res_in_keys *res_keys;
7605		int i, key_count;
7606
7607		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7608
7609		/*
7610		 * We had to drop the lock to allocate our buffer, which
7611		 * leaves time for someone to come in with another
7612		 * persistent reservation.  (That is unlikely, though,
7613		 * since this should be the only persistent reservation
7614		 * command active right now.)
7615		 */
7616		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7617		    (lun->pr_key_count *
7618		     sizeof(struct scsi_per_res_key)))){
7619			mtx_unlock(&lun->lun_lock);
7620			free(ctsio->kern_data_ptr, M_CTL);
7621			printf("%s: reservation length changed, retrying\n",
7622			       __func__);
7623			goto retry;
7624		}
7625
7626		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7627
7628		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7629			     lun->pr_key_count, res_keys->header.length);
7630
7631		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7632			if ((key = ctl_get_prkey(lun, i)) == 0)
7633				continue;
7634
7635			/*
7636			 * We used lun->pr_key_count to calculate the
7637			 * size to allocate.  If it turns out the number of
7638			 * initiators with the registered flag set is
7639			 * larger than that (i.e. they haven't been kept in
7640			 * sync), we've got a problem.
7641			 */
7642			if (key_count >= lun->pr_key_count) {
7643				key_count++;
7644				continue;
7645			}
7646			scsi_u64to8b(key, res_keys->keys[key_count].key);
7647			key_count++;
7648		}
7649		break;
7650	}
7651	case SPRI_RR: { // read reservation
7652		struct scsi_per_res_in_rsrv *res;
7653		int tmp_len, header_only;
7654
7655		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7656
7657		scsi_ulto4b(lun->pr_generation, res->header.generation);
7658
7659		if (lun->flags & CTL_LUN_PR_RESERVED)
7660		{
7661			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7662			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7663				    res->header.length);
7664			header_only = 0;
7665		} else {
7666			tmp_len = sizeof(struct scsi_per_res_in_header);
7667			scsi_ulto4b(0, res->header.length);
7668			header_only = 1;
7669		}
7670
7671		/*
7672		 * We had to drop the lock to allocate our buffer, which
7673		 * leaves time for someone to come in with another
7674		 * persistent reservation.  (That is unlikely, though,
7675		 * since this should be the only persistent reservation
7676		 * command active right now.)
7677		 */
7678		if (tmp_len != total_len) {
7679			mtx_unlock(&lun->lun_lock);
7680			free(ctsio->kern_data_ptr, M_CTL);
7681			printf("%s: reservation status changed, retrying\n",
7682			       __func__);
7683			goto retry;
7684		}
7685
7686		/*
7687		 * No reservation held, so we're done.
7688		 */
7689		if (header_only != 0)
7690			break;
7691
7692		/*
7693		 * If the registration is an All Registrants type, the key
7694		 * is 0, since it doesn't really matter.
7695		 */
7696		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7697			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7698			    res->data.reservation);
7699		}
7700		res->data.scopetype = lun->pr_res_type;
7701		break;
7702	}
7703	case SPRI_RC:     //report capabilities
7704	{
7705		struct scsi_per_res_cap *res_cap;
7706		uint16_t type_mask;
7707
7708		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7709		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7710		res_cap->flags1 = SPRI_CRH;
7711		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7712		type_mask = SPRI_TM_WR_EX_AR |
7713			    SPRI_TM_EX_AC_RO |
7714			    SPRI_TM_WR_EX_RO |
7715			    SPRI_TM_EX_AC |
7716			    SPRI_TM_WR_EX |
7717			    SPRI_TM_EX_AC_AR;
7718		scsi_ulto2b(type_mask, res_cap->type_mask);
7719		break;
7720	}
7721	case SPRI_RS: { // read full status
7722		struct scsi_per_res_in_full *res_status;
7723		struct scsi_per_res_in_full_desc *res_desc;
7724		struct ctl_port *port;
7725		int i, len;
7726
7727		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7728
7729		/*
7730		 * We had to drop the lock to allocate our buffer, which
7731		 * leaves time for someone to come in with another
7732		 * persistent reservation.  (That is unlikely, though,
7733		 * since this should be the only persistent reservation
7734		 * command active right now.)
7735		 */
7736		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7737		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7738		     lun->pr_key_count)){
7739			mtx_unlock(&lun->lun_lock);
7740			free(ctsio->kern_data_ptr, M_CTL);
7741			printf("%s: reservation length changed, retrying\n",
7742			       __func__);
7743			goto retry;
7744		}
7745
7746		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7747
7748		res_desc = &res_status->desc[0];
7749		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7750			if ((key = ctl_get_prkey(lun, i)) == 0)
7751				continue;
7752
7753			scsi_u64to8b(key, res_desc->res_key.key);
7754			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7755			    (lun->pr_res_idx == i ||
7756			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7757				res_desc->flags = SPRI_FULL_R_HOLDER;
7758				res_desc->scopetype = lun->pr_res_type;
7759			}
7760			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7761			    res_desc->rel_trgt_port_id);
7762			len = 0;
7763			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7764			if (port != NULL)
7765				len = ctl_create_iid(port,
7766				    i % CTL_MAX_INIT_PER_PORT,
7767				    res_desc->transport_id);
7768			scsi_ulto4b(len, res_desc->additional_length);
7769			res_desc = (struct scsi_per_res_in_full_desc *)
7770			    &res_desc->transport_id[len];
7771		}
7772		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7773		    res_status->header.length);
7774		break;
7775	}
7776	default:
7777		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7778	}
7779	mtx_unlock(&lun->lun_lock);
7780
7781	ctl_set_success(ctsio);
7782	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7783	ctsio->be_move_done = ctl_config_move_done;
7784	ctl_datamove((union ctl_io *)ctsio);
7785	return (CTL_RETVAL_COMPLETE);
7786}
7787
7788/*
7789 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7790 * it should return.
7791 */
7792static int
7793ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7794		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7795		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7796		struct scsi_per_res_out_parms* param)
7797{
7798	union ctl_ha_msg persis_io;
7799	int i;
7800
7801	mtx_lock(&lun->lun_lock);
7802	if (sa_res_key == 0) {
7803		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7804			/* validate scope and type */
7805			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7806			     SPR_LU_SCOPE) {
7807				mtx_unlock(&lun->lun_lock);
7808				ctl_set_invalid_field(/*ctsio*/ ctsio,
7809						      /*sks_valid*/ 1,
7810						      /*command*/ 1,
7811						      /*field*/ 2,
7812						      /*bit_valid*/ 1,
7813						      /*bit*/ 4);
7814				ctl_done((union ctl_io *)ctsio);
7815				return (1);
7816			}
7817
7818		        if (type>8 || type==2 || type==4 || type==0) {
7819				mtx_unlock(&lun->lun_lock);
7820				ctl_set_invalid_field(/*ctsio*/ ctsio,
7821       	           				      /*sks_valid*/ 1,
7822						      /*command*/ 1,
7823						      /*field*/ 2,
7824						      /*bit_valid*/ 1,
7825						      /*bit*/ 0);
7826				ctl_done((union ctl_io *)ctsio);
7827				return (1);
7828		        }
7829
7830			/*
7831			 * Unregister everybody else and build UA for
7832			 * them
7833			 */
7834			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7835				if (i == residx || ctl_get_prkey(lun, i) == 0)
7836					continue;
7837
7838				ctl_clr_prkey(lun, i);
7839				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7840			}
7841			lun->pr_key_count = 1;
7842			lun->pr_res_type = type;
7843			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7844			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7845				lun->pr_res_idx = residx;
7846			lun->pr_generation++;
7847			mtx_unlock(&lun->lun_lock);
7848
7849			/* send msg to other side */
7850			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7851			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7852			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7853			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7854			persis_io.pr.pr_info.res_type = type;
7855			memcpy(persis_io.pr.pr_info.sa_res_key,
7856			       param->serv_act_res_key,
7857			       sizeof(param->serv_act_res_key));
7858			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7859			    sizeof(persis_io.pr), M_WAITOK);
7860		} else {
7861			/* not all registrants */
7862			mtx_unlock(&lun->lun_lock);
7863			free(ctsio->kern_data_ptr, M_CTL);
7864			ctl_set_invalid_field(ctsio,
7865					      /*sks_valid*/ 1,
7866					      /*command*/ 0,
7867					      /*field*/ 8,
7868					      /*bit_valid*/ 0,
7869					      /*bit*/ 0);
7870			ctl_done((union ctl_io *)ctsio);
7871			return (1);
7872		}
7873	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7874		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7875		int found = 0;
7876
7877		if (res_key == sa_res_key) {
7878			/* special case */
7879			/*
7880			 * The spec implies this is not good but doesn't
7881			 * say what to do. There are two choices either
7882			 * generate a res conflict or check condition
7883			 * with illegal field in parameter data. Since
7884			 * that is what is done when the sa_res_key is
7885			 * zero I'll take that approach since this has
7886			 * to do with the sa_res_key.
7887			 */
7888			mtx_unlock(&lun->lun_lock);
7889			free(ctsio->kern_data_ptr, M_CTL);
7890			ctl_set_invalid_field(ctsio,
7891					      /*sks_valid*/ 1,
7892					      /*command*/ 0,
7893					      /*field*/ 8,
7894					      /*bit_valid*/ 0,
7895					      /*bit*/ 0);
7896			ctl_done((union ctl_io *)ctsio);
7897			return (1);
7898		}
7899
7900		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7901			if (ctl_get_prkey(lun, i) != sa_res_key)
7902				continue;
7903
7904			found = 1;
7905			ctl_clr_prkey(lun, i);
7906			lun->pr_key_count--;
7907			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7908		}
7909		if (!found) {
7910			mtx_unlock(&lun->lun_lock);
7911			free(ctsio->kern_data_ptr, M_CTL);
7912			ctl_set_reservation_conflict(ctsio);
7913			ctl_done((union ctl_io *)ctsio);
7914			return (CTL_RETVAL_COMPLETE);
7915		}
7916		lun->pr_generation++;
7917		mtx_unlock(&lun->lun_lock);
7918
7919		/* send msg to other side */
7920		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7921		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7922		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7923		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7924		persis_io.pr.pr_info.res_type = type;
7925		memcpy(persis_io.pr.pr_info.sa_res_key,
7926		       param->serv_act_res_key,
7927		       sizeof(param->serv_act_res_key));
7928		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7929		    sizeof(persis_io.pr), M_WAITOK);
7930	} else {
7931		/* Reserved but not all registrants */
7932		/* sa_res_key is res holder */
7933		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7934			/* validate scope and type */
7935			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7936			     SPR_LU_SCOPE) {
7937				mtx_unlock(&lun->lun_lock);
7938				ctl_set_invalid_field(/*ctsio*/ ctsio,
7939						      /*sks_valid*/ 1,
7940						      /*command*/ 1,
7941						      /*field*/ 2,
7942						      /*bit_valid*/ 1,
7943						      /*bit*/ 4);
7944				ctl_done((union ctl_io *)ctsio);
7945				return (1);
7946			}
7947
7948			if (type>8 || type==2 || type==4 || type==0) {
7949				mtx_unlock(&lun->lun_lock);
7950				ctl_set_invalid_field(/*ctsio*/ ctsio,
7951						      /*sks_valid*/ 1,
7952						      /*command*/ 1,
7953						      /*field*/ 2,
7954						      /*bit_valid*/ 1,
7955						      /*bit*/ 0);
7956				ctl_done((union ctl_io *)ctsio);
7957				return (1);
7958			}
7959
7960			/*
7961			 * Do the following:
7962			 * if sa_res_key != res_key remove all
7963			 * registrants w/sa_res_key and generate UA
7964			 * for these registrants(Registrations
7965			 * Preempted) if it wasn't an exclusive
7966			 * reservation generate UA(Reservations
7967			 * Preempted) for all other registered nexuses
7968			 * if the type has changed. Establish the new
7969			 * reservation and holder. If res_key and
7970			 * sa_res_key are the same do the above
7971			 * except don't unregister the res holder.
7972			 */
7973
7974			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7975				if (i == residx || ctl_get_prkey(lun, i) == 0)
7976					continue;
7977
7978				if (sa_res_key == ctl_get_prkey(lun, i)) {
7979					ctl_clr_prkey(lun, i);
7980					lun->pr_key_count--;
7981					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7982				} else if (type != lun->pr_res_type &&
7983				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7984				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7985					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7986				}
7987			}
7988			lun->pr_res_type = type;
7989			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7990			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7991				lun->pr_res_idx = residx;
7992			else
7993				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7994			lun->pr_generation++;
7995			mtx_unlock(&lun->lun_lock);
7996
7997			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7998			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7999			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8000			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8001			persis_io.pr.pr_info.res_type = type;
8002			memcpy(persis_io.pr.pr_info.sa_res_key,
8003			       param->serv_act_res_key,
8004			       sizeof(param->serv_act_res_key));
8005			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8006			    sizeof(persis_io.pr), M_WAITOK);
8007		} else {
8008			/*
8009			 * sa_res_key is not the res holder just
8010			 * remove registrants
8011			 */
8012			int found=0;
8013
8014			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8015				if (sa_res_key != ctl_get_prkey(lun, i))
8016					continue;
8017
8018				found = 1;
8019				ctl_clr_prkey(lun, i);
8020				lun->pr_key_count--;
8021				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8022			}
8023
8024			if (!found) {
8025				mtx_unlock(&lun->lun_lock);
8026				free(ctsio->kern_data_ptr, M_CTL);
8027				ctl_set_reservation_conflict(ctsio);
8028				ctl_done((union ctl_io *)ctsio);
8029		        	return (1);
8030			}
8031			lun->pr_generation++;
8032			mtx_unlock(&lun->lun_lock);
8033
8034			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8035			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8036			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8037			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8038			persis_io.pr.pr_info.res_type = type;
8039			memcpy(persis_io.pr.pr_info.sa_res_key,
8040			       param->serv_act_res_key,
8041			       sizeof(param->serv_act_res_key));
8042			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8043			    sizeof(persis_io.pr), M_WAITOK);
8044		}
8045	}
8046	return (0);
8047}
8048
8049static void
8050ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8051{
8052	uint64_t sa_res_key;
8053	int i;
8054
8055	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8056
8057	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8058	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8059	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8060		if (sa_res_key == 0) {
8061			/*
8062			 * Unregister everybody else and build UA for
8063			 * them
8064			 */
8065			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8066				if (i == msg->pr.pr_info.residx ||
8067				    ctl_get_prkey(lun, i) == 0)
8068					continue;
8069
8070				ctl_clr_prkey(lun, i);
8071				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8072			}
8073
8074			lun->pr_key_count = 1;
8075			lun->pr_res_type = msg->pr.pr_info.res_type;
8076			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8077			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8078				lun->pr_res_idx = msg->pr.pr_info.residx;
8079		} else {
8080		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8081				if (sa_res_key == ctl_get_prkey(lun, i))
8082					continue;
8083
8084				ctl_clr_prkey(lun, i);
8085				lun->pr_key_count--;
8086				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8087			}
8088		}
8089	} else {
8090		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8091			if (i == msg->pr.pr_info.residx ||
8092			    ctl_get_prkey(lun, i) == 0)
8093				continue;
8094
8095			if (sa_res_key == ctl_get_prkey(lun, i)) {
8096				ctl_clr_prkey(lun, i);
8097				lun->pr_key_count--;
8098				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8099			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8100			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8101			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8102				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8103			}
8104		}
8105		lun->pr_res_type = msg->pr.pr_info.res_type;
8106		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8107		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8108			lun->pr_res_idx = msg->pr.pr_info.residx;
8109		else
8110			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8111	}
8112	lun->pr_generation++;
8113
8114}
8115
8116
8117int
8118ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8119{
8120	int retval;
8121	u_int32_t param_len;
8122	struct scsi_per_res_out *cdb;
8123	struct ctl_lun *lun;
8124	struct scsi_per_res_out_parms* param;
8125	struct ctl_softc *softc;
8126	uint32_t residx;
8127	uint64_t res_key, sa_res_key, key;
8128	uint8_t type;
8129	union ctl_ha_msg persis_io;
8130	int    i;
8131
8132	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8133
8134	retval = CTL_RETVAL_COMPLETE;
8135
8136	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8137	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8138	softc = lun->ctl_softc;
8139
8140	/*
8141	 * We only support whole-LUN scope.  The scope & type are ignored for
8142	 * register, register and ignore existing key and clear.
8143	 * We sometimes ignore scope and type on preempts too!!
8144	 * Verify reservation type here as well.
8145	 */
8146	type = cdb->scope_type & SPR_TYPE_MASK;
8147	if ((cdb->action == SPRO_RESERVE)
8148	 || (cdb->action == SPRO_RELEASE)) {
8149		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8150			ctl_set_invalid_field(/*ctsio*/ ctsio,
8151					      /*sks_valid*/ 1,
8152					      /*command*/ 1,
8153					      /*field*/ 2,
8154					      /*bit_valid*/ 1,
8155					      /*bit*/ 4);
8156			ctl_done((union ctl_io *)ctsio);
8157			return (CTL_RETVAL_COMPLETE);
8158		}
8159
8160		if (type>8 || type==2 || type==4 || type==0) {
8161			ctl_set_invalid_field(/*ctsio*/ ctsio,
8162					      /*sks_valid*/ 1,
8163					      /*command*/ 1,
8164					      /*field*/ 2,
8165					      /*bit_valid*/ 1,
8166					      /*bit*/ 0);
8167			ctl_done((union ctl_io *)ctsio);
8168			return (CTL_RETVAL_COMPLETE);
8169		}
8170	}
8171
8172	param_len = scsi_4btoul(cdb->length);
8173
8174	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8175		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8176		ctsio->kern_data_len = param_len;
8177		ctsio->kern_total_len = param_len;
8178		ctsio->kern_data_resid = 0;
8179		ctsio->kern_rel_offset = 0;
8180		ctsio->kern_sg_entries = 0;
8181		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8182		ctsio->be_move_done = ctl_config_move_done;
8183		ctl_datamove((union ctl_io *)ctsio);
8184
8185		return (CTL_RETVAL_COMPLETE);
8186	}
8187
8188	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8189
8190	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8191	res_key = scsi_8btou64(param->res_key.key);
8192	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8193
8194	/*
8195	 * Validate the reservation key here except for SPRO_REG_IGNO
8196	 * This must be done for all other service actions
8197	 */
8198	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8199		mtx_lock(&lun->lun_lock);
8200		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8201			if (res_key != key) {
8202				/*
8203				 * The current key passed in doesn't match
8204				 * the one the initiator previously
8205				 * registered.
8206				 */
8207				mtx_unlock(&lun->lun_lock);
8208				free(ctsio->kern_data_ptr, M_CTL);
8209				ctl_set_reservation_conflict(ctsio);
8210				ctl_done((union ctl_io *)ctsio);
8211				return (CTL_RETVAL_COMPLETE);
8212			}
8213		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8214			/*
8215			 * We are not registered
8216			 */
8217			mtx_unlock(&lun->lun_lock);
8218			free(ctsio->kern_data_ptr, M_CTL);
8219			ctl_set_reservation_conflict(ctsio);
8220			ctl_done((union ctl_io *)ctsio);
8221			return (CTL_RETVAL_COMPLETE);
8222		} else if (res_key != 0) {
8223			/*
8224			 * We are not registered and trying to register but
8225			 * the register key isn't zero.
8226			 */
8227			mtx_unlock(&lun->lun_lock);
8228			free(ctsio->kern_data_ptr, M_CTL);
8229			ctl_set_reservation_conflict(ctsio);
8230			ctl_done((union ctl_io *)ctsio);
8231			return (CTL_RETVAL_COMPLETE);
8232		}
8233		mtx_unlock(&lun->lun_lock);
8234	}
8235
8236	switch (cdb->action & SPRO_ACTION_MASK) {
8237	case SPRO_REGISTER:
8238	case SPRO_REG_IGNO: {
8239
8240#if 0
8241		printf("Registration received\n");
8242#endif
8243
8244		/*
8245		 * We don't support any of these options, as we report in
8246		 * the read capabilities request (see
8247		 * ctl_persistent_reserve_in(), above).
8248		 */
8249		if ((param->flags & SPR_SPEC_I_PT)
8250		 || (param->flags & SPR_ALL_TG_PT)
8251		 || (param->flags & SPR_APTPL)) {
8252			int bit_ptr;
8253
8254			if (param->flags & SPR_APTPL)
8255				bit_ptr = 0;
8256			else if (param->flags & SPR_ALL_TG_PT)
8257				bit_ptr = 2;
8258			else /* SPR_SPEC_I_PT */
8259				bit_ptr = 3;
8260
8261			free(ctsio->kern_data_ptr, M_CTL);
8262			ctl_set_invalid_field(ctsio,
8263					      /*sks_valid*/ 1,
8264					      /*command*/ 0,
8265					      /*field*/ 20,
8266					      /*bit_valid*/ 1,
8267					      /*bit*/ bit_ptr);
8268			ctl_done((union ctl_io *)ctsio);
8269			return (CTL_RETVAL_COMPLETE);
8270		}
8271
8272		mtx_lock(&lun->lun_lock);
8273
8274		/*
8275		 * The initiator wants to clear the
8276		 * key/unregister.
8277		 */
8278		if (sa_res_key == 0) {
8279			if ((res_key == 0
8280			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8281			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8282			  && ctl_get_prkey(lun, residx) == 0)) {
8283				mtx_unlock(&lun->lun_lock);
8284				goto done;
8285			}
8286
8287			ctl_clr_prkey(lun, residx);
8288			lun->pr_key_count--;
8289
8290			if (residx == lun->pr_res_idx) {
8291				lun->flags &= ~CTL_LUN_PR_RESERVED;
8292				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8293
8294				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8295				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8296				    lun->pr_key_count) {
8297					/*
8298					 * If the reservation is a registrants
8299					 * only type we need to generate a UA
8300					 * for other registered inits.  The
8301					 * sense code should be RESERVATIONS
8302					 * RELEASED
8303					 */
8304
8305					for (i = softc->init_min; i < softc->init_max; i++){
8306						if (ctl_get_prkey(lun, i) == 0)
8307							continue;
8308						ctl_est_ua(lun, i,
8309						    CTL_UA_RES_RELEASE);
8310					}
8311				}
8312				lun->pr_res_type = 0;
8313			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8314				if (lun->pr_key_count==0) {
8315					lun->flags &= ~CTL_LUN_PR_RESERVED;
8316					lun->pr_res_type = 0;
8317					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8318				}
8319			}
8320			lun->pr_generation++;
8321			mtx_unlock(&lun->lun_lock);
8322
8323			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8324			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8325			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8326			persis_io.pr.pr_info.residx = residx;
8327			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8328			    sizeof(persis_io.pr), M_WAITOK);
8329		} else /* sa_res_key != 0 */ {
8330
8331			/*
8332			 * If we aren't registered currently then increment
8333			 * the key count and set the registered flag.
8334			 */
8335			ctl_alloc_prkey(lun, residx);
8336			if (ctl_get_prkey(lun, residx) == 0)
8337				lun->pr_key_count++;
8338			ctl_set_prkey(lun, residx, sa_res_key);
8339			lun->pr_generation++;
8340			mtx_unlock(&lun->lun_lock);
8341
8342			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8343			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8344			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8345			persis_io.pr.pr_info.residx = residx;
8346			memcpy(persis_io.pr.pr_info.sa_res_key,
8347			       param->serv_act_res_key,
8348			       sizeof(param->serv_act_res_key));
8349			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8350			    sizeof(persis_io.pr), M_WAITOK);
8351		}
8352
8353		break;
8354	}
8355	case SPRO_RESERVE:
8356#if 0
8357                printf("Reserve executed type %d\n", type);
8358#endif
8359		mtx_lock(&lun->lun_lock);
8360		if (lun->flags & CTL_LUN_PR_RESERVED) {
8361			/*
8362			 * if this isn't the reservation holder and it's
8363			 * not a "all registrants" type or if the type is
8364			 * different then we have a conflict
8365			 */
8366			if ((lun->pr_res_idx != residx
8367			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8368			 || lun->pr_res_type != type) {
8369				mtx_unlock(&lun->lun_lock);
8370				free(ctsio->kern_data_ptr, M_CTL);
8371				ctl_set_reservation_conflict(ctsio);
8372				ctl_done((union ctl_io *)ctsio);
8373				return (CTL_RETVAL_COMPLETE);
8374			}
8375			mtx_unlock(&lun->lun_lock);
8376		} else /* create a reservation */ {
8377			/*
8378			 * If it's not an "all registrants" type record
8379			 * reservation holder
8380			 */
8381			if (type != SPR_TYPE_WR_EX_AR
8382			 && type != SPR_TYPE_EX_AC_AR)
8383				lun->pr_res_idx = residx; /* Res holder */
8384			else
8385				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8386
8387			lun->flags |= CTL_LUN_PR_RESERVED;
8388			lun->pr_res_type = type;
8389
8390			mtx_unlock(&lun->lun_lock);
8391
8392			/* send msg to other side */
8393			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8394			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8395			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8396			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8397			persis_io.pr.pr_info.res_type = type;
8398			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8399			    sizeof(persis_io.pr), M_WAITOK);
8400		}
8401		break;
8402
8403	case SPRO_RELEASE:
8404		mtx_lock(&lun->lun_lock);
8405		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8406			/* No reservation exists return good status */
8407			mtx_unlock(&lun->lun_lock);
8408			goto done;
8409		}
8410		/*
8411		 * Is this nexus a reservation holder?
8412		 */
8413		if (lun->pr_res_idx != residx
8414		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8415			/*
8416			 * not a res holder return good status but
8417			 * do nothing
8418			 */
8419			mtx_unlock(&lun->lun_lock);
8420			goto done;
8421		}
8422
8423		if (lun->pr_res_type != type) {
8424			mtx_unlock(&lun->lun_lock);
8425			free(ctsio->kern_data_ptr, M_CTL);
8426			ctl_set_illegal_pr_release(ctsio);
8427			ctl_done((union ctl_io *)ctsio);
8428			return (CTL_RETVAL_COMPLETE);
8429		}
8430
8431		/* okay to release */
8432		lun->flags &= ~CTL_LUN_PR_RESERVED;
8433		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8434		lun->pr_res_type = 0;
8435
8436		/*
8437		 * If this isn't an exclusive access reservation and NUAR
8438		 * is not set, generate UA for all other registrants.
8439		 */
8440		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8441		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8442			for (i = softc->init_min; i < softc->init_max; i++) {
8443				if (i == residx || ctl_get_prkey(lun, i) == 0)
8444					continue;
8445				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8446			}
8447		}
8448		mtx_unlock(&lun->lun_lock);
8449
8450		/* Send msg to other side */
8451		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8452		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8453		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8454		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8455		     sizeof(persis_io.pr), M_WAITOK);
8456		break;
8457
8458	case SPRO_CLEAR:
8459		/* send msg to other side */
8460
8461		mtx_lock(&lun->lun_lock);
8462		lun->flags &= ~CTL_LUN_PR_RESERVED;
8463		lun->pr_res_type = 0;
8464		lun->pr_key_count = 0;
8465		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8466
8467		ctl_clr_prkey(lun, residx);
8468		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8469			if (ctl_get_prkey(lun, i) != 0) {
8470				ctl_clr_prkey(lun, i);
8471				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8472			}
8473		lun->pr_generation++;
8474		mtx_unlock(&lun->lun_lock);
8475
8476		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8477		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8478		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8479		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8480		     sizeof(persis_io.pr), M_WAITOK);
8481		break;
8482
8483	case SPRO_PREEMPT:
8484	case SPRO_PRE_ABO: {
8485		int nretval;
8486
8487		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8488					  residx, ctsio, cdb, param);
8489		if (nretval != 0)
8490			return (CTL_RETVAL_COMPLETE);
8491		break;
8492	}
8493	default:
8494		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8495	}
8496
8497done:
8498	free(ctsio->kern_data_ptr, M_CTL);
8499	ctl_set_success(ctsio);
8500	ctl_done((union ctl_io *)ctsio);
8501
8502	return (retval);
8503}
8504
8505/*
8506 * This routine is for handling a message from the other SC pertaining to
8507 * persistent reserve out. All the error checking will have been done
8508 * so only perorming the action need be done here to keep the two
8509 * in sync.
8510 */
8511static void
8512ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8513{
8514	struct ctl_softc *softc = control_softc;
8515	struct ctl_lun *lun;
8516	int i;
8517	uint32_t residx, targ_lun;
8518
8519	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8520	mtx_lock(&softc->ctl_lock);
8521	if ((targ_lun >= CTL_MAX_LUNS) ||
8522	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8523		mtx_unlock(&softc->ctl_lock);
8524		return;
8525	}
8526	mtx_lock(&lun->lun_lock);
8527	mtx_unlock(&softc->ctl_lock);
8528	if (lun->flags & CTL_LUN_DISABLED) {
8529		mtx_unlock(&lun->lun_lock);
8530		return;
8531	}
8532	residx = ctl_get_initindex(&msg->hdr.nexus);
8533	switch(msg->pr.pr_info.action) {
8534	case CTL_PR_REG_KEY:
8535		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8536		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8537			lun->pr_key_count++;
8538		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8539		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8540		lun->pr_generation++;
8541		break;
8542
8543	case CTL_PR_UNREG_KEY:
8544		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8545		lun->pr_key_count--;
8546
8547		/* XXX Need to see if the reservation has been released */
8548		/* if so do we need to generate UA? */
8549		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8550			lun->flags &= ~CTL_LUN_PR_RESERVED;
8551			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8552
8553			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8554			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8555			    lun->pr_key_count) {
8556				/*
8557				 * If the reservation is a registrants
8558				 * only type we need to generate a UA
8559				 * for other registered inits.  The
8560				 * sense code should be RESERVATIONS
8561				 * RELEASED
8562				 */
8563
8564				for (i = softc->init_min; i < softc->init_max; i++) {
8565					if (ctl_get_prkey(lun, i) == 0)
8566						continue;
8567
8568					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8569				}
8570			}
8571			lun->pr_res_type = 0;
8572		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8573			if (lun->pr_key_count==0) {
8574				lun->flags &= ~CTL_LUN_PR_RESERVED;
8575				lun->pr_res_type = 0;
8576				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8577			}
8578		}
8579		lun->pr_generation++;
8580		break;
8581
8582	case CTL_PR_RESERVE:
8583		lun->flags |= CTL_LUN_PR_RESERVED;
8584		lun->pr_res_type = msg->pr.pr_info.res_type;
8585		lun->pr_res_idx = msg->pr.pr_info.residx;
8586
8587		break;
8588
8589	case CTL_PR_RELEASE:
8590		/*
8591		 * If this isn't an exclusive access reservation and NUAR
8592		 * is not set, generate UA for all other registrants.
8593		 */
8594		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8595		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8596		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8597			for (i = softc->init_min; i < softc->init_max; i++)
8598				if (i == residx || ctl_get_prkey(lun, i) == 0)
8599					continue;
8600				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8601		}
8602
8603		lun->flags &= ~CTL_LUN_PR_RESERVED;
8604		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8605		lun->pr_res_type = 0;
8606		break;
8607
8608	case CTL_PR_PREEMPT:
8609		ctl_pro_preempt_other(lun, msg);
8610		break;
8611	case CTL_PR_CLEAR:
8612		lun->flags &= ~CTL_LUN_PR_RESERVED;
8613		lun->pr_res_type = 0;
8614		lun->pr_key_count = 0;
8615		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8616
8617		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8618			if (ctl_get_prkey(lun, i) == 0)
8619				continue;
8620			ctl_clr_prkey(lun, i);
8621			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8622		}
8623		lun->pr_generation++;
8624		break;
8625	}
8626
8627	mtx_unlock(&lun->lun_lock);
8628}
8629
8630int
8631ctl_read_write(struct ctl_scsiio *ctsio)
8632{
8633	struct ctl_lun *lun;
8634	struct ctl_lba_len_flags *lbalen;
8635	uint64_t lba;
8636	uint32_t num_blocks;
8637	int flags, retval;
8638	int isread;
8639
8640	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8641
8642	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8643
8644	flags = 0;
8645	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8646	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8647	switch (ctsio->cdb[0]) {
8648	case READ_6:
8649	case WRITE_6: {
8650		struct scsi_rw_6 *cdb;
8651
8652		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8653
8654		lba = scsi_3btoul(cdb->addr);
8655		/* only 5 bits are valid in the most significant address byte */
8656		lba &= 0x1fffff;
8657		num_blocks = cdb->length;
8658		/*
8659		 * This is correct according to SBC-2.
8660		 */
8661		if (num_blocks == 0)
8662			num_blocks = 256;
8663		break;
8664	}
8665	case READ_10:
8666	case WRITE_10: {
8667		struct scsi_rw_10 *cdb;
8668
8669		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8670		if (cdb->byte2 & SRW10_FUA)
8671			flags |= CTL_LLF_FUA;
8672		if (cdb->byte2 & SRW10_DPO)
8673			flags |= CTL_LLF_DPO;
8674		lba = scsi_4btoul(cdb->addr);
8675		num_blocks = scsi_2btoul(cdb->length);
8676		break;
8677	}
8678	case WRITE_VERIFY_10: {
8679		struct scsi_write_verify_10 *cdb;
8680
8681		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8682		flags |= CTL_LLF_FUA;
8683		if (cdb->byte2 & SWV_DPO)
8684			flags |= CTL_LLF_DPO;
8685		lba = scsi_4btoul(cdb->addr);
8686		num_blocks = scsi_2btoul(cdb->length);
8687		break;
8688	}
8689	case READ_12:
8690	case WRITE_12: {
8691		struct scsi_rw_12 *cdb;
8692
8693		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8694		if (cdb->byte2 & SRW12_FUA)
8695			flags |= CTL_LLF_FUA;
8696		if (cdb->byte2 & SRW12_DPO)
8697			flags |= CTL_LLF_DPO;
8698		lba = scsi_4btoul(cdb->addr);
8699		num_blocks = scsi_4btoul(cdb->length);
8700		break;
8701	}
8702	case WRITE_VERIFY_12: {
8703		struct scsi_write_verify_12 *cdb;
8704
8705		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8706		flags |= CTL_LLF_FUA;
8707		if (cdb->byte2 & SWV_DPO)
8708			flags |= CTL_LLF_DPO;
8709		lba = scsi_4btoul(cdb->addr);
8710		num_blocks = scsi_4btoul(cdb->length);
8711		break;
8712	}
8713	case READ_16:
8714	case WRITE_16: {
8715		struct scsi_rw_16 *cdb;
8716
8717		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8718		if (cdb->byte2 & SRW12_FUA)
8719			flags |= CTL_LLF_FUA;
8720		if (cdb->byte2 & SRW12_DPO)
8721			flags |= CTL_LLF_DPO;
8722		lba = scsi_8btou64(cdb->addr);
8723		num_blocks = scsi_4btoul(cdb->length);
8724		break;
8725	}
8726	case WRITE_ATOMIC_16: {
8727		struct scsi_write_atomic_16 *cdb;
8728
8729		if (lun->be_lun->atomicblock == 0) {
8730			ctl_set_invalid_opcode(ctsio);
8731			ctl_done((union ctl_io *)ctsio);
8732			return (CTL_RETVAL_COMPLETE);
8733		}
8734
8735		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8736		if (cdb->byte2 & SRW12_FUA)
8737			flags |= CTL_LLF_FUA;
8738		if (cdb->byte2 & SRW12_DPO)
8739			flags |= CTL_LLF_DPO;
8740		lba = scsi_8btou64(cdb->addr);
8741		num_blocks = scsi_2btoul(cdb->length);
8742		if (num_blocks > lun->be_lun->atomicblock) {
8743			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8744			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8745			    /*bit*/ 0);
8746			ctl_done((union ctl_io *)ctsio);
8747			return (CTL_RETVAL_COMPLETE);
8748		}
8749		break;
8750	}
8751	case WRITE_VERIFY_16: {
8752		struct scsi_write_verify_16 *cdb;
8753
8754		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8755		flags |= CTL_LLF_FUA;
8756		if (cdb->byte2 & SWV_DPO)
8757			flags |= CTL_LLF_DPO;
8758		lba = scsi_8btou64(cdb->addr);
8759		num_blocks = scsi_4btoul(cdb->length);
8760		break;
8761	}
8762	default:
8763		/*
8764		 * We got a command we don't support.  This shouldn't
8765		 * happen, commands should be filtered out above us.
8766		 */
8767		ctl_set_invalid_opcode(ctsio);
8768		ctl_done((union ctl_io *)ctsio);
8769
8770		return (CTL_RETVAL_COMPLETE);
8771		break; /* NOTREACHED */
8772	}
8773
8774	/*
8775	 * The first check is to make sure we're in bounds, the second
8776	 * check is to catch wrap-around problems.  If the lba + num blocks
8777	 * is less than the lba, then we've wrapped around and the block
8778	 * range is invalid anyway.
8779	 */
8780	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8781	 || ((lba + num_blocks) < lba)) {
8782		ctl_set_lba_out_of_range(ctsio,
8783		    MAX(lba, lun->be_lun->maxlba + 1));
8784		ctl_done((union ctl_io *)ctsio);
8785		return (CTL_RETVAL_COMPLETE);
8786	}
8787
8788	/*
8789	 * According to SBC-3, a transfer length of 0 is not an error.
8790	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8791	 * translates to 256 blocks for those commands.
8792	 */
8793	if (num_blocks == 0) {
8794		ctl_set_success(ctsio);
8795		ctl_done((union ctl_io *)ctsio);
8796		return (CTL_RETVAL_COMPLETE);
8797	}
8798
8799	/* Set FUA and/or DPO if caches are disabled. */
8800	if (isread) {
8801		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8802			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8803	} else {
8804		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8805			flags |= CTL_LLF_FUA;
8806	}
8807
8808	lbalen = (struct ctl_lba_len_flags *)
8809	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8810	lbalen->lba = lba;
8811	lbalen->len = num_blocks;
8812	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8813
8814	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8815	ctsio->kern_rel_offset = 0;
8816
8817	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8818
8819	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8820	return (retval);
8821}
8822
8823static int
8824ctl_cnw_cont(union ctl_io *io)
8825{
8826	struct ctl_scsiio *ctsio;
8827	struct ctl_lun *lun;
8828	struct ctl_lba_len_flags *lbalen;
8829	int retval;
8830
8831	ctsio = &io->scsiio;
8832	ctsio->io_hdr.status = CTL_STATUS_NONE;
8833	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8834	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8835	lbalen = (struct ctl_lba_len_flags *)
8836	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8837	lbalen->flags &= ~CTL_LLF_COMPARE;
8838	lbalen->flags |= CTL_LLF_WRITE;
8839
8840	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8841	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8842	return (retval);
8843}
8844
8845int
8846ctl_cnw(struct ctl_scsiio *ctsio)
8847{
8848	struct ctl_lun *lun;
8849	struct ctl_lba_len_flags *lbalen;
8850	uint64_t lba;
8851	uint32_t num_blocks;
8852	int flags, retval;
8853
8854	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8855
8856	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8857
8858	flags = 0;
8859	switch (ctsio->cdb[0]) {
8860	case COMPARE_AND_WRITE: {
8861		struct scsi_compare_and_write *cdb;
8862
8863		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8864		if (cdb->byte2 & SRW10_FUA)
8865			flags |= CTL_LLF_FUA;
8866		if (cdb->byte2 & SRW10_DPO)
8867			flags |= CTL_LLF_DPO;
8868		lba = scsi_8btou64(cdb->addr);
8869		num_blocks = cdb->length;
8870		break;
8871	}
8872	default:
8873		/*
8874		 * We got a command we don't support.  This shouldn't
8875		 * happen, commands should be filtered out above us.
8876		 */
8877		ctl_set_invalid_opcode(ctsio);
8878		ctl_done((union ctl_io *)ctsio);
8879
8880		return (CTL_RETVAL_COMPLETE);
8881		break; /* NOTREACHED */
8882	}
8883
8884	/*
8885	 * The first check is to make sure we're in bounds, the second
8886	 * check is to catch wrap-around problems.  If the lba + num blocks
8887	 * is less than the lba, then we've wrapped around and the block
8888	 * range is invalid anyway.
8889	 */
8890	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8891	 || ((lba + num_blocks) < lba)) {
8892		ctl_set_lba_out_of_range(ctsio,
8893		    MAX(lba, lun->be_lun->maxlba + 1));
8894		ctl_done((union ctl_io *)ctsio);
8895		return (CTL_RETVAL_COMPLETE);
8896	}
8897
8898	/*
8899	 * According to SBC-3, a transfer length of 0 is not an error.
8900	 */
8901	if (num_blocks == 0) {
8902		ctl_set_success(ctsio);
8903		ctl_done((union ctl_io *)ctsio);
8904		return (CTL_RETVAL_COMPLETE);
8905	}
8906
8907	/* Set FUA if write cache is disabled. */
8908	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8909		flags |= CTL_LLF_FUA;
8910
8911	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8912	ctsio->kern_rel_offset = 0;
8913
8914	/*
8915	 * Set the IO_CONT flag, so that if this I/O gets passed to
8916	 * ctl_data_submit_done(), it'll get passed back to
8917	 * ctl_ctl_cnw_cont() for further processing.
8918	 */
8919	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8920	ctsio->io_cont = ctl_cnw_cont;
8921
8922	lbalen = (struct ctl_lba_len_flags *)
8923	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8924	lbalen->lba = lba;
8925	lbalen->len = num_blocks;
8926	lbalen->flags = CTL_LLF_COMPARE | flags;
8927
8928	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8929	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8930	return (retval);
8931}
8932
8933int
8934ctl_verify(struct ctl_scsiio *ctsio)
8935{
8936	struct ctl_lun *lun;
8937	struct ctl_lba_len_flags *lbalen;
8938	uint64_t lba;
8939	uint32_t num_blocks;
8940	int bytchk, flags;
8941	int retval;
8942
8943	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8944
8945	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8946
8947	bytchk = 0;
8948	flags = CTL_LLF_FUA;
8949	switch (ctsio->cdb[0]) {
8950	case VERIFY_10: {
8951		struct scsi_verify_10 *cdb;
8952
8953		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8954		if (cdb->byte2 & SVFY_BYTCHK)
8955			bytchk = 1;
8956		if (cdb->byte2 & SVFY_DPO)
8957			flags |= CTL_LLF_DPO;
8958		lba = scsi_4btoul(cdb->addr);
8959		num_blocks = scsi_2btoul(cdb->length);
8960		break;
8961	}
8962	case VERIFY_12: {
8963		struct scsi_verify_12 *cdb;
8964
8965		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8966		if (cdb->byte2 & SVFY_BYTCHK)
8967			bytchk = 1;
8968		if (cdb->byte2 & SVFY_DPO)
8969			flags |= CTL_LLF_DPO;
8970		lba = scsi_4btoul(cdb->addr);
8971		num_blocks = scsi_4btoul(cdb->length);
8972		break;
8973	}
8974	case VERIFY_16: {
8975		struct scsi_rw_16 *cdb;
8976
8977		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8978		if (cdb->byte2 & SVFY_BYTCHK)
8979			bytchk = 1;
8980		if (cdb->byte2 & SVFY_DPO)
8981			flags |= CTL_LLF_DPO;
8982		lba = scsi_8btou64(cdb->addr);
8983		num_blocks = scsi_4btoul(cdb->length);
8984		break;
8985	}
8986	default:
8987		/*
8988		 * We got a command we don't support.  This shouldn't
8989		 * happen, commands should be filtered out above us.
8990		 */
8991		ctl_set_invalid_opcode(ctsio);
8992		ctl_done((union ctl_io *)ctsio);
8993		return (CTL_RETVAL_COMPLETE);
8994	}
8995
8996	/*
8997	 * The first check is to make sure we're in bounds, the second
8998	 * check is to catch wrap-around problems.  If the lba + num blocks
8999	 * is less than the lba, then we've wrapped around and the block
9000	 * range is invalid anyway.
9001	 */
9002	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9003	 || ((lba + num_blocks) < lba)) {
9004		ctl_set_lba_out_of_range(ctsio,
9005		    MAX(lba, lun->be_lun->maxlba + 1));
9006		ctl_done((union ctl_io *)ctsio);
9007		return (CTL_RETVAL_COMPLETE);
9008	}
9009
9010	/*
9011	 * According to SBC-3, a transfer length of 0 is not an error.
9012	 */
9013	if (num_blocks == 0) {
9014		ctl_set_success(ctsio);
9015		ctl_done((union ctl_io *)ctsio);
9016		return (CTL_RETVAL_COMPLETE);
9017	}
9018
9019	lbalen = (struct ctl_lba_len_flags *)
9020	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9021	lbalen->lba = lba;
9022	lbalen->len = num_blocks;
9023	if (bytchk) {
9024		lbalen->flags = CTL_LLF_COMPARE | flags;
9025		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9026	} else {
9027		lbalen->flags = CTL_LLF_VERIFY | flags;
9028		ctsio->kern_total_len = 0;
9029	}
9030	ctsio->kern_rel_offset = 0;
9031
9032	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9033	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9034	return (retval);
9035}
9036
9037int
9038ctl_report_luns(struct ctl_scsiio *ctsio)
9039{
9040	struct ctl_softc *softc;
9041	struct scsi_report_luns *cdb;
9042	struct scsi_report_luns_data *lun_data;
9043	struct ctl_lun *lun, *request_lun;
9044	struct ctl_port *port;
9045	int num_luns, retval;
9046	uint32_t alloc_len, lun_datalen;
9047	int num_filled;
9048	uint32_t initidx, targ_lun_id, lun_id;
9049
9050	retval = CTL_RETVAL_COMPLETE;
9051	cdb = (struct scsi_report_luns *)ctsio->cdb;
9052	port = ctl_io_port(&ctsio->io_hdr);
9053	softc = port->ctl_softc;
9054
9055	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9056
9057	mtx_lock(&softc->ctl_lock);
9058	num_luns = 0;
9059	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9060		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9061			num_luns++;
9062	}
9063	mtx_unlock(&softc->ctl_lock);
9064
9065	switch (cdb->select_report) {
9066	case RPL_REPORT_DEFAULT:
9067	case RPL_REPORT_ALL:
9068	case RPL_REPORT_NONSUBSID:
9069		break;
9070	case RPL_REPORT_WELLKNOWN:
9071	case RPL_REPORT_ADMIN:
9072	case RPL_REPORT_CONGLOM:
9073		num_luns = 0;
9074		break;
9075	default:
9076		ctl_set_invalid_field(ctsio,
9077				      /*sks_valid*/ 1,
9078				      /*command*/ 1,
9079				      /*field*/ 2,
9080				      /*bit_valid*/ 0,
9081				      /*bit*/ 0);
9082		ctl_done((union ctl_io *)ctsio);
9083		return (retval);
9084		break; /* NOTREACHED */
9085	}
9086
9087	alloc_len = scsi_4btoul(cdb->length);
9088	/*
9089	 * The initiator has to allocate at least 16 bytes for this request,
9090	 * so he can at least get the header and the first LUN.  Otherwise
9091	 * we reject the request (per SPC-3 rev 14, section 6.21).
9092	 */
9093	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9094	    sizeof(struct scsi_report_luns_lundata))) {
9095		ctl_set_invalid_field(ctsio,
9096				      /*sks_valid*/ 1,
9097				      /*command*/ 1,
9098				      /*field*/ 6,
9099				      /*bit_valid*/ 0,
9100				      /*bit*/ 0);
9101		ctl_done((union ctl_io *)ctsio);
9102		return (retval);
9103	}
9104
9105	request_lun = (struct ctl_lun *)
9106		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9107
9108	lun_datalen = sizeof(*lun_data) +
9109		(num_luns * sizeof(struct scsi_report_luns_lundata));
9110
9111	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9112	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9113	ctsio->kern_sg_entries = 0;
9114
9115	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9116
9117	mtx_lock(&softc->ctl_lock);
9118	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9119		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9120		if (lun_id >= CTL_MAX_LUNS)
9121			continue;
9122		lun = softc->ctl_luns[lun_id];
9123		if (lun == NULL)
9124			continue;
9125
9126		be64enc(lun_data->luns[num_filled++].lundata,
9127		    ctl_encode_lun(targ_lun_id));
9128
9129		/*
9130		 * According to SPC-3, rev 14 section 6.21:
9131		 *
9132		 * "The execution of a REPORT LUNS command to any valid and
9133		 * installed logical unit shall clear the REPORTED LUNS DATA
9134		 * HAS CHANGED unit attention condition for all logical
9135		 * units of that target with respect to the requesting
9136		 * initiator. A valid and installed logical unit is one
9137		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9138		 * INQUIRY data (see 6.4.2)."
9139		 *
9140		 * If request_lun is NULL, the LUN this report luns command
9141		 * was issued to is either disabled or doesn't exist. In that
9142		 * case, we shouldn't clear any pending lun change unit
9143		 * attention.
9144		 */
9145		if (request_lun != NULL) {
9146			mtx_lock(&lun->lun_lock);
9147			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9148			mtx_unlock(&lun->lun_lock);
9149		}
9150	}
9151	mtx_unlock(&softc->ctl_lock);
9152
9153	/*
9154	 * It's quite possible that we've returned fewer LUNs than we allocated
9155	 * space for.  Trim it.
9156	 */
9157	lun_datalen = sizeof(*lun_data) +
9158		(num_filled * sizeof(struct scsi_report_luns_lundata));
9159
9160	if (lun_datalen < alloc_len) {
9161		ctsio->residual = alloc_len - lun_datalen;
9162		ctsio->kern_data_len = lun_datalen;
9163		ctsio->kern_total_len = lun_datalen;
9164	} else {
9165		ctsio->residual = 0;
9166		ctsio->kern_data_len = alloc_len;
9167		ctsio->kern_total_len = alloc_len;
9168	}
9169	ctsio->kern_data_resid = 0;
9170	ctsio->kern_rel_offset = 0;
9171	ctsio->kern_sg_entries = 0;
9172
9173	/*
9174	 * We set this to the actual data length, regardless of how much
9175	 * space we actually have to return results.  If the user looks at
9176	 * this value, he'll know whether or not he allocated enough space
9177	 * and reissue the command if necessary.  We don't support well
9178	 * known logical units, so if the user asks for that, return none.
9179	 */
9180	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9181
9182	/*
9183	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9184	 * this request.
9185	 */
9186	ctl_set_success(ctsio);
9187	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9188	ctsio->be_move_done = ctl_config_move_done;
9189	ctl_datamove((union ctl_io *)ctsio);
9190	return (retval);
9191}
9192
9193int
9194ctl_request_sense(struct ctl_scsiio *ctsio)
9195{
9196	struct scsi_request_sense *cdb;
9197	struct scsi_sense_data *sense_ptr;
9198	struct ctl_softc *softc;
9199	struct ctl_lun *lun;
9200	uint32_t initidx;
9201	int have_error;
9202	scsi_sense_data_type sense_format;
9203	ctl_ua_type ua_type;
9204	uint8_t asc = 0, ascq = 0;
9205
9206	cdb = (struct scsi_request_sense *)ctsio->cdb;
9207
9208	softc = control_softc;
9209	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9210
9211	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9212
9213	/*
9214	 * Determine which sense format the user wants.
9215	 */
9216	if (cdb->byte2 & SRS_DESC)
9217		sense_format = SSD_TYPE_DESC;
9218	else
9219		sense_format = SSD_TYPE_FIXED;
9220
9221	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9222	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9223	ctsio->kern_sg_entries = 0;
9224
9225	/*
9226	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9227	 * larger than the largest allowed value for the length field in the
9228	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9229	 */
9230	ctsio->residual = 0;
9231	ctsio->kern_data_len = cdb->length;
9232	ctsio->kern_total_len = cdb->length;
9233
9234	ctsio->kern_data_resid = 0;
9235	ctsio->kern_rel_offset = 0;
9236	ctsio->kern_sg_entries = 0;
9237
9238	/*
9239	 * If we don't have a LUN, we don't have any pending sense.
9240	 */
9241	if (lun == NULL ||
9242	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9243	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9244		/* "Logical unit not supported" */
9245		ctl_set_sense_data(sense_ptr, NULL, sense_format,
9246		    /*current_error*/ 1,
9247		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9248		    /*asc*/ 0x25,
9249		    /*ascq*/ 0x00,
9250		    SSD_ELEM_NONE);
9251		goto send;
9252	}
9253
9254	have_error = 0;
9255	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9256	/*
9257	 * Check for pending sense, and then for pending unit attentions.
9258	 * Pending sense gets returned first, then pending unit attentions.
9259	 */
9260	mtx_lock(&lun->lun_lock);
9261#ifdef CTL_WITH_CA
9262	if (ctl_is_set(lun->have_ca, initidx)) {
9263		scsi_sense_data_type stored_format;
9264
9265		/*
9266		 * Check to see which sense format was used for the stored
9267		 * sense data.
9268		 */
9269		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9270
9271		/*
9272		 * If the user requested a different sense format than the
9273		 * one we stored, then we need to convert it to the other
9274		 * format.  If we're going from descriptor to fixed format
9275		 * sense data, we may lose things in translation, depending
9276		 * on what options were used.
9277		 *
9278		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9279		 * for some reason we'll just copy it out as-is.
9280		 */
9281		if ((stored_format == SSD_TYPE_FIXED)
9282		 && (sense_format == SSD_TYPE_DESC))
9283			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9284			    &lun->pending_sense[initidx],
9285			    (struct scsi_sense_data_desc *)sense_ptr);
9286		else if ((stored_format == SSD_TYPE_DESC)
9287		      && (sense_format == SSD_TYPE_FIXED))
9288			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9289			    &lun->pending_sense[initidx],
9290			    (struct scsi_sense_data_fixed *)sense_ptr);
9291		else
9292			memcpy(sense_ptr, &lun->pending_sense[initidx],
9293			       MIN(sizeof(*sense_ptr),
9294			       sizeof(lun->pending_sense[initidx])));
9295
9296		ctl_clear_mask(lun->have_ca, initidx);
9297		have_error = 1;
9298	} else
9299#endif
9300	if (have_error == 0) {
9301		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9302		if (ua_type != CTL_UA_NONE)
9303			have_error = 1;
9304		if (ua_type == CTL_UA_LUN_CHANGE) {
9305			mtx_unlock(&lun->lun_lock);
9306			mtx_lock(&softc->ctl_lock);
9307			ctl_clr_ua_allluns(softc, initidx, ua_type);
9308			mtx_unlock(&softc->ctl_lock);
9309			mtx_lock(&lun->lun_lock);
9310		}
9311	}
9312	if (have_error == 0) {
9313		/*
9314		 * Report informational exception if have one and allowed.
9315		 */
9316		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9317			asc = lun->ie_asc;
9318			ascq = lun->ie_ascq;
9319		}
9320		ctl_set_sense_data(sense_ptr, lun, sense_format,
9321		    /*current_error*/ 1,
9322		    /*sense_key*/ SSD_KEY_NO_SENSE,
9323		    /*asc*/ asc,
9324		    /*ascq*/ ascq,
9325		    SSD_ELEM_NONE);
9326	}
9327	mtx_unlock(&lun->lun_lock);
9328
9329send:
9330	/*
9331	 * We report the SCSI status as OK, since the status of the command
9332	 * itself is OK.  We're reporting sense as parameter data.
9333	 */
9334	ctl_set_success(ctsio);
9335	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9336	ctsio->be_move_done = ctl_config_move_done;
9337	ctl_datamove((union ctl_io *)ctsio);
9338	return (CTL_RETVAL_COMPLETE);
9339}
9340
9341int
9342ctl_tur(struct ctl_scsiio *ctsio)
9343{
9344
9345	CTL_DEBUG_PRINT(("ctl_tur\n"));
9346
9347	ctl_set_success(ctsio);
9348	ctl_done((union ctl_io *)ctsio);
9349
9350	return (CTL_RETVAL_COMPLETE);
9351}
9352
9353/*
9354 * SCSI VPD page 0x00, the Supported VPD Pages page.
9355 */
9356static int
9357ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9358{
9359	struct scsi_vpd_supported_pages *pages;
9360	int sup_page_size;
9361	struct ctl_lun *lun;
9362	int p;
9363
9364	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9365
9366	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9367	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9368	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9369	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9370	ctsio->kern_sg_entries = 0;
9371
9372	if (sup_page_size < alloc_len) {
9373		ctsio->residual = alloc_len - sup_page_size;
9374		ctsio->kern_data_len = sup_page_size;
9375		ctsio->kern_total_len = sup_page_size;
9376	} else {
9377		ctsio->residual = 0;
9378		ctsio->kern_data_len = alloc_len;
9379		ctsio->kern_total_len = alloc_len;
9380	}
9381	ctsio->kern_data_resid = 0;
9382	ctsio->kern_rel_offset = 0;
9383	ctsio->kern_sg_entries = 0;
9384
9385	/*
9386	 * The control device is always connected.  The disk device, on the
9387	 * other hand, may not be online all the time.  Need to change this
9388	 * to figure out whether the disk device is actually online or not.
9389	 */
9390	if (lun != NULL)
9391		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9392				lun->be_lun->lun_type;
9393	else
9394		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9395
9396	p = 0;
9397	/* Supported VPD pages */
9398	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9399	/* Serial Number */
9400	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9401	/* Device Identification */
9402	pages->page_list[p++] = SVPD_DEVICE_ID;
9403	/* Extended INQUIRY Data */
9404	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9405	/* Mode Page Policy */
9406	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9407	/* SCSI Ports */
9408	pages->page_list[p++] = SVPD_SCSI_PORTS;
9409	/* Third-party Copy */
9410	pages->page_list[p++] = SVPD_SCSI_TPC;
9411	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9412		/* Block limits */
9413		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9414		/* Block Device Characteristics */
9415		pages->page_list[p++] = SVPD_BDC;
9416		/* Logical Block Provisioning */
9417		pages->page_list[p++] = SVPD_LBP;
9418	}
9419	pages->length = p;
9420
9421	ctl_set_success(ctsio);
9422	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9423	ctsio->be_move_done = ctl_config_move_done;
9424	ctl_datamove((union ctl_io *)ctsio);
9425	return (CTL_RETVAL_COMPLETE);
9426}
9427
9428/*
9429 * SCSI VPD page 0x80, the Unit Serial Number page.
9430 */
9431static int
9432ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9433{
9434	struct scsi_vpd_unit_serial_number *sn_ptr;
9435	struct ctl_lun *lun;
9436	int data_len;
9437
9438	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9439
9440	data_len = 4 + CTL_SN_LEN;
9441	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9442	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9443	if (data_len < alloc_len) {
9444		ctsio->residual = alloc_len - data_len;
9445		ctsio->kern_data_len = data_len;
9446		ctsio->kern_total_len = data_len;
9447	} else {
9448		ctsio->residual = 0;
9449		ctsio->kern_data_len = alloc_len;
9450		ctsio->kern_total_len = alloc_len;
9451	}
9452	ctsio->kern_data_resid = 0;
9453	ctsio->kern_rel_offset = 0;
9454	ctsio->kern_sg_entries = 0;
9455
9456	/*
9457	 * The control device is always connected.  The disk device, on the
9458	 * other hand, may not be online all the time.  Need to change this
9459	 * to figure out whether the disk device is actually online or not.
9460	 */
9461	if (lun != NULL)
9462		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9463				  lun->be_lun->lun_type;
9464	else
9465		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9466
9467	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9468	sn_ptr->length = CTL_SN_LEN;
9469	/*
9470	 * If we don't have a LUN, we just leave the serial number as
9471	 * all spaces.
9472	 */
9473	if (lun != NULL) {
9474		strncpy((char *)sn_ptr->serial_num,
9475			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9476	} else
9477		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9478
9479	ctl_set_success(ctsio);
9480	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9481	ctsio->be_move_done = ctl_config_move_done;
9482	ctl_datamove((union ctl_io *)ctsio);
9483	return (CTL_RETVAL_COMPLETE);
9484}
9485
9486
9487/*
9488 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9489 */
9490static int
9491ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9492{
9493	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9494	struct ctl_lun *lun;
9495	int data_len;
9496
9497	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9498
9499	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9500	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9501	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9502	ctsio->kern_sg_entries = 0;
9503
9504	if (data_len < alloc_len) {
9505		ctsio->residual = alloc_len - data_len;
9506		ctsio->kern_data_len = data_len;
9507		ctsio->kern_total_len = data_len;
9508	} else {
9509		ctsio->residual = 0;
9510		ctsio->kern_data_len = alloc_len;
9511		ctsio->kern_total_len = alloc_len;
9512	}
9513	ctsio->kern_data_resid = 0;
9514	ctsio->kern_rel_offset = 0;
9515	ctsio->kern_sg_entries = 0;
9516
9517	/*
9518	 * The control device is always connected.  The disk device, on the
9519	 * other hand, may not be online all the time.
9520	 */
9521	if (lun != NULL)
9522		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9523				     lun->be_lun->lun_type;
9524	else
9525		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9526	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9527	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9528	/*
9529	 * We support head of queue, ordered and simple tags.
9530	 */
9531	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9532	/*
9533	 * Volatile cache supported.
9534	 */
9535	eid_ptr->flags3 = SVPD_EID_V_SUP;
9536
9537	/*
9538	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9539	 * attention for a particular IT nexus on all LUNs once we report
9540	 * it to that nexus once.  This bit is required as of SPC-4.
9541	 */
9542	eid_ptr->flags4 = SVPD_EID_LUICLR;
9543
9544	/*
9545	 * XXX KDM in order to correctly answer this, we would need
9546	 * information from the SIM to determine how much sense data it
9547	 * can send.  So this would really be a path inquiry field, most
9548	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9549	 * but the hardware may or may not be able to support that much.
9550	 * 0 just means that the maximum sense data length is not reported.
9551	 */
9552	eid_ptr->max_sense_length = 0;
9553
9554	ctl_set_success(ctsio);
9555	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9556	ctsio->be_move_done = ctl_config_move_done;
9557	ctl_datamove((union ctl_io *)ctsio);
9558	return (CTL_RETVAL_COMPLETE);
9559}
9560
9561static int
9562ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9563{
9564	struct scsi_vpd_mode_page_policy *mpp_ptr;
9565	struct ctl_lun *lun;
9566	int data_len;
9567
9568	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9569
9570	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9571	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9572
9573	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9574	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9575	ctsio->kern_sg_entries = 0;
9576
9577	if (data_len < alloc_len) {
9578		ctsio->residual = alloc_len - data_len;
9579		ctsio->kern_data_len = data_len;
9580		ctsio->kern_total_len = data_len;
9581	} else {
9582		ctsio->residual = 0;
9583		ctsio->kern_data_len = alloc_len;
9584		ctsio->kern_total_len = alloc_len;
9585	}
9586	ctsio->kern_data_resid = 0;
9587	ctsio->kern_rel_offset = 0;
9588	ctsio->kern_sg_entries = 0;
9589
9590	/*
9591	 * The control device is always connected.  The disk device, on the
9592	 * other hand, may not be online all the time.
9593	 */
9594	if (lun != NULL)
9595		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9596				     lun->be_lun->lun_type;
9597	else
9598		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9599	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9600	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9601	mpp_ptr->descr[0].page_code = 0x3f;
9602	mpp_ptr->descr[0].subpage_code = 0xff;
9603	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9604
9605	ctl_set_success(ctsio);
9606	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9607	ctsio->be_move_done = ctl_config_move_done;
9608	ctl_datamove((union ctl_io *)ctsio);
9609	return (CTL_RETVAL_COMPLETE);
9610}
9611
9612/*
9613 * SCSI VPD page 0x83, the Device Identification page.
9614 */
9615static int
9616ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9617{
9618	struct scsi_vpd_device_id *devid_ptr;
9619	struct scsi_vpd_id_descriptor *desc;
9620	struct ctl_softc *softc;
9621	struct ctl_lun *lun;
9622	struct ctl_port *port;
9623	int data_len, g;
9624	uint8_t proto;
9625
9626	softc = control_softc;
9627
9628	port = ctl_io_port(&ctsio->io_hdr);
9629	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9630
9631	data_len = sizeof(struct scsi_vpd_device_id) +
9632	    sizeof(struct scsi_vpd_id_descriptor) +
9633		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9634	    sizeof(struct scsi_vpd_id_descriptor) +
9635		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9636	if (lun && lun->lun_devid)
9637		data_len += lun->lun_devid->len;
9638	if (port && port->port_devid)
9639		data_len += port->port_devid->len;
9640	if (port && port->target_devid)
9641		data_len += port->target_devid->len;
9642
9643	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9644	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9645	ctsio->kern_sg_entries = 0;
9646
9647	if (data_len < alloc_len) {
9648		ctsio->residual = alloc_len - data_len;
9649		ctsio->kern_data_len = data_len;
9650		ctsio->kern_total_len = data_len;
9651	} else {
9652		ctsio->residual = 0;
9653		ctsio->kern_data_len = alloc_len;
9654		ctsio->kern_total_len = alloc_len;
9655	}
9656	ctsio->kern_data_resid = 0;
9657	ctsio->kern_rel_offset = 0;
9658	ctsio->kern_sg_entries = 0;
9659
9660	/*
9661	 * The control device is always connected.  The disk device, on the
9662	 * other hand, may not be online all the time.
9663	 */
9664	if (lun != NULL)
9665		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9666				     lun->be_lun->lun_type;
9667	else
9668		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9669	devid_ptr->page_code = SVPD_DEVICE_ID;
9670	scsi_ulto2b(data_len - 4, devid_ptr->length);
9671
9672	if (port && port->port_type == CTL_PORT_FC)
9673		proto = SCSI_PROTO_FC << 4;
9674	else if (port && port->port_type == CTL_PORT_ISCSI)
9675		proto = SCSI_PROTO_ISCSI << 4;
9676	else
9677		proto = SCSI_PROTO_SPI << 4;
9678	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9679
9680	/*
9681	 * We're using a LUN association here.  i.e., this device ID is a
9682	 * per-LUN identifier.
9683	 */
9684	if (lun && lun->lun_devid) {
9685		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9686		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9687		    lun->lun_devid->len);
9688	}
9689
9690	/*
9691	 * This is for the WWPN which is a port association.
9692	 */
9693	if (port && port->port_devid) {
9694		memcpy(desc, port->port_devid->data, port->port_devid->len);
9695		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9696		    port->port_devid->len);
9697	}
9698
9699	/*
9700	 * This is for the Relative Target Port(type 4h) identifier
9701	 */
9702	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9703	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9704	    SVPD_ID_TYPE_RELTARG;
9705	desc->length = 4;
9706	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9707	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9708	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9709
9710	/*
9711	 * This is for the Target Port Group(type 5h) identifier
9712	 */
9713	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9714	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9715	    SVPD_ID_TYPE_TPORTGRP;
9716	desc->length = 4;
9717	if (softc->is_single ||
9718	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9719		g = 1;
9720	else
9721		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9722	scsi_ulto2b(g, &desc->identifier[2]);
9723	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9724	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9725
9726	/*
9727	 * This is for the Target identifier
9728	 */
9729	if (port && port->target_devid) {
9730		memcpy(desc, port->target_devid->data, port->target_devid->len);
9731	}
9732
9733	ctl_set_success(ctsio);
9734	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9735	ctsio->be_move_done = ctl_config_move_done;
9736	ctl_datamove((union ctl_io *)ctsio);
9737	return (CTL_RETVAL_COMPLETE);
9738}
9739
9740static int
9741ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9742{
9743	struct ctl_softc *softc = control_softc;
9744	struct scsi_vpd_scsi_ports *sp;
9745	struct scsi_vpd_port_designation *pd;
9746	struct scsi_vpd_port_designation_cont *pdc;
9747	struct ctl_lun *lun;
9748	struct ctl_port *port;
9749	int data_len, num_target_ports, iid_len, id_len;
9750
9751	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9752
9753	num_target_ports = 0;
9754	iid_len = 0;
9755	id_len = 0;
9756	mtx_lock(&softc->ctl_lock);
9757	STAILQ_FOREACH(port, &softc->port_list, links) {
9758		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9759			continue;
9760		if (lun != NULL &&
9761		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9762			continue;
9763		num_target_ports++;
9764		if (port->init_devid)
9765			iid_len += port->init_devid->len;
9766		if (port->port_devid)
9767			id_len += port->port_devid->len;
9768	}
9769	mtx_unlock(&softc->ctl_lock);
9770
9771	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9772	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9773	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9774	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9775	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9776	ctsio->kern_sg_entries = 0;
9777
9778	if (data_len < alloc_len) {
9779		ctsio->residual = alloc_len - data_len;
9780		ctsio->kern_data_len = data_len;
9781		ctsio->kern_total_len = data_len;
9782	} else {
9783		ctsio->residual = 0;
9784		ctsio->kern_data_len = alloc_len;
9785		ctsio->kern_total_len = alloc_len;
9786	}
9787	ctsio->kern_data_resid = 0;
9788	ctsio->kern_rel_offset = 0;
9789	ctsio->kern_sg_entries = 0;
9790
9791	/*
9792	 * The control device is always connected.  The disk device, on the
9793	 * other hand, may not be online all the time.  Need to change this
9794	 * to figure out whether the disk device is actually online or not.
9795	 */
9796	if (lun != NULL)
9797		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9798				  lun->be_lun->lun_type;
9799	else
9800		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9801
9802	sp->page_code = SVPD_SCSI_PORTS;
9803	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9804	    sp->page_length);
9805	pd = &sp->design[0];
9806
9807	mtx_lock(&softc->ctl_lock);
9808	STAILQ_FOREACH(port, &softc->port_list, links) {
9809		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9810			continue;
9811		if (lun != NULL &&
9812		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9813			continue;
9814		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9815		if (port->init_devid) {
9816			iid_len = port->init_devid->len;
9817			memcpy(pd->initiator_transportid,
9818			    port->init_devid->data, port->init_devid->len);
9819		} else
9820			iid_len = 0;
9821		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9822		pdc = (struct scsi_vpd_port_designation_cont *)
9823		    (&pd->initiator_transportid[iid_len]);
9824		if (port->port_devid) {
9825			id_len = port->port_devid->len;
9826			memcpy(pdc->target_port_descriptors,
9827			    port->port_devid->data, port->port_devid->len);
9828		} else
9829			id_len = 0;
9830		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9831		pd = (struct scsi_vpd_port_designation *)
9832		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9833	}
9834	mtx_unlock(&softc->ctl_lock);
9835
9836	ctl_set_success(ctsio);
9837	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9838	ctsio->be_move_done = ctl_config_move_done;
9839	ctl_datamove((union ctl_io *)ctsio);
9840	return (CTL_RETVAL_COMPLETE);
9841}
9842
9843static int
9844ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9845{
9846	struct scsi_vpd_block_limits *bl_ptr;
9847	struct ctl_lun *lun;
9848	uint64_t ival;
9849
9850	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9851
9852	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9853	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9854	ctsio->kern_sg_entries = 0;
9855
9856	if (sizeof(*bl_ptr) < alloc_len) {
9857		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9858		ctsio->kern_data_len = sizeof(*bl_ptr);
9859		ctsio->kern_total_len = sizeof(*bl_ptr);
9860	} else {
9861		ctsio->residual = 0;
9862		ctsio->kern_data_len = alloc_len;
9863		ctsio->kern_total_len = alloc_len;
9864	}
9865	ctsio->kern_data_resid = 0;
9866	ctsio->kern_rel_offset = 0;
9867	ctsio->kern_sg_entries = 0;
9868
9869	/*
9870	 * The control device is always connected.  The disk device, on the
9871	 * other hand, may not be online all the time.  Need to change this
9872	 * to figure out whether the disk device is actually online or not.
9873	 */
9874	if (lun != NULL)
9875		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9876				  lun->be_lun->lun_type;
9877	else
9878		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9879
9880	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9881	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9882	bl_ptr->max_cmp_write_len = 0xff;
9883	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9884	if (lun != NULL) {
9885		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9886		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9887			ival = 0xffffffff;
9888			ctl_get_opt_number(&lun->be_lun->options,
9889			    "unmap_max_lba", &ival);
9890			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9891			ival = 0xffffffff;
9892			ctl_get_opt_number(&lun->be_lun->options,
9893			    "unmap_max_descr", &ival);
9894			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9895			if (lun->be_lun->ublockexp != 0) {
9896				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9897				    bl_ptr->opt_unmap_grain);
9898				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9899				    bl_ptr->unmap_grain_align);
9900			}
9901		}
9902		scsi_ulto4b(lun->be_lun->atomicblock,
9903		    bl_ptr->max_atomic_transfer_length);
9904		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9905		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9906		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9907		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9908		ival = UINT64_MAX;
9909		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9910		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9911	}
9912
9913	ctl_set_success(ctsio);
9914	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9915	ctsio->be_move_done = ctl_config_move_done;
9916	ctl_datamove((union ctl_io *)ctsio);
9917	return (CTL_RETVAL_COMPLETE);
9918}
9919
9920static int
9921ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9922{
9923	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9924	struct ctl_lun *lun;
9925	const char *value;
9926	u_int i;
9927
9928	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9929
9930	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9931	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9932	ctsio->kern_sg_entries = 0;
9933
9934	if (sizeof(*bdc_ptr) < alloc_len) {
9935		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9936		ctsio->kern_data_len = sizeof(*bdc_ptr);
9937		ctsio->kern_total_len = sizeof(*bdc_ptr);
9938	} else {
9939		ctsio->residual = 0;
9940		ctsio->kern_data_len = alloc_len;
9941		ctsio->kern_total_len = alloc_len;
9942	}
9943	ctsio->kern_data_resid = 0;
9944	ctsio->kern_rel_offset = 0;
9945	ctsio->kern_sg_entries = 0;
9946
9947	/*
9948	 * The control device is always connected.  The disk device, on the
9949	 * other hand, may not be online all the time.  Need to change this
9950	 * to figure out whether the disk device is actually online or not.
9951	 */
9952	if (lun != NULL)
9953		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9954				  lun->be_lun->lun_type;
9955	else
9956		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9957	bdc_ptr->page_code = SVPD_BDC;
9958	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9959	if (lun != NULL &&
9960	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9961		i = strtol(value, NULL, 0);
9962	else
9963		i = CTL_DEFAULT_ROTATION_RATE;
9964	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9965	if (lun != NULL &&
9966	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9967		i = strtol(value, NULL, 0);
9968	else
9969		i = 0;
9970	bdc_ptr->wab_wac_ff = (i & 0x0f);
9971	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9972
9973	ctl_set_success(ctsio);
9974	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9975	ctsio->be_move_done = ctl_config_move_done;
9976	ctl_datamove((union ctl_io *)ctsio);
9977	return (CTL_RETVAL_COMPLETE);
9978}
9979
9980static int
9981ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9982{
9983	struct scsi_vpd_logical_block_prov *lbp_ptr;
9984	struct ctl_lun *lun;
9985	const char *value;
9986
9987	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9988
9989	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9990	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9991	ctsio->kern_sg_entries = 0;
9992
9993	if (sizeof(*lbp_ptr) < alloc_len) {
9994		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9995		ctsio->kern_data_len = sizeof(*lbp_ptr);
9996		ctsio->kern_total_len = sizeof(*lbp_ptr);
9997	} else {
9998		ctsio->residual = 0;
9999		ctsio->kern_data_len = alloc_len;
10000		ctsio->kern_total_len = alloc_len;
10001	}
10002	ctsio->kern_data_resid = 0;
10003	ctsio->kern_rel_offset = 0;
10004	ctsio->kern_sg_entries = 0;
10005
10006	/*
10007	 * The control device is always connected.  The disk device, on the
10008	 * other hand, may not be online all the time.  Need to change this
10009	 * to figure out whether the disk device is actually online or not.
10010	 */
10011	if (lun != NULL)
10012		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10013				  lun->be_lun->lun_type;
10014	else
10015		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10016
10017	lbp_ptr->page_code = SVPD_LBP;
10018	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10019	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10020	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10021		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10022		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10023		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10024		if (value != NULL) {
10025			if (strcmp(value, "resource") == 0)
10026				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10027			else if (strcmp(value, "thin") == 0)
10028				lbp_ptr->prov_type = SVPD_LBP_THIN;
10029		} else
10030			lbp_ptr->prov_type = SVPD_LBP_THIN;
10031	}
10032
10033	ctl_set_success(ctsio);
10034	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10035	ctsio->be_move_done = ctl_config_move_done;
10036	ctl_datamove((union ctl_io *)ctsio);
10037	return (CTL_RETVAL_COMPLETE);
10038}
10039
10040/*
10041 * INQUIRY with the EVPD bit set.
10042 */
10043static int
10044ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10045{
10046	struct ctl_lun *lun;
10047	struct scsi_inquiry *cdb;
10048	int alloc_len, retval;
10049
10050	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10051	cdb = (struct scsi_inquiry *)ctsio->cdb;
10052	alloc_len = scsi_2btoul(cdb->length);
10053
10054	switch (cdb->page_code) {
10055	case SVPD_SUPPORTED_PAGES:
10056		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10057		break;
10058	case SVPD_UNIT_SERIAL_NUMBER:
10059		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10060		break;
10061	case SVPD_DEVICE_ID:
10062		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10063		break;
10064	case SVPD_EXTENDED_INQUIRY_DATA:
10065		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10066		break;
10067	case SVPD_MODE_PAGE_POLICY:
10068		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10069		break;
10070	case SVPD_SCSI_PORTS:
10071		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10072		break;
10073	case SVPD_SCSI_TPC:
10074		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10075		break;
10076	case SVPD_BLOCK_LIMITS:
10077		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10078			goto err;
10079		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10080		break;
10081	case SVPD_BDC:
10082		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10083			goto err;
10084		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10085		break;
10086	case SVPD_LBP:
10087		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10088			goto err;
10089		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10090		break;
10091	default:
10092err:
10093		ctl_set_invalid_field(ctsio,
10094				      /*sks_valid*/ 1,
10095				      /*command*/ 1,
10096				      /*field*/ 2,
10097				      /*bit_valid*/ 0,
10098				      /*bit*/ 0);
10099		ctl_done((union ctl_io *)ctsio);
10100		retval = CTL_RETVAL_COMPLETE;
10101		break;
10102	}
10103
10104	return (retval);
10105}
10106
10107/*
10108 * Standard INQUIRY data.
10109 */
10110static int
10111ctl_inquiry_std(struct ctl_scsiio *ctsio)
10112{
10113	struct scsi_inquiry_data *inq_ptr;
10114	struct scsi_inquiry *cdb;
10115	struct ctl_softc *softc = control_softc;
10116	struct ctl_port *port;
10117	struct ctl_lun *lun;
10118	char *val;
10119	uint32_t alloc_len, data_len;
10120	ctl_port_type port_type;
10121
10122	port = ctl_io_port(&ctsio->io_hdr);
10123	port_type = port->port_type;
10124	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10125		port_type = CTL_PORT_SCSI;
10126
10127	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10128	cdb = (struct scsi_inquiry *)ctsio->cdb;
10129	alloc_len = scsi_2btoul(cdb->length);
10130
10131	/*
10132	 * We malloc the full inquiry data size here and fill it
10133	 * in.  If the user only asks for less, we'll give him
10134	 * that much.
10135	 */
10136	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10137	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10138	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10139	ctsio->kern_sg_entries = 0;
10140	ctsio->kern_data_resid = 0;
10141	ctsio->kern_rel_offset = 0;
10142
10143	if (data_len < alloc_len) {
10144		ctsio->residual = alloc_len - data_len;
10145		ctsio->kern_data_len = data_len;
10146		ctsio->kern_total_len = data_len;
10147	} else {
10148		ctsio->residual = 0;
10149		ctsio->kern_data_len = alloc_len;
10150		ctsio->kern_total_len = alloc_len;
10151	}
10152
10153	if (lun != NULL) {
10154		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10155		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10156			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10157			    lun->be_lun->lun_type;
10158		} else {
10159			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10160			    lun->be_lun->lun_type;
10161		}
10162		if (lun->flags & CTL_LUN_REMOVABLE)
10163			inq_ptr->dev_qual2 |= SID_RMB;
10164	} else
10165		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10166
10167	/* RMB in byte 2 is 0 */
10168	inq_ptr->version = SCSI_REV_SPC5;
10169
10170	/*
10171	 * According to SAM-3, even if a device only supports a single
10172	 * level of LUN addressing, it should still set the HISUP bit:
10173	 *
10174	 * 4.9.1 Logical unit numbers overview
10175	 *
10176	 * All logical unit number formats described in this standard are
10177	 * hierarchical in structure even when only a single level in that
10178	 * hierarchy is used. The HISUP bit shall be set to one in the
10179	 * standard INQUIRY data (see SPC-2) when any logical unit number
10180	 * format described in this standard is used.  Non-hierarchical
10181	 * formats are outside the scope of this standard.
10182	 *
10183	 * Therefore we set the HiSup bit here.
10184	 *
10185	 * The response format is 2, per SPC-3.
10186	 */
10187	inq_ptr->response_format = SID_HiSup | 2;
10188
10189	inq_ptr->additional_length = data_len -
10190	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10191	CTL_DEBUG_PRINT(("additional_length = %d\n",
10192			 inq_ptr->additional_length));
10193
10194	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10195	if (port_type == CTL_PORT_SCSI)
10196		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10197	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10198	inq_ptr->flags = SID_CmdQue;
10199	if (port_type == CTL_PORT_SCSI)
10200		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10201
10202	/*
10203	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10204	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10205	 * name and 4 bytes for the revision.
10206	 */
10207	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10208	    "vendor")) == NULL) {
10209		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10210	} else {
10211		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10212		strncpy(inq_ptr->vendor, val,
10213		    min(sizeof(inq_ptr->vendor), strlen(val)));
10214	}
10215	if (lun == NULL) {
10216		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10217		    sizeof(inq_ptr->product));
10218	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10219		switch (lun->be_lun->lun_type) {
10220		case T_DIRECT:
10221			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10222			    sizeof(inq_ptr->product));
10223			break;
10224		case T_PROCESSOR:
10225			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10226			    sizeof(inq_ptr->product));
10227			break;
10228		case T_CDROM:
10229			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10230			    sizeof(inq_ptr->product));
10231			break;
10232		default:
10233			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10234			    sizeof(inq_ptr->product));
10235			break;
10236		}
10237	} else {
10238		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10239		strncpy(inq_ptr->product, val,
10240		    min(sizeof(inq_ptr->product), strlen(val)));
10241	}
10242
10243	/*
10244	 * XXX make this a macro somewhere so it automatically gets
10245	 * incremented when we make changes.
10246	 */
10247	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10248	    "revision")) == NULL) {
10249		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10250	} else {
10251		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10252		strncpy(inq_ptr->revision, val,
10253		    min(sizeof(inq_ptr->revision), strlen(val)));
10254	}
10255
10256	/*
10257	 * For parallel SCSI, we support double transition and single
10258	 * transition clocking.  We also support QAS (Quick Arbitration
10259	 * and Selection) and Information Unit transfers on both the
10260	 * control and array devices.
10261	 */
10262	if (port_type == CTL_PORT_SCSI)
10263		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10264				    SID_SPI_IUS;
10265
10266	/* SAM-6 (no version claimed) */
10267	scsi_ulto2b(0x00C0, inq_ptr->version1);
10268	/* SPC-5 (no version claimed) */
10269	scsi_ulto2b(0x05C0, inq_ptr->version2);
10270	if (port_type == CTL_PORT_FC) {
10271		/* FCP-2 ANSI INCITS.350:2003 */
10272		scsi_ulto2b(0x0917, inq_ptr->version3);
10273	} else if (port_type == CTL_PORT_SCSI) {
10274		/* SPI-4 ANSI INCITS.362:200x */
10275		scsi_ulto2b(0x0B56, inq_ptr->version3);
10276	} else if (port_type == CTL_PORT_ISCSI) {
10277		/* iSCSI (no version claimed) */
10278		scsi_ulto2b(0x0960, inq_ptr->version3);
10279	} else if (port_type == CTL_PORT_SAS) {
10280		/* SAS (no version claimed) */
10281		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10282	}
10283
10284	if (lun == NULL) {
10285		/* SBC-4 (no version claimed) */
10286		scsi_ulto2b(0x0600, inq_ptr->version4);
10287	} else {
10288		switch (lun->be_lun->lun_type) {
10289		case T_DIRECT:
10290			/* SBC-4 (no version claimed) */
10291			scsi_ulto2b(0x0600, inq_ptr->version4);
10292			break;
10293		case T_PROCESSOR:
10294			break;
10295		case T_CDROM:
10296			/* MMC-6 (no version claimed) */
10297			scsi_ulto2b(0x04E0, inq_ptr->version4);
10298			break;
10299		default:
10300			break;
10301		}
10302	}
10303
10304	ctl_set_success(ctsio);
10305	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10306	ctsio->be_move_done = ctl_config_move_done;
10307	ctl_datamove((union ctl_io *)ctsio);
10308	return (CTL_RETVAL_COMPLETE);
10309}
10310
10311int
10312ctl_inquiry(struct ctl_scsiio *ctsio)
10313{
10314	struct scsi_inquiry *cdb;
10315	int retval;
10316
10317	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10318
10319	cdb = (struct scsi_inquiry *)ctsio->cdb;
10320	if (cdb->byte2 & SI_EVPD)
10321		retval = ctl_inquiry_evpd(ctsio);
10322	else if (cdb->page_code == 0)
10323		retval = ctl_inquiry_std(ctsio);
10324	else {
10325		ctl_set_invalid_field(ctsio,
10326				      /*sks_valid*/ 1,
10327				      /*command*/ 1,
10328				      /*field*/ 2,
10329				      /*bit_valid*/ 0,
10330				      /*bit*/ 0);
10331		ctl_done((union ctl_io *)ctsio);
10332		return (CTL_RETVAL_COMPLETE);
10333	}
10334
10335	return (retval);
10336}
10337
10338int
10339ctl_get_config(struct ctl_scsiio *ctsio)
10340{
10341	struct scsi_get_config_header *hdr;
10342	struct scsi_get_config_feature *feature;
10343	struct scsi_get_config *cdb;
10344	struct ctl_lun *lun;
10345	uint32_t alloc_len, data_len;
10346	int rt, starting;
10347
10348	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10349	cdb = (struct scsi_get_config *)ctsio->cdb;
10350	rt = (cdb->rt & SGC_RT_MASK);
10351	starting = scsi_2btoul(cdb->starting_feature);
10352	alloc_len = scsi_2btoul(cdb->length);
10353
10354	data_len = sizeof(struct scsi_get_config_header) +
10355	    sizeof(struct scsi_get_config_feature) + 8 +
10356	    sizeof(struct scsi_get_config_feature) + 8 +
10357	    sizeof(struct scsi_get_config_feature) + 4 +
10358	    sizeof(struct scsi_get_config_feature) + 4 +
10359	    sizeof(struct scsi_get_config_feature) + 8 +
10360	    sizeof(struct scsi_get_config_feature) +
10361	    sizeof(struct scsi_get_config_feature) + 4 +
10362	    sizeof(struct scsi_get_config_feature) + 4 +
10363	    sizeof(struct scsi_get_config_feature) + 4 +
10364	    sizeof(struct scsi_get_config_feature) + 4 +
10365	    sizeof(struct scsi_get_config_feature) + 4 +
10366	    sizeof(struct scsi_get_config_feature) + 4;
10367	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10368	ctsio->kern_sg_entries = 0;
10369	ctsio->kern_data_resid = 0;
10370	ctsio->kern_rel_offset = 0;
10371
10372	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10373	if (lun->flags & CTL_LUN_NO_MEDIA)
10374		scsi_ulto2b(0x0000, hdr->current_profile);
10375	else
10376		scsi_ulto2b(0x0010, hdr->current_profile);
10377	feature = (struct scsi_get_config_feature *)(hdr + 1);
10378
10379	if (starting > 0x003b)
10380		goto done;
10381	if (starting > 0x003a)
10382		goto f3b;
10383	if (starting > 0x002b)
10384		goto f3a;
10385	if (starting > 0x002a)
10386		goto f2b;
10387	if (starting > 0x001f)
10388		goto f2a;
10389	if (starting > 0x001e)
10390		goto f1f;
10391	if (starting > 0x001d)
10392		goto f1e;
10393	if (starting > 0x0010)
10394		goto f1d;
10395	if (starting > 0x0003)
10396		goto f10;
10397	if (starting > 0x0002)
10398		goto f3;
10399	if (starting > 0x0001)
10400		goto f2;
10401	if (starting > 0x0000)
10402		goto f1;
10403
10404	/* Profile List */
10405	scsi_ulto2b(0x0000, feature->feature_code);
10406	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10407	feature->add_length = 8;
10408	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10409	feature->feature_data[2] = 0x00;
10410	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10411	feature->feature_data[6] = 0x01;
10412	feature = (struct scsi_get_config_feature *)
10413	    &feature->feature_data[feature->add_length];
10414
10415f1:	/* Core */
10416	scsi_ulto2b(0x0001, feature->feature_code);
10417	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10418	feature->add_length = 8;
10419	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10420	feature->feature_data[4] = 0x03;
10421	feature = (struct scsi_get_config_feature *)
10422	    &feature->feature_data[feature->add_length];
10423
10424f2:	/* Morphing */
10425	scsi_ulto2b(0x0002, feature->feature_code);
10426	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10427	feature->add_length = 4;
10428	feature->feature_data[0] = 0x02;
10429	feature = (struct scsi_get_config_feature *)
10430	    &feature->feature_data[feature->add_length];
10431
10432f3:	/* Removable Medium */
10433	scsi_ulto2b(0x0003, feature->feature_code);
10434	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10435	feature->add_length = 4;
10436	feature->feature_data[0] = 0x39;
10437	feature = (struct scsi_get_config_feature *)
10438	    &feature->feature_data[feature->add_length];
10439
10440	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10441		goto done;
10442
10443f10:	/* Random Read */
10444	scsi_ulto2b(0x0010, feature->feature_code);
10445	feature->flags = 0x00;
10446	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10447		feature->flags |= SGC_F_CURRENT;
10448	feature->add_length = 8;
10449	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10450	scsi_ulto2b(1, &feature->feature_data[4]);
10451	feature->feature_data[6] = 0x00;
10452	feature = (struct scsi_get_config_feature *)
10453	    &feature->feature_data[feature->add_length];
10454
10455f1d:	/* Multi-Read */
10456	scsi_ulto2b(0x001D, feature->feature_code);
10457	feature->flags = 0x00;
10458	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10459		feature->flags |= SGC_F_CURRENT;
10460	feature->add_length = 0;
10461	feature = (struct scsi_get_config_feature *)
10462	    &feature->feature_data[feature->add_length];
10463
10464f1e:	/* CD Read */
10465	scsi_ulto2b(0x001E, feature->feature_code);
10466	feature->flags = 0x00;
10467	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10468		feature->flags |= SGC_F_CURRENT;
10469	feature->add_length = 4;
10470	feature->feature_data[0] = 0x00;
10471	feature = (struct scsi_get_config_feature *)
10472	    &feature->feature_data[feature->add_length];
10473
10474f1f:	/* DVD Read */
10475	scsi_ulto2b(0x001F, feature->feature_code);
10476	feature->flags = 0x08;
10477	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10478		feature->flags |= SGC_F_CURRENT;
10479	feature->add_length = 4;
10480	feature->feature_data[0] = 0x01;
10481	feature->feature_data[2] = 0x03;
10482	feature = (struct scsi_get_config_feature *)
10483	    &feature->feature_data[feature->add_length];
10484
10485f2a:	/* DVD+RW */
10486	scsi_ulto2b(0x002A, feature->feature_code);
10487	feature->flags = 0x04;
10488	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10489		feature->flags |= SGC_F_CURRENT;
10490	feature->add_length = 4;
10491	feature->feature_data[0] = 0x00;
10492	feature->feature_data[1] = 0x00;
10493	feature = (struct scsi_get_config_feature *)
10494	    &feature->feature_data[feature->add_length];
10495
10496f2b:	/* DVD+R */
10497	scsi_ulto2b(0x002B, feature->feature_code);
10498	feature->flags = 0x00;
10499	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10500		feature->flags |= SGC_F_CURRENT;
10501	feature->add_length = 4;
10502	feature->feature_data[0] = 0x00;
10503	feature = (struct scsi_get_config_feature *)
10504	    &feature->feature_data[feature->add_length];
10505
10506f3a:	/* DVD+RW Dual Layer */
10507	scsi_ulto2b(0x003A, feature->feature_code);
10508	feature->flags = 0x00;
10509	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10510		feature->flags |= SGC_F_CURRENT;
10511	feature->add_length = 4;
10512	feature->feature_data[0] = 0x00;
10513	feature->feature_data[1] = 0x00;
10514	feature = (struct scsi_get_config_feature *)
10515	    &feature->feature_data[feature->add_length];
10516
10517f3b:	/* DVD+R Dual Layer */
10518	scsi_ulto2b(0x003B, feature->feature_code);
10519	feature->flags = 0x00;
10520	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10521		feature->flags |= SGC_F_CURRENT;
10522	feature->add_length = 4;
10523	feature->feature_data[0] = 0x00;
10524	feature = (struct scsi_get_config_feature *)
10525	    &feature->feature_data[feature->add_length];
10526
10527done:
10528	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10529	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10530		feature = (struct scsi_get_config_feature *)(hdr + 1);
10531		if (scsi_2btoul(feature->feature_code) == starting)
10532			feature = (struct scsi_get_config_feature *)
10533			    &feature->feature_data[feature->add_length];
10534		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10535	}
10536	scsi_ulto4b(data_len - 4, hdr->data_length);
10537	if (data_len < alloc_len) {
10538		ctsio->residual = alloc_len - data_len;
10539		ctsio->kern_data_len = data_len;
10540		ctsio->kern_total_len = data_len;
10541	} else {
10542		ctsio->residual = 0;
10543		ctsio->kern_data_len = alloc_len;
10544		ctsio->kern_total_len = alloc_len;
10545	}
10546
10547	ctl_set_success(ctsio);
10548	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10549	ctsio->be_move_done = ctl_config_move_done;
10550	ctl_datamove((union ctl_io *)ctsio);
10551	return (CTL_RETVAL_COMPLETE);
10552}
10553
10554int
10555ctl_get_event_status(struct ctl_scsiio *ctsio)
10556{
10557	struct scsi_get_event_status_header *hdr;
10558	struct scsi_get_event_status *cdb;
10559	struct ctl_lun *lun;
10560	uint32_t alloc_len, data_len;
10561	int notif_class;
10562
10563	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10564	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10565	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10566		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10567		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10568		ctl_done((union ctl_io *)ctsio);
10569		return (CTL_RETVAL_COMPLETE);
10570	}
10571	notif_class = cdb->notif_class;
10572	alloc_len = scsi_2btoul(cdb->length);
10573
10574	data_len = sizeof(struct scsi_get_event_status_header);
10575	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10576	ctsio->kern_sg_entries = 0;
10577	ctsio->kern_data_resid = 0;
10578	ctsio->kern_rel_offset = 0;
10579
10580	if (data_len < alloc_len) {
10581		ctsio->residual = alloc_len - data_len;
10582		ctsio->kern_data_len = data_len;
10583		ctsio->kern_total_len = data_len;
10584	} else {
10585		ctsio->residual = 0;
10586		ctsio->kern_data_len = alloc_len;
10587		ctsio->kern_total_len = alloc_len;
10588	}
10589
10590	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10591	scsi_ulto2b(0, hdr->descr_length);
10592	hdr->nea_class = SGESN_NEA;
10593	hdr->supported_class = 0;
10594
10595	ctl_set_success(ctsio);
10596	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10597	ctsio->be_move_done = ctl_config_move_done;
10598	ctl_datamove((union ctl_io *)ctsio);
10599	return (CTL_RETVAL_COMPLETE);
10600}
10601
10602int
10603ctl_mechanism_status(struct ctl_scsiio *ctsio)
10604{
10605	struct scsi_mechanism_status_header *hdr;
10606	struct scsi_mechanism_status *cdb;
10607	struct ctl_lun *lun;
10608	uint32_t alloc_len, data_len;
10609
10610	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
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 scsi_read_toc_hdr *hdr;
10659	struct scsi_read_toc_type01_descr *descr;
10660	struct scsi_read_toc *cdb;
10661	struct ctl_lun *lun;
10662	uint32_t alloc_len, data_len;
10663	int format, msf;
10664
10665	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10666	cdb = (struct scsi_read_toc *)ctsio->cdb;
10667	msf = (cdb->byte2 & CD_MSF) != 0;
10668	format = cdb->format;
10669	alloc_len = scsi_2btoul(cdb->data_len);
10670
10671	data_len = sizeof(struct scsi_read_toc_hdr);
10672	if (format == 0)
10673		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10674	else
10675		data_len += sizeof(struct scsi_read_toc_type01_descr);
10676	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10677	ctsio->kern_sg_entries = 0;
10678	ctsio->kern_data_resid = 0;
10679	ctsio->kern_rel_offset = 0;
10680
10681	if (data_len < alloc_len) {
10682		ctsio->residual = alloc_len - data_len;
10683		ctsio->kern_data_len = data_len;
10684		ctsio->kern_total_len = data_len;
10685	} else {
10686		ctsio->residual = 0;
10687		ctsio->kern_data_len = alloc_len;
10688		ctsio->kern_total_len = alloc_len;
10689	}
10690
10691	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10692	if (format == 0) {
10693		scsi_ulto2b(0x12, hdr->data_length);
10694		hdr->first = 1;
10695		hdr->last = 1;
10696		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10697		descr->addr_ctl = 0x14;
10698		descr->track_number = 1;
10699		if (msf)
10700			ctl_ultomsf(0, descr->track_start);
10701		else
10702			scsi_ulto4b(0, descr->track_start);
10703		descr++;
10704		descr->addr_ctl = 0x14;
10705		descr->track_number = 0xaa;
10706		if (msf)
10707			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10708		else
10709			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10710	} else {
10711		scsi_ulto2b(0x0a, hdr->data_length);
10712		hdr->first = 1;
10713		hdr->last = 1;
10714		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10715		descr->addr_ctl = 0x14;
10716		descr->track_number = 1;
10717		if (msf)
10718			ctl_ultomsf(0, descr->track_start);
10719		else
10720			scsi_ulto4b(0, descr->track_start);
10721	}
10722
10723	ctl_set_success(ctsio);
10724	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10725	ctsio->be_move_done = ctl_config_move_done;
10726	ctl_datamove((union ctl_io *)ctsio);
10727	return (CTL_RETVAL_COMPLETE);
10728}
10729
10730/*
10731 * For known CDB types, parse the LBA and length.
10732 */
10733static int
10734ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10735{
10736	if (io->io_hdr.io_type != CTL_IO_SCSI)
10737		return (1);
10738
10739	switch (io->scsiio.cdb[0]) {
10740	case COMPARE_AND_WRITE: {
10741		struct scsi_compare_and_write *cdb;
10742
10743		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10744
10745		*lba = scsi_8btou64(cdb->addr);
10746		*len = cdb->length;
10747		break;
10748	}
10749	case READ_6:
10750	case WRITE_6: {
10751		struct scsi_rw_6 *cdb;
10752
10753		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10754
10755		*lba = scsi_3btoul(cdb->addr);
10756		/* only 5 bits are valid in the most significant address byte */
10757		*lba &= 0x1fffff;
10758		*len = cdb->length;
10759		break;
10760	}
10761	case READ_10:
10762	case WRITE_10: {
10763		struct scsi_rw_10 *cdb;
10764
10765		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10766
10767		*lba = scsi_4btoul(cdb->addr);
10768		*len = scsi_2btoul(cdb->length);
10769		break;
10770	}
10771	case WRITE_VERIFY_10: {
10772		struct scsi_write_verify_10 *cdb;
10773
10774		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10775
10776		*lba = scsi_4btoul(cdb->addr);
10777		*len = scsi_2btoul(cdb->length);
10778		break;
10779	}
10780	case READ_12:
10781	case WRITE_12: {
10782		struct scsi_rw_12 *cdb;
10783
10784		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10785
10786		*lba = scsi_4btoul(cdb->addr);
10787		*len = scsi_4btoul(cdb->length);
10788		break;
10789	}
10790	case WRITE_VERIFY_12: {
10791		struct scsi_write_verify_12 *cdb;
10792
10793		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10794
10795		*lba = scsi_4btoul(cdb->addr);
10796		*len = scsi_4btoul(cdb->length);
10797		break;
10798	}
10799	case READ_16:
10800	case WRITE_16: {
10801		struct scsi_rw_16 *cdb;
10802
10803		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10804
10805		*lba = scsi_8btou64(cdb->addr);
10806		*len = scsi_4btoul(cdb->length);
10807		break;
10808	}
10809	case WRITE_ATOMIC_16: {
10810		struct scsi_write_atomic_16 *cdb;
10811
10812		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10813
10814		*lba = scsi_8btou64(cdb->addr);
10815		*len = scsi_2btoul(cdb->length);
10816		break;
10817	}
10818	case WRITE_VERIFY_16: {
10819		struct scsi_write_verify_16 *cdb;
10820
10821		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10822
10823		*lba = scsi_8btou64(cdb->addr);
10824		*len = scsi_4btoul(cdb->length);
10825		break;
10826	}
10827	case WRITE_SAME_10: {
10828		struct scsi_write_same_10 *cdb;
10829
10830		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10831
10832		*lba = scsi_4btoul(cdb->addr);
10833		*len = scsi_2btoul(cdb->length);
10834		break;
10835	}
10836	case WRITE_SAME_16: {
10837		struct scsi_write_same_16 *cdb;
10838
10839		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10840
10841		*lba = scsi_8btou64(cdb->addr);
10842		*len = scsi_4btoul(cdb->length);
10843		break;
10844	}
10845	case VERIFY_10: {
10846		struct scsi_verify_10 *cdb;
10847
10848		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10849
10850		*lba = scsi_4btoul(cdb->addr);
10851		*len = scsi_2btoul(cdb->length);
10852		break;
10853	}
10854	case VERIFY_12: {
10855		struct scsi_verify_12 *cdb;
10856
10857		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10858
10859		*lba = scsi_4btoul(cdb->addr);
10860		*len = scsi_4btoul(cdb->length);
10861		break;
10862	}
10863	case VERIFY_16: {
10864		struct scsi_verify_16 *cdb;
10865
10866		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10867
10868		*lba = scsi_8btou64(cdb->addr);
10869		*len = scsi_4btoul(cdb->length);
10870		break;
10871	}
10872	case UNMAP: {
10873		*lba = 0;
10874		*len = UINT64_MAX;
10875		break;
10876	}
10877	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10878		struct scsi_get_lba_status *cdb;
10879
10880		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10881		*lba = scsi_8btou64(cdb->addr);
10882		*len = UINT32_MAX;
10883		break;
10884	}
10885	default:
10886		return (1);
10887		break; /* NOTREACHED */
10888	}
10889
10890	return (0);
10891}
10892
10893static ctl_action
10894ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10895    bool seq)
10896{
10897	uint64_t endlba1, endlba2;
10898
10899	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10900	endlba2 = lba2 + len2 - 1;
10901
10902	if ((endlba1 < lba2) || (endlba2 < lba1))
10903		return (CTL_ACTION_PASS);
10904	else
10905		return (CTL_ACTION_BLOCK);
10906}
10907
10908static int
10909ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10910{
10911	struct ctl_ptr_len_flags *ptrlen;
10912	struct scsi_unmap_desc *buf, *end, *range;
10913	uint64_t lba;
10914	uint32_t len;
10915
10916	/* If not UNMAP -- go other way. */
10917	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10918	    io->scsiio.cdb[0] != UNMAP)
10919		return (CTL_ACTION_ERROR);
10920
10921	/* If UNMAP without data -- block and wait for data. */
10922	ptrlen = (struct ctl_ptr_len_flags *)
10923	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10924	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10925	    ptrlen->ptr == NULL)
10926		return (CTL_ACTION_BLOCK);
10927
10928	/* UNMAP with data -- check for collision. */
10929	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10930	end = buf + ptrlen->len / sizeof(*buf);
10931	for (range = buf; range < end; range++) {
10932		lba = scsi_8btou64(range->lba);
10933		len = scsi_4btoul(range->length);
10934		if ((lba < lba2 + len2) && (lba + len > lba2))
10935			return (CTL_ACTION_BLOCK);
10936	}
10937	return (CTL_ACTION_PASS);
10938}
10939
10940static ctl_action
10941ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10942{
10943	uint64_t lba1, lba2;
10944	uint64_t len1, len2;
10945	int retval;
10946
10947	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10948		return (CTL_ACTION_ERROR);
10949
10950	retval = ctl_extent_check_unmap(io1, lba2, len2);
10951	if (retval != CTL_ACTION_ERROR)
10952		return (retval);
10953
10954	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10955		return (CTL_ACTION_ERROR);
10956
10957	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10958		seq = FALSE;
10959	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10960}
10961
10962static ctl_action
10963ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10964{
10965	uint64_t lba1, lba2;
10966	uint64_t len1, len2;
10967
10968	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10969		return (CTL_ACTION_PASS);
10970	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10971		return (CTL_ACTION_ERROR);
10972	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10973		return (CTL_ACTION_ERROR);
10974
10975	if (lba1 + len1 == lba2)
10976		return (CTL_ACTION_BLOCK);
10977	return (CTL_ACTION_PASS);
10978}
10979
10980static ctl_action
10981ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10982    union ctl_io *ooa_io)
10983{
10984	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10985	const ctl_serialize_action *serialize_row;
10986
10987	/*
10988	 * The initiator attempted multiple untagged commands at the same
10989	 * time.  Can't do that.
10990	 */
10991	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10992	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10993	 && ((pending_io->io_hdr.nexus.targ_port ==
10994	      ooa_io->io_hdr.nexus.targ_port)
10995	  && (pending_io->io_hdr.nexus.initid ==
10996	      ooa_io->io_hdr.nexus.initid))
10997	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10998	      CTL_FLAG_STATUS_SENT)) == 0))
10999		return (CTL_ACTION_OVERLAP);
11000
11001	/*
11002	 * The initiator attempted to send multiple tagged commands with
11003	 * the same ID.  (It's fine if different initiators have the same
11004	 * tag ID.)
11005	 *
11006	 * Even if all of those conditions are true, we don't kill the I/O
11007	 * if the command ahead of us has been aborted.  We won't end up
11008	 * sending it to the FETD, and it's perfectly legal to resend a
11009	 * command with the same tag number as long as the previous
11010	 * instance of this tag number has been aborted somehow.
11011	 */
11012	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11013	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11014	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11015	 && ((pending_io->io_hdr.nexus.targ_port ==
11016	      ooa_io->io_hdr.nexus.targ_port)
11017	  && (pending_io->io_hdr.nexus.initid ==
11018	      ooa_io->io_hdr.nexus.initid))
11019	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11020	      CTL_FLAG_STATUS_SENT)) == 0))
11021		return (CTL_ACTION_OVERLAP_TAG);
11022
11023	/*
11024	 * If we get a head of queue tag, SAM-3 says that we should
11025	 * immediately execute it.
11026	 *
11027	 * What happens if this command would normally block for some other
11028	 * reason?  e.g. a request sense with a head of queue tag
11029	 * immediately after a write.  Normally that would block, but this
11030	 * will result in its getting executed immediately...
11031	 *
11032	 * We currently return "pass" instead of "skip", so we'll end up
11033	 * going through the rest of the queue to check for overlapped tags.
11034	 *
11035	 * XXX KDM check for other types of blockage first??
11036	 */
11037	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11038		return (CTL_ACTION_PASS);
11039
11040	/*
11041	 * Ordered tags have to block until all items ahead of them
11042	 * have completed.  If we get called with an ordered tag, we always
11043	 * block, if something else is ahead of us in the queue.
11044	 */
11045	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11046		return (CTL_ACTION_BLOCK);
11047
11048	/*
11049	 * Simple tags get blocked until all head of queue and ordered tags
11050	 * ahead of them have completed.  I'm lumping untagged commands in
11051	 * with simple tags here.  XXX KDM is that the right thing to do?
11052	 */
11053	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11054	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11055	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11056	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11057		return (CTL_ACTION_BLOCK);
11058
11059	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11060	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11061	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11062	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11063	     pending_io->scsiio.cdb[1], pending_io));
11064	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11065	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11066		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11067	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11068	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11069	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11070	     ooa_io->scsiio.cdb[1], ooa_io));
11071
11072	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11073
11074	switch (serialize_row[pending_entry->seridx]) {
11075	case CTL_SER_BLOCK:
11076		return (CTL_ACTION_BLOCK);
11077	case CTL_SER_EXTENT:
11078		return (ctl_extent_check(ooa_io, pending_io,
11079		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11080	case CTL_SER_EXTENTOPT:
11081		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11082		    SCP_QUEUE_ALG_UNRESTRICTED)
11083			return (ctl_extent_check(ooa_io, pending_io,
11084			    (lun->be_lun &&
11085			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11086		return (CTL_ACTION_PASS);
11087	case CTL_SER_EXTENTSEQ:
11088		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11089			return (ctl_extent_check_seq(ooa_io, pending_io));
11090		return (CTL_ACTION_PASS);
11091	case CTL_SER_PASS:
11092		return (CTL_ACTION_PASS);
11093	case CTL_SER_BLOCKOPT:
11094		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11095		    SCP_QUEUE_ALG_UNRESTRICTED)
11096			return (CTL_ACTION_BLOCK);
11097		return (CTL_ACTION_PASS);
11098	case CTL_SER_SKIP:
11099		return (CTL_ACTION_SKIP);
11100	default:
11101		panic("%s: Invalid serialization value %d for %d => %d",
11102		    __func__, serialize_row[pending_entry->seridx],
11103		    pending_entry->seridx, ooa_entry->seridx);
11104	}
11105
11106	return (CTL_ACTION_ERROR);
11107}
11108
11109/*
11110 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11111 * Assumptions:
11112 * - pending_io is generally either incoming, or on the blocked queue
11113 * - starting I/O is the I/O we want to start the check with.
11114 */
11115static ctl_action
11116ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11117	      union ctl_io *starting_io)
11118{
11119	union ctl_io *ooa_io;
11120	ctl_action action;
11121
11122	mtx_assert(&lun->lun_lock, MA_OWNED);
11123
11124	/*
11125	 * Run back along the OOA queue, starting with the current
11126	 * blocked I/O and going through every I/O before it on the
11127	 * queue.  If starting_io is NULL, we'll just end up returning
11128	 * CTL_ACTION_PASS.
11129	 */
11130	for (ooa_io = starting_io; ooa_io != NULL;
11131	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11132	     ooa_links)){
11133
11134		/*
11135		 * This routine just checks to see whether
11136		 * cur_blocked is blocked by ooa_io, which is ahead
11137		 * of it in the queue.  It doesn't queue/dequeue
11138		 * cur_blocked.
11139		 */
11140		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11141		switch (action) {
11142		case CTL_ACTION_BLOCK:
11143		case CTL_ACTION_OVERLAP:
11144		case CTL_ACTION_OVERLAP_TAG:
11145		case CTL_ACTION_SKIP:
11146		case CTL_ACTION_ERROR:
11147			return (action);
11148			break; /* NOTREACHED */
11149		case CTL_ACTION_PASS:
11150			break;
11151		default:
11152			panic("%s: Invalid action %d\n", __func__, action);
11153		}
11154	}
11155
11156	return (CTL_ACTION_PASS);
11157}
11158
11159/*
11160 * Assumptions:
11161 * - An I/O has just completed, and has been removed from the per-LUN OOA
11162 *   queue, so some items on the blocked queue may now be unblocked.
11163 */
11164static int
11165ctl_check_blocked(struct ctl_lun *lun)
11166{
11167	struct ctl_softc *softc = lun->ctl_softc;
11168	union ctl_io *cur_blocked, *next_blocked;
11169
11170	mtx_assert(&lun->lun_lock, MA_OWNED);
11171
11172	/*
11173	 * Run forward from the head of the blocked queue, checking each
11174	 * entry against the I/Os prior to it on the OOA queue to see if
11175	 * there is still any blockage.
11176	 *
11177	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11178	 * with our removing a variable on it while it is traversing the
11179	 * list.
11180	 */
11181	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11182	     cur_blocked != NULL; cur_blocked = next_blocked) {
11183		union ctl_io *prev_ooa;
11184		ctl_action action;
11185
11186		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11187							  blocked_links);
11188
11189		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11190						      ctl_ooaq, ooa_links);
11191
11192		/*
11193		 * If cur_blocked happens to be the first item in the OOA
11194		 * queue now, prev_ooa will be NULL, and the action
11195		 * returned will just be CTL_ACTION_PASS.
11196		 */
11197		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11198
11199		switch (action) {
11200		case CTL_ACTION_BLOCK:
11201			/* Nothing to do here, still blocked */
11202			break;
11203		case CTL_ACTION_OVERLAP:
11204		case CTL_ACTION_OVERLAP_TAG:
11205			/*
11206			 * This shouldn't happen!  In theory we've already
11207			 * checked this command for overlap...
11208			 */
11209			break;
11210		case CTL_ACTION_PASS:
11211		case CTL_ACTION_SKIP: {
11212			const struct ctl_cmd_entry *entry;
11213
11214			/*
11215			 * The skip case shouldn't happen, this transaction
11216			 * should have never made it onto the blocked queue.
11217			 */
11218			/*
11219			 * This I/O is no longer blocked, we can remove it
11220			 * from the blocked queue.  Since this is a TAILQ
11221			 * (doubly linked list), we can do O(1) removals
11222			 * from any place on the list.
11223			 */
11224			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11225				     blocked_links);
11226			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11227
11228			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11229			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11230				/*
11231				 * Need to send IO back to original side to
11232				 * run
11233				 */
11234				union ctl_ha_msg msg_info;
11235
11236				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11237				msg_info.hdr.original_sc =
11238					cur_blocked->io_hdr.original_sc;
11239				msg_info.hdr.serializing_sc = cur_blocked;
11240				msg_info.hdr.msg_type = CTL_MSG_R2R;
11241				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11242				    sizeof(msg_info.hdr), M_NOWAIT);
11243				break;
11244			}
11245			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11246
11247			/*
11248			 * Check this I/O for LUN state changes that may
11249			 * have happened while this command was blocked.
11250			 * The LUN state may have been changed by a command
11251			 * ahead of us in the queue, so we need to re-check
11252			 * for any states that can be caused by SCSI
11253			 * commands.
11254			 */
11255			if (ctl_scsiio_lun_check(lun, entry,
11256						 &cur_blocked->scsiio) == 0) {
11257				cur_blocked->io_hdr.flags |=
11258				                      CTL_FLAG_IS_WAS_ON_RTR;
11259				ctl_enqueue_rtr(cur_blocked);
11260			} else
11261				ctl_done(cur_blocked);
11262			break;
11263		}
11264		default:
11265			/*
11266			 * This probably shouldn't happen -- we shouldn't
11267			 * get CTL_ACTION_ERROR, or anything else.
11268			 */
11269			break;
11270		}
11271	}
11272
11273	return (CTL_RETVAL_COMPLETE);
11274}
11275
11276/*
11277 * This routine (with one exception) checks LUN flags that can be set by
11278 * commands ahead of us in the OOA queue.  These flags have to be checked
11279 * when a command initially comes in, and when we pull a command off the
11280 * blocked queue and are preparing to execute it.  The reason we have to
11281 * check these flags for commands on the blocked queue is that the LUN
11282 * state may have been changed by a command ahead of us while we're on the
11283 * blocked queue.
11284 *
11285 * Ordering is somewhat important with these checks, so please pay
11286 * careful attention to the placement of any new checks.
11287 */
11288static int
11289ctl_scsiio_lun_check(struct ctl_lun *lun,
11290    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11291{
11292	struct ctl_softc *softc = lun->ctl_softc;
11293	int retval;
11294	uint32_t residx;
11295
11296	retval = 0;
11297
11298	mtx_assert(&lun->lun_lock, MA_OWNED);
11299
11300	/*
11301	 * If this shelf is a secondary shelf controller, we may have to
11302	 * reject some commands disallowed by HA mode and link state.
11303	 */
11304	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11305		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11306		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11307			ctl_set_lun_unavail(ctsio);
11308			retval = 1;
11309			goto bailout;
11310		}
11311		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11312		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11313			ctl_set_lun_transit(ctsio);
11314			retval = 1;
11315			goto bailout;
11316		}
11317		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11318		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11319			ctl_set_lun_standby(ctsio);
11320			retval = 1;
11321			goto bailout;
11322		}
11323
11324		/* The rest of checks are only done on executing side */
11325		if (softc->ha_mode == CTL_HA_MODE_XFER)
11326			goto bailout;
11327	}
11328
11329	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11330		if (lun->be_lun &&
11331		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11332			ctl_set_hw_write_protected(ctsio);
11333			retval = 1;
11334			goto bailout;
11335		}
11336		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11337			ctl_set_sense(ctsio, /*current_error*/ 1,
11338			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11339			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11340			retval = 1;
11341			goto bailout;
11342		}
11343	}
11344
11345	/*
11346	 * Check for a reservation conflict.  If this command isn't allowed
11347	 * even on reserved LUNs, and if this initiator isn't the one who
11348	 * reserved us, reject the command with a reservation conflict.
11349	 */
11350	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11351	if ((lun->flags & CTL_LUN_RESERVED)
11352	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11353		if (lun->res_idx != residx) {
11354			ctl_set_reservation_conflict(ctsio);
11355			retval = 1;
11356			goto bailout;
11357		}
11358	}
11359
11360	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11361	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11362		/* No reservation or command is allowed. */;
11363	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11364	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11365	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11366	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11367		/* The command is allowed for Write Exclusive resv. */;
11368	} else {
11369		/*
11370		 * if we aren't registered or it's a res holder type
11371		 * reservation and this isn't the res holder then set a
11372		 * conflict.
11373		 */
11374		if (ctl_get_prkey(lun, residx) == 0 ||
11375		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11376			ctl_set_reservation_conflict(ctsio);
11377			retval = 1;
11378			goto bailout;
11379		}
11380	}
11381
11382	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11383		if (lun->flags & CTL_LUN_EJECTED)
11384			ctl_set_lun_ejected(ctsio);
11385		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11386			if (lun->flags & CTL_LUN_REMOVABLE)
11387				ctl_set_lun_no_media(ctsio);
11388			else
11389				ctl_set_lun_int_reqd(ctsio);
11390		} else if (lun->flags & CTL_LUN_STOPPED)
11391			ctl_set_lun_stopped(ctsio);
11392		else
11393			goto bailout;
11394		retval = 1;
11395		goto bailout;
11396	}
11397
11398bailout:
11399	return (retval);
11400}
11401
11402static void
11403ctl_failover_io(union ctl_io *io, int have_lock)
11404{
11405	ctl_set_busy(&io->scsiio);
11406	ctl_done(io);
11407}
11408
11409static void
11410ctl_failover_lun(union ctl_io *rio)
11411{
11412	struct ctl_softc *softc = control_softc;
11413	struct ctl_lun *lun;
11414	struct ctl_io_hdr *io, *next_io;
11415	uint32_t targ_lun;
11416
11417	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11418	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11419
11420	/* Find and lock the LUN. */
11421	mtx_lock(&softc->ctl_lock);
11422	if ((targ_lun < CTL_MAX_LUNS) &&
11423	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11424		mtx_lock(&lun->lun_lock);
11425		mtx_unlock(&softc->ctl_lock);
11426		if (lun->flags & CTL_LUN_DISABLED) {
11427			mtx_unlock(&lun->lun_lock);
11428			return;
11429		}
11430	} else {
11431		mtx_unlock(&softc->ctl_lock);
11432		return;
11433	}
11434
11435	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11436		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11437			/* We are master */
11438			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11439				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11440					io->flags |= CTL_FLAG_ABORT;
11441					io->flags |= CTL_FLAG_FAILOVER;
11442				} else { /* This can be only due to DATAMOVE */
11443					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11444					io->flags &= ~CTL_FLAG_DMA_INPROG;
11445					io->flags |= CTL_FLAG_IO_ACTIVE;
11446					io->port_status = 31340;
11447					ctl_enqueue_isc((union ctl_io *)io);
11448				}
11449			}
11450			/* We are slave */
11451			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11452				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11453				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11454					io->flags |= CTL_FLAG_FAILOVER;
11455				} else {
11456					ctl_set_busy(&((union ctl_io *)io)->
11457					    scsiio);
11458					ctl_done((union ctl_io *)io);
11459				}
11460			}
11461		}
11462	} else { /* SERIALIZE modes */
11463		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11464		    next_io) {
11465			/* We are master */
11466			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11467				TAILQ_REMOVE(&lun->blocked_queue, io,
11468				    blocked_links);
11469				io->flags &= ~CTL_FLAG_BLOCKED;
11470				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11471				ctl_free_io((union ctl_io *)io);
11472			}
11473		}
11474		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11475			/* We are master */
11476			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11477				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11478				ctl_free_io((union ctl_io *)io);
11479			}
11480			/* We are slave */
11481			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11482				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11483				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11484					ctl_set_busy(&((union ctl_io *)io)->
11485					    scsiio);
11486					ctl_done((union ctl_io *)io);
11487				}
11488			}
11489		}
11490		ctl_check_blocked(lun);
11491	}
11492	mtx_unlock(&lun->lun_lock);
11493}
11494
11495static int
11496ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11497{
11498	struct ctl_lun *lun;
11499	const struct ctl_cmd_entry *entry;
11500	uint32_t initidx, targ_lun;
11501	int retval;
11502
11503	retval = 0;
11504
11505	lun = NULL;
11506
11507	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11508	if ((targ_lun < CTL_MAX_LUNS)
11509	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11510		/*
11511		 * If the LUN is invalid, pretend that it doesn't exist.
11512		 * It will go away as soon as all pending I/O has been
11513		 * completed.
11514		 */
11515		mtx_lock(&lun->lun_lock);
11516		if (lun->flags & CTL_LUN_DISABLED) {
11517			mtx_unlock(&lun->lun_lock);
11518			lun = NULL;
11519			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11520			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11521		} else {
11522			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11523			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11524				lun->be_lun;
11525
11526			/*
11527			 * Every I/O goes into the OOA queue for a
11528			 * particular LUN, and stays there until completion.
11529			 */
11530#ifdef CTL_TIME_IO
11531			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11532				lun->idle_time += getsbinuptime() -
11533				    lun->last_busy;
11534			}
11535#endif
11536			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11537			    ooa_links);
11538		}
11539	} else {
11540		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11541		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11542	}
11543
11544	/* Get command entry and return error if it is unsuppotyed. */
11545	entry = ctl_validate_command(ctsio);
11546	if (entry == NULL) {
11547		if (lun)
11548			mtx_unlock(&lun->lun_lock);
11549		return (retval);
11550	}
11551
11552	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11553	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11554
11555	/*
11556	 * Check to see whether we can send this command to LUNs that don't
11557	 * exist.  This should pretty much only be the case for inquiry
11558	 * and request sense.  Further checks, below, really require having
11559	 * a LUN, so we can't really check the command anymore.  Just put
11560	 * it on the rtr queue.
11561	 */
11562	if (lun == NULL) {
11563		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11564			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11565			ctl_enqueue_rtr((union ctl_io *)ctsio);
11566			return (retval);
11567		}
11568
11569		ctl_set_unsupported_lun(ctsio);
11570		ctl_done((union ctl_io *)ctsio);
11571		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11572		return (retval);
11573	} else {
11574		/*
11575		 * Make sure we support this particular command on this LUN.
11576		 * e.g., we don't support writes to the control LUN.
11577		 */
11578		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11579			mtx_unlock(&lun->lun_lock);
11580			ctl_set_invalid_opcode(ctsio);
11581			ctl_done((union ctl_io *)ctsio);
11582			return (retval);
11583		}
11584	}
11585
11586	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11587
11588#ifdef CTL_WITH_CA
11589	/*
11590	 * If we've got a request sense, it'll clear the contingent
11591	 * allegiance condition.  Otherwise, if we have a CA condition for
11592	 * this initiator, clear it, because it sent down a command other
11593	 * than request sense.
11594	 */
11595	if ((ctsio->cdb[0] != REQUEST_SENSE)
11596	 && (ctl_is_set(lun->have_ca, initidx)))
11597		ctl_clear_mask(lun->have_ca, initidx);
11598#endif
11599
11600	/*
11601	 * If the command has this flag set, it handles its own unit
11602	 * attention reporting, we shouldn't do anything.  Otherwise we
11603	 * check for any pending unit attentions, and send them back to the
11604	 * initiator.  We only do this when a command initially comes in,
11605	 * not when we pull it off the blocked queue.
11606	 *
11607	 * According to SAM-3, section 5.3.2, the order that things get
11608	 * presented back to the host is basically unit attentions caused
11609	 * by some sort of reset event, busy status, reservation conflicts
11610	 * or task set full, and finally any other status.
11611	 *
11612	 * One issue here is that some of the unit attentions we report
11613	 * don't fall into the "reset" category (e.g. "reported luns data
11614	 * has changed").  So reporting it here, before the reservation
11615	 * check, may be technically wrong.  I guess the only thing to do
11616	 * would be to check for and report the reset events here, and then
11617	 * check for the other unit attention types after we check for a
11618	 * reservation conflict.
11619	 *
11620	 * XXX KDM need to fix this
11621	 */
11622	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11623		ctl_ua_type ua_type;
11624
11625		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11626		    SSD_TYPE_NONE);
11627		if (ua_type != CTL_UA_NONE) {
11628			mtx_unlock(&lun->lun_lock);
11629			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11630			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11631			ctsio->sense_len = SSD_FULL_SIZE;
11632			ctl_done((union ctl_io *)ctsio);
11633			return (retval);
11634		}
11635	}
11636
11637
11638	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11639		mtx_unlock(&lun->lun_lock);
11640		ctl_done((union ctl_io *)ctsio);
11641		return (retval);
11642	}
11643
11644	/*
11645	 * XXX CHD this is where we want to send IO to other side if
11646	 * this LUN is secondary on this SC. We will need to make a copy
11647	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11648	 * the copy we send as FROM_OTHER.
11649	 * We also need to stuff the address of the original IO so we can
11650	 * find it easily. Something similar will need be done on the other
11651	 * side so when we are done we can find the copy.
11652	 */
11653	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11654	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11655	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11656		union ctl_ha_msg msg_info;
11657		int isc_retval;
11658
11659		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11660		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11661		mtx_unlock(&lun->lun_lock);
11662
11663		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11664		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11665		msg_info.hdr.serializing_sc = NULL;
11666		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11667		msg_info.scsi.tag_num = ctsio->tag_num;
11668		msg_info.scsi.tag_type = ctsio->tag_type;
11669		msg_info.scsi.cdb_len = ctsio->cdb_len;
11670		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11671
11672		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11673		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11674		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11675			ctl_set_busy(ctsio);
11676			ctl_done((union ctl_io *)ctsio);
11677			return (retval);
11678		}
11679		return (retval);
11680	}
11681
11682	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11683			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11684			      ctl_ooaq, ooa_links))) {
11685	case CTL_ACTION_BLOCK:
11686		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11687		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11688				  blocked_links);
11689		mtx_unlock(&lun->lun_lock);
11690		return (retval);
11691	case CTL_ACTION_PASS:
11692	case CTL_ACTION_SKIP:
11693		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11694		mtx_unlock(&lun->lun_lock);
11695		ctl_enqueue_rtr((union ctl_io *)ctsio);
11696		break;
11697	case CTL_ACTION_OVERLAP:
11698		mtx_unlock(&lun->lun_lock);
11699		ctl_set_overlapped_cmd(ctsio);
11700		ctl_done((union ctl_io *)ctsio);
11701		break;
11702	case CTL_ACTION_OVERLAP_TAG:
11703		mtx_unlock(&lun->lun_lock);
11704		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11705		ctl_done((union ctl_io *)ctsio);
11706		break;
11707	case CTL_ACTION_ERROR:
11708	default:
11709		mtx_unlock(&lun->lun_lock);
11710		ctl_set_internal_failure(ctsio,
11711					 /*sks_valid*/ 0,
11712					 /*retry_count*/ 0);
11713		ctl_done((union ctl_io *)ctsio);
11714		break;
11715	}
11716	return (retval);
11717}
11718
11719const struct ctl_cmd_entry *
11720ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11721{
11722	const struct ctl_cmd_entry *entry;
11723	int service_action;
11724
11725	entry = &ctl_cmd_table[ctsio->cdb[0]];
11726	if (sa)
11727		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11728	if (entry->flags & CTL_CMD_FLAG_SA5) {
11729		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11730		entry = &((const struct ctl_cmd_entry *)
11731		    entry->execute)[service_action];
11732	}
11733	return (entry);
11734}
11735
11736const struct ctl_cmd_entry *
11737ctl_validate_command(struct ctl_scsiio *ctsio)
11738{
11739	const struct ctl_cmd_entry *entry;
11740	int i, sa;
11741	uint8_t diff;
11742
11743	entry = ctl_get_cmd_entry(ctsio, &sa);
11744	if (entry->execute == NULL) {
11745		if (sa)
11746			ctl_set_invalid_field(ctsio,
11747					      /*sks_valid*/ 1,
11748					      /*command*/ 1,
11749					      /*field*/ 1,
11750					      /*bit_valid*/ 1,
11751					      /*bit*/ 4);
11752		else
11753			ctl_set_invalid_opcode(ctsio);
11754		ctl_done((union ctl_io *)ctsio);
11755		return (NULL);
11756	}
11757	KASSERT(entry->length > 0,
11758	    ("Not defined length for command 0x%02x/0x%02x",
11759	     ctsio->cdb[0], ctsio->cdb[1]));
11760	for (i = 1; i < entry->length; i++) {
11761		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11762		if (diff == 0)
11763			continue;
11764		ctl_set_invalid_field(ctsio,
11765				      /*sks_valid*/ 1,
11766				      /*command*/ 1,
11767				      /*field*/ i,
11768				      /*bit_valid*/ 1,
11769				      /*bit*/ fls(diff) - 1);
11770		ctl_done((union ctl_io *)ctsio);
11771		return (NULL);
11772	}
11773	return (entry);
11774}
11775
11776static int
11777ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11778{
11779
11780	switch (lun_type) {
11781	case T_DIRECT:
11782		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11783			return (0);
11784		break;
11785	case T_PROCESSOR:
11786		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11787			return (0);
11788		break;
11789	case T_CDROM:
11790		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11791			return (0);
11792		break;
11793	default:
11794		return (0);
11795	}
11796	return (1);
11797}
11798
11799static int
11800ctl_scsiio(struct ctl_scsiio *ctsio)
11801{
11802	int retval;
11803	const struct ctl_cmd_entry *entry;
11804
11805	retval = CTL_RETVAL_COMPLETE;
11806
11807	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11808
11809	entry = ctl_get_cmd_entry(ctsio, NULL);
11810
11811	/*
11812	 * If this I/O has been aborted, just send it straight to
11813	 * ctl_done() without executing it.
11814	 */
11815	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11816		ctl_done((union ctl_io *)ctsio);
11817		goto bailout;
11818	}
11819
11820	/*
11821	 * All the checks should have been handled by ctl_scsiio_precheck().
11822	 * We should be clear now to just execute the I/O.
11823	 */
11824	retval = entry->execute(ctsio);
11825
11826bailout:
11827	return (retval);
11828}
11829
11830/*
11831 * Since we only implement one target right now, a bus reset simply resets
11832 * our single target.
11833 */
11834static int
11835ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11836{
11837	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11838}
11839
11840static int
11841ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11842		 ctl_ua_type ua_type)
11843{
11844	struct ctl_port *port;
11845	struct ctl_lun *lun;
11846	int retval;
11847
11848	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11849		union ctl_ha_msg msg_info;
11850
11851		msg_info.hdr.nexus = io->io_hdr.nexus;
11852		if (ua_type==CTL_UA_TARG_RESET)
11853			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11854		else
11855			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11856		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11857		msg_info.hdr.original_sc = NULL;
11858		msg_info.hdr.serializing_sc = NULL;
11859		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11860		    sizeof(msg_info.task), M_WAITOK);
11861	}
11862	retval = 0;
11863
11864	mtx_lock(&softc->ctl_lock);
11865	port = ctl_io_port(&io->io_hdr);
11866	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11867		if (port != NULL &&
11868		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11869			continue;
11870		retval += ctl_do_lun_reset(lun, io, ua_type);
11871	}
11872	mtx_unlock(&softc->ctl_lock);
11873	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11874	return (retval);
11875}
11876
11877/*
11878 * The LUN should always be set.  The I/O is optional, and is used to
11879 * distinguish between I/Os sent by this initiator, and by other
11880 * initiators.  We set unit attention for initiators other than this one.
11881 * SAM-3 is vague on this point.  It does say that a unit attention should
11882 * be established for other initiators when a LUN is reset (see section
11883 * 5.7.3), but it doesn't specifically say that the unit attention should
11884 * be established for this particular initiator when a LUN is reset.  Here
11885 * is the relevant text, from SAM-3 rev 8:
11886 *
11887 * 5.7.2 When a SCSI initiator port aborts its own tasks
11888 *
11889 * When a SCSI initiator port causes its own task(s) to be aborted, no
11890 * notification that the task(s) have been aborted shall be returned to
11891 * the SCSI initiator port other than the completion response for the
11892 * command or task management function action that caused the task(s) to
11893 * be aborted and notification(s) associated with related effects of the
11894 * action (e.g., a reset unit attention condition).
11895 *
11896 * XXX KDM for now, we're setting unit attention for all initiators.
11897 */
11898static int
11899ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11900{
11901	union ctl_io *xio;
11902#if 0
11903	uint32_t initidx;
11904#endif
11905	int i;
11906
11907	mtx_lock(&lun->lun_lock);
11908	/*
11909	 * Run through the OOA queue and abort each I/O.
11910	 */
11911	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11912	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11913		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11914	}
11915
11916	/*
11917	 * This version sets unit attention for every
11918	 */
11919#if 0
11920	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11921	ctl_est_ua_all(lun, initidx, ua_type);
11922#else
11923	ctl_est_ua_all(lun, -1, ua_type);
11924#endif
11925
11926	/*
11927	 * A reset (any kind, really) clears reservations established with
11928	 * RESERVE/RELEASE.  It does not clear reservations established
11929	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11930	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11931	 * reservations made with the RESERVE/RELEASE commands, because
11932	 * those commands are obsolete in SPC-3.
11933	 */
11934	lun->flags &= ~CTL_LUN_RESERVED;
11935
11936#ifdef CTL_WITH_CA
11937	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11938		ctl_clear_mask(lun->have_ca, i);
11939#endif
11940	lun->prevent_count = 0;
11941	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11942		ctl_clear_mask(lun->prevent, i);
11943	mtx_unlock(&lun->lun_lock);
11944
11945	return (0);
11946}
11947
11948static int
11949ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11950{
11951	struct ctl_lun *lun;
11952	uint32_t targ_lun;
11953	int retval;
11954
11955	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11956	mtx_lock(&softc->ctl_lock);
11957	if ((targ_lun >= CTL_MAX_LUNS) ||
11958	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11959		mtx_unlock(&softc->ctl_lock);
11960		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11961		return (1);
11962	}
11963	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11964	mtx_unlock(&softc->ctl_lock);
11965	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11966
11967	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11968		union ctl_ha_msg msg_info;
11969
11970		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11971		msg_info.hdr.nexus = io->io_hdr.nexus;
11972		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11973		msg_info.hdr.original_sc = NULL;
11974		msg_info.hdr.serializing_sc = NULL;
11975		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11976		    sizeof(msg_info.task), M_WAITOK);
11977	}
11978	return (retval);
11979}
11980
11981static void
11982ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11983    int other_sc)
11984{
11985	union ctl_io *xio;
11986
11987	mtx_assert(&lun->lun_lock, MA_OWNED);
11988
11989	/*
11990	 * Run through the OOA queue and attempt to find the given I/O.
11991	 * The target port, initiator ID, tag type and tag number have to
11992	 * match the values that we got from the initiator.  If we have an
11993	 * untagged command to abort, simply abort the first untagged command
11994	 * we come to.  We only allow one untagged command at a time of course.
11995	 */
11996	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11997	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11998
11999		if ((targ_port == UINT32_MAX ||
12000		     targ_port == xio->io_hdr.nexus.targ_port) &&
12001		    (init_id == UINT32_MAX ||
12002		     init_id == xio->io_hdr.nexus.initid)) {
12003			if (targ_port != xio->io_hdr.nexus.targ_port ||
12004			    init_id != xio->io_hdr.nexus.initid)
12005				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12006			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12007			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12008				union ctl_ha_msg msg_info;
12009
12010				msg_info.hdr.nexus = xio->io_hdr.nexus;
12011				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12012				msg_info.task.tag_num = xio->scsiio.tag_num;
12013				msg_info.task.tag_type = xio->scsiio.tag_type;
12014				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12015				msg_info.hdr.original_sc = NULL;
12016				msg_info.hdr.serializing_sc = NULL;
12017				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12018				    sizeof(msg_info.task), M_NOWAIT);
12019			}
12020		}
12021	}
12022}
12023
12024static int
12025ctl_abort_task_set(union ctl_io *io)
12026{
12027	struct ctl_softc *softc = control_softc;
12028	struct ctl_lun *lun;
12029	uint32_t targ_lun;
12030
12031	/*
12032	 * Look up the LUN.
12033	 */
12034	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12035	mtx_lock(&softc->ctl_lock);
12036	if ((targ_lun >= CTL_MAX_LUNS) ||
12037	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12038		mtx_unlock(&softc->ctl_lock);
12039		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12040		return (1);
12041	}
12042
12043	mtx_lock(&lun->lun_lock);
12044	mtx_unlock(&softc->ctl_lock);
12045	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12046		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12047		    io->io_hdr.nexus.initid,
12048		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12049	} else { /* CTL_TASK_CLEAR_TASK_SET */
12050		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12051		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12052	}
12053	mtx_unlock(&lun->lun_lock);
12054	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12055	return (0);
12056}
12057
12058static int
12059ctl_i_t_nexus_reset(union ctl_io *io)
12060{
12061	struct ctl_softc *softc = control_softc;
12062	struct ctl_lun *lun;
12063	uint32_t initidx;
12064
12065	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12066		union ctl_ha_msg msg_info;
12067
12068		msg_info.hdr.nexus = io->io_hdr.nexus;
12069		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12070		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12071		msg_info.hdr.original_sc = NULL;
12072		msg_info.hdr.serializing_sc = NULL;
12073		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12074		    sizeof(msg_info.task), M_WAITOK);
12075	}
12076
12077	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12078	mtx_lock(&softc->ctl_lock);
12079	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12080		mtx_lock(&lun->lun_lock);
12081		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12082		    io->io_hdr.nexus.initid, 1);
12083#ifdef CTL_WITH_CA
12084		ctl_clear_mask(lun->have_ca, initidx);
12085#endif
12086		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12087			lun->flags &= ~CTL_LUN_RESERVED;
12088		if (ctl_is_set(lun->prevent, initidx)) {
12089			ctl_clear_mask(lun->prevent, initidx);
12090			lun->prevent_count--;
12091		}
12092		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12093		mtx_unlock(&lun->lun_lock);
12094	}
12095	mtx_unlock(&softc->ctl_lock);
12096	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12097	return (0);
12098}
12099
12100static int
12101ctl_abort_task(union ctl_io *io)
12102{
12103	union ctl_io *xio;
12104	struct ctl_lun *lun;
12105	struct ctl_softc *softc;
12106#if 0
12107	struct sbuf sb;
12108	char printbuf[128];
12109#endif
12110	int found;
12111	uint32_t targ_lun;
12112
12113	softc = control_softc;
12114	found = 0;
12115
12116	/*
12117	 * Look up the LUN.
12118	 */
12119	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12120	mtx_lock(&softc->ctl_lock);
12121	if ((targ_lun >= CTL_MAX_LUNS) ||
12122	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12123		mtx_unlock(&softc->ctl_lock);
12124		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12125		return (1);
12126	}
12127
12128#if 0
12129	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12130	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12131#endif
12132
12133	mtx_lock(&lun->lun_lock);
12134	mtx_unlock(&softc->ctl_lock);
12135	/*
12136	 * Run through the OOA queue and attempt to find the given I/O.
12137	 * The target port, initiator ID, tag type and tag number have to
12138	 * match the values that we got from the initiator.  If we have an
12139	 * untagged command to abort, simply abort the first untagged command
12140	 * we come to.  We only allow one untagged command at a time of course.
12141	 */
12142	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12143	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12144#if 0
12145		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12146
12147		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12148			    lun->lun, xio->scsiio.tag_num,
12149			    xio->scsiio.tag_type,
12150			    (xio->io_hdr.blocked_links.tqe_prev
12151			    == NULL) ? "" : " BLOCKED",
12152			    (xio->io_hdr.flags &
12153			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12154			    (xio->io_hdr.flags &
12155			    CTL_FLAG_ABORT) ? " ABORT" : "",
12156			    (xio->io_hdr.flags &
12157			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12158		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12159		sbuf_finish(&sb);
12160		printf("%s\n", sbuf_data(&sb));
12161#endif
12162
12163		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12164		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12165		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12166			continue;
12167
12168		/*
12169		 * If the abort says that the task is untagged, the
12170		 * task in the queue must be untagged.  Otherwise,
12171		 * we just check to see whether the tag numbers
12172		 * match.  This is because the QLogic firmware
12173		 * doesn't pass back the tag type in an abort
12174		 * request.
12175		 */
12176#if 0
12177		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12178		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12179		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12180#endif
12181		/*
12182		 * XXX KDM we've got problems with FC, because it
12183		 * doesn't send down a tag type with aborts.  So we
12184		 * can only really go by the tag number...
12185		 * This may cause problems with parallel SCSI.
12186		 * Need to figure that out!!
12187		 */
12188		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12189			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12190			found = 1;
12191			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12192			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12193				union ctl_ha_msg msg_info;
12194
12195				msg_info.hdr.nexus = io->io_hdr.nexus;
12196				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12197				msg_info.task.tag_num = io->taskio.tag_num;
12198				msg_info.task.tag_type = io->taskio.tag_type;
12199				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12200				msg_info.hdr.original_sc = NULL;
12201				msg_info.hdr.serializing_sc = NULL;
12202#if 0
12203				printf("Sent Abort to other side\n");
12204#endif
12205				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12206				    sizeof(msg_info.task), M_NOWAIT);
12207			}
12208#if 0
12209			printf("ctl_abort_task: found I/O to abort\n");
12210#endif
12211		}
12212	}
12213	mtx_unlock(&lun->lun_lock);
12214
12215	if (found == 0) {
12216		/*
12217		 * This isn't really an error.  It's entirely possible for
12218		 * the abort and command completion to cross on the wire.
12219		 * This is more of an informative/diagnostic error.
12220		 */
12221#if 0
12222		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12223		       "%u:%u:%u tag %d type %d\n",
12224		       io->io_hdr.nexus.initid,
12225		       io->io_hdr.nexus.targ_port,
12226		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12227		       io->taskio.tag_type);
12228#endif
12229	}
12230	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12231	return (0);
12232}
12233
12234static int
12235ctl_query_task(union ctl_io *io, int task_set)
12236{
12237	union ctl_io *xio;
12238	struct ctl_lun *lun;
12239	struct ctl_softc *softc;
12240	int found = 0;
12241	uint32_t targ_lun;
12242
12243	softc = control_softc;
12244	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12245	mtx_lock(&softc->ctl_lock);
12246	if ((targ_lun >= CTL_MAX_LUNS) ||
12247	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12248		mtx_unlock(&softc->ctl_lock);
12249		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12250		return (1);
12251	}
12252	mtx_lock(&lun->lun_lock);
12253	mtx_unlock(&softc->ctl_lock);
12254	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12255	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12256
12257		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12258		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12259		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12260			continue;
12261
12262		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12263			found = 1;
12264			break;
12265		}
12266	}
12267	mtx_unlock(&lun->lun_lock);
12268	if (found)
12269		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12270	else
12271		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12272	return (0);
12273}
12274
12275static int
12276ctl_query_async_event(union ctl_io *io)
12277{
12278	struct ctl_lun *lun;
12279	struct ctl_softc *softc;
12280	ctl_ua_type ua;
12281	uint32_t targ_lun, initidx;
12282
12283	softc = control_softc;
12284	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12285	mtx_lock(&softc->ctl_lock);
12286	if ((targ_lun >= CTL_MAX_LUNS) ||
12287	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12288		mtx_unlock(&softc->ctl_lock);
12289		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12290		return (1);
12291	}
12292	mtx_lock(&lun->lun_lock);
12293	mtx_unlock(&softc->ctl_lock);
12294	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12295	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12296	mtx_unlock(&lun->lun_lock);
12297	if (ua != CTL_UA_NONE)
12298		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12299	else
12300		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12301	return (0);
12302}
12303
12304static void
12305ctl_run_task(union ctl_io *io)
12306{
12307	struct ctl_softc *softc = control_softc;
12308	int retval = 1;
12309
12310	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12311	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12312	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12313	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12314	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12315	switch (io->taskio.task_action) {
12316	case CTL_TASK_ABORT_TASK:
12317		retval = ctl_abort_task(io);
12318		break;
12319	case CTL_TASK_ABORT_TASK_SET:
12320	case CTL_TASK_CLEAR_TASK_SET:
12321		retval = ctl_abort_task_set(io);
12322		break;
12323	case CTL_TASK_CLEAR_ACA:
12324		break;
12325	case CTL_TASK_I_T_NEXUS_RESET:
12326		retval = ctl_i_t_nexus_reset(io);
12327		break;
12328	case CTL_TASK_LUN_RESET:
12329		retval = ctl_lun_reset(softc, io);
12330		break;
12331	case CTL_TASK_TARGET_RESET:
12332		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12333		break;
12334	case CTL_TASK_BUS_RESET:
12335		retval = ctl_bus_reset(softc, io);
12336		break;
12337	case CTL_TASK_PORT_LOGIN:
12338		break;
12339	case CTL_TASK_PORT_LOGOUT:
12340		break;
12341	case CTL_TASK_QUERY_TASK:
12342		retval = ctl_query_task(io, 0);
12343		break;
12344	case CTL_TASK_QUERY_TASK_SET:
12345		retval = ctl_query_task(io, 1);
12346		break;
12347	case CTL_TASK_QUERY_ASYNC_EVENT:
12348		retval = ctl_query_async_event(io);
12349		break;
12350	default:
12351		printf("%s: got unknown task management event %d\n",
12352		       __func__, io->taskio.task_action);
12353		break;
12354	}
12355	if (retval == 0)
12356		io->io_hdr.status = CTL_SUCCESS;
12357	else
12358		io->io_hdr.status = CTL_ERROR;
12359	ctl_done(io);
12360}
12361
12362/*
12363 * For HA operation.  Handle commands that come in from the other
12364 * controller.
12365 */
12366static void
12367ctl_handle_isc(union ctl_io *io)
12368{
12369	int free_io;
12370	struct ctl_lun *lun;
12371	struct ctl_softc *softc = control_softc;
12372	uint32_t targ_lun;
12373
12374	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12375	lun = softc->ctl_luns[targ_lun];
12376
12377	switch (io->io_hdr.msg_type) {
12378	case CTL_MSG_SERIALIZE:
12379		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12380		break;
12381	case CTL_MSG_R2R: {
12382		const struct ctl_cmd_entry *entry;
12383
12384		/*
12385		 * This is only used in SER_ONLY mode.
12386		 */
12387		free_io = 0;
12388		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12389		mtx_lock(&lun->lun_lock);
12390		if (ctl_scsiio_lun_check(lun,
12391		    entry, (struct ctl_scsiio *)io) != 0) {
12392			mtx_unlock(&lun->lun_lock);
12393			ctl_done(io);
12394			break;
12395		}
12396		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12397		mtx_unlock(&lun->lun_lock);
12398		ctl_enqueue_rtr(io);
12399		break;
12400	}
12401	case CTL_MSG_FINISH_IO:
12402		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12403			free_io = 0;
12404			ctl_done(io);
12405		} else {
12406			free_io = 1;
12407			mtx_lock(&lun->lun_lock);
12408			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12409				     ooa_links);
12410			ctl_check_blocked(lun);
12411			mtx_unlock(&lun->lun_lock);
12412		}
12413		break;
12414	case CTL_MSG_PERS_ACTION:
12415		ctl_hndl_per_res_out_on_other_sc(
12416			(union ctl_ha_msg *)&io->presio.pr_msg);
12417		free_io = 1;
12418		break;
12419	case CTL_MSG_BAD_JUJU:
12420		free_io = 0;
12421		ctl_done(io);
12422		break;
12423	case CTL_MSG_DATAMOVE:
12424		/* Only used in XFER mode */
12425		free_io = 0;
12426		ctl_datamove_remote(io);
12427		break;
12428	case CTL_MSG_DATAMOVE_DONE:
12429		/* Only used in XFER mode */
12430		free_io = 0;
12431		io->scsiio.be_move_done(io);
12432		break;
12433	case CTL_MSG_FAILOVER:
12434		ctl_failover_lun(io);
12435		free_io = 1;
12436		break;
12437	default:
12438		free_io = 1;
12439		printf("%s: Invalid message type %d\n",
12440		       __func__, io->io_hdr.msg_type);
12441		break;
12442	}
12443	if (free_io)
12444		ctl_free_io(io);
12445
12446}
12447
12448
12449/*
12450 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12451 * there is no match.
12452 */
12453static ctl_lun_error_pattern
12454ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12455{
12456	const struct ctl_cmd_entry *entry;
12457	ctl_lun_error_pattern filtered_pattern, pattern;
12458
12459	pattern = desc->error_pattern;
12460
12461	/*
12462	 * XXX KDM we need more data passed into this function to match a
12463	 * custom pattern, and we actually need to implement custom pattern
12464	 * matching.
12465	 */
12466	if (pattern & CTL_LUN_PAT_CMD)
12467		return (CTL_LUN_PAT_CMD);
12468
12469	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12470		return (CTL_LUN_PAT_ANY);
12471
12472	entry = ctl_get_cmd_entry(ctsio, NULL);
12473
12474	filtered_pattern = entry->pattern & pattern;
12475
12476	/*
12477	 * If the user requested specific flags in the pattern (e.g.
12478	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12479	 * flags.
12480	 *
12481	 * If the user did not specify any flags, it doesn't matter whether
12482	 * or not the command supports the flags.
12483	 */
12484	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12485	     (pattern & ~CTL_LUN_PAT_MASK))
12486		return (CTL_LUN_PAT_NONE);
12487
12488	/*
12489	 * If the user asked for a range check, see if the requested LBA
12490	 * range overlaps with this command's LBA range.
12491	 */
12492	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12493		uint64_t lba1;
12494		uint64_t len1;
12495		ctl_action action;
12496		int retval;
12497
12498		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12499		if (retval != 0)
12500			return (CTL_LUN_PAT_NONE);
12501
12502		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12503					      desc->lba_range.len, FALSE);
12504		/*
12505		 * A "pass" means that the LBA ranges don't overlap, so
12506		 * this doesn't match the user's range criteria.
12507		 */
12508		if (action == CTL_ACTION_PASS)
12509			return (CTL_LUN_PAT_NONE);
12510	}
12511
12512	return (filtered_pattern);
12513}
12514
12515static void
12516ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12517{
12518	struct ctl_error_desc *desc, *desc2;
12519
12520	mtx_assert(&lun->lun_lock, MA_OWNED);
12521
12522	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12523		ctl_lun_error_pattern pattern;
12524		/*
12525		 * Check to see whether this particular command matches
12526		 * the pattern in the descriptor.
12527		 */
12528		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12529		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12530			continue;
12531
12532		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12533		case CTL_LUN_INJ_ABORTED:
12534			ctl_set_aborted(&io->scsiio);
12535			break;
12536		case CTL_LUN_INJ_MEDIUM_ERR:
12537			ctl_set_medium_error(&io->scsiio,
12538			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12539			     CTL_FLAG_DATA_OUT);
12540			break;
12541		case CTL_LUN_INJ_UA:
12542			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12543			 * OCCURRED */
12544			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12545			break;
12546		case CTL_LUN_INJ_CUSTOM:
12547			/*
12548			 * We're assuming the user knows what he is doing.
12549			 * Just copy the sense information without doing
12550			 * checks.
12551			 */
12552			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12553			      MIN(sizeof(desc->custom_sense),
12554				  sizeof(io->scsiio.sense_data)));
12555			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12556			io->scsiio.sense_len = SSD_FULL_SIZE;
12557			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12558			break;
12559		case CTL_LUN_INJ_NONE:
12560		default:
12561			/*
12562			 * If this is an error injection type we don't know
12563			 * about, clear the continuous flag (if it is set)
12564			 * so it will get deleted below.
12565			 */
12566			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12567			break;
12568		}
12569		/*
12570		 * By default, each error injection action is a one-shot
12571		 */
12572		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12573			continue;
12574
12575		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12576
12577		free(desc, M_CTL);
12578	}
12579}
12580
12581#ifdef CTL_IO_DELAY
12582static void
12583ctl_datamove_timer_wakeup(void *arg)
12584{
12585	union ctl_io *io;
12586
12587	io = (union ctl_io *)arg;
12588
12589	ctl_datamove(io);
12590}
12591#endif /* CTL_IO_DELAY */
12592
12593void
12594ctl_datamove(union ctl_io *io)
12595{
12596	struct ctl_lun *lun;
12597	void (*fe_datamove)(union ctl_io *io);
12598
12599	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12600
12601	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12602
12603	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12604#ifdef CTL_TIME_IO
12605	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12606		char str[256];
12607		char path_str[64];
12608		struct sbuf sb;
12609
12610		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12611		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12612
12613		sbuf_cat(&sb, path_str);
12614		switch (io->io_hdr.io_type) {
12615		case CTL_IO_SCSI:
12616			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12617			sbuf_printf(&sb, "\n");
12618			sbuf_cat(&sb, path_str);
12619			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12620				    io->scsiio.tag_num, io->scsiio.tag_type);
12621			break;
12622		case CTL_IO_TASK:
12623			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12624				    "Tag Type: %d\n", io->taskio.task_action,
12625				    io->taskio.tag_num, io->taskio.tag_type);
12626			break;
12627		default:
12628			panic("%s: Invalid CTL I/O type %d\n",
12629			    __func__, io->io_hdr.io_type);
12630		}
12631		sbuf_cat(&sb, path_str);
12632		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12633			    (intmax_t)time_uptime - io->io_hdr.start_time);
12634		sbuf_finish(&sb);
12635		printf("%s", sbuf_data(&sb));
12636	}
12637#endif /* CTL_TIME_IO */
12638
12639#ifdef CTL_IO_DELAY
12640	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12641		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12642	} else {
12643		if ((lun != NULL)
12644		 && (lun->delay_info.datamove_delay > 0)) {
12645
12646			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12647			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12648			callout_reset(&io->io_hdr.delay_callout,
12649				      lun->delay_info.datamove_delay * hz,
12650				      ctl_datamove_timer_wakeup, io);
12651			if (lun->delay_info.datamove_type ==
12652			    CTL_DELAY_TYPE_ONESHOT)
12653				lun->delay_info.datamove_delay = 0;
12654			return;
12655		}
12656	}
12657#endif
12658
12659	/*
12660	 * This command has been aborted.  Set the port status, so we fail
12661	 * the data move.
12662	 */
12663	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12664		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12665		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12666		       io->io_hdr.nexus.targ_port,
12667		       io->io_hdr.nexus.targ_lun);
12668		io->io_hdr.port_status = 31337;
12669		/*
12670		 * Note that the backend, in this case, will get the
12671		 * callback in its context.  In other cases it may get
12672		 * called in the frontend's interrupt thread context.
12673		 */
12674		io->scsiio.be_move_done(io);
12675		return;
12676	}
12677
12678	/* Don't confuse frontend with zero length data move. */
12679	if (io->scsiio.kern_data_len == 0) {
12680		io->scsiio.be_move_done(io);
12681		return;
12682	}
12683
12684	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12685	fe_datamove(io);
12686}
12687
12688static void
12689ctl_send_datamove_done(union ctl_io *io, int have_lock)
12690{
12691	union ctl_ha_msg msg;
12692#ifdef CTL_TIME_IO
12693	struct bintime cur_bt;
12694#endif
12695
12696	memset(&msg, 0, sizeof(msg));
12697	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12698	msg.hdr.original_sc = io;
12699	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12700	msg.hdr.nexus = io->io_hdr.nexus;
12701	msg.hdr.status = io->io_hdr.status;
12702	msg.scsi.tag_num = io->scsiio.tag_num;
12703	msg.scsi.tag_type = io->scsiio.tag_type;
12704	msg.scsi.scsi_status = io->scsiio.scsi_status;
12705	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12706	       io->scsiio.sense_len);
12707	msg.scsi.sense_len = io->scsiio.sense_len;
12708	msg.scsi.sense_residual = io->scsiio.sense_residual;
12709	msg.scsi.fetd_status = io->io_hdr.port_status;
12710	msg.scsi.residual = io->scsiio.residual;
12711	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12712	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12713		ctl_failover_io(io, /*have_lock*/ have_lock);
12714		return;
12715	}
12716	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12717	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12718	    msg.scsi.sense_len, M_WAITOK);
12719
12720#ifdef CTL_TIME_IO
12721	getbinuptime(&cur_bt);
12722	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12723	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12724#endif
12725	io->io_hdr.num_dmas++;
12726}
12727
12728/*
12729 * The DMA to the remote side is done, now we need to tell the other side
12730 * we're done so it can continue with its data movement.
12731 */
12732static void
12733ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12734{
12735	union ctl_io *io;
12736	uint32_t i;
12737
12738	io = rq->context;
12739
12740	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12741		printf("%s: ISC DMA write failed with error %d", __func__,
12742		       rq->ret);
12743		ctl_set_internal_failure(&io->scsiio,
12744					 /*sks_valid*/ 1,
12745					 /*retry_count*/ rq->ret);
12746	}
12747
12748	ctl_dt_req_free(rq);
12749
12750	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12751		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12752	free(io->io_hdr.remote_sglist, M_CTL);
12753	io->io_hdr.remote_sglist = NULL;
12754	io->io_hdr.local_sglist = NULL;
12755
12756	/*
12757	 * The data is in local and remote memory, so now we need to send
12758	 * status (good or back) back to the other side.
12759	 */
12760	ctl_send_datamove_done(io, /*have_lock*/ 0);
12761}
12762
12763/*
12764 * We've moved the data from the host/controller into local memory.  Now we
12765 * need to push it over to the remote controller's memory.
12766 */
12767static int
12768ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12769{
12770	int retval;
12771
12772	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12773					  ctl_datamove_remote_write_cb);
12774	return (retval);
12775}
12776
12777static void
12778ctl_datamove_remote_write(union ctl_io *io)
12779{
12780	int retval;
12781	void (*fe_datamove)(union ctl_io *io);
12782
12783	/*
12784	 * - Get the data from the host/HBA into local memory.
12785	 * - DMA memory from the local controller to the remote controller.
12786	 * - Send status back to the remote controller.
12787	 */
12788
12789	retval = ctl_datamove_remote_sgl_setup(io);
12790	if (retval != 0)
12791		return;
12792
12793	/* Switch the pointer over so the FETD knows what to do */
12794	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12795
12796	/*
12797	 * Use a custom move done callback, since we need to send completion
12798	 * back to the other controller, not to the backend on this side.
12799	 */
12800	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12801
12802	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12803	fe_datamove(io);
12804}
12805
12806static int
12807ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12808{
12809#if 0
12810	char str[256];
12811	char path_str[64];
12812	struct sbuf sb;
12813#endif
12814	uint32_t i;
12815
12816	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12817		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12818	free(io->io_hdr.remote_sglist, M_CTL);
12819	io->io_hdr.remote_sglist = NULL;
12820	io->io_hdr.local_sglist = NULL;
12821
12822#if 0
12823	scsi_path_string(io, path_str, sizeof(path_str));
12824	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12825	sbuf_cat(&sb, path_str);
12826	scsi_command_string(&io->scsiio, NULL, &sb);
12827	sbuf_printf(&sb, "\n");
12828	sbuf_cat(&sb, path_str);
12829	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12830		    io->scsiio.tag_num, io->scsiio.tag_type);
12831	sbuf_cat(&sb, path_str);
12832	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12833		    io->io_hdr.flags, io->io_hdr.status);
12834	sbuf_finish(&sb);
12835	printk("%s", sbuf_data(&sb));
12836#endif
12837
12838
12839	/*
12840	 * The read is done, now we need to send status (good or bad) back
12841	 * to the other side.
12842	 */
12843	ctl_send_datamove_done(io, /*have_lock*/ 0);
12844
12845	return (0);
12846}
12847
12848static void
12849ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12850{
12851	union ctl_io *io;
12852	void (*fe_datamove)(union ctl_io *io);
12853
12854	io = rq->context;
12855
12856	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12857		printf("%s: ISC DMA read failed with error %d\n", __func__,
12858		       rq->ret);
12859		ctl_set_internal_failure(&io->scsiio,
12860					 /*sks_valid*/ 1,
12861					 /*retry_count*/ rq->ret);
12862	}
12863
12864	ctl_dt_req_free(rq);
12865
12866	/* Switch the pointer over so the FETD knows what to do */
12867	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12868
12869	/*
12870	 * Use a custom move done callback, since we need to send completion
12871	 * back to the other controller, not to the backend on this side.
12872	 */
12873	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12874
12875	/* XXX KDM add checks like the ones in ctl_datamove? */
12876
12877	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12878	fe_datamove(io);
12879}
12880
12881static int
12882ctl_datamove_remote_sgl_setup(union ctl_io *io)
12883{
12884	struct ctl_sg_entry *local_sglist;
12885	uint32_t len_to_go;
12886	int retval;
12887	int i;
12888
12889	retval = 0;
12890	local_sglist = io->io_hdr.local_sglist;
12891	len_to_go = io->scsiio.kern_data_len;
12892
12893	/*
12894	 * The difficult thing here is that the size of the various
12895	 * S/G segments may be different than the size from the
12896	 * remote controller.  That'll make it harder when DMAing
12897	 * the data back to the other side.
12898	 */
12899	for (i = 0; len_to_go > 0; i++) {
12900		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12901		local_sglist[i].addr =
12902		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12903
12904		len_to_go -= local_sglist[i].len;
12905	}
12906	/*
12907	 * Reset the number of S/G entries accordingly.  The original
12908	 * number of S/G entries is available in rem_sg_entries.
12909	 */
12910	io->scsiio.kern_sg_entries = i;
12911
12912#if 0
12913	printf("%s: kern_sg_entries = %d\n", __func__,
12914	       io->scsiio.kern_sg_entries);
12915	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12916		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12917		       local_sglist[i].addr, local_sglist[i].len);
12918#endif
12919
12920	return (retval);
12921}
12922
12923static int
12924ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12925			 ctl_ha_dt_cb callback)
12926{
12927	struct ctl_ha_dt_req *rq;
12928	struct ctl_sg_entry *remote_sglist, *local_sglist;
12929	uint32_t local_used, remote_used, total_used;
12930	int i, j, isc_ret;
12931
12932	rq = ctl_dt_req_alloc();
12933
12934	/*
12935	 * If we failed to allocate the request, and if the DMA didn't fail
12936	 * anyway, set busy status.  This is just a resource allocation
12937	 * failure.
12938	 */
12939	if ((rq == NULL)
12940	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12941	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12942		ctl_set_busy(&io->scsiio);
12943
12944	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12945	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12946
12947		if (rq != NULL)
12948			ctl_dt_req_free(rq);
12949
12950		/*
12951		 * The data move failed.  We need to return status back
12952		 * to the other controller.  No point in trying to DMA
12953		 * data to the remote controller.
12954		 */
12955
12956		ctl_send_datamove_done(io, /*have_lock*/ 0);
12957
12958		return (1);
12959	}
12960
12961	local_sglist = io->io_hdr.local_sglist;
12962	remote_sglist = io->io_hdr.remote_sglist;
12963	local_used = 0;
12964	remote_used = 0;
12965	total_used = 0;
12966
12967	/*
12968	 * Pull/push the data over the wire from/to the other controller.
12969	 * This takes into account the possibility that the local and
12970	 * remote sglists may not be identical in terms of the size of
12971	 * the elements and the number of elements.
12972	 *
12973	 * One fundamental assumption here is that the length allocated for
12974	 * both the local and remote sglists is identical.  Otherwise, we've
12975	 * essentially got a coding error of some sort.
12976	 */
12977	isc_ret = CTL_HA_STATUS_SUCCESS;
12978	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12979		uint32_t cur_len;
12980		uint8_t *tmp_ptr;
12981
12982		rq->command = command;
12983		rq->context = io;
12984
12985		/*
12986		 * Both pointers should be aligned.  But it is possible
12987		 * that the allocation length is not.  They should both
12988		 * also have enough slack left over at the end, though,
12989		 * to round up to the next 8 byte boundary.
12990		 */
12991		cur_len = MIN(local_sglist[i].len - local_used,
12992			      remote_sglist[j].len - remote_used);
12993		rq->size = cur_len;
12994
12995		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12996		tmp_ptr += local_used;
12997
12998#if 0
12999		/* Use physical addresses when talking to ISC hardware */
13000		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13001			/* XXX KDM use busdma */
13002			rq->local = vtophys(tmp_ptr);
13003		} else
13004			rq->local = tmp_ptr;
13005#else
13006		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
13007		    ("HA does not support BUS_ADDR"));
13008		rq->local = tmp_ptr;
13009#endif
13010
13011		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13012		tmp_ptr += remote_used;
13013		rq->remote = tmp_ptr;
13014
13015		rq->callback = NULL;
13016
13017		local_used += cur_len;
13018		if (local_used >= local_sglist[i].len) {
13019			i++;
13020			local_used = 0;
13021		}
13022
13023		remote_used += cur_len;
13024		if (remote_used >= remote_sglist[j].len) {
13025			j++;
13026			remote_used = 0;
13027		}
13028		total_used += cur_len;
13029
13030		if (total_used >= io->scsiio.kern_data_len)
13031			rq->callback = callback;
13032
13033#if 0
13034		printf("%s: %s: local %p remote %p size %d\n", __func__,
13035		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13036		       rq->local, rq->remote, rq->size);
13037#endif
13038
13039		isc_ret = ctl_dt_single(rq);
13040		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13041			break;
13042	}
13043	if (isc_ret != CTL_HA_STATUS_WAIT) {
13044		rq->ret = isc_ret;
13045		callback(rq);
13046	}
13047
13048	return (0);
13049}
13050
13051static void
13052ctl_datamove_remote_read(union ctl_io *io)
13053{
13054	int retval;
13055	uint32_t i;
13056
13057	/*
13058	 * This will send an error to the other controller in the case of a
13059	 * failure.
13060	 */
13061	retval = ctl_datamove_remote_sgl_setup(io);
13062	if (retval != 0)
13063		return;
13064
13065	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13066					  ctl_datamove_remote_read_cb);
13067	if (retval != 0) {
13068		/*
13069		 * Make sure we free memory if there was an error..  The
13070		 * ctl_datamove_remote_xfer() function will send the
13071		 * datamove done message, or call the callback with an
13072		 * error if there is a problem.
13073		 */
13074		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13075			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13076		free(io->io_hdr.remote_sglist, M_CTL);
13077		io->io_hdr.remote_sglist = NULL;
13078		io->io_hdr.local_sglist = NULL;
13079	}
13080}
13081
13082/*
13083 * Process a datamove request from the other controller.  This is used for
13084 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13085 * first.  Once that is complete, the data gets DMAed into the remote
13086 * controller's memory.  For reads, we DMA from the remote controller's
13087 * memory into our memory first, and then move it out to the FETD.
13088 */
13089static void
13090ctl_datamove_remote(union ctl_io *io)
13091{
13092
13093	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13094
13095	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13096		ctl_failover_io(io, /*have_lock*/ 0);
13097		return;
13098	}
13099
13100	/*
13101	 * Note that we look for an aborted I/O here, but don't do some of
13102	 * the other checks that ctl_datamove() normally does.
13103	 * We don't need to run the datamove delay code, since that should
13104	 * have been done if need be on the other controller.
13105	 */
13106	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13107		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13108		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13109		       io->io_hdr.nexus.targ_port,
13110		       io->io_hdr.nexus.targ_lun);
13111		io->io_hdr.port_status = 31338;
13112		ctl_send_datamove_done(io, /*have_lock*/ 0);
13113		return;
13114	}
13115
13116	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13117		ctl_datamove_remote_write(io);
13118	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13119		ctl_datamove_remote_read(io);
13120	else {
13121		io->io_hdr.port_status = 31339;
13122		ctl_send_datamove_done(io, /*have_lock*/ 0);
13123	}
13124}
13125
13126static void
13127ctl_process_done(union ctl_io *io)
13128{
13129	struct ctl_lun *lun;
13130	struct ctl_softc *softc = control_softc;
13131	void (*fe_done)(union ctl_io *io);
13132	union ctl_ha_msg msg;
13133	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13134
13135	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13136	fe_done = softc->ctl_ports[targ_port]->fe_done;
13137
13138#ifdef CTL_TIME_IO
13139	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13140		char str[256];
13141		char path_str[64];
13142		struct sbuf sb;
13143
13144		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13145		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13146
13147		sbuf_cat(&sb, path_str);
13148		switch (io->io_hdr.io_type) {
13149		case CTL_IO_SCSI:
13150			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13151			sbuf_printf(&sb, "\n");
13152			sbuf_cat(&sb, path_str);
13153			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13154				    io->scsiio.tag_num, io->scsiio.tag_type);
13155			break;
13156		case CTL_IO_TASK:
13157			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13158				    "Tag Type: %d\n", io->taskio.task_action,
13159				    io->taskio.tag_num, io->taskio.tag_type);
13160			break;
13161		default:
13162			panic("%s: Invalid CTL I/O type %d\n",
13163			    __func__, io->io_hdr.io_type);
13164		}
13165		sbuf_cat(&sb, path_str);
13166		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13167			    (intmax_t)time_uptime - io->io_hdr.start_time);
13168		sbuf_finish(&sb);
13169		printf("%s", sbuf_data(&sb));
13170	}
13171#endif /* CTL_TIME_IO */
13172
13173	switch (io->io_hdr.io_type) {
13174	case CTL_IO_SCSI:
13175		break;
13176	case CTL_IO_TASK:
13177		if (ctl_debug & CTL_DEBUG_INFO)
13178			ctl_io_error_print(io, NULL);
13179		fe_done(io);
13180		return;
13181	default:
13182		panic("%s: Invalid CTL I/O type %d\n",
13183		    __func__, io->io_hdr.io_type);
13184	}
13185
13186	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13187	if (lun == NULL) {
13188		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13189				 io->io_hdr.nexus.targ_mapped_lun));
13190		goto bailout;
13191	}
13192
13193	mtx_lock(&lun->lun_lock);
13194
13195	/*
13196	 * Check to see if we have any informational exception and status
13197	 * of this command can be modified to report it in form of either
13198	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13199	 */
13200	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13201	    io->io_hdr.status == CTL_SUCCESS &&
13202	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13203		uint8_t mrie = lun->MODE_IE.mrie;
13204		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13205		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13206		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13207		     mrie == SIEP_MRIE_REC_UNCOND ||
13208		     mrie == SIEP_MRIE_NO_SENSE) &&
13209		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13210		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13211			ctl_set_sense(&io->scsiio,
13212			      /*current_error*/ 1,
13213			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13214			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13215			      /*asc*/ lun->ie_asc,
13216			      /*ascq*/ lun->ie_ascq,
13217			      SSD_ELEM_NONE);
13218			lun->ie_reported = 1;
13219		}
13220	} else if (lun->ie_reported < 0)
13221		lun->ie_reported = 0;
13222
13223	/*
13224	 * Check to see if we have any errors to inject here.  We only
13225	 * inject errors for commands that don't already have errors set.
13226	 */
13227	if (!STAILQ_EMPTY(&lun->error_list) &&
13228	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13229	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13230		ctl_inject_error(lun, io);
13231
13232	/*
13233	 * XXX KDM how do we treat commands that aren't completed
13234	 * successfully?
13235	 *
13236	 * XXX KDM should we also track I/O latency?
13237	 */
13238	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13239	    io->io_hdr.io_type == CTL_IO_SCSI) {
13240#ifdef CTL_TIME_IO
13241		struct bintime cur_bt;
13242#endif
13243		int type;
13244
13245		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13246		    CTL_FLAG_DATA_IN)
13247			type = CTL_STATS_READ;
13248		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13249		    CTL_FLAG_DATA_OUT)
13250			type = CTL_STATS_WRITE;
13251		else
13252			type = CTL_STATS_NO_IO;
13253
13254		lun->stats.ports[targ_port].bytes[type] +=
13255		    io->scsiio.kern_total_len;
13256		lun->stats.ports[targ_port].operations[type]++;
13257#ifdef CTL_TIME_IO
13258		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13259		   &io->io_hdr.dma_bt);
13260		getbinuptime(&cur_bt);
13261		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13262		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13263#endif
13264		lun->stats.ports[targ_port].num_dmas[type] +=
13265		    io->io_hdr.num_dmas;
13266	}
13267
13268	/*
13269	 * Remove this from the OOA queue.
13270	 */
13271	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13272#ifdef CTL_TIME_IO
13273	if (TAILQ_EMPTY(&lun->ooa_queue))
13274		lun->last_busy = getsbinuptime();
13275#endif
13276
13277	/*
13278	 * Run through the blocked queue on this LUN and see if anything
13279	 * has become unblocked, now that this transaction is done.
13280	 */
13281	ctl_check_blocked(lun);
13282
13283	/*
13284	 * If the LUN has been invalidated, free it if there is nothing
13285	 * left on its OOA queue.
13286	 */
13287	if ((lun->flags & CTL_LUN_INVALID)
13288	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13289		mtx_unlock(&lun->lun_lock);
13290		mtx_lock(&softc->ctl_lock);
13291		ctl_free_lun(lun);
13292		mtx_unlock(&softc->ctl_lock);
13293	} else
13294		mtx_unlock(&lun->lun_lock);
13295
13296bailout:
13297
13298	/*
13299	 * If this command has been aborted, make sure we set the status
13300	 * properly.  The FETD is responsible for freeing the I/O and doing
13301	 * whatever it needs to do to clean up its state.
13302	 */
13303	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13304		ctl_set_task_aborted(&io->scsiio);
13305
13306	/*
13307	 * If enabled, print command error status.
13308	 */
13309	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13310	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13311		ctl_io_error_print(io, NULL);
13312
13313	/*
13314	 * Tell the FETD or the other shelf controller we're done with this
13315	 * command.  Note that only SCSI commands get to this point.  Task
13316	 * management commands are completed above.
13317	 */
13318	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13319	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13320		memset(&msg, 0, sizeof(msg));
13321		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13322		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13323		msg.hdr.nexus = io->io_hdr.nexus;
13324		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13325		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13326		    M_WAITOK);
13327	}
13328
13329	fe_done(io);
13330}
13331
13332#ifdef CTL_WITH_CA
13333/*
13334 * Front end should call this if it doesn't do autosense.  When the request
13335 * sense comes back in from the initiator, we'll dequeue this and send it.
13336 */
13337int
13338ctl_queue_sense(union ctl_io *io)
13339{
13340	struct ctl_lun *lun;
13341	struct ctl_port *port;
13342	struct ctl_softc *softc;
13343	uint32_t initidx, targ_lun;
13344
13345	softc = control_softc;
13346
13347	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13348
13349	/*
13350	 * LUN lookup will likely move to the ctl_work_thread() once we
13351	 * have our new queueing infrastructure (that doesn't put things on
13352	 * a per-LUN queue initially).  That is so that we can handle
13353	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13354	 * can't deal with that right now.
13355	 */
13356	mtx_lock(&softc->ctl_lock);
13357
13358	/*
13359	 * If we don't have a LUN for this, just toss the sense
13360	 * information.
13361	 */
13362	port = ctl_io_port(&ctsio->io_hdr);
13363	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13364	if ((targ_lun < CTL_MAX_LUNS)
13365	 && (softc->ctl_luns[targ_lun] != NULL))
13366		lun = softc->ctl_luns[targ_lun];
13367	else
13368		goto bailout;
13369
13370	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13371
13372	mtx_lock(&lun->lun_lock);
13373	/*
13374	 * Already have CA set for this LUN...toss the sense information.
13375	 */
13376	if (ctl_is_set(lun->have_ca, initidx)) {
13377		mtx_unlock(&lun->lun_lock);
13378		goto bailout;
13379	}
13380
13381	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13382	       MIN(sizeof(lun->pending_sense[initidx]),
13383	       sizeof(io->scsiio.sense_data)));
13384	ctl_set_mask(lun->have_ca, initidx);
13385	mtx_unlock(&lun->lun_lock);
13386
13387bailout:
13388	mtx_unlock(&softc->ctl_lock);
13389
13390	ctl_free_io(io);
13391
13392	return (CTL_RETVAL_COMPLETE);
13393}
13394#endif
13395
13396/*
13397 * Primary command inlet from frontend ports.  All SCSI and task I/O
13398 * requests must go through this function.
13399 */
13400int
13401ctl_queue(union ctl_io *io)
13402{
13403	struct ctl_port *port;
13404
13405	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13406
13407#ifdef CTL_TIME_IO
13408	io->io_hdr.start_time = time_uptime;
13409	getbinuptime(&io->io_hdr.start_bt);
13410#endif /* CTL_TIME_IO */
13411
13412	/* Map FE-specific LUN ID into global one. */
13413	port = ctl_io_port(&io->io_hdr);
13414	io->io_hdr.nexus.targ_mapped_lun =
13415	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13416
13417	switch (io->io_hdr.io_type) {
13418	case CTL_IO_SCSI:
13419	case CTL_IO_TASK:
13420		if (ctl_debug & CTL_DEBUG_CDB)
13421			ctl_io_print(io);
13422		ctl_enqueue_incoming(io);
13423		break;
13424	default:
13425		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13426		return (EINVAL);
13427	}
13428
13429	return (CTL_RETVAL_COMPLETE);
13430}
13431
13432#ifdef CTL_IO_DELAY
13433static void
13434ctl_done_timer_wakeup(void *arg)
13435{
13436	union ctl_io *io;
13437
13438	io = (union ctl_io *)arg;
13439	ctl_done(io);
13440}
13441#endif /* CTL_IO_DELAY */
13442
13443void
13444ctl_serseq_done(union ctl_io *io)
13445{
13446	struct ctl_lun *lun;
13447
13448	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13449	if (lun->be_lun == NULL ||
13450	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13451		return;
13452	mtx_lock(&lun->lun_lock);
13453	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13454	ctl_check_blocked(lun);
13455	mtx_unlock(&lun->lun_lock);
13456}
13457
13458void
13459ctl_done(union ctl_io *io)
13460{
13461
13462	/*
13463	 * Enable this to catch duplicate completion issues.
13464	 */
13465#if 0
13466	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13467		printf("%s: type %d msg %d cdb %x iptl: "
13468		       "%u:%u:%u tag 0x%04x "
13469		       "flag %#x status %x\n",
13470			__func__,
13471			io->io_hdr.io_type,
13472			io->io_hdr.msg_type,
13473			io->scsiio.cdb[0],
13474			io->io_hdr.nexus.initid,
13475			io->io_hdr.nexus.targ_port,
13476			io->io_hdr.nexus.targ_lun,
13477			(io->io_hdr.io_type ==
13478			CTL_IO_TASK) ?
13479			io->taskio.tag_num :
13480			io->scsiio.tag_num,
13481		        io->io_hdr.flags,
13482			io->io_hdr.status);
13483	} else
13484		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13485#endif
13486
13487	/*
13488	 * This is an internal copy of an I/O, and should not go through
13489	 * the normal done processing logic.
13490	 */
13491	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13492		return;
13493
13494#ifdef CTL_IO_DELAY
13495	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13496		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13497	} else {
13498		struct ctl_lun *lun;
13499
13500		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13501
13502		if ((lun != NULL)
13503		 && (lun->delay_info.done_delay > 0)) {
13504
13505			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13506			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13507			callout_reset(&io->io_hdr.delay_callout,
13508				      lun->delay_info.done_delay * hz,
13509				      ctl_done_timer_wakeup, io);
13510			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13511				lun->delay_info.done_delay = 0;
13512			return;
13513		}
13514	}
13515#endif /* CTL_IO_DELAY */
13516
13517	ctl_enqueue_done(io);
13518}
13519
13520static void
13521ctl_work_thread(void *arg)
13522{
13523	struct ctl_thread *thr = (struct ctl_thread *)arg;
13524	struct ctl_softc *softc = thr->ctl_softc;
13525	union ctl_io *io;
13526	int retval;
13527
13528	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13529
13530	for (;;) {
13531		/*
13532		 * We handle the queues in this order:
13533		 * - ISC
13534		 * - done queue (to free up resources, unblock other commands)
13535		 * - RtR queue
13536		 * - incoming queue
13537		 *
13538		 * If those queues are empty, we break out of the loop and
13539		 * go to sleep.
13540		 */
13541		mtx_lock(&thr->queue_lock);
13542		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13543		if (io != NULL) {
13544			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13545			mtx_unlock(&thr->queue_lock);
13546			ctl_handle_isc(io);
13547			continue;
13548		}
13549		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13550		if (io != NULL) {
13551			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13552			/* clear any blocked commands, call fe_done */
13553			mtx_unlock(&thr->queue_lock);
13554			ctl_process_done(io);
13555			continue;
13556		}
13557		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13558		if (io != NULL) {
13559			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13560			mtx_unlock(&thr->queue_lock);
13561			if (io->io_hdr.io_type == CTL_IO_TASK)
13562				ctl_run_task(io);
13563			else
13564				ctl_scsiio_precheck(softc, &io->scsiio);
13565			continue;
13566		}
13567		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13568		if (io != NULL) {
13569			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13570			mtx_unlock(&thr->queue_lock);
13571			retval = ctl_scsiio(&io->scsiio);
13572			if (retval != CTL_RETVAL_COMPLETE)
13573				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13574			continue;
13575		}
13576
13577		/* Sleep until we have something to do. */
13578		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13579	}
13580}
13581
13582static void
13583ctl_lun_thread(void *arg)
13584{
13585	struct ctl_softc *softc = (struct ctl_softc *)arg;
13586	struct ctl_be_lun *be_lun;
13587
13588	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13589
13590	for (;;) {
13591		mtx_lock(&softc->ctl_lock);
13592		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13593		if (be_lun != NULL) {
13594			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13595			mtx_unlock(&softc->ctl_lock);
13596			ctl_create_lun(be_lun);
13597			continue;
13598		}
13599
13600		/* Sleep until we have something to do. */
13601		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13602		    PDROP | PRIBIO, "-", 0);
13603	}
13604}
13605
13606static void
13607ctl_thresh_thread(void *arg)
13608{
13609	struct ctl_softc *softc = (struct ctl_softc *)arg;
13610	struct ctl_lun *lun;
13611	struct ctl_logical_block_provisioning_page *page;
13612	const char *attr;
13613	union ctl_ha_msg msg;
13614	uint64_t thres, val;
13615	int i, e, set;
13616
13617	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13618
13619	for (;;) {
13620		mtx_lock(&softc->ctl_lock);
13621		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13622			if ((lun->flags & CTL_LUN_DISABLED) ||
13623			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13624			    lun->backend->lun_attr == NULL)
13625				continue;
13626			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13627			    softc->ha_mode == CTL_HA_MODE_XFER)
13628				continue;
13629			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13630				continue;
13631			e = 0;
13632			page = &lun->MODE_LBP;
13633			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13634				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13635					continue;
13636				thres = scsi_4btoul(page->descr[i].count);
13637				thres <<= CTL_LBP_EXPONENT;
13638				switch (page->descr[i].resource) {
13639				case 0x01:
13640					attr = "blocksavail";
13641					break;
13642				case 0x02:
13643					attr = "blocksused";
13644					break;
13645				case 0xf1:
13646					attr = "poolblocksavail";
13647					break;
13648				case 0xf2:
13649					attr = "poolblocksused";
13650					break;
13651				default:
13652					continue;
13653				}
13654				mtx_unlock(&softc->ctl_lock); // XXX
13655				val = lun->backend->lun_attr(
13656				    lun->be_lun->be_lun, attr);
13657				mtx_lock(&softc->ctl_lock);
13658				if (val == UINT64_MAX)
13659					continue;
13660				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13661				    == SLBPPD_ARMING_INC)
13662					e = (val >= thres);
13663				else
13664					e = (val <= thres);
13665				if (e)
13666					break;
13667			}
13668			mtx_lock(&lun->lun_lock);
13669			if (e) {
13670				scsi_u64to8b((uint8_t *)&page->descr[i] -
13671				    (uint8_t *)page, lun->ua_tpt_info);
13672				if (lun->lasttpt == 0 ||
13673				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13674					lun->lasttpt = time_uptime;
13675					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13676					set = 1;
13677				} else
13678					set = 0;
13679			} else {
13680				lun->lasttpt = 0;
13681				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13682				set = -1;
13683			}
13684			mtx_unlock(&lun->lun_lock);
13685			if (set != 0 &&
13686			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13687				/* Send msg to other side. */
13688				bzero(&msg.ua, sizeof(msg.ua));
13689				msg.hdr.msg_type = CTL_MSG_UA;
13690				msg.hdr.nexus.initid = -1;
13691				msg.hdr.nexus.targ_port = -1;
13692				msg.hdr.nexus.targ_lun = lun->lun;
13693				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13694				msg.ua.ua_all = 1;
13695				msg.ua.ua_set = (set > 0);
13696				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13697				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13698				mtx_unlock(&softc->ctl_lock); // XXX
13699				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13700				    sizeof(msg.ua), M_WAITOK);
13701				mtx_lock(&softc->ctl_lock);
13702			}
13703		}
13704		mtx_unlock(&softc->ctl_lock);
13705		pause("-", CTL_LBP_PERIOD * hz);
13706	}
13707}
13708
13709static void
13710ctl_enqueue_incoming(union ctl_io *io)
13711{
13712	struct ctl_softc *softc = control_softc;
13713	struct ctl_thread *thr;
13714	u_int idx;
13715
13716	idx = (io->io_hdr.nexus.targ_port * 127 +
13717	       io->io_hdr.nexus.initid) % worker_threads;
13718	thr = &softc->threads[idx];
13719	mtx_lock(&thr->queue_lock);
13720	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13721	mtx_unlock(&thr->queue_lock);
13722	wakeup(thr);
13723}
13724
13725static void
13726ctl_enqueue_rtr(union ctl_io *io)
13727{
13728	struct ctl_softc *softc = control_softc;
13729	struct ctl_thread *thr;
13730
13731	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13732	mtx_lock(&thr->queue_lock);
13733	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13734	mtx_unlock(&thr->queue_lock);
13735	wakeup(thr);
13736}
13737
13738static void
13739ctl_enqueue_done(union ctl_io *io)
13740{
13741	struct ctl_softc *softc = control_softc;
13742	struct ctl_thread *thr;
13743
13744	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13745	mtx_lock(&thr->queue_lock);
13746	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13747	mtx_unlock(&thr->queue_lock);
13748	wakeup(thr);
13749}
13750
13751static void
13752ctl_enqueue_isc(union ctl_io *io)
13753{
13754	struct ctl_softc *softc = control_softc;
13755	struct ctl_thread *thr;
13756
13757	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13758	mtx_lock(&thr->queue_lock);
13759	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13760	mtx_unlock(&thr->queue_lock);
13761	wakeup(thr);
13762}
13763
13764/*
13765 *  vim: ts=8
13766 */
13767