ctl.c revision 312570
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/11/sys/cam/ctl/ctl.c 312570 2017-01-21 08:29:40Z mav $");
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/ctype.h>
51#include <sys/kernel.h>
52#include <sys/types.h>
53#include <sys/kthread.h>
54#include <sys/bio.h>
55#include <sys/fcntl.h>
56#include <sys/lock.h>
57#include <sys/module.h>
58#include <sys/mutex.h>
59#include <sys/condvar.h>
60#include <sys/malloc.h>
61#include <sys/conf.h>
62#include <sys/ioccom.h>
63#include <sys/queue.h>
64#include <sys/sbuf.h>
65#include <sys/smp.h>
66#include <sys/endian.h>
67#include <sys/sysctl.h>
68#include <vm/uma.h>
69
70#include <cam/cam.h>
71#include <cam/scsi/scsi_all.h>
72#include <cam/scsi/scsi_cd.h>
73#include <cam/scsi/scsi_da.h>
74#include <cam/ctl/ctl_io.h>
75#include <cam/ctl/ctl.h>
76#include <cam/ctl/ctl_frontend.h>
77#include <cam/ctl/ctl_util.h>
78#include <cam/ctl/ctl_backend.h>
79#include <cam/ctl/ctl_ioctl.h>
80#include <cam/ctl/ctl_ha.h>
81#include <cam/ctl/ctl_private.h>
82#include <cam/ctl/ctl_debug.h>
83#include <cam/ctl/ctl_scsi_all.h>
84#include <cam/ctl/ctl_error.h>
85
86struct ctl_softc *control_softc = NULL;
87
88/*
89 * Template mode pages.
90 */
91
92/*
93 * Note that these are default values only.  The actual values will be
94 * filled in when the user does a mode sense.
95 */
96const static struct scsi_da_rw_recovery_page rw_er_page_default = {
97	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
98	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
99	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
100	/*read_retry_count*/0,
101	/*correction_span*/0,
102	/*head_offset_count*/0,
103	/*data_strobe_offset_cnt*/0,
104	/*byte8*/SMS_RWER_LBPERE,
105	/*write_retry_count*/0,
106	/*reserved2*/0,
107	/*recovery_time_limit*/{0, 0},
108};
109
110const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
111	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
112	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
113	/*byte3*/SMS_RWER_PER,
114	/*read_retry_count*/0,
115	/*correction_span*/0,
116	/*head_offset_count*/0,
117	/*data_strobe_offset_cnt*/0,
118	/*byte8*/SMS_RWER_LBPERE,
119	/*write_retry_count*/0,
120	/*reserved2*/0,
121	/*recovery_time_limit*/{0, 0},
122};
123
124const static struct scsi_format_page format_page_default = {
125	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
126	/*page_length*/sizeof(struct scsi_format_page) - 2,
127	/*tracks_per_zone*/ {0, 0},
128	/*alt_sectors_per_zone*/ {0, 0},
129	/*alt_tracks_per_zone*/ {0, 0},
130	/*alt_tracks_per_lun*/ {0, 0},
131	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
132			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
133	/*bytes_per_sector*/ {0, 0},
134	/*interleave*/ {0, 0},
135	/*track_skew*/ {0, 0},
136	/*cylinder_skew*/ {0, 0},
137	/*flags*/ SFP_HSEC,
138	/*reserved*/ {0, 0, 0}
139};
140
141const static struct scsi_format_page format_page_changeable = {
142	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
143	/*page_length*/sizeof(struct scsi_format_page) - 2,
144	/*tracks_per_zone*/ {0, 0},
145	/*alt_sectors_per_zone*/ {0, 0},
146	/*alt_tracks_per_zone*/ {0, 0},
147	/*alt_tracks_per_lun*/ {0, 0},
148	/*sectors_per_track*/ {0, 0},
149	/*bytes_per_sector*/ {0, 0},
150	/*interleave*/ {0, 0},
151	/*track_skew*/ {0, 0},
152	/*cylinder_skew*/ {0, 0},
153	/*flags*/ 0,
154	/*reserved*/ {0, 0, 0}
155};
156
157const static struct scsi_rigid_disk_page rigid_disk_page_default = {
158	/*page_code*/SMS_RIGID_DISK_PAGE,
159	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
160	/*cylinders*/ {0, 0, 0},
161	/*heads*/ CTL_DEFAULT_HEADS,
162	/*start_write_precomp*/ {0, 0, 0},
163	/*start_reduced_current*/ {0, 0, 0},
164	/*step_rate*/ {0, 0},
165	/*landing_zone_cylinder*/ {0, 0, 0},
166	/*rpl*/ SRDP_RPL_DISABLED,
167	/*rotational_offset*/ 0,
168	/*reserved1*/ 0,
169	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
170			   CTL_DEFAULT_ROTATION_RATE & 0xff},
171	/*reserved2*/ {0, 0}
172};
173
174const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
175	/*page_code*/SMS_RIGID_DISK_PAGE,
176	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
177	/*cylinders*/ {0, 0, 0},
178	/*heads*/ 0,
179	/*start_write_precomp*/ {0, 0, 0},
180	/*start_reduced_current*/ {0, 0, 0},
181	/*step_rate*/ {0, 0},
182	/*landing_zone_cylinder*/ {0, 0, 0},
183	/*rpl*/ 0,
184	/*rotational_offset*/ 0,
185	/*reserved1*/ 0,
186	/*rotation_rate*/ {0, 0},
187	/*reserved2*/ {0, 0}
188};
189
190const static struct scsi_da_verify_recovery_page verify_er_page_default = {
191	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
192	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
193	/*byte3*/0,
194	/*read_retry_count*/0,
195	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
196	/*recovery_time_limit*/{0, 0},
197};
198
199const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
200	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
201	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
202	/*byte3*/SMS_VER_PER,
203	/*read_retry_count*/0,
204	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
205	/*recovery_time_limit*/{0, 0},
206};
207
208const static struct scsi_caching_page caching_page_default = {
209	/*page_code*/SMS_CACHING_PAGE,
210	/*page_length*/sizeof(struct scsi_caching_page) - 2,
211	/*flags1*/ SCP_DISC | SCP_WCE,
212	/*ret_priority*/ 0,
213	/*disable_pf_transfer_len*/ {0xff, 0xff},
214	/*min_prefetch*/ {0, 0},
215	/*max_prefetch*/ {0xff, 0xff},
216	/*max_pf_ceiling*/ {0xff, 0xff},
217	/*flags2*/ 0,
218	/*cache_segments*/ 0,
219	/*cache_seg_size*/ {0, 0},
220	/*reserved*/ 0,
221	/*non_cache_seg_size*/ {0, 0, 0}
222};
223
224const static struct scsi_caching_page caching_page_changeable = {
225	/*page_code*/SMS_CACHING_PAGE,
226	/*page_length*/sizeof(struct scsi_caching_page) - 2,
227	/*flags1*/ SCP_WCE | SCP_RCD,
228	/*ret_priority*/ 0,
229	/*disable_pf_transfer_len*/ {0, 0},
230	/*min_prefetch*/ {0, 0},
231	/*max_prefetch*/ {0, 0},
232	/*max_pf_ceiling*/ {0, 0},
233	/*flags2*/ 0,
234	/*cache_segments*/ 0,
235	/*cache_seg_size*/ {0, 0},
236	/*reserved*/ 0,
237	/*non_cache_seg_size*/ {0, 0, 0}
238};
239
240const static struct scsi_control_page control_page_default = {
241	/*page_code*/SMS_CONTROL_MODE_PAGE,
242	/*page_length*/sizeof(struct scsi_control_page) - 2,
243	/*rlec*/0,
244	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245	/*eca_and_aen*/0,
246	/*flags4*/SCP_TAS,
247	/*aen_holdoff_period*/{0, 0},
248	/*busy_timeout_period*/{0, 0},
249	/*extended_selftest_completion_time*/{0, 0}
250};
251
252const static struct scsi_control_page control_page_changeable = {
253	/*page_code*/SMS_CONTROL_MODE_PAGE,
254	/*page_length*/sizeof(struct scsi_control_page) - 2,
255	/*rlec*/SCP_DSENSE,
256	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
257	/*eca_and_aen*/SCP_SWP,
258	/*flags4*/0,
259	/*aen_holdoff_period*/{0, 0},
260	/*busy_timeout_period*/{0, 0},
261	/*extended_selftest_completion_time*/{0, 0}
262};
263
264#define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
265
266const static struct scsi_control_ext_page control_ext_page_default = {
267	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268	/*subpage_code*/0x01,
269	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270	/*flags*/0,
271	/*prio*/0,
272	/*max_sense*/0
273};
274
275const static struct scsi_control_ext_page control_ext_page_changeable = {
276	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277	/*subpage_code*/0x01,
278	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279	/*flags*/0,
280	/*prio*/0,
281	/*max_sense*/0xff
282};
283
284const static struct scsi_info_exceptions_page ie_page_default = {
285	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287	/*info_flags*/SIEP_FLAGS_EWASC,
288	/*mrie*/SIEP_MRIE_NO,
289	/*interval_timer*/{0, 0, 0, 0},
290	/*report_count*/{0, 0, 0, 1}
291};
292
293const static struct scsi_info_exceptions_page ie_page_changeable = {
294	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
297	    SIEP_FLAGS_LOGERR,
298	/*mrie*/0x0f,
299	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
300	/*report_count*/{0xff, 0xff, 0xff, 0xff}
301};
302
303#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
304
305const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307	/*subpage_code*/0x02,
308	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309	/*flags*/0,
310	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311	/*descr*/{}},
312	{{/*flags*/0,
313	  /*resource*/0x01,
314	  /*reserved*/{0, 0},
315	  /*count*/{0, 0, 0, 0}},
316	 {/*flags*/0,
317	  /*resource*/0x02,
318	  /*reserved*/{0, 0},
319	  /*count*/{0, 0, 0, 0}},
320	 {/*flags*/0,
321	  /*resource*/0xf1,
322	  /*reserved*/{0, 0},
323	  /*count*/{0, 0, 0, 0}},
324	 {/*flags*/0,
325	  /*resource*/0xf2,
326	  /*reserved*/{0, 0},
327	  /*count*/{0, 0, 0, 0}}
328	}
329};
330
331const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333	/*subpage_code*/0x02,
334	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335	/*flags*/SLBPP_SITUA,
336	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337	/*descr*/{}},
338	{{/*flags*/0,
339	  /*resource*/0,
340	  /*reserved*/{0, 0},
341	  /*count*/{0, 0, 0, 0}},
342	 {/*flags*/0,
343	  /*resource*/0,
344	  /*reserved*/{0, 0},
345	  /*count*/{0, 0, 0, 0}},
346	 {/*flags*/0,
347	  /*resource*/0,
348	  /*reserved*/{0, 0},
349	  /*count*/{0, 0, 0, 0}},
350	 {/*flags*/0,
351	  /*resource*/0,
352	  /*reserved*/{0, 0},
353	  /*count*/{0, 0, 0, 0}}
354	}
355};
356
357const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358	/*page_code*/SMS_CDDVD_CAPS_PAGE,
359	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360	/*caps1*/0x3f,
361	/*caps2*/0x00,
362	/*caps3*/0xf0,
363	/*caps4*/0x00,
364	/*caps5*/0x29,
365	/*caps6*/0x00,
366	/*obsolete*/{0, 0},
367	/*nvol_levels*/{0, 0},
368	/*buffer_size*/{8, 0},
369	/*obsolete2*/{0, 0},
370	/*reserved*/0,
371	/*digital*/0,
372	/*obsolete3*/0,
373	/*copy_management*/0,
374	/*reserved2*/0,
375	/*rotation_control*/0,
376	/*cur_write_speed*/0,
377	/*num_speed_descr*/0,
378};
379
380const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381	/*page_code*/SMS_CDDVD_CAPS_PAGE,
382	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383	/*caps1*/0,
384	/*caps2*/0,
385	/*caps3*/0,
386	/*caps4*/0,
387	/*caps5*/0,
388	/*caps6*/0,
389	/*obsolete*/{0, 0},
390	/*nvol_levels*/{0, 0},
391	/*buffer_size*/{0, 0},
392	/*obsolete2*/{0, 0},
393	/*reserved*/0,
394	/*digital*/0,
395	/*obsolete3*/0,
396	/*copy_management*/0,
397	/*reserved2*/0,
398	/*rotation_control*/0,
399	/*cur_write_speed*/0,
400	/*num_speed_descr*/0,
401};
402
403SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404static int worker_threads = -1;
405SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
406    &worker_threads, 1, "Number of worker threads");
407static int ctl_debug = CTL_DEBUG_NONE;
408SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
409    &ctl_debug, 0, "Enabled debug flags");
410
411/*
412 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
413 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
414 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
415 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
416 */
417#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
418
419static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
420				  int param);
421static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
422static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
423static int ctl_init(void);
424void ctl_shutdown(void);
425static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
426static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
427static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
428static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
429			      struct ctl_ooa *ooa_hdr,
430			      struct ctl_ooa_entry *kern_entries);
431static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
432		     struct thread *td);
433static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
434			 struct ctl_be_lun *be_lun);
435static int ctl_free_lun(struct ctl_lun *lun);
436static void ctl_create_lun(struct ctl_be_lun *be_lun);
437static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
438
439static int ctl_do_mode_select(union ctl_io *io);
440static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
441			   uint64_t res_key, uint64_t sa_res_key,
442			   uint8_t type, uint32_t residx,
443			   struct ctl_scsiio *ctsio,
444			   struct scsi_per_res_out *cdb,
445			   struct scsi_per_res_out_parms* param);
446static void ctl_pro_preempt_other(struct ctl_lun *lun,
447				  union ctl_ha_msg *msg);
448static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
449static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
450static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
451static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
452static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
453static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
455					 int alloc_len);
456static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
457					 int alloc_len);
458static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
459static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
460static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
461static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
462static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
463static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
464    bool seq);
465static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
466static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
467    union ctl_io *pending_io, union ctl_io *ooa_io);
468static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
469				union ctl_io *starting_io);
470static int ctl_check_blocked(struct ctl_lun *lun);
471static int ctl_scsiio_lun_check(struct ctl_lun *lun,
472				const struct ctl_cmd_entry *entry,
473				struct ctl_scsiio *ctsio);
474static void ctl_failover_lun(union ctl_io *io);
475static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
476			       struct ctl_scsiio *ctsio);
477static int ctl_scsiio(struct ctl_scsiio *ctsio);
478
479static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
480static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
481			    ctl_ua_type ua_type);
482static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
483			 ctl_ua_type ua_type);
484static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
485static int ctl_abort_task(union ctl_io *io);
486static int ctl_abort_task_set(union ctl_io *io);
487static int ctl_query_task(union ctl_io *io, int task_set);
488static int ctl_i_t_nexus_reset(union ctl_io *io);
489static int ctl_query_async_event(union ctl_io *io);
490static void ctl_run_task(union ctl_io *io);
491#ifdef CTL_IO_DELAY
492static void ctl_datamove_timer_wakeup(void *arg);
493static void ctl_done_timer_wakeup(void *arg);
494#endif /* CTL_IO_DELAY */
495
496static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
497static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
498static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
499static void ctl_datamove_remote_write(union ctl_io *io);
500static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
501static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
502static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
503static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
504				    ctl_ha_dt_cb callback);
505static void ctl_datamove_remote_read(union ctl_io *io);
506static void ctl_datamove_remote(union ctl_io *io);
507static void ctl_process_done(union ctl_io *io);
508static void ctl_lun_thread(void *arg);
509static void ctl_thresh_thread(void *arg);
510static void ctl_work_thread(void *arg);
511static void ctl_enqueue_incoming(union ctl_io *io);
512static void ctl_enqueue_rtr(union ctl_io *io);
513static void ctl_enqueue_done(union ctl_io *io);
514static void ctl_enqueue_isc(union ctl_io *io);
515static const struct ctl_cmd_entry *
516    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
517static const struct ctl_cmd_entry *
518    ctl_validate_command(struct ctl_scsiio *ctsio);
519static int ctl_cmd_applicable(uint8_t lun_type,
520    const struct ctl_cmd_entry *entry);
521
522static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
523static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
524static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
525static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
526
527/*
528 * Load the serialization table.  This isn't very pretty, but is probably
529 * the easiest way to do it.
530 */
531#include "ctl_ser_table.c"
532
533/*
534 * We only need to define open, close and ioctl routines for this driver.
535 */
536static struct cdevsw ctl_cdevsw = {
537	.d_version =	D_VERSION,
538	.d_flags =	0,
539	.d_open =	ctl_open,
540	.d_close =	ctl_close,
541	.d_ioctl =	ctl_ioctl,
542	.d_name =	"ctl",
543};
544
545
546MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
547
548static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
549
550static moduledata_t ctl_moduledata = {
551	"ctl",
552	ctl_module_event_handler,
553	NULL
554};
555
556DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
557MODULE_VERSION(ctl, 1);
558
559static struct ctl_frontend ha_frontend =
560{
561	.name = "ha",
562};
563
564static void
565ctl_ha_datamove(union ctl_io *io)
566{
567	struct ctl_lun *lun;
568	struct ctl_sg_entry *sgl;
569	union ctl_ha_msg msg;
570	uint32_t sg_entries_sent;
571	int do_sg_copy, i, j;
572
573	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
574	memset(&msg.dt, 0, sizeof(msg.dt));
575	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
576	msg.hdr.original_sc = io->io_hdr.original_sc;
577	msg.hdr.serializing_sc = io;
578	msg.hdr.nexus = io->io_hdr.nexus;
579	msg.hdr.status = io->io_hdr.status;
580	msg.dt.flags = io->io_hdr.flags;
581
582	/*
583	 * We convert everything into a S/G list here.  We can't
584	 * pass by reference, only by value between controllers.
585	 * So we can't pass a pointer to the S/G list, only as many
586	 * S/G entries as we can fit in here.  If it's possible for
587	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
588	 * then we need to break this up into multiple transfers.
589	 */
590	if (io->scsiio.kern_sg_entries == 0) {
591		msg.dt.kern_sg_entries = 1;
592#if 0
593		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
594			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
595		} else {
596			/* XXX KDM use busdma here! */
597			msg.dt.sg_list[0].addr =
598			    (void *)vtophys(io->scsiio.kern_data_ptr);
599		}
600#else
601		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
602		    ("HA does not support BUS_ADDR"));
603		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
604#endif
605		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
606		do_sg_copy = 0;
607	} else {
608		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
609		do_sg_copy = 1;
610	}
611
612	msg.dt.kern_data_len = io->scsiio.kern_data_len;
613	msg.dt.kern_total_len = io->scsiio.kern_total_len;
614	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
615	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
616	msg.dt.sg_sequence = 0;
617
618	/*
619	 * Loop until we've sent all of the S/G entries.  On the
620	 * other end, we'll recompose these S/G entries into one
621	 * contiguous list before processing.
622	 */
623	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
624	    msg.dt.sg_sequence++) {
625		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
626		    sizeof(msg.dt.sg_list[0])),
627		    msg.dt.kern_sg_entries - sg_entries_sent);
628		if (do_sg_copy != 0) {
629			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
630			for (i = sg_entries_sent, j = 0;
631			     i < msg.dt.cur_sg_entries; i++, j++) {
632#if 0
633				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
634					msg.dt.sg_list[j].addr = sgl[i].addr;
635				} else {
636					/* XXX KDM use busdma here! */
637					msg.dt.sg_list[j].addr =
638					    (void *)vtophys(sgl[i].addr);
639				}
640#else
641				KASSERT((io->io_hdr.flags &
642				    CTL_FLAG_BUS_ADDR) == 0,
643				    ("HA does not support BUS_ADDR"));
644				msg.dt.sg_list[j].addr = sgl[i].addr;
645#endif
646				msg.dt.sg_list[j].len = sgl[i].len;
647			}
648		}
649
650		sg_entries_sent += msg.dt.cur_sg_entries;
651		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
652		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
653		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
654		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
655		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
656			io->io_hdr.port_status = 31341;
657			io->scsiio.be_move_done(io);
658			return;
659		}
660		msg.dt.sent_sg_entries = sg_entries_sent;
661	}
662
663	/*
664	 * Officially handover the request from us to peer.
665	 * If failover has just happened, then we must return error.
666	 * If failover happen just after, then it is not our problem.
667	 */
668	if (lun)
669		mtx_lock(&lun->lun_lock);
670	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
671		if (lun)
672			mtx_unlock(&lun->lun_lock);
673		io->io_hdr.port_status = 31342;
674		io->scsiio.be_move_done(io);
675		return;
676	}
677	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
678	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
679	if (lun)
680		mtx_unlock(&lun->lun_lock);
681}
682
683static void
684ctl_ha_done(union ctl_io *io)
685{
686	union ctl_ha_msg msg;
687
688	if (io->io_hdr.io_type == CTL_IO_SCSI) {
689		memset(&msg, 0, sizeof(msg));
690		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
691		msg.hdr.original_sc = io->io_hdr.original_sc;
692		msg.hdr.nexus = io->io_hdr.nexus;
693		msg.hdr.status = io->io_hdr.status;
694		msg.scsi.scsi_status = io->scsiio.scsi_status;
695		msg.scsi.tag_num = io->scsiio.tag_num;
696		msg.scsi.tag_type = io->scsiio.tag_type;
697		msg.scsi.sense_len = io->scsiio.sense_len;
698		msg.scsi.sense_residual = io->scsiio.sense_residual;
699		msg.scsi.residual = io->scsiio.residual;
700		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
701		    io->scsiio.sense_len);
702		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
703		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
704		    msg.scsi.sense_len, M_WAITOK);
705	}
706	ctl_free_io(io);
707}
708
709static void
710ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
711			    union ctl_ha_msg *msg_info)
712{
713	struct ctl_scsiio *ctsio;
714
715	if (msg_info->hdr.original_sc == NULL) {
716		printf("%s: original_sc == NULL!\n", __func__);
717		/* XXX KDM now what? */
718		return;
719	}
720
721	ctsio = &msg_info->hdr.original_sc->scsiio;
722	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
723	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
724	ctsio->io_hdr.status = msg_info->hdr.status;
725	ctsio->scsi_status = msg_info->scsi.scsi_status;
726	ctsio->sense_len = msg_info->scsi.sense_len;
727	ctsio->sense_residual = msg_info->scsi.sense_residual;
728	ctsio->residual = msg_info->scsi.residual;
729	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
730	       msg_info->scsi.sense_len);
731	ctl_enqueue_isc((union ctl_io *)ctsio);
732}
733
734static void
735ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
736				union ctl_ha_msg *msg_info)
737{
738	struct ctl_scsiio *ctsio;
739
740	if (msg_info->hdr.serializing_sc == NULL) {
741		printf("%s: serializing_sc == NULL!\n", __func__);
742		/* XXX KDM now what? */
743		return;
744	}
745
746	ctsio = &msg_info->hdr.serializing_sc->scsiio;
747	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
748	ctl_enqueue_isc((union ctl_io *)ctsio);
749}
750
751void
752ctl_isc_announce_lun(struct ctl_lun *lun)
753{
754	struct ctl_softc *softc = lun->ctl_softc;
755	union ctl_ha_msg *msg;
756	struct ctl_ha_msg_lun_pr_key pr_key;
757	int i, k;
758
759	if (softc->ha_link != CTL_HA_LINK_ONLINE)
760		return;
761	mtx_lock(&lun->lun_lock);
762	i = sizeof(msg->lun);
763	if (lun->lun_devid)
764		i += lun->lun_devid->len;
765	i += sizeof(pr_key) * lun->pr_key_count;
766alloc:
767	mtx_unlock(&lun->lun_lock);
768	msg = malloc(i, M_CTL, M_WAITOK);
769	mtx_lock(&lun->lun_lock);
770	k = sizeof(msg->lun);
771	if (lun->lun_devid)
772		k += lun->lun_devid->len;
773	k += sizeof(pr_key) * lun->pr_key_count;
774	if (i < k) {
775		free(msg, M_CTL);
776		i = k;
777		goto alloc;
778	}
779	bzero(&msg->lun, sizeof(msg->lun));
780	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
781	msg->hdr.nexus.targ_lun = lun->lun;
782	msg->hdr.nexus.targ_mapped_lun = lun->lun;
783	msg->lun.flags = lun->flags;
784	msg->lun.pr_generation = lun->pr_generation;
785	msg->lun.pr_res_idx = lun->pr_res_idx;
786	msg->lun.pr_res_type = lun->pr_res_type;
787	msg->lun.pr_key_count = lun->pr_key_count;
788	i = 0;
789	if (lun->lun_devid) {
790		msg->lun.lun_devid_len = lun->lun_devid->len;
791		memcpy(&msg->lun.data[i], lun->lun_devid->data,
792		    msg->lun.lun_devid_len);
793		i += msg->lun.lun_devid_len;
794	}
795	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
796		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
797			continue;
798		pr_key.pr_iid = k;
799		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
800		i += sizeof(pr_key);
801	}
802	mtx_unlock(&lun->lun_lock);
803	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
804	    M_WAITOK);
805	free(msg, M_CTL);
806
807	if (lun->flags & CTL_LUN_PRIMARY_SC) {
808		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
809			ctl_isc_announce_mode(lun, -1,
810			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
811			    lun->mode_pages.index[i].subpage);
812		}
813	}
814}
815
816void
817ctl_isc_announce_port(struct ctl_port *port)
818{
819	struct ctl_softc *softc = port->ctl_softc;
820	union ctl_ha_msg *msg;
821	int i;
822
823	if (port->targ_port < softc->port_min ||
824	    port->targ_port >= softc->port_max ||
825	    softc->ha_link != CTL_HA_LINK_ONLINE)
826		return;
827	i = sizeof(msg->port) + strlen(port->port_name) + 1;
828	if (port->lun_map)
829		i += sizeof(uint32_t) * CTL_MAX_LUNS;
830	if (port->port_devid)
831		i += port->port_devid->len;
832	if (port->target_devid)
833		i += port->target_devid->len;
834	if (port->init_devid)
835		i += port->init_devid->len;
836	msg = malloc(i, M_CTL, M_WAITOK);
837	bzero(&msg->port, sizeof(msg->port));
838	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
839	msg->hdr.nexus.targ_port = port->targ_port;
840	msg->port.port_type = port->port_type;
841	msg->port.physical_port = port->physical_port;
842	msg->port.virtual_port = port->virtual_port;
843	msg->port.status = port->status;
844	i = 0;
845	msg->port.name_len = sprintf(&msg->port.data[i],
846	    "%d:%s", softc->ha_id, port->port_name) + 1;
847	i += msg->port.name_len;
848	if (port->lun_map) {
849		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
850		memcpy(&msg->port.data[i], port->lun_map,
851		    msg->port.lun_map_len);
852		i += msg->port.lun_map_len;
853	}
854	if (port->port_devid) {
855		msg->port.port_devid_len = port->port_devid->len;
856		memcpy(&msg->port.data[i], port->port_devid->data,
857		    msg->port.port_devid_len);
858		i += msg->port.port_devid_len;
859	}
860	if (port->target_devid) {
861		msg->port.target_devid_len = port->target_devid->len;
862		memcpy(&msg->port.data[i], port->target_devid->data,
863		    msg->port.target_devid_len);
864		i += msg->port.target_devid_len;
865	}
866	if (port->init_devid) {
867		msg->port.init_devid_len = port->init_devid->len;
868		memcpy(&msg->port.data[i], port->init_devid->data,
869		    msg->port.init_devid_len);
870		i += msg->port.init_devid_len;
871	}
872	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
873	    M_WAITOK);
874	free(msg, M_CTL);
875}
876
877void
878ctl_isc_announce_iid(struct ctl_port *port, int iid)
879{
880	struct ctl_softc *softc = port->ctl_softc;
881	union ctl_ha_msg *msg;
882	int i, l;
883
884	if (port->targ_port < softc->port_min ||
885	    port->targ_port >= softc->port_max ||
886	    softc->ha_link != CTL_HA_LINK_ONLINE)
887		return;
888	mtx_lock(&softc->ctl_lock);
889	i = sizeof(msg->iid);
890	l = 0;
891	if (port->wwpn_iid[iid].name)
892		l = strlen(port->wwpn_iid[iid].name) + 1;
893	i += l;
894	msg = malloc(i, M_CTL, M_NOWAIT);
895	if (msg == NULL) {
896		mtx_unlock(&softc->ctl_lock);
897		return;
898	}
899	bzero(&msg->iid, sizeof(msg->iid));
900	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
901	msg->hdr.nexus.targ_port = port->targ_port;
902	msg->hdr.nexus.initid = iid;
903	msg->iid.in_use = port->wwpn_iid[iid].in_use;
904	msg->iid.name_len = l;
905	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
906	if (port->wwpn_iid[iid].name)
907		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
908	mtx_unlock(&softc->ctl_lock);
909	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
910	free(msg, M_CTL);
911}
912
913void
914ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
915    uint8_t page, uint8_t subpage)
916{
917	struct ctl_softc *softc = lun->ctl_softc;
918	union ctl_ha_msg msg;
919	u_int i;
920
921	if (softc->ha_link != CTL_HA_LINK_ONLINE)
922		return;
923	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
924		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
925		    page && lun->mode_pages.index[i].subpage == subpage)
926			break;
927	}
928	if (i == CTL_NUM_MODE_PAGES)
929		return;
930
931	/* Don't try to replicate pages not present on this device. */
932	if (lun->mode_pages.index[i].page_data == NULL)
933		return;
934
935	bzero(&msg.mode, sizeof(msg.mode));
936	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
937	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
938	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
939	msg.hdr.nexus.targ_lun = lun->lun;
940	msg.hdr.nexus.targ_mapped_lun = lun->lun;
941	msg.mode.page_code = page;
942	msg.mode.subpage = subpage;
943	msg.mode.page_len = lun->mode_pages.index[i].page_len;
944	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
945	    msg.mode.page_len);
946	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
947	    M_WAITOK);
948}
949
950static void
951ctl_isc_ha_link_up(struct ctl_softc *softc)
952{
953	struct ctl_port *port;
954	struct ctl_lun *lun;
955	union ctl_ha_msg msg;
956	int i;
957
958	/* Announce this node parameters to peer for validation. */
959	msg.login.msg_type = CTL_MSG_LOGIN;
960	msg.login.version = CTL_HA_VERSION;
961	msg.login.ha_mode = softc->ha_mode;
962	msg.login.ha_id = softc->ha_id;
963	msg.login.max_luns = CTL_MAX_LUNS;
964	msg.login.max_ports = CTL_MAX_PORTS;
965	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
966	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
967	    M_WAITOK);
968
969	STAILQ_FOREACH(port, &softc->port_list, links) {
970		ctl_isc_announce_port(port);
971		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
972			if (port->wwpn_iid[i].in_use)
973				ctl_isc_announce_iid(port, i);
974		}
975	}
976	STAILQ_FOREACH(lun, &softc->lun_list, links)
977		ctl_isc_announce_lun(lun);
978}
979
980static void
981ctl_isc_ha_link_down(struct ctl_softc *softc)
982{
983	struct ctl_port *port;
984	struct ctl_lun *lun;
985	union ctl_io *io;
986	int i;
987
988	mtx_lock(&softc->ctl_lock);
989	STAILQ_FOREACH(lun, &softc->lun_list, links) {
990		mtx_lock(&lun->lun_lock);
991		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
992			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
993			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
994		}
995		mtx_unlock(&lun->lun_lock);
996
997		mtx_unlock(&softc->ctl_lock);
998		io = ctl_alloc_io(softc->othersc_pool);
999		mtx_lock(&softc->ctl_lock);
1000		ctl_zero_io(io);
1001		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1002		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1003		ctl_enqueue_isc(io);
1004	}
1005
1006	STAILQ_FOREACH(port, &softc->port_list, links) {
1007		if (port->targ_port >= softc->port_min &&
1008		    port->targ_port < softc->port_max)
1009			continue;
1010		port->status &= ~CTL_PORT_STATUS_ONLINE;
1011		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1012			port->wwpn_iid[i].in_use = 0;
1013			free(port->wwpn_iid[i].name, M_CTL);
1014			port->wwpn_iid[i].name = NULL;
1015		}
1016	}
1017	mtx_unlock(&softc->ctl_lock);
1018}
1019
1020static void
1021ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1022{
1023	struct ctl_lun *lun;
1024	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1025
1026	mtx_lock(&softc->ctl_lock);
1027	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1028	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1029		mtx_lock(&lun->lun_lock);
1030		mtx_unlock(&softc->ctl_lock);
1031		if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1032		    msg->ua.ua_set)
1033			memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1034		if (msg->ua.ua_all) {
1035			if (msg->ua.ua_set)
1036				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1037			else
1038				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1039		} else {
1040			if (msg->ua.ua_set)
1041				ctl_est_ua(lun, iid, msg->ua.ua_type);
1042			else
1043				ctl_clr_ua(lun, iid, msg->ua.ua_type);
1044		}
1045		mtx_unlock(&lun->lun_lock);
1046	} else
1047		mtx_unlock(&softc->ctl_lock);
1048}
1049
1050static void
1051ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1052{
1053	struct ctl_lun *lun;
1054	struct ctl_ha_msg_lun_pr_key pr_key;
1055	int i, k;
1056	ctl_lun_flags oflags;
1057	uint32_t targ_lun;
1058
1059	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1060	mtx_lock(&softc->ctl_lock);
1061	if ((targ_lun >= CTL_MAX_LUNS) ||
1062	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1063		mtx_unlock(&softc->ctl_lock);
1064		return;
1065	}
1066	mtx_lock(&lun->lun_lock);
1067	mtx_unlock(&softc->ctl_lock);
1068	if (lun->flags & CTL_LUN_DISABLED) {
1069		mtx_unlock(&lun->lun_lock);
1070		return;
1071	}
1072	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1073	if (msg->lun.lun_devid_len != i || (i > 0 &&
1074	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1075		mtx_unlock(&lun->lun_lock);
1076		printf("%s: Received conflicting HA LUN %d\n",
1077		    __func__, msg->hdr.nexus.targ_lun);
1078		return;
1079	} else {
1080		/* Record whether peer is primary. */
1081		oflags = lun->flags;
1082		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1083		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1084			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1085		else
1086			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1087		if (oflags != lun->flags)
1088			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1089
1090		/* If peer is primary and we are not -- use data */
1091		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1092		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1093			lun->pr_generation = msg->lun.pr_generation;
1094			lun->pr_res_idx = msg->lun.pr_res_idx;
1095			lun->pr_res_type = msg->lun.pr_res_type;
1096			lun->pr_key_count = msg->lun.pr_key_count;
1097			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1098				ctl_clr_prkey(lun, k);
1099			for (k = 0; k < msg->lun.pr_key_count; k++) {
1100				memcpy(&pr_key, &msg->lun.data[i],
1101				    sizeof(pr_key));
1102				ctl_alloc_prkey(lun, pr_key.pr_iid);
1103				ctl_set_prkey(lun, pr_key.pr_iid,
1104				    pr_key.pr_key);
1105				i += sizeof(pr_key);
1106			}
1107		}
1108
1109		mtx_unlock(&lun->lun_lock);
1110		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1111		    __func__, msg->hdr.nexus.targ_lun,
1112		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1113		    "primary" : "secondary"));
1114
1115		/* If we are primary but peer doesn't know -- notify */
1116		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1117		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1118			ctl_isc_announce_lun(lun);
1119	}
1120}
1121
1122static void
1123ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1124{
1125	struct ctl_port *port;
1126	struct ctl_lun *lun;
1127	int i, new;
1128
1129	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1130	if (port == NULL) {
1131		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1132		    msg->hdr.nexus.targ_port));
1133		new = 1;
1134		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1135		port->frontend = &ha_frontend;
1136		port->targ_port = msg->hdr.nexus.targ_port;
1137		port->fe_datamove = ctl_ha_datamove;
1138		port->fe_done = ctl_ha_done;
1139	} else if (port->frontend == &ha_frontend) {
1140		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1141		    msg->hdr.nexus.targ_port));
1142		new = 0;
1143	} else {
1144		printf("%s: Received conflicting HA port %d\n",
1145		    __func__, msg->hdr.nexus.targ_port);
1146		return;
1147	}
1148	port->port_type = msg->port.port_type;
1149	port->physical_port = msg->port.physical_port;
1150	port->virtual_port = msg->port.virtual_port;
1151	port->status = msg->port.status;
1152	i = 0;
1153	free(port->port_name, M_CTL);
1154	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1155	    M_CTL);
1156	i += msg->port.name_len;
1157	if (msg->port.lun_map_len != 0) {
1158		if (port->lun_map == NULL)
1159			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1160			    M_CTL, M_WAITOK);
1161		memcpy(port->lun_map, &msg->port.data[i],
1162		    sizeof(uint32_t) * CTL_MAX_LUNS);
1163		i += msg->port.lun_map_len;
1164	} else {
1165		free(port->lun_map, M_CTL);
1166		port->lun_map = NULL;
1167	}
1168	if (msg->port.port_devid_len != 0) {
1169		if (port->port_devid == NULL ||
1170		    port->port_devid->len != msg->port.port_devid_len) {
1171			free(port->port_devid, M_CTL);
1172			port->port_devid = malloc(sizeof(struct ctl_devid) +
1173			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1174		}
1175		memcpy(port->port_devid->data, &msg->port.data[i],
1176		    msg->port.port_devid_len);
1177		port->port_devid->len = msg->port.port_devid_len;
1178		i += msg->port.port_devid_len;
1179	} else {
1180		free(port->port_devid, M_CTL);
1181		port->port_devid = NULL;
1182	}
1183	if (msg->port.target_devid_len != 0) {
1184		if (port->target_devid == NULL ||
1185		    port->target_devid->len != msg->port.target_devid_len) {
1186			free(port->target_devid, M_CTL);
1187			port->target_devid = malloc(sizeof(struct ctl_devid) +
1188			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1189		}
1190		memcpy(port->target_devid->data, &msg->port.data[i],
1191		    msg->port.target_devid_len);
1192		port->target_devid->len = msg->port.target_devid_len;
1193		i += msg->port.target_devid_len;
1194	} else {
1195		free(port->target_devid, M_CTL);
1196		port->target_devid = NULL;
1197	}
1198	if (msg->port.init_devid_len != 0) {
1199		if (port->init_devid == NULL ||
1200		    port->init_devid->len != msg->port.init_devid_len) {
1201			free(port->init_devid, M_CTL);
1202			port->init_devid = malloc(sizeof(struct ctl_devid) +
1203			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1204		}
1205		memcpy(port->init_devid->data, &msg->port.data[i],
1206		    msg->port.init_devid_len);
1207		port->init_devid->len = msg->port.init_devid_len;
1208		i += msg->port.init_devid_len;
1209	} else {
1210		free(port->init_devid, M_CTL);
1211		port->init_devid = NULL;
1212	}
1213	if (new) {
1214		if (ctl_port_register(port) != 0) {
1215			printf("%s: ctl_port_register() failed with error\n",
1216			    __func__);
1217		}
1218	}
1219	mtx_lock(&softc->ctl_lock);
1220	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1221		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1222			continue;
1223		mtx_lock(&lun->lun_lock);
1224		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1225		mtx_unlock(&lun->lun_lock);
1226	}
1227	mtx_unlock(&softc->ctl_lock);
1228}
1229
1230static void
1231ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1232{
1233	struct ctl_port *port;
1234	int iid;
1235
1236	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1237	if (port == NULL) {
1238		printf("%s: Received IID for unknown port %d\n",
1239		    __func__, msg->hdr.nexus.targ_port);
1240		return;
1241	}
1242	iid = msg->hdr.nexus.initid;
1243	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1244	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1245	free(port->wwpn_iid[iid].name, M_CTL);
1246	if (msg->iid.name_len) {
1247		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1248		    msg->iid.name_len, M_CTL);
1249	} else
1250		port->wwpn_iid[iid].name = NULL;
1251}
1252
1253static void
1254ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1255{
1256
1257	if (msg->login.version != CTL_HA_VERSION) {
1258		printf("CTL HA peers have different versions %d != %d\n",
1259		    msg->login.version, CTL_HA_VERSION);
1260		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1261		return;
1262	}
1263	if (msg->login.ha_mode != softc->ha_mode) {
1264		printf("CTL HA peers have different ha_mode %d != %d\n",
1265		    msg->login.ha_mode, softc->ha_mode);
1266		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1267		return;
1268	}
1269	if (msg->login.ha_id == softc->ha_id) {
1270		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1271		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1272		return;
1273	}
1274	if (msg->login.max_luns != CTL_MAX_LUNS ||
1275	    msg->login.max_ports != CTL_MAX_PORTS ||
1276	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1277		printf("CTL HA peers have different limits\n");
1278		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1279		return;
1280	}
1281}
1282
1283static void
1284ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1285{
1286	struct ctl_lun *lun;
1287	u_int i;
1288	uint32_t initidx, targ_lun;
1289
1290	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1291	mtx_lock(&softc->ctl_lock);
1292	if ((targ_lun >= CTL_MAX_LUNS) ||
1293	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1294		mtx_unlock(&softc->ctl_lock);
1295		return;
1296	}
1297	mtx_lock(&lun->lun_lock);
1298	mtx_unlock(&softc->ctl_lock);
1299	if (lun->flags & CTL_LUN_DISABLED) {
1300		mtx_unlock(&lun->lun_lock);
1301		return;
1302	}
1303	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1304		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1305		    msg->mode.page_code &&
1306		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1307			break;
1308	}
1309	if (i == CTL_NUM_MODE_PAGES) {
1310		mtx_unlock(&lun->lun_lock);
1311		return;
1312	}
1313	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1314	    lun->mode_pages.index[i].page_len);
1315	initidx = ctl_get_initindex(&msg->hdr.nexus);
1316	if (initidx != -1)
1317		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1318	mtx_unlock(&lun->lun_lock);
1319}
1320
1321/*
1322 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1323 * subsystem come in here.
1324 */
1325static void
1326ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1327{
1328	struct ctl_softc *softc = control_softc;
1329	union ctl_io *io;
1330	struct ctl_prio *presio;
1331	ctl_ha_status isc_status;
1332
1333	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1334	if (event == CTL_HA_EVT_MSG_RECV) {
1335		union ctl_ha_msg *msg, msgbuf;
1336
1337		if (param > sizeof(msgbuf))
1338			msg = malloc(param, M_CTL, M_WAITOK);
1339		else
1340			msg = &msgbuf;
1341		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1342		    M_WAITOK);
1343		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1344			printf("%s: Error receiving message: %d\n",
1345			    __func__, isc_status);
1346			if (msg != &msgbuf)
1347				free(msg, M_CTL);
1348			return;
1349		}
1350
1351		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1352		switch (msg->hdr.msg_type) {
1353		case CTL_MSG_SERIALIZE:
1354			io = ctl_alloc_io(softc->othersc_pool);
1355			ctl_zero_io(io);
1356			// populate ctsio from msg
1357			io->io_hdr.io_type = CTL_IO_SCSI;
1358			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1359			io->io_hdr.original_sc = msg->hdr.original_sc;
1360			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1361					    CTL_FLAG_IO_ACTIVE;
1362			/*
1363			 * If we're in serialization-only mode, we don't
1364			 * want to go through full done processing.  Thus
1365			 * the COPY flag.
1366			 *
1367			 * XXX KDM add another flag that is more specific.
1368			 */
1369			if (softc->ha_mode != CTL_HA_MODE_XFER)
1370				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1371			io->io_hdr.nexus = msg->hdr.nexus;
1372#if 0
1373			printf("port %u, iid %u, lun %u\n",
1374			       io->io_hdr.nexus.targ_port,
1375			       io->io_hdr.nexus.initid,
1376			       io->io_hdr.nexus.targ_lun);
1377#endif
1378			io->scsiio.tag_num = msg->scsi.tag_num;
1379			io->scsiio.tag_type = msg->scsi.tag_type;
1380#ifdef CTL_TIME_IO
1381			io->io_hdr.start_time = time_uptime;
1382			getbinuptime(&io->io_hdr.start_bt);
1383#endif /* CTL_TIME_IO */
1384			io->scsiio.cdb_len = msg->scsi.cdb_len;
1385			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1386			       CTL_MAX_CDBLEN);
1387			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1388				const struct ctl_cmd_entry *entry;
1389
1390				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1391				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1392				io->io_hdr.flags |=
1393					entry->flags & CTL_FLAG_DATA_MASK;
1394			}
1395			ctl_enqueue_isc(io);
1396			break;
1397
1398		/* Performed on the Originating SC, XFER mode only */
1399		case CTL_MSG_DATAMOVE: {
1400			struct ctl_sg_entry *sgl;
1401			int i, j;
1402
1403			io = msg->hdr.original_sc;
1404			if (io == NULL) {
1405				printf("%s: original_sc == NULL!\n", __func__);
1406				/* XXX KDM do something here */
1407				break;
1408			}
1409			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1410			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1411			/*
1412			 * Keep track of this, we need to send it back over
1413			 * when the datamove is complete.
1414			 */
1415			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1416			if (msg->hdr.status == CTL_SUCCESS)
1417				io->io_hdr.status = msg->hdr.status;
1418
1419			if (msg->dt.sg_sequence == 0) {
1420#ifdef CTL_TIME_IO
1421				getbinuptime(&io->io_hdr.dma_start_bt);
1422#endif
1423				i = msg->dt.kern_sg_entries +
1424				    msg->dt.kern_data_len /
1425				    CTL_HA_DATAMOVE_SEGMENT + 1;
1426				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1427				    M_WAITOK | M_ZERO);
1428				io->io_hdr.remote_sglist = sgl;
1429				io->io_hdr.local_sglist =
1430				    &sgl[msg->dt.kern_sg_entries];
1431
1432				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1433
1434				io->scsiio.kern_sg_entries =
1435					msg->dt.kern_sg_entries;
1436				io->scsiio.rem_sg_entries =
1437					msg->dt.kern_sg_entries;
1438				io->scsiio.kern_data_len =
1439					msg->dt.kern_data_len;
1440				io->scsiio.kern_total_len =
1441					msg->dt.kern_total_len;
1442				io->scsiio.kern_data_resid =
1443					msg->dt.kern_data_resid;
1444				io->scsiio.kern_rel_offset =
1445					msg->dt.kern_rel_offset;
1446				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1447				io->io_hdr.flags |= msg->dt.flags &
1448				    CTL_FLAG_BUS_ADDR;
1449			} else
1450				sgl = (struct ctl_sg_entry *)
1451					io->scsiio.kern_data_ptr;
1452
1453			for (i = msg->dt.sent_sg_entries, j = 0;
1454			     i < (msg->dt.sent_sg_entries +
1455			     msg->dt.cur_sg_entries); i++, j++) {
1456				sgl[i].addr = msg->dt.sg_list[j].addr;
1457				sgl[i].len = msg->dt.sg_list[j].len;
1458
1459#if 0
1460				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1461				    __func__, sgl[i].addr, sgl[i].len, j, i);
1462#endif
1463			}
1464
1465			/*
1466			 * If this is the last piece of the I/O, we've got
1467			 * the full S/G list.  Queue processing in the thread.
1468			 * Otherwise wait for the next piece.
1469			 */
1470			if (msg->dt.sg_last != 0)
1471				ctl_enqueue_isc(io);
1472			break;
1473		}
1474		/* Performed on the Serializing (primary) SC, XFER mode only */
1475		case CTL_MSG_DATAMOVE_DONE: {
1476			if (msg->hdr.serializing_sc == NULL) {
1477				printf("%s: serializing_sc == NULL!\n",
1478				       __func__);
1479				/* XXX KDM now what? */
1480				break;
1481			}
1482			/*
1483			 * We grab the sense information here in case
1484			 * there was a failure, so we can return status
1485			 * back to the initiator.
1486			 */
1487			io = msg->hdr.serializing_sc;
1488			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1489			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1490			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1491			io->io_hdr.port_status = msg->scsi.fetd_status;
1492			io->scsiio.residual = msg->scsi.residual;
1493			if (msg->hdr.status != CTL_STATUS_NONE) {
1494				io->io_hdr.status = msg->hdr.status;
1495				io->scsiio.scsi_status = msg->scsi.scsi_status;
1496				io->scsiio.sense_len = msg->scsi.sense_len;
1497				io->scsiio.sense_residual =msg->scsi.sense_residual;
1498				memcpy(&io->scsiio.sense_data,
1499				    &msg->scsi.sense_data,
1500				    msg->scsi.sense_len);
1501				if (msg->hdr.status == CTL_SUCCESS)
1502					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1503			}
1504			ctl_enqueue_isc(io);
1505			break;
1506		}
1507
1508		/* Preformed on Originating SC, SER_ONLY mode */
1509		case CTL_MSG_R2R:
1510			io = msg->hdr.original_sc;
1511			if (io == NULL) {
1512				printf("%s: original_sc == NULL!\n",
1513				    __func__);
1514				break;
1515			}
1516			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1517			io->io_hdr.msg_type = CTL_MSG_R2R;
1518			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1519			ctl_enqueue_isc(io);
1520			break;
1521
1522		/*
1523		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1524		 * mode.
1525		 * Performed on the Originating (i.e. secondary) SC in XFER
1526		 * mode
1527		 */
1528		case CTL_MSG_FINISH_IO:
1529			if (softc->ha_mode == CTL_HA_MODE_XFER)
1530				ctl_isc_handler_finish_xfer(softc, msg);
1531			else
1532				ctl_isc_handler_finish_ser_only(softc, msg);
1533			break;
1534
1535		/* Preformed on Originating SC */
1536		case CTL_MSG_BAD_JUJU:
1537			io = msg->hdr.original_sc;
1538			if (io == NULL) {
1539				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1540				       __func__);
1541				break;
1542			}
1543			ctl_copy_sense_data(msg, io);
1544			/*
1545			 * IO should have already been cleaned up on other
1546			 * SC so clear this flag so we won't send a message
1547			 * back to finish the IO there.
1548			 */
1549			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1550			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1551
1552			/* io = msg->hdr.serializing_sc; */
1553			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1554			ctl_enqueue_isc(io);
1555			break;
1556
1557		/* Handle resets sent from the other side */
1558		case CTL_MSG_MANAGE_TASKS: {
1559			struct ctl_taskio *taskio;
1560			taskio = (struct ctl_taskio *)ctl_alloc_io(
1561			    softc->othersc_pool);
1562			ctl_zero_io((union ctl_io *)taskio);
1563			taskio->io_hdr.io_type = CTL_IO_TASK;
1564			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1565			taskio->io_hdr.nexus = msg->hdr.nexus;
1566			taskio->task_action = msg->task.task_action;
1567			taskio->tag_num = msg->task.tag_num;
1568			taskio->tag_type = msg->task.tag_type;
1569#ifdef CTL_TIME_IO
1570			taskio->io_hdr.start_time = time_uptime;
1571			getbinuptime(&taskio->io_hdr.start_bt);
1572#endif /* CTL_TIME_IO */
1573			ctl_run_task((union ctl_io *)taskio);
1574			break;
1575		}
1576		/* Persistent Reserve action which needs attention */
1577		case CTL_MSG_PERS_ACTION:
1578			presio = (struct ctl_prio *)ctl_alloc_io(
1579			    softc->othersc_pool);
1580			ctl_zero_io((union ctl_io *)presio);
1581			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1582			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1583			presio->io_hdr.nexus = msg->hdr.nexus;
1584			presio->pr_msg = msg->pr;
1585			ctl_enqueue_isc((union ctl_io *)presio);
1586			break;
1587		case CTL_MSG_UA:
1588			ctl_isc_ua(softc, msg, param);
1589			break;
1590		case CTL_MSG_PORT_SYNC:
1591			ctl_isc_port_sync(softc, msg, param);
1592			break;
1593		case CTL_MSG_LUN_SYNC:
1594			ctl_isc_lun_sync(softc, msg, param);
1595			break;
1596		case CTL_MSG_IID_SYNC:
1597			ctl_isc_iid_sync(softc, msg, param);
1598			break;
1599		case CTL_MSG_LOGIN:
1600			ctl_isc_login(softc, msg, param);
1601			break;
1602		case CTL_MSG_MODE_SYNC:
1603			ctl_isc_mode_sync(softc, msg, param);
1604			break;
1605		default:
1606			printf("Received HA message of unknown type %d\n",
1607			    msg->hdr.msg_type);
1608			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1609			break;
1610		}
1611		if (msg != &msgbuf)
1612			free(msg, M_CTL);
1613	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1614		printf("CTL: HA link status changed from %d to %d\n",
1615		    softc->ha_link, param);
1616		if (param == softc->ha_link)
1617			return;
1618		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1619			softc->ha_link = param;
1620			ctl_isc_ha_link_down(softc);
1621		} else {
1622			softc->ha_link = param;
1623			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1624				ctl_isc_ha_link_up(softc);
1625		}
1626		return;
1627	} else {
1628		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1629		return;
1630	}
1631}
1632
1633static void
1634ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1635{
1636
1637	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1638	    src->scsi.sense_len);
1639	dest->scsiio.scsi_status = src->scsi.scsi_status;
1640	dest->scsiio.sense_len = src->scsi.sense_len;
1641	dest->io_hdr.status = src->hdr.status;
1642}
1643
1644static void
1645ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1646{
1647
1648	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1649	    src->scsiio.sense_len);
1650	dest->scsi.scsi_status = src->scsiio.scsi_status;
1651	dest->scsi.sense_len = src->scsiio.sense_len;
1652	dest->hdr.status = src->io_hdr.status;
1653}
1654
1655void
1656ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1657{
1658	struct ctl_softc *softc = lun->ctl_softc;
1659	ctl_ua_type *pu;
1660
1661	if (initidx < softc->init_min || initidx >= softc->init_max)
1662		return;
1663	mtx_assert(&lun->lun_lock, MA_OWNED);
1664	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1665	if (pu == NULL)
1666		return;
1667	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1668}
1669
1670void
1671ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1672{
1673	int i;
1674
1675	mtx_assert(&lun->lun_lock, MA_OWNED);
1676	if (lun->pending_ua[port] == NULL)
1677		return;
1678	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1679		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1680			continue;
1681		lun->pending_ua[port][i] |= ua;
1682	}
1683}
1684
1685void
1686ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1687{
1688	struct ctl_softc *softc = lun->ctl_softc;
1689	int i;
1690
1691	mtx_assert(&lun->lun_lock, MA_OWNED);
1692	for (i = softc->port_min; i < softc->port_max; i++)
1693		ctl_est_ua_port(lun, i, except, ua);
1694}
1695
1696void
1697ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1698{
1699	struct ctl_softc *softc = lun->ctl_softc;
1700	ctl_ua_type *pu;
1701
1702	if (initidx < softc->init_min || initidx >= softc->init_max)
1703		return;
1704	mtx_assert(&lun->lun_lock, MA_OWNED);
1705	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1706	if (pu == NULL)
1707		return;
1708	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1709}
1710
1711void
1712ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1713{
1714	struct ctl_softc *softc = lun->ctl_softc;
1715	int i, j;
1716
1717	mtx_assert(&lun->lun_lock, MA_OWNED);
1718	for (i = softc->port_min; i < softc->port_max; i++) {
1719		if (lun->pending_ua[i] == NULL)
1720			continue;
1721		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1722			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1723				continue;
1724			lun->pending_ua[i][j] &= ~ua;
1725		}
1726	}
1727}
1728
1729void
1730ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1731    ctl_ua_type ua_type)
1732{
1733	struct ctl_lun *lun;
1734
1735	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1736	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1737		mtx_lock(&lun->lun_lock);
1738		ctl_clr_ua(lun, initidx, ua_type);
1739		mtx_unlock(&lun->lun_lock);
1740	}
1741}
1742
1743static int
1744ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1745{
1746	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1747	struct ctl_lun *lun;
1748	struct ctl_lun_req ireq;
1749	int error, value;
1750
1751	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1752	error = sysctl_handle_int(oidp, &value, 0, req);
1753	if ((error != 0) || (req->newptr == NULL))
1754		return (error);
1755
1756	mtx_lock(&softc->ctl_lock);
1757	if (value == 0)
1758		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1759	else
1760		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1761	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1762		mtx_unlock(&softc->ctl_lock);
1763		bzero(&ireq, sizeof(ireq));
1764		ireq.reqtype = CTL_LUNREQ_MODIFY;
1765		ireq.reqdata.modify.lun_id = lun->lun;
1766		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1767		    curthread);
1768		if (ireq.status != CTL_LUN_OK) {
1769			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1770			    __func__, ireq.status, ireq.error_str);
1771		}
1772		mtx_lock(&softc->ctl_lock);
1773	}
1774	mtx_unlock(&softc->ctl_lock);
1775	return (0);
1776}
1777
1778static int
1779ctl_init(void)
1780{
1781	struct make_dev_args args;
1782	struct ctl_softc *softc;
1783	void *other_pool;
1784	int i, error;
1785
1786	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1787			       M_WAITOK | M_ZERO);
1788
1789	make_dev_args_init(&args);
1790	args.mda_devsw = &ctl_cdevsw;
1791	args.mda_uid = UID_ROOT;
1792	args.mda_gid = GID_OPERATOR;
1793	args.mda_mode = 0600;
1794	args.mda_si_drv1 = softc;
1795	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1796	if (error != 0) {
1797		free(control_softc, M_DEVBUF);
1798		return (error);
1799	}
1800
1801	sysctl_ctx_init(&softc->sysctl_ctx);
1802	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1803		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1804		CTLFLAG_RD, 0, "CAM Target Layer");
1805
1806	if (softc->sysctl_tree == NULL) {
1807		printf("%s: unable to allocate sysctl tree\n", __func__);
1808		destroy_dev(softc->dev);
1809		free(control_softc, M_DEVBUF);
1810		control_softc = NULL;
1811		return (ENOMEM);
1812	}
1813
1814	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1815	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1816	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1817	softc->flags = 0;
1818
1819	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1820	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1821	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1822
1823	/*
1824	 * In Copan's HA scheme, the "master" and "slave" roles are
1825	 * figured out through the slot the controller is in.  Although it
1826	 * is an active/active system, someone has to be in charge.
1827	 */
1828	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1829	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1830	    "HA head ID (0 - no HA)");
1831	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1832		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1833		softc->is_single = 1;
1834		softc->port_cnt = CTL_MAX_PORTS;
1835		softc->port_min = 0;
1836	} else {
1837		softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1838		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1839	}
1840	softc->port_max = softc->port_min + softc->port_cnt;
1841	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1842	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1843
1844	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1845	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1846	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1847
1848	STAILQ_INIT(&softc->lun_list);
1849	STAILQ_INIT(&softc->pending_lun_queue);
1850	STAILQ_INIT(&softc->fe_list);
1851	STAILQ_INIT(&softc->port_list);
1852	STAILQ_INIT(&softc->be_list);
1853	ctl_tpc_init(softc);
1854
1855	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1856	                    &other_pool) != 0)
1857	{
1858		printf("ctl: can't allocate %d entry other SC pool, "
1859		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1860		return (ENOMEM);
1861	}
1862	softc->othersc_pool = other_pool;
1863
1864	if (worker_threads <= 0)
1865		worker_threads = max(1, mp_ncpus / 4);
1866	if (worker_threads > CTL_MAX_THREADS)
1867		worker_threads = CTL_MAX_THREADS;
1868
1869	for (i = 0; i < worker_threads; i++) {
1870		struct ctl_thread *thr = &softc->threads[i];
1871
1872		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1873		thr->ctl_softc = softc;
1874		STAILQ_INIT(&thr->incoming_queue);
1875		STAILQ_INIT(&thr->rtr_queue);
1876		STAILQ_INIT(&thr->done_queue);
1877		STAILQ_INIT(&thr->isc_queue);
1878
1879		error = kproc_kthread_add(ctl_work_thread, thr,
1880		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1881		if (error != 0) {
1882			printf("error creating CTL work thread!\n");
1883			ctl_pool_free(other_pool);
1884			return (error);
1885		}
1886	}
1887	error = kproc_kthread_add(ctl_lun_thread, softc,
1888	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1889	if (error != 0) {
1890		printf("error creating CTL lun thread!\n");
1891		ctl_pool_free(other_pool);
1892		return (error);
1893	}
1894	error = kproc_kthread_add(ctl_thresh_thread, softc,
1895	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1896	if (error != 0) {
1897		printf("error creating CTL threshold thread!\n");
1898		ctl_pool_free(other_pool);
1899		return (error);
1900	}
1901
1902	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1903	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1904	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1905
1906	if (softc->is_single == 0) {
1907		ctl_frontend_register(&ha_frontend);
1908		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1909			printf("ctl_init: ctl_ha_msg_init failed.\n");
1910			softc->is_single = 1;
1911		} else
1912		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1913		    != CTL_HA_STATUS_SUCCESS) {
1914			printf("ctl_init: ctl_ha_msg_register failed.\n");
1915			softc->is_single = 1;
1916		}
1917	}
1918	return (0);
1919}
1920
1921void
1922ctl_shutdown(void)
1923{
1924	struct ctl_softc *softc = control_softc;
1925	struct ctl_lun *lun, *next_lun;
1926
1927	if (softc->is_single == 0) {
1928		ctl_ha_msg_shutdown(softc);
1929		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1930		    != CTL_HA_STATUS_SUCCESS)
1931			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1932		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1933			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1934		ctl_frontend_deregister(&ha_frontend);
1935	}
1936
1937	mtx_lock(&softc->ctl_lock);
1938
1939	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1940		ctl_free_lun(lun);
1941
1942	mtx_unlock(&softc->ctl_lock);
1943
1944#if 0
1945	ctl_shutdown_thread(softc->work_thread);
1946	mtx_destroy(&softc->queue_lock);
1947#endif
1948
1949	ctl_tpc_shutdown(softc);
1950	uma_zdestroy(softc->io_zone);
1951	mtx_destroy(&softc->ctl_lock);
1952
1953	destroy_dev(softc->dev);
1954
1955	sysctl_ctx_free(&softc->sysctl_ctx);
1956
1957	free(control_softc, M_DEVBUF);
1958	control_softc = NULL;
1959}
1960
1961static int
1962ctl_module_event_handler(module_t mod, int what, void *arg)
1963{
1964
1965	switch (what) {
1966	case MOD_LOAD:
1967		return (ctl_init());
1968	case MOD_UNLOAD:
1969		return (EBUSY);
1970	default:
1971		return (EOPNOTSUPP);
1972	}
1973}
1974
1975/*
1976 * XXX KDM should we do some access checks here?  Bump a reference count to
1977 * prevent a CTL module from being unloaded while someone has it open?
1978 */
1979static int
1980ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1981{
1982	return (0);
1983}
1984
1985static int
1986ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1987{
1988	return (0);
1989}
1990
1991/*
1992 * Remove an initiator by port number and initiator ID.
1993 * Returns 0 for success, -1 for failure.
1994 */
1995int
1996ctl_remove_initiator(struct ctl_port *port, int iid)
1997{
1998	struct ctl_softc *softc = port->ctl_softc;
1999
2000	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2001
2002	if (iid > CTL_MAX_INIT_PER_PORT) {
2003		printf("%s: initiator ID %u > maximun %u!\n",
2004		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2005		return (-1);
2006	}
2007
2008	mtx_lock(&softc->ctl_lock);
2009	port->wwpn_iid[iid].in_use--;
2010	port->wwpn_iid[iid].last_use = time_uptime;
2011	mtx_unlock(&softc->ctl_lock);
2012	ctl_isc_announce_iid(port, iid);
2013
2014	return (0);
2015}
2016
2017/*
2018 * Add an initiator to the initiator map.
2019 * Returns iid for success, < 0 for failure.
2020 */
2021int
2022ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2023{
2024	struct ctl_softc *softc = port->ctl_softc;
2025	time_t best_time;
2026	int i, best;
2027
2028	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2029
2030	if (iid >= CTL_MAX_INIT_PER_PORT) {
2031		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2032		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2033		free(name, M_CTL);
2034		return (-1);
2035	}
2036
2037	mtx_lock(&softc->ctl_lock);
2038
2039	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2040		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2041			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2042				iid = i;
2043				break;
2044			}
2045			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2046			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2047				iid = i;
2048				break;
2049			}
2050		}
2051	}
2052
2053	if (iid < 0) {
2054		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2055			if (port->wwpn_iid[i].in_use == 0 &&
2056			    port->wwpn_iid[i].wwpn == 0 &&
2057			    port->wwpn_iid[i].name == NULL) {
2058				iid = i;
2059				break;
2060			}
2061		}
2062	}
2063
2064	if (iid < 0) {
2065		best = -1;
2066		best_time = INT32_MAX;
2067		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2068			if (port->wwpn_iid[i].in_use == 0) {
2069				if (port->wwpn_iid[i].last_use < best_time) {
2070					best = i;
2071					best_time = port->wwpn_iid[i].last_use;
2072				}
2073			}
2074		}
2075		iid = best;
2076	}
2077
2078	if (iid < 0) {
2079		mtx_unlock(&softc->ctl_lock);
2080		free(name, M_CTL);
2081		return (-2);
2082	}
2083
2084	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2085		/*
2086		 * This is not an error yet.
2087		 */
2088		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2089#if 0
2090			printf("%s: port %d iid %u WWPN %#jx arrived"
2091			    " again\n", __func__, port->targ_port,
2092			    iid, (uintmax_t)wwpn);
2093#endif
2094			goto take;
2095		}
2096		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2097		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2098#if 0
2099			printf("%s: port %d iid %u name '%s' arrived"
2100			    " again\n", __func__, port->targ_port,
2101			    iid, name);
2102#endif
2103			goto take;
2104		}
2105
2106		/*
2107		 * This is an error, but what do we do about it?  The
2108		 * driver is telling us we have a new WWPN for this
2109		 * initiator ID, so we pretty much need to use it.
2110		 */
2111		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2112		    " but WWPN %#jx '%s' is still at that address\n",
2113		    __func__, port->targ_port, iid, wwpn, name,
2114		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2115		    port->wwpn_iid[iid].name);
2116
2117		/*
2118		 * XXX KDM clear have_ca and ua_pending on each LUN for
2119		 * this initiator.
2120		 */
2121	}
2122take:
2123	free(port->wwpn_iid[iid].name, M_CTL);
2124	port->wwpn_iid[iid].name = name;
2125	port->wwpn_iid[iid].wwpn = wwpn;
2126	port->wwpn_iid[iid].in_use++;
2127	mtx_unlock(&softc->ctl_lock);
2128	ctl_isc_announce_iid(port, iid);
2129
2130	return (iid);
2131}
2132
2133static int
2134ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2135{
2136	int len;
2137
2138	switch (port->port_type) {
2139	case CTL_PORT_FC:
2140	{
2141		struct scsi_transportid_fcp *id =
2142		    (struct scsi_transportid_fcp *)buf;
2143		if (port->wwpn_iid[iid].wwpn == 0)
2144			return (0);
2145		memset(id, 0, sizeof(*id));
2146		id->format_protocol = SCSI_PROTO_FC;
2147		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2148		return (sizeof(*id));
2149	}
2150	case CTL_PORT_ISCSI:
2151	{
2152		struct scsi_transportid_iscsi_port *id =
2153		    (struct scsi_transportid_iscsi_port *)buf;
2154		if (port->wwpn_iid[iid].name == NULL)
2155			return (0);
2156		memset(id, 0, 256);
2157		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2158		    SCSI_PROTO_ISCSI;
2159		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2160		len = roundup2(min(len, 252), 4);
2161		scsi_ulto2b(len, id->additional_length);
2162		return (sizeof(*id) + len);
2163	}
2164	case CTL_PORT_SAS:
2165	{
2166		struct scsi_transportid_sas *id =
2167		    (struct scsi_transportid_sas *)buf;
2168		if (port->wwpn_iid[iid].wwpn == 0)
2169			return (0);
2170		memset(id, 0, sizeof(*id));
2171		id->format_protocol = SCSI_PROTO_SAS;
2172		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2173		return (sizeof(*id));
2174	}
2175	default:
2176	{
2177		struct scsi_transportid_spi *id =
2178		    (struct scsi_transportid_spi *)buf;
2179		memset(id, 0, sizeof(*id));
2180		id->format_protocol = SCSI_PROTO_SPI;
2181		scsi_ulto2b(iid, id->scsi_addr);
2182		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2183		return (sizeof(*id));
2184	}
2185	}
2186}
2187
2188/*
2189 * Serialize a command that went down the "wrong" side, and so was sent to
2190 * this controller for execution.  The logic is a little different than the
2191 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2192 * sent back to the other side, but in the success case, we execute the
2193 * command on this side (XFER mode) or tell the other side to execute it
2194 * (SER_ONLY mode).
2195 */
2196static int
2197ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2198{
2199	struct ctl_softc *softc = control_softc;
2200	union ctl_ha_msg msg_info;
2201	struct ctl_port *port;
2202	struct ctl_lun *lun;
2203	const struct ctl_cmd_entry *entry;
2204	int retval = 0;
2205	uint32_t targ_lun;
2206
2207	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2208	mtx_lock(&softc->ctl_lock);
2209
2210	/* Make sure that we know about this port. */
2211	port = ctl_io_port(&ctsio->io_hdr);
2212	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2213		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2214					 /*retry_count*/ 1);
2215		goto badjuju;
2216	}
2217
2218	/* Make sure that we know about this LUN. */
2219	if ((targ_lun < CTL_MAX_LUNS) &&
2220	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2221		mtx_lock(&lun->lun_lock);
2222		mtx_unlock(&softc->ctl_lock);
2223		/*
2224		 * If the LUN is invalid, pretend that it doesn't exist.
2225		 * It will go away as soon as all pending I/O has been
2226		 * completed.
2227		 */
2228		if (lun->flags & CTL_LUN_DISABLED) {
2229			mtx_unlock(&lun->lun_lock);
2230			lun = NULL;
2231		}
2232	} else {
2233		mtx_unlock(&softc->ctl_lock);
2234		lun = NULL;
2235	}
2236	if (lun == NULL) {
2237		/*
2238		 * The other node would not send this request to us unless
2239		 * received announce that we are primary node for this LUN.
2240		 * If this LUN does not exist now, it is probably result of
2241		 * a race, so respond to initiator in the most opaque way.
2242		 */
2243		ctl_set_busy(ctsio);
2244		goto badjuju;
2245	}
2246
2247	entry = ctl_get_cmd_entry(ctsio, NULL);
2248	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2249		mtx_unlock(&lun->lun_lock);
2250		goto badjuju;
2251	}
2252
2253	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2254	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2255
2256	/*
2257	 * Every I/O goes into the OOA queue for a
2258	 * particular LUN, and stays there until completion.
2259	 */
2260#ifdef CTL_TIME_IO
2261	if (TAILQ_EMPTY(&lun->ooa_queue))
2262		lun->idle_time += getsbinuptime() - lun->last_busy;
2263#endif
2264	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2265
2266	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2267		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2268		 ooa_links))) {
2269	case CTL_ACTION_BLOCK:
2270		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2271		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2272				  blocked_links);
2273		mtx_unlock(&lun->lun_lock);
2274		break;
2275	case CTL_ACTION_PASS:
2276	case CTL_ACTION_SKIP:
2277		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2278			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2279			ctl_enqueue_rtr((union ctl_io *)ctsio);
2280			mtx_unlock(&lun->lun_lock);
2281		} else {
2282			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2283			mtx_unlock(&lun->lun_lock);
2284
2285			/* send msg back to other side */
2286			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2287			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2288			msg_info.hdr.msg_type = CTL_MSG_R2R;
2289			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2290			    sizeof(msg_info.hdr), M_WAITOK);
2291		}
2292		break;
2293	case CTL_ACTION_OVERLAP:
2294		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2295		mtx_unlock(&lun->lun_lock);
2296		ctl_set_overlapped_cmd(ctsio);
2297		goto badjuju;
2298	case CTL_ACTION_OVERLAP_TAG:
2299		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2300		mtx_unlock(&lun->lun_lock);
2301		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2302		goto badjuju;
2303	case CTL_ACTION_ERROR:
2304	default:
2305		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2306		mtx_unlock(&lun->lun_lock);
2307
2308		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2309					 /*retry_count*/ 0);
2310badjuju:
2311		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2312		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2313		msg_info.hdr.serializing_sc = NULL;
2314		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2315		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2316		    sizeof(msg_info.scsi), M_WAITOK);
2317		retval = 1;
2318		break;
2319	}
2320	return (retval);
2321}
2322
2323/*
2324 * Returns 0 for success, errno for failure.
2325 */
2326static void
2327ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2328		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2329{
2330	union ctl_io *io;
2331
2332	mtx_lock(&lun->lun_lock);
2333	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2334	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2335	     ooa_links)) {
2336		struct ctl_ooa_entry *entry;
2337
2338		/*
2339		 * If we've got more than we can fit, just count the
2340		 * remaining entries.
2341		 */
2342		if (*cur_fill_num >= ooa_hdr->alloc_num)
2343			continue;
2344
2345		entry = &kern_entries[*cur_fill_num];
2346
2347		entry->tag_num = io->scsiio.tag_num;
2348		entry->lun_num = lun->lun;
2349#ifdef CTL_TIME_IO
2350		entry->start_bt = io->io_hdr.start_bt;
2351#endif
2352		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2353		entry->cdb_len = io->scsiio.cdb_len;
2354		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2355			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2356
2357		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2358			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2359
2360		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2361			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2362
2363		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2364			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2365
2366		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2367			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2368	}
2369	mtx_unlock(&lun->lun_lock);
2370}
2371
2372static void *
2373ctl_copyin_alloc(void *user_addr, unsigned int len, char *error_str,
2374		 size_t error_str_len)
2375{
2376	void *kptr;
2377
2378	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2379
2380	if (copyin(user_addr, kptr, len) != 0) {
2381		snprintf(error_str, error_str_len, "Error copying %d bytes "
2382			 "from user address %p to kernel address %p", len,
2383			 user_addr, kptr);
2384		free(kptr, M_CTL);
2385		return (NULL);
2386	}
2387
2388	return (kptr);
2389}
2390
2391static void
2392ctl_free_args(int num_args, struct ctl_be_arg *args)
2393{
2394	int i;
2395
2396	if (args == NULL)
2397		return;
2398
2399	for (i = 0; i < num_args; i++) {
2400		free(args[i].kname, M_CTL);
2401		free(args[i].kvalue, M_CTL);
2402	}
2403
2404	free(args, M_CTL);
2405}
2406
2407static struct ctl_be_arg *
2408ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2409		char *error_str, size_t error_str_len)
2410{
2411	struct ctl_be_arg *args;
2412	int i;
2413
2414	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2415				error_str, error_str_len);
2416
2417	if (args == NULL)
2418		goto bailout;
2419
2420	for (i = 0; i < num_args; i++) {
2421		args[i].kname = NULL;
2422		args[i].kvalue = NULL;
2423	}
2424
2425	for (i = 0; i < num_args; i++) {
2426		uint8_t *tmpptr;
2427
2428		if (args[i].namelen == 0) {
2429			snprintf(error_str, error_str_len, "Argument %d "
2430				 "name length is zero", i);
2431			goto bailout;
2432		}
2433
2434		args[i].kname = ctl_copyin_alloc(args[i].name,
2435			args[i].namelen, error_str, error_str_len);
2436		if (args[i].kname == NULL)
2437			goto bailout;
2438
2439		if (args[i].kname[args[i].namelen - 1] != '\0') {
2440			snprintf(error_str, error_str_len, "Argument %d "
2441				 "name is not NUL-terminated", i);
2442			goto bailout;
2443		}
2444
2445		if (args[i].flags & CTL_BEARG_RD) {
2446			if (args[i].vallen == 0) {
2447				snprintf(error_str, error_str_len, "Argument %d "
2448					 "value length is zero", i);
2449				goto bailout;
2450			}
2451
2452			tmpptr = ctl_copyin_alloc(args[i].value,
2453				args[i].vallen, error_str, error_str_len);
2454			if (tmpptr == NULL)
2455				goto bailout;
2456
2457			if ((args[i].flags & CTL_BEARG_ASCII)
2458			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2459				snprintf(error_str, error_str_len, "Argument "
2460				    "%d value is not NUL-terminated", i);
2461				free(tmpptr, M_CTL);
2462				goto bailout;
2463			}
2464			args[i].kvalue = tmpptr;
2465		} else {
2466			args[i].kvalue = malloc(args[i].vallen,
2467			    M_CTL, M_WAITOK | M_ZERO);
2468		}
2469	}
2470
2471	return (args);
2472bailout:
2473
2474	ctl_free_args(num_args, args);
2475
2476	return (NULL);
2477}
2478
2479static void
2480ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2481{
2482	int i;
2483
2484	for (i = 0; i < num_args; i++) {
2485		if (args[i].flags & CTL_BEARG_WR)
2486			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2487	}
2488}
2489
2490/*
2491 * Escape characters that are illegal or not recommended in XML.
2492 */
2493int
2494ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2495{
2496	char *end = str + size;
2497	int retval;
2498
2499	retval = 0;
2500
2501	for (; *str && str < end; str++) {
2502		switch (*str) {
2503		case '&':
2504			retval = sbuf_printf(sb, "&amp;");
2505			break;
2506		case '>':
2507			retval = sbuf_printf(sb, "&gt;");
2508			break;
2509		case '<':
2510			retval = sbuf_printf(sb, "&lt;");
2511			break;
2512		default:
2513			retval = sbuf_putc(sb, *str);
2514			break;
2515		}
2516
2517		if (retval != 0)
2518			break;
2519
2520	}
2521
2522	return (retval);
2523}
2524
2525static void
2526ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2527{
2528	struct scsi_vpd_id_descriptor *desc;
2529	int i;
2530
2531	if (id == NULL || id->len < 4)
2532		return;
2533	desc = (struct scsi_vpd_id_descriptor *)id->data;
2534	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2535	case SVPD_ID_TYPE_T10:
2536		sbuf_printf(sb, "t10.");
2537		break;
2538	case SVPD_ID_TYPE_EUI64:
2539		sbuf_printf(sb, "eui.");
2540		break;
2541	case SVPD_ID_TYPE_NAA:
2542		sbuf_printf(sb, "naa.");
2543		break;
2544	case SVPD_ID_TYPE_SCSI_NAME:
2545		break;
2546	}
2547	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2548	case SVPD_ID_CODESET_BINARY:
2549		for (i = 0; i < desc->length; i++)
2550			sbuf_printf(sb, "%02x", desc->identifier[i]);
2551		break;
2552	case SVPD_ID_CODESET_ASCII:
2553		sbuf_printf(sb, "%.*s", (int)desc->length,
2554		    (char *)desc->identifier);
2555		break;
2556	case SVPD_ID_CODESET_UTF8:
2557		sbuf_printf(sb, "%s", (char *)desc->identifier);
2558		break;
2559	}
2560}
2561
2562static int
2563ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2564	  struct thread *td)
2565{
2566	struct ctl_softc *softc = dev->si_drv1;
2567	struct ctl_lun *lun;
2568	int retval;
2569
2570	retval = 0;
2571
2572	switch (cmd) {
2573	case CTL_IO:
2574		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2575		break;
2576	case CTL_ENABLE_PORT:
2577	case CTL_DISABLE_PORT:
2578	case CTL_SET_PORT_WWNS: {
2579		struct ctl_port *port;
2580		struct ctl_port_entry *entry;
2581
2582		entry = (struct ctl_port_entry *)addr;
2583
2584		mtx_lock(&softc->ctl_lock);
2585		STAILQ_FOREACH(port, &softc->port_list, links) {
2586			int action, done;
2587
2588			if (port->targ_port < softc->port_min ||
2589			    port->targ_port >= softc->port_max)
2590				continue;
2591
2592			action = 0;
2593			done = 0;
2594			if ((entry->port_type == CTL_PORT_NONE)
2595			 && (entry->targ_port == port->targ_port)) {
2596				/*
2597				 * If the user only wants to enable or
2598				 * disable or set WWNs on a specific port,
2599				 * do the operation and we're done.
2600				 */
2601				action = 1;
2602				done = 1;
2603			} else if (entry->port_type & port->port_type) {
2604				/*
2605				 * Compare the user's type mask with the
2606				 * particular frontend type to see if we
2607				 * have a match.
2608				 */
2609				action = 1;
2610				done = 0;
2611
2612				/*
2613				 * Make sure the user isn't trying to set
2614				 * WWNs on multiple ports at the same time.
2615				 */
2616				if (cmd == CTL_SET_PORT_WWNS) {
2617					printf("%s: Can't set WWNs on "
2618					       "multiple ports\n", __func__);
2619					retval = EINVAL;
2620					break;
2621				}
2622			}
2623			if (action == 0)
2624				continue;
2625
2626			/*
2627			 * XXX KDM we have to drop the lock here, because
2628			 * the online/offline operations can potentially
2629			 * block.  We need to reference count the frontends
2630			 * so they can't go away,
2631			 */
2632			if (cmd == CTL_ENABLE_PORT) {
2633				mtx_unlock(&softc->ctl_lock);
2634				ctl_port_online(port);
2635				mtx_lock(&softc->ctl_lock);
2636			} else if (cmd == CTL_DISABLE_PORT) {
2637				mtx_unlock(&softc->ctl_lock);
2638				ctl_port_offline(port);
2639				mtx_lock(&softc->ctl_lock);
2640			} else if (cmd == CTL_SET_PORT_WWNS) {
2641				ctl_port_set_wwns(port,
2642				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2643				    1 : 0, entry->wwnn,
2644				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2645				    1 : 0, entry->wwpn);
2646			}
2647			if (done != 0)
2648				break;
2649		}
2650		mtx_unlock(&softc->ctl_lock);
2651		break;
2652	}
2653	case CTL_GET_OOA: {
2654		struct ctl_ooa *ooa_hdr;
2655		struct ctl_ooa_entry *entries;
2656		uint32_t cur_fill_num;
2657
2658		ooa_hdr = (struct ctl_ooa *)addr;
2659
2660		if ((ooa_hdr->alloc_len == 0)
2661		 || (ooa_hdr->alloc_num == 0)) {
2662			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2663			       "must be non-zero\n", __func__,
2664			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2665			retval = EINVAL;
2666			break;
2667		}
2668
2669		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2670		    sizeof(struct ctl_ooa_entry))) {
2671			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2672			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2673			       __func__, ooa_hdr->alloc_len,
2674			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2675			retval = EINVAL;
2676			break;
2677		}
2678
2679		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2680		if (entries == NULL) {
2681			printf("%s: could not allocate %d bytes for OOA "
2682			       "dump\n", __func__, ooa_hdr->alloc_len);
2683			retval = ENOMEM;
2684			break;
2685		}
2686
2687		mtx_lock(&softc->ctl_lock);
2688		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2689		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2690		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2691			mtx_unlock(&softc->ctl_lock);
2692			free(entries, M_CTL);
2693			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2694			       __func__, (uintmax_t)ooa_hdr->lun_num);
2695			retval = EINVAL;
2696			break;
2697		}
2698
2699		cur_fill_num = 0;
2700
2701		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2702			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2703				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2704				    ooa_hdr, entries);
2705			}
2706		} else {
2707			lun = softc->ctl_luns[ooa_hdr->lun_num];
2708			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2709			    entries);
2710		}
2711		mtx_unlock(&softc->ctl_lock);
2712
2713		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2714		ooa_hdr->fill_len = ooa_hdr->fill_num *
2715			sizeof(struct ctl_ooa_entry);
2716		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2717		if (retval != 0) {
2718			printf("%s: error copying out %d bytes for OOA dump\n",
2719			       __func__, ooa_hdr->fill_len);
2720		}
2721
2722		getbinuptime(&ooa_hdr->cur_bt);
2723
2724		if (cur_fill_num > ooa_hdr->alloc_num) {
2725			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2726			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2727		} else {
2728			ooa_hdr->dropped_num = 0;
2729			ooa_hdr->status = CTL_OOA_OK;
2730		}
2731
2732		free(entries, M_CTL);
2733		break;
2734	}
2735	case CTL_DELAY_IO: {
2736		struct ctl_io_delay_info *delay_info;
2737
2738		delay_info = (struct ctl_io_delay_info *)addr;
2739
2740#ifdef CTL_IO_DELAY
2741		mtx_lock(&softc->ctl_lock);
2742
2743		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2744		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2745			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2746		} else {
2747			lun = softc->ctl_luns[delay_info->lun_id];
2748			mtx_lock(&lun->lun_lock);
2749
2750			delay_info->status = CTL_DELAY_STATUS_OK;
2751
2752			switch (delay_info->delay_type) {
2753			case CTL_DELAY_TYPE_CONT:
2754				break;
2755			case CTL_DELAY_TYPE_ONESHOT:
2756				break;
2757			default:
2758				delay_info->status =
2759					CTL_DELAY_STATUS_INVALID_TYPE;
2760				break;
2761			}
2762
2763			switch (delay_info->delay_loc) {
2764			case CTL_DELAY_LOC_DATAMOVE:
2765				lun->delay_info.datamove_type =
2766					delay_info->delay_type;
2767				lun->delay_info.datamove_delay =
2768					delay_info->delay_secs;
2769				break;
2770			case CTL_DELAY_LOC_DONE:
2771				lun->delay_info.done_type =
2772					delay_info->delay_type;
2773				lun->delay_info.done_delay =
2774					delay_info->delay_secs;
2775				break;
2776			default:
2777				delay_info->status =
2778					CTL_DELAY_STATUS_INVALID_LOC;
2779				break;
2780			}
2781			mtx_unlock(&lun->lun_lock);
2782		}
2783
2784		mtx_unlock(&softc->ctl_lock);
2785#else
2786		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2787#endif /* CTL_IO_DELAY */
2788		break;
2789	}
2790	case CTL_GETSTATS: {
2791		struct ctl_stats *stats;
2792		int i;
2793
2794		stats = (struct ctl_stats *)addr;
2795
2796		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2797		     stats->alloc_len) {
2798			stats->status = CTL_SS_NEED_MORE_SPACE;
2799			stats->num_luns = softc->num_luns;
2800			break;
2801		}
2802		/*
2803		 * XXX KDM no locking here.  If the LUN list changes,
2804		 * things can blow up.
2805		 */
2806		i = 0;
2807		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2808			retval = copyout(&lun->stats, &stats->lun_stats[i++],
2809					 sizeof(lun->stats));
2810			if (retval != 0)
2811				break;
2812		}
2813		stats->num_luns = softc->num_luns;
2814		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2815				 softc->num_luns;
2816		stats->status = CTL_SS_OK;
2817#ifdef CTL_TIME_IO
2818		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2819#else
2820		stats->flags = CTL_STATS_FLAG_NONE;
2821#endif
2822		getnanouptime(&stats->timestamp);
2823		break;
2824	}
2825	case CTL_ERROR_INJECT: {
2826		struct ctl_error_desc *err_desc, *new_err_desc;
2827
2828		err_desc = (struct ctl_error_desc *)addr;
2829
2830		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2831				      M_WAITOK | M_ZERO);
2832		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2833
2834		mtx_lock(&softc->ctl_lock);
2835		lun = softc->ctl_luns[err_desc->lun_id];
2836		if (lun == NULL) {
2837			mtx_unlock(&softc->ctl_lock);
2838			free(new_err_desc, M_CTL);
2839			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2840			       __func__, (uintmax_t)err_desc->lun_id);
2841			retval = EINVAL;
2842			break;
2843		}
2844		mtx_lock(&lun->lun_lock);
2845		mtx_unlock(&softc->ctl_lock);
2846
2847		/*
2848		 * We could do some checking here to verify the validity
2849		 * of the request, but given the complexity of error
2850		 * injection requests, the checking logic would be fairly
2851		 * complex.
2852		 *
2853		 * For now, if the request is invalid, it just won't get
2854		 * executed and might get deleted.
2855		 */
2856		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2857
2858		/*
2859		 * XXX KDM check to make sure the serial number is unique,
2860		 * in case we somehow manage to wrap.  That shouldn't
2861		 * happen for a very long time, but it's the right thing to
2862		 * do.
2863		 */
2864		new_err_desc->serial = lun->error_serial;
2865		err_desc->serial = lun->error_serial;
2866		lun->error_serial++;
2867
2868		mtx_unlock(&lun->lun_lock);
2869		break;
2870	}
2871	case CTL_ERROR_INJECT_DELETE: {
2872		struct ctl_error_desc *delete_desc, *desc, *desc2;
2873		int delete_done;
2874
2875		delete_desc = (struct ctl_error_desc *)addr;
2876		delete_done = 0;
2877
2878		mtx_lock(&softc->ctl_lock);
2879		lun = softc->ctl_luns[delete_desc->lun_id];
2880		if (lun == NULL) {
2881			mtx_unlock(&softc->ctl_lock);
2882			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2883			       __func__, (uintmax_t)delete_desc->lun_id);
2884			retval = EINVAL;
2885			break;
2886		}
2887		mtx_lock(&lun->lun_lock);
2888		mtx_unlock(&softc->ctl_lock);
2889		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2890			if (desc->serial != delete_desc->serial)
2891				continue;
2892
2893			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2894				      links);
2895			free(desc, M_CTL);
2896			delete_done = 1;
2897		}
2898		mtx_unlock(&lun->lun_lock);
2899		if (delete_done == 0) {
2900			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2901			       "error serial %ju on LUN %u\n", __func__,
2902			       delete_desc->serial, delete_desc->lun_id);
2903			retval = EINVAL;
2904			break;
2905		}
2906		break;
2907	}
2908	case CTL_DUMP_STRUCTS: {
2909		int j, k;
2910		struct ctl_port *port;
2911		struct ctl_frontend *fe;
2912
2913		mtx_lock(&softc->ctl_lock);
2914		printf("CTL Persistent Reservation information start:\n");
2915		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2916			mtx_lock(&lun->lun_lock);
2917			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2918				mtx_unlock(&lun->lun_lock);
2919				continue;
2920			}
2921
2922			for (j = 0; j < CTL_MAX_PORTS; j++) {
2923				if (lun->pr_keys[j] == NULL)
2924					continue;
2925				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2926					if (lun->pr_keys[j][k] == 0)
2927						continue;
2928					printf("  LUN %ju port %d iid %d key "
2929					       "%#jx\n", lun->lun, j, k,
2930					       (uintmax_t)lun->pr_keys[j][k]);
2931				}
2932			}
2933			mtx_unlock(&lun->lun_lock);
2934		}
2935		printf("CTL Persistent Reservation information end\n");
2936		printf("CTL Ports:\n");
2937		STAILQ_FOREACH(port, &softc->port_list, links) {
2938			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2939			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2940			       port->frontend->name, port->port_type,
2941			       port->physical_port, port->virtual_port,
2942			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2943			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2944				if (port->wwpn_iid[j].in_use == 0 &&
2945				    port->wwpn_iid[j].wwpn == 0 &&
2946				    port->wwpn_iid[j].name == NULL)
2947					continue;
2948
2949				printf("    iid %u use %d WWPN %#jx '%s'\n",
2950				    j, port->wwpn_iid[j].in_use,
2951				    (uintmax_t)port->wwpn_iid[j].wwpn,
2952				    port->wwpn_iid[j].name);
2953			}
2954		}
2955		printf("CTL Port information end\n");
2956		mtx_unlock(&softc->ctl_lock);
2957		/*
2958		 * XXX KDM calling this without a lock.  We'd likely want
2959		 * to drop the lock before calling the frontend's dump
2960		 * routine anyway.
2961		 */
2962		printf("CTL Frontends:\n");
2963		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2964			printf("  Frontend '%s'\n", fe->name);
2965			if (fe->fe_dump != NULL)
2966				fe->fe_dump();
2967		}
2968		printf("CTL Frontend information end\n");
2969		break;
2970	}
2971	case CTL_LUN_REQ: {
2972		struct ctl_lun_req *lun_req;
2973		struct ctl_backend_driver *backend;
2974
2975		lun_req = (struct ctl_lun_req *)addr;
2976
2977		backend = ctl_backend_find(lun_req->backend);
2978		if (backend == NULL) {
2979			lun_req->status = CTL_LUN_ERROR;
2980			snprintf(lun_req->error_str,
2981				 sizeof(lun_req->error_str),
2982				 "Backend \"%s\" not found.",
2983				 lun_req->backend);
2984			break;
2985		}
2986		if (lun_req->num_be_args > 0) {
2987			lun_req->kern_be_args = ctl_copyin_args(
2988				lun_req->num_be_args,
2989				lun_req->be_args,
2990				lun_req->error_str,
2991				sizeof(lun_req->error_str));
2992			if (lun_req->kern_be_args == NULL) {
2993				lun_req->status = CTL_LUN_ERROR;
2994				break;
2995			}
2996		}
2997
2998		retval = backend->ioctl(dev, cmd, addr, flag, td);
2999
3000		if (lun_req->num_be_args > 0) {
3001			ctl_copyout_args(lun_req->num_be_args,
3002				      lun_req->kern_be_args);
3003			ctl_free_args(lun_req->num_be_args,
3004				      lun_req->kern_be_args);
3005		}
3006		break;
3007	}
3008	case CTL_LUN_LIST: {
3009		struct sbuf *sb;
3010		struct ctl_lun_list *list;
3011		struct ctl_option *opt;
3012
3013		list = (struct ctl_lun_list *)addr;
3014
3015		/*
3016		 * Allocate a fixed length sbuf here, based on the length
3017		 * of the user's buffer.  We could allocate an auto-extending
3018		 * buffer, and then tell the user how much larger our
3019		 * amount of data is than his buffer, but that presents
3020		 * some problems:
3021		 *
3022		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3023		 *     we can't hold a lock while calling them with an
3024		 *     auto-extending buffer.
3025 		 *
3026		 * 2.  There is not currently a LUN reference counting
3027		 *     mechanism, outside of outstanding transactions on
3028		 *     the LUN's OOA queue.  So a LUN could go away on us
3029		 *     while we're getting the LUN number, backend-specific
3030		 *     information, etc.  Thus, given the way things
3031		 *     currently work, we need to hold the CTL lock while
3032		 *     grabbing LUN information.
3033		 *
3034		 * So, from the user's standpoint, the best thing to do is
3035		 * allocate what he thinks is a reasonable buffer length,
3036		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3037		 * double the buffer length and try again.  (And repeat
3038		 * that until he succeeds.)
3039		 */
3040		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3041		if (sb == NULL) {
3042			list->status = CTL_LUN_LIST_ERROR;
3043			snprintf(list->error_str, sizeof(list->error_str),
3044				 "Unable to allocate %d bytes for LUN list",
3045				 list->alloc_len);
3046			break;
3047		}
3048
3049		sbuf_printf(sb, "<ctllunlist>\n");
3050
3051		mtx_lock(&softc->ctl_lock);
3052		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3053			mtx_lock(&lun->lun_lock);
3054			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3055					     (uintmax_t)lun->lun);
3056
3057			/*
3058			 * Bail out as soon as we see that we've overfilled
3059			 * the buffer.
3060			 */
3061			if (retval != 0)
3062				break;
3063
3064			retval = sbuf_printf(sb, "\t<backend_type>%s"
3065					     "</backend_type>\n",
3066					     (lun->backend == NULL) ?  "none" :
3067					     lun->backend->name);
3068
3069			if (retval != 0)
3070				break;
3071
3072			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3073					     lun->be_lun->lun_type);
3074
3075			if (retval != 0)
3076				break;
3077
3078			if (lun->backend == NULL) {
3079				retval = sbuf_printf(sb, "</lun>\n");
3080				if (retval != 0)
3081					break;
3082				continue;
3083			}
3084
3085			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3086					     (lun->be_lun->maxlba > 0) ?
3087					     lun->be_lun->maxlba + 1 : 0);
3088
3089			if (retval != 0)
3090				break;
3091
3092			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3093					     lun->be_lun->blocksize);
3094
3095			if (retval != 0)
3096				break;
3097
3098			retval = sbuf_printf(sb, "\t<serial_number>");
3099
3100			if (retval != 0)
3101				break;
3102
3103			retval = ctl_sbuf_printf_esc(sb,
3104			    lun->be_lun->serial_num,
3105			    sizeof(lun->be_lun->serial_num));
3106
3107			if (retval != 0)
3108				break;
3109
3110			retval = sbuf_printf(sb, "</serial_number>\n");
3111
3112			if (retval != 0)
3113				break;
3114
3115			retval = sbuf_printf(sb, "\t<device_id>");
3116
3117			if (retval != 0)
3118				break;
3119
3120			retval = ctl_sbuf_printf_esc(sb,
3121			    lun->be_lun->device_id,
3122			    sizeof(lun->be_lun->device_id));
3123
3124			if (retval != 0)
3125				break;
3126
3127			retval = sbuf_printf(sb, "</device_id>\n");
3128
3129			if (retval != 0)
3130				break;
3131
3132			if (lun->backend->lun_info != NULL) {
3133				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3134				if (retval != 0)
3135					break;
3136			}
3137			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3138				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3139				    opt->name, opt->value, opt->name);
3140				if (retval != 0)
3141					break;
3142			}
3143
3144			retval = sbuf_printf(sb, "</lun>\n");
3145
3146			if (retval != 0)
3147				break;
3148			mtx_unlock(&lun->lun_lock);
3149		}
3150		if (lun != NULL)
3151			mtx_unlock(&lun->lun_lock);
3152		mtx_unlock(&softc->ctl_lock);
3153
3154		if ((retval != 0)
3155		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3156			retval = 0;
3157			sbuf_delete(sb);
3158			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3159			snprintf(list->error_str, sizeof(list->error_str),
3160				 "Out of space, %d bytes is too small",
3161				 list->alloc_len);
3162			break;
3163		}
3164
3165		sbuf_finish(sb);
3166
3167		retval = copyout(sbuf_data(sb), list->lun_xml,
3168				 sbuf_len(sb) + 1);
3169
3170		list->fill_len = sbuf_len(sb) + 1;
3171		list->status = CTL_LUN_LIST_OK;
3172		sbuf_delete(sb);
3173		break;
3174	}
3175	case CTL_ISCSI: {
3176		struct ctl_iscsi *ci;
3177		struct ctl_frontend *fe;
3178
3179		ci = (struct ctl_iscsi *)addr;
3180
3181		fe = ctl_frontend_find("iscsi");
3182		if (fe == NULL) {
3183			ci->status = CTL_ISCSI_ERROR;
3184			snprintf(ci->error_str, sizeof(ci->error_str),
3185			    "Frontend \"iscsi\" not found.");
3186			break;
3187		}
3188
3189		retval = fe->ioctl(dev, cmd, addr, flag, td);
3190		break;
3191	}
3192	case CTL_PORT_REQ: {
3193		struct ctl_req *req;
3194		struct ctl_frontend *fe;
3195
3196		req = (struct ctl_req *)addr;
3197
3198		fe = ctl_frontend_find(req->driver);
3199		if (fe == NULL) {
3200			req->status = CTL_LUN_ERROR;
3201			snprintf(req->error_str, sizeof(req->error_str),
3202			    "Frontend \"%s\" not found.", req->driver);
3203			break;
3204		}
3205		if (req->num_args > 0) {
3206			req->kern_args = ctl_copyin_args(req->num_args,
3207			    req->args, req->error_str, sizeof(req->error_str));
3208			if (req->kern_args == NULL) {
3209				req->status = CTL_LUN_ERROR;
3210				break;
3211			}
3212		}
3213
3214		if (fe->ioctl)
3215			retval = fe->ioctl(dev, cmd, addr, flag, td);
3216		else
3217			retval = ENODEV;
3218
3219		if (req->num_args > 0) {
3220			ctl_copyout_args(req->num_args, req->kern_args);
3221			ctl_free_args(req->num_args, req->kern_args);
3222		}
3223		break;
3224	}
3225	case CTL_PORT_LIST: {
3226		struct sbuf *sb;
3227		struct ctl_port *port;
3228		struct ctl_lun_list *list;
3229		struct ctl_option *opt;
3230		int j;
3231		uint32_t plun;
3232
3233		list = (struct ctl_lun_list *)addr;
3234
3235		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3236		if (sb == NULL) {
3237			list->status = CTL_LUN_LIST_ERROR;
3238			snprintf(list->error_str, sizeof(list->error_str),
3239				 "Unable to allocate %d bytes for LUN list",
3240				 list->alloc_len);
3241			break;
3242		}
3243
3244		sbuf_printf(sb, "<ctlportlist>\n");
3245
3246		mtx_lock(&softc->ctl_lock);
3247		STAILQ_FOREACH(port, &softc->port_list, links) {
3248			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3249					     (uintmax_t)port->targ_port);
3250
3251			/*
3252			 * Bail out as soon as we see that we've overfilled
3253			 * the buffer.
3254			 */
3255			if (retval != 0)
3256				break;
3257
3258			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3259			    "</frontend_type>\n", port->frontend->name);
3260			if (retval != 0)
3261				break;
3262
3263			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3264					     port->port_type);
3265			if (retval != 0)
3266				break;
3267
3268			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3269			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3270			if (retval != 0)
3271				break;
3272
3273			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3274			    port->port_name);
3275			if (retval != 0)
3276				break;
3277
3278			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3279			    port->physical_port);
3280			if (retval != 0)
3281				break;
3282
3283			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3284			    port->virtual_port);
3285			if (retval != 0)
3286				break;
3287
3288			if (port->target_devid != NULL) {
3289				sbuf_printf(sb, "\t<target>");
3290				ctl_id_sbuf(port->target_devid, sb);
3291				sbuf_printf(sb, "</target>\n");
3292			}
3293
3294			if (port->port_devid != NULL) {
3295				sbuf_printf(sb, "\t<port>");
3296				ctl_id_sbuf(port->port_devid, sb);
3297				sbuf_printf(sb, "</port>\n");
3298			}
3299
3300			if (port->port_info != NULL) {
3301				retval = port->port_info(port->onoff_arg, sb);
3302				if (retval != 0)
3303					break;
3304			}
3305			STAILQ_FOREACH(opt, &port->options, links) {
3306				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3307				    opt->name, opt->value, opt->name);
3308				if (retval != 0)
3309					break;
3310			}
3311
3312			if (port->lun_map != NULL) {
3313				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3314				for (j = 0; j < CTL_MAX_LUNS; j++) {
3315					plun = ctl_lun_map_from_port(port, j);
3316					if (plun == UINT32_MAX)
3317						continue;
3318					sbuf_printf(sb,
3319					    "\t<lun id=\"%u\">%u</lun>\n",
3320					    j, plun);
3321				}
3322			}
3323
3324			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3325				if (port->wwpn_iid[j].in_use == 0 ||
3326				    (port->wwpn_iid[j].wwpn == 0 &&
3327				     port->wwpn_iid[j].name == NULL))
3328					continue;
3329
3330				if (port->wwpn_iid[j].name != NULL)
3331					retval = sbuf_printf(sb,
3332					    "\t<initiator id=\"%u\">%s</initiator>\n",
3333					    j, port->wwpn_iid[j].name);
3334				else
3335					retval = sbuf_printf(sb,
3336					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3337					    j, port->wwpn_iid[j].wwpn);
3338				if (retval != 0)
3339					break;
3340			}
3341			if (retval != 0)
3342				break;
3343
3344			retval = sbuf_printf(sb, "</targ_port>\n");
3345			if (retval != 0)
3346				break;
3347		}
3348		mtx_unlock(&softc->ctl_lock);
3349
3350		if ((retval != 0)
3351		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3352			retval = 0;
3353			sbuf_delete(sb);
3354			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3355			snprintf(list->error_str, sizeof(list->error_str),
3356				 "Out of space, %d bytes is too small",
3357				 list->alloc_len);
3358			break;
3359		}
3360
3361		sbuf_finish(sb);
3362
3363		retval = copyout(sbuf_data(sb), list->lun_xml,
3364				 sbuf_len(sb) + 1);
3365
3366		list->fill_len = sbuf_len(sb) + 1;
3367		list->status = CTL_LUN_LIST_OK;
3368		sbuf_delete(sb);
3369		break;
3370	}
3371	case CTL_LUN_MAP: {
3372		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3373		struct ctl_port *port;
3374
3375		mtx_lock(&softc->ctl_lock);
3376		if (lm->port < softc->port_min ||
3377		    lm->port >= softc->port_max ||
3378		    (port = softc->ctl_ports[lm->port]) == NULL) {
3379			mtx_unlock(&softc->ctl_lock);
3380			return (ENXIO);
3381		}
3382		if (port->status & CTL_PORT_STATUS_ONLINE) {
3383			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3384				if (ctl_lun_map_to_port(port, lun->lun) ==
3385				    UINT32_MAX)
3386					continue;
3387				mtx_lock(&lun->lun_lock);
3388				ctl_est_ua_port(lun, lm->port, -1,
3389				    CTL_UA_LUN_CHANGE);
3390				mtx_unlock(&lun->lun_lock);
3391			}
3392		}
3393		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3394		if (lm->plun < CTL_MAX_LUNS) {
3395			if (lm->lun == UINT32_MAX)
3396				retval = ctl_lun_map_unset(port, lm->plun);
3397			else if (lm->lun < CTL_MAX_LUNS &&
3398			    softc->ctl_luns[lm->lun] != NULL)
3399				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3400			else
3401				return (ENXIO);
3402		} else if (lm->plun == UINT32_MAX) {
3403			if (lm->lun == UINT32_MAX)
3404				retval = ctl_lun_map_deinit(port);
3405			else
3406				retval = ctl_lun_map_init(port);
3407		} else
3408			return (ENXIO);
3409		if (port->status & CTL_PORT_STATUS_ONLINE)
3410			ctl_isc_announce_port(port);
3411		break;
3412	}
3413	default: {
3414		/* XXX KDM should we fix this? */
3415#if 0
3416		struct ctl_backend_driver *backend;
3417		unsigned int type;
3418		int found;
3419
3420		found = 0;
3421
3422		/*
3423		 * We encode the backend type as the ioctl type for backend
3424		 * ioctls.  So parse it out here, and then search for a
3425		 * backend of this type.
3426		 */
3427		type = _IOC_TYPE(cmd);
3428
3429		STAILQ_FOREACH(backend, &softc->be_list, links) {
3430			if (backend->type == type) {
3431				found = 1;
3432				break;
3433			}
3434		}
3435		if (found == 0) {
3436			printf("ctl: unknown ioctl command %#lx or backend "
3437			       "%d\n", cmd, type);
3438			retval = EINVAL;
3439			break;
3440		}
3441		retval = backend->ioctl(dev, cmd, addr, flag, td);
3442#endif
3443		retval = ENOTTY;
3444		break;
3445	}
3446	}
3447	return (retval);
3448}
3449
3450uint32_t
3451ctl_get_initindex(struct ctl_nexus *nexus)
3452{
3453	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3454}
3455
3456int
3457ctl_lun_map_init(struct ctl_port *port)
3458{
3459	struct ctl_softc *softc = port->ctl_softc;
3460	struct ctl_lun *lun;
3461	uint32_t i;
3462
3463	if (port->lun_map == NULL)
3464		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3465		    M_CTL, M_NOWAIT);
3466	if (port->lun_map == NULL)
3467		return (ENOMEM);
3468	for (i = 0; i < CTL_MAX_LUNS; i++)
3469		port->lun_map[i] = UINT32_MAX;
3470	if (port->status & CTL_PORT_STATUS_ONLINE) {
3471		if (port->lun_disable != NULL) {
3472			STAILQ_FOREACH(lun, &softc->lun_list, links)
3473				port->lun_disable(port->targ_lun_arg, lun->lun);
3474		}
3475		ctl_isc_announce_port(port);
3476	}
3477	return (0);
3478}
3479
3480int
3481ctl_lun_map_deinit(struct ctl_port *port)
3482{
3483	struct ctl_softc *softc = port->ctl_softc;
3484	struct ctl_lun *lun;
3485
3486	if (port->lun_map == NULL)
3487		return (0);
3488	free(port->lun_map, M_CTL);
3489	port->lun_map = NULL;
3490	if (port->status & CTL_PORT_STATUS_ONLINE) {
3491		if (port->lun_enable != NULL) {
3492			STAILQ_FOREACH(lun, &softc->lun_list, links)
3493				port->lun_enable(port->targ_lun_arg, lun->lun);
3494		}
3495		ctl_isc_announce_port(port);
3496	}
3497	return (0);
3498}
3499
3500int
3501ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3502{
3503	int status;
3504	uint32_t old;
3505
3506	if (port->lun_map == NULL) {
3507		status = ctl_lun_map_init(port);
3508		if (status != 0)
3509			return (status);
3510	}
3511	old = port->lun_map[plun];
3512	port->lun_map[plun] = glun;
3513	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3514		if (port->lun_enable != NULL)
3515			port->lun_enable(port->targ_lun_arg, plun);
3516		ctl_isc_announce_port(port);
3517	}
3518	return (0);
3519}
3520
3521int
3522ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3523{
3524	uint32_t old;
3525
3526	if (port->lun_map == NULL)
3527		return (0);
3528	old = port->lun_map[plun];
3529	port->lun_map[plun] = UINT32_MAX;
3530	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3531		if (port->lun_disable != NULL)
3532			port->lun_disable(port->targ_lun_arg, plun);
3533		ctl_isc_announce_port(port);
3534	}
3535	return (0);
3536}
3537
3538uint32_t
3539ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3540{
3541
3542	if (port == NULL)
3543		return (UINT32_MAX);
3544	if (port->lun_map == NULL || lun_id == UINT32_MAX)
3545		return (lun_id);
3546	return (port->lun_map[lun_id]);
3547}
3548
3549uint32_t
3550ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3551{
3552	uint32_t i;
3553
3554	if (port == NULL)
3555		return (UINT32_MAX);
3556	if (port->lun_map == NULL)
3557		return (lun_id);
3558	for (i = 0; i < CTL_MAX_LUNS; i++) {
3559		if (port->lun_map[i] == lun_id)
3560			return (i);
3561	}
3562	return (UINT32_MAX);
3563}
3564
3565uint32_t
3566ctl_decode_lun(uint64_t encoded)
3567{
3568	uint8_t lun[8];
3569	uint32_t result = 0xffffffff;
3570
3571	be64enc(lun, encoded);
3572	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3573	case RPL_LUNDATA_ATYP_PERIPH:
3574		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3575		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3576			result = lun[1];
3577		break;
3578	case RPL_LUNDATA_ATYP_FLAT:
3579		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3580		    lun[6] == 0 && lun[7] == 0)
3581			result = ((lun[0] & 0x3f) << 8) + lun[1];
3582		break;
3583	case RPL_LUNDATA_ATYP_EXTLUN:
3584		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3585		case 0x02:
3586			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3587			case 0x00:
3588				result = lun[1];
3589				break;
3590			case 0x10:
3591				result = (lun[1] << 16) + (lun[2] << 8) +
3592				    lun[3];
3593				break;
3594			case 0x20:
3595				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3596					result = (lun[2] << 24) +
3597					    (lun[3] << 16) + (lun[4] << 8) +
3598					    lun[5];
3599				break;
3600			}
3601			break;
3602		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3603			result = 0xffffffff;
3604			break;
3605		}
3606		break;
3607	}
3608	return (result);
3609}
3610
3611uint64_t
3612ctl_encode_lun(uint32_t decoded)
3613{
3614	uint64_t l = decoded;
3615
3616	if (l <= 0xff)
3617		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3618	if (l <= 0x3fff)
3619		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3620	if (l <= 0xffffff)
3621		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3622		    (l << 32));
3623	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3624}
3625
3626static struct ctl_port *
3627ctl_io_port(struct ctl_io_hdr *io_hdr)
3628{
3629
3630	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3631}
3632
3633int
3634ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3635{
3636	int i;
3637
3638	for (i = first; i < last; i++) {
3639		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3640			return (i);
3641	}
3642	return (-1);
3643}
3644
3645int
3646ctl_set_mask(uint32_t *mask, uint32_t bit)
3647{
3648	uint32_t chunk, piece;
3649
3650	chunk = bit >> 5;
3651	piece = bit % (sizeof(uint32_t) * 8);
3652
3653	if ((mask[chunk] & (1 << piece)) != 0)
3654		return (-1);
3655	else
3656		mask[chunk] |= (1 << piece);
3657
3658	return (0);
3659}
3660
3661int
3662ctl_clear_mask(uint32_t *mask, uint32_t bit)
3663{
3664	uint32_t chunk, piece;
3665
3666	chunk = bit >> 5;
3667	piece = bit % (sizeof(uint32_t) * 8);
3668
3669	if ((mask[chunk] & (1 << piece)) == 0)
3670		return (-1);
3671	else
3672		mask[chunk] &= ~(1 << piece);
3673
3674	return (0);
3675}
3676
3677int
3678ctl_is_set(uint32_t *mask, uint32_t bit)
3679{
3680	uint32_t chunk, piece;
3681
3682	chunk = bit >> 5;
3683	piece = bit % (sizeof(uint32_t) * 8);
3684
3685	if ((mask[chunk] & (1 << piece)) == 0)
3686		return (0);
3687	else
3688		return (1);
3689}
3690
3691static uint64_t
3692ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3693{
3694	uint64_t *t;
3695
3696	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3697	if (t == NULL)
3698		return (0);
3699	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3700}
3701
3702static void
3703ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3704{
3705	uint64_t *t;
3706
3707	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3708	if (t == NULL)
3709		return;
3710	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3711}
3712
3713static void
3714ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3715{
3716	uint64_t *p;
3717	u_int i;
3718
3719	i = residx/CTL_MAX_INIT_PER_PORT;
3720	if (lun->pr_keys[i] != NULL)
3721		return;
3722	mtx_unlock(&lun->lun_lock);
3723	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3724	    M_WAITOK | M_ZERO);
3725	mtx_lock(&lun->lun_lock);
3726	if (lun->pr_keys[i] == NULL)
3727		lun->pr_keys[i] = p;
3728	else
3729		free(p, M_CTL);
3730}
3731
3732static void
3733ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3734{
3735	uint64_t *t;
3736
3737	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3738	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3739	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3740}
3741
3742/*
3743 * ctl_softc, pool_name, total_ctl_io are passed in.
3744 * npool is passed out.
3745 */
3746int
3747ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3748		uint32_t total_ctl_io, void **npool)
3749{
3750#ifdef IO_POOLS
3751	struct ctl_io_pool *pool;
3752
3753	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3754					    M_NOWAIT | M_ZERO);
3755	if (pool == NULL)
3756		return (ENOMEM);
3757
3758	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3759	pool->ctl_softc = ctl_softc;
3760	pool->zone = uma_zsecond_create(pool->name, NULL,
3761	    NULL, NULL, NULL, ctl_softc->io_zone);
3762	/* uma_prealloc(pool->zone, total_ctl_io); */
3763
3764	*npool = pool;
3765#else
3766	*npool = ctl_softc->io_zone;
3767#endif
3768	return (0);
3769}
3770
3771void
3772ctl_pool_free(struct ctl_io_pool *pool)
3773{
3774
3775	if (pool == NULL)
3776		return;
3777
3778#ifdef IO_POOLS
3779	uma_zdestroy(pool->zone);
3780	free(pool, M_CTL);
3781#endif
3782}
3783
3784union ctl_io *
3785ctl_alloc_io(void *pool_ref)
3786{
3787	union ctl_io *io;
3788#ifdef IO_POOLS
3789	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3790
3791	io = uma_zalloc(pool->zone, M_WAITOK);
3792#else
3793	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3794#endif
3795	if (io != NULL)
3796		io->io_hdr.pool = pool_ref;
3797	return (io);
3798}
3799
3800union ctl_io *
3801ctl_alloc_io_nowait(void *pool_ref)
3802{
3803	union ctl_io *io;
3804#ifdef IO_POOLS
3805	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3806
3807	io = uma_zalloc(pool->zone, M_NOWAIT);
3808#else
3809	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3810#endif
3811	if (io != NULL)
3812		io->io_hdr.pool = pool_ref;
3813	return (io);
3814}
3815
3816void
3817ctl_free_io(union ctl_io *io)
3818{
3819#ifdef IO_POOLS
3820	struct ctl_io_pool *pool;
3821#endif
3822
3823	if (io == NULL)
3824		return;
3825
3826#ifdef IO_POOLS
3827	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3828	uma_zfree(pool->zone, io);
3829#else
3830	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3831#endif
3832}
3833
3834void
3835ctl_zero_io(union ctl_io *io)
3836{
3837	void *pool_ref;
3838
3839	if (io == NULL)
3840		return;
3841
3842	/*
3843	 * May need to preserve linked list pointers at some point too.
3844	 */
3845	pool_ref = io->io_hdr.pool;
3846	memset(io, 0, sizeof(*io));
3847	io->io_hdr.pool = pool_ref;
3848}
3849
3850int
3851ctl_expand_number(const char *buf, uint64_t *num)
3852{
3853	char *endptr;
3854	uint64_t number;
3855	unsigned shift;
3856
3857	number = strtoq(buf, &endptr, 0);
3858
3859	switch (tolower((unsigned char)*endptr)) {
3860	case 'e':
3861		shift = 60;
3862		break;
3863	case 'p':
3864		shift = 50;
3865		break;
3866	case 't':
3867		shift = 40;
3868		break;
3869	case 'g':
3870		shift = 30;
3871		break;
3872	case 'm':
3873		shift = 20;
3874		break;
3875	case 'k':
3876		shift = 10;
3877		break;
3878	case 'b':
3879	case '\0': /* No unit. */
3880		*num = number;
3881		return (0);
3882	default:
3883		/* Unrecognized unit. */
3884		return (-1);
3885	}
3886
3887	if ((number << shift) >> shift != number) {
3888		/* Overflow */
3889		return (-1);
3890	}
3891	*num = number << shift;
3892	return (0);
3893}
3894
3895
3896/*
3897 * This routine could be used in the future to load default and/or saved
3898 * mode page parameters for a particuar lun.
3899 */
3900static int
3901ctl_init_page_index(struct ctl_lun *lun)
3902{
3903	int i, page_code;
3904	struct ctl_page_index *page_index;
3905	const char *value;
3906	uint64_t ival;
3907
3908	memcpy(&lun->mode_pages.index, page_index_template,
3909	       sizeof(page_index_template));
3910
3911	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3912
3913		page_index = &lun->mode_pages.index[i];
3914		if (lun->be_lun->lun_type == T_DIRECT &&
3915		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3916			continue;
3917		if (lun->be_lun->lun_type == T_PROCESSOR &&
3918		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3919			continue;
3920		if (lun->be_lun->lun_type == T_CDROM &&
3921		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3922			continue;
3923
3924		page_code = page_index->page_code & SMPH_PC_MASK;
3925		switch (page_code) {
3926		case SMS_RW_ERROR_RECOVERY_PAGE: {
3927			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3928			    ("subpage %#x for page %#x is incorrect!",
3929			    page_index->subpage, page_code));
3930			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3931			       &rw_er_page_default,
3932			       sizeof(rw_er_page_default));
3933			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3934			       &rw_er_page_changeable,
3935			       sizeof(rw_er_page_changeable));
3936			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3937			       &rw_er_page_default,
3938			       sizeof(rw_er_page_default));
3939			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3940			       &rw_er_page_default,
3941			       sizeof(rw_er_page_default));
3942			page_index->page_data =
3943				(uint8_t *)lun->mode_pages.rw_er_page;
3944			break;
3945		}
3946		case SMS_FORMAT_DEVICE_PAGE: {
3947			struct scsi_format_page *format_page;
3948
3949			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3950			    ("subpage %#x for page %#x is incorrect!",
3951			    page_index->subpage, page_code));
3952
3953			/*
3954			 * Sectors per track are set above.  Bytes per
3955			 * sector need to be set here on a per-LUN basis.
3956			 */
3957			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3958			       &format_page_default,
3959			       sizeof(format_page_default));
3960			memcpy(&lun->mode_pages.format_page[
3961			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3962			       sizeof(format_page_changeable));
3963			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3964			       &format_page_default,
3965			       sizeof(format_page_default));
3966			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3967			       &format_page_default,
3968			       sizeof(format_page_default));
3969
3970			format_page = &lun->mode_pages.format_page[
3971				CTL_PAGE_CURRENT];
3972			scsi_ulto2b(lun->be_lun->blocksize,
3973				    format_page->bytes_per_sector);
3974
3975			format_page = &lun->mode_pages.format_page[
3976				CTL_PAGE_DEFAULT];
3977			scsi_ulto2b(lun->be_lun->blocksize,
3978				    format_page->bytes_per_sector);
3979
3980			format_page = &lun->mode_pages.format_page[
3981				CTL_PAGE_SAVED];
3982			scsi_ulto2b(lun->be_lun->blocksize,
3983				    format_page->bytes_per_sector);
3984
3985			page_index->page_data =
3986				(uint8_t *)lun->mode_pages.format_page;
3987			break;
3988		}
3989		case SMS_RIGID_DISK_PAGE: {
3990			struct scsi_rigid_disk_page *rigid_disk_page;
3991			uint32_t sectors_per_cylinder;
3992			uint64_t cylinders;
3993#ifndef	__XSCALE__
3994			int shift;
3995#endif /* !__XSCALE__ */
3996
3997			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3998			    ("subpage %#x for page %#x is incorrect!",
3999			    page_index->subpage, page_code));
4000
4001			/*
4002			 * Rotation rate and sectors per track are set
4003			 * above.  We calculate the cylinders here based on
4004			 * capacity.  Due to the number of heads and
4005			 * sectors per track we're using, smaller arrays
4006			 * may turn out to have 0 cylinders.  Linux and
4007			 * FreeBSD don't pay attention to these mode pages
4008			 * to figure out capacity, but Solaris does.  It
4009			 * seems to deal with 0 cylinders just fine, and
4010			 * works out a fake geometry based on the capacity.
4011			 */
4012			memcpy(&lun->mode_pages.rigid_disk_page[
4013			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4014			       sizeof(rigid_disk_page_default));
4015			memcpy(&lun->mode_pages.rigid_disk_page[
4016			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4017			       sizeof(rigid_disk_page_changeable));
4018
4019			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4020				CTL_DEFAULT_HEADS;
4021
4022			/*
4023			 * The divide method here will be more accurate,
4024			 * probably, but results in floating point being
4025			 * used in the kernel on i386 (__udivdi3()).  On the
4026			 * XScale, though, __udivdi3() is implemented in
4027			 * software.
4028			 *
4029			 * The shift method for cylinder calculation is
4030			 * accurate if sectors_per_cylinder is a power of
4031			 * 2.  Otherwise it might be slightly off -- you
4032			 * might have a bit of a truncation problem.
4033			 */
4034#ifdef	__XSCALE__
4035			cylinders = (lun->be_lun->maxlba + 1) /
4036				sectors_per_cylinder;
4037#else
4038			for (shift = 31; shift > 0; shift--) {
4039				if (sectors_per_cylinder & (1 << shift))
4040					break;
4041			}
4042			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4043#endif
4044
4045			/*
4046			 * We've basically got 3 bytes, or 24 bits for the
4047			 * cylinder size in the mode page.  If we're over,
4048			 * just round down to 2^24.
4049			 */
4050			if (cylinders > 0xffffff)
4051				cylinders = 0xffffff;
4052
4053			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4054				CTL_PAGE_DEFAULT];
4055			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4056
4057			if ((value = ctl_get_opt(&lun->be_lun->options,
4058			    "rpm")) != NULL) {
4059				scsi_ulto2b(strtol(value, NULL, 0),
4060				     rigid_disk_page->rotation_rate);
4061			}
4062
4063			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4064			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4065			       sizeof(rigid_disk_page_default));
4066			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4067			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4068			       sizeof(rigid_disk_page_default));
4069
4070			page_index->page_data =
4071				(uint8_t *)lun->mode_pages.rigid_disk_page;
4072			break;
4073		}
4074		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4075			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4076			    ("subpage %#x for page %#x is incorrect!",
4077			    page_index->subpage, page_code));
4078			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4079			       &verify_er_page_default,
4080			       sizeof(verify_er_page_default));
4081			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4082			       &verify_er_page_changeable,
4083			       sizeof(verify_er_page_changeable));
4084			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4085			       &verify_er_page_default,
4086			       sizeof(verify_er_page_default));
4087			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4088			       &verify_er_page_default,
4089			       sizeof(verify_er_page_default));
4090			page_index->page_data =
4091				(uint8_t *)lun->mode_pages.verify_er_page;
4092			break;
4093		}
4094		case SMS_CACHING_PAGE: {
4095			struct scsi_caching_page *caching_page;
4096
4097			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4098			    ("subpage %#x for page %#x is incorrect!",
4099			    page_index->subpage, page_code));
4100			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4101			       &caching_page_default,
4102			       sizeof(caching_page_default));
4103			memcpy(&lun->mode_pages.caching_page[
4104			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4105			       sizeof(caching_page_changeable));
4106			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4107			       &caching_page_default,
4108			       sizeof(caching_page_default));
4109			caching_page = &lun->mode_pages.caching_page[
4110			    CTL_PAGE_SAVED];
4111			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4112			if (value != NULL && strcmp(value, "off") == 0)
4113				caching_page->flags1 &= ~SCP_WCE;
4114			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4115			if (value != NULL && strcmp(value, "off") == 0)
4116				caching_page->flags1 |= SCP_RCD;
4117			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4118			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4119			       sizeof(caching_page_default));
4120			page_index->page_data =
4121				(uint8_t *)lun->mode_pages.caching_page;
4122			break;
4123		}
4124		case SMS_CONTROL_MODE_PAGE: {
4125			switch (page_index->subpage) {
4126			case SMS_SUBPAGE_PAGE_0: {
4127				struct scsi_control_page *control_page;
4128
4129				memcpy(&lun->mode_pages.control_page[
4130				    CTL_PAGE_DEFAULT],
4131				       &control_page_default,
4132				       sizeof(control_page_default));
4133				memcpy(&lun->mode_pages.control_page[
4134				    CTL_PAGE_CHANGEABLE],
4135				       &control_page_changeable,
4136				       sizeof(control_page_changeable));
4137				memcpy(&lun->mode_pages.control_page[
4138				    CTL_PAGE_SAVED],
4139				       &control_page_default,
4140				       sizeof(control_page_default));
4141				control_page = &lun->mode_pages.control_page[
4142				    CTL_PAGE_SAVED];
4143				value = ctl_get_opt(&lun->be_lun->options,
4144				    "reordering");
4145				if (value != NULL &&
4146				    strcmp(value, "unrestricted") == 0) {
4147					control_page->queue_flags &=
4148					    ~SCP_QUEUE_ALG_MASK;
4149					control_page->queue_flags |=
4150					    SCP_QUEUE_ALG_UNRESTRICTED;
4151				}
4152				memcpy(&lun->mode_pages.control_page[
4153				    CTL_PAGE_CURRENT],
4154				       &lun->mode_pages.control_page[
4155				    CTL_PAGE_SAVED],
4156				       sizeof(control_page_default));
4157				page_index->page_data =
4158				    (uint8_t *)lun->mode_pages.control_page;
4159				break;
4160			}
4161			case 0x01:
4162				memcpy(&lun->mode_pages.control_ext_page[
4163				    CTL_PAGE_DEFAULT],
4164				       &control_ext_page_default,
4165				       sizeof(control_ext_page_default));
4166				memcpy(&lun->mode_pages.control_ext_page[
4167				    CTL_PAGE_CHANGEABLE],
4168				       &control_ext_page_changeable,
4169				       sizeof(control_ext_page_changeable));
4170				memcpy(&lun->mode_pages.control_ext_page[
4171				    CTL_PAGE_SAVED],
4172				       &control_ext_page_default,
4173				       sizeof(control_ext_page_default));
4174				memcpy(&lun->mode_pages.control_ext_page[
4175				    CTL_PAGE_CURRENT],
4176				       &lun->mode_pages.control_ext_page[
4177				    CTL_PAGE_SAVED],
4178				       sizeof(control_ext_page_default));
4179				page_index->page_data =
4180				    (uint8_t *)lun->mode_pages.control_ext_page;
4181				break;
4182			default:
4183				panic("subpage %#x for page %#x is incorrect!",
4184				      page_index->subpage, page_code);
4185			}
4186			break;
4187		}
4188		case SMS_INFO_EXCEPTIONS_PAGE: {
4189			switch (page_index->subpage) {
4190			case SMS_SUBPAGE_PAGE_0:
4191				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4192				       &ie_page_default,
4193				       sizeof(ie_page_default));
4194				memcpy(&lun->mode_pages.ie_page[
4195				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4196				       sizeof(ie_page_changeable));
4197				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4198				       &ie_page_default,
4199				       sizeof(ie_page_default));
4200				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4201				       &ie_page_default,
4202				       sizeof(ie_page_default));
4203				page_index->page_data =
4204					(uint8_t *)lun->mode_pages.ie_page;
4205				break;
4206			case 0x02: {
4207				struct ctl_logical_block_provisioning_page *page;
4208
4209				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4210				       &lbp_page_default,
4211				       sizeof(lbp_page_default));
4212				memcpy(&lun->mode_pages.lbp_page[
4213				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4214				       sizeof(lbp_page_changeable));
4215				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4216				       &lbp_page_default,
4217				       sizeof(lbp_page_default));
4218				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4219				value = ctl_get_opt(&lun->be_lun->options,
4220				    "avail-threshold");
4221				if (value != NULL &&
4222				    ctl_expand_number(value, &ival) == 0) {
4223					page->descr[0].flags |= SLBPPD_ENABLED |
4224					    SLBPPD_ARMING_DEC;
4225					if (lun->be_lun->blocksize)
4226						ival /= lun->be_lun->blocksize;
4227					else
4228						ival /= 512;
4229					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4230					    page->descr[0].count);
4231				}
4232				value = ctl_get_opt(&lun->be_lun->options,
4233				    "used-threshold");
4234				if (value != NULL &&
4235				    ctl_expand_number(value, &ival) == 0) {
4236					page->descr[1].flags |= SLBPPD_ENABLED |
4237					    SLBPPD_ARMING_INC;
4238					if (lun->be_lun->blocksize)
4239						ival /= lun->be_lun->blocksize;
4240					else
4241						ival /= 512;
4242					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4243					    page->descr[1].count);
4244				}
4245				value = ctl_get_opt(&lun->be_lun->options,
4246				    "pool-avail-threshold");
4247				if (value != NULL &&
4248				    ctl_expand_number(value, &ival) == 0) {
4249					page->descr[2].flags |= SLBPPD_ENABLED |
4250					    SLBPPD_ARMING_DEC;
4251					if (lun->be_lun->blocksize)
4252						ival /= lun->be_lun->blocksize;
4253					else
4254						ival /= 512;
4255					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4256					    page->descr[2].count);
4257				}
4258				value = ctl_get_opt(&lun->be_lun->options,
4259				    "pool-used-threshold");
4260				if (value != NULL &&
4261				    ctl_expand_number(value, &ival) == 0) {
4262					page->descr[3].flags |= SLBPPD_ENABLED |
4263					    SLBPPD_ARMING_INC;
4264					if (lun->be_lun->blocksize)
4265						ival /= lun->be_lun->blocksize;
4266					else
4267						ival /= 512;
4268					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4269					    page->descr[3].count);
4270				}
4271				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4272				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4273				       sizeof(lbp_page_default));
4274				page_index->page_data =
4275					(uint8_t *)lun->mode_pages.lbp_page;
4276				break;
4277			}
4278			default:
4279				panic("subpage %#x for page %#x is incorrect!",
4280				      page_index->subpage, page_code);
4281			}
4282			break;
4283		}
4284		case SMS_CDDVD_CAPS_PAGE:{
4285			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4286			    ("subpage %#x for page %#x is incorrect!",
4287			    page_index->subpage, page_code));
4288			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4289			       &cddvd_page_default,
4290			       sizeof(cddvd_page_default));
4291			memcpy(&lun->mode_pages.cddvd_page[
4292			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4293			       sizeof(cddvd_page_changeable));
4294			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4295			       &cddvd_page_default,
4296			       sizeof(cddvd_page_default));
4297			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4298			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4299			       sizeof(cddvd_page_default));
4300			page_index->page_data =
4301				(uint8_t *)lun->mode_pages.cddvd_page;
4302			break;
4303		}
4304		default:
4305			panic("invalid page code value %#x", page_code);
4306		}
4307	}
4308
4309	return (CTL_RETVAL_COMPLETE);
4310}
4311
4312static int
4313ctl_init_log_page_index(struct ctl_lun *lun)
4314{
4315	struct ctl_page_index *page_index;
4316	int i, j, k, prev;
4317
4318	memcpy(&lun->log_pages.index, log_page_index_template,
4319	       sizeof(log_page_index_template));
4320
4321	prev = -1;
4322	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4323
4324		page_index = &lun->log_pages.index[i];
4325		if (lun->be_lun->lun_type == T_DIRECT &&
4326		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4327			continue;
4328		if (lun->be_lun->lun_type == T_PROCESSOR &&
4329		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4330			continue;
4331		if (lun->be_lun->lun_type == T_CDROM &&
4332		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4333			continue;
4334
4335		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4336		    lun->backend->lun_attr == NULL)
4337			continue;
4338
4339		if (page_index->page_code != prev) {
4340			lun->log_pages.pages_page[j] = page_index->page_code;
4341			prev = page_index->page_code;
4342			j++;
4343		}
4344		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4345		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4346		k++;
4347	}
4348	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4349	lun->log_pages.index[0].page_len = j;
4350	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4351	lun->log_pages.index[1].page_len = k * 2;
4352	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4353	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4354	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4355	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4356	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4357	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4358
4359	return (CTL_RETVAL_COMPLETE);
4360}
4361
4362static int
4363hex2bin(const char *str, uint8_t *buf, int buf_size)
4364{
4365	int i;
4366	u_char c;
4367
4368	memset(buf, 0, buf_size);
4369	while (isspace(str[0]))
4370		str++;
4371	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4372		str += 2;
4373	buf_size *= 2;
4374	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4375		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4376			str++;
4377		c = str[i];
4378		if (isdigit(c))
4379			c -= '0';
4380		else if (isalpha(c))
4381			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4382		else
4383			break;
4384		if (c >= 16)
4385			break;
4386		if ((i & 1) == 0)
4387			buf[i / 2] |= (c << 4);
4388		else
4389			buf[i / 2] |= c;
4390	}
4391	return ((i + 1) / 2);
4392}
4393
4394/*
4395 * LUN allocation.
4396 *
4397 * Requirements:
4398 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4399 *   wants us to allocate the LUN and he can block.
4400 * - ctl_softc is always set
4401 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4402 *
4403 * Returns 0 for success, non-zero (errno) for failure.
4404 */
4405static int
4406ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4407	      struct ctl_be_lun *const be_lun)
4408{
4409	struct ctl_lun *nlun, *lun;
4410	struct scsi_vpd_id_descriptor *desc;
4411	struct scsi_vpd_id_t10 *t10id;
4412	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4413	int lun_number, i, lun_malloced;
4414	int devidlen, idlen1, idlen2 = 0, len;
4415
4416	if (be_lun == NULL)
4417		return (EINVAL);
4418
4419	/*
4420	 * We currently only support Direct Access or Processor LUN types.
4421	 */
4422	switch (be_lun->lun_type) {
4423	case T_DIRECT:
4424	case T_PROCESSOR:
4425	case T_CDROM:
4426		break;
4427	case T_SEQUENTIAL:
4428	case T_CHANGER:
4429	default:
4430		be_lun->lun_config_status(be_lun->be_lun,
4431					  CTL_LUN_CONFIG_FAILURE);
4432		break;
4433	}
4434	if (ctl_lun == NULL) {
4435		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4436		lun_malloced = 1;
4437	} else {
4438		lun_malloced = 0;
4439		lun = ctl_lun;
4440	}
4441
4442	memset(lun, 0, sizeof(*lun));
4443	if (lun_malloced)
4444		lun->flags = CTL_LUN_MALLOCED;
4445
4446	/* Generate LUN ID. */
4447	devidlen = max(CTL_DEVID_MIN_LEN,
4448	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4449	idlen1 = sizeof(*t10id) + devidlen;
4450	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4451	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4452	if (scsiname != NULL) {
4453		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4454		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4455	}
4456	eui = ctl_get_opt(&be_lun->options, "eui");
4457	if (eui != NULL) {
4458		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4459	}
4460	naa = ctl_get_opt(&be_lun->options, "naa");
4461	if (naa != NULL) {
4462		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4463	}
4464	uuid = ctl_get_opt(&be_lun->options, "uuid");
4465	if (uuid != NULL) {
4466		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4467	}
4468	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4469	    M_CTL, M_WAITOK | M_ZERO);
4470	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4471	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4472	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4473	desc->length = idlen1;
4474	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4475	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4476	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4477		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4478	} else {
4479		strncpy(t10id->vendor, vendor,
4480		    min(sizeof(t10id->vendor), strlen(vendor)));
4481	}
4482	strncpy((char *)t10id->vendor_spec_id,
4483	    (char *)be_lun->device_id, devidlen);
4484	if (scsiname != NULL) {
4485		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4486		    desc->length);
4487		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4488		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4489		    SVPD_ID_TYPE_SCSI_NAME;
4490		desc->length = idlen2;
4491		strlcpy(desc->identifier, scsiname, idlen2);
4492	}
4493	if (eui != NULL) {
4494		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4495		    desc->length);
4496		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4497		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4498		    SVPD_ID_TYPE_EUI64;
4499		desc->length = hex2bin(eui, desc->identifier, 16);
4500		desc->length = desc->length > 12 ? 16 :
4501		    (desc->length > 8 ? 12 : 8);
4502		len -= 16 - desc->length;
4503	}
4504	if (naa != NULL) {
4505		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4506		    desc->length);
4507		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4508		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4509		    SVPD_ID_TYPE_NAA;
4510		desc->length = hex2bin(naa, desc->identifier, 16);
4511		desc->length = desc->length > 8 ? 16 : 8;
4512		len -= 16 - desc->length;
4513	}
4514	if (uuid != NULL) {
4515		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4516		    desc->length);
4517		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4518		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4519		    SVPD_ID_TYPE_UUID;
4520		desc->identifier[0] = 0x10;
4521		hex2bin(uuid, &desc->identifier[2], 16);
4522		desc->length = 18;
4523	}
4524	lun->lun_devid->len = len;
4525
4526	mtx_lock(&ctl_softc->ctl_lock);
4527	/*
4528	 * See if the caller requested a particular LUN number.  If so, see
4529	 * if it is available.  Otherwise, allocate the first available LUN.
4530	 */
4531	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4532		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4533		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4534			mtx_unlock(&ctl_softc->ctl_lock);
4535			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4536				printf("ctl: requested LUN ID %d is higher "
4537				       "than CTL_MAX_LUNS - 1 (%d)\n",
4538				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4539			} else {
4540				/*
4541				 * XXX KDM return an error, or just assign
4542				 * another LUN ID in this case??
4543				 */
4544				printf("ctl: requested LUN ID %d is already "
4545				       "in use\n", be_lun->req_lun_id);
4546			}
4547			if (lun->flags & CTL_LUN_MALLOCED)
4548				free(lun, M_CTL);
4549			be_lun->lun_config_status(be_lun->be_lun,
4550						  CTL_LUN_CONFIG_FAILURE);
4551			return (ENOSPC);
4552		}
4553		lun_number = be_lun->req_lun_id;
4554	} else {
4555		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4556		if (lun_number == -1) {
4557			mtx_unlock(&ctl_softc->ctl_lock);
4558			printf("ctl: can't allocate LUN, out of LUNs\n");
4559			if (lun->flags & CTL_LUN_MALLOCED)
4560				free(lun, M_CTL);
4561			be_lun->lun_config_status(be_lun->be_lun,
4562						  CTL_LUN_CONFIG_FAILURE);
4563			return (ENOSPC);
4564		}
4565	}
4566	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4567
4568	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4569	lun->lun = lun_number;
4570	lun->be_lun = be_lun;
4571	/*
4572	 * The processor LUN is always enabled.  Disk LUNs come on line
4573	 * disabled, and must be enabled by the backend.
4574	 */
4575	lun->flags |= CTL_LUN_DISABLED;
4576	lun->backend = be_lun->be;
4577	be_lun->ctl_lun = lun;
4578	be_lun->lun_id = lun_number;
4579	atomic_add_int(&be_lun->be->num_luns, 1);
4580	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4581		lun->flags |= CTL_LUN_EJECTED;
4582	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4583		lun->flags |= CTL_LUN_NO_MEDIA;
4584	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4585		lun->flags |= CTL_LUN_STOPPED;
4586
4587	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4588		lun->flags |= CTL_LUN_PRIMARY_SC;
4589
4590	value = ctl_get_opt(&be_lun->options, "removable");
4591	if (value != NULL) {
4592		if (strcmp(value, "on") == 0)
4593			lun->flags |= CTL_LUN_REMOVABLE;
4594	} else if (be_lun->lun_type == T_CDROM)
4595		lun->flags |= CTL_LUN_REMOVABLE;
4596
4597	lun->ctl_softc = ctl_softc;
4598#ifdef CTL_TIME_IO
4599	lun->last_busy = getsbinuptime();
4600#endif
4601	TAILQ_INIT(&lun->ooa_queue);
4602	TAILQ_INIT(&lun->blocked_queue);
4603	STAILQ_INIT(&lun->error_list);
4604	lun->ie_reported = 1;
4605	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4606	ctl_tpc_lun_init(lun);
4607
4608	/*
4609	 * Initialize the mode and log page index.
4610	 */
4611	ctl_init_page_index(lun);
4612	ctl_init_log_page_index(lun);
4613
4614	/*
4615	 * Now, before we insert this lun on the lun list, set the lun
4616	 * inventory changed UA for all other luns.
4617	 */
4618	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4619		mtx_lock(&nlun->lun_lock);
4620		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4621		mtx_unlock(&nlun->lun_lock);
4622	}
4623
4624	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4625
4626	ctl_softc->ctl_luns[lun_number] = lun;
4627
4628	ctl_softc->num_luns++;
4629
4630	/* Setup statistics gathering */
4631	lun->stats.device_type = be_lun->lun_type;
4632	lun->stats.lun_number = lun_number;
4633	lun->stats.blocksize = be_lun->blocksize;
4634	if (be_lun->blocksize == 0)
4635		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4636	for (i = 0;i < CTL_MAX_PORTS;i++)
4637		lun->stats.ports[i].targ_port = i;
4638
4639	mtx_unlock(&ctl_softc->ctl_lock);
4640
4641	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4642	return (0);
4643}
4644
4645/*
4646 * Delete a LUN.
4647 * Assumptions:
4648 * - LUN has already been marked invalid and any pending I/O has been taken
4649 *   care of.
4650 */
4651static int
4652ctl_free_lun(struct ctl_lun *lun)
4653{
4654	struct ctl_softc *softc;
4655	struct ctl_lun *nlun;
4656	int i;
4657
4658	softc = lun->ctl_softc;
4659
4660	mtx_assert(&softc->ctl_lock, MA_OWNED);
4661
4662	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4663
4664	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4665
4666	softc->ctl_luns[lun->lun] = NULL;
4667
4668	if (!TAILQ_EMPTY(&lun->ooa_queue))
4669		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4670
4671	softc->num_luns--;
4672
4673	/*
4674	 * Tell the backend to free resources, if this LUN has a backend.
4675	 */
4676	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4677	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4678
4679	lun->ie_reportcnt = UINT32_MAX;
4680	callout_drain(&lun->ie_callout);
4681
4682	ctl_tpc_lun_shutdown(lun);
4683	mtx_destroy(&lun->lun_lock);
4684	free(lun->lun_devid, M_CTL);
4685	for (i = 0; i < CTL_MAX_PORTS; i++)
4686		free(lun->pending_ua[i], M_CTL);
4687	for (i = 0; i < CTL_MAX_PORTS; i++)
4688		free(lun->pr_keys[i], M_CTL);
4689	free(lun->write_buffer, M_CTL);
4690	if (lun->flags & CTL_LUN_MALLOCED)
4691		free(lun, M_CTL);
4692
4693	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4694		mtx_lock(&nlun->lun_lock);
4695		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4696		mtx_unlock(&nlun->lun_lock);
4697	}
4698
4699	return (0);
4700}
4701
4702static void
4703ctl_create_lun(struct ctl_be_lun *be_lun)
4704{
4705
4706	/*
4707	 * ctl_alloc_lun() should handle all potential failure cases.
4708	 */
4709	ctl_alloc_lun(control_softc, NULL, be_lun);
4710}
4711
4712int
4713ctl_add_lun(struct ctl_be_lun *be_lun)
4714{
4715	struct ctl_softc *softc = control_softc;
4716
4717	mtx_lock(&softc->ctl_lock);
4718	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4719	mtx_unlock(&softc->ctl_lock);
4720	wakeup(&softc->pending_lun_queue);
4721
4722	return (0);
4723}
4724
4725int
4726ctl_enable_lun(struct ctl_be_lun *be_lun)
4727{
4728	struct ctl_softc *softc;
4729	struct ctl_port *port, *nport;
4730	struct ctl_lun *lun;
4731	int retval;
4732
4733	lun = (struct ctl_lun *)be_lun->ctl_lun;
4734	softc = lun->ctl_softc;
4735
4736	mtx_lock(&softc->ctl_lock);
4737	mtx_lock(&lun->lun_lock);
4738	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4739		/*
4740		 * eh?  Why did we get called if the LUN is already
4741		 * enabled?
4742		 */
4743		mtx_unlock(&lun->lun_lock);
4744		mtx_unlock(&softc->ctl_lock);
4745		return (0);
4746	}
4747	lun->flags &= ~CTL_LUN_DISABLED;
4748	mtx_unlock(&lun->lun_lock);
4749
4750	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4751		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4752		    port->lun_map != NULL || port->lun_enable == NULL)
4753			continue;
4754
4755		/*
4756		 * Drop the lock while we call the FETD's enable routine.
4757		 * This can lead to a callback into CTL (at least in the
4758		 * case of the internal initiator frontend.
4759		 */
4760		mtx_unlock(&softc->ctl_lock);
4761		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4762		mtx_lock(&softc->ctl_lock);
4763		if (retval != 0) {
4764			printf("%s: FETD %s port %d returned error "
4765			       "%d for lun_enable on lun %jd\n",
4766			       __func__, port->port_name, port->targ_port,
4767			       retval, (intmax_t)lun->lun);
4768		}
4769	}
4770
4771	mtx_unlock(&softc->ctl_lock);
4772	ctl_isc_announce_lun(lun);
4773
4774	return (0);
4775}
4776
4777int
4778ctl_disable_lun(struct ctl_be_lun *be_lun)
4779{
4780	struct ctl_softc *softc;
4781	struct ctl_port *port;
4782	struct ctl_lun *lun;
4783	int retval;
4784
4785	lun = (struct ctl_lun *)be_lun->ctl_lun;
4786	softc = lun->ctl_softc;
4787
4788	mtx_lock(&softc->ctl_lock);
4789	mtx_lock(&lun->lun_lock);
4790	if (lun->flags & CTL_LUN_DISABLED) {
4791		mtx_unlock(&lun->lun_lock);
4792		mtx_unlock(&softc->ctl_lock);
4793		return (0);
4794	}
4795	lun->flags |= CTL_LUN_DISABLED;
4796	mtx_unlock(&lun->lun_lock);
4797
4798	STAILQ_FOREACH(port, &softc->port_list, links) {
4799		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4800		    port->lun_map != NULL || port->lun_disable == NULL)
4801			continue;
4802
4803		/*
4804		 * Drop the lock before we call the frontend's disable
4805		 * routine, to avoid lock order reversals.
4806		 *
4807		 * XXX KDM what happens if the frontend list changes while
4808		 * we're traversing it?  It's unlikely, but should be handled.
4809		 */
4810		mtx_unlock(&softc->ctl_lock);
4811		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4812		mtx_lock(&softc->ctl_lock);
4813		if (retval != 0) {
4814			printf("%s: FETD %s port %d returned error "
4815			       "%d for lun_disable on lun %jd\n",
4816			       __func__, port->port_name, port->targ_port,
4817			       retval, (intmax_t)lun->lun);
4818		}
4819	}
4820
4821	mtx_unlock(&softc->ctl_lock);
4822	ctl_isc_announce_lun(lun);
4823
4824	return (0);
4825}
4826
4827int
4828ctl_start_lun(struct ctl_be_lun *be_lun)
4829{
4830	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4831
4832	mtx_lock(&lun->lun_lock);
4833	lun->flags &= ~CTL_LUN_STOPPED;
4834	mtx_unlock(&lun->lun_lock);
4835	return (0);
4836}
4837
4838int
4839ctl_stop_lun(struct ctl_be_lun *be_lun)
4840{
4841	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4842
4843	mtx_lock(&lun->lun_lock);
4844	lun->flags |= CTL_LUN_STOPPED;
4845	mtx_unlock(&lun->lun_lock);
4846	return (0);
4847}
4848
4849int
4850ctl_lun_no_media(struct ctl_be_lun *be_lun)
4851{
4852	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4853
4854	mtx_lock(&lun->lun_lock);
4855	lun->flags |= CTL_LUN_NO_MEDIA;
4856	mtx_unlock(&lun->lun_lock);
4857	return (0);
4858}
4859
4860int
4861ctl_lun_has_media(struct ctl_be_lun *be_lun)
4862{
4863	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4864	union ctl_ha_msg msg;
4865
4866	mtx_lock(&lun->lun_lock);
4867	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4868	if (lun->flags & CTL_LUN_REMOVABLE)
4869		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4870	mtx_unlock(&lun->lun_lock);
4871	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4872	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4873		bzero(&msg.ua, sizeof(msg.ua));
4874		msg.hdr.msg_type = CTL_MSG_UA;
4875		msg.hdr.nexus.initid = -1;
4876		msg.hdr.nexus.targ_port = -1;
4877		msg.hdr.nexus.targ_lun = lun->lun;
4878		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4879		msg.ua.ua_all = 1;
4880		msg.ua.ua_set = 1;
4881		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4882		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4883		    M_WAITOK);
4884	}
4885	return (0);
4886}
4887
4888int
4889ctl_lun_ejected(struct ctl_be_lun *be_lun)
4890{
4891	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4892
4893	mtx_lock(&lun->lun_lock);
4894	lun->flags |= CTL_LUN_EJECTED;
4895	mtx_unlock(&lun->lun_lock);
4896	return (0);
4897}
4898
4899int
4900ctl_lun_primary(struct ctl_be_lun *be_lun)
4901{
4902	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4903
4904	mtx_lock(&lun->lun_lock);
4905	lun->flags |= CTL_LUN_PRIMARY_SC;
4906	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4907	mtx_unlock(&lun->lun_lock);
4908	ctl_isc_announce_lun(lun);
4909	return (0);
4910}
4911
4912int
4913ctl_lun_secondary(struct ctl_be_lun *be_lun)
4914{
4915	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4916
4917	mtx_lock(&lun->lun_lock);
4918	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4919	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4920	mtx_unlock(&lun->lun_lock);
4921	ctl_isc_announce_lun(lun);
4922	return (0);
4923}
4924
4925int
4926ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4927{
4928	struct ctl_softc *softc;
4929	struct ctl_lun *lun;
4930
4931	lun = (struct ctl_lun *)be_lun->ctl_lun;
4932	softc = lun->ctl_softc;
4933
4934	mtx_lock(&lun->lun_lock);
4935
4936	/*
4937	 * The LUN needs to be disabled before it can be marked invalid.
4938	 */
4939	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4940		mtx_unlock(&lun->lun_lock);
4941		return (-1);
4942	}
4943	/*
4944	 * Mark the LUN invalid.
4945	 */
4946	lun->flags |= CTL_LUN_INVALID;
4947
4948	/*
4949	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4950	 * If we have something in the OOA queue, we'll free it when the
4951	 * last I/O completes.
4952	 */
4953	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4954		mtx_unlock(&lun->lun_lock);
4955		mtx_lock(&softc->ctl_lock);
4956		ctl_free_lun(lun);
4957		mtx_unlock(&softc->ctl_lock);
4958	} else
4959		mtx_unlock(&lun->lun_lock);
4960
4961	return (0);
4962}
4963
4964void
4965ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4966{
4967	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4968	union ctl_ha_msg msg;
4969
4970	mtx_lock(&lun->lun_lock);
4971	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4972	mtx_unlock(&lun->lun_lock);
4973	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4974		/* Send msg to other side. */
4975		bzero(&msg.ua, sizeof(msg.ua));
4976		msg.hdr.msg_type = CTL_MSG_UA;
4977		msg.hdr.nexus.initid = -1;
4978		msg.hdr.nexus.targ_port = -1;
4979		msg.hdr.nexus.targ_lun = lun->lun;
4980		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4981		msg.ua.ua_all = 1;
4982		msg.ua.ua_set = 1;
4983		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4984		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4985		    M_WAITOK);
4986	}
4987}
4988
4989/*
4990 * Backend "memory move is complete" callback for requests that never
4991 * make it down to say RAIDCore's configuration code.
4992 */
4993int
4994ctl_config_move_done(union ctl_io *io)
4995{
4996	int retval;
4997
4998	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4999	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5000	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5001
5002	if ((io->io_hdr.port_status != 0) &&
5003	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5004	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5005		/*
5006		 * For hardware error sense keys, the sense key
5007		 * specific value is defined to be a retry count,
5008		 * but we use it to pass back an internal FETD
5009		 * error code.  XXX KDM  Hopefully the FETD is only
5010		 * using 16 bits for an error code, since that's
5011		 * all the space we have in the sks field.
5012		 */
5013		ctl_set_internal_failure(&io->scsiio,
5014					 /*sks_valid*/ 1,
5015					 /*retry_count*/
5016					 io->io_hdr.port_status);
5017	}
5018
5019	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5020		ctl_data_print(io);
5021	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5022	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5023	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5024	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5025		/*
5026		 * XXX KDM just assuming a single pointer here, and not a
5027		 * S/G list.  If we start using S/G lists for config data,
5028		 * we'll need to know how to clean them up here as well.
5029		 */
5030		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5031			free(io->scsiio.kern_data_ptr, M_CTL);
5032		ctl_done(io);
5033		retval = CTL_RETVAL_COMPLETE;
5034	} else {
5035		/*
5036		 * XXX KDM now we need to continue data movement.  Some
5037		 * options:
5038		 * - call ctl_scsiio() again?  We don't do this for data
5039		 *   writes, because for those at least we know ahead of
5040		 *   time where the write will go and how long it is.  For
5041		 *   config writes, though, that information is largely
5042		 *   contained within the write itself, thus we need to
5043		 *   parse out the data again.
5044		 *
5045		 * - Call some other function once the data is in?
5046		 */
5047
5048		/*
5049		 * XXX KDM call ctl_scsiio() again for now, and check flag
5050		 * bits to see whether we're allocated or not.
5051		 */
5052		retval = ctl_scsiio(&io->scsiio);
5053	}
5054	return (retval);
5055}
5056
5057/*
5058 * This gets called by a backend driver when it is done with a
5059 * data_submit method.
5060 */
5061void
5062ctl_data_submit_done(union ctl_io *io)
5063{
5064	/*
5065	 * If the IO_CONT flag is set, we need to call the supplied
5066	 * function to continue processing the I/O, instead of completing
5067	 * the I/O just yet.
5068	 *
5069	 * If there is an error, though, we don't want to keep processing.
5070	 * Instead, just send status back to the initiator.
5071	 */
5072	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5073	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5074	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5075	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5076		io->scsiio.io_cont(io);
5077		return;
5078	}
5079	ctl_done(io);
5080}
5081
5082/*
5083 * This gets called by a backend driver when it is done with a
5084 * configuration write.
5085 */
5086void
5087ctl_config_write_done(union ctl_io *io)
5088{
5089	uint8_t *buf;
5090
5091	/*
5092	 * If the IO_CONT flag is set, we need to call the supplied
5093	 * function to continue processing the I/O, instead of completing
5094	 * the I/O just yet.
5095	 *
5096	 * If there is an error, though, we don't want to keep processing.
5097	 * Instead, just send status back to the initiator.
5098	 */
5099	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5100	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5101	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5102	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5103		io->scsiio.io_cont(io);
5104		return;
5105	}
5106	/*
5107	 * Since a configuration write can be done for commands that actually
5108	 * have data allocated, like write buffer, and commands that have
5109	 * no data, like start/stop unit, we need to check here.
5110	 */
5111	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5112		buf = io->scsiio.kern_data_ptr;
5113	else
5114		buf = NULL;
5115	ctl_done(io);
5116	if (buf)
5117		free(buf, M_CTL);
5118}
5119
5120void
5121ctl_config_read_done(union ctl_io *io)
5122{
5123	uint8_t *buf;
5124
5125	/*
5126	 * If there is some error -- we are done, skip data transfer.
5127	 */
5128	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5129	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5130	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5131		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5132			buf = io->scsiio.kern_data_ptr;
5133		else
5134			buf = NULL;
5135		ctl_done(io);
5136		if (buf)
5137			free(buf, M_CTL);
5138		return;
5139	}
5140
5141	/*
5142	 * If the IO_CONT flag is set, we need to call the supplied
5143	 * function to continue processing the I/O, instead of completing
5144	 * the I/O just yet.
5145	 */
5146	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5147		io->scsiio.io_cont(io);
5148		return;
5149	}
5150
5151	ctl_datamove(io);
5152}
5153
5154/*
5155 * SCSI release command.
5156 */
5157int
5158ctl_scsi_release(struct ctl_scsiio *ctsio)
5159{
5160	struct ctl_lun *lun;
5161	uint32_t residx;
5162
5163	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5164
5165	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5166	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5167
5168	/*
5169	 * XXX KDM right now, we only support LUN reservation.  We don't
5170	 * support 3rd party reservations, or extent reservations, which
5171	 * might actually need the parameter list.  If we've gotten this
5172	 * far, we've got a LUN reservation.  Anything else got kicked out
5173	 * above.  So, according to SPC, ignore the length.
5174	 */
5175
5176	mtx_lock(&lun->lun_lock);
5177
5178	/*
5179	 * According to SPC, it is not an error for an intiator to attempt
5180	 * to release a reservation on a LUN that isn't reserved, or that
5181	 * is reserved by another initiator.  The reservation can only be
5182	 * released, though, by the initiator who made it or by one of
5183	 * several reset type events.
5184	 */
5185	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5186			lun->flags &= ~CTL_LUN_RESERVED;
5187
5188	mtx_unlock(&lun->lun_lock);
5189
5190	ctl_set_success(ctsio);
5191	ctl_done((union ctl_io *)ctsio);
5192	return (CTL_RETVAL_COMPLETE);
5193}
5194
5195int
5196ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5197{
5198	struct ctl_lun *lun;
5199	uint32_t residx;
5200
5201	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5202
5203	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5204	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5205
5206	/*
5207	 * XXX KDM right now, we only support LUN reservation.  We don't
5208	 * support 3rd party reservations, or extent reservations, which
5209	 * might actually need the parameter list.  If we've gotten this
5210	 * far, we've got a LUN reservation.  Anything else got kicked out
5211	 * above.  So, according to SPC, ignore the length.
5212	 */
5213
5214	mtx_lock(&lun->lun_lock);
5215	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5216		ctl_set_reservation_conflict(ctsio);
5217		goto bailout;
5218	}
5219
5220	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5221	if (lun->flags & CTL_LUN_PR_RESERVED) {
5222		ctl_set_success(ctsio);
5223		goto bailout;
5224	}
5225
5226	lun->flags |= CTL_LUN_RESERVED;
5227	lun->res_idx = residx;
5228	ctl_set_success(ctsio);
5229
5230bailout:
5231	mtx_unlock(&lun->lun_lock);
5232	ctl_done((union ctl_io *)ctsio);
5233	return (CTL_RETVAL_COMPLETE);
5234}
5235
5236int
5237ctl_start_stop(struct ctl_scsiio *ctsio)
5238{
5239	struct scsi_start_stop_unit *cdb;
5240	struct ctl_lun *lun;
5241	int retval;
5242
5243	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5244
5245	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5246	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5247
5248	if ((cdb->how & SSS_PC_MASK) == 0) {
5249		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5250		    (cdb->how & SSS_START) == 0) {
5251			uint32_t residx;
5252
5253			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5254			if (ctl_get_prkey(lun, residx) == 0 ||
5255			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5256
5257				ctl_set_reservation_conflict(ctsio);
5258				ctl_done((union ctl_io *)ctsio);
5259				return (CTL_RETVAL_COMPLETE);
5260			}
5261		}
5262
5263		if ((cdb->how & SSS_LOEJ) &&
5264		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5265			ctl_set_invalid_field(ctsio,
5266					      /*sks_valid*/ 1,
5267					      /*command*/ 1,
5268					      /*field*/ 4,
5269					      /*bit_valid*/ 1,
5270					      /*bit*/ 1);
5271			ctl_done((union ctl_io *)ctsio);
5272			return (CTL_RETVAL_COMPLETE);
5273		}
5274
5275		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5276		    lun->prevent_count > 0) {
5277			/* "Medium removal prevented" */
5278			ctl_set_sense(ctsio, /*current_error*/ 1,
5279			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5280			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5281			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5282			ctl_done((union ctl_io *)ctsio);
5283			return (CTL_RETVAL_COMPLETE);
5284		}
5285	}
5286
5287	retval = lun->backend->config_write((union ctl_io *)ctsio);
5288	return (retval);
5289}
5290
5291int
5292ctl_prevent_allow(struct ctl_scsiio *ctsio)
5293{
5294	struct ctl_lun *lun;
5295	struct scsi_prevent *cdb;
5296	int retval;
5297	uint32_t initidx;
5298
5299	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5300
5301	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5302	cdb = (struct scsi_prevent *)ctsio->cdb;
5303
5304	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5305		ctl_set_invalid_opcode(ctsio);
5306		ctl_done((union ctl_io *)ctsio);
5307		return (CTL_RETVAL_COMPLETE);
5308	}
5309
5310	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5311	mtx_lock(&lun->lun_lock);
5312	if ((cdb->how & PR_PREVENT) &&
5313	    ctl_is_set(lun->prevent, initidx) == 0) {
5314		ctl_set_mask(lun->prevent, initidx);
5315		lun->prevent_count++;
5316	} else if ((cdb->how & PR_PREVENT) == 0 &&
5317	    ctl_is_set(lun->prevent, initidx)) {
5318		ctl_clear_mask(lun->prevent, initidx);
5319		lun->prevent_count--;
5320	}
5321	mtx_unlock(&lun->lun_lock);
5322	retval = lun->backend->config_write((union ctl_io *)ctsio);
5323	return (retval);
5324}
5325
5326/*
5327 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5328 * we don't really do anything with the LBA and length fields if the user
5329 * passes them in.  Instead we'll just flush out the cache for the entire
5330 * LUN.
5331 */
5332int
5333ctl_sync_cache(struct ctl_scsiio *ctsio)
5334{
5335	struct ctl_lun *lun;
5336	struct ctl_softc *softc;
5337	struct ctl_lba_len_flags *lbalen;
5338	uint64_t starting_lba;
5339	uint32_t block_count;
5340	int retval;
5341	uint8_t byte2;
5342
5343	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5344
5345	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5346	softc = lun->ctl_softc;
5347	retval = 0;
5348
5349	switch (ctsio->cdb[0]) {
5350	case SYNCHRONIZE_CACHE: {
5351		struct scsi_sync_cache *cdb;
5352		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5353
5354		starting_lba = scsi_4btoul(cdb->begin_lba);
5355		block_count = scsi_2btoul(cdb->lb_count);
5356		byte2 = cdb->byte2;
5357		break;
5358	}
5359	case SYNCHRONIZE_CACHE_16: {
5360		struct scsi_sync_cache_16 *cdb;
5361		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5362
5363		starting_lba = scsi_8btou64(cdb->begin_lba);
5364		block_count = scsi_4btoul(cdb->lb_count);
5365		byte2 = cdb->byte2;
5366		break;
5367	}
5368	default:
5369		ctl_set_invalid_opcode(ctsio);
5370		ctl_done((union ctl_io *)ctsio);
5371		goto bailout;
5372		break; /* NOTREACHED */
5373	}
5374
5375	/*
5376	 * We check the LBA and length, but don't do anything with them.
5377	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5378	 * get flushed.  This check will just help satisfy anyone who wants
5379	 * to see an error for an out of range LBA.
5380	 */
5381	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5382		ctl_set_lba_out_of_range(ctsio,
5383		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5384		ctl_done((union ctl_io *)ctsio);
5385		goto bailout;
5386	}
5387
5388	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5389	lbalen->lba = starting_lba;
5390	lbalen->len = block_count;
5391	lbalen->flags = byte2;
5392	retval = lun->backend->config_write((union ctl_io *)ctsio);
5393
5394bailout:
5395	return (retval);
5396}
5397
5398int
5399ctl_format(struct ctl_scsiio *ctsio)
5400{
5401	struct scsi_format *cdb;
5402	struct ctl_lun *lun;
5403	int length, defect_list_len;
5404
5405	CTL_DEBUG_PRINT(("ctl_format\n"));
5406
5407	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5408
5409	cdb = (struct scsi_format *)ctsio->cdb;
5410
5411	length = 0;
5412	if (cdb->byte2 & SF_FMTDATA) {
5413		if (cdb->byte2 & SF_LONGLIST)
5414			length = sizeof(struct scsi_format_header_long);
5415		else
5416			length = sizeof(struct scsi_format_header_short);
5417	}
5418
5419	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5420	 && (length > 0)) {
5421		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5422		ctsio->kern_data_len = length;
5423		ctsio->kern_total_len = length;
5424		ctsio->kern_data_resid = 0;
5425		ctsio->kern_rel_offset = 0;
5426		ctsio->kern_sg_entries = 0;
5427		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5428		ctsio->be_move_done = ctl_config_move_done;
5429		ctl_datamove((union ctl_io *)ctsio);
5430
5431		return (CTL_RETVAL_COMPLETE);
5432	}
5433
5434	defect_list_len = 0;
5435
5436	if (cdb->byte2 & SF_FMTDATA) {
5437		if (cdb->byte2 & SF_LONGLIST) {
5438			struct scsi_format_header_long *header;
5439
5440			header = (struct scsi_format_header_long *)
5441				ctsio->kern_data_ptr;
5442
5443			defect_list_len = scsi_4btoul(header->defect_list_len);
5444			if (defect_list_len != 0) {
5445				ctl_set_invalid_field(ctsio,
5446						      /*sks_valid*/ 1,
5447						      /*command*/ 0,
5448						      /*field*/ 2,
5449						      /*bit_valid*/ 0,
5450						      /*bit*/ 0);
5451				goto bailout;
5452			}
5453		} else {
5454			struct scsi_format_header_short *header;
5455
5456			header = (struct scsi_format_header_short *)
5457				ctsio->kern_data_ptr;
5458
5459			defect_list_len = scsi_2btoul(header->defect_list_len);
5460			if (defect_list_len != 0) {
5461				ctl_set_invalid_field(ctsio,
5462						      /*sks_valid*/ 1,
5463						      /*command*/ 0,
5464						      /*field*/ 2,
5465						      /*bit_valid*/ 0,
5466						      /*bit*/ 0);
5467				goto bailout;
5468			}
5469		}
5470	}
5471
5472	ctl_set_success(ctsio);
5473bailout:
5474
5475	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5476		free(ctsio->kern_data_ptr, M_CTL);
5477		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5478	}
5479
5480	ctl_done((union ctl_io *)ctsio);
5481	return (CTL_RETVAL_COMPLETE);
5482}
5483
5484int
5485ctl_read_buffer(struct ctl_scsiio *ctsio)
5486{
5487	struct ctl_lun *lun;
5488	uint64_t buffer_offset;
5489	uint32_t len;
5490	uint8_t byte2;
5491	static uint8_t descr[4];
5492	static uint8_t echo_descr[4] = { 0 };
5493
5494	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5495	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5496	switch (ctsio->cdb[0]) {
5497	case READ_BUFFER: {
5498		struct scsi_read_buffer *cdb;
5499
5500		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5501		buffer_offset = scsi_3btoul(cdb->offset);
5502		len = scsi_3btoul(cdb->length);
5503		byte2 = cdb->byte2;
5504		break;
5505	}
5506	case READ_BUFFER_16: {
5507		struct scsi_read_buffer_16 *cdb;
5508
5509		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5510		buffer_offset = scsi_8btou64(cdb->offset);
5511		len = scsi_4btoul(cdb->length);
5512		byte2 = cdb->byte2;
5513		break;
5514	}
5515	default: /* This shouldn't happen. */
5516		ctl_set_invalid_opcode(ctsio);
5517		ctl_done((union ctl_io *)ctsio);
5518		return (CTL_RETVAL_COMPLETE);
5519	}
5520
5521	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5522	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5523		ctl_set_invalid_field(ctsio,
5524				      /*sks_valid*/ 1,
5525				      /*command*/ 1,
5526				      /*field*/ 6,
5527				      /*bit_valid*/ 0,
5528				      /*bit*/ 0);
5529		ctl_done((union ctl_io *)ctsio);
5530		return (CTL_RETVAL_COMPLETE);
5531	}
5532
5533	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5534		descr[0] = 0;
5535		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5536		ctsio->kern_data_ptr = descr;
5537		len = min(len, sizeof(descr));
5538	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5539		ctsio->kern_data_ptr = echo_descr;
5540		len = min(len, sizeof(echo_descr));
5541	} else {
5542		if (lun->write_buffer == NULL) {
5543			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5544			    M_CTL, M_WAITOK);
5545		}
5546		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5547	}
5548	ctsio->kern_data_len = len;
5549	ctsio->kern_total_len = len;
5550	ctsio->kern_data_resid = 0;
5551	ctsio->kern_rel_offset = 0;
5552	ctsio->kern_sg_entries = 0;
5553	ctl_set_success(ctsio);
5554	ctsio->be_move_done = ctl_config_move_done;
5555	ctl_datamove((union ctl_io *)ctsio);
5556	return (CTL_RETVAL_COMPLETE);
5557}
5558
5559int
5560ctl_write_buffer(struct ctl_scsiio *ctsio)
5561{
5562	struct scsi_write_buffer *cdb;
5563	struct ctl_lun *lun;
5564	int buffer_offset, len;
5565
5566	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5567
5568	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5569	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5570
5571	len = scsi_3btoul(cdb->length);
5572	buffer_offset = scsi_3btoul(cdb->offset);
5573
5574	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5575		ctl_set_invalid_field(ctsio,
5576				      /*sks_valid*/ 1,
5577				      /*command*/ 1,
5578				      /*field*/ 6,
5579				      /*bit_valid*/ 0,
5580				      /*bit*/ 0);
5581		ctl_done((union ctl_io *)ctsio);
5582		return (CTL_RETVAL_COMPLETE);
5583	}
5584
5585	/*
5586	 * If we've got a kernel request that hasn't been malloced yet,
5587	 * malloc it and tell the caller the data buffer is here.
5588	 */
5589	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5590		if (lun->write_buffer == NULL) {
5591			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5592			    M_CTL, M_WAITOK);
5593		}
5594		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5595		ctsio->kern_data_len = len;
5596		ctsio->kern_total_len = len;
5597		ctsio->kern_data_resid = 0;
5598		ctsio->kern_rel_offset = 0;
5599		ctsio->kern_sg_entries = 0;
5600		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5601		ctsio->be_move_done = ctl_config_move_done;
5602		ctl_datamove((union ctl_io *)ctsio);
5603
5604		return (CTL_RETVAL_COMPLETE);
5605	}
5606
5607	ctl_set_success(ctsio);
5608	ctl_done((union ctl_io *)ctsio);
5609	return (CTL_RETVAL_COMPLETE);
5610}
5611
5612int
5613ctl_write_same(struct ctl_scsiio *ctsio)
5614{
5615	struct ctl_lun *lun;
5616	struct ctl_lba_len_flags *lbalen;
5617	uint64_t lba;
5618	uint32_t num_blocks;
5619	int len, retval;
5620	uint8_t byte2;
5621
5622	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5623
5624	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5625
5626	switch (ctsio->cdb[0]) {
5627	case WRITE_SAME_10: {
5628		struct scsi_write_same_10 *cdb;
5629
5630		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5631
5632		lba = scsi_4btoul(cdb->addr);
5633		num_blocks = scsi_2btoul(cdb->length);
5634		byte2 = cdb->byte2;
5635		break;
5636	}
5637	case WRITE_SAME_16: {
5638		struct scsi_write_same_16 *cdb;
5639
5640		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5641
5642		lba = scsi_8btou64(cdb->addr);
5643		num_blocks = scsi_4btoul(cdb->length);
5644		byte2 = cdb->byte2;
5645		break;
5646	}
5647	default:
5648		/*
5649		 * We got a command we don't support.  This shouldn't
5650		 * happen, commands should be filtered out above us.
5651		 */
5652		ctl_set_invalid_opcode(ctsio);
5653		ctl_done((union ctl_io *)ctsio);
5654
5655		return (CTL_RETVAL_COMPLETE);
5656		break; /* NOTREACHED */
5657	}
5658
5659	/* ANCHOR flag can be used only together with UNMAP */
5660	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5661		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5662		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5663		ctl_done((union ctl_io *)ctsio);
5664		return (CTL_RETVAL_COMPLETE);
5665	}
5666
5667	/*
5668	 * The first check is to make sure we're in bounds, the second
5669	 * check is to catch wrap-around problems.  If the lba + num blocks
5670	 * is less than the lba, then we've wrapped around and the block
5671	 * range is invalid anyway.
5672	 */
5673	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5674	 || ((lba + num_blocks) < lba)) {
5675		ctl_set_lba_out_of_range(ctsio,
5676		    MAX(lba, lun->be_lun->maxlba + 1));
5677		ctl_done((union ctl_io *)ctsio);
5678		return (CTL_RETVAL_COMPLETE);
5679	}
5680
5681	/* Zero number of blocks means "to the last logical block" */
5682	if (num_blocks == 0) {
5683		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5684			ctl_set_invalid_field(ctsio,
5685					      /*sks_valid*/ 0,
5686					      /*command*/ 1,
5687					      /*field*/ 0,
5688					      /*bit_valid*/ 0,
5689					      /*bit*/ 0);
5690			ctl_done((union ctl_io *)ctsio);
5691			return (CTL_RETVAL_COMPLETE);
5692		}
5693		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5694	}
5695
5696	len = lun->be_lun->blocksize;
5697
5698	/*
5699	 * If we've got a kernel request that hasn't been malloced yet,
5700	 * malloc it and tell the caller the data buffer is here.
5701	 */
5702	if ((byte2 & SWS_NDOB) == 0 &&
5703	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5704		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5705		ctsio->kern_data_len = len;
5706		ctsio->kern_total_len = len;
5707		ctsio->kern_data_resid = 0;
5708		ctsio->kern_rel_offset = 0;
5709		ctsio->kern_sg_entries = 0;
5710		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5711		ctsio->be_move_done = ctl_config_move_done;
5712		ctl_datamove((union ctl_io *)ctsio);
5713
5714		return (CTL_RETVAL_COMPLETE);
5715	}
5716
5717	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5718	lbalen->lba = lba;
5719	lbalen->len = num_blocks;
5720	lbalen->flags = byte2;
5721	retval = lun->backend->config_write((union ctl_io *)ctsio);
5722
5723	return (retval);
5724}
5725
5726int
5727ctl_unmap(struct ctl_scsiio *ctsio)
5728{
5729	struct ctl_lun *lun;
5730	struct scsi_unmap *cdb;
5731	struct ctl_ptr_len_flags *ptrlen;
5732	struct scsi_unmap_header *hdr;
5733	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5734	uint64_t lba;
5735	uint32_t num_blocks;
5736	int len, retval;
5737	uint8_t byte2;
5738
5739	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5740
5741	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5742	cdb = (struct scsi_unmap *)ctsio->cdb;
5743
5744	len = scsi_2btoul(cdb->length);
5745	byte2 = cdb->byte2;
5746
5747	/*
5748	 * If we've got a kernel request that hasn't been malloced yet,
5749	 * malloc it and tell the caller the data buffer is here.
5750	 */
5751	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5752		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5753		ctsio->kern_data_len = len;
5754		ctsio->kern_total_len = len;
5755		ctsio->kern_data_resid = 0;
5756		ctsio->kern_rel_offset = 0;
5757		ctsio->kern_sg_entries = 0;
5758		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5759		ctsio->be_move_done = ctl_config_move_done;
5760		ctl_datamove((union ctl_io *)ctsio);
5761
5762		return (CTL_RETVAL_COMPLETE);
5763	}
5764
5765	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5766	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5767	if (len < sizeof (*hdr) ||
5768	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5769	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5770	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5771		ctl_set_invalid_field(ctsio,
5772				      /*sks_valid*/ 0,
5773				      /*command*/ 0,
5774				      /*field*/ 0,
5775				      /*bit_valid*/ 0,
5776				      /*bit*/ 0);
5777		goto done;
5778	}
5779	len = scsi_2btoul(hdr->desc_length);
5780	buf = (struct scsi_unmap_desc *)(hdr + 1);
5781	end = buf + len / sizeof(*buf);
5782
5783	endnz = buf;
5784	for (range = buf; range < end; range++) {
5785		lba = scsi_8btou64(range->lba);
5786		num_blocks = scsi_4btoul(range->length);
5787		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5788		 || ((lba + num_blocks) < lba)) {
5789			ctl_set_lba_out_of_range(ctsio,
5790			    MAX(lba, lun->be_lun->maxlba + 1));
5791			ctl_done((union ctl_io *)ctsio);
5792			return (CTL_RETVAL_COMPLETE);
5793		}
5794		if (num_blocks != 0)
5795			endnz = range + 1;
5796	}
5797
5798	/*
5799	 * Block backend can not handle zero last range.
5800	 * Filter it out and return if there is nothing left.
5801	 */
5802	len = (uint8_t *)endnz - (uint8_t *)buf;
5803	if (len == 0) {
5804		ctl_set_success(ctsio);
5805		goto done;
5806	}
5807
5808	mtx_lock(&lun->lun_lock);
5809	ptrlen = (struct ctl_ptr_len_flags *)
5810	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5811	ptrlen->ptr = (void *)buf;
5812	ptrlen->len = len;
5813	ptrlen->flags = byte2;
5814	ctl_check_blocked(lun);
5815	mtx_unlock(&lun->lun_lock);
5816
5817	retval = lun->backend->config_write((union ctl_io *)ctsio);
5818	return (retval);
5819
5820done:
5821	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5822		free(ctsio->kern_data_ptr, M_CTL);
5823		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5824	}
5825	ctl_done((union ctl_io *)ctsio);
5826	return (CTL_RETVAL_COMPLETE);
5827}
5828
5829int
5830ctl_default_page_handler(struct ctl_scsiio *ctsio,
5831			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5832{
5833	struct ctl_lun *lun;
5834	uint8_t *current_cp, *saved_cp;
5835	int set_ua;
5836	uint32_t initidx;
5837
5838	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5839	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5840	set_ua = 0;
5841
5842	current_cp = (page_index->page_data + (page_index->page_len *
5843	    CTL_PAGE_CURRENT));
5844	saved_cp = (page_index->page_data + (page_index->page_len *
5845	    CTL_PAGE_SAVED));
5846
5847	mtx_lock(&lun->lun_lock);
5848	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5849		memcpy(current_cp, page_ptr, page_index->page_len);
5850		memcpy(saved_cp, page_ptr, page_index->page_len);
5851		set_ua = 1;
5852	}
5853	if (set_ua != 0)
5854		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5855	mtx_unlock(&lun->lun_lock);
5856	if (set_ua) {
5857		ctl_isc_announce_mode(lun,
5858		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5859		    page_index->page_code, page_index->subpage);
5860	}
5861	return (CTL_RETVAL_COMPLETE);
5862}
5863
5864static void
5865ctl_ie_timer(void *arg)
5866{
5867	struct ctl_lun *lun = arg;
5868	uint64_t t;
5869
5870	if (lun->ie_asc == 0)
5871		return;
5872
5873	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5874		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5875	else
5876		lun->ie_reported = 0;
5877
5878	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5879		lun->ie_reportcnt++;
5880		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5881		if (t == 0 || t == UINT32_MAX)
5882			t = 3000;  /* 5 min */
5883		callout_schedule(&lun->ie_callout, t * hz / 10);
5884	}
5885}
5886
5887int
5888ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5889			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5890{
5891	struct scsi_info_exceptions_page *pg;
5892	struct ctl_lun *lun;
5893	uint64_t t;
5894
5895	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5896
5897	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5898	pg = (struct scsi_info_exceptions_page *)page_ptr;
5899	mtx_lock(&lun->lun_lock);
5900	if (pg->info_flags & SIEP_FLAGS_TEST) {
5901		lun->ie_asc = 0x5d;
5902		lun->ie_ascq = 0xff;
5903		if (pg->mrie == SIEP_MRIE_UA) {
5904			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5905			lun->ie_reported = 1;
5906		} else {
5907			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5908			lun->ie_reported = -1;
5909		}
5910		lun->ie_reportcnt = 1;
5911		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5912			lun->ie_reportcnt++;
5913			t = scsi_4btoul(pg->interval_timer);
5914			if (t == 0 || t == UINT32_MAX)
5915				t = 3000;  /* 5 min */
5916			callout_reset(&lun->ie_callout, t * hz / 10,
5917			    ctl_ie_timer, lun);
5918		}
5919	} else {
5920		lun->ie_asc = 0;
5921		lun->ie_ascq = 0;
5922		lun->ie_reported = 1;
5923		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5924		lun->ie_reportcnt = UINT32_MAX;
5925		callout_stop(&lun->ie_callout);
5926	}
5927	mtx_unlock(&lun->lun_lock);
5928	return (CTL_RETVAL_COMPLETE);
5929}
5930
5931static int
5932ctl_do_mode_select(union ctl_io *io)
5933{
5934	struct scsi_mode_page_header *page_header;
5935	struct ctl_page_index *page_index;
5936	struct ctl_scsiio *ctsio;
5937	int page_len, page_len_offset, page_len_size;
5938	union ctl_modepage_info *modepage_info;
5939	struct ctl_lun *lun;
5940	int *len_left, *len_used;
5941	int retval, i;
5942
5943	ctsio = &io->scsiio;
5944	page_index = NULL;
5945	page_len = 0;
5946	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5947
5948	modepage_info = (union ctl_modepage_info *)
5949		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5950	len_left = &modepage_info->header.len_left;
5951	len_used = &modepage_info->header.len_used;
5952
5953do_next_page:
5954
5955	page_header = (struct scsi_mode_page_header *)
5956		(ctsio->kern_data_ptr + *len_used);
5957
5958	if (*len_left == 0) {
5959		free(ctsio->kern_data_ptr, M_CTL);
5960		ctl_set_success(ctsio);
5961		ctl_done((union ctl_io *)ctsio);
5962		return (CTL_RETVAL_COMPLETE);
5963	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5964
5965		free(ctsio->kern_data_ptr, M_CTL);
5966		ctl_set_param_len_error(ctsio);
5967		ctl_done((union ctl_io *)ctsio);
5968		return (CTL_RETVAL_COMPLETE);
5969
5970	} else if ((page_header->page_code & SMPH_SPF)
5971		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5972
5973		free(ctsio->kern_data_ptr, M_CTL);
5974		ctl_set_param_len_error(ctsio);
5975		ctl_done((union ctl_io *)ctsio);
5976		return (CTL_RETVAL_COMPLETE);
5977	}
5978
5979
5980	/*
5981	 * XXX KDM should we do something with the block descriptor?
5982	 */
5983	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5984		page_index = &lun->mode_pages.index[i];
5985		if (lun->be_lun->lun_type == T_DIRECT &&
5986		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5987			continue;
5988		if (lun->be_lun->lun_type == T_PROCESSOR &&
5989		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5990			continue;
5991		if (lun->be_lun->lun_type == T_CDROM &&
5992		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5993			continue;
5994
5995		if ((page_index->page_code & SMPH_PC_MASK) !=
5996		    (page_header->page_code & SMPH_PC_MASK))
5997			continue;
5998
5999		/*
6000		 * If neither page has a subpage code, then we've got a
6001		 * match.
6002		 */
6003		if (((page_index->page_code & SMPH_SPF) == 0)
6004		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6005			page_len = page_header->page_length;
6006			break;
6007		}
6008
6009		/*
6010		 * If both pages have subpages, then the subpage numbers
6011		 * have to match.
6012		 */
6013		if ((page_index->page_code & SMPH_SPF)
6014		  && (page_header->page_code & SMPH_SPF)) {
6015			struct scsi_mode_page_header_sp *sph;
6016
6017			sph = (struct scsi_mode_page_header_sp *)page_header;
6018			if (page_index->subpage == sph->subpage) {
6019				page_len = scsi_2btoul(sph->page_length);
6020				break;
6021			}
6022		}
6023	}
6024
6025	/*
6026	 * If we couldn't find the page, or if we don't have a mode select
6027	 * handler for it, send back an error to the user.
6028	 */
6029	if ((i >= CTL_NUM_MODE_PAGES)
6030	 || (page_index->select_handler == NULL)) {
6031		ctl_set_invalid_field(ctsio,
6032				      /*sks_valid*/ 1,
6033				      /*command*/ 0,
6034				      /*field*/ *len_used,
6035				      /*bit_valid*/ 0,
6036				      /*bit*/ 0);
6037		free(ctsio->kern_data_ptr, M_CTL);
6038		ctl_done((union ctl_io *)ctsio);
6039		return (CTL_RETVAL_COMPLETE);
6040	}
6041
6042	if (page_index->page_code & SMPH_SPF) {
6043		page_len_offset = 2;
6044		page_len_size = 2;
6045	} else {
6046		page_len_size = 1;
6047		page_len_offset = 1;
6048	}
6049
6050	/*
6051	 * If the length the initiator gives us isn't the one we specify in
6052	 * the mode page header, or if they didn't specify enough data in
6053	 * the CDB to avoid truncating this page, kick out the request.
6054	 */
6055	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6056		ctl_set_invalid_field(ctsio,
6057				      /*sks_valid*/ 1,
6058				      /*command*/ 0,
6059				      /*field*/ *len_used + page_len_offset,
6060				      /*bit_valid*/ 0,
6061				      /*bit*/ 0);
6062		free(ctsio->kern_data_ptr, M_CTL);
6063		ctl_done((union ctl_io *)ctsio);
6064		return (CTL_RETVAL_COMPLETE);
6065	}
6066	if (*len_left < page_index->page_len) {
6067		free(ctsio->kern_data_ptr, M_CTL);
6068		ctl_set_param_len_error(ctsio);
6069		ctl_done((union ctl_io *)ctsio);
6070		return (CTL_RETVAL_COMPLETE);
6071	}
6072
6073	/*
6074	 * Run through the mode page, checking to make sure that the bits
6075	 * the user changed are actually legal for him to change.
6076	 */
6077	for (i = 0; i < page_index->page_len; i++) {
6078		uint8_t *user_byte, *change_mask, *current_byte;
6079		int bad_bit;
6080		int j;
6081
6082		user_byte = (uint8_t *)page_header + i;
6083		change_mask = page_index->page_data +
6084			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6085		current_byte = page_index->page_data +
6086			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6087
6088		/*
6089		 * Check to see whether the user set any bits in this byte
6090		 * that he is not allowed to set.
6091		 */
6092		if ((*user_byte & ~(*change_mask)) ==
6093		    (*current_byte & ~(*change_mask)))
6094			continue;
6095
6096		/*
6097		 * Go through bit by bit to determine which one is illegal.
6098		 */
6099		bad_bit = 0;
6100		for (j = 7; j >= 0; j--) {
6101			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6102			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6103				bad_bit = i;
6104				break;
6105			}
6106		}
6107		ctl_set_invalid_field(ctsio,
6108				      /*sks_valid*/ 1,
6109				      /*command*/ 0,
6110				      /*field*/ *len_used + i,
6111				      /*bit_valid*/ 1,
6112				      /*bit*/ bad_bit);
6113		free(ctsio->kern_data_ptr, M_CTL);
6114		ctl_done((union ctl_io *)ctsio);
6115		return (CTL_RETVAL_COMPLETE);
6116	}
6117
6118	/*
6119	 * Decrement these before we call the page handler, since we may
6120	 * end up getting called back one way or another before the handler
6121	 * returns to this context.
6122	 */
6123	*len_left -= page_index->page_len;
6124	*len_used += page_index->page_len;
6125
6126	retval = page_index->select_handler(ctsio, page_index,
6127					    (uint8_t *)page_header);
6128
6129	/*
6130	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6131	 * wait until this queued command completes to finish processing
6132	 * the mode page.  If it returns anything other than
6133	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6134	 * already set the sense information, freed the data pointer, and
6135	 * completed the io for us.
6136	 */
6137	if (retval != CTL_RETVAL_COMPLETE)
6138		goto bailout_no_done;
6139
6140	/*
6141	 * If the initiator sent us more than one page, parse the next one.
6142	 */
6143	if (*len_left > 0)
6144		goto do_next_page;
6145
6146	ctl_set_success(ctsio);
6147	free(ctsio->kern_data_ptr, M_CTL);
6148	ctl_done((union ctl_io *)ctsio);
6149
6150bailout_no_done:
6151
6152	return (CTL_RETVAL_COMPLETE);
6153
6154}
6155
6156int
6157ctl_mode_select(struct ctl_scsiio *ctsio)
6158{
6159	int param_len, pf, sp;
6160	int header_size, bd_len;
6161	union ctl_modepage_info *modepage_info;
6162
6163	switch (ctsio->cdb[0]) {
6164	case MODE_SELECT_6: {
6165		struct scsi_mode_select_6 *cdb;
6166
6167		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6168
6169		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6170		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6171		param_len = cdb->length;
6172		header_size = sizeof(struct scsi_mode_header_6);
6173		break;
6174	}
6175	case MODE_SELECT_10: {
6176		struct scsi_mode_select_10 *cdb;
6177
6178		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6179
6180		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6181		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6182		param_len = scsi_2btoul(cdb->length);
6183		header_size = sizeof(struct scsi_mode_header_10);
6184		break;
6185	}
6186	default:
6187		ctl_set_invalid_opcode(ctsio);
6188		ctl_done((union ctl_io *)ctsio);
6189		return (CTL_RETVAL_COMPLETE);
6190	}
6191
6192	/*
6193	 * From SPC-3:
6194	 * "A parameter list length of zero indicates that the Data-Out Buffer
6195	 * shall be empty. This condition shall not be considered as an error."
6196	 */
6197	if (param_len == 0) {
6198		ctl_set_success(ctsio);
6199		ctl_done((union ctl_io *)ctsio);
6200		return (CTL_RETVAL_COMPLETE);
6201	}
6202
6203	/*
6204	 * Since we'll hit this the first time through, prior to
6205	 * allocation, we don't need to free a data buffer here.
6206	 */
6207	if (param_len < header_size) {
6208		ctl_set_param_len_error(ctsio);
6209		ctl_done((union ctl_io *)ctsio);
6210		return (CTL_RETVAL_COMPLETE);
6211	}
6212
6213	/*
6214	 * Allocate the data buffer and grab the user's data.  In theory,
6215	 * we shouldn't have to sanity check the parameter list length here
6216	 * because the maximum size is 64K.  We should be able to malloc
6217	 * that much without too many problems.
6218	 */
6219	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6220		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6221		ctsio->kern_data_len = param_len;
6222		ctsio->kern_total_len = param_len;
6223		ctsio->kern_data_resid = 0;
6224		ctsio->kern_rel_offset = 0;
6225		ctsio->kern_sg_entries = 0;
6226		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6227		ctsio->be_move_done = ctl_config_move_done;
6228		ctl_datamove((union ctl_io *)ctsio);
6229
6230		return (CTL_RETVAL_COMPLETE);
6231	}
6232
6233	switch (ctsio->cdb[0]) {
6234	case MODE_SELECT_6: {
6235		struct scsi_mode_header_6 *mh6;
6236
6237		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6238		bd_len = mh6->blk_desc_len;
6239		break;
6240	}
6241	case MODE_SELECT_10: {
6242		struct scsi_mode_header_10 *mh10;
6243
6244		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6245		bd_len = scsi_2btoul(mh10->blk_desc_len);
6246		break;
6247	}
6248	default:
6249		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6250	}
6251
6252	if (param_len < (header_size + bd_len)) {
6253		free(ctsio->kern_data_ptr, M_CTL);
6254		ctl_set_param_len_error(ctsio);
6255		ctl_done((union ctl_io *)ctsio);
6256		return (CTL_RETVAL_COMPLETE);
6257	}
6258
6259	/*
6260	 * Set the IO_CONT flag, so that if this I/O gets passed to
6261	 * ctl_config_write_done(), it'll get passed back to
6262	 * ctl_do_mode_select() for further processing, or completion if
6263	 * we're all done.
6264	 */
6265	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6266	ctsio->io_cont = ctl_do_mode_select;
6267
6268	modepage_info = (union ctl_modepage_info *)
6269		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6270	memset(modepage_info, 0, sizeof(*modepage_info));
6271	modepage_info->header.len_left = param_len - header_size - bd_len;
6272	modepage_info->header.len_used = header_size + bd_len;
6273
6274	return (ctl_do_mode_select((union ctl_io *)ctsio));
6275}
6276
6277int
6278ctl_mode_sense(struct ctl_scsiio *ctsio)
6279{
6280	struct ctl_lun *lun;
6281	int pc, page_code, dbd, llba, subpage;
6282	int alloc_len, page_len, header_len, total_len;
6283	struct scsi_mode_block_descr *block_desc;
6284	struct ctl_page_index *page_index;
6285
6286	dbd = 0;
6287	llba = 0;
6288	block_desc = NULL;
6289
6290	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6291
6292	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6293	switch (ctsio->cdb[0]) {
6294	case MODE_SENSE_6: {
6295		struct scsi_mode_sense_6 *cdb;
6296
6297		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6298
6299		header_len = sizeof(struct scsi_mode_hdr_6);
6300		if (cdb->byte2 & SMS_DBD)
6301			dbd = 1;
6302		else
6303			header_len += sizeof(struct scsi_mode_block_descr);
6304
6305		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6306		page_code = cdb->page & SMS_PAGE_CODE;
6307		subpage = cdb->subpage;
6308		alloc_len = cdb->length;
6309		break;
6310	}
6311	case MODE_SENSE_10: {
6312		struct scsi_mode_sense_10 *cdb;
6313
6314		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6315
6316		header_len = sizeof(struct scsi_mode_hdr_10);
6317
6318		if (cdb->byte2 & SMS_DBD)
6319			dbd = 1;
6320		else
6321			header_len += sizeof(struct scsi_mode_block_descr);
6322		if (cdb->byte2 & SMS10_LLBAA)
6323			llba = 1;
6324		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6325		page_code = cdb->page & SMS_PAGE_CODE;
6326		subpage = cdb->subpage;
6327		alloc_len = scsi_2btoul(cdb->length);
6328		break;
6329	}
6330	default:
6331		ctl_set_invalid_opcode(ctsio);
6332		ctl_done((union ctl_io *)ctsio);
6333		return (CTL_RETVAL_COMPLETE);
6334		break; /* NOTREACHED */
6335	}
6336
6337	/*
6338	 * We have to make a first pass through to calculate the size of
6339	 * the pages that match the user's query.  Then we allocate enough
6340	 * memory to hold it, and actually copy the data into the buffer.
6341	 */
6342	switch (page_code) {
6343	case SMS_ALL_PAGES_PAGE: {
6344		u_int i;
6345
6346		page_len = 0;
6347
6348		/*
6349		 * At the moment, values other than 0 and 0xff here are
6350		 * reserved according to SPC-3.
6351		 */
6352		if ((subpage != SMS_SUBPAGE_PAGE_0)
6353		 && (subpage != SMS_SUBPAGE_ALL)) {
6354			ctl_set_invalid_field(ctsio,
6355					      /*sks_valid*/ 1,
6356					      /*command*/ 1,
6357					      /*field*/ 3,
6358					      /*bit_valid*/ 0,
6359					      /*bit*/ 0);
6360			ctl_done((union ctl_io *)ctsio);
6361			return (CTL_RETVAL_COMPLETE);
6362		}
6363
6364		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6365			page_index = &lun->mode_pages.index[i];
6366
6367			/* Make sure the page is supported for this dev type */
6368			if (lun->be_lun->lun_type == T_DIRECT &&
6369			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6370				continue;
6371			if (lun->be_lun->lun_type == T_PROCESSOR &&
6372			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6373				continue;
6374			if (lun->be_lun->lun_type == T_CDROM &&
6375			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6376				continue;
6377
6378			/*
6379			 * We don't use this subpage if the user didn't
6380			 * request all subpages.
6381			 */
6382			if ((page_index->subpage != 0)
6383			 && (subpage == SMS_SUBPAGE_PAGE_0))
6384				continue;
6385
6386#if 0
6387			printf("found page %#x len %d\n",
6388			       page_index->page_code & SMPH_PC_MASK,
6389			       page_index->page_len);
6390#endif
6391			page_len += page_index->page_len;
6392		}
6393		break;
6394	}
6395	default: {
6396		u_int i;
6397
6398		page_len = 0;
6399
6400		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6401			page_index = &lun->mode_pages.index[i];
6402
6403			/* Make sure the page is supported for this dev type */
6404			if (lun->be_lun->lun_type == T_DIRECT &&
6405			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6406				continue;
6407			if (lun->be_lun->lun_type == T_PROCESSOR &&
6408			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6409				continue;
6410			if (lun->be_lun->lun_type == T_CDROM &&
6411			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6412				continue;
6413
6414			/* Look for the right page code */
6415			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6416				continue;
6417
6418			/* Look for the right subpage or the subpage wildcard*/
6419			if ((page_index->subpage != subpage)
6420			 && (subpage != SMS_SUBPAGE_ALL))
6421				continue;
6422
6423#if 0
6424			printf("found page %#x len %d\n",
6425			       page_index->page_code & SMPH_PC_MASK,
6426			       page_index->page_len);
6427#endif
6428
6429			page_len += page_index->page_len;
6430		}
6431
6432		if (page_len == 0) {
6433			ctl_set_invalid_field(ctsio,
6434					      /*sks_valid*/ 1,
6435					      /*command*/ 1,
6436					      /*field*/ 2,
6437					      /*bit_valid*/ 1,
6438					      /*bit*/ 5);
6439			ctl_done((union ctl_io *)ctsio);
6440			return (CTL_RETVAL_COMPLETE);
6441		}
6442		break;
6443	}
6444	}
6445
6446	total_len = header_len + page_len;
6447#if 0
6448	printf("header_len = %d, page_len = %d, total_len = %d\n",
6449	       header_len, page_len, total_len);
6450#endif
6451
6452	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6453	ctsio->kern_sg_entries = 0;
6454	ctsio->kern_data_resid = 0;
6455	ctsio->kern_rel_offset = 0;
6456	if (total_len < alloc_len) {
6457		ctsio->residual = alloc_len - total_len;
6458		ctsio->kern_data_len = total_len;
6459		ctsio->kern_total_len = total_len;
6460	} else {
6461		ctsio->residual = 0;
6462		ctsio->kern_data_len = alloc_len;
6463		ctsio->kern_total_len = alloc_len;
6464	}
6465
6466	switch (ctsio->cdb[0]) {
6467	case MODE_SENSE_6: {
6468		struct scsi_mode_hdr_6 *header;
6469
6470		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6471
6472		header->datalen = MIN(total_len - 1, 254);
6473		if (lun->be_lun->lun_type == T_DIRECT) {
6474			header->dev_specific = 0x10; /* DPOFUA */
6475			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6476			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6477				header->dev_specific |= 0x80; /* WP */
6478		}
6479		if (dbd)
6480			header->block_descr_len = 0;
6481		else
6482			header->block_descr_len =
6483				sizeof(struct scsi_mode_block_descr);
6484		block_desc = (struct scsi_mode_block_descr *)&header[1];
6485		break;
6486	}
6487	case MODE_SENSE_10: {
6488		struct scsi_mode_hdr_10 *header;
6489		int datalen;
6490
6491		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6492
6493		datalen = MIN(total_len - 2, 65533);
6494		scsi_ulto2b(datalen, header->datalen);
6495		if (lun->be_lun->lun_type == T_DIRECT) {
6496			header->dev_specific = 0x10; /* DPOFUA */
6497			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6498			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6499				header->dev_specific |= 0x80; /* WP */
6500		}
6501		if (dbd)
6502			scsi_ulto2b(0, header->block_descr_len);
6503		else
6504			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6505				    header->block_descr_len);
6506		block_desc = (struct scsi_mode_block_descr *)&header[1];
6507		break;
6508	}
6509	default:
6510		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6511	}
6512
6513	/*
6514	 * If we've got a disk, use its blocksize in the block
6515	 * descriptor.  Otherwise, just set it to 0.
6516	 */
6517	if (dbd == 0) {
6518		if (lun->be_lun->lun_type == T_DIRECT)
6519			scsi_ulto3b(lun->be_lun->blocksize,
6520				    block_desc->block_len);
6521		else
6522			scsi_ulto3b(0, block_desc->block_len);
6523	}
6524
6525	switch (page_code) {
6526	case SMS_ALL_PAGES_PAGE: {
6527		int i, data_used;
6528
6529		data_used = header_len;
6530		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6531			struct ctl_page_index *page_index;
6532
6533			page_index = &lun->mode_pages.index[i];
6534			if (lun->be_lun->lun_type == T_DIRECT &&
6535			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6536				continue;
6537			if (lun->be_lun->lun_type == T_PROCESSOR &&
6538			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6539				continue;
6540			if (lun->be_lun->lun_type == T_CDROM &&
6541			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6542				continue;
6543
6544			/*
6545			 * We don't use this subpage if the user didn't
6546			 * request all subpages.  We already checked (above)
6547			 * to make sure the user only specified a subpage
6548			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6549			 */
6550			if ((page_index->subpage != 0)
6551			 && (subpage == SMS_SUBPAGE_PAGE_0))
6552				continue;
6553
6554			/*
6555			 * Call the handler, if it exists, to update the
6556			 * page to the latest values.
6557			 */
6558			if (page_index->sense_handler != NULL)
6559				page_index->sense_handler(ctsio, page_index,pc);
6560
6561			memcpy(ctsio->kern_data_ptr + data_used,
6562			       page_index->page_data +
6563			       (page_index->page_len * pc),
6564			       page_index->page_len);
6565			data_used += page_index->page_len;
6566		}
6567		break;
6568	}
6569	default: {
6570		int i, data_used;
6571
6572		data_used = header_len;
6573
6574		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6575			struct ctl_page_index *page_index;
6576
6577			page_index = &lun->mode_pages.index[i];
6578
6579			/* Look for the right page code */
6580			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6581				continue;
6582
6583			/* Look for the right subpage or the subpage wildcard*/
6584			if ((page_index->subpage != subpage)
6585			 && (subpage != SMS_SUBPAGE_ALL))
6586				continue;
6587
6588			/* Make sure the page is supported for this dev type */
6589			if (lun->be_lun->lun_type == T_DIRECT &&
6590			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6591				continue;
6592			if (lun->be_lun->lun_type == T_PROCESSOR &&
6593			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6594				continue;
6595			if (lun->be_lun->lun_type == T_CDROM &&
6596			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6597				continue;
6598
6599			/*
6600			 * Call the handler, if it exists, to update the
6601			 * page to the latest values.
6602			 */
6603			if (page_index->sense_handler != NULL)
6604				page_index->sense_handler(ctsio, page_index,pc);
6605
6606			memcpy(ctsio->kern_data_ptr + data_used,
6607			       page_index->page_data +
6608			       (page_index->page_len * pc),
6609			       page_index->page_len);
6610			data_used += page_index->page_len;
6611		}
6612		break;
6613	}
6614	}
6615
6616	ctl_set_success(ctsio);
6617	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6618	ctsio->be_move_done = ctl_config_move_done;
6619	ctl_datamove((union ctl_io *)ctsio);
6620	return (CTL_RETVAL_COMPLETE);
6621}
6622
6623int
6624ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6625			       struct ctl_page_index *page_index,
6626			       int pc)
6627{
6628	struct ctl_lun *lun;
6629	struct scsi_log_param_header *phdr;
6630	uint8_t *data;
6631	uint64_t val;
6632
6633	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6634	data = page_index->page_data;
6635
6636	if (lun->backend->lun_attr != NULL &&
6637	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6638	     != UINT64_MAX) {
6639		phdr = (struct scsi_log_param_header *)data;
6640		scsi_ulto2b(0x0001, phdr->param_code);
6641		phdr->param_control = SLP_LBIN | SLP_LP;
6642		phdr->param_len = 8;
6643		data = (uint8_t *)(phdr + 1);
6644		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6645		data[4] = 0x02; /* per-pool */
6646		data += phdr->param_len;
6647	}
6648
6649	if (lun->backend->lun_attr != NULL &&
6650	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6651	     != UINT64_MAX) {
6652		phdr = (struct scsi_log_param_header *)data;
6653		scsi_ulto2b(0x0002, phdr->param_code);
6654		phdr->param_control = SLP_LBIN | SLP_LP;
6655		phdr->param_len = 8;
6656		data = (uint8_t *)(phdr + 1);
6657		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6658		data[4] = 0x01; /* per-LUN */
6659		data += phdr->param_len;
6660	}
6661
6662	if (lun->backend->lun_attr != NULL &&
6663	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6664	     != UINT64_MAX) {
6665		phdr = (struct scsi_log_param_header *)data;
6666		scsi_ulto2b(0x00f1, phdr->param_code);
6667		phdr->param_control = SLP_LBIN | SLP_LP;
6668		phdr->param_len = 8;
6669		data = (uint8_t *)(phdr + 1);
6670		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6671		data[4] = 0x02; /* per-pool */
6672		data += phdr->param_len;
6673	}
6674
6675	if (lun->backend->lun_attr != NULL &&
6676	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6677	     != UINT64_MAX) {
6678		phdr = (struct scsi_log_param_header *)data;
6679		scsi_ulto2b(0x00f2, phdr->param_code);
6680		phdr->param_control = SLP_LBIN | SLP_LP;
6681		phdr->param_len = 8;
6682		data = (uint8_t *)(phdr + 1);
6683		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6684		data[4] = 0x02; /* per-pool */
6685		data += phdr->param_len;
6686	}
6687
6688	page_index->page_len = data - page_index->page_data;
6689	return (0);
6690}
6691
6692int
6693ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6694			       struct ctl_page_index *page_index,
6695			       int pc)
6696{
6697	struct ctl_lun *lun;
6698	struct stat_page *data;
6699	uint64_t rn, wn, rb, wb;
6700	struct bintime rt, wt;
6701	int i;
6702
6703	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6704	data = (struct stat_page *)page_index->page_data;
6705
6706	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6707	data->sap.hdr.param_control = SLP_LBIN;
6708	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6709	    sizeof(struct scsi_log_param_header);
6710	rn = wn = rb = wb = 0;
6711	bintime_clear(&rt);
6712	bintime_clear(&wt);
6713	for (i = 0; i < CTL_MAX_PORTS; i++) {
6714		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6715		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6716		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6717		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6718		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6719		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6720	}
6721	scsi_u64to8b(rn, data->sap.read_num);
6722	scsi_u64to8b(wn, data->sap.write_num);
6723	if (lun->stats.blocksize > 0) {
6724		scsi_u64to8b(wb / lun->stats.blocksize,
6725		    data->sap.recvieved_lba);
6726		scsi_u64to8b(rb / lun->stats.blocksize,
6727		    data->sap.transmitted_lba);
6728	}
6729	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6730	    data->sap.read_int);
6731	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6732	    data->sap.write_int);
6733	scsi_u64to8b(0, data->sap.weighted_num);
6734	scsi_u64to8b(0, data->sap.weighted_int);
6735	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6736	data->it.hdr.param_control = SLP_LBIN;
6737	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6738	    sizeof(struct scsi_log_param_header);
6739#ifdef CTL_TIME_IO
6740	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6741#endif
6742	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6743	data->it.hdr.param_control = SLP_LBIN;
6744	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6745	    sizeof(struct scsi_log_param_header);
6746	scsi_ulto4b(3, data->ti.exponent);
6747	scsi_ulto4b(1, data->ti.integer);
6748	return (0);
6749}
6750
6751int
6752ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6753			       struct ctl_page_index *page_index,
6754			       int pc)
6755{
6756	struct ctl_lun *lun;
6757	struct scsi_log_informational_exceptions *data;
6758
6759	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6760	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6761
6762	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6763	data->hdr.param_control = SLP_LBIN;
6764	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6765	    sizeof(struct scsi_log_param_header);
6766	data->ie_asc = lun->ie_asc;
6767	data->ie_ascq = lun->ie_ascq;
6768	data->temperature = 0xff;
6769	return (0);
6770}
6771
6772int
6773ctl_log_sense(struct ctl_scsiio *ctsio)
6774{
6775	struct ctl_lun *lun;
6776	int i, pc, page_code, subpage;
6777	int alloc_len, total_len;
6778	struct ctl_page_index *page_index;
6779	struct scsi_log_sense *cdb;
6780	struct scsi_log_header *header;
6781
6782	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6783
6784	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6785	cdb = (struct scsi_log_sense *)ctsio->cdb;
6786	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6787	page_code = cdb->page & SLS_PAGE_CODE;
6788	subpage = cdb->subpage;
6789	alloc_len = scsi_2btoul(cdb->length);
6790
6791	page_index = NULL;
6792	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6793		page_index = &lun->log_pages.index[i];
6794
6795		/* Look for the right page code */
6796		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6797			continue;
6798
6799		/* Look for the right subpage or the subpage wildcard*/
6800		if (page_index->subpage != subpage)
6801			continue;
6802
6803		break;
6804	}
6805	if (i >= CTL_NUM_LOG_PAGES) {
6806		ctl_set_invalid_field(ctsio,
6807				      /*sks_valid*/ 1,
6808				      /*command*/ 1,
6809				      /*field*/ 2,
6810				      /*bit_valid*/ 0,
6811				      /*bit*/ 0);
6812		ctl_done((union ctl_io *)ctsio);
6813		return (CTL_RETVAL_COMPLETE);
6814	}
6815
6816	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6817
6818	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6819	ctsio->kern_sg_entries = 0;
6820	ctsio->kern_data_resid = 0;
6821	ctsio->kern_rel_offset = 0;
6822	if (total_len < alloc_len) {
6823		ctsio->residual = alloc_len - total_len;
6824		ctsio->kern_data_len = total_len;
6825		ctsio->kern_total_len = total_len;
6826	} else {
6827		ctsio->residual = 0;
6828		ctsio->kern_data_len = alloc_len;
6829		ctsio->kern_total_len = alloc_len;
6830	}
6831
6832	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6833	header->page = page_index->page_code;
6834	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6835		header->page |= SL_DS;
6836	if (page_index->subpage) {
6837		header->page |= SL_SPF;
6838		header->subpage = page_index->subpage;
6839	}
6840	scsi_ulto2b(page_index->page_len, header->datalen);
6841
6842	/*
6843	 * Call the handler, if it exists, to update the
6844	 * page to the latest values.
6845	 */
6846	if (page_index->sense_handler != NULL)
6847		page_index->sense_handler(ctsio, page_index, pc);
6848
6849	memcpy(header + 1, page_index->page_data, page_index->page_len);
6850
6851	ctl_set_success(ctsio);
6852	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6853	ctsio->be_move_done = ctl_config_move_done;
6854	ctl_datamove((union ctl_io *)ctsio);
6855	return (CTL_RETVAL_COMPLETE);
6856}
6857
6858int
6859ctl_read_capacity(struct ctl_scsiio *ctsio)
6860{
6861	struct scsi_read_capacity *cdb;
6862	struct scsi_read_capacity_data *data;
6863	struct ctl_lun *lun;
6864	uint32_t lba;
6865
6866	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6867
6868	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6869
6870	lba = scsi_4btoul(cdb->addr);
6871	if (((cdb->pmi & SRC_PMI) == 0)
6872	 && (lba != 0)) {
6873		ctl_set_invalid_field(/*ctsio*/ ctsio,
6874				      /*sks_valid*/ 1,
6875				      /*command*/ 1,
6876				      /*field*/ 2,
6877				      /*bit_valid*/ 0,
6878				      /*bit*/ 0);
6879		ctl_done((union ctl_io *)ctsio);
6880		return (CTL_RETVAL_COMPLETE);
6881	}
6882
6883	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6884
6885	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6886	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6887	ctsio->residual = 0;
6888	ctsio->kern_data_len = sizeof(*data);
6889	ctsio->kern_total_len = sizeof(*data);
6890	ctsio->kern_data_resid = 0;
6891	ctsio->kern_rel_offset = 0;
6892	ctsio->kern_sg_entries = 0;
6893
6894	/*
6895	 * If the maximum LBA is greater than 0xfffffffe, the user must
6896	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6897	 * serivce action set.
6898	 */
6899	if (lun->be_lun->maxlba > 0xfffffffe)
6900		scsi_ulto4b(0xffffffff, data->addr);
6901	else
6902		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6903
6904	/*
6905	 * XXX KDM this may not be 512 bytes...
6906	 */
6907	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6908
6909	ctl_set_success(ctsio);
6910	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6911	ctsio->be_move_done = ctl_config_move_done;
6912	ctl_datamove((union ctl_io *)ctsio);
6913	return (CTL_RETVAL_COMPLETE);
6914}
6915
6916int
6917ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6918{
6919	struct scsi_read_capacity_16 *cdb;
6920	struct scsi_read_capacity_data_long *data;
6921	struct ctl_lun *lun;
6922	uint64_t lba;
6923	uint32_t alloc_len;
6924
6925	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6926
6927	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6928
6929	alloc_len = scsi_4btoul(cdb->alloc_len);
6930	lba = scsi_8btou64(cdb->addr);
6931
6932	if ((cdb->reladr & SRC16_PMI)
6933	 && (lba != 0)) {
6934		ctl_set_invalid_field(/*ctsio*/ ctsio,
6935				      /*sks_valid*/ 1,
6936				      /*command*/ 1,
6937				      /*field*/ 2,
6938				      /*bit_valid*/ 0,
6939				      /*bit*/ 0);
6940		ctl_done((union ctl_io *)ctsio);
6941		return (CTL_RETVAL_COMPLETE);
6942	}
6943
6944	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6945
6946	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6947	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6948
6949	if (sizeof(*data) < alloc_len) {
6950		ctsio->residual = alloc_len - sizeof(*data);
6951		ctsio->kern_data_len = sizeof(*data);
6952		ctsio->kern_total_len = sizeof(*data);
6953	} else {
6954		ctsio->residual = 0;
6955		ctsio->kern_data_len = alloc_len;
6956		ctsio->kern_total_len = alloc_len;
6957	}
6958	ctsio->kern_data_resid = 0;
6959	ctsio->kern_rel_offset = 0;
6960	ctsio->kern_sg_entries = 0;
6961
6962	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6963	/* XXX KDM this may not be 512 bytes... */
6964	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6965	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6966	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6967	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6968		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6969
6970	ctl_set_success(ctsio);
6971	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6972	ctsio->be_move_done = ctl_config_move_done;
6973	ctl_datamove((union ctl_io *)ctsio);
6974	return (CTL_RETVAL_COMPLETE);
6975}
6976
6977int
6978ctl_get_lba_status(struct ctl_scsiio *ctsio)
6979{
6980	struct scsi_get_lba_status *cdb;
6981	struct scsi_get_lba_status_data *data;
6982	struct ctl_lun *lun;
6983	struct ctl_lba_len_flags *lbalen;
6984	uint64_t lba;
6985	uint32_t alloc_len, total_len;
6986	int retval;
6987
6988	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6989
6990	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6991	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6992	lba = scsi_8btou64(cdb->addr);
6993	alloc_len = scsi_4btoul(cdb->alloc_len);
6994
6995	if (lba > lun->be_lun->maxlba) {
6996		ctl_set_lba_out_of_range(ctsio, lba);
6997		ctl_done((union ctl_io *)ctsio);
6998		return (CTL_RETVAL_COMPLETE);
6999	}
7000
7001	total_len = sizeof(*data) + sizeof(data->descr[0]);
7002	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7003	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7004
7005	if (total_len < alloc_len) {
7006		ctsio->residual = alloc_len - total_len;
7007		ctsio->kern_data_len = total_len;
7008		ctsio->kern_total_len = total_len;
7009	} else {
7010		ctsio->residual = 0;
7011		ctsio->kern_data_len = alloc_len;
7012		ctsio->kern_total_len = alloc_len;
7013	}
7014	ctsio->kern_data_resid = 0;
7015	ctsio->kern_rel_offset = 0;
7016	ctsio->kern_sg_entries = 0;
7017
7018	/* Fill dummy data in case backend can't tell anything. */
7019	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7020	scsi_u64to8b(lba, data->descr[0].addr);
7021	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7022	    data->descr[0].length);
7023	data->descr[0].status = 0; /* Mapped or unknown. */
7024
7025	ctl_set_success(ctsio);
7026	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7027	ctsio->be_move_done = ctl_config_move_done;
7028
7029	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7030	lbalen->lba = lba;
7031	lbalen->len = total_len;
7032	lbalen->flags = 0;
7033	retval = lun->backend->config_read((union ctl_io *)ctsio);
7034	return (CTL_RETVAL_COMPLETE);
7035}
7036
7037int
7038ctl_read_defect(struct ctl_scsiio *ctsio)
7039{
7040	struct scsi_read_defect_data_10 *ccb10;
7041	struct scsi_read_defect_data_12 *ccb12;
7042	struct scsi_read_defect_data_hdr_10 *data10;
7043	struct scsi_read_defect_data_hdr_12 *data12;
7044	uint32_t alloc_len, data_len;
7045	uint8_t format;
7046
7047	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7048
7049	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7050		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7051		format = ccb10->format;
7052		alloc_len = scsi_2btoul(ccb10->alloc_length);
7053		data_len = sizeof(*data10);
7054	} else {
7055		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7056		format = ccb12->format;
7057		alloc_len = scsi_4btoul(ccb12->alloc_length);
7058		data_len = sizeof(*data12);
7059	}
7060	if (alloc_len == 0) {
7061		ctl_set_success(ctsio);
7062		ctl_done((union ctl_io *)ctsio);
7063		return (CTL_RETVAL_COMPLETE);
7064	}
7065
7066	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7067	if (data_len < alloc_len) {
7068		ctsio->residual = alloc_len - data_len;
7069		ctsio->kern_data_len = data_len;
7070		ctsio->kern_total_len = data_len;
7071	} else {
7072		ctsio->residual = 0;
7073		ctsio->kern_data_len = alloc_len;
7074		ctsio->kern_total_len = alloc_len;
7075	}
7076	ctsio->kern_data_resid = 0;
7077	ctsio->kern_rel_offset = 0;
7078	ctsio->kern_sg_entries = 0;
7079
7080	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7081		data10 = (struct scsi_read_defect_data_hdr_10 *)
7082		    ctsio->kern_data_ptr;
7083		data10->format = format;
7084		scsi_ulto2b(0, data10->length);
7085	} else {
7086		data12 = (struct scsi_read_defect_data_hdr_12 *)
7087		    ctsio->kern_data_ptr;
7088		data12->format = format;
7089		scsi_ulto2b(0, data12->generation);
7090		scsi_ulto4b(0, data12->length);
7091	}
7092
7093	ctl_set_success(ctsio);
7094	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7095	ctsio->be_move_done = ctl_config_move_done;
7096	ctl_datamove((union ctl_io *)ctsio);
7097	return (CTL_RETVAL_COMPLETE);
7098}
7099
7100int
7101ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7102{
7103	struct scsi_maintenance_in *cdb;
7104	int retval;
7105	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7106	int num_ha_groups, num_target_ports, shared_group;
7107	struct ctl_lun *lun;
7108	struct ctl_softc *softc;
7109	struct ctl_port *port;
7110	struct scsi_target_group_data *rtg_ptr;
7111	struct scsi_target_group_data_extended *rtg_ext_ptr;
7112	struct scsi_target_port_group_descriptor *tpg_desc;
7113
7114	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7115
7116	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7117	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7118	softc = lun->ctl_softc;
7119
7120	retval = CTL_RETVAL_COMPLETE;
7121
7122	switch (cdb->byte2 & STG_PDF_MASK) {
7123	case STG_PDF_LENGTH:
7124		ext = 0;
7125		break;
7126	case STG_PDF_EXTENDED:
7127		ext = 1;
7128		break;
7129	default:
7130		ctl_set_invalid_field(/*ctsio*/ ctsio,
7131				      /*sks_valid*/ 1,
7132				      /*command*/ 1,
7133				      /*field*/ 2,
7134				      /*bit_valid*/ 1,
7135				      /*bit*/ 5);
7136		ctl_done((union ctl_io *)ctsio);
7137		return(retval);
7138	}
7139
7140	num_target_ports = 0;
7141	shared_group = (softc->is_single != 0);
7142	mtx_lock(&softc->ctl_lock);
7143	STAILQ_FOREACH(port, &softc->port_list, links) {
7144		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7145			continue;
7146		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7147			continue;
7148		num_target_ports++;
7149		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7150			shared_group = 1;
7151	}
7152	mtx_unlock(&softc->ctl_lock);
7153	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7154
7155	if (ext)
7156		total_len = sizeof(struct scsi_target_group_data_extended);
7157	else
7158		total_len = sizeof(struct scsi_target_group_data);
7159	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7160		(shared_group + num_ha_groups) +
7161	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7162
7163	alloc_len = scsi_4btoul(cdb->length);
7164
7165	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7166
7167	ctsio->kern_sg_entries = 0;
7168
7169	if (total_len < alloc_len) {
7170		ctsio->residual = alloc_len - total_len;
7171		ctsio->kern_data_len = total_len;
7172		ctsio->kern_total_len = total_len;
7173	} else {
7174		ctsio->residual = 0;
7175		ctsio->kern_data_len = alloc_len;
7176		ctsio->kern_total_len = alloc_len;
7177	}
7178	ctsio->kern_data_resid = 0;
7179	ctsio->kern_rel_offset = 0;
7180
7181	if (ext) {
7182		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7183		    ctsio->kern_data_ptr;
7184		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7185		rtg_ext_ptr->format_type = 0x10;
7186		rtg_ext_ptr->implicit_transition_time = 0;
7187		tpg_desc = &rtg_ext_ptr->groups[0];
7188	} else {
7189		rtg_ptr = (struct scsi_target_group_data *)
7190		    ctsio->kern_data_ptr;
7191		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7192		tpg_desc = &rtg_ptr->groups[0];
7193	}
7194
7195	mtx_lock(&softc->ctl_lock);
7196	pg = softc->port_min / softc->port_cnt;
7197	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7198		/* Some shelf is known to be primary. */
7199		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7200			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7201		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7202			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7203		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7204			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7205		else
7206			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7207		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7208			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7209		} else {
7210			ts = os;
7211			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7212		}
7213	} else {
7214		/* No known primary shelf. */
7215		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7216			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7217			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7218		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7219			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7220			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7221		} else {
7222			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7223		}
7224	}
7225	if (shared_group) {
7226		tpg_desc->pref_state = ts;
7227		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7228		    TPG_U_SUP | TPG_T_SUP;
7229		scsi_ulto2b(1, tpg_desc->target_port_group);
7230		tpg_desc->status = TPG_IMPLICIT;
7231		pc = 0;
7232		STAILQ_FOREACH(port, &softc->port_list, links) {
7233			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7234				continue;
7235			if (!softc->is_single &&
7236			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7237				continue;
7238			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7239				continue;
7240			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7241			    relative_target_port_identifier);
7242			pc++;
7243		}
7244		tpg_desc->target_port_count = pc;
7245		tpg_desc = (struct scsi_target_port_group_descriptor *)
7246		    &tpg_desc->descriptors[pc];
7247	}
7248	for (g = 0; g < num_ha_groups; g++) {
7249		tpg_desc->pref_state = (g == pg) ? ts : os;
7250		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7251		    TPG_U_SUP | TPG_T_SUP;
7252		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7253		tpg_desc->status = TPG_IMPLICIT;
7254		pc = 0;
7255		STAILQ_FOREACH(port, &softc->port_list, links) {
7256			if (port->targ_port < g * softc->port_cnt ||
7257			    port->targ_port >= (g + 1) * softc->port_cnt)
7258				continue;
7259			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7260				continue;
7261			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7262				continue;
7263			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7264				continue;
7265			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7266			    relative_target_port_identifier);
7267			pc++;
7268		}
7269		tpg_desc->target_port_count = pc;
7270		tpg_desc = (struct scsi_target_port_group_descriptor *)
7271		    &tpg_desc->descriptors[pc];
7272	}
7273	mtx_unlock(&softc->ctl_lock);
7274
7275	ctl_set_success(ctsio);
7276	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7277	ctsio->be_move_done = ctl_config_move_done;
7278	ctl_datamove((union ctl_io *)ctsio);
7279	return(retval);
7280}
7281
7282int
7283ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7284{
7285	struct ctl_lun *lun;
7286	struct scsi_report_supported_opcodes *cdb;
7287	const struct ctl_cmd_entry *entry, *sentry;
7288	struct scsi_report_supported_opcodes_all *all;
7289	struct scsi_report_supported_opcodes_descr *descr;
7290	struct scsi_report_supported_opcodes_one *one;
7291	int retval;
7292	int alloc_len, total_len;
7293	int opcode, service_action, i, j, num;
7294
7295	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7296
7297	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7298	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7299
7300	retval = CTL_RETVAL_COMPLETE;
7301
7302	opcode = cdb->requested_opcode;
7303	service_action = scsi_2btoul(cdb->requested_service_action);
7304	switch (cdb->options & RSO_OPTIONS_MASK) {
7305	case RSO_OPTIONS_ALL:
7306		num = 0;
7307		for (i = 0; i < 256; i++) {
7308			entry = &ctl_cmd_table[i];
7309			if (entry->flags & CTL_CMD_FLAG_SA5) {
7310				for (j = 0; j < 32; j++) {
7311					sentry = &((const struct ctl_cmd_entry *)
7312					    entry->execute)[j];
7313					if (ctl_cmd_applicable(
7314					    lun->be_lun->lun_type, sentry))
7315						num++;
7316				}
7317			} else {
7318				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7319				    entry))
7320					num++;
7321			}
7322		}
7323		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7324		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7325		break;
7326	case RSO_OPTIONS_OC:
7327		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7328			ctl_set_invalid_field(/*ctsio*/ ctsio,
7329					      /*sks_valid*/ 1,
7330					      /*command*/ 1,
7331					      /*field*/ 2,
7332					      /*bit_valid*/ 1,
7333					      /*bit*/ 2);
7334			ctl_done((union ctl_io *)ctsio);
7335			return (CTL_RETVAL_COMPLETE);
7336		}
7337		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7338		break;
7339	case RSO_OPTIONS_OC_SA:
7340		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7341		    service_action >= 32) {
7342			ctl_set_invalid_field(/*ctsio*/ ctsio,
7343					      /*sks_valid*/ 1,
7344					      /*command*/ 1,
7345					      /*field*/ 2,
7346					      /*bit_valid*/ 1,
7347					      /*bit*/ 2);
7348			ctl_done((union ctl_io *)ctsio);
7349			return (CTL_RETVAL_COMPLETE);
7350		}
7351		/* FALLTHROUGH */
7352	case RSO_OPTIONS_OC_ASA:
7353		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7354		break;
7355	default:
7356		ctl_set_invalid_field(/*ctsio*/ ctsio,
7357				      /*sks_valid*/ 1,
7358				      /*command*/ 1,
7359				      /*field*/ 2,
7360				      /*bit_valid*/ 1,
7361				      /*bit*/ 2);
7362		ctl_done((union ctl_io *)ctsio);
7363		return (CTL_RETVAL_COMPLETE);
7364	}
7365
7366	alloc_len = scsi_4btoul(cdb->length);
7367
7368	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7369
7370	ctsio->kern_sg_entries = 0;
7371
7372	if (total_len < alloc_len) {
7373		ctsio->residual = alloc_len - total_len;
7374		ctsio->kern_data_len = total_len;
7375		ctsio->kern_total_len = total_len;
7376	} else {
7377		ctsio->residual = 0;
7378		ctsio->kern_data_len = alloc_len;
7379		ctsio->kern_total_len = alloc_len;
7380	}
7381	ctsio->kern_data_resid = 0;
7382	ctsio->kern_rel_offset = 0;
7383
7384	switch (cdb->options & RSO_OPTIONS_MASK) {
7385	case RSO_OPTIONS_ALL:
7386		all = (struct scsi_report_supported_opcodes_all *)
7387		    ctsio->kern_data_ptr;
7388		num = 0;
7389		for (i = 0; i < 256; i++) {
7390			entry = &ctl_cmd_table[i];
7391			if (entry->flags & CTL_CMD_FLAG_SA5) {
7392				for (j = 0; j < 32; j++) {
7393					sentry = &((const struct ctl_cmd_entry *)
7394					    entry->execute)[j];
7395					if (!ctl_cmd_applicable(
7396					    lun->be_lun->lun_type, sentry))
7397						continue;
7398					descr = &all->descr[num++];
7399					descr->opcode = i;
7400					scsi_ulto2b(j, descr->service_action);
7401					descr->flags = RSO_SERVACTV;
7402					scsi_ulto2b(sentry->length,
7403					    descr->cdb_length);
7404				}
7405			} else {
7406				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7407				    entry))
7408					continue;
7409				descr = &all->descr[num++];
7410				descr->opcode = i;
7411				scsi_ulto2b(0, descr->service_action);
7412				descr->flags = 0;
7413				scsi_ulto2b(entry->length, descr->cdb_length);
7414			}
7415		}
7416		scsi_ulto4b(
7417		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7418		    all->length);
7419		break;
7420	case RSO_OPTIONS_OC:
7421		one = (struct scsi_report_supported_opcodes_one *)
7422		    ctsio->kern_data_ptr;
7423		entry = &ctl_cmd_table[opcode];
7424		goto fill_one;
7425	case RSO_OPTIONS_OC_SA:
7426		one = (struct scsi_report_supported_opcodes_one *)
7427		    ctsio->kern_data_ptr;
7428		entry = &ctl_cmd_table[opcode];
7429		entry = &((const struct ctl_cmd_entry *)
7430		    entry->execute)[service_action];
7431fill_one:
7432		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7433			one->support = 3;
7434			scsi_ulto2b(entry->length, one->cdb_length);
7435			one->cdb_usage[0] = opcode;
7436			memcpy(&one->cdb_usage[1], entry->usage,
7437			    entry->length - 1);
7438		} else
7439			one->support = 1;
7440		break;
7441	case RSO_OPTIONS_OC_ASA:
7442		one = (struct scsi_report_supported_opcodes_one *)
7443		    ctsio->kern_data_ptr;
7444		entry = &ctl_cmd_table[opcode];
7445		if (entry->flags & CTL_CMD_FLAG_SA5) {
7446			entry = &((const struct ctl_cmd_entry *)
7447			    entry->execute)[service_action];
7448		} else if (service_action != 0) {
7449			one->support = 1;
7450			break;
7451		}
7452		goto fill_one;
7453	}
7454
7455	ctl_set_success(ctsio);
7456	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7457	ctsio->be_move_done = ctl_config_move_done;
7458	ctl_datamove((union ctl_io *)ctsio);
7459	return(retval);
7460}
7461
7462int
7463ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7464{
7465	struct scsi_report_supported_tmf *cdb;
7466	struct scsi_report_supported_tmf_ext_data *data;
7467	int retval;
7468	int alloc_len, total_len;
7469
7470	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7471
7472	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7473
7474	retval = CTL_RETVAL_COMPLETE;
7475
7476	if (cdb->options & RST_REPD)
7477		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7478	else
7479		total_len = sizeof(struct scsi_report_supported_tmf_data);
7480	alloc_len = scsi_4btoul(cdb->length);
7481
7482	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7483
7484	ctsio->kern_sg_entries = 0;
7485
7486	if (total_len < alloc_len) {
7487		ctsio->residual = alloc_len - total_len;
7488		ctsio->kern_data_len = total_len;
7489		ctsio->kern_total_len = total_len;
7490	} else {
7491		ctsio->residual = 0;
7492		ctsio->kern_data_len = alloc_len;
7493		ctsio->kern_total_len = alloc_len;
7494	}
7495	ctsio->kern_data_resid = 0;
7496	ctsio->kern_rel_offset = 0;
7497
7498	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7499	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7500	    RST_TRS;
7501	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7502	data->length = total_len - 4;
7503
7504	ctl_set_success(ctsio);
7505	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7506	ctsio->be_move_done = ctl_config_move_done;
7507	ctl_datamove((union ctl_io *)ctsio);
7508	return (retval);
7509}
7510
7511int
7512ctl_report_timestamp(struct ctl_scsiio *ctsio)
7513{
7514	struct scsi_report_timestamp *cdb;
7515	struct scsi_report_timestamp_data *data;
7516	struct timeval tv;
7517	int64_t timestamp;
7518	int retval;
7519	int alloc_len, total_len;
7520
7521	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7522
7523	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7524
7525	retval = CTL_RETVAL_COMPLETE;
7526
7527	total_len = sizeof(struct scsi_report_timestamp_data);
7528	alloc_len = scsi_4btoul(cdb->length);
7529
7530	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7531
7532	ctsio->kern_sg_entries = 0;
7533
7534	if (total_len < alloc_len) {
7535		ctsio->residual = alloc_len - total_len;
7536		ctsio->kern_data_len = total_len;
7537		ctsio->kern_total_len = total_len;
7538	} else {
7539		ctsio->residual = 0;
7540		ctsio->kern_data_len = alloc_len;
7541		ctsio->kern_total_len = alloc_len;
7542	}
7543	ctsio->kern_data_resid = 0;
7544	ctsio->kern_rel_offset = 0;
7545
7546	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7547	scsi_ulto2b(sizeof(*data) - 2, data->length);
7548	data->origin = RTS_ORIG_OUTSIDE;
7549	getmicrotime(&tv);
7550	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7551	scsi_ulto4b(timestamp >> 16, data->timestamp);
7552	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7553
7554	ctl_set_success(ctsio);
7555	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7556	ctsio->be_move_done = ctl_config_move_done;
7557	ctl_datamove((union ctl_io *)ctsio);
7558	return (retval);
7559}
7560
7561int
7562ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7563{
7564	struct scsi_per_res_in *cdb;
7565	int alloc_len, total_len = 0;
7566	/* struct scsi_per_res_in_rsrv in_data; */
7567	struct ctl_lun *lun;
7568	struct ctl_softc *softc;
7569	uint64_t key;
7570
7571	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7572
7573	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7574
7575	alloc_len = scsi_2btoul(cdb->length);
7576
7577	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7578	softc = lun->ctl_softc;
7579
7580retry:
7581	mtx_lock(&lun->lun_lock);
7582	switch (cdb->action) {
7583	case SPRI_RK: /* read keys */
7584		total_len = sizeof(struct scsi_per_res_in_keys) +
7585			lun->pr_key_count *
7586			sizeof(struct scsi_per_res_key);
7587		break;
7588	case SPRI_RR: /* read reservation */
7589		if (lun->flags & CTL_LUN_PR_RESERVED)
7590			total_len = sizeof(struct scsi_per_res_in_rsrv);
7591		else
7592			total_len = sizeof(struct scsi_per_res_in_header);
7593		break;
7594	case SPRI_RC: /* report capabilities */
7595		total_len = sizeof(struct scsi_per_res_cap);
7596		break;
7597	case SPRI_RS: /* read full status */
7598		total_len = sizeof(struct scsi_per_res_in_header) +
7599		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7600		    lun->pr_key_count;
7601		break;
7602	default:
7603		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7604	}
7605	mtx_unlock(&lun->lun_lock);
7606
7607	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7608
7609	if (total_len < alloc_len) {
7610		ctsio->residual = alloc_len - total_len;
7611		ctsio->kern_data_len = total_len;
7612		ctsio->kern_total_len = total_len;
7613	} else {
7614		ctsio->residual = 0;
7615		ctsio->kern_data_len = alloc_len;
7616		ctsio->kern_total_len = alloc_len;
7617	}
7618
7619	ctsio->kern_data_resid = 0;
7620	ctsio->kern_rel_offset = 0;
7621	ctsio->kern_sg_entries = 0;
7622
7623	mtx_lock(&lun->lun_lock);
7624	switch (cdb->action) {
7625	case SPRI_RK: { // read keys
7626        struct scsi_per_res_in_keys *res_keys;
7627		int i, key_count;
7628
7629		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7630
7631		/*
7632		 * We had to drop the lock to allocate our buffer, which
7633		 * leaves time for someone to come in with another
7634		 * persistent reservation.  (That is unlikely, though,
7635		 * since this should be the only persistent reservation
7636		 * command active right now.)
7637		 */
7638		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7639		    (lun->pr_key_count *
7640		     sizeof(struct scsi_per_res_key)))){
7641			mtx_unlock(&lun->lun_lock);
7642			free(ctsio->kern_data_ptr, M_CTL);
7643			printf("%s: reservation length changed, retrying\n",
7644			       __func__);
7645			goto retry;
7646		}
7647
7648		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7649
7650		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7651			     lun->pr_key_count, res_keys->header.length);
7652
7653		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7654			if ((key = ctl_get_prkey(lun, i)) == 0)
7655				continue;
7656
7657			/*
7658			 * We used lun->pr_key_count to calculate the
7659			 * size to allocate.  If it turns out the number of
7660			 * initiators with the registered flag set is
7661			 * larger than that (i.e. they haven't been kept in
7662			 * sync), we've got a problem.
7663			 */
7664			if (key_count >= lun->pr_key_count) {
7665				key_count++;
7666				continue;
7667			}
7668			scsi_u64to8b(key, res_keys->keys[key_count].key);
7669			key_count++;
7670		}
7671		break;
7672	}
7673	case SPRI_RR: { // read reservation
7674		struct scsi_per_res_in_rsrv *res;
7675		int tmp_len, header_only;
7676
7677		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7678
7679		scsi_ulto4b(lun->pr_generation, res->header.generation);
7680
7681		if (lun->flags & CTL_LUN_PR_RESERVED)
7682		{
7683			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7684			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7685				    res->header.length);
7686			header_only = 0;
7687		} else {
7688			tmp_len = sizeof(struct scsi_per_res_in_header);
7689			scsi_ulto4b(0, res->header.length);
7690			header_only = 1;
7691		}
7692
7693		/*
7694		 * We had to drop the lock to allocate our buffer, which
7695		 * leaves time for someone to come in with another
7696		 * persistent reservation.  (That is unlikely, though,
7697		 * since this should be the only persistent reservation
7698		 * command active right now.)
7699		 */
7700		if (tmp_len != total_len) {
7701			mtx_unlock(&lun->lun_lock);
7702			free(ctsio->kern_data_ptr, M_CTL);
7703			printf("%s: reservation status changed, retrying\n",
7704			       __func__);
7705			goto retry;
7706		}
7707
7708		/*
7709		 * No reservation held, so we're done.
7710		 */
7711		if (header_only != 0)
7712			break;
7713
7714		/*
7715		 * If the registration is an All Registrants type, the key
7716		 * is 0, since it doesn't really matter.
7717		 */
7718		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7719			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7720			    res->data.reservation);
7721		}
7722		res->data.scopetype = lun->pr_res_type;
7723		break;
7724	}
7725	case SPRI_RC:     //report capabilities
7726	{
7727		struct scsi_per_res_cap *res_cap;
7728		uint16_t type_mask;
7729
7730		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7731		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7732		res_cap->flags1 = SPRI_CRH;
7733		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7734		type_mask = SPRI_TM_WR_EX_AR |
7735			    SPRI_TM_EX_AC_RO |
7736			    SPRI_TM_WR_EX_RO |
7737			    SPRI_TM_EX_AC |
7738			    SPRI_TM_WR_EX |
7739			    SPRI_TM_EX_AC_AR;
7740		scsi_ulto2b(type_mask, res_cap->type_mask);
7741		break;
7742	}
7743	case SPRI_RS: { // read full status
7744		struct scsi_per_res_in_full *res_status;
7745		struct scsi_per_res_in_full_desc *res_desc;
7746		struct ctl_port *port;
7747		int i, len;
7748
7749		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7750
7751		/*
7752		 * We had to drop the lock to allocate our buffer, which
7753		 * leaves time for someone to come in with another
7754		 * persistent reservation.  (That is unlikely, though,
7755		 * since this should be the only persistent reservation
7756		 * command active right now.)
7757		 */
7758		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7759		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7760		     lun->pr_key_count)){
7761			mtx_unlock(&lun->lun_lock);
7762			free(ctsio->kern_data_ptr, M_CTL);
7763			printf("%s: reservation length changed, retrying\n",
7764			       __func__);
7765			goto retry;
7766		}
7767
7768		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7769
7770		res_desc = &res_status->desc[0];
7771		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7772			if ((key = ctl_get_prkey(lun, i)) == 0)
7773				continue;
7774
7775			scsi_u64to8b(key, res_desc->res_key.key);
7776			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7777			    (lun->pr_res_idx == i ||
7778			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7779				res_desc->flags = SPRI_FULL_R_HOLDER;
7780				res_desc->scopetype = lun->pr_res_type;
7781			}
7782			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7783			    res_desc->rel_trgt_port_id);
7784			len = 0;
7785			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7786			if (port != NULL)
7787				len = ctl_create_iid(port,
7788				    i % CTL_MAX_INIT_PER_PORT,
7789				    res_desc->transport_id);
7790			scsi_ulto4b(len, res_desc->additional_length);
7791			res_desc = (struct scsi_per_res_in_full_desc *)
7792			    &res_desc->transport_id[len];
7793		}
7794		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7795		    res_status->header.length);
7796		break;
7797	}
7798	default:
7799		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7800	}
7801	mtx_unlock(&lun->lun_lock);
7802
7803	ctl_set_success(ctsio);
7804	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7805	ctsio->be_move_done = ctl_config_move_done;
7806	ctl_datamove((union ctl_io *)ctsio);
7807	return (CTL_RETVAL_COMPLETE);
7808}
7809
7810/*
7811 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7812 * it should return.
7813 */
7814static int
7815ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7816		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7817		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7818		struct scsi_per_res_out_parms* param)
7819{
7820	union ctl_ha_msg persis_io;
7821	int i;
7822
7823	mtx_lock(&lun->lun_lock);
7824	if (sa_res_key == 0) {
7825		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7826			/* validate scope and type */
7827			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7828			     SPR_LU_SCOPE) {
7829				mtx_unlock(&lun->lun_lock);
7830				ctl_set_invalid_field(/*ctsio*/ ctsio,
7831						      /*sks_valid*/ 1,
7832						      /*command*/ 1,
7833						      /*field*/ 2,
7834						      /*bit_valid*/ 1,
7835						      /*bit*/ 4);
7836				ctl_done((union ctl_io *)ctsio);
7837				return (1);
7838			}
7839
7840		        if (type>8 || type==2 || type==4 || type==0) {
7841				mtx_unlock(&lun->lun_lock);
7842				ctl_set_invalid_field(/*ctsio*/ ctsio,
7843       	           				      /*sks_valid*/ 1,
7844						      /*command*/ 1,
7845						      /*field*/ 2,
7846						      /*bit_valid*/ 1,
7847						      /*bit*/ 0);
7848				ctl_done((union ctl_io *)ctsio);
7849				return (1);
7850		        }
7851
7852			/*
7853			 * Unregister everybody else and build UA for
7854			 * them
7855			 */
7856			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7857				if (i == residx || ctl_get_prkey(lun, i) == 0)
7858					continue;
7859
7860				ctl_clr_prkey(lun, i);
7861				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7862			}
7863			lun->pr_key_count = 1;
7864			lun->pr_res_type = type;
7865			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7866			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7867				lun->pr_res_idx = residx;
7868			lun->pr_generation++;
7869			mtx_unlock(&lun->lun_lock);
7870
7871			/* send msg to other side */
7872			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7873			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7874			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7875			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7876			persis_io.pr.pr_info.res_type = type;
7877			memcpy(persis_io.pr.pr_info.sa_res_key,
7878			       param->serv_act_res_key,
7879			       sizeof(param->serv_act_res_key));
7880			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7881			    sizeof(persis_io.pr), M_WAITOK);
7882		} else {
7883			/* not all registrants */
7884			mtx_unlock(&lun->lun_lock);
7885			free(ctsio->kern_data_ptr, M_CTL);
7886			ctl_set_invalid_field(ctsio,
7887					      /*sks_valid*/ 1,
7888					      /*command*/ 0,
7889					      /*field*/ 8,
7890					      /*bit_valid*/ 0,
7891					      /*bit*/ 0);
7892			ctl_done((union ctl_io *)ctsio);
7893			return (1);
7894		}
7895	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7896		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7897		int found = 0;
7898
7899		if (res_key == sa_res_key) {
7900			/* special case */
7901			/*
7902			 * The spec implies this is not good but doesn't
7903			 * say what to do. There are two choices either
7904			 * generate a res conflict or check condition
7905			 * with illegal field in parameter data. Since
7906			 * that is what is done when the sa_res_key is
7907			 * zero I'll take that approach since this has
7908			 * to do with the sa_res_key.
7909			 */
7910			mtx_unlock(&lun->lun_lock);
7911			free(ctsio->kern_data_ptr, M_CTL);
7912			ctl_set_invalid_field(ctsio,
7913					      /*sks_valid*/ 1,
7914					      /*command*/ 0,
7915					      /*field*/ 8,
7916					      /*bit_valid*/ 0,
7917					      /*bit*/ 0);
7918			ctl_done((union ctl_io *)ctsio);
7919			return (1);
7920		}
7921
7922		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7923			if (ctl_get_prkey(lun, i) != sa_res_key)
7924				continue;
7925
7926			found = 1;
7927			ctl_clr_prkey(lun, i);
7928			lun->pr_key_count--;
7929			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7930		}
7931		if (!found) {
7932			mtx_unlock(&lun->lun_lock);
7933			free(ctsio->kern_data_ptr, M_CTL);
7934			ctl_set_reservation_conflict(ctsio);
7935			ctl_done((union ctl_io *)ctsio);
7936			return (CTL_RETVAL_COMPLETE);
7937		}
7938		lun->pr_generation++;
7939		mtx_unlock(&lun->lun_lock);
7940
7941		/* send msg to other side */
7942		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7943		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7944		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7945		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7946		persis_io.pr.pr_info.res_type = type;
7947		memcpy(persis_io.pr.pr_info.sa_res_key,
7948		       param->serv_act_res_key,
7949		       sizeof(param->serv_act_res_key));
7950		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7951		    sizeof(persis_io.pr), M_WAITOK);
7952	} else {
7953		/* Reserved but not all registrants */
7954		/* sa_res_key is res holder */
7955		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7956			/* validate scope and type */
7957			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7958			     SPR_LU_SCOPE) {
7959				mtx_unlock(&lun->lun_lock);
7960				ctl_set_invalid_field(/*ctsio*/ ctsio,
7961						      /*sks_valid*/ 1,
7962						      /*command*/ 1,
7963						      /*field*/ 2,
7964						      /*bit_valid*/ 1,
7965						      /*bit*/ 4);
7966				ctl_done((union ctl_io *)ctsio);
7967				return (1);
7968			}
7969
7970			if (type>8 || type==2 || type==4 || type==0) {
7971				mtx_unlock(&lun->lun_lock);
7972				ctl_set_invalid_field(/*ctsio*/ ctsio,
7973						      /*sks_valid*/ 1,
7974						      /*command*/ 1,
7975						      /*field*/ 2,
7976						      /*bit_valid*/ 1,
7977						      /*bit*/ 0);
7978				ctl_done((union ctl_io *)ctsio);
7979				return (1);
7980			}
7981
7982			/*
7983			 * Do the following:
7984			 * if sa_res_key != res_key remove all
7985			 * registrants w/sa_res_key and generate UA
7986			 * for these registrants(Registrations
7987			 * Preempted) if it wasn't an exclusive
7988			 * reservation generate UA(Reservations
7989			 * Preempted) for all other registered nexuses
7990			 * if the type has changed. Establish the new
7991			 * reservation and holder. If res_key and
7992			 * sa_res_key are the same do the above
7993			 * except don't unregister the res holder.
7994			 */
7995
7996			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7997				if (i == residx || ctl_get_prkey(lun, i) == 0)
7998					continue;
7999
8000				if (sa_res_key == ctl_get_prkey(lun, i)) {
8001					ctl_clr_prkey(lun, i);
8002					lun->pr_key_count--;
8003					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8004				} else if (type != lun->pr_res_type &&
8005				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8006				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8007					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8008				}
8009			}
8010			lun->pr_res_type = type;
8011			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8012			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8013				lun->pr_res_idx = residx;
8014			else
8015				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8016			lun->pr_generation++;
8017			mtx_unlock(&lun->lun_lock);
8018
8019			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8020			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8021			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8022			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8023			persis_io.pr.pr_info.res_type = type;
8024			memcpy(persis_io.pr.pr_info.sa_res_key,
8025			       param->serv_act_res_key,
8026			       sizeof(param->serv_act_res_key));
8027			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8028			    sizeof(persis_io.pr), M_WAITOK);
8029		} else {
8030			/*
8031			 * sa_res_key is not the res holder just
8032			 * remove registrants
8033			 */
8034			int found=0;
8035
8036			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8037				if (sa_res_key != ctl_get_prkey(lun, i))
8038					continue;
8039
8040				found = 1;
8041				ctl_clr_prkey(lun, i);
8042				lun->pr_key_count--;
8043				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8044			}
8045
8046			if (!found) {
8047				mtx_unlock(&lun->lun_lock);
8048				free(ctsio->kern_data_ptr, M_CTL);
8049				ctl_set_reservation_conflict(ctsio);
8050				ctl_done((union ctl_io *)ctsio);
8051		        	return (1);
8052			}
8053			lun->pr_generation++;
8054			mtx_unlock(&lun->lun_lock);
8055
8056			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8057			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8058			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8059			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8060			persis_io.pr.pr_info.res_type = type;
8061			memcpy(persis_io.pr.pr_info.sa_res_key,
8062			       param->serv_act_res_key,
8063			       sizeof(param->serv_act_res_key));
8064			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8065			    sizeof(persis_io.pr), M_WAITOK);
8066		}
8067	}
8068	return (0);
8069}
8070
8071static void
8072ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8073{
8074	uint64_t sa_res_key;
8075	int i;
8076
8077	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8078
8079	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8080	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8081	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8082		if (sa_res_key == 0) {
8083			/*
8084			 * Unregister everybody else and build UA for
8085			 * them
8086			 */
8087			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8088				if (i == msg->pr.pr_info.residx ||
8089				    ctl_get_prkey(lun, i) == 0)
8090					continue;
8091
8092				ctl_clr_prkey(lun, i);
8093				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8094			}
8095
8096			lun->pr_key_count = 1;
8097			lun->pr_res_type = msg->pr.pr_info.res_type;
8098			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8099			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8100				lun->pr_res_idx = msg->pr.pr_info.residx;
8101		} else {
8102		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8103				if (sa_res_key == ctl_get_prkey(lun, i))
8104					continue;
8105
8106				ctl_clr_prkey(lun, i);
8107				lun->pr_key_count--;
8108				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8109			}
8110		}
8111	} else {
8112		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8113			if (i == msg->pr.pr_info.residx ||
8114			    ctl_get_prkey(lun, i) == 0)
8115				continue;
8116
8117			if (sa_res_key == ctl_get_prkey(lun, i)) {
8118				ctl_clr_prkey(lun, i);
8119				lun->pr_key_count--;
8120				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8121			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8122			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8123			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8124				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8125			}
8126		}
8127		lun->pr_res_type = msg->pr.pr_info.res_type;
8128		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8129		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8130			lun->pr_res_idx = msg->pr.pr_info.residx;
8131		else
8132			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8133	}
8134	lun->pr_generation++;
8135
8136}
8137
8138
8139int
8140ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8141{
8142	int retval;
8143	u_int32_t param_len;
8144	struct scsi_per_res_out *cdb;
8145	struct ctl_lun *lun;
8146	struct scsi_per_res_out_parms* param;
8147	struct ctl_softc *softc;
8148	uint32_t residx;
8149	uint64_t res_key, sa_res_key, key;
8150	uint8_t type;
8151	union ctl_ha_msg persis_io;
8152	int    i;
8153
8154	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8155
8156	retval = CTL_RETVAL_COMPLETE;
8157
8158	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8159	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8160	softc = lun->ctl_softc;
8161
8162	/*
8163	 * We only support whole-LUN scope.  The scope & type are ignored for
8164	 * register, register and ignore existing key and clear.
8165	 * We sometimes ignore scope and type on preempts too!!
8166	 * Verify reservation type here as well.
8167	 */
8168	type = cdb->scope_type & SPR_TYPE_MASK;
8169	if ((cdb->action == SPRO_RESERVE)
8170	 || (cdb->action == SPRO_RELEASE)) {
8171		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8172			ctl_set_invalid_field(/*ctsio*/ ctsio,
8173					      /*sks_valid*/ 1,
8174					      /*command*/ 1,
8175					      /*field*/ 2,
8176					      /*bit_valid*/ 1,
8177					      /*bit*/ 4);
8178			ctl_done((union ctl_io *)ctsio);
8179			return (CTL_RETVAL_COMPLETE);
8180		}
8181
8182		if (type>8 || type==2 || type==4 || type==0) {
8183			ctl_set_invalid_field(/*ctsio*/ ctsio,
8184					      /*sks_valid*/ 1,
8185					      /*command*/ 1,
8186					      /*field*/ 2,
8187					      /*bit_valid*/ 1,
8188					      /*bit*/ 0);
8189			ctl_done((union ctl_io *)ctsio);
8190			return (CTL_RETVAL_COMPLETE);
8191		}
8192	}
8193
8194	param_len = scsi_4btoul(cdb->length);
8195
8196	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8197		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8198		ctsio->kern_data_len = param_len;
8199		ctsio->kern_total_len = param_len;
8200		ctsio->kern_data_resid = 0;
8201		ctsio->kern_rel_offset = 0;
8202		ctsio->kern_sg_entries = 0;
8203		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8204		ctsio->be_move_done = ctl_config_move_done;
8205		ctl_datamove((union ctl_io *)ctsio);
8206
8207		return (CTL_RETVAL_COMPLETE);
8208	}
8209
8210	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8211
8212	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8213	res_key = scsi_8btou64(param->res_key.key);
8214	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8215
8216	/*
8217	 * Validate the reservation key here except for SPRO_REG_IGNO
8218	 * This must be done for all other service actions
8219	 */
8220	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8221		mtx_lock(&lun->lun_lock);
8222		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8223			if (res_key != key) {
8224				/*
8225				 * The current key passed in doesn't match
8226				 * the one the initiator previously
8227				 * registered.
8228				 */
8229				mtx_unlock(&lun->lun_lock);
8230				free(ctsio->kern_data_ptr, M_CTL);
8231				ctl_set_reservation_conflict(ctsio);
8232				ctl_done((union ctl_io *)ctsio);
8233				return (CTL_RETVAL_COMPLETE);
8234			}
8235		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8236			/*
8237			 * We are not registered
8238			 */
8239			mtx_unlock(&lun->lun_lock);
8240			free(ctsio->kern_data_ptr, M_CTL);
8241			ctl_set_reservation_conflict(ctsio);
8242			ctl_done((union ctl_io *)ctsio);
8243			return (CTL_RETVAL_COMPLETE);
8244		} else if (res_key != 0) {
8245			/*
8246			 * We are not registered and trying to register but
8247			 * the register key isn't zero.
8248			 */
8249			mtx_unlock(&lun->lun_lock);
8250			free(ctsio->kern_data_ptr, M_CTL);
8251			ctl_set_reservation_conflict(ctsio);
8252			ctl_done((union ctl_io *)ctsio);
8253			return (CTL_RETVAL_COMPLETE);
8254		}
8255		mtx_unlock(&lun->lun_lock);
8256	}
8257
8258	switch (cdb->action & SPRO_ACTION_MASK) {
8259	case SPRO_REGISTER:
8260	case SPRO_REG_IGNO: {
8261
8262#if 0
8263		printf("Registration received\n");
8264#endif
8265
8266		/*
8267		 * We don't support any of these options, as we report in
8268		 * the read capabilities request (see
8269		 * ctl_persistent_reserve_in(), above).
8270		 */
8271		if ((param->flags & SPR_SPEC_I_PT)
8272		 || (param->flags & SPR_ALL_TG_PT)
8273		 || (param->flags & SPR_APTPL)) {
8274			int bit_ptr;
8275
8276			if (param->flags & SPR_APTPL)
8277				bit_ptr = 0;
8278			else if (param->flags & SPR_ALL_TG_PT)
8279				bit_ptr = 2;
8280			else /* SPR_SPEC_I_PT */
8281				bit_ptr = 3;
8282
8283			free(ctsio->kern_data_ptr, M_CTL);
8284			ctl_set_invalid_field(ctsio,
8285					      /*sks_valid*/ 1,
8286					      /*command*/ 0,
8287					      /*field*/ 20,
8288					      /*bit_valid*/ 1,
8289					      /*bit*/ bit_ptr);
8290			ctl_done((union ctl_io *)ctsio);
8291			return (CTL_RETVAL_COMPLETE);
8292		}
8293
8294		mtx_lock(&lun->lun_lock);
8295
8296		/*
8297		 * The initiator wants to clear the
8298		 * key/unregister.
8299		 */
8300		if (sa_res_key == 0) {
8301			if ((res_key == 0
8302			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8303			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8304			  && ctl_get_prkey(lun, residx) == 0)) {
8305				mtx_unlock(&lun->lun_lock);
8306				goto done;
8307			}
8308
8309			ctl_clr_prkey(lun, residx);
8310			lun->pr_key_count--;
8311
8312			if (residx == lun->pr_res_idx) {
8313				lun->flags &= ~CTL_LUN_PR_RESERVED;
8314				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8315
8316				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8317				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8318				    lun->pr_key_count) {
8319					/*
8320					 * If the reservation is a registrants
8321					 * only type we need to generate a UA
8322					 * for other registered inits.  The
8323					 * sense code should be RESERVATIONS
8324					 * RELEASED
8325					 */
8326
8327					for (i = softc->init_min; i < softc->init_max; i++){
8328						if (ctl_get_prkey(lun, i) == 0)
8329							continue;
8330						ctl_est_ua(lun, i,
8331						    CTL_UA_RES_RELEASE);
8332					}
8333				}
8334				lun->pr_res_type = 0;
8335			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8336				if (lun->pr_key_count==0) {
8337					lun->flags &= ~CTL_LUN_PR_RESERVED;
8338					lun->pr_res_type = 0;
8339					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8340				}
8341			}
8342			lun->pr_generation++;
8343			mtx_unlock(&lun->lun_lock);
8344
8345			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8346			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8347			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8348			persis_io.pr.pr_info.residx = residx;
8349			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8350			    sizeof(persis_io.pr), M_WAITOK);
8351		} else /* sa_res_key != 0 */ {
8352
8353			/*
8354			 * If we aren't registered currently then increment
8355			 * the key count and set the registered flag.
8356			 */
8357			ctl_alloc_prkey(lun, residx);
8358			if (ctl_get_prkey(lun, residx) == 0)
8359				lun->pr_key_count++;
8360			ctl_set_prkey(lun, residx, sa_res_key);
8361			lun->pr_generation++;
8362			mtx_unlock(&lun->lun_lock);
8363
8364			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8365			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8366			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8367			persis_io.pr.pr_info.residx = residx;
8368			memcpy(persis_io.pr.pr_info.sa_res_key,
8369			       param->serv_act_res_key,
8370			       sizeof(param->serv_act_res_key));
8371			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8372			    sizeof(persis_io.pr), M_WAITOK);
8373		}
8374
8375		break;
8376	}
8377	case SPRO_RESERVE:
8378#if 0
8379                printf("Reserve executed type %d\n", type);
8380#endif
8381		mtx_lock(&lun->lun_lock);
8382		if (lun->flags & CTL_LUN_PR_RESERVED) {
8383			/*
8384			 * if this isn't the reservation holder and it's
8385			 * not a "all registrants" type or if the type is
8386			 * different then we have a conflict
8387			 */
8388			if ((lun->pr_res_idx != residx
8389			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8390			 || lun->pr_res_type != type) {
8391				mtx_unlock(&lun->lun_lock);
8392				free(ctsio->kern_data_ptr, M_CTL);
8393				ctl_set_reservation_conflict(ctsio);
8394				ctl_done((union ctl_io *)ctsio);
8395				return (CTL_RETVAL_COMPLETE);
8396			}
8397			mtx_unlock(&lun->lun_lock);
8398		} else /* create a reservation */ {
8399			/*
8400			 * If it's not an "all registrants" type record
8401			 * reservation holder
8402			 */
8403			if (type != SPR_TYPE_WR_EX_AR
8404			 && type != SPR_TYPE_EX_AC_AR)
8405				lun->pr_res_idx = residx; /* Res holder */
8406			else
8407				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8408
8409			lun->flags |= CTL_LUN_PR_RESERVED;
8410			lun->pr_res_type = type;
8411
8412			mtx_unlock(&lun->lun_lock);
8413
8414			/* send msg to other side */
8415			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8416			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8417			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8418			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8419			persis_io.pr.pr_info.res_type = type;
8420			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8421			    sizeof(persis_io.pr), M_WAITOK);
8422		}
8423		break;
8424
8425	case SPRO_RELEASE:
8426		mtx_lock(&lun->lun_lock);
8427		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8428			/* No reservation exists return good status */
8429			mtx_unlock(&lun->lun_lock);
8430			goto done;
8431		}
8432		/*
8433		 * Is this nexus a reservation holder?
8434		 */
8435		if (lun->pr_res_idx != residx
8436		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8437			/*
8438			 * not a res holder return good status but
8439			 * do nothing
8440			 */
8441			mtx_unlock(&lun->lun_lock);
8442			goto done;
8443		}
8444
8445		if (lun->pr_res_type != type) {
8446			mtx_unlock(&lun->lun_lock);
8447			free(ctsio->kern_data_ptr, M_CTL);
8448			ctl_set_illegal_pr_release(ctsio);
8449			ctl_done((union ctl_io *)ctsio);
8450			return (CTL_RETVAL_COMPLETE);
8451		}
8452
8453		/* okay to release */
8454		lun->flags &= ~CTL_LUN_PR_RESERVED;
8455		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8456		lun->pr_res_type = 0;
8457
8458		/*
8459		 * If this isn't an exclusive access reservation and NUAR
8460		 * is not set, generate UA for all other registrants.
8461		 */
8462		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8463		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8464			for (i = softc->init_min; i < softc->init_max; i++) {
8465				if (i == residx || ctl_get_prkey(lun, i) == 0)
8466					continue;
8467				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8468			}
8469		}
8470		mtx_unlock(&lun->lun_lock);
8471
8472		/* Send msg to other side */
8473		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8474		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8475		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8476		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8477		     sizeof(persis_io.pr), M_WAITOK);
8478		break;
8479
8480	case SPRO_CLEAR:
8481		/* send msg to other side */
8482
8483		mtx_lock(&lun->lun_lock);
8484		lun->flags &= ~CTL_LUN_PR_RESERVED;
8485		lun->pr_res_type = 0;
8486		lun->pr_key_count = 0;
8487		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8488
8489		ctl_clr_prkey(lun, residx);
8490		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8491			if (ctl_get_prkey(lun, i) != 0) {
8492				ctl_clr_prkey(lun, i);
8493				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8494			}
8495		lun->pr_generation++;
8496		mtx_unlock(&lun->lun_lock);
8497
8498		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8499		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8500		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8501		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8502		     sizeof(persis_io.pr), M_WAITOK);
8503		break;
8504
8505	case SPRO_PREEMPT:
8506	case SPRO_PRE_ABO: {
8507		int nretval;
8508
8509		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8510					  residx, ctsio, cdb, param);
8511		if (nretval != 0)
8512			return (CTL_RETVAL_COMPLETE);
8513		break;
8514	}
8515	default:
8516		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8517	}
8518
8519done:
8520	free(ctsio->kern_data_ptr, M_CTL);
8521	ctl_set_success(ctsio);
8522	ctl_done((union ctl_io *)ctsio);
8523
8524	return (retval);
8525}
8526
8527/*
8528 * This routine is for handling a message from the other SC pertaining to
8529 * persistent reserve out. All the error checking will have been done
8530 * so only perorming the action need be done here to keep the two
8531 * in sync.
8532 */
8533static void
8534ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8535{
8536	struct ctl_softc *softc = control_softc;
8537	struct ctl_lun *lun;
8538	int i;
8539	uint32_t residx, targ_lun;
8540
8541	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8542	mtx_lock(&softc->ctl_lock);
8543	if ((targ_lun >= CTL_MAX_LUNS) ||
8544	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8545		mtx_unlock(&softc->ctl_lock);
8546		return;
8547	}
8548	mtx_lock(&lun->lun_lock);
8549	mtx_unlock(&softc->ctl_lock);
8550	if (lun->flags & CTL_LUN_DISABLED) {
8551		mtx_unlock(&lun->lun_lock);
8552		return;
8553	}
8554	residx = ctl_get_initindex(&msg->hdr.nexus);
8555	switch(msg->pr.pr_info.action) {
8556	case CTL_PR_REG_KEY:
8557		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8558		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8559			lun->pr_key_count++;
8560		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8561		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8562		lun->pr_generation++;
8563		break;
8564
8565	case CTL_PR_UNREG_KEY:
8566		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8567		lun->pr_key_count--;
8568
8569		/* XXX Need to see if the reservation has been released */
8570		/* if so do we need to generate UA? */
8571		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8572			lun->flags &= ~CTL_LUN_PR_RESERVED;
8573			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8574
8575			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8576			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8577			    lun->pr_key_count) {
8578				/*
8579				 * If the reservation is a registrants
8580				 * only type we need to generate a UA
8581				 * for other registered inits.  The
8582				 * sense code should be RESERVATIONS
8583				 * RELEASED
8584				 */
8585
8586				for (i = softc->init_min; i < softc->init_max; i++) {
8587					if (ctl_get_prkey(lun, i) == 0)
8588						continue;
8589
8590					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8591				}
8592			}
8593			lun->pr_res_type = 0;
8594		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8595			if (lun->pr_key_count==0) {
8596				lun->flags &= ~CTL_LUN_PR_RESERVED;
8597				lun->pr_res_type = 0;
8598				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8599			}
8600		}
8601		lun->pr_generation++;
8602		break;
8603
8604	case CTL_PR_RESERVE:
8605		lun->flags |= CTL_LUN_PR_RESERVED;
8606		lun->pr_res_type = msg->pr.pr_info.res_type;
8607		lun->pr_res_idx = msg->pr.pr_info.residx;
8608
8609		break;
8610
8611	case CTL_PR_RELEASE:
8612		/*
8613		 * If this isn't an exclusive access reservation and NUAR
8614		 * is not set, generate UA for all other registrants.
8615		 */
8616		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8617		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8618		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8619			for (i = softc->init_min; i < softc->init_max; i++)
8620				if (i == residx || ctl_get_prkey(lun, i) == 0)
8621					continue;
8622				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8623		}
8624
8625		lun->flags &= ~CTL_LUN_PR_RESERVED;
8626		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8627		lun->pr_res_type = 0;
8628		break;
8629
8630	case CTL_PR_PREEMPT:
8631		ctl_pro_preempt_other(lun, msg);
8632		break;
8633	case CTL_PR_CLEAR:
8634		lun->flags &= ~CTL_LUN_PR_RESERVED;
8635		lun->pr_res_type = 0;
8636		lun->pr_key_count = 0;
8637		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8638
8639		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8640			if (ctl_get_prkey(lun, i) == 0)
8641				continue;
8642			ctl_clr_prkey(lun, i);
8643			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8644		}
8645		lun->pr_generation++;
8646		break;
8647	}
8648
8649	mtx_unlock(&lun->lun_lock);
8650}
8651
8652int
8653ctl_read_write(struct ctl_scsiio *ctsio)
8654{
8655	struct ctl_lun *lun;
8656	struct ctl_lba_len_flags *lbalen;
8657	uint64_t lba;
8658	uint32_t num_blocks;
8659	int flags, retval;
8660	int isread;
8661
8662	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8663
8664	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8665
8666	flags = 0;
8667	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8668	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8669	switch (ctsio->cdb[0]) {
8670	case READ_6:
8671	case WRITE_6: {
8672		struct scsi_rw_6 *cdb;
8673
8674		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8675
8676		lba = scsi_3btoul(cdb->addr);
8677		/* only 5 bits are valid in the most significant address byte */
8678		lba &= 0x1fffff;
8679		num_blocks = cdb->length;
8680		/*
8681		 * This is correct according to SBC-2.
8682		 */
8683		if (num_blocks == 0)
8684			num_blocks = 256;
8685		break;
8686	}
8687	case READ_10:
8688	case WRITE_10: {
8689		struct scsi_rw_10 *cdb;
8690
8691		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8692		if (cdb->byte2 & SRW10_FUA)
8693			flags |= CTL_LLF_FUA;
8694		if (cdb->byte2 & SRW10_DPO)
8695			flags |= CTL_LLF_DPO;
8696		lba = scsi_4btoul(cdb->addr);
8697		num_blocks = scsi_2btoul(cdb->length);
8698		break;
8699	}
8700	case WRITE_VERIFY_10: {
8701		struct scsi_write_verify_10 *cdb;
8702
8703		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8704		flags |= CTL_LLF_FUA;
8705		if (cdb->byte2 & SWV_DPO)
8706			flags |= CTL_LLF_DPO;
8707		lba = scsi_4btoul(cdb->addr);
8708		num_blocks = scsi_2btoul(cdb->length);
8709		break;
8710	}
8711	case READ_12:
8712	case WRITE_12: {
8713		struct scsi_rw_12 *cdb;
8714
8715		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8716		if (cdb->byte2 & SRW12_FUA)
8717			flags |= CTL_LLF_FUA;
8718		if (cdb->byte2 & SRW12_DPO)
8719			flags |= CTL_LLF_DPO;
8720		lba = scsi_4btoul(cdb->addr);
8721		num_blocks = scsi_4btoul(cdb->length);
8722		break;
8723	}
8724	case WRITE_VERIFY_12: {
8725		struct scsi_write_verify_12 *cdb;
8726
8727		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8728		flags |= CTL_LLF_FUA;
8729		if (cdb->byte2 & SWV_DPO)
8730			flags |= CTL_LLF_DPO;
8731		lba = scsi_4btoul(cdb->addr);
8732		num_blocks = scsi_4btoul(cdb->length);
8733		break;
8734	}
8735	case READ_16:
8736	case WRITE_16: {
8737		struct scsi_rw_16 *cdb;
8738
8739		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8740		if (cdb->byte2 & SRW12_FUA)
8741			flags |= CTL_LLF_FUA;
8742		if (cdb->byte2 & SRW12_DPO)
8743			flags |= CTL_LLF_DPO;
8744		lba = scsi_8btou64(cdb->addr);
8745		num_blocks = scsi_4btoul(cdb->length);
8746		break;
8747	}
8748	case WRITE_ATOMIC_16: {
8749		struct scsi_write_atomic_16 *cdb;
8750
8751		if (lun->be_lun->atomicblock == 0) {
8752			ctl_set_invalid_opcode(ctsio);
8753			ctl_done((union ctl_io *)ctsio);
8754			return (CTL_RETVAL_COMPLETE);
8755		}
8756
8757		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8758		if (cdb->byte2 & SRW12_FUA)
8759			flags |= CTL_LLF_FUA;
8760		if (cdb->byte2 & SRW12_DPO)
8761			flags |= CTL_LLF_DPO;
8762		lba = scsi_8btou64(cdb->addr);
8763		num_blocks = scsi_2btoul(cdb->length);
8764		if (num_blocks > lun->be_lun->atomicblock) {
8765			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8766			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8767			    /*bit*/ 0);
8768			ctl_done((union ctl_io *)ctsio);
8769			return (CTL_RETVAL_COMPLETE);
8770		}
8771		break;
8772	}
8773	case WRITE_VERIFY_16: {
8774		struct scsi_write_verify_16 *cdb;
8775
8776		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8777		flags |= CTL_LLF_FUA;
8778		if (cdb->byte2 & SWV_DPO)
8779			flags |= CTL_LLF_DPO;
8780		lba = scsi_8btou64(cdb->addr);
8781		num_blocks = scsi_4btoul(cdb->length);
8782		break;
8783	}
8784	default:
8785		/*
8786		 * We got a command we don't support.  This shouldn't
8787		 * happen, commands should be filtered out above us.
8788		 */
8789		ctl_set_invalid_opcode(ctsio);
8790		ctl_done((union ctl_io *)ctsio);
8791
8792		return (CTL_RETVAL_COMPLETE);
8793		break; /* NOTREACHED */
8794	}
8795
8796	/*
8797	 * The first check is to make sure we're in bounds, the second
8798	 * check is to catch wrap-around problems.  If the lba + num blocks
8799	 * is less than the lba, then we've wrapped around and the block
8800	 * range is invalid anyway.
8801	 */
8802	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8803	 || ((lba + num_blocks) < lba)) {
8804		ctl_set_lba_out_of_range(ctsio,
8805		    MAX(lba, lun->be_lun->maxlba + 1));
8806		ctl_done((union ctl_io *)ctsio);
8807		return (CTL_RETVAL_COMPLETE);
8808	}
8809
8810	/*
8811	 * According to SBC-3, a transfer length of 0 is not an error.
8812	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8813	 * translates to 256 blocks for those commands.
8814	 */
8815	if (num_blocks == 0) {
8816		ctl_set_success(ctsio);
8817		ctl_done((union ctl_io *)ctsio);
8818		return (CTL_RETVAL_COMPLETE);
8819	}
8820
8821	/* Set FUA and/or DPO if caches are disabled. */
8822	if (isread) {
8823		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8824			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8825	} else {
8826		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8827			flags |= CTL_LLF_FUA;
8828	}
8829
8830	lbalen = (struct ctl_lba_len_flags *)
8831	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8832	lbalen->lba = lba;
8833	lbalen->len = num_blocks;
8834	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8835
8836	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8837	ctsio->kern_rel_offset = 0;
8838
8839	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8840
8841	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8842	return (retval);
8843}
8844
8845static int
8846ctl_cnw_cont(union ctl_io *io)
8847{
8848	struct ctl_scsiio *ctsio;
8849	struct ctl_lun *lun;
8850	struct ctl_lba_len_flags *lbalen;
8851	int retval;
8852
8853	ctsio = &io->scsiio;
8854	ctsio->io_hdr.status = CTL_STATUS_NONE;
8855	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8856	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8857	lbalen = (struct ctl_lba_len_flags *)
8858	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8859	lbalen->flags &= ~CTL_LLF_COMPARE;
8860	lbalen->flags |= CTL_LLF_WRITE;
8861
8862	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8863	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8864	return (retval);
8865}
8866
8867int
8868ctl_cnw(struct ctl_scsiio *ctsio)
8869{
8870	struct ctl_lun *lun;
8871	struct ctl_lba_len_flags *lbalen;
8872	uint64_t lba;
8873	uint32_t num_blocks;
8874	int flags, retval;
8875
8876	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8877
8878	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8879
8880	flags = 0;
8881	switch (ctsio->cdb[0]) {
8882	case COMPARE_AND_WRITE: {
8883		struct scsi_compare_and_write *cdb;
8884
8885		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8886		if (cdb->byte2 & SRW10_FUA)
8887			flags |= CTL_LLF_FUA;
8888		if (cdb->byte2 & SRW10_DPO)
8889			flags |= CTL_LLF_DPO;
8890		lba = scsi_8btou64(cdb->addr);
8891		num_blocks = cdb->length;
8892		break;
8893	}
8894	default:
8895		/*
8896		 * We got a command we don't support.  This shouldn't
8897		 * happen, commands should be filtered out above us.
8898		 */
8899		ctl_set_invalid_opcode(ctsio);
8900		ctl_done((union ctl_io *)ctsio);
8901
8902		return (CTL_RETVAL_COMPLETE);
8903		break; /* NOTREACHED */
8904	}
8905
8906	/*
8907	 * The first check is to make sure we're in bounds, the second
8908	 * check is to catch wrap-around problems.  If the lba + num blocks
8909	 * is less than the lba, then we've wrapped around and the block
8910	 * range is invalid anyway.
8911	 */
8912	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8913	 || ((lba + num_blocks) < lba)) {
8914		ctl_set_lba_out_of_range(ctsio,
8915		    MAX(lba, lun->be_lun->maxlba + 1));
8916		ctl_done((union ctl_io *)ctsio);
8917		return (CTL_RETVAL_COMPLETE);
8918	}
8919
8920	/*
8921	 * According to SBC-3, a transfer length of 0 is not an error.
8922	 */
8923	if (num_blocks == 0) {
8924		ctl_set_success(ctsio);
8925		ctl_done((union ctl_io *)ctsio);
8926		return (CTL_RETVAL_COMPLETE);
8927	}
8928
8929	/* Set FUA if write cache is disabled. */
8930	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8931		flags |= CTL_LLF_FUA;
8932
8933	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8934	ctsio->kern_rel_offset = 0;
8935
8936	/*
8937	 * Set the IO_CONT flag, so that if this I/O gets passed to
8938	 * ctl_data_submit_done(), it'll get passed back to
8939	 * ctl_ctl_cnw_cont() for further processing.
8940	 */
8941	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8942	ctsio->io_cont = ctl_cnw_cont;
8943
8944	lbalen = (struct ctl_lba_len_flags *)
8945	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8946	lbalen->lba = lba;
8947	lbalen->len = num_blocks;
8948	lbalen->flags = CTL_LLF_COMPARE | flags;
8949
8950	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8951	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8952	return (retval);
8953}
8954
8955int
8956ctl_verify(struct ctl_scsiio *ctsio)
8957{
8958	struct ctl_lun *lun;
8959	struct ctl_lba_len_flags *lbalen;
8960	uint64_t lba;
8961	uint32_t num_blocks;
8962	int bytchk, flags;
8963	int retval;
8964
8965	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8966
8967	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8968
8969	bytchk = 0;
8970	flags = CTL_LLF_FUA;
8971	switch (ctsio->cdb[0]) {
8972	case VERIFY_10: {
8973		struct scsi_verify_10 *cdb;
8974
8975		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8976		if (cdb->byte2 & SVFY_BYTCHK)
8977			bytchk = 1;
8978		if (cdb->byte2 & SVFY_DPO)
8979			flags |= CTL_LLF_DPO;
8980		lba = scsi_4btoul(cdb->addr);
8981		num_blocks = scsi_2btoul(cdb->length);
8982		break;
8983	}
8984	case VERIFY_12: {
8985		struct scsi_verify_12 *cdb;
8986
8987		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8988		if (cdb->byte2 & SVFY_BYTCHK)
8989			bytchk = 1;
8990		if (cdb->byte2 & SVFY_DPO)
8991			flags |= CTL_LLF_DPO;
8992		lba = scsi_4btoul(cdb->addr);
8993		num_blocks = scsi_4btoul(cdb->length);
8994		break;
8995	}
8996	case VERIFY_16: {
8997		struct scsi_rw_16 *cdb;
8998
8999		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9000		if (cdb->byte2 & SVFY_BYTCHK)
9001			bytchk = 1;
9002		if (cdb->byte2 & SVFY_DPO)
9003			flags |= CTL_LLF_DPO;
9004		lba = scsi_8btou64(cdb->addr);
9005		num_blocks = scsi_4btoul(cdb->length);
9006		break;
9007	}
9008	default:
9009		/*
9010		 * We got a command we don't support.  This shouldn't
9011		 * happen, commands should be filtered out above us.
9012		 */
9013		ctl_set_invalid_opcode(ctsio);
9014		ctl_done((union ctl_io *)ctsio);
9015		return (CTL_RETVAL_COMPLETE);
9016	}
9017
9018	/*
9019	 * The first check is to make sure we're in bounds, the second
9020	 * check is to catch wrap-around problems.  If the lba + num blocks
9021	 * is less than the lba, then we've wrapped around and the block
9022	 * range is invalid anyway.
9023	 */
9024	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9025	 || ((lba + num_blocks) < lba)) {
9026		ctl_set_lba_out_of_range(ctsio,
9027		    MAX(lba, lun->be_lun->maxlba + 1));
9028		ctl_done((union ctl_io *)ctsio);
9029		return (CTL_RETVAL_COMPLETE);
9030	}
9031
9032	/*
9033	 * According to SBC-3, a transfer length of 0 is not an error.
9034	 */
9035	if (num_blocks == 0) {
9036		ctl_set_success(ctsio);
9037		ctl_done((union ctl_io *)ctsio);
9038		return (CTL_RETVAL_COMPLETE);
9039	}
9040
9041	lbalen = (struct ctl_lba_len_flags *)
9042	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9043	lbalen->lba = lba;
9044	lbalen->len = num_blocks;
9045	if (bytchk) {
9046		lbalen->flags = CTL_LLF_COMPARE | flags;
9047		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9048	} else {
9049		lbalen->flags = CTL_LLF_VERIFY | flags;
9050		ctsio->kern_total_len = 0;
9051	}
9052	ctsio->kern_rel_offset = 0;
9053
9054	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9055	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9056	return (retval);
9057}
9058
9059int
9060ctl_report_luns(struct ctl_scsiio *ctsio)
9061{
9062	struct ctl_softc *softc;
9063	struct scsi_report_luns *cdb;
9064	struct scsi_report_luns_data *lun_data;
9065	struct ctl_lun *lun, *request_lun;
9066	struct ctl_port *port;
9067	int num_luns, retval;
9068	uint32_t alloc_len, lun_datalen;
9069	int num_filled;
9070	uint32_t initidx, targ_lun_id, lun_id;
9071
9072	retval = CTL_RETVAL_COMPLETE;
9073	cdb = (struct scsi_report_luns *)ctsio->cdb;
9074	port = ctl_io_port(&ctsio->io_hdr);
9075	softc = port->ctl_softc;
9076
9077	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9078
9079	mtx_lock(&softc->ctl_lock);
9080	num_luns = 0;
9081	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9082		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9083			num_luns++;
9084	}
9085	mtx_unlock(&softc->ctl_lock);
9086
9087	switch (cdb->select_report) {
9088	case RPL_REPORT_DEFAULT:
9089	case RPL_REPORT_ALL:
9090	case RPL_REPORT_NONSUBSID:
9091		break;
9092	case RPL_REPORT_WELLKNOWN:
9093	case RPL_REPORT_ADMIN:
9094	case RPL_REPORT_CONGLOM:
9095		num_luns = 0;
9096		break;
9097	default:
9098		ctl_set_invalid_field(ctsio,
9099				      /*sks_valid*/ 1,
9100				      /*command*/ 1,
9101				      /*field*/ 2,
9102				      /*bit_valid*/ 0,
9103				      /*bit*/ 0);
9104		ctl_done((union ctl_io *)ctsio);
9105		return (retval);
9106		break; /* NOTREACHED */
9107	}
9108
9109	alloc_len = scsi_4btoul(cdb->length);
9110	/*
9111	 * The initiator has to allocate at least 16 bytes for this request,
9112	 * so he can at least get the header and the first LUN.  Otherwise
9113	 * we reject the request (per SPC-3 rev 14, section 6.21).
9114	 */
9115	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9116	    sizeof(struct scsi_report_luns_lundata))) {
9117		ctl_set_invalid_field(ctsio,
9118				      /*sks_valid*/ 1,
9119				      /*command*/ 1,
9120				      /*field*/ 6,
9121				      /*bit_valid*/ 0,
9122				      /*bit*/ 0);
9123		ctl_done((union ctl_io *)ctsio);
9124		return (retval);
9125	}
9126
9127	request_lun = (struct ctl_lun *)
9128		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9129
9130	lun_datalen = sizeof(*lun_data) +
9131		(num_luns * sizeof(struct scsi_report_luns_lundata));
9132
9133	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9134	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9135	ctsio->kern_sg_entries = 0;
9136
9137	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9138
9139	mtx_lock(&softc->ctl_lock);
9140	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9141		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9142		if (lun_id == UINT32_MAX)
9143			continue;
9144		lun = softc->ctl_luns[lun_id];
9145		if (lun == NULL)
9146			continue;
9147
9148		be64enc(lun_data->luns[num_filled++].lundata,
9149		    ctl_encode_lun(targ_lun_id));
9150
9151		/*
9152		 * According to SPC-3, rev 14 section 6.21:
9153		 *
9154		 * "The execution of a REPORT LUNS command to any valid and
9155		 * installed logical unit shall clear the REPORTED LUNS DATA
9156		 * HAS CHANGED unit attention condition for all logical
9157		 * units of that target with respect to the requesting
9158		 * initiator. A valid and installed logical unit is one
9159		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9160		 * INQUIRY data (see 6.4.2)."
9161		 *
9162		 * If request_lun is NULL, the LUN this report luns command
9163		 * was issued to is either disabled or doesn't exist. In that
9164		 * case, we shouldn't clear any pending lun change unit
9165		 * attention.
9166		 */
9167		if (request_lun != NULL) {
9168			mtx_lock(&lun->lun_lock);
9169			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9170			mtx_unlock(&lun->lun_lock);
9171		}
9172	}
9173	mtx_unlock(&softc->ctl_lock);
9174
9175	/*
9176	 * It's quite possible that we've returned fewer LUNs than we allocated
9177	 * space for.  Trim it.
9178	 */
9179	lun_datalen = sizeof(*lun_data) +
9180		(num_filled * sizeof(struct scsi_report_luns_lundata));
9181
9182	if (lun_datalen < alloc_len) {
9183		ctsio->residual = alloc_len - lun_datalen;
9184		ctsio->kern_data_len = lun_datalen;
9185		ctsio->kern_total_len = lun_datalen;
9186	} else {
9187		ctsio->residual = 0;
9188		ctsio->kern_data_len = alloc_len;
9189		ctsio->kern_total_len = alloc_len;
9190	}
9191	ctsio->kern_data_resid = 0;
9192	ctsio->kern_rel_offset = 0;
9193	ctsio->kern_sg_entries = 0;
9194
9195	/*
9196	 * We set this to the actual data length, regardless of how much
9197	 * space we actually have to return results.  If the user looks at
9198	 * this value, he'll know whether or not he allocated enough space
9199	 * and reissue the command if necessary.  We don't support well
9200	 * known logical units, so if the user asks for that, return none.
9201	 */
9202	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9203
9204	/*
9205	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9206	 * this request.
9207	 */
9208	ctl_set_success(ctsio);
9209	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9210	ctsio->be_move_done = ctl_config_move_done;
9211	ctl_datamove((union ctl_io *)ctsio);
9212	return (retval);
9213}
9214
9215int
9216ctl_request_sense(struct ctl_scsiio *ctsio)
9217{
9218	struct scsi_request_sense *cdb;
9219	struct scsi_sense_data *sense_ptr;
9220	struct ctl_softc *softc;
9221	struct ctl_lun *lun;
9222	uint32_t initidx;
9223	int have_error;
9224	u_int sense_len = SSD_FULL_SIZE;
9225	scsi_sense_data_type sense_format;
9226	ctl_ua_type ua_type;
9227	uint8_t asc = 0, ascq = 0;
9228
9229	cdb = (struct scsi_request_sense *)ctsio->cdb;
9230
9231	softc = control_softc;
9232	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9233
9234	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9235
9236	/*
9237	 * Determine which sense format the user wants.
9238	 */
9239	if (cdb->byte2 & SRS_DESC)
9240		sense_format = SSD_TYPE_DESC;
9241	else
9242		sense_format = SSD_TYPE_FIXED;
9243
9244	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9245	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9246	ctsio->kern_sg_entries = 0;
9247
9248	/*
9249	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9250	 * larger than the largest allowed value for the length field in the
9251	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9252	 */
9253	ctsio->residual = 0;
9254	ctsio->kern_data_len = cdb->length;
9255	ctsio->kern_total_len = cdb->length;
9256
9257	ctsio->kern_data_resid = 0;
9258	ctsio->kern_rel_offset = 0;
9259	ctsio->kern_sg_entries = 0;
9260
9261	/*
9262	 * If we don't have a LUN, we don't have any pending sense.
9263	 */
9264	if (lun == NULL ||
9265	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9266	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9267		/* "Logical unit not supported" */
9268		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9269		    /*current_error*/ 1,
9270		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9271		    /*asc*/ 0x25,
9272		    /*ascq*/ 0x00,
9273		    SSD_ELEM_NONE);
9274		goto send;
9275	}
9276
9277	have_error = 0;
9278	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9279	/*
9280	 * Check for pending sense, and then for pending unit attentions.
9281	 * Pending sense gets returned first, then pending unit attentions.
9282	 */
9283	mtx_lock(&lun->lun_lock);
9284#ifdef CTL_WITH_CA
9285	if (ctl_is_set(lun->have_ca, initidx)) {
9286		scsi_sense_data_type stored_format;
9287
9288		/*
9289		 * Check to see which sense format was used for the stored
9290		 * sense data.
9291		 */
9292		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9293
9294		/*
9295		 * If the user requested a different sense format than the
9296		 * one we stored, then we need to convert it to the other
9297		 * format.  If we're going from descriptor to fixed format
9298		 * sense data, we may lose things in translation, depending
9299		 * on what options were used.
9300		 *
9301		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9302		 * for some reason we'll just copy it out as-is.
9303		 */
9304		if ((stored_format == SSD_TYPE_FIXED)
9305		 && (sense_format == SSD_TYPE_DESC))
9306			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9307			    &lun->pending_sense[initidx],
9308			    (struct scsi_sense_data_desc *)sense_ptr);
9309		else if ((stored_format == SSD_TYPE_DESC)
9310		      && (sense_format == SSD_TYPE_FIXED))
9311			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9312			    &lun->pending_sense[initidx],
9313			    (struct scsi_sense_data_fixed *)sense_ptr);
9314		else
9315			memcpy(sense_ptr, &lun->pending_sense[initidx],
9316			       MIN(sizeof(*sense_ptr),
9317			       sizeof(lun->pending_sense[initidx])));
9318
9319		ctl_clear_mask(lun->have_ca, initidx);
9320		have_error = 1;
9321	} else
9322#endif
9323	if (have_error == 0) {
9324		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9325		    sense_format);
9326		if (ua_type != CTL_UA_NONE)
9327			have_error = 1;
9328	}
9329	if (have_error == 0) {
9330		/*
9331		 * Report informational exception if have one and allowed.
9332		 */
9333		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9334			asc = lun->ie_asc;
9335			ascq = lun->ie_ascq;
9336		}
9337		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9338		    /*current_error*/ 1,
9339		    /*sense_key*/ SSD_KEY_NO_SENSE,
9340		    /*asc*/ asc,
9341		    /*ascq*/ ascq,
9342		    SSD_ELEM_NONE);
9343	}
9344	mtx_unlock(&lun->lun_lock);
9345
9346send:
9347	/*
9348	 * We report the SCSI status as OK, since the status of the command
9349	 * itself is OK.  We're reporting sense as parameter data.
9350	 */
9351	ctl_set_success(ctsio);
9352	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9353	ctsio->be_move_done = ctl_config_move_done;
9354	ctl_datamove((union ctl_io *)ctsio);
9355	return (CTL_RETVAL_COMPLETE);
9356}
9357
9358int
9359ctl_tur(struct ctl_scsiio *ctsio)
9360{
9361
9362	CTL_DEBUG_PRINT(("ctl_tur\n"));
9363
9364	ctl_set_success(ctsio);
9365	ctl_done((union ctl_io *)ctsio);
9366
9367	return (CTL_RETVAL_COMPLETE);
9368}
9369
9370/*
9371 * SCSI VPD page 0x00, the Supported VPD Pages page.
9372 */
9373static int
9374ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9375{
9376	struct scsi_vpd_supported_pages *pages;
9377	int sup_page_size;
9378	struct ctl_lun *lun;
9379	int p;
9380
9381	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9382
9383	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9384	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9385	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9386	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9387	ctsio->kern_sg_entries = 0;
9388
9389	if (sup_page_size < alloc_len) {
9390		ctsio->residual = alloc_len - sup_page_size;
9391		ctsio->kern_data_len = sup_page_size;
9392		ctsio->kern_total_len = sup_page_size;
9393	} else {
9394		ctsio->residual = 0;
9395		ctsio->kern_data_len = alloc_len;
9396		ctsio->kern_total_len = alloc_len;
9397	}
9398	ctsio->kern_data_resid = 0;
9399	ctsio->kern_rel_offset = 0;
9400	ctsio->kern_sg_entries = 0;
9401
9402	/*
9403	 * The control device is always connected.  The disk device, on the
9404	 * other hand, may not be online all the time.  Need to change this
9405	 * to figure out whether the disk device is actually online or not.
9406	 */
9407	if (lun != NULL)
9408		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9409				lun->be_lun->lun_type;
9410	else
9411		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9412
9413	p = 0;
9414	/* Supported VPD pages */
9415	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9416	/* Serial Number */
9417	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9418	/* Device Identification */
9419	pages->page_list[p++] = SVPD_DEVICE_ID;
9420	/* Extended INQUIRY Data */
9421	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9422	/* Mode Page Policy */
9423	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9424	/* SCSI Ports */
9425	pages->page_list[p++] = SVPD_SCSI_PORTS;
9426	/* Third-party Copy */
9427	pages->page_list[p++] = SVPD_SCSI_TPC;
9428	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9429		/* Block limits */
9430		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9431		/* Block Device Characteristics */
9432		pages->page_list[p++] = SVPD_BDC;
9433		/* Logical Block Provisioning */
9434		pages->page_list[p++] = SVPD_LBP;
9435	}
9436	pages->length = p;
9437
9438	ctl_set_success(ctsio);
9439	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9440	ctsio->be_move_done = ctl_config_move_done;
9441	ctl_datamove((union ctl_io *)ctsio);
9442	return (CTL_RETVAL_COMPLETE);
9443}
9444
9445/*
9446 * SCSI VPD page 0x80, the Unit Serial Number page.
9447 */
9448static int
9449ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9450{
9451	struct scsi_vpd_unit_serial_number *sn_ptr;
9452	struct ctl_lun *lun;
9453	int data_len;
9454
9455	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9456
9457	data_len = 4 + CTL_SN_LEN;
9458	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9459	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9460	if (data_len < alloc_len) {
9461		ctsio->residual = alloc_len - data_len;
9462		ctsio->kern_data_len = data_len;
9463		ctsio->kern_total_len = data_len;
9464	} else {
9465		ctsio->residual = 0;
9466		ctsio->kern_data_len = alloc_len;
9467		ctsio->kern_total_len = alloc_len;
9468	}
9469	ctsio->kern_data_resid = 0;
9470	ctsio->kern_rel_offset = 0;
9471	ctsio->kern_sg_entries = 0;
9472
9473	/*
9474	 * The control device is always connected.  The disk device, on the
9475	 * other hand, may not be online all the time.  Need to change this
9476	 * to figure out whether the disk device is actually online or not.
9477	 */
9478	if (lun != NULL)
9479		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9480				  lun->be_lun->lun_type;
9481	else
9482		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9483
9484	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9485	sn_ptr->length = CTL_SN_LEN;
9486	/*
9487	 * If we don't have a LUN, we just leave the serial number as
9488	 * all spaces.
9489	 */
9490	if (lun != NULL) {
9491		strncpy((char *)sn_ptr->serial_num,
9492			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9493	} else
9494		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9495
9496	ctl_set_success(ctsio);
9497	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9498	ctsio->be_move_done = ctl_config_move_done;
9499	ctl_datamove((union ctl_io *)ctsio);
9500	return (CTL_RETVAL_COMPLETE);
9501}
9502
9503
9504/*
9505 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9506 */
9507static int
9508ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9509{
9510	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9511	struct ctl_lun *lun;
9512	int data_len;
9513
9514	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9515
9516	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9517	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9518	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9519	ctsio->kern_sg_entries = 0;
9520
9521	if (data_len < alloc_len) {
9522		ctsio->residual = alloc_len - data_len;
9523		ctsio->kern_data_len = data_len;
9524		ctsio->kern_total_len = data_len;
9525	} else {
9526		ctsio->residual = 0;
9527		ctsio->kern_data_len = alloc_len;
9528		ctsio->kern_total_len = alloc_len;
9529	}
9530	ctsio->kern_data_resid = 0;
9531	ctsio->kern_rel_offset = 0;
9532	ctsio->kern_sg_entries = 0;
9533
9534	/*
9535	 * The control device is always connected.  The disk device, on the
9536	 * other hand, may not be online all the time.
9537	 */
9538	if (lun != NULL)
9539		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9540				     lun->be_lun->lun_type;
9541	else
9542		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9543	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9544	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9545	/*
9546	 * We support head of queue, ordered and simple tags.
9547	 */
9548	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9549	/*
9550	 * Volatile cache supported.
9551	 */
9552	eid_ptr->flags3 = SVPD_EID_V_SUP;
9553
9554	/*
9555	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9556	 * attention for a particular IT nexus on all LUNs once we report
9557	 * it to that nexus once.  This bit is required as of SPC-4.
9558	 */
9559	eid_ptr->flags4 = SVPD_EID_LUICLR;
9560
9561	/*
9562	 * XXX KDM in order to correctly answer this, we would need
9563	 * information from the SIM to determine how much sense data it
9564	 * can send.  So this would really be a path inquiry field, most
9565	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9566	 * but the hardware may or may not be able to support that much.
9567	 * 0 just means that the maximum sense data length is not reported.
9568	 */
9569	eid_ptr->max_sense_length = 0;
9570
9571	ctl_set_success(ctsio);
9572	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9573	ctsio->be_move_done = ctl_config_move_done;
9574	ctl_datamove((union ctl_io *)ctsio);
9575	return (CTL_RETVAL_COMPLETE);
9576}
9577
9578static int
9579ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9580{
9581	struct scsi_vpd_mode_page_policy *mpp_ptr;
9582	struct ctl_lun *lun;
9583	int data_len;
9584
9585	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9586
9587	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9588	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9589
9590	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9591	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9592	ctsio->kern_sg_entries = 0;
9593
9594	if (data_len < alloc_len) {
9595		ctsio->residual = alloc_len - data_len;
9596		ctsio->kern_data_len = data_len;
9597		ctsio->kern_total_len = data_len;
9598	} else {
9599		ctsio->residual = 0;
9600		ctsio->kern_data_len = alloc_len;
9601		ctsio->kern_total_len = alloc_len;
9602	}
9603	ctsio->kern_data_resid = 0;
9604	ctsio->kern_rel_offset = 0;
9605	ctsio->kern_sg_entries = 0;
9606
9607	/*
9608	 * The control device is always connected.  The disk device, on the
9609	 * other hand, may not be online all the time.
9610	 */
9611	if (lun != NULL)
9612		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9613				     lun->be_lun->lun_type;
9614	else
9615		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9616	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9617	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9618	mpp_ptr->descr[0].page_code = 0x3f;
9619	mpp_ptr->descr[0].subpage_code = 0xff;
9620	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9621
9622	ctl_set_success(ctsio);
9623	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9624	ctsio->be_move_done = ctl_config_move_done;
9625	ctl_datamove((union ctl_io *)ctsio);
9626	return (CTL_RETVAL_COMPLETE);
9627}
9628
9629/*
9630 * SCSI VPD page 0x83, the Device Identification page.
9631 */
9632static int
9633ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9634{
9635	struct scsi_vpd_device_id *devid_ptr;
9636	struct scsi_vpd_id_descriptor *desc;
9637	struct ctl_softc *softc;
9638	struct ctl_lun *lun;
9639	struct ctl_port *port;
9640	int data_len, g;
9641	uint8_t proto;
9642
9643	softc = control_softc;
9644
9645	port = ctl_io_port(&ctsio->io_hdr);
9646	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9647
9648	data_len = sizeof(struct scsi_vpd_device_id) +
9649	    sizeof(struct scsi_vpd_id_descriptor) +
9650		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9651	    sizeof(struct scsi_vpd_id_descriptor) +
9652		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9653	if (lun && lun->lun_devid)
9654		data_len += lun->lun_devid->len;
9655	if (port && port->port_devid)
9656		data_len += port->port_devid->len;
9657	if (port && port->target_devid)
9658		data_len += port->target_devid->len;
9659
9660	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9661	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9662	ctsio->kern_sg_entries = 0;
9663
9664	if (data_len < alloc_len) {
9665		ctsio->residual = alloc_len - data_len;
9666		ctsio->kern_data_len = data_len;
9667		ctsio->kern_total_len = data_len;
9668	} else {
9669		ctsio->residual = 0;
9670		ctsio->kern_data_len = alloc_len;
9671		ctsio->kern_total_len = alloc_len;
9672	}
9673	ctsio->kern_data_resid = 0;
9674	ctsio->kern_rel_offset = 0;
9675	ctsio->kern_sg_entries = 0;
9676
9677	/*
9678	 * The control device is always connected.  The disk device, on the
9679	 * other hand, may not be online all the time.
9680	 */
9681	if (lun != NULL)
9682		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9683				     lun->be_lun->lun_type;
9684	else
9685		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9686	devid_ptr->page_code = SVPD_DEVICE_ID;
9687	scsi_ulto2b(data_len - 4, devid_ptr->length);
9688
9689	if (port && port->port_type == CTL_PORT_FC)
9690		proto = SCSI_PROTO_FC << 4;
9691	else if (port && port->port_type == CTL_PORT_ISCSI)
9692		proto = SCSI_PROTO_ISCSI << 4;
9693	else
9694		proto = SCSI_PROTO_SPI << 4;
9695	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9696
9697	/*
9698	 * We're using a LUN association here.  i.e., this device ID is a
9699	 * per-LUN identifier.
9700	 */
9701	if (lun && lun->lun_devid) {
9702		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9703		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9704		    lun->lun_devid->len);
9705	}
9706
9707	/*
9708	 * This is for the WWPN which is a port association.
9709	 */
9710	if (port && port->port_devid) {
9711		memcpy(desc, port->port_devid->data, port->port_devid->len);
9712		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9713		    port->port_devid->len);
9714	}
9715
9716	/*
9717	 * This is for the Relative Target Port(type 4h) identifier
9718	 */
9719	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9720	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9721	    SVPD_ID_TYPE_RELTARG;
9722	desc->length = 4;
9723	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9724	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9725	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9726
9727	/*
9728	 * This is for the Target Port Group(type 5h) identifier
9729	 */
9730	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9731	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9732	    SVPD_ID_TYPE_TPORTGRP;
9733	desc->length = 4;
9734	if (softc->is_single ||
9735	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9736		g = 1;
9737	else
9738		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9739	scsi_ulto2b(g, &desc->identifier[2]);
9740	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9741	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9742
9743	/*
9744	 * This is for the Target identifier
9745	 */
9746	if (port && port->target_devid) {
9747		memcpy(desc, port->target_devid->data, port->target_devid->len);
9748	}
9749
9750	ctl_set_success(ctsio);
9751	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9752	ctsio->be_move_done = ctl_config_move_done;
9753	ctl_datamove((union ctl_io *)ctsio);
9754	return (CTL_RETVAL_COMPLETE);
9755}
9756
9757static int
9758ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9759{
9760	struct ctl_softc *softc = control_softc;
9761	struct scsi_vpd_scsi_ports *sp;
9762	struct scsi_vpd_port_designation *pd;
9763	struct scsi_vpd_port_designation_cont *pdc;
9764	struct ctl_lun *lun;
9765	struct ctl_port *port;
9766	int data_len, num_target_ports, iid_len, id_len;
9767
9768	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9769
9770	num_target_ports = 0;
9771	iid_len = 0;
9772	id_len = 0;
9773	mtx_lock(&softc->ctl_lock);
9774	STAILQ_FOREACH(port, &softc->port_list, links) {
9775		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9776			continue;
9777		if (lun != NULL &&
9778		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9779			continue;
9780		num_target_ports++;
9781		if (port->init_devid)
9782			iid_len += port->init_devid->len;
9783		if (port->port_devid)
9784			id_len += port->port_devid->len;
9785	}
9786	mtx_unlock(&softc->ctl_lock);
9787
9788	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9789	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9790	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9791	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9792	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9793	ctsio->kern_sg_entries = 0;
9794
9795	if (data_len < alloc_len) {
9796		ctsio->residual = alloc_len - data_len;
9797		ctsio->kern_data_len = data_len;
9798		ctsio->kern_total_len = data_len;
9799	} else {
9800		ctsio->residual = 0;
9801		ctsio->kern_data_len = alloc_len;
9802		ctsio->kern_total_len = alloc_len;
9803	}
9804	ctsio->kern_data_resid = 0;
9805	ctsio->kern_rel_offset = 0;
9806	ctsio->kern_sg_entries = 0;
9807
9808	/*
9809	 * The control device is always connected.  The disk device, on the
9810	 * other hand, may not be online all the time.  Need to change this
9811	 * to figure out whether the disk device is actually online or not.
9812	 */
9813	if (lun != NULL)
9814		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9815				  lun->be_lun->lun_type;
9816	else
9817		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9818
9819	sp->page_code = SVPD_SCSI_PORTS;
9820	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9821	    sp->page_length);
9822	pd = &sp->design[0];
9823
9824	mtx_lock(&softc->ctl_lock);
9825	STAILQ_FOREACH(port, &softc->port_list, links) {
9826		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9827			continue;
9828		if (lun != NULL &&
9829		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9830			continue;
9831		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9832		if (port->init_devid) {
9833			iid_len = port->init_devid->len;
9834			memcpy(pd->initiator_transportid,
9835			    port->init_devid->data, port->init_devid->len);
9836		} else
9837			iid_len = 0;
9838		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9839		pdc = (struct scsi_vpd_port_designation_cont *)
9840		    (&pd->initiator_transportid[iid_len]);
9841		if (port->port_devid) {
9842			id_len = port->port_devid->len;
9843			memcpy(pdc->target_port_descriptors,
9844			    port->port_devid->data, port->port_devid->len);
9845		} else
9846			id_len = 0;
9847		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9848		pd = (struct scsi_vpd_port_designation *)
9849		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9850	}
9851	mtx_unlock(&softc->ctl_lock);
9852
9853	ctl_set_success(ctsio);
9854	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9855	ctsio->be_move_done = ctl_config_move_done;
9856	ctl_datamove((union ctl_io *)ctsio);
9857	return (CTL_RETVAL_COMPLETE);
9858}
9859
9860static int
9861ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9862{
9863	struct scsi_vpd_block_limits *bl_ptr;
9864	struct ctl_lun *lun;
9865	uint64_t ival;
9866
9867	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9868
9869	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9870	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9871	ctsio->kern_sg_entries = 0;
9872
9873	if (sizeof(*bl_ptr) < alloc_len) {
9874		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9875		ctsio->kern_data_len = sizeof(*bl_ptr);
9876		ctsio->kern_total_len = sizeof(*bl_ptr);
9877	} else {
9878		ctsio->residual = 0;
9879		ctsio->kern_data_len = alloc_len;
9880		ctsio->kern_total_len = alloc_len;
9881	}
9882	ctsio->kern_data_resid = 0;
9883	ctsio->kern_rel_offset = 0;
9884	ctsio->kern_sg_entries = 0;
9885
9886	/*
9887	 * The control device is always connected.  The disk device, on the
9888	 * other hand, may not be online all the time.  Need to change this
9889	 * to figure out whether the disk device is actually online or not.
9890	 */
9891	if (lun != NULL)
9892		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9893				  lun->be_lun->lun_type;
9894	else
9895		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9896
9897	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9898	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9899	bl_ptr->max_cmp_write_len = 0xff;
9900	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9901	if (lun != NULL) {
9902		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9903		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9904			ival = 0xffffffff;
9905			ctl_get_opt_number(&lun->be_lun->options,
9906			    "unmap_max_lba", &ival);
9907			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9908			ival = 0xffffffff;
9909			ctl_get_opt_number(&lun->be_lun->options,
9910			    "unmap_max_descr", &ival);
9911			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9912			if (lun->be_lun->ublockexp != 0) {
9913				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9914				    bl_ptr->opt_unmap_grain);
9915				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9916				    bl_ptr->unmap_grain_align);
9917			}
9918		}
9919		scsi_ulto4b(lun->be_lun->atomicblock,
9920		    bl_ptr->max_atomic_transfer_length);
9921		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9922		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9923		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9924		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9925		ival = UINT64_MAX;
9926		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9927		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9928	}
9929
9930	ctl_set_success(ctsio);
9931	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9932	ctsio->be_move_done = ctl_config_move_done;
9933	ctl_datamove((union ctl_io *)ctsio);
9934	return (CTL_RETVAL_COMPLETE);
9935}
9936
9937static int
9938ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9939{
9940	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9941	struct ctl_lun *lun;
9942	const char *value;
9943	u_int i;
9944
9945	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9946
9947	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9948	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9949	ctsio->kern_sg_entries = 0;
9950
9951	if (sizeof(*bdc_ptr) < alloc_len) {
9952		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9953		ctsio->kern_data_len = sizeof(*bdc_ptr);
9954		ctsio->kern_total_len = sizeof(*bdc_ptr);
9955	} else {
9956		ctsio->residual = 0;
9957		ctsio->kern_data_len = alloc_len;
9958		ctsio->kern_total_len = alloc_len;
9959	}
9960	ctsio->kern_data_resid = 0;
9961	ctsio->kern_rel_offset = 0;
9962	ctsio->kern_sg_entries = 0;
9963
9964	/*
9965	 * The control device is always connected.  The disk device, on the
9966	 * other hand, may not be online all the time.  Need to change this
9967	 * to figure out whether the disk device is actually online or not.
9968	 */
9969	if (lun != NULL)
9970		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9971				  lun->be_lun->lun_type;
9972	else
9973		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9974	bdc_ptr->page_code = SVPD_BDC;
9975	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9976	if (lun != NULL &&
9977	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9978		i = strtol(value, NULL, 0);
9979	else
9980		i = CTL_DEFAULT_ROTATION_RATE;
9981	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9982	if (lun != NULL &&
9983	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9984		i = strtol(value, NULL, 0);
9985	else
9986		i = 0;
9987	bdc_ptr->wab_wac_ff = (i & 0x0f);
9988	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9989
9990	ctl_set_success(ctsio);
9991	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9992	ctsio->be_move_done = ctl_config_move_done;
9993	ctl_datamove((union ctl_io *)ctsio);
9994	return (CTL_RETVAL_COMPLETE);
9995}
9996
9997static int
9998ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9999{
10000	struct scsi_vpd_logical_block_prov *lbp_ptr;
10001	struct ctl_lun *lun;
10002	const char *value;
10003
10004	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10005
10006	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10007	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10008	ctsio->kern_sg_entries = 0;
10009
10010	if (sizeof(*lbp_ptr) < alloc_len) {
10011		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10012		ctsio->kern_data_len = sizeof(*lbp_ptr);
10013		ctsio->kern_total_len = sizeof(*lbp_ptr);
10014	} else {
10015		ctsio->residual = 0;
10016		ctsio->kern_data_len = alloc_len;
10017		ctsio->kern_total_len = alloc_len;
10018	}
10019	ctsio->kern_data_resid = 0;
10020	ctsio->kern_rel_offset = 0;
10021	ctsio->kern_sg_entries = 0;
10022
10023	/*
10024	 * The control device is always connected.  The disk device, on the
10025	 * other hand, may not be online all the time.  Need to change this
10026	 * to figure out whether the disk device is actually online or not.
10027	 */
10028	if (lun != NULL)
10029		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10030				  lun->be_lun->lun_type;
10031	else
10032		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10033
10034	lbp_ptr->page_code = SVPD_LBP;
10035	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10036	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10037	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10038		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10039		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10040		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10041		if (value != NULL) {
10042			if (strcmp(value, "resource") == 0)
10043				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10044			else if (strcmp(value, "thin") == 0)
10045				lbp_ptr->prov_type = SVPD_LBP_THIN;
10046		} else
10047			lbp_ptr->prov_type = SVPD_LBP_THIN;
10048	}
10049
10050	ctl_set_success(ctsio);
10051	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10052	ctsio->be_move_done = ctl_config_move_done;
10053	ctl_datamove((union ctl_io *)ctsio);
10054	return (CTL_RETVAL_COMPLETE);
10055}
10056
10057/*
10058 * INQUIRY with the EVPD bit set.
10059 */
10060static int
10061ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10062{
10063	struct ctl_lun *lun;
10064	struct scsi_inquiry *cdb;
10065	int alloc_len, retval;
10066
10067	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10068	cdb = (struct scsi_inquiry *)ctsio->cdb;
10069	alloc_len = scsi_2btoul(cdb->length);
10070
10071	switch (cdb->page_code) {
10072	case SVPD_SUPPORTED_PAGES:
10073		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10074		break;
10075	case SVPD_UNIT_SERIAL_NUMBER:
10076		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10077		break;
10078	case SVPD_DEVICE_ID:
10079		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10080		break;
10081	case SVPD_EXTENDED_INQUIRY_DATA:
10082		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10083		break;
10084	case SVPD_MODE_PAGE_POLICY:
10085		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10086		break;
10087	case SVPD_SCSI_PORTS:
10088		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10089		break;
10090	case SVPD_SCSI_TPC:
10091		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10092		break;
10093	case SVPD_BLOCK_LIMITS:
10094		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10095			goto err;
10096		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10097		break;
10098	case SVPD_BDC:
10099		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10100			goto err;
10101		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10102		break;
10103	case SVPD_LBP:
10104		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10105			goto err;
10106		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10107		break;
10108	default:
10109err:
10110		ctl_set_invalid_field(ctsio,
10111				      /*sks_valid*/ 1,
10112				      /*command*/ 1,
10113				      /*field*/ 2,
10114				      /*bit_valid*/ 0,
10115				      /*bit*/ 0);
10116		ctl_done((union ctl_io *)ctsio);
10117		retval = CTL_RETVAL_COMPLETE;
10118		break;
10119	}
10120
10121	return (retval);
10122}
10123
10124/*
10125 * Standard INQUIRY data.
10126 */
10127static int
10128ctl_inquiry_std(struct ctl_scsiio *ctsio)
10129{
10130	struct scsi_inquiry_data *inq_ptr;
10131	struct scsi_inquiry *cdb;
10132	struct ctl_softc *softc = control_softc;
10133	struct ctl_port *port;
10134	struct ctl_lun *lun;
10135	char *val;
10136	uint32_t alloc_len, data_len;
10137	ctl_port_type port_type;
10138
10139	port = ctl_io_port(&ctsio->io_hdr);
10140	port_type = port->port_type;
10141	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10142		port_type = CTL_PORT_SCSI;
10143
10144	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10145	cdb = (struct scsi_inquiry *)ctsio->cdb;
10146	alloc_len = scsi_2btoul(cdb->length);
10147
10148	/*
10149	 * We malloc the full inquiry data size here and fill it
10150	 * in.  If the user only asks for less, we'll give him
10151	 * that much.
10152	 */
10153	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10154	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10155	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10156	ctsio->kern_sg_entries = 0;
10157	ctsio->kern_data_resid = 0;
10158	ctsio->kern_rel_offset = 0;
10159
10160	if (data_len < alloc_len) {
10161		ctsio->residual = alloc_len - data_len;
10162		ctsio->kern_data_len = data_len;
10163		ctsio->kern_total_len = data_len;
10164	} else {
10165		ctsio->residual = 0;
10166		ctsio->kern_data_len = alloc_len;
10167		ctsio->kern_total_len = alloc_len;
10168	}
10169
10170	if (lun != NULL) {
10171		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10172		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10173			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10174			    lun->be_lun->lun_type;
10175		} else {
10176			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10177			    lun->be_lun->lun_type;
10178		}
10179		if (lun->flags & CTL_LUN_REMOVABLE)
10180			inq_ptr->dev_qual2 |= SID_RMB;
10181	} else
10182		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10183
10184	/* RMB in byte 2 is 0 */
10185	inq_ptr->version = SCSI_REV_SPC5;
10186
10187	/*
10188	 * According to SAM-3, even if a device only supports a single
10189	 * level of LUN addressing, it should still set the HISUP bit:
10190	 *
10191	 * 4.9.1 Logical unit numbers overview
10192	 *
10193	 * All logical unit number formats described in this standard are
10194	 * hierarchical in structure even when only a single level in that
10195	 * hierarchy is used. The HISUP bit shall be set to one in the
10196	 * standard INQUIRY data (see SPC-2) when any logical unit number
10197	 * format described in this standard is used.  Non-hierarchical
10198	 * formats are outside the scope of this standard.
10199	 *
10200	 * Therefore we set the HiSup bit here.
10201	 *
10202	 * The response format is 2, per SPC-3.
10203	 */
10204	inq_ptr->response_format = SID_HiSup | 2;
10205
10206	inq_ptr->additional_length = data_len -
10207	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10208	CTL_DEBUG_PRINT(("additional_length = %d\n",
10209			 inq_ptr->additional_length));
10210
10211	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10212	if (port_type == CTL_PORT_SCSI)
10213		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10214	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10215	inq_ptr->flags = SID_CmdQue;
10216	if (port_type == CTL_PORT_SCSI)
10217		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10218
10219	/*
10220	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10221	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10222	 * name and 4 bytes for the revision.
10223	 */
10224	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10225	    "vendor")) == NULL) {
10226		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10227	} else {
10228		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10229		strncpy(inq_ptr->vendor, val,
10230		    min(sizeof(inq_ptr->vendor), strlen(val)));
10231	}
10232	if (lun == NULL) {
10233		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10234		    sizeof(inq_ptr->product));
10235	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10236		switch (lun->be_lun->lun_type) {
10237		case T_DIRECT:
10238			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10239			    sizeof(inq_ptr->product));
10240			break;
10241		case T_PROCESSOR:
10242			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10243			    sizeof(inq_ptr->product));
10244			break;
10245		case T_CDROM:
10246			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10247			    sizeof(inq_ptr->product));
10248			break;
10249		default:
10250			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10251			    sizeof(inq_ptr->product));
10252			break;
10253		}
10254	} else {
10255		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10256		strncpy(inq_ptr->product, val,
10257		    min(sizeof(inq_ptr->product), strlen(val)));
10258	}
10259
10260	/*
10261	 * XXX make this a macro somewhere so it automatically gets
10262	 * incremented when we make changes.
10263	 */
10264	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10265	    "revision")) == NULL) {
10266		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10267	} else {
10268		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10269		strncpy(inq_ptr->revision, val,
10270		    min(sizeof(inq_ptr->revision), strlen(val)));
10271	}
10272
10273	/*
10274	 * For parallel SCSI, we support double transition and single
10275	 * transition clocking.  We also support QAS (Quick Arbitration
10276	 * and Selection) and Information Unit transfers on both the
10277	 * control and array devices.
10278	 */
10279	if (port_type == CTL_PORT_SCSI)
10280		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10281				    SID_SPI_IUS;
10282
10283	/* SAM-6 (no version claimed) */
10284	scsi_ulto2b(0x00C0, inq_ptr->version1);
10285	/* SPC-5 (no version claimed) */
10286	scsi_ulto2b(0x05C0, inq_ptr->version2);
10287	if (port_type == CTL_PORT_FC) {
10288		/* FCP-2 ANSI INCITS.350:2003 */
10289		scsi_ulto2b(0x0917, inq_ptr->version3);
10290	} else if (port_type == CTL_PORT_SCSI) {
10291		/* SPI-4 ANSI INCITS.362:200x */
10292		scsi_ulto2b(0x0B56, inq_ptr->version3);
10293	} else if (port_type == CTL_PORT_ISCSI) {
10294		/* iSCSI (no version claimed) */
10295		scsi_ulto2b(0x0960, inq_ptr->version3);
10296	} else if (port_type == CTL_PORT_SAS) {
10297		/* SAS (no version claimed) */
10298		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10299	}
10300
10301	if (lun == NULL) {
10302		/* SBC-4 (no version claimed) */
10303		scsi_ulto2b(0x0600, inq_ptr->version4);
10304	} else {
10305		switch (lun->be_lun->lun_type) {
10306		case T_DIRECT:
10307			/* SBC-4 (no version claimed) */
10308			scsi_ulto2b(0x0600, inq_ptr->version4);
10309			break;
10310		case T_PROCESSOR:
10311			break;
10312		case T_CDROM:
10313			/* MMC-6 (no version claimed) */
10314			scsi_ulto2b(0x04E0, inq_ptr->version4);
10315			break;
10316		default:
10317			break;
10318		}
10319	}
10320
10321	ctl_set_success(ctsio);
10322	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10323	ctsio->be_move_done = ctl_config_move_done;
10324	ctl_datamove((union ctl_io *)ctsio);
10325	return (CTL_RETVAL_COMPLETE);
10326}
10327
10328int
10329ctl_inquiry(struct ctl_scsiio *ctsio)
10330{
10331	struct scsi_inquiry *cdb;
10332	int retval;
10333
10334	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10335
10336	cdb = (struct scsi_inquiry *)ctsio->cdb;
10337	if (cdb->byte2 & SI_EVPD)
10338		retval = ctl_inquiry_evpd(ctsio);
10339	else if (cdb->page_code == 0)
10340		retval = ctl_inquiry_std(ctsio);
10341	else {
10342		ctl_set_invalid_field(ctsio,
10343				      /*sks_valid*/ 1,
10344				      /*command*/ 1,
10345				      /*field*/ 2,
10346				      /*bit_valid*/ 0,
10347				      /*bit*/ 0);
10348		ctl_done((union ctl_io *)ctsio);
10349		return (CTL_RETVAL_COMPLETE);
10350	}
10351
10352	return (retval);
10353}
10354
10355int
10356ctl_get_config(struct ctl_scsiio *ctsio)
10357{
10358	struct scsi_get_config_header *hdr;
10359	struct scsi_get_config_feature *feature;
10360	struct scsi_get_config *cdb;
10361	struct ctl_lun *lun;
10362	uint32_t alloc_len, data_len;
10363	int rt, starting;
10364
10365	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10366	cdb = (struct scsi_get_config *)ctsio->cdb;
10367	rt = (cdb->rt & SGC_RT_MASK);
10368	starting = scsi_2btoul(cdb->starting_feature);
10369	alloc_len = scsi_2btoul(cdb->length);
10370
10371	data_len = sizeof(struct scsi_get_config_header) +
10372	    sizeof(struct scsi_get_config_feature) + 8 +
10373	    sizeof(struct scsi_get_config_feature) + 8 +
10374	    sizeof(struct scsi_get_config_feature) + 4 +
10375	    sizeof(struct scsi_get_config_feature) + 4 +
10376	    sizeof(struct scsi_get_config_feature) + 8 +
10377	    sizeof(struct scsi_get_config_feature) +
10378	    sizeof(struct scsi_get_config_feature) + 4 +
10379	    sizeof(struct scsi_get_config_feature) + 4 +
10380	    sizeof(struct scsi_get_config_feature) + 4 +
10381	    sizeof(struct scsi_get_config_feature) + 4 +
10382	    sizeof(struct scsi_get_config_feature) + 4 +
10383	    sizeof(struct scsi_get_config_feature) + 4;
10384	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10385	ctsio->kern_sg_entries = 0;
10386	ctsio->kern_data_resid = 0;
10387	ctsio->kern_rel_offset = 0;
10388
10389	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10390	if (lun->flags & CTL_LUN_NO_MEDIA)
10391		scsi_ulto2b(0x0000, hdr->current_profile);
10392	else
10393		scsi_ulto2b(0x0010, hdr->current_profile);
10394	feature = (struct scsi_get_config_feature *)(hdr + 1);
10395
10396	if (starting > 0x003b)
10397		goto done;
10398	if (starting > 0x003a)
10399		goto f3b;
10400	if (starting > 0x002b)
10401		goto f3a;
10402	if (starting > 0x002a)
10403		goto f2b;
10404	if (starting > 0x001f)
10405		goto f2a;
10406	if (starting > 0x001e)
10407		goto f1f;
10408	if (starting > 0x001d)
10409		goto f1e;
10410	if (starting > 0x0010)
10411		goto f1d;
10412	if (starting > 0x0003)
10413		goto f10;
10414	if (starting > 0x0002)
10415		goto f3;
10416	if (starting > 0x0001)
10417		goto f2;
10418	if (starting > 0x0000)
10419		goto f1;
10420
10421	/* Profile List */
10422	scsi_ulto2b(0x0000, feature->feature_code);
10423	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10424	feature->add_length = 8;
10425	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10426	feature->feature_data[2] = 0x00;
10427	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10428	feature->feature_data[6] = 0x01;
10429	feature = (struct scsi_get_config_feature *)
10430	    &feature->feature_data[feature->add_length];
10431
10432f1:	/* Core */
10433	scsi_ulto2b(0x0001, feature->feature_code);
10434	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10435	feature->add_length = 8;
10436	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10437	feature->feature_data[4] = 0x03;
10438	feature = (struct scsi_get_config_feature *)
10439	    &feature->feature_data[feature->add_length];
10440
10441f2:	/* Morphing */
10442	scsi_ulto2b(0x0002, feature->feature_code);
10443	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10444	feature->add_length = 4;
10445	feature->feature_data[0] = 0x02;
10446	feature = (struct scsi_get_config_feature *)
10447	    &feature->feature_data[feature->add_length];
10448
10449f3:	/* Removable Medium */
10450	scsi_ulto2b(0x0003, feature->feature_code);
10451	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10452	feature->add_length = 4;
10453	feature->feature_data[0] = 0x39;
10454	feature = (struct scsi_get_config_feature *)
10455	    &feature->feature_data[feature->add_length];
10456
10457	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10458		goto done;
10459
10460f10:	/* Random Read */
10461	scsi_ulto2b(0x0010, feature->feature_code);
10462	feature->flags = 0x00;
10463	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10464		feature->flags |= SGC_F_CURRENT;
10465	feature->add_length = 8;
10466	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10467	scsi_ulto2b(1, &feature->feature_data[4]);
10468	feature->feature_data[6] = 0x00;
10469	feature = (struct scsi_get_config_feature *)
10470	    &feature->feature_data[feature->add_length];
10471
10472f1d:	/* Multi-Read */
10473	scsi_ulto2b(0x001D, feature->feature_code);
10474	feature->flags = 0x00;
10475	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10476		feature->flags |= SGC_F_CURRENT;
10477	feature->add_length = 0;
10478	feature = (struct scsi_get_config_feature *)
10479	    &feature->feature_data[feature->add_length];
10480
10481f1e:	/* CD Read */
10482	scsi_ulto2b(0x001E, feature->feature_code);
10483	feature->flags = 0x00;
10484	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10485		feature->flags |= SGC_F_CURRENT;
10486	feature->add_length = 4;
10487	feature->feature_data[0] = 0x00;
10488	feature = (struct scsi_get_config_feature *)
10489	    &feature->feature_data[feature->add_length];
10490
10491f1f:	/* DVD Read */
10492	scsi_ulto2b(0x001F, feature->feature_code);
10493	feature->flags = 0x08;
10494	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10495		feature->flags |= SGC_F_CURRENT;
10496	feature->add_length = 4;
10497	feature->feature_data[0] = 0x01;
10498	feature->feature_data[2] = 0x03;
10499	feature = (struct scsi_get_config_feature *)
10500	    &feature->feature_data[feature->add_length];
10501
10502f2a:	/* DVD+RW */
10503	scsi_ulto2b(0x002A, feature->feature_code);
10504	feature->flags = 0x04;
10505	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10506		feature->flags |= SGC_F_CURRENT;
10507	feature->add_length = 4;
10508	feature->feature_data[0] = 0x00;
10509	feature->feature_data[1] = 0x00;
10510	feature = (struct scsi_get_config_feature *)
10511	    &feature->feature_data[feature->add_length];
10512
10513f2b:	/* DVD+R */
10514	scsi_ulto2b(0x002B, feature->feature_code);
10515	feature->flags = 0x00;
10516	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10517		feature->flags |= SGC_F_CURRENT;
10518	feature->add_length = 4;
10519	feature->feature_data[0] = 0x00;
10520	feature = (struct scsi_get_config_feature *)
10521	    &feature->feature_data[feature->add_length];
10522
10523f3a:	/* DVD+RW Dual Layer */
10524	scsi_ulto2b(0x003A, feature->feature_code);
10525	feature->flags = 0x00;
10526	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10527		feature->flags |= SGC_F_CURRENT;
10528	feature->add_length = 4;
10529	feature->feature_data[0] = 0x00;
10530	feature->feature_data[1] = 0x00;
10531	feature = (struct scsi_get_config_feature *)
10532	    &feature->feature_data[feature->add_length];
10533
10534f3b:	/* DVD+R Dual Layer */
10535	scsi_ulto2b(0x003B, feature->feature_code);
10536	feature->flags = 0x00;
10537	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10538		feature->flags |= SGC_F_CURRENT;
10539	feature->add_length = 4;
10540	feature->feature_data[0] = 0x00;
10541	feature = (struct scsi_get_config_feature *)
10542	    &feature->feature_data[feature->add_length];
10543
10544done:
10545	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10546	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10547		feature = (struct scsi_get_config_feature *)(hdr + 1);
10548		if (scsi_2btoul(feature->feature_code) == starting)
10549			feature = (struct scsi_get_config_feature *)
10550			    &feature->feature_data[feature->add_length];
10551		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10552	}
10553	scsi_ulto4b(data_len - 4, hdr->data_length);
10554	if (data_len < alloc_len) {
10555		ctsio->residual = alloc_len - data_len;
10556		ctsio->kern_data_len = data_len;
10557		ctsio->kern_total_len = data_len;
10558	} else {
10559		ctsio->residual = 0;
10560		ctsio->kern_data_len = alloc_len;
10561		ctsio->kern_total_len = alloc_len;
10562	}
10563
10564	ctl_set_success(ctsio);
10565	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10566	ctsio->be_move_done = ctl_config_move_done;
10567	ctl_datamove((union ctl_io *)ctsio);
10568	return (CTL_RETVAL_COMPLETE);
10569}
10570
10571int
10572ctl_get_event_status(struct ctl_scsiio *ctsio)
10573{
10574	struct scsi_get_event_status_header *hdr;
10575	struct scsi_get_event_status *cdb;
10576	struct ctl_lun *lun;
10577	uint32_t alloc_len, data_len;
10578	int notif_class;
10579
10580	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10581	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10582	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10583		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10584		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10585		ctl_done((union ctl_io *)ctsio);
10586		return (CTL_RETVAL_COMPLETE);
10587	}
10588	notif_class = cdb->notif_class;
10589	alloc_len = scsi_2btoul(cdb->length);
10590
10591	data_len = sizeof(struct scsi_get_event_status_header);
10592	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10593	ctsio->kern_sg_entries = 0;
10594	ctsio->kern_data_resid = 0;
10595	ctsio->kern_rel_offset = 0;
10596
10597	if (data_len < alloc_len) {
10598		ctsio->residual = alloc_len - data_len;
10599		ctsio->kern_data_len = data_len;
10600		ctsio->kern_total_len = data_len;
10601	} else {
10602		ctsio->residual = 0;
10603		ctsio->kern_data_len = alloc_len;
10604		ctsio->kern_total_len = alloc_len;
10605	}
10606
10607	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10608	scsi_ulto2b(0, hdr->descr_length);
10609	hdr->nea_class = SGESN_NEA;
10610	hdr->supported_class = 0;
10611
10612	ctl_set_success(ctsio);
10613	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10614	ctsio->be_move_done = ctl_config_move_done;
10615	ctl_datamove((union ctl_io *)ctsio);
10616	return (CTL_RETVAL_COMPLETE);
10617}
10618
10619int
10620ctl_mechanism_status(struct ctl_scsiio *ctsio)
10621{
10622	struct scsi_mechanism_status_header *hdr;
10623	struct scsi_mechanism_status *cdb;
10624	struct ctl_lun *lun;
10625	uint32_t alloc_len, data_len;
10626
10627	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10628	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10629	alloc_len = scsi_2btoul(cdb->length);
10630
10631	data_len = sizeof(struct scsi_mechanism_status_header);
10632	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10633	ctsio->kern_sg_entries = 0;
10634	ctsio->kern_data_resid = 0;
10635	ctsio->kern_rel_offset = 0;
10636
10637	if (data_len < alloc_len) {
10638		ctsio->residual = alloc_len - data_len;
10639		ctsio->kern_data_len = data_len;
10640		ctsio->kern_total_len = data_len;
10641	} else {
10642		ctsio->residual = 0;
10643		ctsio->kern_data_len = alloc_len;
10644		ctsio->kern_total_len = alloc_len;
10645	}
10646
10647	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10648	hdr->state1 = 0x00;
10649	hdr->state2 = 0xe0;
10650	scsi_ulto3b(0, hdr->lba);
10651	hdr->slots_num = 0;
10652	scsi_ulto2b(0, hdr->slots_length);
10653
10654	ctl_set_success(ctsio);
10655	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10656	ctsio->be_move_done = ctl_config_move_done;
10657	ctl_datamove((union ctl_io *)ctsio);
10658	return (CTL_RETVAL_COMPLETE);
10659}
10660
10661static void
10662ctl_ultomsf(uint32_t lba, uint8_t *buf)
10663{
10664
10665	lba += 150;
10666	buf[0] = 0;
10667	buf[1] = bin2bcd((lba / 75) / 60);
10668	buf[2] = bin2bcd((lba / 75) % 60);
10669	buf[3] = bin2bcd(lba % 75);
10670}
10671
10672int
10673ctl_read_toc(struct ctl_scsiio *ctsio)
10674{
10675	struct scsi_read_toc_hdr *hdr;
10676	struct scsi_read_toc_type01_descr *descr;
10677	struct scsi_read_toc *cdb;
10678	struct ctl_lun *lun;
10679	uint32_t alloc_len, data_len;
10680	int format, msf;
10681
10682	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10683	cdb = (struct scsi_read_toc *)ctsio->cdb;
10684	msf = (cdb->byte2 & CD_MSF) != 0;
10685	format = cdb->format;
10686	alloc_len = scsi_2btoul(cdb->data_len);
10687
10688	data_len = sizeof(struct scsi_read_toc_hdr);
10689	if (format == 0)
10690		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10691	else
10692		data_len += sizeof(struct scsi_read_toc_type01_descr);
10693	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10694	ctsio->kern_sg_entries = 0;
10695	ctsio->kern_data_resid = 0;
10696	ctsio->kern_rel_offset = 0;
10697
10698	if (data_len < alloc_len) {
10699		ctsio->residual = alloc_len - data_len;
10700		ctsio->kern_data_len = data_len;
10701		ctsio->kern_total_len = data_len;
10702	} else {
10703		ctsio->residual = 0;
10704		ctsio->kern_data_len = alloc_len;
10705		ctsio->kern_total_len = alloc_len;
10706	}
10707
10708	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10709	if (format == 0) {
10710		scsi_ulto2b(0x12, hdr->data_length);
10711		hdr->first = 1;
10712		hdr->last = 1;
10713		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10714		descr->addr_ctl = 0x14;
10715		descr->track_number = 1;
10716		if (msf)
10717			ctl_ultomsf(0, descr->track_start);
10718		else
10719			scsi_ulto4b(0, descr->track_start);
10720		descr++;
10721		descr->addr_ctl = 0x14;
10722		descr->track_number = 0xaa;
10723		if (msf)
10724			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10725		else
10726			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10727	} else {
10728		scsi_ulto2b(0x0a, hdr->data_length);
10729		hdr->first = 1;
10730		hdr->last = 1;
10731		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10732		descr->addr_ctl = 0x14;
10733		descr->track_number = 1;
10734		if (msf)
10735			ctl_ultomsf(0, descr->track_start);
10736		else
10737			scsi_ulto4b(0, descr->track_start);
10738	}
10739
10740	ctl_set_success(ctsio);
10741	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10742	ctsio->be_move_done = ctl_config_move_done;
10743	ctl_datamove((union ctl_io *)ctsio);
10744	return (CTL_RETVAL_COMPLETE);
10745}
10746
10747/*
10748 * For known CDB types, parse the LBA and length.
10749 */
10750static int
10751ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10752{
10753	if (io->io_hdr.io_type != CTL_IO_SCSI)
10754		return (1);
10755
10756	switch (io->scsiio.cdb[0]) {
10757	case COMPARE_AND_WRITE: {
10758		struct scsi_compare_and_write *cdb;
10759
10760		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10761
10762		*lba = scsi_8btou64(cdb->addr);
10763		*len = cdb->length;
10764		break;
10765	}
10766	case READ_6:
10767	case WRITE_6: {
10768		struct scsi_rw_6 *cdb;
10769
10770		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10771
10772		*lba = scsi_3btoul(cdb->addr);
10773		/* only 5 bits are valid in the most significant address byte */
10774		*lba &= 0x1fffff;
10775		*len = cdb->length;
10776		break;
10777	}
10778	case READ_10:
10779	case WRITE_10: {
10780		struct scsi_rw_10 *cdb;
10781
10782		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10783
10784		*lba = scsi_4btoul(cdb->addr);
10785		*len = scsi_2btoul(cdb->length);
10786		break;
10787	}
10788	case WRITE_VERIFY_10: {
10789		struct scsi_write_verify_10 *cdb;
10790
10791		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10792
10793		*lba = scsi_4btoul(cdb->addr);
10794		*len = scsi_2btoul(cdb->length);
10795		break;
10796	}
10797	case READ_12:
10798	case WRITE_12: {
10799		struct scsi_rw_12 *cdb;
10800
10801		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10802
10803		*lba = scsi_4btoul(cdb->addr);
10804		*len = scsi_4btoul(cdb->length);
10805		break;
10806	}
10807	case WRITE_VERIFY_12: {
10808		struct scsi_write_verify_12 *cdb;
10809
10810		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10811
10812		*lba = scsi_4btoul(cdb->addr);
10813		*len = scsi_4btoul(cdb->length);
10814		break;
10815	}
10816	case READ_16:
10817	case WRITE_16: {
10818		struct scsi_rw_16 *cdb;
10819
10820		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10821
10822		*lba = scsi_8btou64(cdb->addr);
10823		*len = scsi_4btoul(cdb->length);
10824		break;
10825	}
10826	case WRITE_ATOMIC_16: {
10827		struct scsi_write_atomic_16 *cdb;
10828
10829		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10830
10831		*lba = scsi_8btou64(cdb->addr);
10832		*len = scsi_2btoul(cdb->length);
10833		break;
10834	}
10835	case WRITE_VERIFY_16: {
10836		struct scsi_write_verify_16 *cdb;
10837
10838		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10839
10840		*lba = scsi_8btou64(cdb->addr);
10841		*len = scsi_4btoul(cdb->length);
10842		break;
10843	}
10844	case WRITE_SAME_10: {
10845		struct scsi_write_same_10 *cdb;
10846
10847		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10848
10849		*lba = scsi_4btoul(cdb->addr);
10850		*len = scsi_2btoul(cdb->length);
10851		break;
10852	}
10853	case WRITE_SAME_16: {
10854		struct scsi_write_same_16 *cdb;
10855
10856		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10857
10858		*lba = scsi_8btou64(cdb->addr);
10859		*len = scsi_4btoul(cdb->length);
10860		break;
10861	}
10862	case VERIFY_10: {
10863		struct scsi_verify_10 *cdb;
10864
10865		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10866
10867		*lba = scsi_4btoul(cdb->addr);
10868		*len = scsi_2btoul(cdb->length);
10869		break;
10870	}
10871	case VERIFY_12: {
10872		struct scsi_verify_12 *cdb;
10873
10874		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10875
10876		*lba = scsi_4btoul(cdb->addr);
10877		*len = scsi_4btoul(cdb->length);
10878		break;
10879	}
10880	case VERIFY_16: {
10881		struct scsi_verify_16 *cdb;
10882
10883		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10884
10885		*lba = scsi_8btou64(cdb->addr);
10886		*len = scsi_4btoul(cdb->length);
10887		break;
10888	}
10889	case UNMAP: {
10890		*lba = 0;
10891		*len = UINT64_MAX;
10892		break;
10893	}
10894	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10895		struct scsi_get_lba_status *cdb;
10896
10897		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10898		*lba = scsi_8btou64(cdb->addr);
10899		*len = UINT32_MAX;
10900		break;
10901	}
10902	default:
10903		return (1);
10904		break; /* NOTREACHED */
10905	}
10906
10907	return (0);
10908}
10909
10910static ctl_action
10911ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10912    bool seq)
10913{
10914	uint64_t endlba1, endlba2;
10915
10916	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10917	endlba2 = lba2 + len2 - 1;
10918
10919	if ((endlba1 < lba2) || (endlba2 < lba1))
10920		return (CTL_ACTION_PASS);
10921	else
10922		return (CTL_ACTION_BLOCK);
10923}
10924
10925static int
10926ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10927{
10928	struct ctl_ptr_len_flags *ptrlen;
10929	struct scsi_unmap_desc *buf, *end, *range;
10930	uint64_t lba;
10931	uint32_t len;
10932
10933	/* If not UNMAP -- go other way. */
10934	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10935	    io->scsiio.cdb[0] != UNMAP)
10936		return (CTL_ACTION_ERROR);
10937
10938	/* If UNMAP without data -- block and wait for data. */
10939	ptrlen = (struct ctl_ptr_len_flags *)
10940	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10941	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10942	    ptrlen->ptr == NULL)
10943		return (CTL_ACTION_BLOCK);
10944
10945	/* UNMAP with data -- check for collision. */
10946	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10947	end = buf + ptrlen->len / sizeof(*buf);
10948	for (range = buf; range < end; range++) {
10949		lba = scsi_8btou64(range->lba);
10950		len = scsi_4btoul(range->length);
10951		if ((lba < lba2 + len2) && (lba + len > lba2))
10952			return (CTL_ACTION_BLOCK);
10953	}
10954	return (CTL_ACTION_PASS);
10955}
10956
10957static ctl_action
10958ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10959{
10960	uint64_t lba1, lba2;
10961	uint64_t len1, len2;
10962	int retval;
10963
10964	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10965		return (CTL_ACTION_ERROR);
10966
10967	retval = ctl_extent_check_unmap(io1, lba2, len2);
10968	if (retval != CTL_ACTION_ERROR)
10969		return (retval);
10970
10971	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10972		return (CTL_ACTION_ERROR);
10973
10974	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10975		seq = FALSE;
10976	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10977}
10978
10979static ctl_action
10980ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10981{
10982	uint64_t lba1, lba2;
10983	uint64_t len1, len2;
10984
10985	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10986		return (CTL_ACTION_PASS);
10987	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10988		return (CTL_ACTION_ERROR);
10989	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10990		return (CTL_ACTION_ERROR);
10991
10992	if (lba1 + len1 == lba2)
10993		return (CTL_ACTION_BLOCK);
10994	return (CTL_ACTION_PASS);
10995}
10996
10997static ctl_action
10998ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10999    union ctl_io *ooa_io)
11000{
11001	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11002	const ctl_serialize_action *serialize_row;
11003
11004	/*
11005	 * The initiator attempted multiple untagged commands at the same
11006	 * time.  Can't do that.
11007	 */
11008	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11009	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11010	 && ((pending_io->io_hdr.nexus.targ_port ==
11011	      ooa_io->io_hdr.nexus.targ_port)
11012	  && (pending_io->io_hdr.nexus.initid ==
11013	      ooa_io->io_hdr.nexus.initid))
11014	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11015	      CTL_FLAG_STATUS_SENT)) == 0))
11016		return (CTL_ACTION_OVERLAP);
11017
11018	/*
11019	 * The initiator attempted to send multiple tagged commands with
11020	 * the same ID.  (It's fine if different initiators have the same
11021	 * tag ID.)
11022	 *
11023	 * Even if all of those conditions are true, we don't kill the I/O
11024	 * if the command ahead of us has been aborted.  We won't end up
11025	 * sending it to the FETD, and it's perfectly legal to resend a
11026	 * command with the same tag number as long as the previous
11027	 * instance of this tag number has been aborted somehow.
11028	 */
11029	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11030	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11031	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11032	 && ((pending_io->io_hdr.nexus.targ_port ==
11033	      ooa_io->io_hdr.nexus.targ_port)
11034	  && (pending_io->io_hdr.nexus.initid ==
11035	      ooa_io->io_hdr.nexus.initid))
11036	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11037	      CTL_FLAG_STATUS_SENT)) == 0))
11038		return (CTL_ACTION_OVERLAP_TAG);
11039
11040	/*
11041	 * If we get a head of queue tag, SAM-3 says that we should
11042	 * immediately execute it.
11043	 *
11044	 * What happens if this command would normally block for some other
11045	 * reason?  e.g. a request sense with a head of queue tag
11046	 * immediately after a write.  Normally that would block, but this
11047	 * will result in its getting executed immediately...
11048	 *
11049	 * We currently return "pass" instead of "skip", so we'll end up
11050	 * going through the rest of the queue to check for overlapped tags.
11051	 *
11052	 * XXX KDM check for other types of blockage first??
11053	 */
11054	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11055		return (CTL_ACTION_PASS);
11056
11057	/*
11058	 * Ordered tags have to block until all items ahead of them
11059	 * have completed.  If we get called with an ordered tag, we always
11060	 * block, if something else is ahead of us in the queue.
11061	 */
11062	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11063		return (CTL_ACTION_BLOCK);
11064
11065	/*
11066	 * Simple tags get blocked until all head of queue and ordered tags
11067	 * ahead of them have completed.  I'm lumping untagged commands in
11068	 * with simple tags here.  XXX KDM is that the right thing to do?
11069	 */
11070	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11071	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11072	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11073	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11074		return (CTL_ACTION_BLOCK);
11075
11076	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11077	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11078	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11079	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11080	     pending_io->scsiio.cdb[1], pending_io));
11081	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11082	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11083		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11084	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11085	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11086	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11087	     ooa_io->scsiio.cdb[1], ooa_io));
11088
11089	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11090
11091	switch (serialize_row[pending_entry->seridx]) {
11092	case CTL_SER_BLOCK:
11093		return (CTL_ACTION_BLOCK);
11094	case CTL_SER_EXTENT:
11095		return (ctl_extent_check(ooa_io, pending_io,
11096		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11097	case CTL_SER_EXTENTOPT:
11098		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11099		    SCP_QUEUE_ALG_UNRESTRICTED)
11100			return (ctl_extent_check(ooa_io, pending_io,
11101			    (lun->be_lun &&
11102			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11103		return (CTL_ACTION_PASS);
11104	case CTL_SER_EXTENTSEQ:
11105		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11106			return (ctl_extent_check_seq(ooa_io, pending_io));
11107		return (CTL_ACTION_PASS);
11108	case CTL_SER_PASS:
11109		return (CTL_ACTION_PASS);
11110	case CTL_SER_BLOCKOPT:
11111		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11112		    SCP_QUEUE_ALG_UNRESTRICTED)
11113			return (CTL_ACTION_BLOCK);
11114		return (CTL_ACTION_PASS);
11115	case CTL_SER_SKIP:
11116		return (CTL_ACTION_SKIP);
11117	default:
11118		panic("%s: Invalid serialization value %d for %d => %d",
11119		    __func__, serialize_row[pending_entry->seridx],
11120		    pending_entry->seridx, ooa_entry->seridx);
11121	}
11122
11123	return (CTL_ACTION_ERROR);
11124}
11125
11126/*
11127 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11128 * Assumptions:
11129 * - pending_io is generally either incoming, or on the blocked queue
11130 * - starting I/O is the I/O we want to start the check with.
11131 */
11132static ctl_action
11133ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11134	      union ctl_io *starting_io)
11135{
11136	union ctl_io *ooa_io;
11137	ctl_action action;
11138
11139	mtx_assert(&lun->lun_lock, MA_OWNED);
11140
11141	/*
11142	 * Run back along the OOA queue, starting with the current
11143	 * blocked I/O and going through every I/O before it on the
11144	 * queue.  If starting_io is NULL, we'll just end up returning
11145	 * CTL_ACTION_PASS.
11146	 */
11147	for (ooa_io = starting_io; ooa_io != NULL;
11148	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11149	     ooa_links)){
11150
11151		/*
11152		 * This routine just checks to see whether
11153		 * cur_blocked is blocked by ooa_io, which is ahead
11154		 * of it in the queue.  It doesn't queue/dequeue
11155		 * cur_blocked.
11156		 */
11157		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11158		switch (action) {
11159		case CTL_ACTION_BLOCK:
11160		case CTL_ACTION_OVERLAP:
11161		case CTL_ACTION_OVERLAP_TAG:
11162		case CTL_ACTION_SKIP:
11163		case CTL_ACTION_ERROR:
11164			return (action);
11165			break; /* NOTREACHED */
11166		case CTL_ACTION_PASS:
11167			break;
11168		default:
11169			panic("%s: Invalid action %d\n", __func__, action);
11170		}
11171	}
11172
11173	return (CTL_ACTION_PASS);
11174}
11175
11176/*
11177 * Assumptions:
11178 * - An I/O has just completed, and has been removed from the per-LUN OOA
11179 *   queue, so some items on the blocked queue may now be unblocked.
11180 */
11181static int
11182ctl_check_blocked(struct ctl_lun *lun)
11183{
11184	struct ctl_softc *softc = lun->ctl_softc;
11185	union ctl_io *cur_blocked, *next_blocked;
11186
11187	mtx_assert(&lun->lun_lock, MA_OWNED);
11188
11189	/*
11190	 * Run forward from the head of the blocked queue, checking each
11191	 * entry against the I/Os prior to it on the OOA queue to see if
11192	 * there is still any blockage.
11193	 *
11194	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11195	 * with our removing a variable on it while it is traversing the
11196	 * list.
11197	 */
11198	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11199	     cur_blocked != NULL; cur_blocked = next_blocked) {
11200		union ctl_io *prev_ooa;
11201		ctl_action action;
11202
11203		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11204							  blocked_links);
11205
11206		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11207						      ctl_ooaq, ooa_links);
11208
11209		/*
11210		 * If cur_blocked happens to be the first item in the OOA
11211		 * queue now, prev_ooa will be NULL, and the action
11212		 * returned will just be CTL_ACTION_PASS.
11213		 */
11214		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11215
11216		switch (action) {
11217		case CTL_ACTION_BLOCK:
11218			/* Nothing to do here, still blocked */
11219			break;
11220		case CTL_ACTION_OVERLAP:
11221		case CTL_ACTION_OVERLAP_TAG:
11222			/*
11223			 * This shouldn't happen!  In theory we've already
11224			 * checked this command for overlap...
11225			 */
11226			break;
11227		case CTL_ACTION_PASS:
11228		case CTL_ACTION_SKIP: {
11229			const struct ctl_cmd_entry *entry;
11230
11231			/*
11232			 * The skip case shouldn't happen, this transaction
11233			 * should have never made it onto the blocked queue.
11234			 */
11235			/*
11236			 * This I/O is no longer blocked, we can remove it
11237			 * from the blocked queue.  Since this is a TAILQ
11238			 * (doubly linked list), we can do O(1) removals
11239			 * from any place on the list.
11240			 */
11241			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11242				     blocked_links);
11243			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11244
11245			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11246			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11247				/*
11248				 * Need to send IO back to original side to
11249				 * run
11250				 */
11251				union ctl_ha_msg msg_info;
11252
11253				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11254				msg_info.hdr.original_sc =
11255					cur_blocked->io_hdr.original_sc;
11256				msg_info.hdr.serializing_sc = cur_blocked;
11257				msg_info.hdr.msg_type = CTL_MSG_R2R;
11258				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11259				    sizeof(msg_info.hdr), M_NOWAIT);
11260				break;
11261			}
11262			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11263
11264			/*
11265			 * Check this I/O for LUN state changes that may
11266			 * have happened while this command was blocked.
11267			 * The LUN state may have been changed by a command
11268			 * ahead of us in the queue, so we need to re-check
11269			 * for any states that can be caused by SCSI
11270			 * commands.
11271			 */
11272			if (ctl_scsiio_lun_check(lun, entry,
11273						 &cur_blocked->scsiio) == 0) {
11274				cur_blocked->io_hdr.flags |=
11275				                      CTL_FLAG_IS_WAS_ON_RTR;
11276				ctl_enqueue_rtr(cur_blocked);
11277			} else
11278				ctl_done(cur_blocked);
11279			break;
11280		}
11281		default:
11282			/*
11283			 * This probably shouldn't happen -- we shouldn't
11284			 * get CTL_ACTION_ERROR, or anything else.
11285			 */
11286			break;
11287		}
11288	}
11289
11290	return (CTL_RETVAL_COMPLETE);
11291}
11292
11293/*
11294 * This routine (with one exception) checks LUN flags that can be set by
11295 * commands ahead of us in the OOA queue.  These flags have to be checked
11296 * when a command initially comes in, and when we pull a command off the
11297 * blocked queue and are preparing to execute it.  The reason we have to
11298 * check these flags for commands on the blocked queue is that the LUN
11299 * state may have been changed by a command ahead of us while we're on the
11300 * blocked queue.
11301 *
11302 * Ordering is somewhat important with these checks, so please pay
11303 * careful attention to the placement of any new checks.
11304 */
11305static int
11306ctl_scsiio_lun_check(struct ctl_lun *lun,
11307    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11308{
11309	struct ctl_softc *softc = lun->ctl_softc;
11310	int retval;
11311	uint32_t residx;
11312
11313	retval = 0;
11314
11315	mtx_assert(&lun->lun_lock, MA_OWNED);
11316
11317	/*
11318	 * If this shelf is a secondary shelf controller, we may have to
11319	 * reject some commands disallowed by HA mode and link state.
11320	 */
11321	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11322		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11323		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11324			ctl_set_lun_unavail(ctsio);
11325			retval = 1;
11326			goto bailout;
11327		}
11328		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11329		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11330			ctl_set_lun_transit(ctsio);
11331			retval = 1;
11332			goto bailout;
11333		}
11334		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11335		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11336			ctl_set_lun_standby(ctsio);
11337			retval = 1;
11338			goto bailout;
11339		}
11340
11341		/* The rest of checks are only done on executing side */
11342		if (softc->ha_mode == CTL_HA_MODE_XFER)
11343			goto bailout;
11344	}
11345
11346	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11347		if (lun->be_lun &&
11348		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11349			ctl_set_hw_write_protected(ctsio);
11350			retval = 1;
11351			goto bailout;
11352		}
11353		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11354			ctl_set_sense(ctsio, /*current_error*/ 1,
11355			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11356			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11357			retval = 1;
11358			goto bailout;
11359		}
11360	}
11361
11362	/*
11363	 * Check for a reservation conflict.  If this command isn't allowed
11364	 * even on reserved LUNs, and if this initiator isn't the one who
11365	 * reserved us, reject the command with a reservation conflict.
11366	 */
11367	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11368	if ((lun->flags & CTL_LUN_RESERVED)
11369	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11370		if (lun->res_idx != residx) {
11371			ctl_set_reservation_conflict(ctsio);
11372			retval = 1;
11373			goto bailout;
11374		}
11375	}
11376
11377	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11378	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11379		/* No reservation or command is allowed. */;
11380	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11381	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11382	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11383	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11384		/* The command is allowed for Write Exclusive resv. */;
11385	} else {
11386		/*
11387		 * if we aren't registered or it's a res holder type
11388		 * reservation and this isn't the res holder then set a
11389		 * conflict.
11390		 */
11391		if (ctl_get_prkey(lun, residx) == 0 ||
11392		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11393			ctl_set_reservation_conflict(ctsio);
11394			retval = 1;
11395			goto bailout;
11396		}
11397	}
11398
11399	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11400		if (lun->flags & CTL_LUN_EJECTED)
11401			ctl_set_lun_ejected(ctsio);
11402		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11403			if (lun->flags & CTL_LUN_REMOVABLE)
11404				ctl_set_lun_no_media(ctsio);
11405			else
11406				ctl_set_lun_int_reqd(ctsio);
11407		} else if (lun->flags & CTL_LUN_STOPPED)
11408			ctl_set_lun_stopped(ctsio);
11409		else
11410			goto bailout;
11411		retval = 1;
11412		goto bailout;
11413	}
11414
11415bailout:
11416	return (retval);
11417}
11418
11419static void
11420ctl_failover_io(union ctl_io *io, int have_lock)
11421{
11422	ctl_set_busy(&io->scsiio);
11423	ctl_done(io);
11424}
11425
11426static void
11427ctl_failover_lun(union ctl_io *rio)
11428{
11429	struct ctl_softc *softc = control_softc;
11430	struct ctl_lun *lun;
11431	struct ctl_io_hdr *io, *next_io;
11432	uint32_t targ_lun;
11433
11434	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11435	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11436
11437	/* Find and lock the LUN. */
11438	mtx_lock(&softc->ctl_lock);
11439	if ((targ_lun < CTL_MAX_LUNS) &&
11440	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11441		mtx_lock(&lun->lun_lock);
11442		mtx_unlock(&softc->ctl_lock);
11443		if (lun->flags & CTL_LUN_DISABLED) {
11444			mtx_unlock(&lun->lun_lock);
11445			return;
11446		}
11447	} else {
11448		mtx_unlock(&softc->ctl_lock);
11449		return;
11450	}
11451
11452	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11453		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11454			/* We are master */
11455			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11456				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11457					io->flags |= CTL_FLAG_ABORT;
11458					io->flags |= CTL_FLAG_FAILOVER;
11459				} else { /* This can be only due to DATAMOVE */
11460					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11461					io->flags &= ~CTL_FLAG_DMA_INPROG;
11462					io->flags |= CTL_FLAG_IO_ACTIVE;
11463					io->port_status = 31340;
11464					ctl_enqueue_isc((union ctl_io *)io);
11465				}
11466			}
11467			/* We are slave */
11468			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11469				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11470				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11471					io->flags |= CTL_FLAG_FAILOVER;
11472				} else {
11473					ctl_set_busy(&((union ctl_io *)io)->
11474					    scsiio);
11475					ctl_done((union ctl_io *)io);
11476				}
11477			}
11478		}
11479	} else { /* SERIALIZE modes */
11480		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11481		    next_io) {
11482			/* We are master */
11483			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11484				TAILQ_REMOVE(&lun->blocked_queue, io,
11485				    blocked_links);
11486				io->flags &= ~CTL_FLAG_BLOCKED;
11487				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11488				ctl_free_io((union ctl_io *)io);
11489			}
11490		}
11491		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11492			/* We are master */
11493			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11494				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11495				ctl_free_io((union ctl_io *)io);
11496			}
11497			/* We are slave */
11498			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11499				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11500				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11501					ctl_set_busy(&((union ctl_io *)io)->
11502					    scsiio);
11503					ctl_done((union ctl_io *)io);
11504				}
11505			}
11506		}
11507		ctl_check_blocked(lun);
11508	}
11509	mtx_unlock(&lun->lun_lock);
11510}
11511
11512static int
11513ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11514{
11515	struct ctl_lun *lun;
11516	const struct ctl_cmd_entry *entry;
11517	uint32_t initidx, targ_lun;
11518	int retval;
11519
11520	retval = 0;
11521
11522	lun = NULL;
11523
11524	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11525	if ((targ_lun < CTL_MAX_LUNS)
11526	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11527		/*
11528		 * If the LUN is invalid, pretend that it doesn't exist.
11529		 * It will go away as soon as all pending I/O has been
11530		 * completed.
11531		 */
11532		mtx_lock(&lun->lun_lock);
11533		if (lun->flags & CTL_LUN_DISABLED) {
11534			mtx_unlock(&lun->lun_lock);
11535			lun = NULL;
11536			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11537			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11538		} else {
11539			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11540			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11541				lun->be_lun;
11542
11543			/*
11544			 * Every I/O goes into the OOA queue for a
11545			 * particular LUN, and stays there until completion.
11546			 */
11547#ifdef CTL_TIME_IO
11548			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11549				lun->idle_time += getsbinuptime() -
11550				    lun->last_busy;
11551			}
11552#endif
11553			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11554			    ooa_links);
11555		}
11556	} else {
11557		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11558		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11559	}
11560
11561	/* Get command entry and return error if it is unsuppotyed. */
11562	entry = ctl_validate_command(ctsio);
11563	if (entry == NULL) {
11564		if (lun)
11565			mtx_unlock(&lun->lun_lock);
11566		return (retval);
11567	}
11568
11569	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11570	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11571
11572	/*
11573	 * Check to see whether we can send this command to LUNs that don't
11574	 * exist.  This should pretty much only be the case for inquiry
11575	 * and request sense.  Further checks, below, really require having
11576	 * a LUN, so we can't really check the command anymore.  Just put
11577	 * it on the rtr queue.
11578	 */
11579	if (lun == NULL) {
11580		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11581			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11582			ctl_enqueue_rtr((union ctl_io *)ctsio);
11583			return (retval);
11584		}
11585
11586		ctl_set_unsupported_lun(ctsio);
11587		ctl_done((union ctl_io *)ctsio);
11588		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11589		return (retval);
11590	} else {
11591		/*
11592		 * Make sure we support this particular command on this LUN.
11593		 * e.g., we don't support writes to the control LUN.
11594		 */
11595		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11596			mtx_unlock(&lun->lun_lock);
11597			ctl_set_invalid_opcode(ctsio);
11598			ctl_done((union ctl_io *)ctsio);
11599			return (retval);
11600		}
11601	}
11602
11603	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11604
11605#ifdef CTL_WITH_CA
11606	/*
11607	 * If we've got a request sense, it'll clear the contingent
11608	 * allegiance condition.  Otherwise, if we have a CA condition for
11609	 * this initiator, clear it, because it sent down a command other
11610	 * than request sense.
11611	 */
11612	if ((ctsio->cdb[0] != REQUEST_SENSE)
11613	 && (ctl_is_set(lun->have_ca, initidx)))
11614		ctl_clear_mask(lun->have_ca, initidx);
11615#endif
11616
11617	/*
11618	 * If the command has this flag set, it handles its own unit
11619	 * attention reporting, we shouldn't do anything.  Otherwise we
11620	 * check for any pending unit attentions, and send them back to the
11621	 * initiator.  We only do this when a command initially comes in,
11622	 * not when we pull it off the blocked queue.
11623	 *
11624	 * According to SAM-3, section 5.3.2, the order that things get
11625	 * presented back to the host is basically unit attentions caused
11626	 * by some sort of reset event, busy status, reservation conflicts
11627	 * or task set full, and finally any other status.
11628	 *
11629	 * One issue here is that some of the unit attentions we report
11630	 * don't fall into the "reset" category (e.g. "reported luns data
11631	 * has changed").  So reporting it here, before the reservation
11632	 * check, may be technically wrong.  I guess the only thing to do
11633	 * would be to check for and report the reset events here, and then
11634	 * check for the other unit attention types after we check for a
11635	 * reservation conflict.
11636	 *
11637	 * XXX KDM need to fix this
11638	 */
11639	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11640		ctl_ua_type ua_type;
11641		u_int sense_len = 0;
11642
11643		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11644		    &sense_len, SSD_TYPE_NONE);
11645		if (ua_type != CTL_UA_NONE) {
11646			mtx_unlock(&lun->lun_lock);
11647			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11648			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11649			ctsio->sense_len = sense_len;
11650			ctl_done((union ctl_io *)ctsio);
11651			return (retval);
11652		}
11653	}
11654
11655
11656	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11657		mtx_unlock(&lun->lun_lock);
11658		ctl_done((union ctl_io *)ctsio);
11659		return (retval);
11660	}
11661
11662	/*
11663	 * XXX CHD this is where we want to send IO to other side if
11664	 * this LUN is secondary on this SC. We will need to make a copy
11665	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11666	 * the copy we send as FROM_OTHER.
11667	 * We also need to stuff the address of the original IO so we can
11668	 * find it easily. Something similar will need be done on the other
11669	 * side so when we are done we can find the copy.
11670	 */
11671	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11672	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11673	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11674		union ctl_ha_msg msg_info;
11675		int isc_retval;
11676
11677		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11678		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11679		mtx_unlock(&lun->lun_lock);
11680
11681		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11682		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11683		msg_info.hdr.serializing_sc = NULL;
11684		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11685		msg_info.scsi.tag_num = ctsio->tag_num;
11686		msg_info.scsi.tag_type = ctsio->tag_type;
11687		msg_info.scsi.cdb_len = ctsio->cdb_len;
11688		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11689
11690		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11691		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11692		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11693			ctl_set_busy(ctsio);
11694			ctl_done((union ctl_io *)ctsio);
11695			return (retval);
11696		}
11697		return (retval);
11698	}
11699
11700	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11701			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11702			      ctl_ooaq, ooa_links))) {
11703	case CTL_ACTION_BLOCK:
11704		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11705		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11706				  blocked_links);
11707		mtx_unlock(&lun->lun_lock);
11708		return (retval);
11709	case CTL_ACTION_PASS:
11710	case CTL_ACTION_SKIP:
11711		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11712		mtx_unlock(&lun->lun_lock);
11713		ctl_enqueue_rtr((union ctl_io *)ctsio);
11714		break;
11715	case CTL_ACTION_OVERLAP:
11716		mtx_unlock(&lun->lun_lock);
11717		ctl_set_overlapped_cmd(ctsio);
11718		ctl_done((union ctl_io *)ctsio);
11719		break;
11720	case CTL_ACTION_OVERLAP_TAG:
11721		mtx_unlock(&lun->lun_lock);
11722		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11723		ctl_done((union ctl_io *)ctsio);
11724		break;
11725	case CTL_ACTION_ERROR:
11726	default:
11727		mtx_unlock(&lun->lun_lock);
11728		ctl_set_internal_failure(ctsio,
11729					 /*sks_valid*/ 0,
11730					 /*retry_count*/ 0);
11731		ctl_done((union ctl_io *)ctsio);
11732		break;
11733	}
11734	return (retval);
11735}
11736
11737const struct ctl_cmd_entry *
11738ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11739{
11740	const struct ctl_cmd_entry *entry;
11741	int service_action;
11742
11743	entry = &ctl_cmd_table[ctsio->cdb[0]];
11744	if (sa)
11745		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11746	if (entry->flags & CTL_CMD_FLAG_SA5) {
11747		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11748		entry = &((const struct ctl_cmd_entry *)
11749		    entry->execute)[service_action];
11750	}
11751	return (entry);
11752}
11753
11754const struct ctl_cmd_entry *
11755ctl_validate_command(struct ctl_scsiio *ctsio)
11756{
11757	const struct ctl_cmd_entry *entry;
11758	int i, sa;
11759	uint8_t diff;
11760
11761	entry = ctl_get_cmd_entry(ctsio, &sa);
11762	if (entry->execute == NULL) {
11763		if (sa)
11764			ctl_set_invalid_field(ctsio,
11765					      /*sks_valid*/ 1,
11766					      /*command*/ 1,
11767					      /*field*/ 1,
11768					      /*bit_valid*/ 1,
11769					      /*bit*/ 4);
11770		else
11771			ctl_set_invalid_opcode(ctsio);
11772		ctl_done((union ctl_io *)ctsio);
11773		return (NULL);
11774	}
11775	KASSERT(entry->length > 0,
11776	    ("Not defined length for command 0x%02x/0x%02x",
11777	     ctsio->cdb[0], ctsio->cdb[1]));
11778	for (i = 1; i < entry->length; i++) {
11779		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11780		if (diff == 0)
11781			continue;
11782		ctl_set_invalid_field(ctsio,
11783				      /*sks_valid*/ 1,
11784				      /*command*/ 1,
11785				      /*field*/ i,
11786				      /*bit_valid*/ 1,
11787				      /*bit*/ fls(diff) - 1);
11788		ctl_done((union ctl_io *)ctsio);
11789		return (NULL);
11790	}
11791	return (entry);
11792}
11793
11794static int
11795ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11796{
11797
11798	switch (lun_type) {
11799	case T_DIRECT:
11800		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11801			return (0);
11802		break;
11803	case T_PROCESSOR:
11804		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11805			return (0);
11806		break;
11807	case T_CDROM:
11808		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11809			return (0);
11810		break;
11811	default:
11812		return (0);
11813	}
11814	return (1);
11815}
11816
11817static int
11818ctl_scsiio(struct ctl_scsiio *ctsio)
11819{
11820	int retval;
11821	const struct ctl_cmd_entry *entry;
11822
11823	retval = CTL_RETVAL_COMPLETE;
11824
11825	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11826
11827	entry = ctl_get_cmd_entry(ctsio, NULL);
11828
11829	/*
11830	 * If this I/O has been aborted, just send it straight to
11831	 * ctl_done() without executing it.
11832	 */
11833	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11834		ctl_done((union ctl_io *)ctsio);
11835		goto bailout;
11836	}
11837
11838	/*
11839	 * All the checks should have been handled by ctl_scsiio_precheck().
11840	 * We should be clear now to just execute the I/O.
11841	 */
11842	retval = entry->execute(ctsio);
11843
11844bailout:
11845	return (retval);
11846}
11847
11848/*
11849 * Since we only implement one target right now, a bus reset simply resets
11850 * our single target.
11851 */
11852static int
11853ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11854{
11855	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11856}
11857
11858static int
11859ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11860		 ctl_ua_type ua_type)
11861{
11862	struct ctl_port *port;
11863	struct ctl_lun *lun;
11864	int retval;
11865
11866	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11867		union ctl_ha_msg msg_info;
11868
11869		msg_info.hdr.nexus = io->io_hdr.nexus;
11870		if (ua_type==CTL_UA_TARG_RESET)
11871			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11872		else
11873			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11874		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11875		msg_info.hdr.original_sc = NULL;
11876		msg_info.hdr.serializing_sc = NULL;
11877		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11878		    sizeof(msg_info.task), M_WAITOK);
11879	}
11880	retval = 0;
11881
11882	mtx_lock(&softc->ctl_lock);
11883	port = ctl_io_port(&io->io_hdr);
11884	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11885		if (port != NULL &&
11886		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11887			continue;
11888		retval += ctl_do_lun_reset(lun, io, ua_type);
11889	}
11890	mtx_unlock(&softc->ctl_lock);
11891	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11892	return (retval);
11893}
11894
11895/*
11896 * The LUN should always be set.  The I/O is optional, and is used to
11897 * distinguish between I/Os sent by this initiator, and by other
11898 * initiators.  We set unit attention for initiators other than this one.
11899 * SAM-3 is vague on this point.  It does say that a unit attention should
11900 * be established for other initiators when a LUN is reset (see section
11901 * 5.7.3), but it doesn't specifically say that the unit attention should
11902 * be established for this particular initiator when a LUN is reset.  Here
11903 * is the relevant text, from SAM-3 rev 8:
11904 *
11905 * 5.7.2 When a SCSI initiator port aborts its own tasks
11906 *
11907 * When a SCSI initiator port causes its own task(s) to be aborted, no
11908 * notification that the task(s) have been aborted shall be returned to
11909 * the SCSI initiator port other than the completion response for the
11910 * command or task management function action that caused the task(s) to
11911 * be aborted and notification(s) associated with related effects of the
11912 * action (e.g., a reset unit attention condition).
11913 *
11914 * XXX KDM for now, we're setting unit attention for all initiators.
11915 */
11916static int
11917ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11918{
11919	union ctl_io *xio;
11920#if 0
11921	uint32_t initidx;
11922#endif
11923	int i;
11924
11925	mtx_lock(&lun->lun_lock);
11926	/*
11927	 * Run through the OOA queue and abort each I/O.
11928	 */
11929	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11930	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11931		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11932	}
11933
11934	/*
11935	 * This version sets unit attention for every
11936	 */
11937#if 0
11938	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11939	ctl_est_ua_all(lun, initidx, ua_type);
11940#else
11941	ctl_est_ua_all(lun, -1, ua_type);
11942#endif
11943
11944	/*
11945	 * A reset (any kind, really) clears reservations established with
11946	 * RESERVE/RELEASE.  It does not clear reservations established
11947	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11948	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11949	 * reservations made with the RESERVE/RELEASE commands, because
11950	 * those commands are obsolete in SPC-3.
11951	 */
11952	lun->flags &= ~CTL_LUN_RESERVED;
11953
11954#ifdef CTL_WITH_CA
11955	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11956		ctl_clear_mask(lun->have_ca, i);
11957#endif
11958	lun->prevent_count = 0;
11959	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11960		ctl_clear_mask(lun->prevent, i);
11961	mtx_unlock(&lun->lun_lock);
11962
11963	return (0);
11964}
11965
11966static int
11967ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11968{
11969	struct ctl_lun *lun;
11970	uint32_t targ_lun;
11971	int retval;
11972
11973	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11974	mtx_lock(&softc->ctl_lock);
11975	if ((targ_lun >= CTL_MAX_LUNS) ||
11976	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11977		mtx_unlock(&softc->ctl_lock);
11978		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11979		return (1);
11980	}
11981	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11982	mtx_unlock(&softc->ctl_lock);
11983	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11984
11985	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11986		union ctl_ha_msg msg_info;
11987
11988		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11989		msg_info.hdr.nexus = io->io_hdr.nexus;
11990		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11991		msg_info.hdr.original_sc = NULL;
11992		msg_info.hdr.serializing_sc = NULL;
11993		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11994		    sizeof(msg_info.task), M_WAITOK);
11995	}
11996	return (retval);
11997}
11998
11999static void
12000ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12001    int other_sc)
12002{
12003	union ctl_io *xio;
12004
12005	mtx_assert(&lun->lun_lock, MA_OWNED);
12006
12007	/*
12008	 * Run through the OOA queue and attempt to find the given I/O.
12009	 * The target port, initiator ID, tag type and tag number have to
12010	 * match the values that we got from the initiator.  If we have an
12011	 * untagged command to abort, simply abort the first untagged command
12012	 * we come to.  We only allow one untagged command at a time of course.
12013	 */
12014	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12015	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12016
12017		if ((targ_port == UINT32_MAX ||
12018		     targ_port == xio->io_hdr.nexus.targ_port) &&
12019		    (init_id == UINT32_MAX ||
12020		     init_id == xio->io_hdr.nexus.initid)) {
12021			if (targ_port != xio->io_hdr.nexus.targ_port ||
12022			    init_id != xio->io_hdr.nexus.initid)
12023				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12024			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12025			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12026				union ctl_ha_msg msg_info;
12027
12028				msg_info.hdr.nexus = xio->io_hdr.nexus;
12029				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12030				msg_info.task.tag_num = xio->scsiio.tag_num;
12031				msg_info.task.tag_type = xio->scsiio.tag_type;
12032				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12033				msg_info.hdr.original_sc = NULL;
12034				msg_info.hdr.serializing_sc = NULL;
12035				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12036				    sizeof(msg_info.task), M_NOWAIT);
12037			}
12038		}
12039	}
12040}
12041
12042static int
12043ctl_abort_task_set(union ctl_io *io)
12044{
12045	struct ctl_softc *softc = control_softc;
12046	struct ctl_lun *lun;
12047	uint32_t targ_lun;
12048
12049	/*
12050	 * Look up the LUN.
12051	 */
12052	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12053	mtx_lock(&softc->ctl_lock);
12054	if ((targ_lun >= CTL_MAX_LUNS) ||
12055	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12056		mtx_unlock(&softc->ctl_lock);
12057		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12058		return (1);
12059	}
12060
12061	mtx_lock(&lun->lun_lock);
12062	mtx_unlock(&softc->ctl_lock);
12063	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12064		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12065		    io->io_hdr.nexus.initid,
12066		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12067	} else { /* CTL_TASK_CLEAR_TASK_SET */
12068		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12069		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12070	}
12071	mtx_unlock(&lun->lun_lock);
12072	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12073	return (0);
12074}
12075
12076static int
12077ctl_i_t_nexus_reset(union ctl_io *io)
12078{
12079	struct ctl_softc *softc = control_softc;
12080	struct ctl_lun *lun;
12081	uint32_t initidx;
12082
12083	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12084		union ctl_ha_msg msg_info;
12085
12086		msg_info.hdr.nexus = io->io_hdr.nexus;
12087		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12088		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12089		msg_info.hdr.original_sc = NULL;
12090		msg_info.hdr.serializing_sc = NULL;
12091		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12092		    sizeof(msg_info.task), M_WAITOK);
12093	}
12094
12095	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12096	mtx_lock(&softc->ctl_lock);
12097	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12098		mtx_lock(&lun->lun_lock);
12099		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12100		    io->io_hdr.nexus.initid, 1);
12101#ifdef CTL_WITH_CA
12102		ctl_clear_mask(lun->have_ca, initidx);
12103#endif
12104		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12105			lun->flags &= ~CTL_LUN_RESERVED;
12106		if (ctl_is_set(lun->prevent, initidx)) {
12107			ctl_clear_mask(lun->prevent, initidx);
12108			lun->prevent_count--;
12109		}
12110		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12111		mtx_unlock(&lun->lun_lock);
12112	}
12113	mtx_unlock(&softc->ctl_lock);
12114	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12115	return (0);
12116}
12117
12118static int
12119ctl_abort_task(union ctl_io *io)
12120{
12121	union ctl_io *xio;
12122	struct ctl_lun *lun;
12123	struct ctl_softc *softc;
12124#if 0
12125	struct sbuf sb;
12126	char printbuf[128];
12127#endif
12128	int found;
12129	uint32_t targ_lun;
12130
12131	softc = control_softc;
12132	found = 0;
12133
12134	/*
12135	 * Look up the LUN.
12136	 */
12137	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12138	mtx_lock(&softc->ctl_lock);
12139	if ((targ_lun >= CTL_MAX_LUNS) ||
12140	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12141		mtx_unlock(&softc->ctl_lock);
12142		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12143		return (1);
12144	}
12145
12146#if 0
12147	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12148	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12149#endif
12150
12151	mtx_lock(&lun->lun_lock);
12152	mtx_unlock(&softc->ctl_lock);
12153	/*
12154	 * Run through the OOA queue and attempt to find the given I/O.
12155	 * The target port, initiator ID, tag type and tag number have to
12156	 * match the values that we got from the initiator.  If we have an
12157	 * untagged command to abort, simply abort the first untagged command
12158	 * we come to.  We only allow one untagged command at a time of course.
12159	 */
12160	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12161	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12162#if 0
12163		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12164
12165		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12166			    lun->lun, xio->scsiio.tag_num,
12167			    xio->scsiio.tag_type,
12168			    (xio->io_hdr.blocked_links.tqe_prev
12169			    == NULL) ? "" : " BLOCKED",
12170			    (xio->io_hdr.flags &
12171			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12172			    (xio->io_hdr.flags &
12173			    CTL_FLAG_ABORT) ? " ABORT" : "",
12174			    (xio->io_hdr.flags &
12175			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12176		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12177		sbuf_finish(&sb);
12178		printf("%s\n", sbuf_data(&sb));
12179#endif
12180
12181		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12182		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12183		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12184			continue;
12185
12186		/*
12187		 * If the abort says that the task is untagged, the
12188		 * task in the queue must be untagged.  Otherwise,
12189		 * we just check to see whether the tag numbers
12190		 * match.  This is because the QLogic firmware
12191		 * doesn't pass back the tag type in an abort
12192		 * request.
12193		 */
12194#if 0
12195		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12196		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12197		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12198#endif
12199		/*
12200		 * XXX KDM we've got problems with FC, because it
12201		 * doesn't send down a tag type with aborts.  So we
12202		 * can only really go by the tag number...
12203		 * This may cause problems with parallel SCSI.
12204		 * Need to figure that out!!
12205		 */
12206		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12207			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12208			found = 1;
12209			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12210			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12211				union ctl_ha_msg msg_info;
12212
12213				msg_info.hdr.nexus = io->io_hdr.nexus;
12214				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12215				msg_info.task.tag_num = io->taskio.tag_num;
12216				msg_info.task.tag_type = io->taskio.tag_type;
12217				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12218				msg_info.hdr.original_sc = NULL;
12219				msg_info.hdr.serializing_sc = NULL;
12220#if 0
12221				printf("Sent Abort to other side\n");
12222#endif
12223				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12224				    sizeof(msg_info.task), M_NOWAIT);
12225			}
12226#if 0
12227			printf("ctl_abort_task: found I/O to abort\n");
12228#endif
12229		}
12230	}
12231	mtx_unlock(&lun->lun_lock);
12232
12233	if (found == 0) {
12234		/*
12235		 * This isn't really an error.  It's entirely possible for
12236		 * the abort and command completion to cross on the wire.
12237		 * This is more of an informative/diagnostic error.
12238		 */
12239#if 0
12240		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12241		       "%u:%u:%u tag %d type %d\n",
12242		       io->io_hdr.nexus.initid,
12243		       io->io_hdr.nexus.targ_port,
12244		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12245		       io->taskio.tag_type);
12246#endif
12247	}
12248	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12249	return (0);
12250}
12251
12252static int
12253ctl_query_task(union ctl_io *io, int task_set)
12254{
12255	union ctl_io *xio;
12256	struct ctl_lun *lun;
12257	struct ctl_softc *softc;
12258	int found = 0;
12259	uint32_t targ_lun;
12260
12261	softc = control_softc;
12262	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12263	mtx_lock(&softc->ctl_lock);
12264	if ((targ_lun >= CTL_MAX_LUNS) ||
12265	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12266		mtx_unlock(&softc->ctl_lock);
12267		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12268		return (1);
12269	}
12270	mtx_lock(&lun->lun_lock);
12271	mtx_unlock(&softc->ctl_lock);
12272	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12273	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12274
12275		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12276		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12277		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12278			continue;
12279
12280		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12281			found = 1;
12282			break;
12283		}
12284	}
12285	mtx_unlock(&lun->lun_lock);
12286	if (found)
12287		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12288	else
12289		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12290	return (0);
12291}
12292
12293static int
12294ctl_query_async_event(union ctl_io *io)
12295{
12296	struct ctl_lun *lun;
12297	struct ctl_softc *softc;
12298	ctl_ua_type ua;
12299	uint32_t targ_lun, initidx;
12300
12301	softc = control_softc;
12302	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12303	mtx_lock(&softc->ctl_lock);
12304	if ((targ_lun >= CTL_MAX_LUNS) ||
12305	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12306		mtx_unlock(&softc->ctl_lock);
12307		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12308		return (1);
12309	}
12310	mtx_lock(&lun->lun_lock);
12311	mtx_unlock(&softc->ctl_lock);
12312	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12313	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12314	mtx_unlock(&lun->lun_lock);
12315	if (ua != CTL_UA_NONE)
12316		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12317	else
12318		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12319	return (0);
12320}
12321
12322static void
12323ctl_run_task(union ctl_io *io)
12324{
12325	struct ctl_softc *softc = control_softc;
12326	int retval = 1;
12327
12328	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12329	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12330	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12331	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12332	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12333	switch (io->taskio.task_action) {
12334	case CTL_TASK_ABORT_TASK:
12335		retval = ctl_abort_task(io);
12336		break;
12337	case CTL_TASK_ABORT_TASK_SET:
12338	case CTL_TASK_CLEAR_TASK_SET:
12339		retval = ctl_abort_task_set(io);
12340		break;
12341	case CTL_TASK_CLEAR_ACA:
12342		break;
12343	case CTL_TASK_I_T_NEXUS_RESET:
12344		retval = ctl_i_t_nexus_reset(io);
12345		break;
12346	case CTL_TASK_LUN_RESET:
12347		retval = ctl_lun_reset(softc, io);
12348		break;
12349	case CTL_TASK_TARGET_RESET:
12350		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12351		break;
12352	case CTL_TASK_BUS_RESET:
12353		retval = ctl_bus_reset(softc, io);
12354		break;
12355	case CTL_TASK_PORT_LOGIN:
12356		break;
12357	case CTL_TASK_PORT_LOGOUT:
12358		break;
12359	case CTL_TASK_QUERY_TASK:
12360		retval = ctl_query_task(io, 0);
12361		break;
12362	case CTL_TASK_QUERY_TASK_SET:
12363		retval = ctl_query_task(io, 1);
12364		break;
12365	case CTL_TASK_QUERY_ASYNC_EVENT:
12366		retval = ctl_query_async_event(io);
12367		break;
12368	default:
12369		printf("%s: got unknown task management event %d\n",
12370		       __func__, io->taskio.task_action);
12371		break;
12372	}
12373	if (retval == 0)
12374		io->io_hdr.status = CTL_SUCCESS;
12375	else
12376		io->io_hdr.status = CTL_ERROR;
12377	ctl_done(io);
12378}
12379
12380/*
12381 * For HA operation.  Handle commands that come in from the other
12382 * controller.
12383 */
12384static void
12385ctl_handle_isc(union ctl_io *io)
12386{
12387	int free_io;
12388	struct ctl_lun *lun;
12389	struct ctl_softc *softc = control_softc;
12390	uint32_t targ_lun;
12391
12392	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12393	lun = softc->ctl_luns[targ_lun];
12394
12395	switch (io->io_hdr.msg_type) {
12396	case CTL_MSG_SERIALIZE:
12397		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12398		break;
12399	case CTL_MSG_R2R: {
12400		const struct ctl_cmd_entry *entry;
12401
12402		/*
12403		 * This is only used in SER_ONLY mode.
12404		 */
12405		free_io = 0;
12406		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12407		mtx_lock(&lun->lun_lock);
12408		if (ctl_scsiio_lun_check(lun,
12409		    entry, (struct ctl_scsiio *)io) != 0) {
12410			mtx_unlock(&lun->lun_lock);
12411			ctl_done(io);
12412			break;
12413		}
12414		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12415		mtx_unlock(&lun->lun_lock);
12416		ctl_enqueue_rtr(io);
12417		break;
12418	}
12419	case CTL_MSG_FINISH_IO:
12420		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12421			free_io = 0;
12422			ctl_done(io);
12423		} else {
12424			free_io = 1;
12425			mtx_lock(&lun->lun_lock);
12426			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12427				     ooa_links);
12428			ctl_check_blocked(lun);
12429			mtx_unlock(&lun->lun_lock);
12430		}
12431		break;
12432	case CTL_MSG_PERS_ACTION:
12433		ctl_hndl_per_res_out_on_other_sc(
12434			(union ctl_ha_msg *)&io->presio.pr_msg);
12435		free_io = 1;
12436		break;
12437	case CTL_MSG_BAD_JUJU:
12438		free_io = 0;
12439		ctl_done(io);
12440		break;
12441	case CTL_MSG_DATAMOVE:
12442		/* Only used in XFER mode */
12443		free_io = 0;
12444		ctl_datamove_remote(io);
12445		break;
12446	case CTL_MSG_DATAMOVE_DONE:
12447		/* Only used in XFER mode */
12448		free_io = 0;
12449		io->scsiio.be_move_done(io);
12450		break;
12451	case CTL_MSG_FAILOVER:
12452		ctl_failover_lun(io);
12453		free_io = 1;
12454		break;
12455	default:
12456		free_io = 1;
12457		printf("%s: Invalid message type %d\n",
12458		       __func__, io->io_hdr.msg_type);
12459		break;
12460	}
12461	if (free_io)
12462		ctl_free_io(io);
12463
12464}
12465
12466
12467/*
12468 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12469 * there is no match.
12470 */
12471static ctl_lun_error_pattern
12472ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12473{
12474	const struct ctl_cmd_entry *entry;
12475	ctl_lun_error_pattern filtered_pattern, pattern;
12476
12477	pattern = desc->error_pattern;
12478
12479	/*
12480	 * XXX KDM we need more data passed into this function to match a
12481	 * custom pattern, and we actually need to implement custom pattern
12482	 * matching.
12483	 */
12484	if (pattern & CTL_LUN_PAT_CMD)
12485		return (CTL_LUN_PAT_CMD);
12486
12487	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12488		return (CTL_LUN_PAT_ANY);
12489
12490	entry = ctl_get_cmd_entry(ctsio, NULL);
12491
12492	filtered_pattern = entry->pattern & pattern;
12493
12494	/*
12495	 * If the user requested specific flags in the pattern (e.g.
12496	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12497	 * flags.
12498	 *
12499	 * If the user did not specify any flags, it doesn't matter whether
12500	 * or not the command supports the flags.
12501	 */
12502	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12503	     (pattern & ~CTL_LUN_PAT_MASK))
12504		return (CTL_LUN_PAT_NONE);
12505
12506	/*
12507	 * If the user asked for a range check, see if the requested LBA
12508	 * range overlaps with this command's LBA range.
12509	 */
12510	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12511		uint64_t lba1;
12512		uint64_t len1;
12513		ctl_action action;
12514		int retval;
12515
12516		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12517		if (retval != 0)
12518			return (CTL_LUN_PAT_NONE);
12519
12520		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12521					      desc->lba_range.len, FALSE);
12522		/*
12523		 * A "pass" means that the LBA ranges don't overlap, so
12524		 * this doesn't match the user's range criteria.
12525		 */
12526		if (action == CTL_ACTION_PASS)
12527			return (CTL_LUN_PAT_NONE);
12528	}
12529
12530	return (filtered_pattern);
12531}
12532
12533static void
12534ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12535{
12536	struct ctl_error_desc *desc, *desc2;
12537
12538	mtx_assert(&lun->lun_lock, MA_OWNED);
12539
12540	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12541		ctl_lun_error_pattern pattern;
12542		/*
12543		 * Check to see whether this particular command matches
12544		 * the pattern in the descriptor.
12545		 */
12546		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12547		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12548			continue;
12549
12550		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12551		case CTL_LUN_INJ_ABORTED:
12552			ctl_set_aborted(&io->scsiio);
12553			break;
12554		case CTL_LUN_INJ_MEDIUM_ERR:
12555			ctl_set_medium_error(&io->scsiio,
12556			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12557			     CTL_FLAG_DATA_OUT);
12558			break;
12559		case CTL_LUN_INJ_UA:
12560			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12561			 * OCCURRED */
12562			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12563			break;
12564		case CTL_LUN_INJ_CUSTOM:
12565			/*
12566			 * We're assuming the user knows what he is doing.
12567			 * Just copy the sense information without doing
12568			 * checks.
12569			 */
12570			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12571			      MIN(sizeof(desc->custom_sense),
12572				  sizeof(io->scsiio.sense_data)));
12573			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12574			io->scsiio.sense_len = SSD_FULL_SIZE;
12575			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12576			break;
12577		case CTL_LUN_INJ_NONE:
12578		default:
12579			/*
12580			 * If this is an error injection type we don't know
12581			 * about, clear the continuous flag (if it is set)
12582			 * so it will get deleted below.
12583			 */
12584			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12585			break;
12586		}
12587		/*
12588		 * By default, each error injection action is a one-shot
12589		 */
12590		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12591			continue;
12592
12593		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12594
12595		free(desc, M_CTL);
12596	}
12597}
12598
12599#ifdef CTL_IO_DELAY
12600static void
12601ctl_datamove_timer_wakeup(void *arg)
12602{
12603	union ctl_io *io;
12604
12605	io = (union ctl_io *)arg;
12606
12607	ctl_datamove(io);
12608}
12609#endif /* CTL_IO_DELAY */
12610
12611void
12612ctl_datamove(union ctl_io *io)
12613{
12614	struct ctl_lun *lun;
12615	void (*fe_datamove)(union ctl_io *io);
12616
12617	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12618
12619	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12620
12621	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12622#ifdef CTL_TIME_IO
12623	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12624		char str[256];
12625		char path_str[64];
12626		struct sbuf sb;
12627
12628		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12629		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12630
12631		sbuf_cat(&sb, path_str);
12632		switch (io->io_hdr.io_type) {
12633		case CTL_IO_SCSI:
12634			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12635			sbuf_printf(&sb, "\n");
12636			sbuf_cat(&sb, path_str);
12637			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12638				    io->scsiio.tag_num, io->scsiio.tag_type);
12639			break;
12640		case CTL_IO_TASK:
12641			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12642				    "Tag Type: %d\n", io->taskio.task_action,
12643				    io->taskio.tag_num, io->taskio.tag_type);
12644			break;
12645		default:
12646			panic("%s: Invalid CTL I/O type %d\n",
12647			    __func__, io->io_hdr.io_type);
12648		}
12649		sbuf_cat(&sb, path_str);
12650		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12651			    (intmax_t)time_uptime - io->io_hdr.start_time);
12652		sbuf_finish(&sb);
12653		printf("%s", sbuf_data(&sb));
12654	}
12655#endif /* CTL_TIME_IO */
12656
12657#ifdef CTL_IO_DELAY
12658	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12659		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12660	} else {
12661		if ((lun != NULL)
12662		 && (lun->delay_info.datamove_delay > 0)) {
12663
12664			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12665			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12666			callout_reset(&io->io_hdr.delay_callout,
12667				      lun->delay_info.datamove_delay * hz,
12668				      ctl_datamove_timer_wakeup, io);
12669			if (lun->delay_info.datamove_type ==
12670			    CTL_DELAY_TYPE_ONESHOT)
12671				lun->delay_info.datamove_delay = 0;
12672			return;
12673		}
12674	}
12675#endif
12676
12677	/*
12678	 * This command has been aborted.  Set the port status, so we fail
12679	 * the data move.
12680	 */
12681	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12682		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12683		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12684		       io->io_hdr.nexus.targ_port,
12685		       io->io_hdr.nexus.targ_lun);
12686		io->io_hdr.port_status = 31337;
12687		/*
12688		 * Note that the backend, in this case, will get the
12689		 * callback in its context.  In other cases it may get
12690		 * called in the frontend's interrupt thread context.
12691		 */
12692		io->scsiio.be_move_done(io);
12693		return;
12694	}
12695
12696	/* Don't confuse frontend with zero length data move. */
12697	if (io->scsiio.kern_data_len == 0) {
12698		io->scsiio.be_move_done(io);
12699		return;
12700	}
12701
12702	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12703	fe_datamove(io);
12704}
12705
12706static void
12707ctl_send_datamove_done(union ctl_io *io, int have_lock)
12708{
12709	union ctl_ha_msg msg;
12710#ifdef CTL_TIME_IO
12711	struct bintime cur_bt;
12712#endif
12713
12714	memset(&msg, 0, sizeof(msg));
12715	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12716	msg.hdr.original_sc = io;
12717	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12718	msg.hdr.nexus = io->io_hdr.nexus;
12719	msg.hdr.status = io->io_hdr.status;
12720	msg.scsi.tag_num = io->scsiio.tag_num;
12721	msg.scsi.tag_type = io->scsiio.tag_type;
12722	msg.scsi.scsi_status = io->scsiio.scsi_status;
12723	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12724	       io->scsiio.sense_len);
12725	msg.scsi.sense_len = io->scsiio.sense_len;
12726	msg.scsi.sense_residual = io->scsiio.sense_residual;
12727	msg.scsi.fetd_status = io->io_hdr.port_status;
12728	msg.scsi.residual = io->scsiio.residual;
12729	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12730	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12731		ctl_failover_io(io, /*have_lock*/ have_lock);
12732		return;
12733	}
12734	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12735	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12736	    msg.scsi.sense_len, M_WAITOK);
12737
12738#ifdef CTL_TIME_IO
12739	getbinuptime(&cur_bt);
12740	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12741	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12742#endif
12743	io->io_hdr.num_dmas++;
12744}
12745
12746/*
12747 * The DMA to the remote side is done, now we need to tell the other side
12748 * we're done so it can continue with its data movement.
12749 */
12750static void
12751ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12752{
12753	union ctl_io *io;
12754	uint32_t i;
12755
12756	io = rq->context;
12757
12758	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12759		printf("%s: ISC DMA write failed with error %d", __func__,
12760		       rq->ret);
12761		ctl_set_internal_failure(&io->scsiio,
12762					 /*sks_valid*/ 1,
12763					 /*retry_count*/ rq->ret);
12764	}
12765
12766	ctl_dt_req_free(rq);
12767
12768	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12769		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12770	free(io->io_hdr.remote_sglist, M_CTL);
12771	io->io_hdr.remote_sglist = NULL;
12772	io->io_hdr.local_sglist = NULL;
12773
12774	/*
12775	 * The data is in local and remote memory, so now we need to send
12776	 * status (good or back) back to the other side.
12777	 */
12778	ctl_send_datamove_done(io, /*have_lock*/ 0);
12779}
12780
12781/*
12782 * We've moved the data from the host/controller into local memory.  Now we
12783 * need to push it over to the remote controller's memory.
12784 */
12785static int
12786ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12787{
12788	int retval;
12789
12790	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12791					  ctl_datamove_remote_write_cb);
12792	return (retval);
12793}
12794
12795static void
12796ctl_datamove_remote_write(union ctl_io *io)
12797{
12798	int retval;
12799	void (*fe_datamove)(union ctl_io *io);
12800
12801	/*
12802	 * - Get the data from the host/HBA into local memory.
12803	 * - DMA memory from the local controller to the remote controller.
12804	 * - Send status back to the remote controller.
12805	 */
12806
12807	retval = ctl_datamove_remote_sgl_setup(io);
12808	if (retval != 0)
12809		return;
12810
12811	/* Switch the pointer over so the FETD knows what to do */
12812	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12813
12814	/*
12815	 * Use a custom move done callback, since we need to send completion
12816	 * back to the other controller, not to the backend on this side.
12817	 */
12818	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12819
12820	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12821	fe_datamove(io);
12822}
12823
12824static int
12825ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12826{
12827#if 0
12828	char str[256];
12829	char path_str[64];
12830	struct sbuf sb;
12831#endif
12832	uint32_t i;
12833
12834	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12835		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12836	free(io->io_hdr.remote_sglist, M_CTL);
12837	io->io_hdr.remote_sglist = NULL;
12838	io->io_hdr.local_sglist = NULL;
12839
12840#if 0
12841	scsi_path_string(io, path_str, sizeof(path_str));
12842	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12843	sbuf_cat(&sb, path_str);
12844	scsi_command_string(&io->scsiio, NULL, &sb);
12845	sbuf_printf(&sb, "\n");
12846	sbuf_cat(&sb, path_str);
12847	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12848		    io->scsiio.tag_num, io->scsiio.tag_type);
12849	sbuf_cat(&sb, path_str);
12850	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12851		    io->io_hdr.flags, io->io_hdr.status);
12852	sbuf_finish(&sb);
12853	printk("%s", sbuf_data(&sb));
12854#endif
12855
12856
12857	/*
12858	 * The read is done, now we need to send status (good or bad) back
12859	 * to the other side.
12860	 */
12861	ctl_send_datamove_done(io, /*have_lock*/ 0);
12862
12863	return (0);
12864}
12865
12866static void
12867ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12868{
12869	union ctl_io *io;
12870	void (*fe_datamove)(union ctl_io *io);
12871
12872	io = rq->context;
12873
12874	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12875		printf("%s: ISC DMA read failed with error %d\n", __func__,
12876		       rq->ret);
12877		ctl_set_internal_failure(&io->scsiio,
12878					 /*sks_valid*/ 1,
12879					 /*retry_count*/ rq->ret);
12880	}
12881
12882	ctl_dt_req_free(rq);
12883
12884	/* Switch the pointer over so the FETD knows what to do */
12885	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12886
12887	/*
12888	 * Use a custom move done callback, since we need to send completion
12889	 * back to the other controller, not to the backend on this side.
12890	 */
12891	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12892
12893	/* XXX KDM add checks like the ones in ctl_datamove? */
12894
12895	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12896	fe_datamove(io);
12897}
12898
12899static int
12900ctl_datamove_remote_sgl_setup(union ctl_io *io)
12901{
12902	struct ctl_sg_entry *local_sglist;
12903	uint32_t len_to_go;
12904	int retval;
12905	int i;
12906
12907	retval = 0;
12908	local_sglist = io->io_hdr.local_sglist;
12909	len_to_go = io->scsiio.kern_data_len;
12910
12911	/*
12912	 * The difficult thing here is that the size of the various
12913	 * S/G segments may be different than the size from the
12914	 * remote controller.  That'll make it harder when DMAing
12915	 * the data back to the other side.
12916	 */
12917	for (i = 0; len_to_go > 0; i++) {
12918		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12919		local_sglist[i].addr =
12920		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12921
12922		len_to_go -= local_sglist[i].len;
12923	}
12924	/*
12925	 * Reset the number of S/G entries accordingly.  The original
12926	 * number of S/G entries is available in rem_sg_entries.
12927	 */
12928	io->scsiio.kern_sg_entries = i;
12929
12930#if 0
12931	printf("%s: kern_sg_entries = %d\n", __func__,
12932	       io->scsiio.kern_sg_entries);
12933	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12934		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12935		       local_sglist[i].addr, local_sglist[i].len);
12936#endif
12937
12938	return (retval);
12939}
12940
12941static int
12942ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12943			 ctl_ha_dt_cb callback)
12944{
12945	struct ctl_ha_dt_req *rq;
12946	struct ctl_sg_entry *remote_sglist, *local_sglist;
12947	uint32_t local_used, remote_used, total_used;
12948	int i, j, isc_ret;
12949
12950	rq = ctl_dt_req_alloc();
12951
12952	/*
12953	 * If we failed to allocate the request, and if the DMA didn't fail
12954	 * anyway, set busy status.  This is just a resource allocation
12955	 * failure.
12956	 */
12957	if ((rq == NULL)
12958	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12959	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12960		ctl_set_busy(&io->scsiio);
12961
12962	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12963	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12964
12965		if (rq != NULL)
12966			ctl_dt_req_free(rq);
12967
12968		/*
12969		 * The data move failed.  We need to return status back
12970		 * to the other controller.  No point in trying to DMA
12971		 * data to the remote controller.
12972		 */
12973
12974		ctl_send_datamove_done(io, /*have_lock*/ 0);
12975
12976		return (1);
12977	}
12978
12979	local_sglist = io->io_hdr.local_sglist;
12980	remote_sglist = io->io_hdr.remote_sglist;
12981	local_used = 0;
12982	remote_used = 0;
12983	total_used = 0;
12984
12985	/*
12986	 * Pull/push the data over the wire from/to the other controller.
12987	 * This takes into account the possibility that the local and
12988	 * remote sglists may not be identical in terms of the size of
12989	 * the elements and the number of elements.
12990	 *
12991	 * One fundamental assumption here is that the length allocated for
12992	 * both the local and remote sglists is identical.  Otherwise, we've
12993	 * essentially got a coding error of some sort.
12994	 */
12995	isc_ret = CTL_HA_STATUS_SUCCESS;
12996	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12997		uint32_t cur_len;
12998		uint8_t *tmp_ptr;
12999
13000		rq->command = command;
13001		rq->context = io;
13002
13003		/*
13004		 * Both pointers should be aligned.  But it is possible
13005		 * that the allocation length is not.  They should both
13006		 * also have enough slack left over at the end, though,
13007		 * to round up to the next 8 byte boundary.
13008		 */
13009		cur_len = MIN(local_sglist[i].len - local_used,
13010			      remote_sglist[j].len - remote_used);
13011		rq->size = cur_len;
13012
13013		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13014		tmp_ptr += local_used;
13015
13016#if 0
13017		/* Use physical addresses when talking to ISC hardware */
13018		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13019			/* XXX KDM use busdma */
13020			rq->local = vtophys(tmp_ptr);
13021		} else
13022			rq->local = tmp_ptr;
13023#else
13024		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
13025		    ("HA does not support BUS_ADDR"));
13026		rq->local = tmp_ptr;
13027#endif
13028
13029		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13030		tmp_ptr += remote_used;
13031		rq->remote = tmp_ptr;
13032
13033		rq->callback = NULL;
13034
13035		local_used += cur_len;
13036		if (local_used >= local_sglist[i].len) {
13037			i++;
13038			local_used = 0;
13039		}
13040
13041		remote_used += cur_len;
13042		if (remote_used >= remote_sglist[j].len) {
13043			j++;
13044			remote_used = 0;
13045		}
13046		total_used += cur_len;
13047
13048		if (total_used >= io->scsiio.kern_data_len)
13049			rq->callback = callback;
13050
13051#if 0
13052		printf("%s: %s: local %p remote %p size %d\n", __func__,
13053		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13054		       rq->local, rq->remote, rq->size);
13055#endif
13056
13057		isc_ret = ctl_dt_single(rq);
13058		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13059			break;
13060	}
13061	if (isc_ret != CTL_HA_STATUS_WAIT) {
13062		rq->ret = isc_ret;
13063		callback(rq);
13064	}
13065
13066	return (0);
13067}
13068
13069static void
13070ctl_datamove_remote_read(union ctl_io *io)
13071{
13072	int retval;
13073	uint32_t i;
13074
13075	/*
13076	 * This will send an error to the other controller in the case of a
13077	 * failure.
13078	 */
13079	retval = ctl_datamove_remote_sgl_setup(io);
13080	if (retval != 0)
13081		return;
13082
13083	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13084					  ctl_datamove_remote_read_cb);
13085	if (retval != 0) {
13086		/*
13087		 * Make sure we free memory if there was an error..  The
13088		 * ctl_datamove_remote_xfer() function will send the
13089		 * datamove done message, or call the callback with an
13090		 * error if there is a problem.
13091		 */
13092		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13093			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13094		free(io->io_hdr.remote_sglist, M_CTL);
13095		io->io_hdr.remote_sglist = NULL;
13096		io->io_hdr.local_sglist = NULL;
13097	}
13098}
13099
13100/*
13101 * Process a datamove request from the other controller.  This is used for
13102 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13103 * first.  Once that is complete, the data gets DMAed into the remote
13104 * controller's memory.  For reads, we DMA from the remote controller's
13105 * memory into our memory first, and then move it out to the FETD.
13106 */
13107static void
13108ctl_datamove_remote(union ctl_io *io)
13109{
13110
13111	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13112
13113	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13114		ctl_failover_io(io, /*have_lock*/ 0);
13115		return;
13116	}
13117
13118	/*
13119	 * Note that we look for an aborted I/O here, but don't do some of
13120	 * the other checks that ctl_datamove() normally does.
13121	 * We don't need to run the datamove delay code, since that should
13122	 * have been done if need be on the other controller.
13123	 */
13124	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13125		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13126		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13127		       io->io_hdr.nexus.targ_port,
13128		       io->io_hdr.nexus.targ_lun);
13129		io->io_hdr.port_status = 31338;
13130		ctl_send_datamove_done(io, /*have_lock*/ 0);
13131		return;
13132	}
13133
13134	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13135		ctl_datamove_remote_write(io);
13136	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13137		ctl_datamove_remote_read(io);
13138	else {
13139		io->io_hdr.port_status = 31339;
13140		ctl_send_datamove_done(io, /*have_lock*/ 0);
13141	}
13142}
13143
13144static void
13145ctl_process_done(union ctl_io *io)
13146{
13147	struct ctl_lun *lun;
13148	struct ctl_softc *softc = control_softc;
13149	void (*fe_done)(union ctl_io *io);
13150	union ctl_ha_msg msg;
13151	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13152
13153	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13154	fe_done = softc->ctl_ports[targ_port]->fe_done;
13155
13156#ifdef CTL_TIME_IO
13157	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13158		char str[256];
13159		char path_str[64];
13160		struct sbuf sb;
13161
13162		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13163		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13164
13165		sbuf_cat(&sb, path_str);
13166		switch (io->io_hdr.io_type) {
13167		case CTL_IO_SCSI:
13168			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13169			sbuf_printf(&sb, "\n");
13170			sbuf_cat(&sb, path_str);
13171			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13172				    io->scsiio.tag_num, io->scsiio.tag_type);
13173			break;
13174		case CTL_IO_TASK:
13175			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13176				    "Tag Type: %d\n", io->taskio.task_action,
13177				    io->taskio.tag_num, io->taskio.tag_type);
13178			break;
13179		default:
13180			panic("%s: Invalid CTL I/O type %d\n",
13181			    __func__, io->io_hdr.io_type);
13182		}
13183		sbuf_cat(&sb, path_str);
13184		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13185			    (intmax_t)time_uptime - io->io_hdr.start_time);
13186		sbuf_finish(&sb);
13187		printf("%s", sbuf_data(&sb));
13188	}
13189#endif /* CTL_TIME_IO */
13190
13191	switch (io->io_hdr.io_type) {
13192	case CTL_IO_SCSI:
13193		break;
13194	case CTL_IO_TASK:
13195		if (ctl_debug & CTL_DEBUG_INFO)
13196			ctl_io_error_print(io, NULL);
13197		fe_done(io);
13198		return;
13199	default:
13200		panic("%s: Invalid CTL I/O type %d\n",
13201		    __func__, io->io_hdr.io_type);
13202	}
13203
13204	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13205	if (lun == NULL) {
13206		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13207				 io->io_hdr.nexus.targ_mapped_lun));
13208		goto bailout;
13209	}
13210
13211	mtx_lock(&lun->lun_lock);
13212
13213	/*
13214	 * Check to see if we have any informational exception and status
13215	 * of this command can be modified to report it in form of either
13216	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13217	 */
13218	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13219	    io->io_hdr.status == CTL_SUCCESS &&
13220	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13221		uint8_t mrie = lun->MODE_IE.mrie;
13222		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13223		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13224		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13225		     mrie == SIEP_MRIE_REC_UNCOND ||
13226		     mrie == SIEP_MRIE_NO_SENSE) &&
13227		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13228		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13229			ctl_set_sense(&io->scsiio,
13230			      /*current_error*/ 1,
13231			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13232			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13233			      /*asc*/ lun->ie_asc,
13234			      /*ascq*/ lun->ie_ascq,
13235			      SSD_ELEM_NONE);
13236			lun->ie_reported = 1;
13237		}
13238	} else if (lun->ie_reported < 0)
13239		lun->ie_reported = 0;
13240
13241	/*
13242	 * Check to see if we have any errors to inject here.  We only
13243	 * inject errors for commands that don't already have errors set.
13244	 */
13245	if (!STAILQ_EMPTY(&lun->error_list) &&
13246	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13247	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13248		ctl_inject_error(lun, io);
13249
13250	/*
13251	 * XXX KDM how do we treat commands that aren't completed
13252	 * successfully?
13253	 *
13254	 * XXX KDM should we also track I/O latency?
13255	 */
13256	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13257	    io->io_hdr.io_type == CTL_IO_SCSI) {
13258#ifdef CTL_TIME_IO
13259		struct bintime cur_bt;
13260#endif
13261		int type;
13262
13263		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13264		    CTL_FLAG_DATA_IN)
13265			type = CTL_STATS_READ;
13266		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13267		    CTL_FLAG_DATA_OUT)
13268			type = CTL_STATS_WRITE;
13269		else
13270			type = CTL_STATS_NO_IO;
13271
13272		lun->stats.ports[targ_port].bytes[type] +=
13273		    io->scsiio.kern_total_len;
13274		lun->stats.ports[targ_port].operations[type]++;
13275#ifdef CTL_TIME_IO
13276		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13277		   &io->io_hdr.dma_bt);
13278		getbinuptime(&cur_bt);
13279		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13280		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13281#endif
13282		lun->stats.ports[targ_port].num_dmas[type] +=
13283		    io->io_hdr.num_dmas;
13284	}
13285
13286	/*
13287	 * Remove this from the OOA queue.
13288	 */
13289	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13290#ifdef CTL_TIME_IO
13291	if (TAILQ_EMPTY(&lun->ooa_queue))
13292		lun->last_busy = getsbinuptime();
13293#endif
13294
13295	/*
13296	 * Run through the blocked queue on this LUN and see if anything
13297	 * has become unblocked, now that this transaction is done.
13298	 */
13299	ctl_check_blocked(lun);
13300
13301	/*
13302	 * If the LUN has been invalidated, free it if there is nothing
13303	 * left on its OOA queue.
13304	 */
13305	if ((lun->flags & CTL_LUN_INVALID)
13306	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13307		mtx_unlock(&lun->lun_lock);
13308		mtx_lock(&softc->ctl_lock);
13309		ctl_free_lun(lun);
13310		mtx_unlock(&softc->ctl_lock);
13311	} else
13312		mtx_unlock(&lun->lun_lock);
13313
13314bailout:
13315
13316	/*
13317	 * If this command has been aborted, make sure we set the status
13318	 * properly.  The FETD is responsible for freeing the I/O and doing
13319	 * whatever it needs to do to clean up its state.
13320	 */
13321	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13322		ctl_set_task_aborted(&io->scsiio);
13323
13324	/*
13325	 * If enabled, print command error status.
13326	 */
13327	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13328	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13329		ctl_io_error_print(io, NULL);
13330
13331	/*
13332	 * Tell the FETD or the other shelf controller we're done with this
13333	 * command.  Note that only SCSI commands get to this point.  Task
13334	 * management commands are completed above.
13335	 */
13336	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13337	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13338		memset(&msg, 0, sizeof(msg));
13339		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13340		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13341		msg.hdr.nexus = io->io_hdr.nexus;
13342		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13343		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13344		    M_WAITOK);
13345	}
13346
13347	fe_done(io);
13348}
13349
13350#ifdef CTL_WITH_CA
13351/*
13352 * Front end should call this if it doesn't do autosense.  When the request
13353 * sense comes back in from the initiator, we'll dequeue this and send it.
13354 */
13355int
13356ctl_queue_sense(union ctl_io *io)
13357{
13358	struct ctl_lun *lun;
13359	struct ctl_port *port;
13360	struct ctl_softc *softc;
13361	uint32_t initidx, targ_lun;
13362
13363	softc = control_softc;
13364
13365	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13366
13367	/*
13368	 * LUN lookup will likely move to the ctl_work_thread() once we
13369	 * have our new queueing infrastructure (that doesn't put things on
13370	 * a per-LUN queue initially).  That is so that we can handle
13371	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13372	 * can't deal with that right now.
13373	 */
13374	mtx_lock(&softc->ctl_lock);
13375
13376	/*
13377	 * If we don't have a LUN for this, just toss the sense
13378	 * information.
13379	 */
13380	port = ctl_io_port(&ctsio->io_hdr);
13381	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13382	if ((targ_lun < CTL_MAX_LUNS)
13383	 && (softc->ctl_luns[targ_lun] != NULL))
13384		lun = softc->ctl_luns[targ_lun];
13385	else
13386		goto bailout;
13387
13388	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13389
13390	mtx_lock(&lun->lun_lock);
13391	/*
13392	 * Already have CA set for this LUN...toss the sense information.
13393	 */
13394	if (ctl_is_set(lun->have_ca, initidx)) {
13395		mtx_unlock(&lun->lun_lock);
13396		goto bailout;
13397	}
13398
13399	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13400	       MIN(sizeof(lun->pending_sense[initidx]),
13401	       sizeof(io->scsiio.sense_data)));
13402	ctl_set_mask(lun->have_ca, initidx);
13403	mtx_unlock(&lun->lun_lock);
13404
13405bailout:
13406	mtx_unlock(&softc->ctl_lock);
13407
13408	ctl_free_io(io);
13409
13410	return (CTL_RETVAL_COMPLETE);
13411}
13412#endif
13413
13414/*
13415 * Primary command inlet from frontend ports.  All SCSI and task I/O
13416 * requests must go through this function.
13417 */
13418int
13419ctl_queue(union ctl_io *io)
13420{
13421	struct ctl_port *port;
13422
13423	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13424
13425#ifdef CTL_TIME_IO
13426	io->io_hdr.start_time = time_uptime;
13427	getbinuptime(&io->io_hdr.start_bt);
13428#endif /* CTL_TIME_IO */
13429
13430	/* Map FE-specific LUN ID into global one. */
13431	port = ctl_io_port(&io->io_hdr);
13432	io->io_hdr.nexus.targ_mapped_lun =
13433	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13434
13435	switch (io->io_hdr.io_type) {
13436	case CTL_IO_SCSI:
13437	case CTL_IO_TASK:
13438		if (ctl_debug & CTL_DEBUG_CDB)
13439			ctl_io_print(io);
13440		ctl_enqueue_incoming(io);
13441		break;
13442	default:
13443		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13444		return (EINVAL);
13445	}
13446
13447	return (CTL_RETVAL_COMPLETE);
13448}
13449
13450#ifdef CTL_IO_DELAY
13451static void
13452ctl_done_timer_wakeup(void *arg)
13453{
13454	union ctl_io *io;
13455
13456	io = (union ctl_io *)arg;
13457	ctl_done(io);
13458}
13459#endif /* CTL_IO_DELAY */
13460
13461void
13462ctl_serseq_done(union ctl_io *io)
13463{
13464	struct ctl_lun *lun;
13465
13466	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13467	if (lun->be_lun == NULL ||
13468	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13469		return;
13470	mtx_lock(&lun->lun_lock);
13471	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13472	ctl_check_blocked(lun);
13473	mtx_unlock(&lun->lun_lock);
13474}
13475
13476void
13477ctl_done(union ctl_io *io)
13478{
13479
13480	/*
13481	 * Enable this to catch duplicate completion issues.
13482	 */
13483#if 0
13484	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13485		printf("%s: type %d msg %d cdb %x iptl: "
13486		       "%u:%u:%u tag 0x%04x "
13487		       "flag %#x status %x\n",
13488			__func__,
13489			io->io_hdr.io_type,
13490			io->io_hdr.msg_type,
13491			io->scsiio.cdb[0],
13492			io->io_hdr.nexus.initid,
13493			io->io_hdr.nexus.targ_port,
13494			io->io_hdr.nexus.targ_lun,
13495			(io->io_hdr.io_type ==
13496			CTL_IO_TASK) ?
13497			io->taskio.tag_num :
13498			io->scsiio.tag_num,
13499		        io->io_hdr.flags,
13500			io->io_hdr.status);
13501	} else
13502		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13503#endif
13504
13505	/*
13506	 * This is an internal copy of an I/O, and should not go through
13507	 * the normal done processing logic.
13508	 */
13509	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13510		return;
13511
13512#ifdef CTL_IO_DELAY
13513	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13514		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13515	} else {
13516		struct ctl_lun *lun;
13517
13518		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13519
13520		if ((lun != NULL)
13521		 && (lun->delay_info.done_delay > 0)) {
13522
13523			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13524			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13525			callout_reset(&io->io_hdr.delay_callout,
13526				      lun->delay_info.done_delay * hz,
13527				      ctl_done_timer_wakeup, io);
13528			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13529				lun->delay_info.done_delay = 0;
13530			return;
13531		}
13532	}
13533#endif /* CTL_IO_DELAY */
13534
13535	ctl_enqueue_done(io);
13536}
13537
13538static void
13539ctl_work_thread(void *arg)
13540{
13541	struct ctl_thread *thr = (struct ctl_thread *)arg;
13542	struct ctl_softc *softc = thr->ctl_softc;
13543	union ctl_io *io;
13544	int retval;
13545
13546	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13547
13548	for (;;) {
13549		/*
13550		 * We handle the queues in this order:
13551		 * - ISC
13552		 * - done queue (to free up resources, unblock other commands)
13553		 * - RtR queue
13554		 * - incoming queue
13555		 *
13556		 * If those queues are empty, we break out of the loop and
13557		 * go to sleep.
13558		 */
13559		mtx_lock(&thr->queue_lock);
13560		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13561		if (io != NULL) {
13562			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13563			mtx_unlock(&thr->queue_lock);
13564			ctl_handle_isc(io);
13565			continue;
13566		}
13567		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13568		if (io != NULL) {
13569			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13570			/* clear any blocked commands, call fe_done */
13571			mtx_unlock(&thr->queue_lock);
13572			ctl_process_done(io);
13573			continue;
13574		}
13575		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13576		if (io != NULL) {
13577			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13578			mtx_unlock(&thr->queue_lock);
13579			if (io->io_hdr.io_type == CTL_IO_TASK)
13580				ctl_run_task(io);
13581			else
13582				ctl_scsiio_precheck(softc, &io->scsiio);
13583			continue;
13584		}
13585		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13586		if (io != NULL) {
13587			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13588			mtx_unlock(&thr->queue_lock);
13589			retval = ctl_scsiio(&io->scsiio);
13590			if (retval != CTL_RETVAL_COMPLETE)
13591				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13592			continue;
13593		}
13594
13595		/* Sleep until we have something to do. */
13596		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13597	}
13598}
13599
13600static void
13601ctl_lun_thread(void *arg)
13602{
13603	struct ctl_softc *softc = (struct ctl_softc *)arg;
13604	struct ctl_be_lun *be_lun;
13605
13606	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13607
13608	for (;;) {
13609		mtx_lock(&softc->ctl_lock);
13610		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13611		if (be_lun != NULL) {
13612			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13613			mtx_unlock(&softc->ctl_lock);
13614			ctl_create_lun(be_lun);
13615			continue;
13616		}
13617
13618		/* Sleep until we have something to do. */
13619		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13620		    PDROP | PRIBIO, "-", 0);
13621	}
13622}
13623
13624static void
13625ctl_thresh_thread(void *arg)
13626{
13627	struct ctl_softc *softc = (struct ctl_softc *)arg;
13628	struct ctl_lun *lun;
13629	struct ctl_logical_block_provisioning_page *page;
13630	const char *attr;
13631	union ctl_ha_msg msg;
13632	uint64_t thres, val;
13633	int i, e, set;
13634
13635	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13636
13637	for (;;) {
13638		mtx_lock(&softc->ctl_lock);
13639		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13640			if ((lun->flags & CTL_LUN_DISABLED) ||
13641			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13642			    lun->backend->lun_attr == NULL)
13643				continue;
13644			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13645			    softc->ha_mode == CTL_HA_MODE_XFER)
13646				continue;
13647			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13648				continue;
13649			e = 0;
13650			page = &lun->MODE_LBP;
13651			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13652				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13653					continue;
13654				thres = scsi_4btoul(page->descr[i].count);
13655				thres <<= CTL_LBP_EXPONENT;
13656				switch (page->descr[i].resource) {
13657				case 0x01:
13658					attr = "blocksavail";
13659					break;
13660				case 0x02:
13661					attr = "blocksused";
13662					break;
13663				case 0xf1:
13664					attr = "poolblocksavail";
13665					break;
13666				case 0xf2:
13667					attr = "poolblocksused";
13668					break;
13669				default:
13670					continue;
13671				}
13672				mtx_unlock(&softc->ctl_lock); // XXX
13673				val = lun->backend->lun_attr(
13674				    lun->be_lun->be_lun, attr);
13675				mtx_lock(&softc->ctl_lock);
13676				if (val == UINT64_MAX)
13677					continue;
13678				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13679				    == SLBPPD_ARMING_INC)
13680					e = (val >= thres);
13681				else
13682					e = (val <= thres);
13683				if (e)
13684					break;
13685			}
13686			mtx_lock(&lun->lun_lock);
13687			if (e) {
13688				scsi_u64to8b((uint8_t *)&page->descr[i] -
13689				    (uint8_t *)page, lun->ua_tpt_info);
13690				if (lun->lasttpt == 0 ||
13691				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13692					lun->lasttpt = time_uptime;
13693					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13694					set = 1;
13695				} else
13696					set = 0;
13697			} else {
13698				lun->lasttpt = 0;
13699				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13700				set = -1;
13701			}
13702			mtx_unlock(&lun->lun_lock);
13703			if (set != 0 &&
13704			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13705				/* Send msg to other side. */
13706				bzero(&msg.ua, sizeof(msg.ua));
13707				msg.hdr.msg_type = CTL_MSG_UA;
13708				msg.hdr.nexus.initid = -1;
13709				msg.hdr.nexus.targ_port = -1;
13710				msg.hdr.nexus.targ_lun = lun->lun;
13711				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13712				msg.ua.ua_all = 1;
13713				msg.ua.ua_set = (set > 0);
13714				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13715				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13716				mtx_unlock(&softc->ctl_lock); // XXX
13717				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13718				    sizeof(msg.ua), M_WAITOK);
13719				mtx_lock(&softc->ctl_lock);
13720			}
13721		}
13722		mtx_unlock(&softc->ctl_lock);
13723		pause("-", CTL_LBP_PERIOD * hz);
13724	}
13725}
13726
13727static void
13728ctl_enqueue_incoming(union ctl_io *io)
13729{
13730	struct ctl_softc *softc = control_softc;
13731	struct ctl_thread *thr;
13732	u_int idx;
13733
13734	idx = (io->io_hdr.nexus.targ_port * 127 +
13735	       io->io_hdr.nexus.initid) % worker_threads;
13736	thr = &softc->threads[idx];
13737	mtx_lock(&thr->queue_lock);
13738	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13739	mtx_unlock(&thr->queue_lock);
13740	wakeup(thr);
13741}
13742
13743static void
13744ctl_enqueue_rtr(union ctl_io *io)
13745{
13746	struct ctl_softc *softc = control_softc;
13747	struct ctl_thread *thr;
13748
13749	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13750	mtx_lock(&thr->queue_lock);
13751	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13752	mtx_unlock(&thr->queue_lock);
13753	wakeup(thr);
13754}
13755
13756static void
13757ctl_enqueue_done(union ctl_io *io)
13758{
13759	struct ctl_softc *softc = control_softc;
13760	struct ctl_thread *thr;
13761
13762	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13763	mtx_lock(&thr->queue_lock);
13764	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13765	mtx_unlock(&thr->queue_lock);
13766	wakeup(thr);
13767}
13768
13769static void
13770ctl_enqueue_isc(union ctl_io *io)
13771{
13772	struct ctl_softc *softc = control_softc;
13773	struct ctl_thread *thr;
13774
13775	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13776	mtx_lock(&thr->queue_lock);
13777	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13778	mtx_unlock(&thr->queue_lock);
13779	wakeup(thr);
13780}
13781
13782/*
13783 *  vim: ts=8
13784 */
13785