ctl.c revision 309516
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 309516 2016-12-03 21:27:19Z trasz $");
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/ctype.h>
51#include <sys/kernel.h>
52#include <sys/types.h>
53#include <sys/kthread.h>
54#include <sys/bio.h>
55#include <sys/fcntl.h>
56#include <sys/lock.h>
57#include <sys/module.h>
58#include <sys/mutex.h>
59#include <sys/condvar.h>
60#include <sys/malloc.h>
61#include <sys/conf.h>
62#include <sys/ioccom.h>
63#include <sys/queue.h>
64#include <sys/sbuf.h>
65#include <sys/smp.h>
66#include <sys/endian.h>
67#include <sys/sysctl.h>
68#include <vm/uma.h>
69
70#include <cam/cam.h>
71#include <cam/scsi/scsi_all.h>
72#include <cam/scsi/scsi_cd.h>
73#include <cam/scsi/scsi_da.h>
74#include <cam/ctl/ctl_io.h>
75#include <cam/ctl/ctl.h>
76#include <cam/ctl/ctl_frontend.h>
77#include <cam/ctl/ctl_util.h>
78#include <cam/ctl/ctl_backend.h>
79#include <cam/ctl/ctl_ioctl.h>
80#include <cam/ctl/ctl_ha.h>
81#include <cam/ctl/ctl_private.h>
82#include <cam/ctl/ctl_debug.h>
83#include <cam/ctl/ctl_scsi_all.h>
84#include <cam/ctl/ctl_error.h>
85
86struct ctl_softc *control_softc = NULL;
87
88/*
89 * Template mode pages.
90 */
91
92/*
93 * Note that these are default values only.  The actual values will be
94 * filled in when the user does a mode sense.
95 */
96const static struct copan_debugconf_subpage debugconf_page_default = {
97	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
98	DBGCNF_SUBPAGE_CODE,		/* subpage */
99	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
100	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
101	DBGCNF_VERSION,			/* page_version */
102	{CTL_TIME_IO_DEFAULT_SECS>>8,
103	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
104};
105
106const static struct copan_debugconf_subpage debugconf_page_changeable = {
107	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
108	DBGCNF_SUBPAGE_CODE,		/* subpage */
109	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
110	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
111	0,				/* page_version */
112	{0xff,0xff},			/* ctl_time_io_secs */
113};
114
115const static struct scsi_da_rw_recovery_page rw_er_page_default = {
116	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
117	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
118	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
119	/*read_retry_count*/0,
120	/*correction_span*/0,
121	/*head_offset_count*/0,
122	/*data_strobe_offset_cnt*/0,
123	/*byte8*/SMS_RWER_LBPERE,
124	/*write_retry_count*/0,
125	/*reserved2*/0,
126	/*recovery_time_limit*/{0, 0},
127};
128
129const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
130	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
131	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
132	/*byte3*/0,
133	/*read_retry_count*/0,
134	/*correction_span*/0,
135	/*head_offset_count*/0,
136	/*data_strobe_offset_cnt*/0,
137	/*byte8*/0,
138	/*write_retry_count*/0,
139	/*reserved2*/0,
140	/*recovery_time_limit*/{0, 0},
141};
142
143const static struct scsi_format_page format_page_default = {
144	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
145	/*page_length*/sizeof(struct scsi_format_page) - 2,
146	/*tracks_per_zone*/ {0, 0},
147	/*alt_sectors_per_zone*/ {0, 0},
148	/*alt_tracks_per_zone*/ {0, 0},
149	/*alt_tracks_per_lun*/ {0, 0},
150	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
151			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
152	/*bytes_per_sector*/ {0, 0},
153	/*interleave*/ {0, 0},
154	/*track_skew*/ {0, 0},
155	/*cylinder_skew*/ {0, 0},
156	/*flags*/ SFP_HSEC,
157	/*reserved*/ {0, 0, 0}
158};
159
160const static struct scsi_format_page format_page_changeable = {
161	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
162	/*page_length*/sizeof(struct scsi_format_page) - 2,
163	/*tracks_per_zone*/ {0, 0},
164	/*alt_sectors_per_zone*/ {0, 0},
165	/*alt_tracks_per_zone*/ {0, 0},
166	/*alt_tracks_per_lun*/ {0, 0},
167	/*sectors_per_track*/ {0, 0},
168	/*bytes_per_sector*/ {0, 0},
169	/*interleave*/ {0, 0},
170	/*track_skew*/ {0, 0},
171	/*cylinder_skew*/ {0, 0},
172	/*flags*/ 0,
173	/*reserved*/ {0, 0, 0}
174};
175
176const static struct scsi_rigid_disk_page rigid_disk_page_default = {
177	/*page_code*/SMS_RIGID_DISK_PAGE,
178	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
179	/*cylinders*/ {0, 0, 0},
180	/*heads*/ CTL_DEFAULT_HEADS,
181	/*start_write_precomp*/ {0, 0, 0},
182	/*start_reduced_current*/ {0, 0, 0},
183	/*step_rate*/ {0, 0},
184	/*landing_zone_cylinder*/ {0, 0, 0},
185	/*rpl*/ SRDP_RPL_DISABLED,
186	/*rotational_offset*/ 0,
187	/*reserved1*/ 0,
188	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
189			   CTL_DEFAULT_ROTATION_RATE & 0xff},
190	/*reserved2*/ {0, 0}
191};
192
193const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
194	/*page_code*/SMS_RIGID_DISK_PAGE,
195	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
196	/*cylinders*/ {0, 0, 0},
197	/*heads*/ 0,
198	/*start_write_precomp*/ {0, 0, 0},
199	/*start_reduced_current*/ {0, 0, 0},
200	/*step_rate*/ {0, 0},
201	/*landing_zone_cylinder*/ {0, 0, 0},
202	/*rpl*/ 0,
203	/*rotational_offset*/ 0,
204	/*reserved1*/ 0,
205	/*rotation_rate*/ {0, 0},
206	/*reserved2*/ {0, 0}
207};
208
209const static struct scsi_caching_page caching_page_default = {
210	/*page_code*/SMS_CACHING_PAGE,
211	/*page_length*/sizeof(struct scsi_caching_page) - 2,
212	/*flags1*/ SCP_DISC | SCP_WCE,
213	/*ret_priority*/ 0,
214	/*disable_pf_transfer_len*/ {0xff, 0xff},
215	/*min_prefetch*/ {0, 0},
216	/*max_prefetch*/ {0xff, 0xff},
217	/*max_pf_ceiling*/ {0xff, 0xff},
218	/*flags2*/ 0,
219	/*cache_segments*/ 0,
220	/*cache_seg_size*/ {0, 0},
221	/*reserved*/ 0,
222	/*non_cache_seg_size*/ {0, 0, 0}
223};
224
225const static struct scsi_caching_page caching_page_changeable = {
226	/*page_code*/SMS_CACHING_PAGE,
227	/*page_length*/sizeof(struct scsi_caching_page) - 2,
228	/*flags1*/ SCP_WCE | SCP_RCD,
229	/*ret_priority*/ 0,
230	/*disable_pf_transfer_len*/ {0, 0},
231	/*min_prefetch*/ {0, 0},
232	/*max_prefetch*/ {0, 0},
233	/*max_pf_ceiling*/ {0, 0},
234	/*flags2*/ 0,
235	/*cache_segments*/ 0,
236	/*cache_seg_size*/ {0, 0},
237	/*reserved*/ 0,
238	/*non_cache_seg_size*/ {0, 0, 0}
239};
240
241const static struct scsi_control_page control_page_default = {
242	/*page_code*/SMS_CONTROL_MODE_PAGE,
243	/*page_length*/sizeof(struct scsi_control_page) - 2,
244	/*rlec*/0,
245	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
246	/*eca_and_aen*/0,
247	/*flags4*/SCP_TAS,
248	/*aen_holdoff_period*/{0, 0},
249	/*busy_timeout_period*/{0, 0},
250	/*extended_selftest_completion_time*/{0, 0}
251};
252
253const static struct scsi_control_page control_page_changeable = {
254	/*page_code*/SMS_CONTROL_MODE_PAGE,
255	/*page_length*/sizeof(struct scsi_control_page) - 2,
256	/*rlec*/SCP_DSENSE,
257	/*queue_flags*/SCP_QUEUE_ALG_MASK,
258	/*eca_and_aen*/SCP_SWP,
259	/*flags4*/0,
260	/*aen_holdoff_period*/{0, 0},
261	/*busy_timeout_period*/{0, 0},
262	/*extended_selftest_completion_time*/{0, 0}
263};
264
265#define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
266
267const static struct scsi_control_ext_page control_ext_page_default = {
268	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
269	/*subpage_code*/0x01,
270	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
271	/*flags*/0,
272	/*prio*/0,
273	/*max_sense*/0
274};
275
276const static struct scsi_control_ext_page control_ext_page_changeable = {
277	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
278	/*subpage_code*/0x01,
279	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
280	/*flags*/0,
281	/*prio*/0,
282	/*max_sense*/0
283};
284
285const static struct scsi_info_exceptions_page ie_page_default = {
286	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
287	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
288	/*info_flags*/SIEP_FLAGS_DEXCPT,
289	/*mrie*/0,
290	/*interval_timer*/{0, 0, 0, 0},
291	/*report_count*/{0, 0, 0, 0}
292};
293
294const static struct scsi_info_exceptions_page ie_page_changeable = {
295	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
296	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
297	/*info_flags*/0,
298	/*mrie*/0,
299	/*interval_timer*/{0, 0, 0, 0},
300	/*report_count*/{0, 0, 0, 0}
301};
302
303#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
304
305const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307	/*subpage_code*/0x02,
308	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309	/*flags*/0,
310	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311	/*descr*/{}},
312	{{/*flags*/0,
313	  /*resource*/0x01,
314	  /*reserved*/{0, 0},
315	  /*count*/{0, 0, 0, 0}},
316	 {/*flags*/0,
317	  /*resource*/0x02,
318	  /*reserved*/{0, 0},
319	  /*count*/{0, 0, 0, 0}},
320	 {/*flags*/0,
321	  /*resource*/0xf1,
322	  /*reserved*/{0, 0},
323	  /*count*/{0, 0, 0, 0}},
324	 {/*flags*/0,
325	  /*resource*/0xf2,
326	  /*reserved*/{0, 0},
327	  /*count*/{0, 0, 0, 0}}
328	}
329};
330
331const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333	/*subpage_code*/0x02,
334	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335	/*flags*/0,
336	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337	/*descr*/{}},
338	{{/*flags*/0,
339	  /*resource*/0,
340	  /*reserved*/{0, 0},
341	  /*count*/{0, 0, 0, 0}},
342	 {/*flags*/0,
343	  /*resource*/0,
344	  /*reserved*/{0, 0},
345	  /*count*/{0, 0, 0, 0}},
346	 {/*flags*/0,
347	  /*resource*/0,
348	  /*reserved*/{0, 0},
349	  /*count*/{0, 0, 0, 0}},
350	 {/*flags*/0,
351	  /*resource*/0,
352	  /*reserved*/{0, 0},
353	  /*count*/{0, 0, 0, 0}}
354	}
355};
356
357const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358	/*page_code*/SMS_CDDVD_CAPS_PAGE,
359	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360	/*caps1*/0x3f,
361	/*caps2*/0x00,
362	/*caps3*/0xf0,
363	/*caps4*/0x00,
364	/*caps5*/0x29,
365	/*caps6*/0x00,
366	/*obsolete*/{0, 0},
367	/*nvol_levels*/{0, 0},
368	/*buffer_size*/{8, 0},
369	/*obsolete2*/{0, 0},
370	/*reserved*/0,
371	/*digital*/0,
372	/*obsolete3*/0,
373	/*copy_management*/0,
374	/*reserved2*/0,
375	/*rotation_control*/0,
376	/*cur_write_speed*/0,
377	/*num_speed_descr*/0,
378};
379
380const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381	/*page_code*/SMS_CDDVD_CAPS_PAGE,
382	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383	/*caps1*/0,
384	/*caps2*/0,
385	/*caps3*/0,
386	/*caps4*/0,
387	/*caps5*/0,
388	/*caps6*/0,
389	/*obsolete*/{0, 0},
390	/*nvol_levels*/{0, 0},
391	/*buffer_size*/{0, 0},
392	/*obsolete2*/{0, 0},
393	/*reserved*/0,
394	/*digital*/0,
395	/*obsolete3*/0,
396	/*copy_management*/0,
397	/*reserved2*/0,
398	/*rotation_control*/0,
399	/*cur_write_speed*/0,
400	/*num_speed_descr*/0,
401};
402
403SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404static int worker_threads = -1;
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) >= CTL_MAX_LUNS)
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 i, 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		for (i = 0; i < CTL_MAX_LUNS; i++) {
2916			lun = softc->ctl_luns[i];
2917
2918			if ((lun == NULL)
2919			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2920				continue;
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 %d port %d iid %d key "
2929					       "%#jx\n", i, j, k,
2930					       (uintmax_t)lun->pr_keys[j][k]);
2931				}
2932			}
2933		}
2934		printf("CTL Persistent Reservation information end\n");
2935		printf("CTL Ports:\n");
2936		STAILQ_FOREACH(port, &softc->port_list, links) {
2937			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2938			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2939			       port->frontend->name, port->port_type,
2940			       port->physical_port, port->virtual_port,
2941			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2942			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2943				if (port->wwpn_iid[j].in_use == 0 &&
2944				    port->wwpn_iid[j].wwpn == 0 &&
2945				    port->wwpn_iid[j].name == NULL)
2946					continue;
2947
2948				printf("    iid %u use %d WWPN %#jx '%s'\n",
2949				    j, port->wwpn_iid[j].in_use,
2950				    (uintmax_t)port->wwpn_iid[j].wwpn,
2951				    port->wwpn_iid[j].name);
2952			}
2953		}
2954		printf("CTL Port information end\n");
2955		mtx_unlock(&softc->ctl_lock);
2956		/*
2957		 * XXX KDM calling this without a lock.  We'd likely want
2958		 * to drop the lock before calling the frontend's dump
2959		 * routine anyway.
2960		 */
2961		printf("CTL Frontends:\n");
2962		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2963			printf("  Frontend '%s'\n", fe->name);
2964			if (fe->fe_dump != NULL)
2965				fe->fe_dump();
2966		}
2967		printf("CTL Frontend information end\n");
2968		break;
2969	}
2970	case CTL_LUN_REQ: {
2971		struct ctl_lun_req *lun_req;
2972		struct ctl_backend_driver *backend;
2973
2974		lun_req = (struct ctl_lun_req *)addr;
2975
2976		backend = ctl_backend_find(lun_req->backend);
2977		if (backend == NULL) {
2978			lun_req->status = CTL_LUN_ERROR;
2979			snprintf(lun_req->error_str,
2980				 sizeof(lun_req->error_str),
2981				 "Backend \"%s\" not found.",
2982				 lun_req->backend);
2983			break;
2984		}
2985		if (lun_req->num_be_args > 0) {
2986			lun_req->kern_be_args = ctl_copyin_args(
2987				lun_req->num_be_args,
2988				lun_req->be_args,
2989				lun_req->error_str,
2990				sizeof(lun_req->error_str));
2991			if (lun_req->kern_be_args == NULL) {
2992				lun_req->status = CTL_LUN_ERROR;
2993				break;
2994			}
2995		}
2996
2997		retval = backend->ioctl(dev, cmd, addr, flag, td);
2998
2999		if (lun_req->num_be_args > 0) {
3000			ctl_copyout_args(lun_req->num_be_args,
3001				      lun_req->kern_be_args);
3002			ctl_free_args(lun_req->num_be_args,
3003				      lun_req->kern_be_args);
3004		}
3005		break;
3006	}
3007	case CTL_LUN_LIST: {
3008		struct sbuf *sb;
3009		struct ctl_lun_list *list;
3010		struct ctl_option *opt;
3011
3012		list = (struct ctl_lun_list *)addr;
3013
3014		/*
3015		 * Allocate a fixed length sbuf here, based on the length
3016		 * of the user's buffer.  We could allocate an auto-extending
3017		 * buffer, and then tell the user how much larger our
3018		 * amount of data is than his buffer, but that presents
3019		 * some problems:
3020		 *
3021		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3022		 *     we can't hold a lock while calling them with an
3023		 *     auto-extending buffer.
3024 		 *
3025		 * 2.  There is not currently a LUN reference counting
3026		 *     mechanism, outside of outstanding transactions on
3027		 *     the LUN's OOA queue.  So a LUN could go away on us
3028		 *     while we're getting the LUN number, backend-specific
3029		 *     information, etc.  Thus, given the way things
3030		 *     currently work, we need to hold the CTL lock while
3031		 *     grabbing LUN information.
3032		 *
3033		 * So, from the user's standpoint, the best thing to do is
3034		 * allocate what he thinks is a reasonable buffer length,
3035		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3036		 * double the buffer length and try again.  (And repeat
3037		 * that until he succeeds.)
3038		 */
3039		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3040		if (sb == NULL) {
3041			list->status = CTL_LUN_LIST_ERROR;
3042			snprintf(list->error_str, sizeof(list->error_str),
3043				 "Unable to allocate %d bytes for LUN list",
3044				 list->alloc_len);
3045			break;
3046		}
3047
3048		sbuf_printf(sb, "<ctllunlist>\n");
3049
3050		mtx_lock(&softc->ctl_lock);
3051		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3052			mtx_lock(&lun->lun_lock);
3053			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3054					     (uintmax_t)lun->lun);
3055
3056			/*
3057			 * Bail out as soon as we see that we've overfilled
3058			 * the buffer.
3059			 */
3060			if (retval != 0)
3061				break;
3062
3063			retval = sbuf_printf(sb, "\t<backend_type>%s"
3064					     "</backend_type>\n",
3065					     (lun->backend == NULL) ?  "none" :
3066					     lun->backend->name);
3067
3068			if (retval != 0)
3069				break;
3070
3071			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3072					     lun->be_lun->lun_type);
3073
3074			if (retval != 0)
3075				break;
3076
3077			if (lun->backend == NULL) {
3078				retval = sbuf_printf(sb, "</lun>\n");
3079				if (retval != 0)
3080					break;
3081				continue;
3082			}
3083
3084			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3085					     (lun->be_lun->maxlba > 0) ?
3086					     lun->be_lun->maxlba + 1 : 0);
3087
3088			if (retval != 0)
3089				break;
3090
3091			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3092					     lun->be_lun->blocksize);
3093
3094			if (retval != 0)
3095				break;
3096
3097			retval = sbuf_printf(sb, "\t<serial_number>");
3098
3099			if (retval != 0)
3100				break;
3101
3102			retval = ctl_sbuf_printf_esc(sb,
3103			    lun->be_lun->serial_num,
3104			    sizeof(lun->be_lun->serial_num));
3105
3106			if (retval != 0)
3107				break;
3108
3109			retval = sbuf_printf(sb, "</serial_number>\n");
3110
3111			if (retval != 0)
3112				break;
3113
3114			retval = sbuf_printf(sb, "\t<device_id>");
3115
3116			if (retval != 0)
3117				break;
3118
3119			retval = ctl_sbuf_printf_esc(sb,
3120			    lun->be_lun->device_id,
3121			    sizeof(lun->be_lun->device_id));
3122
3123			if (retval != 0)
3124				break;
3125
3126			retval = sbuf_printf(sb, "</device_id>\n");
3127
3128			if (retval != 0)
3129				break;
3130
3131			if (lun->backend->lun_info != NULL) {
3132				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3133				if (retval != 0)
3134					break;
3135			}
3136			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3137				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3138				    opt->name, opt->value, opt->name);
3139				if (retval != 0)
3140					break;
3141			}
3142
3143			retval = sbuf_printf(sb, "</lun>\n");
3144
3145			if (retval != 0)
3146				break;
3147			mtx_unlock(&lun->lun_lock);
3148		}
3149		if (lun != NULL)
3150			mtx_unlock(&lun->lun_lock);
3151		mtx_unlock(&softc->ctl_lock);
3152
3153		if ((retval != 0)
3154		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3155			retval = 0;
3156			sbuf_delete(sb);
3157			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3158			snprintf(list->error_str, sizeof(list->error_str),
3159				 "Out of space, %d bytes is too small",
3160				 list->alloc_len);
3161			break;
3162		}
3163
3164		sbuf_finish(sb);
3165
3166		retval = copyout(sbuf_data(sb), list->lun_xml,
3167				 sbuf_len(sb) + 1);
3168
3169		list->fill_len = sbuf_len(sb) + 1;
3170		list->status = CTL_LUN_LIST_OK;
3171		sbuf_delete(sb);
3172		break;
3173	}
3174	case CTL_ISCSI: {
3175		struct ctl_iscsi *ci;
3176		struct ctl_frontend *fe;
3177
3178		ci = (struct ctl_iscsi *)addr;
3179
3180		fe = ctl_frontend_find("iscsi");
3181		if (fe == NULL) {
3182			ci->status = CTL_ISCSI_ERROR;
3183			snprintf(ci->error_str, sizeof(ci->error_str),
3184			    "Frontend \"iscsi\" not found.");
3185			break;
3186		}
3187
3188		retval = fe->ioctl(dev, cmd, addr, flag, td);
3189		break;
3190	}
3191	case CTL_PORT_REQ: {
3192		struct ctl_req *req;
3193		struct ctl_frontend *fe;
3194
3195		req = (struct ctl_req *)addr;
3196
3197		fe = ctl_frontend_find(req->driver);
3198		if (fe == NULL) {
3199			req->status = CTL_LUN_ERROR;
3200			snprintf(req->error_str, sizeof(req->error_str),
3201			    "Frontend \"%s\" not found.", req->driver);
3202			break;
3203		}
3204		if (req->num_args > 0) {
3205			req->kern_args = ctl_copyin_args(req->num_args,
3206			    req->args, req->error_str, sizeof(req->error_str));
3207			if (req->kern_args == NULL) {
3208				req->status = CTL_LUN_ERROR;
3209				break;
3210			}
3211		}
3212
3213		if (fe->ioctl)
3214			retval = fe->ioctl(dev, cmd, addr, flag, td);
3215		else
3216			retval = ENODEV;
3217
3218		if (req->num_args > 0) {
3219			ctl_copyout_args(req->num_args, req->kern_args);
3220			ctl_free_args(req->num_args, req->kern_args);
3221		}
3222		break;
3223	}
3224	case CTL_PORT_LIST: {
3225		struct sbuf *sb;
3226		struct ctl_port *port;
3227		struct ctl_lun_list *list;
3228		struct ctl_option *opt;
3229		int j;
3230		uint32_t plun;
3231
3232		list = (struct ctl_lun_list *)addr;
3233
3234		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3235		if (sb == NULL) {
3236			list->status = CTL_LUN_LIST_ERROR;
3237			snprintf(list->error_str, sizeof(list->error_str),
3238				 "Unable to allocate %d bytes for LUN list",
3239				 list->alloc_len);
3240			break;
3241		}
3242
3243		sbuf_printf(sb, "<ctlportlist>\n");
3244
3245		mtx_lock(&softc->ctl_lock);
3246		STAILQ_FOREACH(port, &softc->port_list, links) {
3247			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3248					     (uintmax_t)port->targ_port);
3249
3250			/*
3251			 * Bail out as soon as we see that we've overfilled
3252			 * the buffer.
3253			 */
3254			if (retval != 0)
3255				break;
3256
3257			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3258			    "</frontend_type>\n", port->frontend->name);
3259			if (retval != 0)
3260				break;
3261
3262			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3263					     port->port_type);
3264			if (retval != 0)
3265				break;
3266
3267			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3268			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3269			if (retval != 0)
3270				break;
3271
3272			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3273			    port->port_name);
3274			if (retval != 0)
3275				break;
3276
3277			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3278			    port->physical_port);
3279			if (retval != 0)
3280				break;
3281
3282			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3283			    port->virtual_port);
3284			if (retval != 0)
3285				break;
3286
3287			if (port->target_devid != NULL) {
3288				sbuf_printf(sb, "\t<target>");
3289				ctl_id_sbuf(port->target_devid, sb);
3290				sbuf_printf(sb, "</target>\n");
3291			}
3292
3293			if (port->port_devid != NULL) {
3294				sbuf_printf(sb, "\t<port>");
3295				ctl_id_sbuf(port->port_devid, sb);
3296				sbuf_printf(sb, "</port>\n");
3297			}
3298
3299			if (port->port_info != NULL) {
3300				retval = port->port_info(port->onoff_arg, sb);
3301				if (retval != 0)
3302					break;
3303			}
3304			STAILQ_FOREACH(opt, &port->options, links) {
3305				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3306				    opt->name, opt->value, opt->name);
3307				if (retval != 0)
3308					break;
3309			}
3310
3311			if (port->lun_map != NULL) {
3312				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3313				for (j = 0; j < CTL_MAX_LUNS; j++) {
3314					plun = ctl_lun_map_from_port(port, j);
3315					if (plun >= CTL_MAX_LUNS)
3316						continue;
3317					sbuf_printf(sb,
3318					    "\t<lun id=\"%u\">%u</lun>\n",
3319					    j, plun);
3320				}
3321			}
3322
3323			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3324				if (port->wwpn_iid[j].in_use == 0 ||
3325				    (port->wwpn_iid[j].wwpn == 0 &&
3326				     port->wwpn_iid[j].name == NULL))
3327					continue;
3328
3329				if (port->wwpn_iid[j].name != NULL)
3330					retval = sbuf_printf(sb,
3331					    "\t<initiator id=\"%u\">%s</initiator>\n",
3332					    j, port->wwpn_iid[j].name);
3333				else
3334					retval = sbuf_printf(sb,
3335					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3336					    j, port->wwpn_iid[j].wwpn);
3337				if (retval != 0)
3338					break;
3339			}
3340			if (retval != 0)
3341				break;
3342
3343			retval = sbuf_printf(sb, "</targ_port>\n");
3344			if (retval != 0)
3345				break;
3346		}
3347		mtx_unlock(&softc->ctl_lock);
3348
3349		if ((retval != 0)
3350		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3351			retval = 0;
3352			sbuf_delete(sb);
3353			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3354			snprintf(list->error_str, sizeof(list->error_str),
3355				 "Out of space, %d bytes is too small",
3356				 list->alloc_len);
3357			break;
3358		}
3359
3360		sbuf_finish(sb);
3361
3362		retval = copyout(sbuf_data(sb), list->lun_xml,
3363				 sbuf_len(sb) + 1);
3364
3365		list->fill_len = sbuf_len(sb) + 1;
3366		list->status = CTL_LUN_LIST_OK;
3367		sbuf_delete(sb);
3368		break;
3369	}
3370	case CTL_LUN_MAP: {
3371		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3372		struct ctl_port *port;
3373
3374		mtx_lock(&softc->ctl_lock);
3375		if (lm->port < softc->port_min ||
3376		    lm->port >= softc->port_max ||
3377		    (port = softc->ctl_ports[lm->port]) == NULL) {
3378			mtx_unlock(&softc->ctl_lock);
3379			return (ENXIO);
3380		}
3381		if (port->status & CTL_PORT_STATUS_ONLINE) {
3382			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3383				if (ctl_lun_map_to_port(port, lun->lun) >=
3384				    CTL_MAX_LUNS)
3385					continue;
3386				mtx_lock(&lun->lun_lock);
3387				ctl_est_ua_port(lun, lm->port, -1,
3388				    CTL_UA_LUN_CHANGE);
3389				mtx_unlock(&lun->lun_lock);
3390			}
3391		}
3392		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3393		if (lm->plun < CTL_MAX_LUNS) {
3394			if (lm->lun == UINT32_MAX)
3395				retval = ctl_lun_map_unset(port, lm->plun);
3396			else if (lm->lun < CTL_MAX_LUNS &&
3397			    softc->ctl_luns[lm->lun] != NULL)
3398				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3399			else
3400				return (ENXIO);
3401		} else if (lm->plun == UINT32_MAX) {
3402			if (lm->lun == UINT32_MAX)
3403				retval = ctl_lun_map_deinit(port);
3404			else
3405				retval = ctl_lun_map_init(port);
3406		} else
3407			return (ENXIO);
3408		if (port->status & CTL_PORT_STATUS_ONLINE)
3409			ctl_isc_announce_port(port);
3410		break;
3411	}
3412	default: {
3413		/* XXX KDM should we fix this? */
3414#if 0
3415		struct ctl_backend_driver *backend;
3416		unsigned int type;
3417		int found;
3418
3419		found = 0;
3420
3421		/*
3422		 * We encode the backend type as the ioctl type for backend
3423		 * ioctls.  So parse it out here, and then search for a
3424		 * backend of this type.
3425		 */
3426		type = _IOC_TYPE(cmd);
3427
3428		STAILQ_FOREACH(backend, &softc->be_list, links) {
3429			if (backend->type == type) {
3430				found = 1;
3431				break;
3432			}
3433		}
3434		if (found == 0) {
3435			printf("ctl: unknown ioctl command %#lx or backend "
3436			       "%d\n", cmd, type);
3437			retval = EINVAL;
3438			break;
3439		}
3440		retval = backend->ioctl(dev, cmd, addr, flag, td);
3441#endif
3442		retval = ENOTTY;
3443		break;
3444	}
3445	}
3446	return (retval);
3447}
3448
3449uint32_t
3450ctl_get_initindex(struct ctl_nexus *nexus)
3451{
3452	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3453}
3454
3455int
3456ctl_lun_map_init(struct ctl_port *port)
3457{
3458	struct ctl_softc *softc = port->ctl_softc;
3459	struct ctl_lun *lun;
3460	uint32_t i;
3461
3462	if (port->lun_map == NULL)
3463		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3464		    M_CTL, M_NOWAIT);
3465	if (port->lun_map == NULL)
3466		return (ENOMEM);
3467	for (i = 0; i < CTL_MAX_LUNS; i++)
3468		port->lun_map[i] = UINT32_MAX;
3469	if (port->status & CTL_PORT_STATUS_ONLINE) {
3470		if (port->lun_disable != NULL) {
3471			STAILQ_FOREACH(lun, &softc->lun_list, links)
3472				port->lun_disable(port->targ_lun_arg, lun->lun);
3473		}
3474		ctl_isc_announce_port(port);
3475	}
3476	return (0);
3477}
3478
3479int
3480ctl_lun_map_deinit(struct ctl_port *port)
3481{
3482	struct ctl_softc *softc = port->ctl_softc;
3483	struct ctl_lun *lun;
3484
3485	if (port->lun_map == NULL)
3486		return (0);
3487	free(port->lun_map, M_CTL);
3488	port->lun_map = NULL;
3489	if (port->status & CTL_PORT_STATUS_ONLINE) {
3490		if (port->lun_enable != NULL) {
3491			STAILQ_FOREACH(lun, &softc->lun_list, links)
3492				port->lun_enable(port->targ_lun_arg, lun->lun);
3493		}
3494		ctl_isc_announce_port(port);
3495	}
3496	return (0);
3497}
3498
3499int
3500ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3501{
3502	int status;
3503	uint32_t old;
3504
3505	if (port->lun_map == NULL) {
3506		status = ctl_lun_map_init(port);
3507		if (status != 0)
3508			return (status);
3509	}
3510	old = port->lun_map[plun];
3511	port->lun_map[plun] = glun;
3512	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3513		if (port->lun_enable != NULL)
3514			port->lun_enable(port->targ_lun_arg, plun);
3515		ctl_isc_announce_port(port);
3516	}
3517	return (0);
3518}
3519
3520int
3521ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3522{
3523	uint32_t old;
3524
3525	if (port->lun_map == NULL)
3526		return (0);
3527	old = port->lun_map[plun];
3528	port->lun_map[plun] = UINT32_MAX;
3529	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3530		if (port->lun_disable != NULL)
3531			port->lun_disable(port->targ_lun_arg, plun);
3532		ctl_isc_announce_port(port);
3533	}
3534	return (0);
3535}
3536
3537uint32_t
3538ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3539{
3540
3541	if (port == NULL)
3542		return (UINT32_MAX);
3543	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3544		return (lun_id);
3545	return (port->lun_map[lun_id]);
3546}
3547
3548uint32_t
3549ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3550{
3551	uint32_t i;
3552
3553	if (port == NULL)
3554		return (UINT32_MAX);
3555	if (port->lun_map == NULL)
3556		return (lun_id);
3557	for (i = 0; i < CTL_MAX_LUNS; i++) {
3558		if (port->lun_map[i] == lun_id)
3559			return (i);
3560	}
3561	return (UINT32_MAX);
3562}
3563
3564uint32_t
3565ctl_decode_lun(uint64_t encoded)
3566{
3567	uint8_t lun[8];
3568	uint32_t result = 0xffffffff;
3569
3570	be64enc(lun, encoded);
3571	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3572	case RPL_LUNDATA_ATYP_PERIPH:
3573		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3574		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3575			result = lun[1];
3576		break;
3577	case RPL_LUNDATA_ATYP_FLAT:
3578		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3579		    lun[6] == 0 && lun[7] == 0)
3580			result = ((lun[0] & 0x3f) << 8) + lun[1];
3581		break;
3582	case RPL_LUNDATA_ATYP_EXTLUN:
3583		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3584		case 0x02:
3585			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3586			case 0x00:
3587				result = lun[1];
3588				break;
3589			case 0x10:
3590				result = (lun[1] << 16) + (lun[2] << 8) +
3591				    lun[3];
3592				break;
3593			case 0x20:
3594				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3595					result = (lun[2] << 24) +
3596					    (lun[3] << 16) + (lun[4] << 8) +
3597					    lun[5];
3598				break;
3599			}
3600			break;
3601		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3602			result = 0xffffffff;
3603			break;
3604		}
3605		break;
3606	}
3607	return (result);
3608}
3609
3610uint64_t
3611ctl_encode_lun(uint32_t decoded)
3612{
3613	uint64_t l = decoded;
3614
3615	if (l <= 0xff)
3616		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3617	if (l <= 0x3fff)
3618		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3619	if (l <= 0xffffff)
3620		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3621		    (l << 32));
3622	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3623}
3624
3625static struct ctl_port *
3626ctl_io_port(struct ctl_io_hdr *io_hdr)
3627{
3628
3629	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3630}
3631
3632int
3633ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3634{
3635	int i;
3636
3637	for (i = first; i < last; i++) {
3638		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3639			return (i);
3640	}
3641	return (-1);
3642}
3643
3644int
3645ctl_set_mask(uint32_t *mask, uint32_t bit)
3646{
3647	uint32_t chunk, piece;
3648
3649	chunk = bit >> 5;
3650	piece = bit % (sizeof(uint32_t) * 8);
3651
3652	if ((mask[chunk] & (1 << piece)) != 0)
3653		return (-1);
3654	else
3655		mask[chunk] |= (1 << piece);
3656
3657	return (0);
3658}
3659
3660int
3661ctl_clear_mask(uint32_t *mask, uint32_t bit)
3662{
3663	uint32_t chunk, piece;
3664
3665	chunk = bit >> 5;
3666	piece = bit % (sizeof(uint32_t) * 8);
3667
3668	if ((mask[chunk] & (1 << piece)) == 0)
3669		return (-1);
3670	else
3671		mask[chunk] &= ~(1 << piece);
3672
3673	return (0);
3674}
3675
3676int
3677ctl_is_set(uint32_t *mask, uint32_t bit)
3678{
3679	uint32_t chunk, piece;
3680
3681	chunk = bit >> 5;
3682	piece = bit % (sizeof(uint32_t) * 8);
3683
3684	if ((mask[chunk] & (1 << piece)) == 0)
3685		return (0);
3686	else
3687		return (1);
3688}
3689
3690static uint64_t
3691ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3692{
3693	uint64_t *t;
3694
3695	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3696	if (t == NULL)
3697		return (0);
3698	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3699}
3700
3701static void
3702ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3703{
3704	uint64_t *t;
3705
3706	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3707	if (t == NULL)
3708		return;
3709	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3710}
3711
3712static void
3713ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3714{
3715	uint64_t *p;
3716	u_int i;
3717
3718	i = residx/CTL_MAX_INIT_PER_PORT;
3719	if (lun->pr_keys[i] != NULL)
3720		return;
3721	mtx_unlock(&lun->lun_lock);
3722	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3723	    M_WAITOK | M_ZERO);
3724	mtx_lock(&lun->lun_lock);
3725	if (lun->pr_keys[i] == NULL)
3726		lun->pr_keys[i] = p;
3727	else
3728		free(p, M_CTL);
3729}
3730
3731static void
3732ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3733{
3734	uint64_t *t;
3735
3736	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3737	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3738	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3739}
3740
3741/*
3742 * ctl_softc, pool_name, total_ctl_io are passed in.
3743 * npool is passed out.
3744 */
3745int
3746ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3747		uint32_t total_ctl_io, void **npool)
3748{
3749#ifdef IO_POOLS
3750	struct ctl_io_pool *pool;
3751
3752	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3753					    M_NOWAIT | M_ZERO);
3754	if (pool == NULL)
3755		return (ENOMEM);
3756
3757	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3758	pool->ctl_softc = ctl_softc;
3759	pool->zone = uma_zsecond_create(pool->name, NULL,
3760	    NULL, NULL, NULL, ctl_softc->io_zone);
3761	/* uma_prealloc(pool->zone, total_ctl_io); */
3762
3763	*npool = pool;
3764#else
3765	*npool = ctl_softc->io_zone;
3766#endif
3767	return (0);
3768}
3769
3770void
3771ctl_pool_free(struct ctl_io_pool *pool)
3772{
3773
3774	if (pool == NULL)
3775		return;
3776
3777#ifdef IO_POOLS
3778	uma_zdestroy(pool->zone);
3779	free(pool, M_CTL);
3780#endif
3781}
3782
3783union ctl_io *
3784ctl_alloc_io(void *pool_ref)
3785{
3786	union ctl_io *io;
3787#ifdef IO_POOLS
3788	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3789
3790	io = uma_zalloc(pool->zone, M_WAITOK);
3791#else
3792	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3793#endif
3794	if (io != NULL)
3795		io->io_hdr.pool = pool_ref;
3796	return (io);
3797}
3798
3799union ctl_io *
3800ctl_alloc_io_nowait(void *pool_ref)
3801{
3802	union ctl_io *io;
3803#ifdef IO_POOLS
3804	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3805
3806	io = uma_zalloc(pool->zone, M_NOWAIT);
3807#else
3808	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3809#endif
3810	if (io != NULL)
3811		io->io_hdr.pool = pool_ref;
3812	return (io);
3813}
3814
3815void
3816ctl_free_io(union ctl_io *io)
3817{
3818#ifdef IO_POOLS
3819	struct ctl_io_pool *pool;
3820#endif
3821
3822	if (io == NULL)
3823		return;
3824
3825#ifdef IO_POOLS
3826	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3827	uma_zfree(pool->zone, io);
3828#else
3829	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3830#endif
3831}
3832
3833void
3834ctl_zero_io(union ctl_io *io)
3835{
3836	void *pool_ref;
3837
3838	if (io == NULL)
3839		return;
3840
3841	/*
3842	 * May need to preserve linked list pointers at some point too.
3843	 */
3844	pool_ref = io->io_hdr.pool;
3845	memset(io, 0, sizeof(*io));
3846	io->io_hdr.pool = pool_ref;
3847}
3848
3849int
3850ctl_expand_number(const char *buf, uint64_t *num)
3851{
3852	char *endptr;
3853	uint64_t number;
3854	unsigned shift;
3855
3856	number = strtoq(buf, &endptr, 0);
3857
3858	switch (tolower((unsigned char)*endptr)) {
3859	case 'e':
3860		shift = 60;
3861		break;
3862	case 'p':
3863		shift = 50;
3864		break;
3865	case 't':
3866		shift = 40;
3867		break;
3868	case 'g':
3869		shift = 30;
3870		break;
3871	case 'm':
3872		shift = 20;
3873		break;
3874	case 'k':
3875		shift = 10;
3876		break;
3877	case 'b':
3878	case '\0': /* No unit. */
3879		*num = number;
3880		return (0);
3881	default:
3882		/* Unrecognized unit. */
3883		return (-1);
3884	}
3885
3886	if ((number << shift) >> shift != number) {
3887		/* Overflow */
3888		return (-1);
3889	}
3890	*num = number << shift;
3891	return (0);
3892}
3893
3894
3895/*
3896 * This routine could be used in the future to load default and/or saved
3897 * mode page parameters for a particuar lun.
3898 */
3899static int
3900ctl_init_page_index(struct ctl_lun *lun)
3901{
3902	int i, page_code;
3903	struct ctl_page_index *page_index;
3904	const char *value;
3905	uint64_t ival;
3906
3907	memcpy(&lun->mode_pages.index, page_index_template,
3908	       sizeof(page_index_template));
3909
3910	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3911
3912		page_index = &lun->mode_pages.index[i];
3913		if (lun->be_lun->lun_type == T_DIRECT &&
3914		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3915			continue;
3916		if (lun->be_lun->lun_type == T_PROCESSOR &&
3917		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3918			continue;
3919		if (lun->be_lun->lun_type == T_CDROM &&
3920		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3921			continue;
3922
3923		page_code = page_index->page_code & SMPH_PC_MASK;
3924		switch (page_code) {
3925		case SMS_RW_ERROR_RECOVERY_PAGE: {
3926			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3927			    ("subpage %#x for page %#x is incorrect!",
3928			    page_index->subpage, page_code));
3929			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3930			       &rw_er_page_default,
3931			       sizeof(rw_er_page_default));
3932			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3933			       &rw_er_page_changeable,
3934			       sizeof(rw_er_page_changeable));
3935			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3936			       &rw_er_page_default,
3937			       sizeof(rw_er_page_default));
3938			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3939			       &rw_er_page_default,
3940			       sizeof(rw_er_page_default));
3941			page_index->page_data =
3942				(uint8_t *)lun->mode_pages.rw_er_page;
3943			break;
3944		}
3945		case SMS_FORMAT_DEVICE_PAGE: {
3946			struct scsi_format_page *format_page;
3947
3948			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3949			    ("subpage %#x for page %#x is incorrect!",
3950			    page_index->subpage, page_code));
3951
3952			/*
3953			 * Sectors per track are set above.  Bytes per
3954			 * sector need to be set here on a per-LUN basis.
3955			 */
3956			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3957			       &format_page_default,
3958			       sizeof(format_page_default));
3959			memcpy(&lun->mode_pages.format_page[
3960			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3961			       sizeof(format_page_changeable));
3962			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3963			       &format_page_default,
3964			       sizeof(format_page_default));
3965			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3966			       &format_page_default,
3967			       sizeof(format_page_default));
3968
3969			format_page = &lun->mode_pages.format_page[
3970				CTL_PAGE_CURRENT];
3971			scsi_ulto2b(lun->be_lun->blocksize,
3972				    format_page->bytes_per_sector);
3973
3974			format_page = &lun->mode_pages.format_page[
3975				CTL_PAGE_DEFAULT];
3976			scsi_ulto2b(lun->be_lun->blocksize,
3977				    format_page->bytes_per_sector);
3978
3979			format_page = &lun->mode_pages.format_page[
3980				CTL_PAGE_SAVED];
3981			scsi_ulto2b(lun->be_lun->blocksize,
3982				    format_page->bytes_per_sector);
3983
3984			page_index->page_data =
3985				(uint8_t *)lun->mode_pages.format_page;
3986			break;
3987		}
3988		case SMS_RIGID_DISK_PAGE: {
3989			struct scsi_rigid_disk_page *rigid_disk_page;
3990			uint32_t sectors_per_cylinder;
3991			uint64_t cylinders;
3992#ifndef	__XSCALE__
3993			int shift;
3994#endif /* !__XSCALE__ */
3995
3996			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3997			    ("subpage %#x for page %#x is incorrect!",
3998			    page_index->subpage, page_code));
3999
4000			/*
4001			 * Rotation rate and sectors per track are set
4002			 * above.  We calculate the cylinders here based on
4003			 * capacity.  Due to the number of heads and
4004			 * sectors per track we're using, smaller arrays
4005			 * may turn out to have 0 cylinders.  Linux and
4006			 * FreeBSD don't pay attention to these mode pages
4007			 * to figure out capacity, but Solaris does.  It
4008			 * seems to deal with 0 cylinders just fine, and
4009			 * works out a fake geometry based on the capacity.
4010			 */
4011			memcpy(&lun->mode_pages.rigid_disk_page[
4012			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4013			       sizeof(rigid_disk_page_default));
4014			memcpy(&lun->mode_pages.rigid_disk_page[
4015			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4016			       sizeof(rigid_disk_page_changeable));
4017
4018			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4019				CTL_DEFAULT_HEADS;
4020
4021			/*
4022			 * The divide method here will be more accurate,
4023			 * probably, but results in floating point being
4024			 * used in the kernel on i386 (__udivdi3()).  On the
4025			 * XScale, though, __udivdi3() is implemented in
4026			 * software.
4027			 *
4028			 * The shift method for cylinder calculation is
4029			 * accurate if sectors_per_cylinder is a power of
4030			 * 2.  Otherwise it might be slightly off -- you
4031			 * might have a bit of a truncation problem.
4032			 */
4033#ifdef	__XSCALE__
4034			cylinders = (lun->be_lun->maxlba + 1) /
4035				sectors_per_cylinder;
4036#else
4037			for (shift = 31; shift > 0; shift--) {
4038				if (sectors_per_cylinder & (1 << shift))
4039					break;
4040			}
4041			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4042#endif
4043
4044			/*
4045			 * We've basically got 3 bytes, or 24 bits for the
4046			 * cylinder size in the mode page.  If we're over,
4047			 * just round down to 2^24.
4048			 */
4049			if (cylinders > 0xffffff)
4050				cylinders = 0xffffff;
4051
4052			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4053				CTL_PAGE_DEFAULT];
4054			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4055
4056			if ((value = ctl_get_opt(&lun->be_lun->options,
4057			    "rpm")) != NULL) {
4058				scsi_ulto2b(strtol(value, NULL, 0),
4059				     rigid_disk_page->rotation_rate);
4060			}
4061
4062			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4063			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4064			       sizeof(rigid_disk_page_default));
4065			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4066			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4067			       sizeof(rigid_disk_page_default));
4068
4069			page_index->page_data =
4070				(uint8_t *)lun->mode_pages.rigid_disk_page;
4071			break;
4072		}
4073		case SMS_CACHING_PAGE: {
4074			struct scsi_caching_page *caching_page;
4075
4076			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4077			    ("subpage %#x for page %#x is incorrect!",
4078			    page_index->subpage, page_code));
4079			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4080			       &caching_page_default,
4081			       sizeof(caching_page_default));
4082			memcpy(&lun->mode_pages.caching_page[
4083			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4084			       sizeof(caching_page_changeable));
4085			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4086			       &caching_page_default,
4087			       sizeof(caching_page_default));
4088			caching_page = &lun->mode_pages.caching_page[
4089			    CTL_PAGE_SAVED];
4090			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4091			if (value != NULL && strcmp(value, "off") == 0)
4092				caching_page->flags1 &= ~SCP_WCE;
4093			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4094			if (value != NULL && strcmp(value, "off") == 0)
4095				caching_page->flags1 |= SCP_RCD;
4096			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4097			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4098			       sizeof(caching_page_default));
4099			page_index->page_data =
4100				(uint8_t *)lun->mode_pages.caching_page;
4101			break;
4102		}
4103		case SMS_CONTROL_MODE_PAGE: {
4104			switch (page_index->subpage) {
4105			case SMS_SUBPAGE_PAGE_0: {
4106				struct scsi_control_page *control_page;
4107
4108				memcpy(&lun->mode_pages.control_page[
4109				    CTL_PAGE_DEFAULT],
4110				       &control_page_default,
4111				       sizeof(control_page_default));
4112				memcpy(&lun->mode_pages.control_page[
4113				    CTL_PAGE_CHANGEABLE],
4114				       &control_page_changeable,
4115				       sizeof(control_page_changeable));
4116				memcpy(&lun->mode_pages.control_page[
4117				    CTL_PAGE_SAVED],
4118				       &control_page_default,
4119				       sizeof(control_page_default));
4120				control_page = &lun->mode_pages.control_page[
4121				    CTL_PAGE_SAVED];
4122				value = ctl_get_opt(&lun->be_lun->options,
4123				    "reordering");
4124				if (value != NULL &&
4125				    strcmp(value, "unrestricted") == 0) {
4126					control_page->queue_flags &=
4127					    ~SCP_QUEUE_ALG_MASK;
4128					control_page->queue_flags |=
4129					    SCP_QUEUE_ALG_UNRESTRICTED;
4130				}
4131				memcpy(&lun->mode_pages.control_page[
4132				    CTL_PAGE_CURRENT],
4133				       &lun->mode_pages.control_page[
4134				    CTL_PAGE_SAVED],
4135				       sizeof(control_page_default));
4136				page_index->page_data =
4137				    (uint8_t *)lun->mode_pages.control_page;
4138				break;
4139			}
4140			case 0x01:
4141				memcpy(&lun->mode_pages.control_ext_page[
4142				    CTL_PAGE_DEFAULT],
4143				       &control_ext_page_default,
4144				       sizeof(control_ext_page_default));
4145				memcpy(&lun->mode_pages.control_ext_page[
4146				    CTL_PAGE_CHANGEABLE],
4147				       &control_ext_page_changeable,
4148				       sizeof(control_ext_page_changeable));
4149				memcpy(&lun->mode_pages.control_ext_page[
4150				    CTL_PAGE_SAVED],
4151				       &control_ext_page_default,
4152				       sizeof(control_ext_page_default));
4153				memcpy(&lun->mode_pages.control_ext_page[
4154				    CTL_PAGE_CURRENT],
4155				       &lun->mode_pages.control_ext_page[
4156				    CTL_PAGE_SAVED],
4157				       sizeof(control_ext_page_default));
4158				page_index->page_data =
4159				    (uint8_t *)lun->mode_pages.control_ext_page;
4160				break;
4161			default:
4162				panic("subpage %#x for page %#x is incorrect!",
4163				      page_index->subpage, page_code);
4164			}
4165			break;
4166		}
4167		case SMS_INFO_EXCEPTIONS_PAGE: {
4168			switch (page_index->subpage) {
4169			case SMS_SUBPAGE_PAGE_0:
4170				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4171				       &ie_page_default,
4172				       sizeof(ie_page_default));
4173				memcpy(&lun->mode_pages.ie_page[
4174				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4175				       sizeof(ie_page_changeable));
4176				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4177				       &ie_page_default,
4178				       sizeof(ie_page_default));
4179				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4180				       &ie_page_default,
4181				       sizeof(ie_page_default));
4182				page_index->page_data =
4183					(uint8_t *)lun->mode_pages.ie_page;
4184				break;
4185			case 0x02: {
4186				struct ctl_logical_block_provisioning_page *page;
4187
4188				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4189				       &lbp_page_default,
4190				       sizeof(lbp_page_default));
4191				memcpy(&lun->mode_pages.lbp_page[
4192				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4193				       sizeof(lbp_page_changeable));
4194				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4195				       &lbp_page_default,
4196				       sizeof(lbp_page_default));
4197				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4198				value = ctl_get_opt(&lun->be_lun->options,
4199				    "avail-threshold");
4200				if (value != NULL &&
4201				    ctl_expand_number(value, &ival) == 0) {
4202					page->descr[0].flags |= SLBPPD_ENABLED |
4203					    SLBPPD_ARMING_DEC;
4204					if (lun->be_lun->blocksize)
4205						ival /= lun->be_lun->blocksize;
4206					else
4207						ival /= 512;
4208					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4209					    page->descr[0].count);
4210				}
4211				value = ctl_get_opt(&lun->be_lun->options,
4212				    "used-threshold");
4213				if (value != NULL &&
4214				    ctl_expand_number(value, &ival) == 0) {
4215					page->descr[1].flags |= SLBPPD_ENABLED |
4216					    SLBPPD_ARMING_INC;
4217					if (lun->be_lun->blocksize)
4218						ival /= lun->be_lun->blocksize;
4219					else
4220						ival /= 512;
4221					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4222					    page->descr[1].count);
4223				}
4224				value = ctl_get_opt(&lun->be_lun->options,
4225				    "pool-avail-threshold");
4226				if (value != NULL &&
4227				    ctl_expand_number(value, &ival) == 0) {
4228					page->descr[2].flags |= SLBPPD_ENABLED |
4229					    SLBPPD_ARMING_DEC;
4230					if (lun->be_lun->blocksize)
4231						ival /= lun->be_lun->blocksize;
4232					else
4233						ival /= 512;
4234					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4235					    page->descr[2].count);
4236				}
4237				value = ctl_get_opt(&lun->be_lun->options,
4238				    "pool-used-threshold");
4239				if (value != NULL &&
4240				    ctl_expand_number(value, &ival) == 0) {
4241					page->descr[3].flags |= SLBPPD_ENABLED |
4242					    SLBPPD_ARMING_INC;
4243					if (lun->be_lun->blocksize)
4244						ival /= lun->be_lun->blocksize;
4245					else
4246						ival /= 512;
4247					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4248					    page->descr[3].count);
4249				}
4250				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4251				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4252				       sizeof(lbp_page_default));
4253				page_index->page_data =
4254					(uint8_t *)lun->mode_pages.lbp_page;
4255				break;
4256			}
4257			default:
4258				panic("subpage %#x for page %#x is incorrect!",
4259				      page_index->subpage, page_code);
4260			}
4261			break;
4262		}
4263		case SMS_CDDVD_CAPS_PAGE:{
4264			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4265			    ("subpage %#x for page %#x is incorrect!",
4266			    page_index->subpage, page_code));
4267			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4268			       &cddvd_page_default,
4269			       sizeof(cddvd_page_default));
4270			memcpy(&lun->mode_pages.cddvd_page[
4271			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4272			       sizeof(cddvd_page_changeable));
4273			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4274			       &cddvd_page_default,
4275			       sizeof(cddvd_page_default));
4276			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4277			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4278			       sizeof(cddvd_page_default));
4279			page_index->page_data =
4280				(uint8_t *)lun->mode_pages.cddvd_page;
4281			break;
4282		}
4283		case SMS_VENDOR_SPECIFIC_PAGE:{
4284			switch (page_index->subpage) {
4285			case DBGCNF_SUBPAGE_CODE: {
4286				memcpy(&lun->mode_pages.debugconf_subpage[
4287				       CTL_PAGE_CURRENT],
4288				       &debugconf_page_default,
4289				       sizeof(debugconf_page_default));
4290				memcpy(&lun->mode_pages.debugconf_subpage[
4291				       CTL_PAGE_CHANGEABLE],
4292				       &debugconf_page_changeable,
4293				       sizeof(debugconf_page_changeable));
4294				memcpy(&lun->mode_pages.debugconf_subpage[
4295				       CTL_PAGE_DEFAULT],
4296				       &debugconf_page_default,
4297				       sizeof(debugconf_page_default));
4298				memcpy(&lun->mode_pages.debugconf_subpage[
4299				       CTL_PAGE_SAVED],
4300				       &debugconf_page_default,
4301				       sizeof(debugconf_page_default));
4302				page_index->page_data =
4303				    (uint8_t *)lun->mode_pages.debugconf_subpage;
4304				break;
4305			}
4306			default:
4307				panic("subpage %#x for page %#x is incorrect!",
4308				      page_index->subpage, page_code);
4309			}
4310			break;
4311		}
4312		default:
4313			panic("invalid page code value %#x", page_code);
4314		}
4315	}
4316
4317	return (CTL_RETVAL_COMPLETE);
4318}
4319
4320static int
4321ctl_init_log_page_index(struct ctl_lun *lun)
4322{
4323	struct ctl_page_index *page_index;
4324	int i, j, k, prev;
4325
4326	memcpy(&lun->log_pages.index, log_page_index_template,
4327	       sizeof(log_page_index_template));
4328
4329	prev = -1;
4330	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4331
4332		page_index = &lun->log_pages.index[i];
4333		if (lun->be_lun->lun_type == T_DIRECT &&
4334		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4335			continue;
4336		if (lun->be_lun->lun_type == T_PROCESSOR &&
4337		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4338			continue;
4339		if (lun->be_lun->lun_type == T_CDROM &&
4340		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4341			continue;
4342
4343		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4344		    lun->backend->lun_attr == NULL)
4345			continue;
4346
4347		if (page_index->page_code != prev) {
4348			lun->log_pages.pages_page[j] = page_index->page_code;
4349			prev = page_index->page_code;
4350			j++;
4351		}
4352		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4353		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4354		k++;
4355	}
4356	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4357	lun->log_pages.index[0].page_len = j;
4358	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4359	lun->log_pages.index[1].page_len = k * 2;
4360	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4361	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4362	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4363	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4364
4365	return (CTL_RETVAL_COMPLETE);
4366}
4367
4368static int
4369hex2bin(const char *str, uint8_t *buf, int buf_size)
4370{
4371	int i;
4372	u_char c;
4373
4374	memset(buf, 0, buf_size);
4375	while (isspace(str[0]))
4376		str++;
4377	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4378		str += 2;
4379	buf_size *= 2;
4380	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4381		c = str[i];
4382		if (isdigit(c))
4383			c -= '0';
4384		else if (isalpha(c))
4385			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4386		else
4387			break;
4388		if (c >= 16)
4389			break;
4390		if ((i & 1) == 0)
4391			buf[i / 2] |= (c << 4);
4392		else
4393			buf[i / 2] |= c;
4394	}
4395	return ((i + 1) / 2);
4396}
4397
4398/*
4399 * LUN allocation.
4400 *
4401 * Requirements:
4402 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4403 *   wants us to allocate the LUN and he can block.
4404 * - ctl_softc is always set
4405 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4406 *
4407 * Returns 0 for success, non-zero (errno) for failure.
4408 */
4409static int
4410ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4411	      struct ctl_be_lun *const be_lun)
4412{
4413	struct ctl_lun *nlun, *lun;
4414	struct scsi_vpd_id_descriptor *desc;
4415	struct scsi_vpd_id_t10 *t10id;
4416	const char *eui, *naa, *scsiname, *vendor, *value;
4417	int lun_number, i, lun_malloced;
4418	int devidlen, idlen1, idlen2 = 0, len;
4419
4420	if (be_lun == NULL)
4421		return (EINVAL);
4422
4423	/*
4424	 * We currently only support Direct Access or Processor LUN types.
4425	 */
4426	switch (be_lun->lun_type) {
4427	case T_DIRECT:
4428	case T_PROCESSOR:
4429	case T_CDROM:
4430		break;
4431	case T_SEQUENTIAL:
4432	case T_CHANGER:
4433	default:
4434		be_lun->lun_config_status(be_lun->be_lun,
4435					  CTL_LUN_CONFIG_FAILURE);
4436		break;
4437	}
4438	if (ctl_lun == NULL) {
4439		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4440		lun_malloced = 1;
4441	} else {
4442		lun_malloced = 0;
4443		lun = ctl_lun;
4444	}
4445
4446	memset(lun, 0, sizeof(*lun));
4447	if (lun_malloced)
4448		lun->flags = CTL_LUN_MALLOCED;
4449
4450	/* Generate LUN ID. */
4451	devidlen = max(CTL_DEVID_MIN_LEN,
4452	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4453	idlen1 = sizeof(*t10id) + devidlen;
4454	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4455	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4456	if (scsiname != NULL) {
4457		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4458		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4459	}
4460	eui = ctl_get_opt(&be_lun->options, "eui");
4461	if (eui != NULL) {
4462		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4463	}
4464	naa = ctl_get_opt(&be_lun->options, "naa");
4465	if (naa != NULL) {
4466		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
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	lun->lun_devid->len = len;
4515
4516	mtx_lock(&ctl_softc->ctl_lock);
4517	/*
4518	 * See if the caller requested a particular LUN number.  If so, see
4519	 * if it is available.  Otherwise, allocate the first available LUN.
4520	 */
4521	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4522		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4523		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4524			mtx_unlock(&ctl_softc->ctl_lock);
4525			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4526				printf("ctl: requested LUN ID %d is higher "
4527				       "than CTL_MAX_LUNS - 1 (%d)\n",
4528				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4529			} else {
4530				/*
4531				 * XXX KDM return an error, or just assign
4532				 * another LUN ID in this case??
4533				 */
4534				printf("ctl: requested LUN ID %d is already "
4535				       "in use\n", be_lun->req_lun_id);
4536			}
4537			if (lun->flags & CTL_LUN_MALLOCED)
4538				free(lun, M_CTL);
4539			be_lun->lun_config_status(be_lun->be_lun,
4540						  CTL_LUN_CONFIG_FAILURE);
4541			return (ENOSPC);
4542		}
4543		lun_number = be_lun->req_lun_id;
4544	} else {
4545		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4546		if (lun_number == -1) {
4547			mtx_unlock(&ctl_softc->ctl_lock);
4548			printf("ctl: can't allocate LUN, out of LUNs\n");
4549			if (lun->flags & CTL_LUN_MALLOCED)
4550				free(lun, M_CTL);
4551			be_lun->lun_config_status(be_lun->be_lun,
4552						  CTL_LUN_CONFIG_FAILURE);
4553			return (ENOSPC);
4554		}
4555	}
4556	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4557
4558	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4559	lun->lun = lun_number;
4560	lun->be_lun = be_lun;
4561	/*
4562	 * The processor LUN is always enabled.  Disk LUNs come on line
4563	 * disabled, and must be enabled by the backend.
4564	 */
4565	lun->flags |= CTL_LUN_DISABLED;
4566	lun->backend = be_lun->be;
4567	be_lun->ctl_lun = lun;
4568	be_lun->lun_id = lun_number;
4569	atomic_add_int(&be_lun->be->num_luns, 1);
4570	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4571		lun->flags |= CTL_LUN_EJECTED;
4572	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4573		lun->flags |= CTL_LUN_NO_MEDIA;
4574	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4575		lun->flags |= CTL_LUN_STOPPED;
4576
4577	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4578		lun->flags |= CTL_LUN_PRIMARY_SC;
4579
4580	value = ctl_get_opt(&be_lun->options, "removable");
4581	if (value != NULL) {
4582		if (strcmp(value, "on") == 0)
4583			lun->flags |= CTL_LUN_REMOVABLE;
4584	} else if (be_lun->lun_type == T_CDROM)
4585		lun->flags |= CTL_LUN_REMOVABLE;
4586
4587	lun->ctl_softc = ctl_softc;
4588#ifdef CTL_TIME_IO
4589	lun->last_busy = getsbinuptime();
4590#endif
4591	TAILQ_INIT(&lun->ooa_queue);
4592	TAILQ_INIT(&lun->blocked_queue);
4593	STAILQ_INIT(&lun->error_list);
4594	ctl_tpc_lun_init(lun);
4595
4596	/*
4597	 * Initialize the mode and log page index.
4598	 */
4599	ctl_init_page_index(lun);
4600	ctl_init_log_page_index(lun);
4601
4602	/*
4603	 * Now, before we insert this lun on the lun list, set the lun
4604	 * inventory changed UA for all other luns.
4605	 */
4606	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4607		mtx_lock(&nlun->lun_lock);
4608		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4609		mtx_unlock(&nlun->lun_lock);
4610	}
4611
4612	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4613
4614	ctl_softc->ctl_luns[lun_number] = lun;
4615
4616	ctl_softc->num_luns++;
4617
4618	/* Setup statistics gathering */
4619	lun->stats.device_type = be_lun->lun_type;
4620	lun->stats.lun_number = lun_number;
4621	lun->stats.blocksize = be_lun->blocksize;
4622	if (be_lun->blocksize == 0)
4623		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4624	for (i = 0;i < CTL_MAX_PORTS;i++)
4625		lun->stats.ports[i].targ_port = i;
4626
4627	mtx_unlock(&ctl_softc->ctl_lock);
4628
4629	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4630	return (0);
4631}
4632
4633/*
4634 * Delete a LUN.
4635 * Assumptions:
4636 * - LUN has already been marked invalid and any pending I/O has been taken
4637 *   care of.
4638 */
4639static int
4640ctl_free_lun(struct ctl_lun *lun)
4641{
4642	struct ctl_softc *softc;
4643	struct ctl_lun *nlun;
4644	int i;
4645
4646	softc = lun->ctl_softc;
4647
4648	mtx_assert(&softc->ctl_lock, MA_OWNED);
4649
4650	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4651
4652	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4653
4654	softc->ctl_luns[lun->lun] = NULL;
4655
4656	if (!TAILQ_EMPTY(&lun->ooa_queue))
4657		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4658
4659	softc->num_luns--;
4660
4661	/*
4662	 * Tell the backend to free resources, if this LUN has a backend.
4663	 */
4664	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4665	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4666
4667	ctl_tpc_lun_shutdown(lun);
4668	mtx_destroy(&lun->lun_lock);
4669	free(lun->lun_devid, M_CTL);
4670	for (i = 0; i < CTL_MAX_PORTS; i++)
4671		free(lun->pending_ua[i], M_CTL);
4672	for (i = 0; i < CTL_MAX_PORTS; i++)
4673		free(lun->pr_keys[i], M_CTL);
4674	free(lun->write_buffer, M_CTL);
4675	if (lun->flags & CTL_LUN_MALLOCED)
4676		free(lun, M_CTL);
4677
4678	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4679		mtx_lock(&nlun->lun_lock);
4680		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4681		mtx_unlock(&nlun->lun_lock);
4682	}
4683
4684	return (0);
4685}
4686
4687static void
4688ctl_create_lun(struct ctl_be_lun *be_lun)
4689{
4690
4691	/*
4692	 * ctl_alloc_lun() should handle all potential failure cases.
4693	 */
4694	ctl_alloc_lun(control_softc, NULL, be_lun);
4695}
4696
4697int
4698ctl_add_lun(struct ctl_be_lun *be_lun)
4699{
4700	struct ctl_softc *softc = control_softc;
4701
4702	mtx_lock(&softc->ctl_lock);
4703	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4704	mtx_unlock(&softc->ctl_lock);
4705	wakeup(&softc->pending_lun_queue);
4706
4707	return (0);
4708}
4709
4710int
4711ctl_enable_lun(struct ctl_be_lun *be_lun)
4712{
4713	struct ctl_softc *softc;
4714	struct ctl_port *port, *nport;
4715	struct ctl_lun *lun;
4716	int retval;
4717
4718	lun = (struct ctl_lun *)be_lun->ctl_lun;
4719	softc = lun->ctl_softc;
4720
4721	mtx_lock(&softc->ctl_lock);
4722	mtx_lock(&lun->lun_lock);
4723	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4724		/*
4725		 * eh?  Why did we get called if the LUN is already
4726		 * enabled?
4727		 */
4728		mtx_unlock(&lun->lun_lock);
4729		mtx_unlock(&softc->ctl_lock);
4730		return (0);
4731	}
4732	lun->flags &= ~CTL_LUN_DISABLED;
4733	mtx_unlock(&lun->lun_lock);
4734
4735	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4736		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4737		    port->lun_map != NULL || port->lun_enable == NULL)
4738			continue;
4739
4740		/*
4741		 * Drop the lock while we call the FETD's enable routine.
4742		 * This can lead to a callback into CTL (at least in the
4743		 * case of the internal initiator frontend.
4744		 */
4745		mtx_unlock(&softc->ctl_lock);
4746		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4747		mtx_lock(&softc->ctl_lock);
4748		if (retval != 0) {
4749			printf("%s: FETD %s port %d returned error "
4750			       "%d for lun_enable on lun %jd\n",
4751			       __func__, port->port_name, port->targ_port,
4752			       retval, (intmax_t)lun->lun);
4753		}
4754	}
4755
4756	mtx_unlock(&softc->ctl_lock);
4757	ctl_isc_announce_lun(lun);
4758
4759	return (0);
4760}
4761
4762int
4763ctl_disable_lun(struct ctl_be_lun *be_lun)
4764{
4765	struct ctl_softc *softc;
4766	struct ctl_port *port;
4767	struct ctl_lun *lun;
4768	int retval;
4769
4770	lun = (struct ctl_lun *)be_lun->ctl_lun;
4771	softc = lun->ctl_softc;
4772
4773	mtx_lock(&softc->ctl_lock);
4774	mtx_lock(&lun->lun_lock);
4775	if (lun->flags & CTL_LUN_DISABLED) {
4776		mtx_unlock(&lun->lun_lock);
4777		mtx_unlock(&softc->ctl_lock);
4778		return (0);
4779	}
4780	lun->flags |= CTL_LUN_DISABLED;
4781	mtx_unlock(&lun->lun_lock);
4782
4783	STAILQ_FOREACH(port, &softc->port_list, links) {
4784		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4785		    port->lun_map != NULL || port->lun_disable == NULL)
4786			continue;
4787
4788		/*
4789		 * Drop the lock before we call the frontend's disable
4790		 * routine, to avoid lock order reversals.
4791		 *
4792		 * XXX KDM what happens if the frontend list changes while
4793		 * we're traversing it?  It's unlikely, but should be handled.
4794		 */
4795		mtx_unlock(&softc->ctl_lock);
4796		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4797		mtx_lock(&softc->ctl_lock);
4798		if (retval != 0) {
4799			printf("%s: FETD %s port %d returned error "
4800			       "%d for lun_disable on lun %jd\n",
4801			       __func__, port->port_name, port->targ_port,
4802			       retval, (intmax_t)lun->lun);
4803		}
4804	}
4805
4806	mtx_unlock(&softc->ctl_lock);
4807	ctl_isc_announce_lun(lun);
4808
4809	return (0);
4810}
4811
4812int
4813ctl_start_lun(struct ctl_be_lun *be_lun)
4814{
4815	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4816
4817	mtx_lock(&lun->lun_lock);
4818	lun->flags &= ~CTL_LUN_STOPPED;
4819	mtx_unlock(&lun->lun_lock);
4820	return (0);
4821}
4822
4823int
4824ctl_stop_lun(struct ctl_be_lun *be_lun)
4825{
4826	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4827
4828	mtx_lock(&lun->lun_lock);
4829	lun->flags |= CTL_LUN_STOPPED;
4830	mtx_unlock(&lun->lun_lock);
4831	return (0);
4832}
4833
4834int
4835ctl_lun_no_media(struct ctl_be_lun *be_lun)
4836{
4837	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4838
4839	mtx_lock(&lun->lun_lock);
4840	lun->flags |= CTL_LUN_NO_MEDIA;
4841	mtx_unlock(&lun->lun_lock);
4842	return (0);
4843}
4844
4845int
4846ctl_lun_has_media(struct ctl_be_lun *be_lun)
4847{
4848	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4849	union ctl_ha_msg msg;
4850
4851	mtx_lock(&lun->lun_lock);
4852	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4853	if (lun->flags & CTL_LUN_REMOVABLE)
4854		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4855	mtx_unlock(&lun->lun_lock);
4856	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4857	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4858		bzero(&msg.ua, sizeof(msg.ua));
4859		msg.hdr.msg_type = CTL_MSG_UA;
4860		msg.hdr.nexus.initid = -1;
4861		msg.hdr.nexus.targ_port = -1;
4862		msg.hdr.nexus.targ_lun = lun->lun;
4863		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4864		msg.ua.ua_all = 1;
4865		msg.ua.ua_set = 1;
4866		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4867		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4868		    M_WAITOK);
4869	}
4870	return (0);
4871}
4872
4873int
4874ctl_lun_ejected(struct ctl_be_lun *be_lun)
4875{
4876	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4877
4878	mtx_lock(&lun->lun_lock);
4879	lun->flags |= CTL_LUN_EJECTED;
4880	mtx_unlock(&lun->lun_lock);
4881	return (0);
4882}
4883
4884int
4885ctl_lun_primary(struct ctl_be_lun *be_lun)
4886{
4887	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4888
4889	mtx_lock(&lun->lun_lock);
4890	lun->flags |= CTL_LUN_PRIMARY_SC;
4891	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4892	mtx_unlock(&lun->lun_lock);
4893	ctl_isc_announce_lun(lun);
4894	return (0);
4895}
4896
4897int
4898ctl_lun_secondary(struct ctl_be_lun *be_lun)
4899{
4900	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4901
4902	mtx_lock(&lun->lun_lock);
4903	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4904	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4905	mtx_unlock(&lun->lun_lock);
4906	ctl_isc_announce_lun(lun);
4907	return (0);
4908}
4909
4910int
4911ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4912{
4913	struct ctl_softc *softc;
4914	struct ctl_lun *lun;
4915
4916	lun = (struct ctl_lun *)be_lun->ctl_lun;
4917	softc = lun->ctl_softc;
4918
4919	mtx_lock(&lun->lun_lock);
4920
4921	/*
4922	 * The LUN needs to be disabled before it can be marked invalid.
4923	 */
4924	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4925		mtx_unlock(&lun->lun_lock);
4926		return (-1);
4927	}
4928	/*
4929	 * Mark the LUN invalid.
4930	 */
4931	lun->flags |= CTL_LUN_INVALID;
4932
4933	/*
4934	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4935	 * If we have something in the OOA queue, we'll free it when the
4936	 * last I/O completes.
4937	 */
4938	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4939		mtx_unlock(&lun->lun_lock);
4940		mtx_lock(&softc->ctl_lock);
4941		ctl_free_lun(lun);
4942		mtx_unlock(&softc->ctl_lock);
4943	} else
4944		mtx_unlock(&lun->lun_lock);
4945
4946	return (0);
4947}
4948
4949void
4950ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4951{
4952	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4953	union ctl_ha_msg msg;
4954
4955	mtx_lock(&lun->lun_lock);
4956	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4957	mtx_unlock(&lun->lun_lock);
4958	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4959		/* Send msg to other side. */
4960		bzero(&msg.ua, sizeof(msg.ua));
4961		msg.hdr.msg_type = CTL_MSG_UA;
4962		msg.hdr.nexus.initid = -1;
4963		msg.hdr.nexus.targ_port = -1;
4964		msg.hdr.nexus.targ_lun = lun->lun;
4965		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4966		msg.ua.ua_all = 1;
4967		msg.ua.ua_set = 1;
4968		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4969		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4970		    M_WAITOK);
4971	}
4972}
4973
4974/*
4975 * Backend "memory move is complete" callback for requests that never
4976 * make it down to say RAIDCore's configuration code.
4977 */
4978int
4979ctl_config_move_done(union ctl_io *io)
4980{
4981	int retval;
4982
4983	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4984	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4985	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4986
4987	if ((io->io_hdr.port_status != 0) &&
4988	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4989	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4990		/*
4991		 * For hardware error sense keys, the sense key
4992		 * specific value is defined to be a retry count,
4993		 * but we use it to pass back an internal FETD
4994		 * error code.  XXX KDM  Hopefully the FETD is only
4995		 * using 16 bits for an error code, since that's
4996		 * all the space we have in the sks field.
4997		 */
4998		ctl_set_internal_failure(&io->scsiio,
4999					 /*sks_valid*/ 1,
5000					 /*retry_count*/
5001					 io->io_hdr.port_status);
5002	}
5003
5004	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5005		ctl_data_print(io);
5006	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5007	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5008	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5009	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5010		/*
5011		 * XXX KDM just assuming a single pointer here, and not a
5012		 * S/G list.  If we start using S/G lists for config data,
5013		 * we'll need to know how to clean them up here as well.
5014		 */
5015		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5016			free(io->scsiio.kern_data_ptr, M_CTL);
5017		ctl_done(io);
5018		retval = CTL_RETVAL_COMPLETE;
5019	} else {
5020		/*
5021		 * XXX KDM now we need to continue data movement.  Some
5022		 * options:
5023		 * - call ctl_scsiio() again?  We don't do this for data
5024		 *   writes, because for those at least we know ahead of
5025		 *   time where the write will go and how long it is.  For
5026		 *   config writes, though, that information is largely
5027		 *   contained within the write itself, thus we need to
5028		 *   parse out the data again.
5029		 *
5030		 * - Call some other function once the data is in?
5031		 */
5032
5033		/*
5034		 * XXX KDM call ctl_scsiio() again for now, and check flag
5035		 * bits to see whether we're allocated or not.
5036		 */
5037		retval = ctl_scsiio(&io->scsiio);
5038	}
5039	return (retval);
5040}
5041
5042/*
5043 * This gets called by a backend driver when it is done with a
5044 * data_submit method.
5045 */
5046void
5047ctl_data_submit_done(union ctl_io *io)
5048{
5049	/*
5050	 * If the IO_CONT flag is set, we need to call the supplied
5051	 * function to continue processing the I/O, instead of completing
5052	 * the I/O just yet.
5053	 *
5054	 * If there is an error, though, we don't want to keep processing.
5055	 * Instead, just send status back to the initiator.
5056	 */
5057	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5058	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5059	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5060	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5061		io->scsiio.io_cont(io);
5062		return;
5063	}
5064	ctl_done(io);
5065}
5066
5067/*
5068 * This gets called by a backend driver when it is done with a
5069 * configuration write.
5070 */
5071void
5072ctl_config_write_done(union ctl_io *io)
5073{
5074	uint8_t *buf;
5075
5076	/*
5077	 * If the IO_CONT flag is set, we need to call the supplied
5078	 * function to continue processing the I/O, instead of completing
5079	 * the I/O just yet.
5080	 *
5081	 * If there is an error, though, we don't want to keep processing.
5082	 * Instead, just send status back to the initiator.
5083	 */
5084	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5085	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5086	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5087	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5088		io->scsiio.io_cont(io);
5089		return;
5090	}
5091	/*
5092	 * Since a configuration write can be done for commands that actually
5093	 * have data allocated, like write buffer, and commands that have
5094	 * no data, like start/stop unit, we need to check here.
5095	 */
5096	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5097		buf = io->scsiio.kern_data_ptr;
5098	else
5099		buf = NULL;
5100	ctl_done(io);
5101	if (buf)
5102		free(buf, M_CTL);
5103}
5104
5105void
5106ctl_config_read_done(union ctl_io *io)
5107{
5108	uint8_t *buf;
5109
5110	/*
5111	 * If there is some error -- we are done, skip data transfer.
5112	 */
5113	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5114	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5115	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5116		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5117			buf = io->scsiio.kern_data_ptr;
5118		else
5119			buf = NULL;
5120		ctl_done(io);
5121		if (buf)
5122			free(buf, M_CTL);
5123		return;
5124	}
5125
5126	/*
5127	 * If the IO_CONT flag is set, we need to call the supplied
5128	 * function to continue processing the I/O, instead of completing
5129	 * the I/O just yet.
5130	 */
5131	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5132		io->scsiio.io_cont(io);
5133		return;
5134	}
5135
5136	ctl_datamove(io);
5137}
5138
5139/*
5140 * SCSI release command.
5141 */
5142int
5143ctl_scsi_release(struct ctl_scsiio *ctsio)
5144{
5145	struct ctl_lun *lun;
5146	uint32_t residx;
5147
5148	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5149
5150	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5151	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5152
5153	/*
5154	 * XXX KDM right now, we only support LUN reservation.  We don't
5155	 * support 3rd party reservations, or extent reservations, which
5156	 * might actually need the parameter list.  If we've gotten this
5157	 * far, we've got a LUN reservation.  Anything else got kicked out
5158	 * above.  So, according to SPC, ignore the length.
5159	 */
5160
5161	mtx_lock(&lun->lun_lock);
5162
5163	/*
5164	 * According to SPC, it is not an error for an intiator to attempt
5165	 * to release a reservation on a LUN that isn't reserved, or that
5166	 * is reserved by another initiator.  The reservation can only be
5167	 * released, though, by the initiator who made it or by one of
5168	 * several reset type events.
5169	 */
5170	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5171			lun->flags &= ~CTL_LUN_RESERVED;
5172
5173	mtx_unlock(&lun->lun_lock);
5174
5175	ctl_set_success(ctsio);
5176	ctl_done((union ctl_io *)ctsio);
5177	return (CTL_RETVAL_COMPLETE);
5178}
5179
5180int
5181ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5182{
5183	struct ctl_lun *lun;
5184	uint32_t residx;
5185
5186	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5187
5188	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5189	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5190
5191	/*
5192	 * XXX KDM right now, we only support LUN reservation.  We don't
5193	 * support 3rd party reservations, or extent reservations, which
5194	 * might actually need the parameter list.  If we've gotten this
5195	 * far, we've got a LUN reservation.  Anything else got kicked out
5196	 * above.  So, according to SPC, ignore the length.
5197	 */
5198
5199	mtx_lock(&lun->lun_lock);
5200	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5201		ctl_set_reservation_conflict(ctsio);
5202		goto bailout;
5203	}
5204
5205	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5206	if (lun->flags & CTL_LUN_PR_RESERVED) {
5207		ctl_set_success(ctsio);
5208		goto bailout;
5209	}
5210
5211	lun->flags |= CTL_LUN_RESERVED;
5212	lun->res_idx = residx;
5213	ctl_set_success(ctsio);
5214
5215bailout:
5216	mtx_unlock(&lun->lun_lock);
5217	ctl_done((union ctl_io *)ctsio);
5218	return (CTL_RETVAL_COMPLETE);
5219}
5220
5221int
5222ctl_start_stop(struct ctl_scsiio *ctsio)
5223{
5224	struct scsi_start_stop_unit *cdb;
5225	struct ctl_lun *lun;
5226	int retval;
5227
5228	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5229
5230	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5231	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5232
5233	if ((cdb->how & SSS_PC_MASK) == 0) {
5234		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5235		    (cdb->how & SSS_START) == 0) {
5236			uint32_t residx;
5237
5238			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5239			if (ctl_get_prkey(lun, residx) == 0 ||
5240			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5241
5242				ctl_set_reservation_conflict(ctsio);
5243				ctl_done((union ctl_io *)ctsio);
5244				return (CTL_RETVAL_COMPLETE);
5245			}
5246		}
5247
5248		if ((cdb->how & SSS_LOEJ) &&
5249		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5250			ctl_set_invalid_field(ctsio,
5251					      /*sks_valid*/ 1,
5252					      /*command*/ 1,
5253					      /*field*/ 4,
5254					      /*bit_valid*/ 1,
5255					      /*bit*/ 1);
5256			ctl_done((union ctl_io *)ctsio);
5257			return (CTL_RETVAL_COMPLETE);
5258		}
5259
5260		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5261		    lun->prevent_count > 0) {
5262			/* "Medium removal prevented" */
5263			ctl_set_sense(ctsio, /*current_error*/ 1,
5264			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5265			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5266			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5267			ctl_done((union ctl_io *)ctsio);
5268			return (CTL_RETVAL_COMPLETE);
5269		}
5270	}
5271
5272	retval = lun->backend->config_write((union ctl_io *)ctsio);
5273	return (retval);
5274}
5275
5276int
5277ctl_prevent_allow(struct ctl_scsiio *ctsio)
5278{
5279	struct ctl_lun *lun;
5280	struct scsi_prevent *cdb;
5281	int retval;
5282	uint32_t initidx;
5283
5284	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5285
5286	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5287	cdb = (struct scsi_prevent *)ctsio->cdb;
5288
5289	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5290		ctl_set_invalid_opcode(ctsio);
5291		ctl_done((union ctl_io *)ctsio);
5292		return (CTL_RETVAL_COMPLETE);
5293	}
5294
5295	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5296	mtx_lock(&lun->lun_lock);
5297	if ((cdb->how & PR_PREVENT) &&
5298	    ctl_is_set(lun->prevent, initidx) == 0) {
5299		ctl_set_mask(lun->prevent, initidx);
5300		lun->prevent_count++;
5301	} else if ((cdb->how & PR_PREVENT) == 0 &&
5302	    ctl_is_set(lun->prevent, initidx)) {
5303		ctl_clear_mask(lun->prevent, initidx);
5304		lun->prevent_count--;
5305	}
5306	mtx_unlock(&lun->lun_lock);
5307	retval = lun->backend->config_write((union ctl_io *)ctsio);
5308	return (retval);
5309}
5310
5311/*
5312 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5313 * we don't really do anything with the LBA and length fields if the user
5314 * passes them in.  Instead we'll just flush out the cache for the entire
5315 * LUN.
5316 */
5317int
5318ctl_sync_cache(struct ctl_scsiio *ctsio)
5319{
5320	struct ctl_lun *lun;
5321	struct ctl_softc *softc;
5322	struct ctl_lba_len_flags *lbalen;
5323	uint64_t starting_lba;
5324	uint32_t block_count;
5325	int retval;
5326	uint8_t byte2;
5327
5328	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5329
5330	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5331	softc = lun->ctl_softc;
5332	retval = 0;
5333
5334	switch (ctsio->cdb[0]) {
5335	case SYNCHRONIZE_CACHE: {
5336		struct scsi_sync_cache *cdb;
5337		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5338
5339		starting_lba = scsi_4btoul(cdb->begin_lba);
5340		block_count = scsi_2btoul(cdb->lb_count);
5341		byte2 = cdb->byte2;
5342		break;
5343	}
5344	case SYNCHRONIZE_CACHE_16: {
5345		struct scsi_sync_cache_16 *cdb;
5346		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5347
5348		starting_lba = scsi_8btou64(cdb->begin_lba);
5349		block_count = scsi_4btoul(cdb->lb_count);
5350		byte2 = cdb->byte2;
5351		break;
5352	}
5353	default:
5354		ctl_set_invalid_opcode(ctsio);
5355		ctl_done((union ctl_io *)ctsio);
5356		goto bailout;
5357		break; /* NOTREACHED */
5358	}
5359
5360	/*
5361	 * We check the LBA and length, but don't do anything with them.
5362	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5363	 * get flushed.  This check will just help satisfy anyone who wants
5364	 * to see an error for an out of range LBA.
5365	 */
5366	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5367		ctl_set_lba_out_of_range(ctsio);
5368		ctl_done((union ctl_io *)ctsio);
5369		goto bailout;
5370	}
5371
5372	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5373	lbalen->lba = starting_lba;
5374	lbalen->len = block_count;
5375	lbalen->flags = byte2;
5376	retval = lun->backend->config_write((union ctl_io *)ctsio);
5377
5378bailout:
5379	return (retval);
5380}
5381
5382int
5383ctl_format(struct ctl_scsiio *ctsio)
5384{
5385	struct scsi_format *cdb;
5386	struct ctl_lun *lun;
5387	int length, defect_list_len;
5388
5389	CTL_DEBUG_PRINT(("ctl_format\n"));
5390
5391	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5392
5393	cdb = (struct scsi_format *)ctsio->cdb;
5394
5395	length = 0;
5396	if (cdb->byte2 & SF_FMTDATA) {
5397		if (cdb->byte2 & SF_LONGLIST)
5398			length = sizeof(struct scsi_format_header_long);
5399		else
5400			length = sizeof(struct scsi_format_header_short);
5401	}
5402
5403	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5404	 && (length > 0)) {
5405		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5406		ctsio->kern_data_len = length;
5407		ctsio->kern_total_len = length;
5408		ctsio->kern_data_resid = 0;
5409		ctsio->kern_rel_offset = 0;
5410		ctsio->kern_sg_entries = 0;
5411		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5412		ctsio->be_move_done = ctl_config_move_done;
5413		ctl_datamove((union ctl_io *)ctsio);
5414
5415		return (CTL_RETVAL_COMPLETE);
5416	}
5417
5418	defect_list_len = 0;
5419
5420	if (cdb->byte2 & SF_FMTDATA) {
5421		if (cdb->byte2 & SF_LONGLIST) {
5422			struct scsi_format_header_long *header;
5423
5424			header = (struct scsi_format_header_long *)
5425				ctsio->kern_data_ptr;
5426
5427			defect_list_len = scsi_4btoul(header->defect_list_len);
5428			if (defect_list_len != 0) {
5429				ctl_set_invalid_field(ctsio,
5430						      /*sks_valid*/ 1,
5431						      /*command*/ 0,
5432						      /*field*/ 2,
5433						      /*bit_valid*/ 0,
5434						      /*bit*/ 0);
5435				goto bailout;
5436			}
5437		} else {
5438			struct scsi_format_header_short *header;
5439
5440			header = (struct scsi_format_header_short *)
5441				ctsio->kern_data_ptr;
5442
5443			defect_list_len = scsi_2btoul(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		}
5454	}
5455
5456	ctl_set_success(ctsio);
5457bailout:
5458
5459	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5460		free(ctsio->kern_data_ptr, M_CTL);
5461		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5462	}
5463
5464	ctl_done((union ctl_io *)ctsio);
5465	return (CTL_RETVAL_COMPLETE);
5466}
5467
5468int
5469ctl_read_buffer(struct ctl_scsiio *ctsio)
5470{
5471	struct ctl_lun *lun;
5472	uint64_t buffer_offset;
5473	uint32_t len;
5474	uint8_t byte2;
5475	static uint8_t descr[4];
5476	static uint8_t echo_descr[4] = { 0 };
5477
5478	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5479	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5480	switch (ctsio->cdb[0]) {
5481	case READ_BUFFER: {
5482		struct scsi_read_buffer *cdb;
5483
5484		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5485		buffer_offset = scsi_3btoul(cdb->offset);
5486		len = scsi_3btoul(cdb->length);
5487		byte2 = cdb->byte2;
5488		break;
5489	}
5490	case READ_BUFFER_16: {
5491		struct scsi_read_buffer_16 *cdb;
5492
5493		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5494		buffer_offset = scsi_8btou64(cdb->offset);
5495		len = scsi_4btoul(cdb->length);
5496		byte2 = cdb->byte2;
5497		break;
5498	}
5499	default: /* This shouldn't happen. */
5500		ctl_set_invalid_opcode(ctsio);
5501		ctl_done((union ctl_io *)ctsio);
5502		return (CTL_RETVAL_COMPLETE);
5503	}
5504
5505	if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5506	    (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5507	    (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5508		ctl_set_invalid_field(ctsio,
5509				      /*sks_valid*/ 1,
5510				      /*command*/ 1,
5511				      /*field*/ 1,
5512				      /*bit_valid*/ 1,
5513				      /*bit*/ 4);
5514		ctl_done((union ctl_io *)ctsio);
5515		return (CTL_RETVAL_COMPLETE);
5516	}
5517
5518	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5519	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5520		ctl_set_invalid_field(ctsio,
5521				      /*sks_valid*/ 1,
5522				      /*command*/ 1,
5523				      /*field*/ 6,
5524				      /*bit_valid*/ 0,
5525				      /*bit*/ 0);
5526		ctl_done((union ctl_io *)ctsio);
5527		return (CTL_RETVAL_COMPLETE);
5528	}
5529
5530	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5531		descr[0] = 0;
5532		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5533		ctsio->kern_data_ptr = descr;
5534		len = min(len, sizeof(descr));
5535	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5536		ctsio->kern_data_ptr = echo_descr;
5537		len = min(len, sizeof(echo_descr));
5538	} else {
5539		if (lun->write_buffer == NULL) {
5540			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5541			    M_CTL, M_WAITOK);
5542		}
5543		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5544	}
5545	ctsio->kern_data_len = len;
5546	ctsio->kern_total_len = len;
5547	ctsio->kern_data_resid = 0;
5548	ctsio->kern_rel_offset = 0;
5549	ctsio->kern_sg_entries = 0;
5550	ctl_set_success(ctsio);
5551	ctsio->be_move_done = ctl_config_move_done;
5552	ctl_datamove((union ctl_io *)ctsio);
5553	return (CTL_RETVAL_COMPLETE);
5554}
5555
5556int
5557ctl_write_buffer(struct ctl_scsiio *ctsio)
5558{
5559	struct scsi_write_buffer *cdb;
5560	struct ctl_lun *lun;
5561	int buffer_offset, len;
5562
5563	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5564
5565	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5566	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5567
5568	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5569		ctl_set_invalid_field(ctsio,
5570				      /*sks_valid*/ 1,
5571				      /*command*/ 1,
5572				      /*field*/ 1,
5573				      /*bit_valid*/ 1,
5574				      /*bit*/ 4);
5575		ctl_done((union ctl_io *)ctsio);
5576		return (CTL_RETVAL_COMPLETE);
5577	}
5578
5579	len = scsi_3btoul(cdb->length);
5580	buffer_offset = scsi_3btoul(cdb->offset);
5581
5582	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5583		ctl_set_invalid_field(ctsio,
5584				      /*sks_valid*/ 1,
5585				      /*command*/ 1,
5586				      /*field*/ 6,
5587				      /*bit_valid*/ 0,
5588				      /*bit*/ 0);
5589		ctl_done((union ctl_io *)ctsio);
5590		return (CTL_RETVAL_COMPLETE);
5591	}
5592
5593	/*
5594	 * If we've got a kernel request that hasn't been malloced yet,
5595	 * malloc it and tell the caller the data buffer is here.
5596	 */
5597	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5598		if (lun->write_buffer == NULL) {
5599			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5600			    M_CTL, M_WAITOK);
5601		}
5602		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5603		ctsio->kern_data_len = len;
5604		ctsio->kern_total_len = len;
5605		ctsio->kern_data_resid = 0;
5606		ctsio->kern_rel_offset = 0;
5607		ctsio->kern_sg_entries = 0;
5608		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5609		ctsio->be_move_done = ctl_config_move_done;
5610		ctl_datamove((union ctl_io *)ctsio);
5611
5612		return (CTL_RETVAL_COMPLETE);
5613	}
5614
5615	ctl_set_success(ctsio);
5616	ctl_done((union ctl_io *)ctsio);
5617	return (CTL_RETVAL_COMPLETE);
5618}
5619
5620int
5621ctl_write_same(struct ctl_scsiio *ctsio)
5622{
5623	struct ctl_lun *lun;
5624	struct ctl_lba_len_flags *lbalen;
5625	uint64_t lba;
5626	uint32_t num_blocks;
5627	int len, retval;
5628	uint8_t byte2;
5629
5630	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5631
5632	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5633
5634	switch (ctsio->cdb[0]) {
5635	case WRITE_SAME_10: {
5636		struct scsi_write_same_10 *cdb;
5637
5638		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5639
5640		lba = scsi_4btoul(cdb->addr);
5641		num_blocks = scsi_2btoul(cdb->length);
5642		byte2 = cdb->byte2;
5643		break;
5644	}
5645	case WRITE_SAME_16: {
5646		struct scsi_write_same_16 *cdb;
5647
5648		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5649
5650		lba = scsi_8btou64(cdb->addr);
5651		num_blocks = scsi_4btoul(cdb->length);
5652		byte2 = cdb->byte2;
5653		break;
5654	}
5655	default:
5656		/*
5657		 * We got a command we don't support.  This shouldn't
5658		 * happen, commands should be filtered out above us.
5659		 */
5660		ctl_set_invalid_opcode(ctsio);
5661		ctl_done((union ctl_io *)ctsio);
5662
5663		return (CTL_RETVAL_COMPLETE);
5664		break; /* NOTREACHED */
5665	}
5666
5667	/* ANCHOR flag can be used only together with UNMAP */
5668	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5669		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5670		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5671		ctl_done((union ctl_io *)ctsio);
5672		return (CTL_RETVAL_COMPLETE);
5673	}
5674
5675	/*
5676	 * The first check is to make sure we're in bounds, the second
5677	 * check is to catch wrap-around problems.  If the lba + num blocks
5678	 * is less than the lba, then we've wrapped around and the block
5679	 * range is invalid anyway.
5680	 */
5681	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5682	 || ((lba + num_blocks) < lba)) {
5683		ctl_set_lba_out_of_range(ctsio);
5684		ctl_done((union ctl_io *)ctsio);
5685		return (CTL_RETVAL_COMPLETE);
5686	}
5687
5688	/* Zero number of blocks means "to the last logical block" */
5689	if (num_blocks == 0) {
5690		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5691			ctl_set_invalid_field(ctsio,
5692					      /*sks_valid*/ 0,
5693					      /*command*/ 1,
5694					      /*field*/ 0,
5695					      /*bit_valid*/ 0,
5696					      /*bit*/ 0);
5697			ctl_done((union ctl_io *)ctsio);
5698			return (CTL_RETVAL_COMPLETE);
5699		}
5700		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5701	}
5702
5703	len = lun->be_lun->blocksize;
5704
5705	/*
5706	 * If we've got a kernel request that hasn't been malloced yet,
5707	 * malloc it and tell the caller the data buffer is here.
5708	 */
5709	if ((byte2 & SWS_NDOB) == 0 &&
5710	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5711		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5712		ctsio->kern_data_len = len;
5713		ctsio->kern_total_len = len;
5714		ctsio->kern_data_resid = 0;
5715		ctsio->kern_rel_offset = 0;
5716		ctsio->kern_sg_entries = 0;
5717		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5718		ctsio->be_move_done = ctl_config_move_done;
5719		ctl_datamove((union ctl_io *)ctsio);
5720
5721		return (CTL_RETVAL_COMPLETE);
5722	}
5723
5724	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5725	lbalen->lba = lba;
5726	lbalen->len = num_blocks;
5727	lbalen->flags = byte2;
5728	retval = lun->backend->config_write((union ctl_io *)ctsio);
5729
5730	return (retval);
5731}
5732
5733int
5734ctl_unmap(struct ctl_scsiio *ctsio)
5735{
5736	struct ctl_lun *lun;
5737	struct scsi_unmap *cdb;
5738	struct ctl_ptr_len_flags *ptrlen;
5739	struct scsi_unmap_header *hdr;
5740	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5741	uint64_t lba;
5742	uint32_t num_blocks;
5743	int len, retval;
5744	uint8_t byte2;
5745
5746	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5747
5748	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5749	cdb = (struct scsi_unmap *)ctsio->cdb;
5750
5751	len = scsi_2btoul(cdb->length);
5752	byte2 = cdb->byte2;
5753
5754	/*
5755	 * If we've got a kernel request that hasn't been malloced yet,
5756	 * malloc it and tell the caller the data buffer is here.
5757	 */
5758	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5759		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5760		ctsio->kern_data_len = len;
5761		ctsio->kern_total_len = len;
5762		ctsio->kern_data_resid = 0;
5763		ctsio->kern_rel_offset = 0;
5764		ctsio->kern_sg_entries = 0;
5765		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5766		ctsio->be_move_done = ctl_config_move_done;
5767		ctl_datamove((union ctl_io *)ctsio);
5768
5769		return (CTL_RETVAL_COMPLETE);
5770	}
5771
5772	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5773	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5774	if (len < sizeof (*hdr) ||
5775	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5776	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5777	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5778		ctl_set_invalid_field(ctsio,
5779				      /*sks_valid*/ 0,
5780				      /*command*/ 0,
5781				      /*field*/ 0,
5782				      /*bit_valid*/ 0,
5783				      /*bit*/ 0);
5784		goto done;
5785	}
5786	len = scsi_2btoul(hdr->desc_length);
5787	buf = (struct scsi_unmap_desc *)(hdr + 1);
5788	end = buf + len / sizeof(*buf);
5789
5790	endnz = buf;
5791	for (range = buf; range < end; range++) {
5792		lba = scsi_8btou64(range->lba);
5793		num_blocks = scsi_4btoul(range->length);
5794		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5795		 || ((lba + num_blocks) < lba)) {
5796			ctl_set_lba_out_of_range(ctsio);
5797			ctl_done((union ctl_io *)ctsio);
5798			return (CTL_RETVAL_COMPLETE);
5799		}
5800		if (num_blocks != 0)
5801			endnz = range + 1;
5802	}
5803
5804	/*
5805	 * Block backend can not handle zero last range.
5806	 * Filter it out and return if there is nothing left.
5807	 */
5808	len = (uint8_t *)endnz - (uint8_t *)buf;
5809	if (len == 0) {
5810		ctl_set_success(ctsio);
5811		goto done;
5812	}
5813
5814	mtx_lock(&lun->lun_lock);
5815	ptrlen = (struct ctl_ptr_len_flags *)
5816	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5817	ptrlen->ptr = (void *)buf;
5818	ptrlen->len = len;
5819	ptrlen->flags = byte2;
5820	ctl_check_blocked(lun);
5821	mtx_unlock(&lun->lun_lock);
5822
5823	retval = lun->backend->config_write((union ctl_io *)ctsio);
5824	return (retval);
5825
5826done:
5827	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5828		free(ctsio->kern_data_ptr, M_CTL);
5829		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5830	}
5831	ctl_done((union ctl_io *)ctsio);
5832	return (CTL_RETVAL_COMPLETE);
5833}
5834
5835/*
5836 * Note that this function currently doesn't actually do anything inside
5837 * CTL to enforce things if the DQue bit is turned on.
5838 *
5839 * Also note that this function can't be used in the default case, because
5840 * the DQue bit isn't set in the changeable mask for the control mode page
5841 * anyway.  This is just here as an example for how to implement a page
5842 * handler, and a placeholder in case we want to allow the user to turn
5843 * tagged queueing on and off.
5844 *
5845 * The D_SENSE bit handling is functional, however, and will turn
5846 * descriptor sense on and off for a given LUN.
5847 */
5848int
5849ctl_control_page_handler(struct ctl_scsiio *ctsio,
5850			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5851{
5852	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5853	struct ctl_lun *lun;
5854	int set_ua;
5855	uint32_t initidx;
5856
5857	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5858	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5859	set_ua = 0;
5860
5861	user_cp = (struct scsi_control_page *)page_ptr;
5862	current_cp = (struct scsi_control_page *)
5863		(page_index->page_data + (page_index->page_len *
5864		CTL_PAGE_CURRENT));
5865	saved_cp = (struct scsi_control_page *)
5866		(page_index->page_data + (page_index->page_len *
5867		CTL_PAGE_SAVED));
5868
5869	mtx_lock(&lun->lun_lock);
5870	if (((current_cp->rlec & SCP_DSENSE) == 0)
5871	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5872		/*
5873		 * Descriptor sense is currently turned off and the user
5874		 * wants to turn it on.
5875		 */
5876		current_cp->rlec |= SCP_DSENSE;
5877		saved_cp->rlec |= SCP_DSENSE;
5878		lun->flags |= CTL_LUN_SENSE_DESC;
5879		set_ua = 1;
5880	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5881		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5882		/*
5883		 * Descriptor sense is currently turned on, and the user
5884		 * wants to turn it off.
5885		 */
5886		current_cp->rlec &= ~SCP_DSENSE;
5887		saved_cp->rlec &= ~SCP_DSENSE;
5888		lun->flags &= ~CTL_LUN_SENSE_DESC;
5889		set_ua = 1;
5890	}
5891	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5892	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5893		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5894		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5895		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5896		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5897		set_ua = 1;
5898	}
5899	if ((current_cp->eca_and_aen & SCP_SWP) !=
5900	    (user_cp->eca_and_aen & SCP_SWP)) {
5901		current_cp->eca_and_aen &= ~SCP_SWP;
5902		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5903		saved_cp->eca_and_aen &= ~SCP_SWP;
5904		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5905		set_ua = 1;
5906	}
5907	if (set_ua != 0)
5908		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5909	mtx_unlock(&lun->lun_lock);
5910	if (set_ua) {
5911		ctl_isc_announce_mode(lun,
5912		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5913		    page_index->page_code, page_index->subpage);
5914	}
5915	return (0);
5916}
5917
5918int
5919ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5920		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5921{
5922	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5923	struct ctl_lun *lun;
5924	int set_ua;
5925	uint32_t initidx;
5926
5927	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5928	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5929	set_ua = 0;
5930
5931	user_cp = (struct scsi_caching_page *)page_ptr;
5932	current_cp = (struct scsi_caching_page *)
5933		(page_index->page_data + (page_index->page_len *
5934		CTL_PAGE_CURRENT));
5935	saved_cp = (struct scsi_caching_page *)
5936		(page_index->page_data + (page_index->page_len *
5937		CTL_PAGE_SAVED));
5938
5939	mtx_lock(&lun->lun_lock);
5940	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5941	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5942		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5943		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5944		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5945		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5946		set_ua = 1;
5947	}
5948	if (set_ua != 0)
5949		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5950	mtx_unlock(&lun->lun_lock);
5951	if (set_ua) {
5952		ctl_isc_announce_mode(lun,
5953		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5954		    page_index->page_code, page_index->subpage);
5955	}
5956	return (0);
5957}
5958
5959int
5960ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5961				struct ctl_page_index *page_index,
5962				uint8_t *page_ptr)
5963{
5964	uint8_t *c;
5965	int i;
5966
5967	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5968	ctl_time_io_secs =
5969		(c[0] << 8) |
5970		(c[1] << 0) |
5971		0;
5972	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5973	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5974	printf("page data:");
5975	for (i=0; i<8; i++)
5976		printf(" %.2x",page_ptr[i]);
5977	printf("\n");
5978	return (0);
5979}
5980
5981int
5982ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5983			       struct ctl_page_index *page_index,
5984			       int pc)
5985{
5986	struct copan_debugconf_subpage *page;
5987
5988	page = (struct copan_debugconf_subpage *)page_index->page_data +
5989		(page_index->page_len * pc);
5990
5991	switch (pc) {
5992	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5993	case SMS_PAGE_CTRL_DEFAULT >> 6:
5994	case SMS_PAGE_CTRL_SAVED >> 6:
5995		/*
5996		 * We don't update the changeable or default bits for this page.
5997		 */
5998		break;
5999	case SMS_PAGE_CTRL_CURRENT >> 6:
6000		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6001		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6002		break;
6003	default:
6004		break;
6005	}
6006	return (0);
6007}
6008
6009
6010static int
6011ctl_do_mode_select(union ctl_io *io)
6012{
6013	struct scsi_mode_page_header *page_header;
6014	struct ctl_page_index *page_index;
6015	struct ctl_scsiio *ctsio;
6016	int page_len, page_len_offset, page_len_size;
6017	union ctl_modepage_info *modepage_info;
6018	struct ctl_lun *lun;
6019	int *len_left, *len_used;
6020	int retval, i;
6021
6022	ctsio = &io->scsiio;
6023	page_index = NULL;
6024	page_len = 0;
6025	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6026
6027	modepage_info = (union ctl_modepage_info *)
6028		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6029	len_left = &modepage_info->header.len_left;
6030	len_used = &modepage_info->header.len_used;
6031
6032do_next_page:
6033
6034	page_header = (struct scsi_mode_page_header *)
6035		(ctsio->kern_data_ptr + *len_used);
6036
6037	if (*len_left == 0) {
6038		free(ctsio->kern_data_ptr, M_CTL);
6039		ctl_set_success(ctsio);
6040		ctl_done((union ctl_io *)ctsio);
6041		return (CTL_RETVAL_COMPLETE);
6042	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6043
6044		free(ctsio->kern_data_ptr, M_CTL);
6045		ctl_set_param_len_error(ctsio);
6046		ctl_done((union ctl_io *)ctsio);
6047		return (CTL_RETVAL_COMPLETE);
6048
6049	} else if ((page_header->page_code & SMPH_SPF)
6050		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6051
6052		free(ctsio->kern_data_ptr, M_CTL);
6053		ctl_set_param_len_error(ctsio);
6054		ctl_done((union ctl_io *)ctsio);
6055		return (CTL_RETVAL_COMPLETE);
6056	}
6057
6058
6059	/*
6060	 * XXX KDM should we do something with the block descriptor?
6061	 */
6062	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6063		page_index = &lun->mode_pages.index[i];
6064		if (lun->be_lun->lun_type == T_DIRECT &&
6065		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6066			continue;
6067		if (lun->be_lun->lun_type == T_PROCESSOR &&
6068		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6069			continue;
6070		if (lun->be_lun->lun_type == T_CDROM &&
6071		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6072			continue;
6073
6074		if ((page_index->page_code & SMPH_PC_MASK) !=
6075		    (page_header->page_code & SMPH_PC_MASK))
6076			continue;
6077
6078		/*
6079		 * If neither page has a subpage code, then we've got a
6080		 * match.
6081		 */
6082		if (((page_index->page_code & SMPH_SPF) == 0)
6083		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6084			page_len = page_header->page_length;
6085			break;
6086		}
6087
6088		/*
6089		 * If both pages have subpages, then the subpage numbers
6090		 * have to match.
6091		 */
6092		if ((page_index->page_code & SMPH_SPF)
6093		  && (page_header->page_code & SMPH_SPF)) {
6094			struct scsi_mode_page_header_sp *sph;
6095
6096			sph = (struct scsi_mode_page_header_sp *)page_header;
6097			if (page_index->subpage == sph->subpage) {
6098				page_len = scsi_2btoul(sph->page_length);
6099				break;
6100			}
6101		}
6102	}
6103
6104	/*
6105	 * If we couldn't find the page, or if we don't have a mode select
6106	 * handler for it, send back an error to the user.
6107	 */
6108	if ((i >= CTL_NUM_MODE_PAGES)
6109	 || (page_index->select_handler == NULL)) {
6110		ctl_set_invalid_field(ctsio,
6111				      /*sks_valid*/ 1,
6112				      /*command*/ 0,
6113				      /*field*/ *len_used,
6114				      /*bit_valid*/ 0,
6115				      /*bit*/ 0);
6116		free(ctsio->kern_data_ptr, M_CTL);
6117		ctl_done((union ctl_io *)ctsio);
6118		return (CTL_RETVAL_COMPLETE);
6119	}
6120
6121	if (page_index->page_code & SMPH_SPF) {
6122		page_len_offset = 2;
6123		page_len_size = 2;
6124	} else {
6125		page_len_size = 1;
6126		page_len_offset = 1;
6127	}
6128
6129	/*
6130	 * If the length the initiator gives us isn't the one we specify in
6131	 * the mode page header, or if they didn't specify enough data in
6132	 * the CDB to avoid truncating this page, kick out the request.
6133	 */
6134	if ((page_len != (page_index->page_len - page_len_offset -
6135			  page_len_size))
6136	 || (*len_left < page_index->page_len)) {
6137
6138
6139		ctl_set_invalid_field(ctsio,
6140				      /*sks_valid*/ 1,
6141				      /*command*/ 0,
6142				      /*field*/ *len_used + page_len_offset,
6143				      /*bit_valid*/ 0,
6144				      /*bit*/ 0);
6145		free(ctsio->kern_data_ptr, M_CTL);
6146		ctl_done((union ctl_io *)ctsio);
6147		return (CTL_RETVAL_COMPLETE);
6148	}
6149
6150	/*
6151	 * Run through the mode page, checking to make sure that the bits
6152	 * the user changed are actually legal for him to change.
6153	 */
6154	for (i = 0; i < page_index->page_len; i++) {
6155		uint8_t *user_byte, *change_mask, *current_byte;
6156		int bad_bit;
6157		int j;
6158
6159		user_byte = (uint8_t *)page_header + i;
6160		change_mask = page_index->page_data +
6161			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6162		current_byte = page_index->page_data +
6163			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6164
6165		/*
6166		 * Check to see whether the user set any bits in this byte
6167		 * that he is not allowed to set.
6168		 */
6169		if ((*user_byte & ~(*change_mask)) ==
6170		    (*current_byte & ~(*change_mask)))
6171			continue;
6172
6173		/*
6174		 * Go through bit by bit to determine which one is illegal.
6175		 */
6176		bad_bit = 0;
6177		for (j = 7; j >= 0; j--) {
6178			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6179			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6180				bad_bit = i;
6181				break;
6182			}
6183		}
6184		ctl_set_invalid_field(ctsio,
6185				      /*sks_valid*/ 1,
6186				      /*command*/ 0,
6187				      /*field*/ *len_used + i,
6188				      /*bit_valid*/ 1,
6189				      /*bit*/ bad_bit);
6190		free(ctsio->kern_data_ptr, M_CTL);
6191		ctl_done((union ctl_io *)ctsio);
6192		return (CTL_RETVAL_COMPLETE);
6193	}
6194
6195	/*
6196	 * Decrement these before we call the page handler, since we may
6197	 * end up getting called back one way or another before the handler
6198	 * returns to this context.
6199	 */
6200	*len_left -= page_index->page_len;
6201	*len_used += page_index->page_len;
6202
6203	retval = page_index->select_handler(ctsio, page_index,
6204					    (uint8_t *)page_header);
6205
6206	/*
6207	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6208	 * wait until this queued command completes to finish processing
6209	 * the mode page.  If it returns anything other than
6210	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6211	 * already set the sense information, freed the data pointer, and
6212	 * completed the io for us.
6213	 */
6214	if (retval != CTL_RETVAL_COMPLETE)
6215		goto bailout_no_done;
6216
6217	/*
6218	 * If the initiator sent us more than one page, parse the next one.
6219	 */
6220	if (*len_left > 0)
6221		goto do_next_page;
6222
6223	ctl_set_success(ctsio);
6224	free(ctsio->kern_data_ptr, M_CTL);
6225	ctl_done((union ctl_io *)ctsio);
6226
6227bailout_no_done:
6228
6229	return (CTL_RETVAL_COMPLETE);
6230
6231}
6232
6233int
6234ctl_mode_select(struct ctl_scsiio *ctsio)
6235{
6236	int param_len, pf, sp;
6237	int header_size, bd_len;
6238	union ctl_modepage_info *modepage_info;
6239
6240	switch (ctsio->cdb[0]) {
6241	case MODE_SELECT_6: {
6242		struct scsi_mode_select_6 *cdb;
6243
6244		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6245
6246		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6247		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6248		param_len = cdb->length;
6249		header_size = sizeof(struct scsi_mode_header_6);
6250		break;
6251	}
6252	case MODE_SELECT_10: {
6253		struct scsi_mode_select_10 *cdb;
6254
6255		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6256
6257		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6258		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6259		param_len = scsi_2btoul(cdb->length);
6260		header_size = sizeof(struct scsi_mode_header_10);
6261		break;
6262	}
6263	default:
6264		ctl_set_invalid_opcode(ctsio);
6265		ctl_done((union ctl_io *)ctsio);
6266		return (CTL_RETVAL_COMPLETE);
6267	}
6268
6269	/*
6270	 * From SPC-3:
6271	 * "A parameter list length of zero indicates that the Data-Out Buffer
6272	 * shall be empty. This condition shall not be considered as an error."
6273	 */
6274	if (param_len == 0) {
6275		ctl_set_success(ctsio);
6276		ctl_done((union ctl_io *)ctsio);
6277		return (CTL_RETVAL_COMPLETE);
6278	}
6279
6280	/*
6281	 * Since we'll hit this the first time through, prior to
6282	 * allocation, we don't need to free a data buffer here.
6283	 */
6284	if (param_len < header_size) {
6285		ctl_set_param_len_error(ctsio);
6286		ctl_done((union ctl_io *)ctsio);
6287		return (CTL_RETVAL_COMPLETE);
6288	}
6289
6290	/*
6291	 * Allocate the data buffer and grab the user's data.  In theory,
6292	 * we shouldn't have to sanity check the parameter list length here
6293	 * because the maximum size is 64K.  We should be able to malloc
6294	 * that much without too many problems.
6295	 */
6296	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6297		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6298		ctsio->kern_data_len = param_len;
6299		ctsio->kern_total_len = param_len;
6300		ctsio->kern_data_resid = 0;
6301		ctsio->kern_rel_offset = 0;
6302		ctsio->kern_sg_entries = 0;
6303		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6304		ctsio->be_move_done = ctl_config_move_done;
6305		ctl_datamove((union ctl_io *)ctsio);
6306
6307		return (CTL_RETVAL_COMPLETE);
6308	}
6309
6310	switch (ctsio->cdb[0]) {
6311	case MODE_SELECT_6: {
6312		struct scsi_mode_header_6 *mh6;
6313
6314		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6315		bd_len = mh6->blk_desc_len;
6316		break;
6317	}
6318	case MODE_SELECT_10: {
6319		struct scsi_mode_header_10 *mh10;
6320
6321		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6322		bd_len = scsi_2btoul(mh10->blk_desc_len);
6323		break;
6324	}
6325	default:
6326		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6327	}
6328
6329	if (param_len < (header_size + bd_len)) {
6330		free(ctsio->kern_data_ptr, M_CTL);
6331		ctl_set_param_len_error(ctsio);
6332		ctl_done((union ctl_io *)ctsio);
6333		return (CTL_RETVAL_COMPLETE);
6334	}
6335
6336	/*
6337	 * Set the IO_CONT flag, so that if this I/O gets passed to
6338	 * ctl_config_write_done(), it'll get passed back to
6339	 * ctl_do_mode_select() for further processing, or completion if
6340	 * we're all done.
6341	 */
6342	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6343	ctsio->io_cont = ctl_do_mode_select;
6344
6345	modepage_info = (union ctl_modepage_info *)
6346		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6347	memset(modepage_info, 0, sizeof(*modepage_info));
6348	modepage_info->header.len_left = param_len - header_size - bd_len;
6349	modepage_info->header.len_used = header_size + bd_len;
6350
6351	return (ctl_do_mode_select((union ctl_io *)ctsio));
6352}
6353
6354int
6355ctl_mode_sense(struct ctl_scsiio *ctsio)
6356{
6357	struct ctl_lun *lun;
6358	int pc, page_code, dbd, llba, subpage;
6359	int alloc_len, page_len, header_len, total_len;
6360	struct scsi_mode_block_descr *block_desc;
6361	struct ctl_page_index *page_index;
6362
6363	dbd = 0;
6364	llba = 0;
6365	block_desc = NULL;
6366
6367	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6368
6369	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6370	switch (ctsio->cdb[0]) {
6371	case MODE_SENSE_6: {
6372		struct scsi_mode_sense_6 *cdb;
6373
6374		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6375
6376		header_len = sizeof(struct scsi_mode_hdr_6);
6377		if (cdb->byte2 & SMS_DBD)
6378			dbd = 1;
6379		else
6380			header_len += sizeof(struct scsi_mode_block_descr);
6381
6382		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6383		page_code = cdb->page & SMS_PAGE_CODE;
6384		subpage = cdb->subpage;
6385		alloc_len = cdb->length;
6386		break;
6387	}
6388	case MODE_SENSE_10: {
6389		struct scsi_mode_sense_10 *cdb;
6390
6391		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6392
6393		header_len = sizeof(struct scsi_mode_hdr_10);
6394
6395		if (cdb->byte2 & SMS_DBD)
6396			dbd = 1;
6397		else
6398			header_len += sizeof(struct scsi_mode_block_descr);
6399		if (cdb->byte2 & SMS10_LLBAA)
6400			llba = 1;
6401		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6402		page_code = cdb->page & SMS_PAGE_CODE;
6403		subpage = cdb->subpage;
6404		alloc_len = scsi_2btoul(cdb->length);
6405		break;
6406	}
6407	default:
6408		ctl_set_invalid_opcode(ctsio);
6409		ctl_done((union ctl_io *)ctsio);
6410		return (CTL_RETVAL_COMPLETE);
6411		break; /* NOTREACHED */
6412	}
6413
6414	/*
6415	 * We have to make a first pass through to calculate the size of
6416	 * the pages that match the user's query.  Then we allocate enough
6417	 * memory to hold it, and actually copy the data into the buffer.
6418	 */
6419	switch (page_code) {
6420	case SMS_ALL_PAGES_PAGE: {
6421		u_int i;
6422
6423		page_len = 0;
6424
6425		/*
6426		 * At the moment, values other than 0 and 0xff here are
6427		 * reserved according to SPC-3.
6428		 */
6429		if ((subpage != SMS_SUBPAGE_PAGE_0)
6430		 && (subpage != SMS_SUBPAGE_ALL)) {
6431			ctl_set_invalid_field(ctsio,
6432					      /*sks_valid*/ 1,
6433					      /*command*/ 1,
6434					      /*field*/ 3,
6435					      /*bit_valid*/ 0,
6436					      /*bit*/ 0);
6437			ctl_done((union ctl_io *)ctsio);
6438			return (CTL_RETVAL_COMPLETE);
6439		}
6440
6441		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6442			page_index = &lun->mode_pages.index[i];
6443
6444			/* Make sure the page is supported for this dev type */
6445			if (lun->be_lun->lun_type == T_DIRECT &&
6446			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6447				continue;
6448			if (lun->be_lun->lun_type == T_PROCESSOR &&
6449			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6450				continue;
6451			if (lun->be_lun->lun_type == T_CDROM &&
6452			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6453				continue;
6454
6455			/*
6456			 * We don't use this subpage if the user didn't
6457			 * request all subpages.
6458			 */
6459			if ((page_index->subpage != 0)
6460			 && (subpage == SMS_SUBPAGE_PAGE_0))
6461				continue;
6462
6463#if 0
6464			printf("found page %#x len %d\n",
6465			       page_index->page_code & SMPH_PC_MASK,
6466			       page_index->page_len);
6467#endif
6468			page_len += page_index->page_len;
6469		}
6470		break;
6471	}
6472	default: {
6473		u_int i;
6474
6475		page_len = 0;
6476
6477		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6478			page_index = &lun->mode_pages.index[i];
6479
6480			/* Make sure the page is supported for this dev type */
6481			if (lun->be_lun->lun_type == T_DIRECT &&
6482			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6483				continue;
6484			if (lun->be_lun->lun_type == T_PROCESSOR &&
6485			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6486				continue;
6487			if (lun->be_lun->lun_type == T_CDROM &&
6488			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6489				continue;
6490
6491			/* Look for the right page code */
6492			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6493				continue;
6494
6495			/* Look for the right subpage or the subpage wildcard*/
6496			if ((page_index->subpage != subpage)
6497			 && (subpage != SMS_SUBPAGE_ALL))
6498				continue;
6499
6500#if 0
6501			printf("found page %#x len %d\n",
6502			       page_index->page_code & SMPH_PC_MASK,
6503			       page_index->page_len);
6504#endif
6505
6506			page_len += page_index->page_len;
6507		}
6508
6509		if (page_len == 0) {
6510			ctl_set_invalid_field(ctsio,
6511					      /*sks_valid*/ 1,
6512					      /*command*/ 1,
6513					      /*field*/ 2,
6514					      /*bit_valid*/ 1,
6515					      /*bit*/ 5);
6516			ctl_done((union ctl_io *)ctsio);
6517			return (CTL_RETVAL_COMPLETE);
6518		}
6519		break;
6520	}
6521	}
6522
6523	total_len = header_len + page_len;
6524#if 0
6525	printf("header_len = %d, page_len = %d, total_len = %d\n",
6526	       header_len, page_len, total_len);
6527#endif
6528
6529	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6530	ctsio->kern_sg_entries = 0;
6531	ctsio->kern_data_resid = 0;
6532	ctsio->kern_rel_offset = 0;
6533	if (total_len < alloc_len) {
6534		ctsio->residual = alloc_len - total_len;
6535		ctsio->kern_data_len = total_len;
6536		ctsio->kern_total_len = total_len;
6537	} else {
6538		ctsio->residual = 0;
6539		ctsio->kern_data_len = alloc_len;
6540		ctsio->kern_total_len = alloc_len;
6541	}
6542
6543	switch (ctsio->cdb[0]) {
6544	case MODE_SENSE_6: {
6545		struct scsi_mode_hdr_6 *header;
6546
6547		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6548
6549		header->datalen = MIN(total_len - 1, 254);
6550		if (lun->be_lun->lun_type == T_DIRECT) {
6551			header->dev_specific = 0x10; /* DPOFUA */
6552			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6553			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6554			    .eca_and_aen & SCP_SWP) != 0)
6555				    header->dev_specific |= 0x80; /* WP */
6556		}
6557		if (dbd)
6558			header->block_descr_len = 0;
6559		else
6560			header->block_descr_len =
6561				sizeof(struct scsi_mode_block_descr);
6562		block_desc = (struct scsi_mode_block_descr *)&header[1];
6563		break;
6564	}
6565	case MODE_SENSE_10: {
6566		struct scsi_mode_hdr_10 *header;
6567		int datalen;
6568
6569		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6570
6571		datalen = MIN(total_len - 2, 65533);
6572		scsi_ulto2b(datalen, header->datalen);
6573		if (lun->be_lun->lun_type == T_DIRECT) {
6574			header->dev_specific = 0x10; /* DPOFUA */
6575			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6576			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6577			    .eca_and_aen & SCP_SWP) != 0)
6578				    header->dev_specific |= 0x80; /* WP */
6579		}
6580		if (dbd)
6581			scsi_ulto2b(0, header->block_descr_len);
6582		else
6583			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6584				    header->block_descr_len);
6585		block_desc = (struct scsi_mode_block_descr *)&header[1];
6586		break;
6587	}
6588	default:
6589		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6590	}
6591
6592	/*
6593	 * If we've got a disk, use its blocksize in the block
6594	 * descriptor.  Otherwise, just set it to 0.
6595	 */
6596	if (dbd == 0) {
6597		if (lun->be_lun->lun_type == T_DIRECT)
6598			scsi_ulto3b(lun->be_lun->blocksize,
6599				    block_desc->block_len);
6600		else
6601			scsi_ulto3b(0, block_desc->block_len);
6602	}
6603
6604	switch (page_code) {
6605	case SMS_ALL_PAGES_PAGE: {
6606		int i, data_used;
6607
6608		data_used = header_len;
6609		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6610			struct ctl_page_index *page_index;
6611
6612			page_index = &lun->mode_pages.index[i];
6613			if (lun->be_lun->lun_type == T_DIRECT &&
6614			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6615				continue;
6616			if (lun->be_lun->lun_type == T_PROCESSOR &&
6617			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6618				continue;
6619			if (lun->be_lun->lun_type == T_CDROM &&
6620			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6621				continue;
6622
6623			/*
6624			 * We don't use this subpage if the user didn't
6625			 * request all subpages.  We already checked (above)
6626			 * to make sure the user only specified a subpage
6627			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6628			 */
6629			if ((page_index->subpage != 0)
6630			 && (subpage == SMS_SUBPAGE_PAGE_0))
6631				continue;
6632
6633			/*
6634			 * Call the handler, if it exists, to update the
6635			 * page to the latest values.
6636			 */
6637			if (page_index->sense_handler != NULL)
6638				page_index->sense_handler(ctsio, page_index,pc);
6639
6640			memcpy(ctsio->kern_data_ptr + data_used,
6641			       page_index->page_data +
6642			       (page_index->page_len * pc),
6643			       page_index->page_len);
6644			data_used += page_index->page_len;
6645		}
6646		break;
6647	}
6648	default: {
6649		int i, data_used;
6650
6651		data_used = header_len;
6652
6653		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6654			struct ctl_page_index *page_index;
6655
6656			page_index = &lun->mode_pages.index[i];
6657
6658			/* Look for the right page code */
6659			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6660				continue;
6661
6662			/* Look for the right subpage or the subpage wildcard*/
6663			if ((page_index->subpage != subpage)
6664			 && (subpage != SMS_SUBPAGE_ALL))
6665				continue;
6666
6667			/* Make sure the page is supported for this dev type */
6668			if (lun->be_lun->lun_type == T_DIRECT &&
6669			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6670				continue;
6671			if (lun->be_lun->lun_type == T_PROCESSOR &&
6672			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6673				continue;
6674			if (lun->be_lun->lun_type == T_CDROM &&
6675			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6676				continue;
6677
6678			/*
6679			 * Call the handler, if it exists, to update the
6680			 * page to the latest values.
6681			 */
6682			if (page_index->sense_handler != NULL)
6683				page_index->sense_handler(ctsio, page_index,pc);
6684
6685			memcpy(ctsio->kern_data_ptr + data_used,
6686			       page_index->page_data +
6687			       (page_index->page_len * pc),
6688			       page_index->page_len);
6689			data_used += page_index->page_len;
6690		}
6691		break;
6692	}
6693	}
6694
6695	ctl_set_success(ctsio);
6696	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6697	ctsio->be_move_done = ctl_config_move_done;
6698	ctl_datamove((union ctl_io *)ctsio);
6699	return (CTL_RETVAL_COMPLETE);
6700}
6701
6702int
6703ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6704			       struct ctl_page_index *page_index,
6705			       int pc)
6706{
6707	struct ctl_lun *lun;
6708	struct scsi_log_param_header *phdr;
6709	uint8_t *data;
6710	uint64_t val;
6711
6712	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6713	data = page_index->page_data;
6714
6715	if (lun->backend->lun_attr != NULL &&
6716	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6717	     != UINT64_MAX) {
6718		phdr = (struct scsi_log_param_header *)data;
6719		scsi_ulto2b(0x0001, phdr->param_code);
6720		phdr->param_control = SLP_LBIN | SLP_LP;
6721		phdr->param_len = 8;
6722		data = (uint8_t *)(phdr + 1);
6723		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6724		data[4] = 0x02; /* per-pool */
6725		data += phdr->param_len;
6726	}
6727
6728	if (lun->backend->lun_attr != NULL &&
6729	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6730	     != UINT64_MAX) {
6731		phdr = (struct scsi_log_param_header *)data;
6732		scsi_ulto2b(0x0002, phdr->param_code);
6733		phdr->param_control = SLP_LBIN | SLP_LP;
6734		phdr->param_len = 8;
6735		data = (uint8_t *)(phdr + 1);
6736		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6737		data[4] = 0x01; /* per-LUN */
6738		data += phdr->param_len;
6739	}
6740
6741	if (lun->backend->lun_attr != NULL &&
6742	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6743	     != UINT64_MAX) {
6744		phdr = (struct scsi_log_param_header *)data;
6745		scsi_ulto2b(0x00f1, phdr->param_code);
6746		phdr->param_control = SLP_LBIN | SLP_LP;
6747		phdr->param_len = 8;
6748		data = (uint8_t *)(phdr + 1);
6749		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6750		data[4] = 0x02; /* per-pool */
6751		data += phdr->param_len;
6752	}
6753
6754	if (lun->backend->lun_attr != NULL &&
6755	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6756	     != UINT64_MAX) {
6757		phdr = (struct scsi_log_param_header *)data;
6758		scsi_ulto2b(0x00f2, phdr->param_code);
6759		phdr->param_control = SLP_LBIN | SLP_LP;
6760		phdr->param_len = 8;
6761		data = (uint8_t *)(phdr + 1);
6762		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6763		data[4] = 0x02; /* per-pool */
6764		data += phdr->param_len;
6765	}
6766
6767	page_index->page_len = data - page_index->page_data;
6768	return (0);
6769}
6770
6771int
6772ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6773			       struct ctl_page_index *page_index,
6774			       int pc)
6775{
6776	struct ctl_lun *lun;
6777	struct stat_page *data;
6778	uint64_t rn, wn, rb, wb;
6779	struct bintime rt, wt;
6780	int i;
6781
6782	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6783	data = (struct stat_page *)page_index->page_data;
6784
6785	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6786	data->sap.hdr.param_control = SLP_LBIN;
6787	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6788	    sizeof(struct scsi_log_param_header);
6789	rn = wn = rb = wb = 0;
6790	bintime_clear(&rt);
6791	bintime_clear(&wt);
6792	for (i = 0; i < CTL_MAX_PORTS; i++) {
6793		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6794		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6795		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6796		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6797		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6798		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6799	}
6800	scsi_u64to8b(rn, data->sap.read_num);
6801	scsi_u64to8b(wn, data->sap.write_num);
6802	if (lun->stats.blocksize > 0) {
6803		scsi_u64to8b(wb / lun->stats.blocksize,
6804		    data->sap.recvieved_lba);
6805		scsi_u64to8b(rb / lun->stats.blocksize,
6806		    data->sap.transmitted_lba);
6807	}
6808	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6809	    data->sap.read_int);
6810	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6811	    data->sap.write_int);
6812	scsi_u64to8b(0, data->sap.weighted_num);
6813	scsi_u64to8b(0, data->sap.weighted_int);
6814	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6815	data->it.hdr.param_control = SLP_LBIN;
6816	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6817	    sizeof(struct scsi_log_param_header);
6818#ifdef CTL_TIME_IO
6819	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6820#endif
6821	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6822	data->it.hdr.param_control = SLP_LBIN;
6823	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6824	    sizeof(struct scsi_log_param_header);
6825	scsi_ulto4b(3, data->ti.exponent);
6826	scsi_ulto4b(1, data->ti.integer);
6827
6828	page_index->page_len = sizeof(*data);
6829	return (0);
6830}
6831
6832int
6833ctl_log_sense(struct ctl_scsiio *ctsio)
6834{
6835	struct ctl_lun *lun;
6836	int i, pc, page_code, subpage;
6837	int alloc_len, total_len;
6838	struct ctl_page_index *page_index;
6839	struct scsi_log_sense *cdb;
6840	struct scsi_log_header *header;
6841
6842	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6843
6844	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6845	cdb = (struct scsi_log_sense *)ctsio->cdb;
6846	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6847	page_code = cdb->page & SLS_PAGE_CODE;
6848	subpage = cdb->subpage;
6849	alloc_len = scsi_2btoul(cdb->length);
6850
6851	page_index = NULL;
6852	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6853		page_index = &lun->log_pages.index[i];
6854
6855		/* Look for the right page code */
6856		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6857			continue;
6858
6859		/* Look for the right subpage or the subpage wildcard*/
6860		if (page_index->subpage != subpage)
6861			continue;
6862
6863		break;
6864	}
6865	if (i >= CTL_NUM_LOG_PAGES) {
6866		ctl_set_invalid_field(ctsio,
6867				      /*sks_valid*/ 1,
6868				      /*command*/ 1,
6869				      /*field*/ 2,
6870				      /*bit_valid*/ 0,
6871				      /*bit*/ 0);
6872		ctl_done((union ctl_io *)ctsio);
6873		return (CTL_RETVAL_COMPLETE);
6874	}
6875
6876	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6877
6878	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6879	ctsio->kern_sg_entries = 0;
6880	ctsio->kern_data_resid = 0;
6881	ctsio->kern_rel_offset = 0;
6882	if (total_len < alloc_len) {
6883		ctsio->residual = alloc_len - total_len;
6884		ctsio->kern_data_len = total_len;
6885		ctsio->kern_total_len = total_len;
6886	} else {
6887		ctsio->residual = 0;
6888		ctsio->kern_data_len = alloc_len;
6889		ctsio->kern_total_len = alloc_len;
6890	}
6891
6892	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6893	header->page = page_index->page_code;
6894	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6895		header->page |= SL_DS;
6896	if (page_index->subpage) {
6897		header->page |= SL_SPF;
6898		header->subpage = page_index->subpage;
6899	}
6900	scsi_ulto2b(page_index->page_len, header->datalen);
6901
6902	/*
6903	 * Call the handler, if it exists, to update the
6904	 * page to the latest values.
6905	 */
6906	if (page_index->sense_handler != NULL)
6907		page_index->sense_handler(ctsio, page_index, pc);
6908
6909	memcpy(header + 1, page_index->page_data, page_index->page_len);
6910
6911	ctl_set_success(ctsio);
6912	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6913	ctsio->be_move_done = ctl_config_move_done;
6914	ctl_datamove((union ctl_io *)ctsio);
6915	return (CTL_RETVAL_COMPLETE);
6916}
6917
6918int
6919ctl_read_capacity(struct ctl_scsiio *ctsio)
6920{
6921	struct scsi_read_capacity *cdb;
6922	struct scsi_read_capacity_data *data;
6923	struct ctl_lun *lun;
6924	uint32_t lba;
6925
6926	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6927
6928	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6929
6930	lba = scsi_4btoul(cdb->addr);
6931	if (((cdb->pmi & SRC_PMI) == 0)
6932	 && (lba != 0)) {
6933		ctl_set_invalid_field(/*ctsio*/ ctsio,
6934				      /*sks_valid*/ 1,
6935				      /*command*/ 1,
6936				      /*field*/ 2,
6937				      /*bit_valid*/ 0,
6938				      /*bit*/ 0);
6939		ctl_done((union ctl_io *)ctsio);
6940		return (CTL_RETVAL_COMPLETE);
6941	}
6942
6943	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6944
6945	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6946	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6947	ctsio->residual = 0;
6948	ctsio->kern_data_len = sizeof(*data);
6949	ctsio->kern_total_len = sizeof(*data);
6950	ctsio->kern_data_resid = 0;
6951	ctsio->kern_rel_offset = 0;
6952	ctsio->kern_sg_entries = 0;
6953
6954	/*
6955	 * If the maximum LBA is greater than 0xfffffffe, the user must
6956	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6957	 * serivce action set.
6958	 */
6959	if (lun->be_lun->maxlba > 0xfffffffe)
6960		scsi_ulto4b(0xffffffff, data->addr);
6961	else
6962		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6963
6964	/*
6965	 * XXX KDM this may not be 512 bytes...
6966	 */
6967	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6968
6969	ctl_set_success(ctsio);
6970	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6971	ctsio->be_move_done = ctl_config_move_done;
6972	ctl_datamove((union ctl_io *)ctsio);
6973	return (CTL_RETVAL_COMPLETE);
6974}
6975
6976int
6977ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6978{
6979	struct scsi_read_capacity_16 *cdb;
6980	struct scsi_read_capacity_data_long *data;
6981	struct ctl_lun *lun;
6982	uint64_t lba;
6983	uint32_t alloc_len;
6984
6985	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6986
6987	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6988
6989	alloc_len = scsi_4btoul(cdb->alloc_len);
6990	lba = scsi_8btou64(cdb->addr);
6991
6992	if ((cdb->reladr & SRC16_PMI)
6993	 && (lba != 0)) {
6994		ctl_set_invalid_field(/*ctsio*/ ctsio,
6995				      /*sks_valid*/ 1,
6996				      /*command*/ 1,
6997				      /*field*/ 2,
6998				      /*bit_valid*/ 0,
6999				      /*bit*/ 0);
7000		ctl_done((union ctl_io *)ctsio);
7001		return (CTL_RETVAL_COMPLETE);
7002	}
7003
7004	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7005
7006	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7007	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7008
7009	if (sizeof(*data) < alloc_len) {
7010		ctsio->residual = alloc_len - sizeof(*data);
7011		ctsio->kern_data_len = sizeof(*data);
7012		ctsio->kern_total_len = sizeof(*data);
7013	} else {
7014		ctsio->residual = 0;
7015		ctsio->kern_data_len = alloc_len;
7016		ctsio->kern_total_len = alloc_len;
7017	}
7018	ctsio->kern_data_resid = 0;
7019	ctsio->kern_rel_offset = 0;
7020	ctsio->kern_sg_entries = 0;
7021
7022	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7023	/* XXX KDM this may not be 512 bytes... */
7024	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7025	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7026	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7027	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7028		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7029
7030	ctl_set_success(ctsio);
7031	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7032	ctsio->be_move_done = ctl_config_move_done;
7033	ctl_datamove((union ctl_io *)ctsio);
7034	return (CTL_RETVAL_COMPLETE);
7035}
7036
7037int
7038ctl_get_lba_status(struct ctl_scsiio *ctsio)
7039{
7040	struct scsi_get_lba_status *cdb;
7041	struct scsi_get_lba_status_data *data;
7042	struct ctl_lun *lun;
7043	struct ctl_lba_len_flags *lbalen;
7044	uint64_t lba;
7045	uint32_t alloc_len, total_len;
7046	int retval;
7047
7048	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7049
7050	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7051	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7052	lba = scsi_8btou64(cdb->addr);
7053	alloc_len = scsi_4btoul(cdb->alloc_len);
7054
7055	if (lba > lun->be_lun->maxlba) {
7056		ctl_set_lba_out_of_range(ctsio);
7057		ctl_done((union ctl_io *)ctsio);
7058		return (CTL_RETVAL_COMPLETE);
7059	}
7060
7061	total_len = sizeof(*data) + sizeof(data->descr[0]);
7062	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7063	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7064
7065	if (total_len < alloc_len) {
7066		ctsio->residual = alloc_len - total_len;
7067		ctsio->kern_data_len = total_len;
7068		ctsio->kern_total_len = total_len;
7069	} else {
7070		ctsio->residual = 0;
7071		ctsio->kern_data_len = alloc_len;
7072		ctsio->kern_total_len = alloc_len;
7073	}
7074	ctsio->kern_data_resid = 0;
7075	ctsio->kern_rel_offset = 0;
7076	ctsio->kern_sg_entries = 0;
7077
7078	/* Fill dummy data in case backend can't tell anything. */
7079	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7080	scsi_u64to8b(lba, data->descr[0].addr);
7081	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7082	    data->descr[0].length);
7083	data->descr[0].status = 0; /* Mapped or unknown. */
7084
7085	ctl_set_success(ctsio);
7086	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7087	ctsio->be_move_done = ctl_config_move_done;
7088
7089	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7090	lbalen->lba = lba;
7091	lbalen->len = total_len;
7092	lbalen->flags = 0;
7093	retval = lun->backend->config_read((union ctl_io *)ctsio);
7094	return (CTL_RETVAL_COMPLETE);
7095}
7096
7097int
7098ctl_read_defect(struct ctl_scsiio *ctsio)
7099{
7100	struct scsi_read_defect_data_10 *ccb10;
7101	struct scsi_read_defect_data_12 *ccb12;
7102	struct scsi_read_defect_data_hdr_10 *data10;
7103	struct scsi_read_defect_data_hdr_12 *data12;
7104	uint32_t alloc_len, data_len;
7105	uint8_t format;
7106
7107	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7108
7109	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7110		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7111		format = ccb10->format;
7112		alloc_len = scsi_2btoul(ccb10->alloc_length);
7113		data_len = sizeof(*data10);
7114	} else {
7115		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7116		format = ccb12->format;
7117		alloc_len = scsi_4btoul(ccb12->alloc_length);
7118		data_len = sizeof(*data12);
7119	}
7120	if (alloc_len == 0) {
7121		ctl_set_success(ctsio);
7122		ctl_done((union ctl_io *)ctsio);
7123		return (CTL_RETVAL_COMPLETE);
7124	}
7125
7126	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7127	if (data_len < alloc_len) {
7128		ctsio->residual = alloc_len - data_len;
7129		ctsio->kern_data_len = data_len;
7130		ctsio->kern_total_len = data_len;
7131	} else {
7132		ctsio->residual = 0;
7133		ctsio->kern_data_len = alloc_len;
7134		ctsio->kern_total_len = alloc_len;
7135	}
7136	ctsio->kern_data_resid = 0;
7137	ctsio->kern_rel_offset = 0;
7138	ctsio->kern_sg_entries = 0;
7139
7140	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7141		data10 = (struct scsi_read_defect_data_hdr_10 *)
7142		    ctsio->kern_data_ptr;
7143		data10->format = format;
7144		scsi_ulto2b(0, data10->length);
7145	} else {
7146		data12 = (struct scsi_read_defect_data_hdr_12 *)
7147		    ctsio->kern_data_ptr;
7148		data12->format = format;
7149		scsi_ulto2b(0, data12->generation);
7150		scsi_ulto4b(0, data12->length);
7151	}
7152
7153	ctl_set_success(ctsio);
7154	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7155	ctsio->be_move_done = ctl_config_move_done;
7156	ctl_datamove((union ctl_io *)ctsio);
7157	return (CTL_RETVAL_COMPLETE);
7158}
7159
7160int
7161ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7162{
7163	struct scsi_maintenance_in *cdb;
7164	int retval;
7165	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7166	int num_ha_groups, num_target_ports, shared_group;
7167	struct ctl_lun *lun;
7168	struct ctl_softc *softc;
7169	struct ctl_port *port;
7170	struct scsi_target_group_data *rtg_ptr;
7171	struct scsi_target_group_data_extended *rtg_ext_ptr;
7172	struct scsi_target_port_group_descriptor *tpg_desc;
7173
7174	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7175
7176	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7177	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7178	softc = lun->ctl_softc;
7179
7180	retval = CTL_RETVAL_COMPLETE;
7181
7182	switch (cdb->byte2 & STG_PDF_MASK) {
7183	case STG_PDF_LENGTH:
7184		ext = 0;
7185		break;
7186	case STG_PDF_EXTENDED:
7187		ext = 1;
7188		break;
7189	default:
7190		ctl_set_invalid_field(/*ctsio*/ ctsio,
7191				      /*sks_valid*/ 1,
7192				      /*command*/ 1,
7193				      /*field*/ 2,
7194				      /*bit_valid*/ 1,
7195				      /*bit*/ 5);
7196		ctl_done((union ctl_io *)ctsio);
7197		return(retval);
7198	}
7199
7200	num_target_ports = 0;
7201	shared_group = (softc->is_single != 0);
7202	mtx_lock(&softc->ctl_lock);
7203	STAILQ_FOREACH(port, &softc->port_list, links) {
7204		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7205			continue;
7206		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7207			continue;
7208		num_target_ports++;
7209		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7210			shared_group = 1;
7211	}
7212	mtx_unlock(&softc->ctl_lock);
7213	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7214
7215	if (ext)
7216		total_len = sizeof(struct scsi_target_group_data_extended);
7217	else
7218		total_len = sizeof(struct scsi_target_group_data);
7219	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7220		(shared_group + num_ha_groups) +
7221	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7222
7223	alloc_len = scsi_4btoul(cdb->length);
7224
7225	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7226
7227	ctsio->kern_sg_entries = 0;
7228
7229	if (total_len < alloc_len) {
7230		ctsio->residual = alloc_len - total_len;
7231		ctsio->kern_data_len = total_len;
7232		ctsio->kern_total_len = total_len;
7233	} else {
7234		ctsio->residual = 0;
7235		ctsio->kern_data_len = alloc_len;
7236		ctsio->kern_total_len = alloc_len;
7237	}
7238	ctsio->kern_data_resid = 0;
7239	ctsio->kern_rel_offset = 0;
7240
7241	if (ext) {
7242		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7243		    ctsio->kern_data_ptr;
7244		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7245		rtg_ext_ptr->format_type = 0x10;
7246		rtg_ext_ptr->implicit_transition_time = 0;
7247		tpg_desc = &rtg_ext_ptr->groups[0];
7248	} else {
7249		rtg_ptr = (struct scsi_target_group_data *)
7250		    ctsio->kern_data_ptr;
7251		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7252		tpg_desc = &rtg_ptr->groups[0];
7253	}
7254
7255	mtx_lock(&softc->ctl_lock);
7256	pg = softc->port_min / softc->port_cnt;
7257	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7258		/* Some shelf is known to be primary. */
7259		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7260			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7261		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7262			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7263		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7264			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7265		else
7266			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7267		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7268			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7269		} else {
7270			ts = os;
7271			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7272		}
7273	} else {
7274		/* No known primary shelf. */
7275		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7276			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7277			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7278		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7279			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7280			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7281		} else {
7282			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7283		}
7284	}
7285	if (shared_group) {
7286		tpg_desc->pref_state = ts;
7287		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7288		    TPG_U_SUP | TPG_T_SUP;
7289		scsi_ulto2b(1, tpg_desc->target_port_group);
7290		tpg_desc->status = TPG_IMPLICIT;
7291		pc = 0;
7292		STAILQ_FOREACH(port, &softc->port_list, links) {
7293			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7294				continue;
7295			if (!softc->is_single &&
7296			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7297				continue;
7298			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7299				continue;
7300			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7301			    relative_target_port_identifier);
7302			pc++;
7303		}
7304		tpg_desc->target_port_count = pc;
7305		tpg_desc = (struct scsi_target_port_group_descriptor *)
7306		    &tpg_desc->descriptors[pc];
7307	}
7308	for (g = 0; g < num_ha_groups; g++) {
7309		tpg_desc->pref_state = (g == pg) ? ts : os;
7310		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7311		    TPG_U_SUP | TPG_T_SUP;
7312		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7313		tpg_desc->status = TPG_IMPLICIT;
7314		pc = 0;
7315		STAILQ_FOREACH(port, &softc->port_list, links) {
7316			if (port->targ_port < g * softc->port_cnt ||
7317			    port->targ_port >= (g + 1) * softc->port_cnt)
7318				continue;
7319			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7320				continue;
7321			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7322				continue;
7323			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7324				continue;
7325			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7326			    relative_target_port_identifier);
7327			pc++;
7328		}
7329		tpg_desc->target_port_count = pc;
7330		tpg_desc = (struct scsi_target_port_group_descriptor *)
7331		    &tpg_desc->descriptors[pc];
7332	}
7333	mtx_unlock(&softc->ctl_lock);
7334
7335	ctl_set_success(ctsio);
7336	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7337	ctsio->be_move_done = ctl_config_move_done;
7338	ctl_datamove((union ctl_io *)ctsio);
7339	return(retval);
7340}
7341
7342int
7343ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7344{
7345	struct ctl_lun *lun;
7346	struct scsi_report_supported_opcodes *cdb;
7347	const struct ctl_cmd_entry *entry, *sentry;
7348	struct scsi_report_supported_opcodes_all *all;
7349	struct scsi_report_supported_opcodes_descr *descr;
7350	struct scsi_report_supported_opcodes_one *one;
7351	int retval;
7352	int alloc_len, total_len;
7353	int opcode, service_action, i, j, num;
7354
7355	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7356
7357	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7358	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7359
7360	retval = CTL_RETVAL_COMPLETE;
7361
7362	opcode = cdb->requested_opcode;
7363	service_action = scsi_2btoul(cdb->requested_service_action);
7364	switch (cdb->options & RSO_OPTIONS_MASK) {
7365	case RSO_OPTIONS_ALL:
7366		num = 0;
7367		for (i = 0; i < 256; i++) {
7368			entry = &ctl_cmd_table[i];
7369			if (entry->flags & CTL_CMD_FLAG_SA5) {
7370				for (j = 0; j < 32; j++) {
7371					sentry = &((const struct ctl_cmd_entry *)
7372					    entry->execute)[j];
7373					if (ctl_cmd_applicable(
7374					    lun->be_lun->lun_type, sentry))
7375						num++;
7376				}
7377			} else {
7378				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7379				    entry))
7380					num++;
7381			}
7382		}
7383		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7384		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7385		break;
7386	case RSO_OPTIONS_OC:
7387		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7388			ctl_set_invalid_field(/*ctsio*/ ctsio,
7389					      /*sks_valid*/ 1,
7390					      /*command*/ 1,
7391					      /*field*/ 2,
7392					      /*bit_valid*/ 1,
7393					      /*bit*/ 2);
7394			ctl_done((union ctl_io *)ctsio);
7395			return (CTL_RETVAL_COMPLETE);
7396		}
7397		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7398		break;
7399	case RSO_OPTIONS_OC_SA:
7400		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7401		    service_action >= 32) {
7402			ctl_set_invalid_field(/*ctsio*/ ctsio,
7403					      /*sks_valid*/ 1,
7404					      /*command*/ 1,
7405					      /*field*/ 2,
7406					      /*bit_valid*/ 1,
7407					      /*bit*/ 2);
7408			ctl_done((union ctl_io *)ctsio);
7409			return (CTL_RETVAL_COMPLETE);
7410		}
7411		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7412		break;
7413	default:
7414		ctl_set_invalid_field(/*ctsio*/ ctsio,
7415				      /*sks_valid*/ 1,
7416				      /*command*/ 1,
7417				      /*field*/ 2,
7418				      /*bit_valid*/ 1,
7419				      /*bit*/ 2);
7420		ctl_done((union ctl_io *)ctsio);
7421		return (CTL_RETVAL_COMPLETE);
7422	}
7423
7424	alloc_len = scsi_4btoul(cdb->length);
7425
7426	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7427
7428	ctsio->kern_sg_entries = 0;
7429
7430	if (total_len < alloc_len) {
7431		ctsio->residual = alloc_len - total_len;
7432		ctsio->kern_data_len = total_len;
7433		ctsio->kern_total_len = total_len;
7434	} else {
7435		ctsio->residual = 0;
7436		ctsio->kern_data_len = alloc_len;
7437		ctsio->kern_total_len = alloc_len;
7438	}
7439	ctsio->kern_data_resid = 0;
7440	ctsio->kern_rel_offset = 0;
7441
7442	switch (cdb->options & RSO_OPTIONS_MASK) {
7443	case RSO_OPTIONS_ALL:
7444		all = (struct scsi_report_supported_opcodes_all *)
7445		    ctsio->kern_data_ptr;
7446		num = 0;
7447		for (i = 0; i < 256; i++) {
7448			entry = &ctl_cmd_table[i];
7449			if (entry->flags & CTL_CMD_FLAG_SA5) {
7450				for (j = 0; j < 32; j++) {
7451					sentry = &((const struct ctl_cmd_entry *)
7452					    entry->execute)[j];
7453					if (!ctl_cmd_applicable(
7454					    lun->be_lun->lun_type, sentry))
7455						continue;
7456					descr = &all->descr[num++];
7457					descr->opcode = i;
7458					scsi_ulto2b(j, descr->service_action);
7459					descr->flags = RSO_SERVACTV;
7460					scsi_ulto2b(sentry->length,
7461					    descr->cdb_length);
7462				}
7463			} else {
7464				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7465				    entry))
7466					continue;
7467				descr = &all->descr[num++];
7468				descr->opcode = i;
7469				scsi_ulto2b(0, descr->service_action);
7470				descr->flags = 0;
7471				scsi_ulto2b(entry->length, descr->cdb_length);
7472			}
7473		}
7474		scsi_ulto4b(
7475		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7476		    all->length);
7477		break;
7478	case RSO_OPTIONS_OC:
7479		one = (struct scsi_report_supported_opcodes_one *)
7480		    ctsio->kern_data_ptr;
7481		entry = &ctl_cmd_table[opcode];
7482		goto fill_one;
7483	case RSO_OPTIONS_OC_SA:
7484		one = (struct scsi_report_supported_opcodes_one *)
7485		    ctsio->kern_data_ptr;
7486		entry = &ctl_cmd_table[opcode];
7487		entry = &((const struct ctl_cmd_entry *)
7488		    entry->execute)[service_action];
7489fill_one:
7490		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7491			one->support = 3;
7492			scsi_ulto2b(entry->length, one->cdb_length);
7493			one->cdb_usage[0] = opcode;
7494			memcpy(&one->cdb_usage[1], entry->usage,
7495			    entry->length - 1);
7496		} else
7497			one->support = 1;
7498		break;
7499	}
7500
7501	ctl_set_success(ctsio);
7502	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7503	ctsio->be_move_done = ctl_config_move_done;
7504	ctl_datamove((union ctl_io *)ctsio);
7505	return(retval);
7506}
7507
7508int
7509ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7510{
7511	struct scsi_report_supported_tmf *cdb;
7512	struct scsi_report_supported_tmf_data *data;
7513	int retval;
7514	int alloc_len, total_len;
7515
7516	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7517
7518	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7519
7520	retval = CTL_RETVAL_COMPLETE;
7521
7522	total_len = sizeof(struct scsi_report_supported_tmf_data);
7523	alloc_len = scsi_4btoul(cdb->length);
7524
7525	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7526
7527	ctsio->kern_sg_entries = 0;
7528
7529	if (total_len < alloc_len) {
7530		ctsio->residual = alloc_len - total_len;
7531		ctsio->kern_data_len = total_len;
7532		ctsio->kern_total_len = total_len;
7533	} else {
7534		ctsio->residual = 0;
7535		ctsio->kern_data_len = alloc_len;
7536		ctsio->kern_total_len = alloc_len;
7537	}
7538	ctsio->kern_data_resid = 0;
7539	ctsio->kern_rel_offset = 0;
7540
7541	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7542	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7543	    RST_TRS;
7544	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7545
7546	ctl_set_success(ctsio);
7547	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7548	ctsio->be_move_done = ctl_config_move_done;
7549	ctl_datamove((union ctl_io *)ctsio);
7550	return (retval);
7551}
7552
7553int
7554ctl_report_timestamp(struct ctl_scsiio *ctsio)
7555{
7556	struct scsi_report_timestamp *cdb;
7557	struct scsi_report_timestamp_data *data;
7558	struct timeval tv;
7559	int64_t timestamp;
7560	int retval;
7561	int alloc_len, total_len;
7562
7563	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7564
7565	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7566
7567	retval = CTL_RETVAL_COMPLETE;
7568
7569	total_len = sizeof(struct scsi_report_timestamp_data);
7570	alloc_len = scsi_4btoul(cdb->length);
7571
7572	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7573
7574	ctsio->kern_sg_entries = 0;
7575
7576	if (total_len < alloc_len) {
7577		ctsio->residual = alloc_len - total_len;
7578		ctsio->kern_data_len = total_len;
7579		ctsio->kern_total_len = total_len;
7580	} else {
7581		ctsio->residual = 0;
7582		ctsio->kern_data_len = alloc_len;
7583		ctsio->kern_total_len = alloc_len;
7584	}
7585	ctsio->kern_data_resid = 0;
7586	ctsio->kern_rel_offset = 0;
7587
7588	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7589	scsi_ulto2b(sizeof(*data) - 2, data->length);
7590	data->origin = RTS_ORIG_OUTSIDE;
7591	getmicrotime(&tv);
7592	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7593	scsi_ulto4b(timestamp >> 16, data->timestamp);
7594	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7595
7596	ctl_set_success(ctsio);
7597	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7598	ctsio->be_move_done = ctl_config_move_done;
7599	ctl_datamove((union ctl_io *)ctsio);
7600	return (retval);
7601}
7602
7603int
7604ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7605{
7606	struct scsi_per_res_in *cdb;
7607	int alloc_len, total_len = 0;
7608	/* struct scsi_per_res_in_rsrv in_data; */
7609	struct ctl_lun *lun;
7610	struct ctl_softc *softc;
7611	uint64_t key;
7612
7613	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7614
7615	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7616
7617	alloc_len = scsi_2btoul(cdb->length);
7618
7619	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7620	softc = lun->ctl_softc;
7621
7622retry:
7623	mtx_lock(&lun->lun_lock);
7624	switch (cdb->action) {
7625	case SPRI_RK: /* read keys */
7626		total_len = sizeof(struct scsi_per_res_in_keys) +
7627			lun->pr_key_count *
7628			sizeof(struct scsi_per_res_key);
7629		break;
7630	case SPRI_RR: /* read reservation */
7631		if (lun->flags & CTL_LUN_PR_RESERVED)
7632			total_len = sizeof(struct scsi_per_res_in_rsrv);
7633		else
7634			total_len = sizeof(struct scsi_per_res_in_header);
7635		break;
7636	case SPRI_RC: /* report capabilities */
7637		total_len = sizeof(struct scsi_per_res_cap);
7638		break;
7639	case SPRI_RS: /* read full status */
7640		total_len = sizeof(struct scsi_per_res_in_header) +
7641		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7642		    lun->pr_key_count;
7643		break;
7644	default:
7645		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7646	}
7647	mtx_unlock(&lun->lun_lock);
7648
7649	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7650
7651	if (total_len < alloc_len) {
7652		ctsio->residual = alloc_len - total_len;
7653		ctsio->kern_data_len = total_len;
7654		ctsio->kern_total_len = total_len;
7655	} else {
7656		ctsio->residual = 0;
7657		ctsio->kern_data_len = alloc_len;
7658		ctsio->kern_total_len = alloc_len;
7659	}
7660
7661	ctsio->kern_data_resid = 0;
7662	ctsio->kern_rel_offset = 0;
7663	ctsio->kern_sg_entries = 0;
7664
7665	mtx_lock(&lun->lun_lock);
7666	switch (cdb->action) {
7667	case SPRI_RK: { // read keys
7668        struct scsi_per_res_in_keys *res_keys;
7669		int i, key_count;
7670
7671		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7672
7673		/*
7674		 * We had to drop the lock to allocate our buffer, which
7675		 * leaves time for someone to come in with another
7676		 * persistent reservation.  (That is unlikely, though,
7677		 * since this should be the only persistent reservation
7678		 * command active right now.)
7679		 */
7680		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7681		    (lun->pr_key_count *
7682		     sizeof(struct scsi_per_res_key)))){
7683			mtx_unlock(&lun->lun_lock);
7684			free(ctsio->kern_data_ptr, M_CTL);
7685			printf("%s: reservation length changed, retrying\n",
7686			       __func__);
7687			goto retry;
7688		}
7689
7690		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7691
7692		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7693			     lun->pr_key_count, res_keys->header.length);
7694
7695		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7696			if ((key = ctl_get_prkey(lun, i)) == 0)
7697				continue;
7698
7699			/*
7700			 * We used lun->pr_key_count to calculate the
7701			 * size to allocate.  If it turns out the number of
7702			 * initiators with the registered flag set is
7703			 * larger than that (i.e. they haven't been kept in
7704			 * sync), we've got a problem.
7705			 */
7706			if (key_count >= lun->pr_key_count) {
7707				key_count++;
7708				continue;
7709			}
7710			scsi_u64to8b(key, res_keys->keys[key_count].key);
7711			key_count++;
7712		}
7713		break;
7714	}
7715	case SPRI_RR: { // read reservation
7716		struct scsi_per_res_in_rsrv *res;
7717		int tmp_len, header_only;
7718
7719		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7720
7721		scsi_ulto4b(lun->pr_generation, res->header.generation);
7722
7723		if (lun->flags & CTL_LUN_PR_RESERVED)
7724		{
7725			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7726			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7727				    res->header.length);
7728			header_only = 0;
7729		} else {
7730			tmp_len = sizeof(struct scsi_per_res_in_header);
7731			scsi_ulto4b(0, res->header.length);
7732			header_only = 1;
7733		}
7734
7735		/*
7736		 * We had to drop the lock to allocate our buffer, which
7737		 * leaves time for someone to come in with another
7738		 * persistent reservation.  (That is unlikely, though,
7739		 * since this should be the only persistent reservation
7740		 * command active right now.)
7741		 */
7742		if (tmp_len != total_len) {
7743			mtx_unlock(&lun->lun_lock);
7744			free(ctsio->kern_data_ptr, M_CTL);
7745			printf("%s: reservation status changed, retrying\n",
7746			       __func__);
7747			goto retry;
7748		}
7749
7750		/*
7751		 * No reservation held, so we're done.
7752		 */
7753		if (header_only != 0)
7754			break;
7755
7756		/*
7757		 * If the registration is an All Registrants type, the key
7758		 * is 0, since it doesn't really matter.
7759		 */
7760		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7761			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7762			    res->data.reservation);
7763		}
7764		res->data.scopetype = lun->pr_res_type;
7765		break;
7766	}
7767	case SPRI_RC:     //report capabilities
7768	{
7769		struct scsi_per_res_cap *res_cap;
7770		uint16_t type_mask;
7771
7772		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7773		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7774		res_cap->flags1 = SPRI_CRH;
7775		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7776		type_mask = SPRI_TM_WR_EX_AR |
7777			    SPRI_TM_EX_AC_RO |
7778			    SPRI_TM_WR_EX_RO |
7779			    SPRI_TM_EX_AC |
7780			    SPRI_TM_WR_EX |
7781			    SPRI_TM_EX_AC_AR;
7782		scsi_ulto2b(type_mask, res_cap->type_mask);
7783		break;
7784	}
7785	case SPRI_RS: { // read full status
7786		struct scsi_per_res_in_full *res_status;
7787		struct scsi_per_res_in_full_desc *res_desc;
7788		struct ctl_port *port;
7789		int i, len;
7790
7791		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7792
7793		/*
7794		 * We had to drop the lock to allocate our buffer, which
7795		 * leaves time for someone to come in with another
7796		 * persistent reservation.  (That is unlikely, though,
7797		 * since this should be the only persistent reservation
7798		 * command active right now.)
7799		 */
7800		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7801		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7802		     lun->pr_key_count)){
7803			mtx_unlock(&lun->lun_lock);
7804			free(ctsio->kern_data_ptr, M_CTL);
7805			printf("%s: reservation length changed, retrying\n",
7806			       __func__);
7807			goto retry;
7808		}
7809
7810		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7811
7812		res_desc = &res_status->desc[0];
7813		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7814			if ((key = ctl_get_prkey(lun, i)) == 0)
7815				continue;
7816
7817			scsi_u64to8b(key, res_desc->res_key.key);
7818			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7819			    (lun->pr_res_idx == i ||
7820			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7821				res_desc->flags = SPRI_FULL_R_HOLDER;
7822				res_desc->scopetype = lun->pr_res_type;
7823			}
7824			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7825			    res_desc->rel_trgt_port_id);
7826			len = 0;
7827			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7828			if (port != NULL)
7829				len = ctl_create_iid(port,
7830				    i % CTL_MAX_INIT_PER_PORT,
7831				    res_desc->transport_id);
7832			scsi_ulto4b(len, res_desc->additional_length);
7833			res_desc = (struct scsi_per_res_in_full_desc *)
7834			    &res_desc->transport_id[len];
7835		}
7836		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7837		    res_status->header.length);
7838		break;
7839	}
7840	default:
7841		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7842	}
7843	mtx_unlock(&lun->lun_lock);
7844
7845	ctl_set_success(ctsio);
7846	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7847	ctsio->be_move_done = ctl_config_move_done;
7848	ctl_datamove((union ctl_io *)ctsio);
7849	return (CTL_RETVAL_COMPLETE);
7850}
7851
7852/*
7853 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7854 * it should return.
7855 */
7856static int
7857ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7858		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7859		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7860		struct scsi_per_res_out_parms* param)
7861{
7862	union ctl_ha_msg persis_io;
7863	int i;
7864
7865	mtx_lock(&lun->lun_lock);
7866	if (sa_res_key == 0) {
7867		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7868			/* validate scope and type */
7869			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7870			     SPR_LU_SCOPE) {
7871				mtx_unlock(&lun->lun_lock);
7872				ctl_set_invalid_field(/*ctsio*/ ctsio,
7873						      /*sks_valid*/ 1,
7874						      /*command*/ 1,
7875						      /*field*/ 2,
7876						      /*bit_valid*/ 1,
7877						      /*bit*/ 4);
7878				ctl_done((union ctl_io *)ctsio);
7879				return (1);
7880			}
7881
7882		        if (type>8 || type==2 || type==4 || type==0) {
7883				mtx_unlock(&lun->lun_lock);
7884				ctl_set_invalid_field(/*ctsio*/ ctsio,
7885       	           				      /*sks_valid*/ 1,
7886						      /*command*/ 1,
7887						      /*field*/ 2,
7888						      /*bit_valid*/ 1,
7889						      /*bit*/ 0);
7890				ctl_done((union ctl_io *)ctsio);
7891				return (1);
7892		        }
7893
7894			/*
7895			 * Unregister everybody else and build UA for
7896			 * them
7897			 */
7898			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7899				if (i == residx || ctl_get_prkey(lun, i) == 0)
7900					continue;
7901
7902				ctl_clr_prkey(lun, i);
7903				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7904			}
7905			lun->pr_key_count = 1;
7906			lun->pr_res_type = type;
7907			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7908			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7909				lun->pr_res_idx = residx;
7910			lun->pr_generation++;
7911			mtx_unlock(&lun->lun_lock);
7912
7913			/* send msg to other side */
7914			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7915			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7916			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7917			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7918			persis_io.pr.pr_info.res_type = type;
7919			memcpy(persis_io.pr.pr_info.sa_res_key,
7920			       param->serv_act_res_key,
7921			       sizeof(param->serv_act_res_key));
7922			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7923			    sizeof(persis_io.pr), M_WAITOK);
7924		} else {
7925			/* not all registrants */
7926			mtx_unlock(&lun->lun_lock);
7927			free(ctsio->kern_data_ptr, M_CTL);
7928			ctl_set_invalid_field(ctsio,
7929					      /*sks_valid*/ 1,
7930					      /*command*/ 0,
7931					      /*field*/ 8,
7932					      /*bit_valid*/ 0,
7933					      /*bit*/ 0);
7934			ctl_done((union ctl_io *)ctsio);
7935			return (1);
7936		}
7937	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7938		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7939		int found = 0;
7940
7941		if (res_key == sa_res_key) {
7942			/* special case */
7943			/*
7944			 * The spec implies this is not good but doesn't
7945			 * say what to do. There are two choices either
7946			 * generate a res conflict or check condition
7947			 * with illegal field in parameter data. Since
7948			 * that is what is done when the sa_res_key is
7949			 * zero I'll take that approach since this has
7950			 * to do with the sa_res_key.
7951			 */
7952			mtx_unlock(&lun->lun_lock);
7953			free(ctsio->kern_data_ptr, M_CTL);
7954			ctl_set_invalid_field(ctsio,
7955					      /*sks_valid*/ 1,
7956					      /*command*/ 0,
7957					      /*field*/ 8,
7958					      /*bit_valid*/ 0,
7959					      /*bit*/ 0);
7960			ctl_done((union ctl_io *)ctsio);
7961			return (1);
7962		}
7963
7964		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7965			if (ctl_get_prkey(lun, i) != sa_res_key)
7966				continue;
7967
7968			found = 1;
7969			ctl_clr_prkey(lun, i);
7970			lun->pr_key_count--;
7971			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7972		}
7973		if (!found) {
7974			mtx_unlock(&lun->lun_lock);
7975			free(ctsio->kern_data_ptr, M_CTL);
7976			ctl_set_reservation_conflict(ctsio);
7977			ctl_done((union ctl_io *)ctsio);
7978			return (CTL_RETVAL_COMPLETE);
7979		}
7980		lun->pr_generation++;
7981		mtx_unlock(&lun->lun_lock);
7982
7983		/* send msg to other side */
7984		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7985		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7986		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7987		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7988		persis_io.pr.pr_info.res_type = type;
7989		memcpy(persis_io.pr.pr_info.sa_res_key,
7990		       param->serv_act_res_key,
7991		       sizeof(param->serv_act_res_key));
7992		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7993		    sizeof(persis_io.pr), M_WAITOK);
7994	} else {
7995		/* Reserved but not all registrants */
7996		/* sa_res_key is res holder */
7997		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7998			/* validate scope and type */
7999			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8000			     SPR_LU_SCOPE) {
8001				mtx_unlock(&lun->lun_lock);
8002				ctl_set_invalid_field(/*ctsio*/ ctsio,
8003						      /*sks_valid*/ 1,
8004						      /*command*/ 1,
8005						      /*field*/ 2,
8006						      /*bit_valid*/ 1,
8007						      /*bit*/ 4);
8008				ctl_done((union ctl_io *)ctsio);
8009				return (1);
8010			}
8011
8012			if (type>8 || type==2 || type==4 || type==0) {
8013				mtx_unlock(&lun->lun_lock);
8014				ctl_set_invalid_field(/*ctsio*/ ctsio,
8015						      /*sks_valid*/ 1,
8016						      /*command*/ 1,
8017						      /*field*/ 2,
8018						      /*bit_valid*/ 1,
8019						      /*bit*/ 0);
8020				ctl_done((union ctl_io *)ctsio);
8021				return (1);
8022			}
8023
8024			/*
8025			 * Do the following:
8026			 * if sa_res_key != res_key remove all
8027			 * registrants w/sa_res_key and generate UA
8028			 * for these registrants(Registrations
8029			 * Preempted) if it wasn't an exclusive
8030			 * reservation generate UA(Reservations
8031			 * Preempted) for all other registered nexuses
8032			 * if the type has changed. Establish the new
8033			 * reservation and holder. If res_key and
8034			 * sa_res_key are the same do the above
8035			 * except don't unregister the res holder.
8036			 */
8037
8038			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8039				if (i == residx || ctl_get_prkey(lun, i) == 0)
8040					continue;
8041
8042				if (sa_res_key == ctl_get_prkey(lun, i)) {
8043					ctl_clr_prkey(lun, i);
8044					lun->pr_key_count--;
8045					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8046				} else if (type != lun->pr_res_type &&
8047				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8048				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8049					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8050				}
8051			}
8052			lun->pr_res_type = type;
8053			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8054			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8055				lun->pr_res_idx = residx;
8056			else
8057				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8058			lun->pr_generation++;
8059			mtx_unlock(&lun->lun_lock);
8060
8061			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8062			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8063			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8064			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8065			persis_io.pr.pr_info.res_type = type;
8066			memcpy(persis_io.pr.pr_info.sa_res_key,
8067			       param->serv_act_res_key,
8068			       sizeof(param->serv_act_res_key));
8069			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8070			    sizeof(persis_io.pr), M_WAITOK);
8071		} else {
8072			/*
8073			 * sa_res_key is not the res holder just
8074			 * remove registrants
8075			 */
8076			int found=0;
8077
8078			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8079				if (sa_res_key != ctl_get_prkey(lun, i))
8080					continue;
8081
8082				found = 1;
8083				ctl_clr_prkey(lun, i);
8084				lun->pr_key_count--;
8085				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8086			}
8087
8088			if (!found) {
8089				mtx_unlock(&lun->lun_lock);
8090				free(ctsio->kern_data_ptr, M_CTL);
8091				ctl_set_reservation_conflict(ctsio);
8092				ctl_done((union ctl_io *)ctsio);
8093		        	return (1);
8094			}
8095			lun->pr_generation++;
8096			mtx_unlock(&lun->lun_lock);
8097
8098			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8099			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8100			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8101			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8102			persis_io.pr.pr_info.res_type = type;
8103			memcpy(persis_io.pr.pr_info.sa_res_key,
8104			       param->serv_act_res_key,
8105			       sizeof(param->serv_act_res_key));
8106			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8107			    sizeof(persis_io.pr), M_WAITOK);
8108		}
8109	}
8110	return (0);
8111}
8112
8113static void
8114ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8115{
8116	uint64_t sa_res_key;
8117	int i;
8118
8119	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8120
8121	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8122	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8123	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8124		if (sa_res_key == 0) {
8125			/*
8126			 * Unregister everybody else and build UA for
8127			 * them
8128			 */
8129			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8130				if (i == msg->pr.pr_info.residx ||
8131				    ctl_get_prkey(lun, i) == 0)
8132					continue;
8133
8134				ctl_clr_prkey(lun, i);
8135				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8136			}
8137
8138			lun->pr_key_count = 1;
8139			lun->pr_res_type = msg->pr.pr_info.res_type;
8140			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8141			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8142				lun->pr_res_idx = msg->pr.pr_info.residx;
8143		} else {
8144		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8145				if (sa_res_key == ctl_get_prkey(lun, i))
8146					continue;
8147
8148				ctl_clr_prkey(lun, i);
8149				lun->pr_key_count--;
8150				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8151			}
8152		}
8153	} else {
8154		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8155			if (i == msg->pr.pr_info.residx ||
8156			    ctl_get_prkey(lun, i) == 0)
8157				continue;
8158
8159			if (sa_res_key == ctl_get_prkey(lun, i)) {
8160				ctl_clr_prkey(lun, i);
8161				lun->pr_key_count--;
8162				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8163			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8164			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8165			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8166				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8167			}
8168		}
8169		lun->pr_res_type = msg->pr.pr_info.res_type;
8170		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8171		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8172			lun->pr_res_idx = msg->pr.pr_info.residx;
8173		else
8174			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8175	}
8176	lun->pr_generation++;
8177
8178}
8179
8180
8181int
8182ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8183{
8184	int retval;
8185	u_int32_t param_len;
8186	struct scsi_per_res_out *cdb;
8187	struct ctl_lun *lun;
8188	struct scsi_per_res_out_parms* param;
8189	struct ctl_softc *softc;
8190	uint32_t residx;
8191	uint64_t res_key, sa_res_key, key;
8192	uint8_t type;
8193	union ctl_ha_msg persis_io;
8194	int    i;
8195
8196	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8197
8198	retval = CTL_RETVAL_COMPLETE;
8199
8200	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8201	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8202	softc = lun->ctl_softc;
8203
8204	/*
8205	 * We only support whole-LUN scope.  The scope & type are ignored for
8206	 * register, register and ignore existing key and clear.
8207	 * We sometimes ignore scope and type on preempts too!!
8208	 * Verify reservation type here as well.
8209	 */
8210	type = cdb->scope_type & SPR_TYPE_MASK;
8211	if ((cdb->action == SPRO_RESERVE)
8212	 || (cdb->action == SPRO_RELEASE)) {
8213		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8214			ctl_set_invalid_field(/*ctsio*/ ctsio,
8215					      /*sks_valid*/ 1,
8216					      /*command*/ 1,
8217					      /*field*/ 2,
8218					      /*bit_valid*/ 1,
8219					      /*bit*/ 4);
8220			ctl_done((union ctl_io *)ctsio);
8221			return (CTL_RETVAL_COMPLETE);
8222		}
8223
8224		if (type>8 || type==2 || type==4 || type==0) {
8225			ctl_set_invalid_field(/*ctsio*/ ctsio,
8226					      /*sks_valid*/ 1,
8227					      /*command*/ 1,
8228					      /*field*/ 2,
8229					      /*bit_valid*/ 1,
8230					      /*bit*/ 0);
8231			ctl_done((union ctl_io *)ctsio);
8232			return (CTL_RETVAL_COMPLETE);
8233		}
8234	}
8235
8236	param_len = scsi_4btoul(cdb->length);
8237
8238	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8239		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8240		ctsio->kern_data_len = param_len;
8241		ctsio->kern_total_len = param_len;
8242		ctsio->kern_data_resid = 0;
8243		ctsio->kern_rel_offset = 0;
8244		ctsio->kern_sg_entries = 0;
8245		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8246		ctsio->be_move_done = ctl_config_move_done;
8247		ctl_datamove((union ctl_io *)ctsio);
8248
8249		return (CTL_RETVAL_COMPLETE);
8250	}
8251
8252	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8253
8254	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8255	res_key = scsi_8btou64(param->res_key.key);
8256	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8257
8258	/*
8259	 * Validate the reservation key here except for SPRO_REG_IGNO
8260	 * This must be done for all other service actions
8261	 */
8262	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8263		mtx_lock(&lun->lun_lock);
8264		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8265			if (res_key != key) {
8266				/*
8267				 * The current key passed in doesn't match
8268				 * the one the initiator previously
8269				 * registered.
8270				 */
8271				mtx_unlock(&lun->lun_lock);
8272				free(ctsio->kern_data_ptr, M_CTL);
8273				ctl_set_reservation_conflict(ctsio);
8274				ctl_done((union ctl_io *)ctsio);
8275				return (CTL_RETVAL_COMPLETE);
8276			}
8277		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8278			/*
8279			 * We are not registered
8280			 */
8281			mtx_unlock(&lun->lun_lock);
8282			free(ctsio->kern_data_ptr, M_CTL);
8283			ctl_set_reservation_conflict(ctsio);
8284			ctl_done((union ctl_io *)ctsio);
8285			return (CTL_RETVAL_COMPLETE);
8286		} else if (res_key != 0) {
8287			/*
8288			 * We are not registered and trying to register but
8289			 * the register key isn't zero.
8290			 */
8291			mtx_unlock(&lun->lun_lock);
8292			free(ctsio->kern_data_ptr, M_CTL);
8293			ctl_set_reservation_conflict(ctsio);
8294			ctl_done((union ctl_io *)ctsio);
8295			return (CTL_RETVAL_COMPLETE);
8296		}
8297		mtx_unlock(&lun->lun_lock);
8298	}
8299
8300	switch (cdb->action & SPRO_ACTION_MASK) {
8301	case SPRO_REGISTER:
8302	case SPRO_REG_IGNO: {
8303
8304#if 0
8305		printf("Registration received\n");
8306#endif
8307
8308		/*
8309		 * We don't support any of these options, as we report in
8310		 * the read capabilities request (see
8311		 * ctl_persistent_reserve_in(), above).
8312		 */
8313		if ((param->flags & SPR_SPEC_I_PT)
8314		 || (param->flags & SPR_ALL_TG_PT)
8315		 || (param->flags & SPR_APTPL)) {
8316			int bit_ptr;
8317
8318			if (param->flags & SPR_APTPL)
8319				bit_ptr = 0;
8320			else if (param->flags & SPR_ALL_TG_PT)
8321				bit_ptr = 2;
8322			else /* SPR_SPEC_I_PT */
8323				bit_ptr = 3;
8324
8325			free(ctsio->kern_data_ptr, M_CTL);
8326			ctl_set_invalid_field(ctsio,
8327					      /*sks_valid*/ 1,
8328					      /*command*/ 0,
8329					      /*field*/ 20,
8330					      /*bit_valid*/ 1,
8331					      /*bit*/ bit_ptr);
8332			ctl_done((union ctl_io *)ctsio);
8333			return (CTL_RETVAL_COMPLETE);
8334		}
8335
8336		mtx_lock(&lun->lun_lock);
8337
8338		/*
8339		 * The initiator wants to clear the
8340		 * key/unregister.
8341		 */
8342		if (sa_res_key == 0) {
8343			if ((res_key == 0
8344			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8345			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8346			  && ctl_get_prkey(lun, residx) == 0)) {
8347				mtx_unlock(&lun->lun_lock);
8348				goto done;
8349			}
8350
8351			ctl_clr_prkey(lun, residx);
8352			lun->pr_key_count--;
8353
8354			if (residx == lun->pr_res_idx) {
8355				lun->flags &= ~CTL_LUN_PR_RESERVED;
8356				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8357
8358				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8359				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8360				    lun->pr_key_count) {
8361					/*
8362					 * If the reservation is a registrants
8363					 * only type we need to generate a UA
8364					 * for other registered inits.  The
8365					 * sense code should be RESERVATIONS
8366					 * RELEASED
8367					 */
8368
8369					for (i = softc->init_min; i < softc->init_max; i++){
8370						if (ctl_get_prkey(lun, i) == 0)
8371							continue;
8372						ctl_est_ua(lun, i,
8373						    CTL_UA_RES_RELEASE);
8374					}
8375				}
8376				lun->pr_res_type = 0;
8377			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8378				if (lun->pr_key_count==0) {
8379					lun->flags &= ~CTL_LUN_PR_RESERVED;
8380					lun->pr_res_type = 0;
8381					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8382				}
8383			}
8384			lun->pr_generation++;
8385			mtx_unlock(&lun->lun_lock);
8386
8387			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8388			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8389			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8390			persis_io.pr.pr_info.residx = residx;
8391			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8392			    sizeof(persis_io.pr), M_WAITOK);
8393		} else /* sa_res_key != 0 */ {
8394
8395			/*
8396			 * If we aren't registered currently then increment
8397			 * the key count and set the registered flag.
8398			 */
8399			ctl_alloc_prkey(lun, residx);
8400			if (ctl_get_prkey(lun, residx) == 0)
8401				lun->pr_key_count++;
8402			ctl_set_prkey(lun, residx, sa_res_key);
8403			lun->pr_generation++;
8404			mtx_unlock(&lun->lun_lock);
8405
8406			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8407			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8408			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8409			persis_io.pr.pr_info.residx = residx;
8410			memcpy(persis_io.pr.pr_info.sa_res_key,
8411			       param->serv_act_res_key,
8412			       sizeof(param->serv_act_res_key));
8413			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8414			    sizeof(persis_io.pr), M_WAITOK);
8415		}
8416
8417		break;
8418	}
8419	case SPRO_RESERVE:
8420#if 0
8421                printf("Reserve executed type %d\n", type);
8422#endif
8423		mtx_lock(&lun->lun_lock);
8424		if (lun->flags & CTL_LUN_PR_RESERVED) {
8425			/*
8426			 * if this isn't the reservation holder and it's
8427			 * not a "all registrants" type or if the type is
8428			 * different then we have a conflict
8429			 */
8430			if ((lun->pr_res_idx != residx
8431			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8432			 || lun->pr_res_type != type) {
8433				mtx_unlock(&lun->lun_lock);
8434				free(ctsio->kern_data_ptr, M_CTL);
8435				ctl_set_reservation_conflict(ctsio);
8436				ctl_done((union ctl_io *)ctsio);
8437				return (CTL_RETVAL_COMPLETE);
8438			}
8439			mtx_unlock(&lun->lun_lock);
8440		} else /* create a reservation */ {
8441			/*
8442			 * If it's not an "all registrants" type record
8443			 * reservation holder
8444			 */
8445			if (type != SPR_TYPE_WR_EX_AR
8446			 && type != SPR_TYPE_EX_AC_AR)
8447				lun->pr_res_idx = residx; /* Res holder */
8448			else
8449				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8450
8451			lun->flags |= CTL_LUN_PR_RESERVED;
8452			lun->pr_res_type = type;
8453
8454			mtx_unlock(&lun->lun_lock);
8455
8456			/* send msg to other side */
8457			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8458			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8459			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8460			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8461			persis_io.pr.pr_info.res_type = type;
8462			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8463			    sizeof(persis_io.pr), M_WAITOK);
8464		}
8465		break;
8466
8467	case SPRO_RELEASE:
8468		mtx_lock(&lun->lun_lock);
8469		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8470			/* No reservation exists return good status */
8471			mtx_unlock(&lun->lun_lock);
8472			goto done;
8473		}
8474		/*
8475		 * Is this nexus a reservation holder?
8476		 */
8477		if (lun->pr_res_idx != residx
8478		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8479			/*
8480			 * not a res holder return good status but
8481			 * do nothing
8482			 */
8483			mtx_unlock(&lun->lun_lock);
8484			goto done;
8485		}
8486
8487		if (lun->pr_res_type != type) {
8488			mtx_unlock(&lun->lun_lock);
8489			free(ctsio->kern_data_ptr, M_CTL);
8490			ctl_set_illegal_pr_release(ctsio);
8491			ctl_done((union ctl_io *)ctsio);
8492			return (CTL_RETVAL_COMPLETE);
8493		}
8494
8495		/* okay to release */
8496		lun->flags &= ~CTL_LUN_PR_RESERVED;
8497		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8498		lun->pr_res_type = 0;
8499
8500		/*
8501		 * if this isn't an exclusive access
8502		 * res generate UA for all other
8503		 * registrants.
8504		 */
8505		if (type != SPR_TYPE_EX_AC
8506		 && type != SPR_TYPE_WR_EX) {
8507			for (i = softc->init_min; i < softc->init_max; i++) {
8508				if (i == residx || ctl_get_prkey(lun, i) == 0)
8509					continue;
8510				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8511			}
8512		}
8513		mtx_unlock(&lun->lun_lock);
8514
8515		/* Send msg to other side */
8516		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8517		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8518		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8519		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8520		     sizeof(persis_io.pr), M_WAITOK);
8521		break;
8522
8523	case SPRO_CLEAR:
8524		/* send msg to other side */
8525
8526		mtx_lock(&lun->lun_lock);
8527		lun->flags &= ~CTL_LUN_PR_RESERVED;
8528		lun->pr_res_type = 0;
8529		lun->pr_key_count = 0;
8530		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8531
8532		ctl_clr_prkey(lun, residx);
8533		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8534			if (ctl_get_prkey(lun, i) != 0) {
8535				ctl_clr_prkey(lun, i);
8536				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8537			}
8538		lun->pr_generation++;
8539		mtx_unlock(&lun->lun_lock);
8540
8541		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8542		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8543		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8544		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8545		     sizeof(persis_io.pr), M_WAITOK);
8546		break;
8547
8548	case SPRO_PREEMPT:
8549	case SPRO_PRE_ABO: {
8550		int nretval;
8551
8552		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8553					  residx, ctsio, cdb, param);
8554		if (nretval != 0)
8555			return (CTL_RETVAL_COMPLETE);
8556		break;
8557	}
8558	default:
8559		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8560	}
8561
8562done:
8563	free(ctsio->kern_data_ptr, M_CTL);
8564	ctl_set_success(ctsio);
8565	ctl_done((union ctl_io *)ctsio);
8566
8567	return (retval);
8568}
8569
8570/*
8571 * This routine is for handling a message from the other SC pertaining to
8572 * persistent reserve out. All the error checking will have been done
8573 * so only perorming the action need be done here to keep the two
8574 * in sync.
8575 */
8576static void
8577ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8578{
8579	struct ctl_softc *softc = control_softc;
8580	struct ctl_lun *lun;
8581	int i;
8582	uint32_t residx, targ_lun;
8583
8584	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8585	mtx_lock(&softc->ctl_lock);
8586	if ((targ_lun >= CTL_MAX_LUNS) ||
8587	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8588		mtx_unlock(&softc->ctl_lock);
8589		return;
8590	}
8591	mtx_lock(&lun->lun_lock);
8592	mtx_unlock(&softc->ctl_lock);
8593	if (lun->flags & CTL_LUN_DISABLED) {
8594		mtx_unlock(&lun->lun_lock);
8595		return;
8596	}
8597	residx = ctl_get_initindex(&msg->hdr.nexus);
8598	switch(msg->pr.pr_info.action) {
8599	case CTL_PR_REG_KEY:
8600		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8601		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8602			lun->pr_key_count++;
8603		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8604		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8605		lun->pr_generation++;
8606		break;
8607
8608	case CTL_PR_UNREG_KEY:
8609		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8610		lun->pr_key_count--;
8611
8612		/* XXX Need to see if the reservation has been released */
8613		/* if so do we need to generate UA? */
8614		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8615			lun->flags &= ~CTL_LUN_PR_RESERVED;
8616			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8617
8618			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8619			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8620			    lun->pr_key_count) {
8621				/*
8622				 * If the reservation is a registrants
8623				 * only type we need to generate a UA
8624				 * for other registered inits.  The
8625				 * sense code should be RESERVATIONS
8626				 * RELEASED
8627				 */
8628
8629				for (i = softc->init_min; i < softc->init_max; i++) {
8630					if (ctl_get_prkey(lun, i) == 0)
8631						continue;
8632
8633					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8634				}
8635			}
8636			lun->pr_res_type = 0;
8637		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8638			if (lun->pr_key_count==0) {
8639				lun->flags &= ~CTL_LUN_PR_RESERVED;
8640				lun->pr_res_type = 0;
8641				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8642			}
8643		}
8644		lun->pr_generation++;
8645		break;
8646
8647	case CTL_PR_RESERVE:
8648		lun->flags |= CTL_LUN_PR_RESERVED;
8649		lun->pr_res_type = msg->pr.pr_info.res_type;
8650		lun->pr_res_idx = msg->pr.pr_info.residx;
8651
8652		break;
8653
8654	case CTL_PR_RELEASE:
8655		/*
8656		 * if this isn't an exclusive access res generate UA for all
8657		 * other registrants.
8658		 */
8659		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8660		    lun->pr_res_type != SPR_TYPE_WR_EX) {
8661			for (i = softc->init_min; i < softc->init_max; i++)
8662				if (i == residx || ctl_get_prkey(lun, i) == 0)
8663					continue;
8664				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8665		}
8666
8667		lun->flags &= ~CTL_LUN_PR_RESERVED;
8668		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8669		lun->pr_res_type = 0;
8670		break;
8671
8672	case CTL_PR_PREEMPT:
8673		ctl_pro_preempt_other(lun, msg);
8674		break;
8675	case CTL_PR_CLEAR:
8676		lun->flags &= ~CTL_LUN_PR_RESERVED;
8677		lun->pr_res_type = 0;
8678		lun->pr_key_count = 0;
8679		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8680
8681		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8682			if (ctl_get_prkey(lun, i) == 0)
8683				continue;
8684			ctl_clr_prkey(lun, i);
8685			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8686		}
8687		lun->pr_generation++;
8688		break;
8689	}
8690
8691	mtx_unlock(&lun->lun_lock);
8692}
8693
8694int
8695ctl_read_write(struct ctl_scsiio *ctsio)
8696{
8697	struct ctl_lun *lun;
8698	struct ctl_lba_len_flags *lbalen;
8699	uint64_t lba;
8700	uint32_t num_blocks;
8701	int flags, retval;
8702	int isread;
8703
8704	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8705
8706	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8707
8708	flags = 0;
8709	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8710	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8711	switch (ctsio->cdb[0]) {
8712	case READ_6:
8713	case WRITE_6: {
8714		struct scsi_rw_6 *cdb;
8715
8716		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8717
8718		lba = scsi_3btoul(cdb->addr);
8719		/* only 5 bits are valid in the most significant address byte */
8720		lba &= 0x1fffff;
8721		num_blocks = cdb->length;
8722		/*
8723		 * This is correct according to SBC-2.
8724		 */
8725		if (num_blocks == 0)
8726			num_blocks = 256;
8727		break;
8728	}
8729	case READ_10:
8730	case WRITE_10: {
8731		struct scsi_rw_10 *cdb;
8732
8733		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8734		if (cdb->byte2 & SRW10_FUA)
8735			flags |= CTL_LLF_FUA;
8736		if (cdb->byte2 & SRW10_DPO)
8737			flags |= CTL_LLF_DPO;
8738		lba = scsi_4btoul(cdb->addr);
8739		num_blocks = scsi_2btoul(cdb->length);
8740		break;
8741	}
8742	case WRITE_VERIFY_10: {
8743		struct scsi_write_verify_10 *cdb;
8744
8745		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8746		flags |= CTL_LLF_FUA;
8747		if (cdb->byte2 & SWV_DPO)
8748			flags |= CTL_LLF_DPO;
8749		lba = scsi_4btoul(cdb->addr);
8750		num_blocks = scsi_2btoul(cdb->length);
8751		break;
8752	}
8753	case READ_12:
8754	case WRITE_12: {
8755		struct scsi_rw_12 *cdb;
8756
8757		cdb = (struct scsi_rw_12 *)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_4btoul(cdb->addr);
8763		num_blocks = scsi_4btoul(cdb->length);
8764		break;
8765	}
8766	case WRITE_VERIFY_12: {
8767		struct scsi_write_verify_12 *cdb;
8768
8769		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8770		flags |= CTL_LLF_FUA;
8771		if (cdb->byte2 & SWV_DPO)
8772			flags |= CTL_LLF_DPO;
8773		lba = scsi_4btoul(cdb->addr);
8774		num_blocks = scsi_4btoul(cdb->length);
8775		break;
8776	}
8777	case READ_16:
8778	case WRITE_16: {
8779		struct scsi_rw_16 *cdb;
8780
8781		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8782		if (cdb->byte2 & SRW12_FUA)
8783			flags |= CTL_LLF_FUA;
8784		if (cdb->byte2 & SRW12_DPO)
8785			flags |= CTL_LLF_DPO;
8786		lba = scsi_8btou64(cdb->addr);
8787		num_blocks = scsi_4btoul(cdb->length);
8788		break;
8789	}
8790	case WRITE_ATOMIC_16: {
8791		struct scsi_write_atomic_16 *cdb;
8792
8793		if (lun->be_lun->atomicblock == 0) {
8794			ctl_set_invalid_opcode(ctsio);
8795			ctl_done((union ctl_io *)ctsio);
8796			return (CTL_RETVAL_COMPLETE);
8797		}
8798
8799		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8800		if (cdb->byte2 & SRW12_FUA)
8801			flags |= CTL_LLF_FUA;
8802		if (cdb->byte2 & SRW12_DPO)
8803			flags |= CTL_LLF_DPO;
8804		lba = scsi_8btou64(cdb->addr);
8805		num_blocks = scsi_2btoul(cdb->length);
8806		if (num_blocks > lun->be_lun->atomicblock) {
8807			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8808			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8809			    /*bit*/ 0);
8810			ctl_done((union ctl_io *)ctsio);
8811			return (CTL_RETVAL_COMPLETE);
8812		}
8813		break;
8814	}
8815	case WRITE_VERIFY_16: {
8816		struct scsi_write_verify_16 *cdb;
8817
8818		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8819		flags |= CTL_LLF_FUA;
8820		if (cdb->byte2 & SWV_DPO)
8821			flags |= CTL_LLF_DPO;
8822		lba = scsi_8btou64(cdb->addr);
8823		num_blocks = scsi_4btoul(cdb->length);
8824		break;
8825	}
8826	default:
8827		/*
8828		 * We got a command we don't support.  This shouldn't
8829		 * happen, commands should be filtered out above us.
8830		 */
8831		ctl_set_invalid_opcode(ctsio);
8832		ctl_done((union ctl_io *)ctsio);
8833
8834		return (CTL_RETVAL_COMPLETE);
8835		break; /* NOTREACHED */
8836	}
8837
8838	/*
8839	 * The first check is to make sure we're in bounds, the second
8840	 * check is to catch wrap-around problems.  If the lba + num blocks
8841	 * is less than the lba, then we've wrapped around and the block
8842	 * range is invalid anyway.
8843	 */
8844	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8845	 || ((lba + num_blocks) < lba)) {
8846		ctl_set_lba_out_of_range(ctsio);
8847		ctl_done((union ctl_io *)ctsio);
8848		return (CTL_RETVAL_COMPLETE);
8849	}
8850
8851	/*
8852	 * According to SBC-3, a transfer length of 0 is not an error.
8853	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8854	 * translates to 256 blocks for those commands.
8855	 */
8856	if (num_blocks == 0) {
8857		ctl_set_success(ctsio);
8858		ctl_done((union ctl_io *)ctsio);
8859		return (CTL_RETVAL_COMPLETE);
8860	}
8861
8862	/* Set FUA and/or DPO if caches are disabled. */
8863	if (isread) {
8864		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8865		    SCP_RCD) != 0)
8866			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8867	} else {
8868		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8869		    SCP_WCE) == 0)
8870			flags |= CTL_LLF_FUA;
8871	}
8872
8873	lbalen = (struct ctl_lba_len_flags *)
8874	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8875	lbalen->lba = lba;
8876	lbalen->len = num_blocks;
8877	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8878
8879	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8880	ctsio->kern_rel_offset = 0;
8881
8882	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8883
8884	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8885	return (retval);
8886}
8887
8888static int
8889ctl_cnw_cont(union ctl_io *io)
8890{
8891	struct ctl_scsiio *ctsio;
8892	struct ctl_lun *lun;
8893	struct ctl_lba_len_flags *lbalen;
8894	int retval;
8895
8896	ctsio = &io->scsiio;
8897	ctsio->io_hdr.status = CTL_STATUS_NONE;
8898	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8899	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8900	lbalen = (struct ctl_lba_len_flags *)
8901	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8902	lbalen->flags &= ~CTL_LLF_COMPARE;
8903	lbalen->flags |= CTL_LLF_WRITE;
8904
8905	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8906	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8907	return (retval);
8908}
8909
8910int
8911ctl_cnw(struct ctl_scsiio *ctsio)
8912{
8913	struct ctl_lun *lun;
8914	struct ctl_lba_len_flags *lbalen;
8915	uint64_t lba;
8916	uint32_t num_blocks;
8917	int flags, retval;
8918
8919	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8920
8921	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8922
8923	flags = 0;
8924	switch (ctsio->cdb[0]) {
8925	case COMPARE_AND_WRITE: {
8926		struct scsi_compare_and_write *cdb;
8927
8928		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8929		if (cdb->byte2 & SRW10_FUA)
8930			flags |= CTL_LLF_FUA;
8931		if (cdb->byte2 & SRW10_DPO)
8932			flags |= CTL_LLF_DPO;
8933		lba = scsi_8btou64(cdb->addr);
8934		num_blocks = cdb->length;
8935		break;
8936	}
8937	default:
8938		/*
8939		 * We got a command we don't support.  This shouldn't
8940		 * happen, commands should be filtered out above us.
8941		 */
8942		ctl_set_invalid_opcode(ctsio);
8943		ctl_done((union ctl_io *)ctsio);
8944
8945		return (CTL_RETVAL_COMPLETE);
8946		break; /* NOTREACHED */
8947	}
8948
8949	/*
8950	 * The first check is to make sure we're in bounds, the second
8951	 * check is to catch wrap-around problems.  If the lba + num blocks
8952	 * is less than the lba, then we've wrapped around and the block
8953	 * range is invalid anyway.
8954	 */
8955	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8956	 || ((lba + num_blocks) < lba)) {
8957		ctl_set_lba_out_of_range(ctsio);
8958		ctl_done((union ctl_io *)ctsio);
8959		return (CTL_RETVAL_COMPLETE);
8960	}
8961
8962	/*
8963	 * According to SBC-3, a transfer length of 0 is not an error.
8964	 */
8965	if (num_blocks == 0) {
8966		ctl_set_success(ctsio);
8967		ctl_done((union ctl_io *)ctsio);
8968		return (CTL_RETVAL_COMPLETE);
8969	}
8970
8971	/* Set FUA if write cache is disabled. */
8972	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8973	    SCP_WCE) == 0)
8974		flags |= CTL_LLF_FUA;
8975
8976	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8977	ctsio->kern_rel_offset = 0;
8978
8979	/*
8980	 * Set the IO_CONT flag, so that if this I/O gets passed to
8981	 * ctl_data_submit_done(), it'll get passed back to
8982	 * ctl_ctl_cnw_cont() for further processing.
8983	 */
8984	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8985	ctsio->io_cont = ctl_cnw_cont;
8986
8987	lbalen = (struct ctl_lba_len_flags *)
8988	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8989	lbalen->lba = lba;
8990	lbalen->len = num_blocks;
8991	lbalen->flags = CTL_LLF_COMPARE | flags;
8992
8993	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8994	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8995	return (retval);
8996}
8997
8998int
8999ctl_verify(struct ctl_scsiio *ctsio)
9000{
9001	struct ctl_lun *lun;
9002	struct ctl_lba_len_flags *lbalen;
9003	uint64_t lba;
9004	uint32_t num_blocks;
9005	int bytchk, flags;
9006	int retval;
9007
9008	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9009
9010	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9011
9012	bytchk = 0;
9013	flags = CTL_LLF_FUA;
9014	switch (ctsio->cdb[0]) {
9015	case VERIFY_10: {
9016		struct scsi_verify_10 *cdb;
9017
9018		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9019		if (cdb->byte2 & SVFY_BYTCHK)
9020			bytchk = 1;
9021		if (cdb->byte2 & SVFY_DPO)
9022			flags |= CTL_LLF_DPO;
9023		lba = scsi_4btoul(cdb->addr);
9024		num_blocks = scsi_2btoul(cdb->length);
9025		break;
9026	}
9027	case VERIFY_12: {
9028		struct scsi_verify_12 *cdb;
9029
9030		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9031		if (cdb->byte2 & SVFY_BYTCHK)
9032			bytchk = 1;
9033		if (cdb->byte2 & SVFY_DPO)
9034			flags |= CTL_LLF_DPO;
9035		lba = scsi_4btoul(cdb->addr);
9036		num_blocks = scsi_4btoul(cdb->length);
9037		break;
9038	}
9039	case VERIFY_16: {
9040		struct scsi_rw_16 *cdb;
9041
9042		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9043		if (cdb->byte2 & SVFY_BYTCHK)
9044			bytchk = 1;
9045		if (cdb->byte2 & SVFY_DPO)
9046			flags |= CTL_LLF_DPO;
9047		lba = scsi_8btou64(cdb->addr);
9048		num_blocks = scsi_4btoul(cdb->length);
9049		break;
9050	}
9051	default:
9052		/*
9053		 * We got a command we don't support.  This shouldn't
9054		 * happen, commands should be filtered out above us.
9055		 */
9056		ctl_set_invalid_opcode(ctsio);
9057		ctl_done((union ctl_io *)ctsio);
9058		return (CTL_RETVAL_COMPLETE);
9059	}
9060
9061	/*
9062	 * The first check is to make sure we're in bounds, the second
9063	 * check is to catch wrap-around problems.  If the lba + num blocks
9064	 * is less than the lba, then we've wrapped around and the block
9065	 * range is invalid anyway.
9066	 */
9067	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9068	 || ((lba + num_blocks) < lba)) {
9069		ctl_set_lba_out_of_range(ctsio);
9070		ctl_done((union ctl_io *)ctsio);
9071		return (CTL_RETVAL_COMPLETE);
9072	}
9073
9074	/*
9075	 * According to SBC-3, a transfer length of 0 is not an error.
9076	 */
9077	if (num_blocks == 0) {
9078		ctl_set_success(ctsio);
9079		ctl_done((union ctl_io *)ctsio);
9080		return (CTL_RETVAL_COMPLETE);
9081	}
9082
9083	lbalen = (struct ctl_lba_len_flags *)
9084	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9085	lbalen->lba = lba;
9086	lbalen->len = num_blocks;
9087	if (bytchk) {
9088		lbalen->flags = CTL_LLF_COMPARE | flags;
9089		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9090	} else {
9091		lbalen->flags = CTL_LLF_VERIFY | flags;
9092		ctsio->kern_total_len = 0;
9093	}
9094	ctsio->kern_rel_offset = 0;
9095
9096	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9097	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9098	return (retval);
9099}
9100
9101int
9102ctl_report_luns(struct ctl_scsiio *ctsio)
9103{
9104	struct ctl_softc *softc;
9105	struct scsi_report_luns *cdb;
9106	struct scsi_report_luns_data *lun_data;
9107	struct ctl_lun *lun, *request_lun;
9108	struct ctl_port *port;
9109	int num_luns, retval;
9110	uint32_t alloc_len, lun_datalen;
9111	int num_filled;
9112	uint32_t initidx, targ_lun_id, lun_id;
9113
9114	retval = CTL_RETVAL_COMPLETE;
9115	cdb = (struct scsi_report_luns *)ctsio->cdb;
9116	port = ctl_io_port(&ctsio->io_hdr);
9117	softc = port->ctl_softc;
9118
9119	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9120
9121	mtx_lock(&softc->ctl_lock);
9122	num_luns = 0;
9123	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9124		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9125			num_luns++;
9126	}
9127	mtx_unlock(&softc->ctl_lock);
9128
9129	switch (cdb->select_report) {
9130	case RPL_REPORT_DEFAULT:
9131	case RPL_REPORT_ALL:
9132	case RPL_REPORT_NONSUBSID:
9133		break;
9134	case RPL_REPORT_WELLKNOWN:
9135	case RPL_REPORT_ADMIN:
9136	case RPL_REPORT_CONGLOM:
9137		num_luns = 0;
9138		break;
9139	default:
9140		ctl_set_invalid_field(ctsio,
9141				      /*sks_valid*/ 1,
9142				      /*command*/ 1,
9143				      /*field*/ 2,
9144				      /*bit_valid*/ 0,
9145				      /*bit*/ 0);
9146		ctl_done((union ctl_io *)ctsio);
9147		return (retval);
9148		break; /* NOTREACHED */
9149	}
9150
9151	alloc_len = scsi_4btoul(cdb->length);
9152	/*
9153	 * The initiator has to allocate at least 16 bytes for this request,
9154	 * so he can at least get the header and the first LUN.  Otherwise
9155	 * we reject the request (per SPC-3 rev 14, section 6.21).
9156	 */
9157	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9158	    sizeof(struct scsi_report_luns_lundata))) {
9159		ctl_set_invalid_field(ctsio,
9160				      /*sks_valid*/ 1,
9161				      /*command*/ 1,
9162				      /*field*/ 6,
9163				      /*bit_valid*/ 0,
9164				      /*bit*/ 0);
9165		ctl_done((union ctl_io *)ctsio);
9166		return (retval);
9167	}
9168
9169	request_lun = (struct ctl_lun *)
9170		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9171
9172	lun_datalen = sizeof(*lun_data) +
9173		(num_luns * sizeof(struct scsi_report_luns_lundata));
9174
9175	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9176	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9177	ctsio->kern_sg_entries = 0;
9178
9179	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9180
9181	mtx_lock(&softc->ctl_lock);
9182	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9183		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9184		if (lun_id >= CTL_MAX_LUNS)
9185			continue;
9186		lun = softc->ctl_luns[lun_id];
9187		if (lun == NULL)
9188			continue;
9189
9190		be64enc(lun_data->luns[num_filled++].lundata,
9191		    ctl_encode_lun(targ_lun_id));
9192
9193		/*
9194		 * According to SPC-3, rev 14 section 6.21:
9195		 *
9196		 * "The execution of a REPORT LUNS command to any valid and
9197		 * installed logical unit shall clear the REPORTED LUNS DATA
9198		 * HAS CHANGED unit attention condition for all logical
9199		 * units of that target with respect to the requesting
9200		 * initiator. A valid and installed logical unit is one
9201		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9202		 * INQUIRY data (see 6.4.2)."
9203		 *
9204		 * If request_lun is NULL, the LUN this report luns command
9205		 * was issued to is either disabled or doesn't exist. In that
9206		 * case, we shouldn't clear any pending lun change unit
9207		 * attention.
9208		 */
9209		if (request_lun != NULL) {
9210			mtx_lock(&lun->lun_lock);
9211			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9212			mtx_unlock(&lun->lun_lock);
9213		}
9214	}
9215	mtx_unlock(&softc->ctl_lock);
9216
9217	/*
9218	 * It's quite possible that we've returned fewer LUNs than we allocated
9219	 * space for.  Trim it.
9220	 */
9221	lun_datalen = sizeof(*lun_data) +
9222		(num_filled * sizeof(struct scsi_report_luns_lundata));
9223
9224	if (lun_datalen < alloc_len) {
9225		ctsio->residual = alloc_len - lun_datalen;
9226		ctsio->kern_data_len = lun_datalen;
9227		ctsio->kern_total_len = lun_datalen;
9228	} else {
9229		ctsio->residual = 0;
9230		ctsio->kern_data_len = alloc_len;
9231		ctsio->kern_total_len = alloc_len;
9232	}
9233	ctsio->kern_data_resid = 0;
9234	ctsio->kern_rel_offset = 0;
9235	ctsio->kern_sg_entries = 0;
9236
9237	/*
9238	 * We set this to the actual data length, regardless of how much
9239	 * space we actually have to return results.  If the user looks at
9240	 * this value, he'll know whether or not he allocated enough space
9241	 * and reissue the command if necessary.  We don't support well
9242	 * known logical units, so if the user asks for that, return none.
9243	 */
9244	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9245
9246	/*
9247	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9248	 * this request.
9249	 */
9250	ctl_set_success(ctsio);
9251	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9252	ctsio->be_move_done = ctl_config_move_done;
9253	ctl_datamove((union ctl_io *)ctsio);
9254	return (retval);
9255}
9256
9257int
9258ctl_request_sense(struct ctl_scsiio *ctsio)
9259{
9260	struct scsi_request_sense *cdb;
9261	struct scsi_sense_data *sense_ptr;
9262	struct ctl_softc *ctl_softc;
9263	struct ctl_lun *lun;
9264	uint32_t initidx;
9265	int have_error;
9266	scsi_sense_data_type sense_format;
9267	ctl_ua_type ua_type;
9268
9269	cdb = (struct scsi_request_sense *)ctsio->cdb;
9270
9271	ctl_softc = control_softc;
9272	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9273
9274	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9275
9276	/*
9277	 * Determine which sense format the user wants.
9278	 */
9279	if (cdb->byte2 & SRS_DESC)
9280		sense_format = SSD_TYPE_DESC;
9281	else
9282		sense_format = SSD_TYPE_FIXED;
9283
9284	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9285	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9286	ctsio->kern_sg_entries = 0;
9287
9288	/*
9289	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9290	 * larger than the largest allowed value for the length field in the
9291	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9292	 */
9293	ctsio->residual = 0;
9294	ctsio->kern_data_len = cdb->length;
9295	ctsio->kern_total_len = cdb->length;
9296
9297	ctsio->kern_data_resid = 0;
9298	ctsio->kern_rel_offset = 0;
9299	ctsio->kern_sg_entries = 0;
9300
9301	/*
9302	 * If we don't have a LUN, we don't have any pending sense.
9303	 */
9304	if (lun == NULL)
9305		goto no_sense;
9306
9307	have_error = 0;
9308	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9309	/*
9310	 * Check for pending sense, and then for pending unit attentions.
9311	 * Pending sense gets returned first, then pending unit attentions.
9312	 */
9313	mtx_lock(&lun->lun_lock);
9314#ifdef CTL_WITH_CA
9315	if (ctl_is_set(lun->have_ca, initidx)) {
9316		scsi_sense_data_type stored_format;
9317
9318		/*
9319		 * Check to see which sense format was used for the stored
9320		 * sense data.
9321		 */
9322		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9323
9324		/*
9325		 * If the user requested a different sense format than the
9326		 * one we stored, then we need to convert it to the other
9327		 * format.  If we're going from descriptor to fixed format
9328		 * sense data, we may lose things in translation, depending
9329		 * on what options were used.
9330		 *
9331		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9332		 * for some reason we'll just copy it out as-is.
9333		 */
9334		if ((stored_format == SSD_TYPE_FIXED)
9335		 && (sense_format == SSD_TYPE_DESC))
9336			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9337			    &lun->pending_sense[initidx],
9338			    (struct scsi_sense_data_desc *)sense_ptr);
9339		else if ((stored_format == SSD_TYPE_DESC)
9340		      && (sense_format == SSD_TYPE_FIXED))
9341			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9342			    &lun->pending_sense[initidx],
9343			    (struct scsi_sense_data_fixed *)sense_ptr);
9344		else
9345			memcpy(sense_ptr, &lun->pending_sense[initidx],
9346			       MIN(sizeof(*sense_ptr),
9347			       sizeof(lun->pending_sense[initidx])));
9348
9349		ctl_clear_mask(lun->have_ca, initidx);
9350		have_error = 1;
9351	} else
9352#endif
9353	{
9354		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9355		if (ua_type != CTL_UA_NONE)
9356			have_error = 1;
9357		if (ua_type == CTL_UA_LUN_CHANGE) {
9358			mtx_unlock(&lun->lun_lock);
9359			mtx_lock(&ctl_softc->ctl_lock);
9360			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9361			mtx_unlock(&ctl_softc->ctl_lock);
9362			mtx_lock(&lun->lun_lock);
9363		}
9364
9365	}
9366	mtx_unlock(&lun->lun_lock);
9367
9368	/*
9369	 * We already have a pending error, return it.
9370	 */
9371	if (have_error != 0) {
9372		/*
9373		 * We report the SCSI status as OK, since the status of the
9374		 * request sense command itself is OK.
9375		 * We report 0 for the sense length, because we aren't doing
9376		 * autosense in this case.  We're reporting sense as
9377		 * parameter data.
9378		 */
9379		ctl_set_success(ctsio);
9380		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9381		ctsio->be_move_done = ctl_config_move_done;
9382		ctl_datamove((union ctl_io *)ctsio);
9383		return (CTL_RETVAL_COMPLETE);
9384	}
9385
9386no_sense:
9387
9388	/*
9389	 * No sense information to report, so we report that everything is
9390	 * okay.
9391	 */
9392	ctl_set_sense_data(sense_ptr,
9393			   lun,
9394			   sense_format,
9395			   /*current_error*/ 1,
9396			   /*sense_key*/ SSD_KEY_NO_SENSE,
9397			   /*asc*/ 0x00,
9398			   /*ascq*/ 0x00,
9399			   SSD_ELEM_NONE);
9400
9401	/*
9402	 * We report 0 for the sense length, because we aren't doing
9403	 * autosense in this case.  We're reporting sense as parameter data.
9404	 */
9405	ctl_set_success(ctsio);
9406	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9407	ctsio->be_move_done = ctl_config_move_done;
9408	ctl_datamove((union ctl_io *)ctsio);
9409	return (CTL_RETVAL_COMPLETE);
9410}
9411
9412int
9413ctl_tur(struct ctl_scsiio *ctsio)
9414{
9415
9416	CTL_DEBUG_PRINT(("ctl_tur\n"));
9417
9418	ctl_set_success(ctsio);
9419	ctl_done((union ctl_io *)ctsio);
9420
9421	return (CTL_RETVAL_COMPLETE);
9422}
9423
9424/*
9425 * SCSI VPD page 0x00, the Supported VPD Pages page.
9426 */
9427static int
9428ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9429{
9430	struct scsi_vpd_supported_pages *pages;
9431	int sup_page_size;
9432	struct ctl_lun *lun;
9433	int p;
9434
9435	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9436
9437	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9438	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9439	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9440	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9441	ctsio->kern_sg_entries = 0;
9442
9443	if (sup_page_size < alloc_len) {
9444		ctsio->residual = alloc_len - sup_page_size;
9445		ctsio->kern_data_len = sup_page_size;
9446		ctsio->kern_total_len = sup_page_size;
9447	} else {
9448		ctsio->residual = 0;
9449		ctsio->kern_data_len = alloc_len;
9450		ctsio->kern_total_len = alloc_len;
9451	}
9452	ctsio->kern_data_resid = 0;
9453	ctsio->kern_rel_offset = 0;
9454	ctsio->kern_sg_entries = 0;
9455
9456	/*
9457	 * The control device is always connected.  The disk device, on the
9458	 * other hand, may not be online all the time.  Need to change this
9459	 * to figure out whether the disk device is actually online or not.
9460	 */
9461	if (lun != NULL)
9462		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9463				lun->be_lun->lun_type;
9464	else
9465		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9466
9467	p = 0;
9468	/* Supported VPD pages */
9469	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9470	/* Serial Number */
9471	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9472	/* Device Identification */
9473	pages->page_list[p++] = SVPD_DEVICE_ID;
9474	/* Extended INQUIRY Data */
9475	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9476	/* Mode Page Policy */
9477	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9478	/* SCSI Ports */
9479	pages->page_list[p++] = SVPD_SCSI_PORTS;
9480	/* Third-party Copy */
9481	pages->page_list[p++] = SVPD_SCSI_TPC;
9482	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9483		/* Block limits */
9484		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9485		/* Block Device Characteristics */
9486		pages->page_list[p++] = SVPD_BDC;
9487		/* Logical Block Provisioning */
9488		pages->page_list[p++] = SVPD_LBP;
9489	}
9490	pages->length = p;
9491
9492	ctl_set_success(ctsio);
9493	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9494	ctsio->be_move_done = ctl_config_move_done;
9495	ctl_datamove((union ctl_io *)ctsio);
9496	return (CTL_RETVAL_COMPLETE);
9497}
9498
9499/*
9500 * SCSI VPD page 0x80, the Unit Serial Number page.
9501 */
9502static int
9503ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9504{
9505	struct scsi_vpd_unit_serial_number *sn_ptr;
9506	struct ctl_lun *lun;
9507	int data_len;
9508
9509	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9510
9511	data_len = 4 + CTL_SN_LEN;
9512	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9513	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9514	if (data_len < alloc_len) {
9515		ctsio->residual = alloc_len - data_len;
9516		ctsio->kern_data_len = data_len;
9517		ctsio->kern_total_len = data_len;
9518	} else {
9519		ctsio->residual = 0;
9520		ctsio->kern_data_len = alloc_len;
9521		ctsio->kern_total_len = alloc_len;
9522	}
9523	ctsio->kern_data_resid = 0;
9524	ctsio->kern_rel_offset = 0;
9525	ctsio->kern_sg_entries = 0;
9526
9527	/*
9528	 * The control device is always connected.  The disk device, on the
9529	 * other hand, may not be online all the time.  Need to change this
9530	 * to figure out whether the disk device is actually online or not.
9531	 */
9532	if (lun != NULL)
9533		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9534				  lun->be_lun->lun_type;
9535	else
9536		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9537
9538	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9539	sn_ptr->length = CTL_SN_LEN;
9540	/*
9541	 * If we don't have a LUN, we just leave the serial number as
9542	 * all spaces.
9543	 */
9544	if (lun != NULL) {
9545		strncpy((char *)sn_ptr->serial_num,
9546			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9547	} else
9548		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9549
9550	ctl_set_success(ctsio);
9551	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9552	ctsio->be_move_done = ctl_config_move_done;
9553	ctl_datamove((union ctl_io *)ctsio);
9554	return (CTL_RETVAL_COMPLETE);
9555}
9556
9557
9558/*
9559 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9560 */
9561static int
9562ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9563{
9564	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9565	struct ctl_lun *lun;
9566	int data_len;
9567
9568	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9569
9570	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9571	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9572	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9573	ctsio->kern_sg_entries = 0;
9574
9575	if (data_len < alloc_len) {
9576		ctsio->residual = alloc_len - data_len;
9577		ctsio->kern_data_len = data_len;
9578		ctsio->kern_total_len = data_len;
9579	} else {
9580		ctsio->residual = 0;
9581		ctsio->kern_data_len = alloc_len;
9582		ctsio->kern_total_len = alloc_len;
9583	}
9584	ctsio->kern_data_resid = 0;
9585	ctsio->kern_rel_offset = 0;
9586	ctsio->kern_sg_entries = 0;
9587
9588	/*
9589	 * The control device is always connected.  The disk device, on the
9590	 * other hand, may not be online all the time.
9591	 */
9592	if (lun != NULL)
9593		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9594				     lun->be_lun->lun_type;
9595	else
9596		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9597	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9598	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9599	/*
9600	 * We support head of queue, ordered and simple tags.
9601	 */
9602	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9603	/*
9604	 * Volatile cache supported.
9605	 */
9606	eid_ptr->flags3 = SVPD_EID_V_SUP;
9607
9608	/*
9609	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9610	 * attention for a particular IT nexus on all LUNs once we report
9611	 * it to that nexus once.  This bit is required as of SPC-4.
9612	 */
9613	eid_ptr->flags4 = SVPD_EID_LUICLT;
9614
9615	/*
9616	 * XXX KDM in order to correctly answer this, we would need
9617	 * information from the SIM to determine how much sense data it
9618	 * can send.  So this would really be a path inquiry field, most
9619	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9620	 * but the hardware may or may not be able to support that much.
9621	 * 0 just means that the maximum sense data length is not reported.
9622	 */
9623	eid_ptr->max_sense_length = 0;
9624
9625	ctl_set_success(ctsio);
9626	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9627	ctsio->be_move_done = ctl_config_move_done;
9628	ctl_datamove((union ctl_io *)ctsio);
9629	return (CTL_RETVAL_COMPLETE);
9630}
9631
9632static int
9633ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9634{
9635	struct scsi_vpd_mode_page_policy *mpp_ptr;
9636	struct ctl_lun *lun;
9637	int data_len;
9638
9639	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9640
9641	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9642	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9643
9644	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9645	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9646	ctsio->kern_sg_entries = 0;
9647
9648	if (data_len < alloc_len) {
9649		ctsio->residual = alloc_len - data_len;
9650		ctsio->kern_data_len = data_len;
9651		ctsio->kern_total_len = data_len;
9652	} else {
9653		ctsio->residual = 0;
9654		ctsio->kern_data_len = alloc_len;
9655		ctsio->kern_total_len = alloc_len;
9656	}
9657	ctsio->kern_data_resid = 0;
9658	ctsio->kern_rel_offset = 0;
9659	ctsio->kern_sg_entries = 0;
9660
9661	/*
9662	 * The control device is always connected.  The disk device, on the
9663	 * other hand, may not be online all the time.
9664	 */
9665	if (lun != NULL)
9666		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9667				     lun->be_lun->lun_type;
9668	else
9669		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9670	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9671	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9672	mpp_ptr->descr[0].page_code = 0x3f;
9673	mpp_ptr->descr[0].subpage_code = 0xff;
9674	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9675
9676	ctl_set_success(ctsio);
9677	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9678	ctsio->be_move_done = ctl_config_move_done;
9679	ctl_datamove((union ctl_io *)ctsio);
9680	return (CTL_RETVAL_COMPLETE);
9681}
9682
9683/*
9684 * SCSI VPD page 0x83, the Device Identification page.
9685 */
9686static int
9687ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9688{
9689	struct scsi_vpd_device_id *devid_ptr;
9690	struct scsi_vpd_id_descriptor *desc;
9691	struct ctl_softc *softc;
9692	struct ctl_lun *lun;
9693	struct ctl_port *port;
9694	int data_len, g;
9695	uint8_t proto;
9696
9697	softc = control_softc;
9698
9699	port = ctl_io_port(&ctsio->io_hdr);
9700	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9701
9702	data_len = sizeof(struct scsi_vpd_device_id) +
9703	    sizeof(struct scsi_vpd_id_descriptor) +
9704		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9705	    sizeof(struct scsi_vpd_id_descriptor) +
9706		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9707	if (lun && lun->lun_devid)
9708		data_len += lun->lun_devid->len;
9709	if (port && port->port_devid)
9710		data_len += port->port_devid->len;
9711	if (port && port->target_devid)
9712		data_len += port->target_devid->len;
9713
9714	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9715	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9716	ctsio->kern_sg_entries = 0;
9717
9718	if (data_len < alloc_len) {
9719		ctsio->residual = alloc_len - data_len;
9720		ctsio->kern_data_len = data_len;
9721		ctsio->kern_total_len = data_len;
9722	} else {
9723		ctsio->residual = 0;
9724		ctsio->kern_data_len = alloc_len;
9725		ctsio->kern_total_len = alloc_len;
9726	}
9727	ctsio->kern_data_resid = 0;
9728	ctsio->kern_rel_offset = 0;
9729	ctsio->kern_sg_entries = 0;
9730
9731	/*
9732	 * The control device is always connected.  The disk device, on the
9733	 * other hand, may not be online all the time.
9734	 */
9735	if (lun != NULL)
9736		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9737				     lun->be_lun->lun_type;
9738	else
9739		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9740	devid_ptr->page_code = SVPD_DEVICE_ID;
9741	scsi_ulto2b(data_len - 4, devid_ptr->length);
9742
9743	if (port && port->port_type == CTL_PORT_FC)
9744		proto = SCSI_PROTO_FC << 4;
9745	else if (port && port->port_type == CTL_PORT_ISCSI)
9746		proto = SCSI_PROTO_ISCSI << 4;
9747	else
9748		proto = SCSI_PROTO_SPI << 4;
9749	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9750
9751	/*
9752	 * We're using a LUN association here.  i.e., this device ID is a
9753	 * per-LUN identifier.
9754	 */
9755	if (lun && lun->lun_devid) {
9756		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9757		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9758		    lun->lun_devid->len);
9759	}
9760
9761	/*
9762	 * This is for the WWPN which is a port association.
9763	 */
9764	if (port && port->port_devid) {
9765		memcpy(desc, port->port_devid->data, port->port_devid->len);
9766		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9767		    port->port_devid->len);
9768	}
9769
9770	/*
9771	 * This is for the Relative Target Port(type 4h) identifier
9772	 */
9773	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9774	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9775	    SVPD_ID_TYPE_RELTARG;
9776	desc->length = 4;
9777	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9778	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9779	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9780
9781	/*
9782	 * This is for the Target Port Group(type 5h) identifier
9783	 */
9784	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9785	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9786	    SVPD_ID_TYPE_TPORTGRP;
9787	desc->length = 4;
9788	if (softc->is_single ||
9789	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9790		g = 1;
9791	else
9792		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9793	scsi_ulto2b(g, &desc->identifier[2]);
9794	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9795	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9796
9797	/*
9798	 * This is for the Target identifier
9799	 */
9800	if (port && port->target_devid) {
9801		memcpy(desc, port->target_devid->data, port->target_devid->len);
9802	}
9803
9804	ctl_set_success(ctsio);
9805	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9806	ctsio->be_move_done = ctl_config_move_done;
9807	ctl_datamove((union ctl_io *)ctsio);
9808	return (CTL_RETVAL_COMPLETE);
9809}
9810
9811static int
9812ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9813{
9814	struct ctl_softc *softc = control_softc;
9815	struct scsi_vpd_scsi_ports *sp;
9816	struct scsi_vpd_port_designation *pd;
9817	struct scsi_vpd_port_designation_cont *pdc;
9818	struct ctl_lun *lun;
9819	struct ctl_port *port;
9820	int data_len, num_target_ports, iid_len, id_len;
9821
9822	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9823
9824	num_target_ports = 0;
9825	iid_len = 0;
9826	id_len = 0;
9827	mtx_lock(&softc->ctl_lock);
9828	STAILQ_FOREACH(port, &softc->port_list, links) {
9829		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9830			continue;
9831		if (lun != NULL &&
9832		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9833			continue;
9834		num_target_ports++;
9835		if (port->init_devid)
9836			iid_len += port->init_devid->len;
9837		if (port->port_devid)
9838			id_len += port->port_devid->len;
9839	}
9840	mtx_unlock(&softc->ctl_lock);
9841
9842	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9843	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9844	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9845	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9846	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9847	ctsio->kern_sg_entries = 0;
9848
9849	if (data_len < alloc_len) {
9850		ctsio->residual = alloc_len - data_len;
9851		ctsio->kern_data_len = data_len;
9852		ctsio->kern_total_len = data_len;
9853	} else {
9854		ctsio->residual = 0;
9855		ctsio->kern_data_len = alloc_len;
9856		ctsio->kern_total_len = alloc_len;
9857	}
9858	ctsio->kern_data_resid = 0;
9859	ctsio->kern_rel_offset = 0;
9860	ctsio->kern_sg_entries = 0;
9861
9862	/*
9863	 * The control device is always connected.  The disk device, on the
9864	 * other hand, may not be online all the time.  Need to change this
9865	 * to figure out whether the disk device is actually online or not.
9866	 */
9867	if (lun != NULL)
9868		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9869				  lun->be_lun->lun_type;
9870	else
9871		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9872
9873	sp->page_code = SVPD_SCSI_PORTS;
9874	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9875	    sp->page_length);
9876	pd = &sp->design[0];
9877
9878	mtx_lock(&softc->ctl_lock);
9879	STAILQ_FOREACH(port, &softc->port_list, links) {
9880		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9881			continue;
9882		if (lun != NULL &&
9883		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9884			continue;
9885		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9886		if (port->init_devid) {
9887			iid_len = port->init_devid->len;
9888			memcpy(pd->initiator_transportid,
9889			    port->init_devid->data, port->init_devid->len);
9890		} else
9891			iid_len = 0;
9892		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9893		pdc = (struct scsi_vpd_port_designation_cont *)
9894		    (&pd->initiator_transportid[iid_len]);
9895		if (port->port_devid) {
9896			id_len = port->port_devid->len;
9897			memcpy(pdc->target_port_descriptors,
9898			    port->port_devid->data, port->port_devid->len);
9899		} else
9900			id_len = 0;
9901		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9902		pd = (struct scsi_vpd_port_designation *)
9903		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9904	}
9905	mtx_unlock(&softc->ctl_lock);
9906
9907	ctl_set_success(ctsio);
9908	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9909	ctsio->be_move_done = ctl_config_move_done;
9910	ctl_datamove((union ctl_io *)ctsio);
9911	return (CTL_RETVAL_COMPLETE);
9912}
9913
9914static int
9915ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9916{
9917	struct scsi_vpd_block_limits *bl_ptr;
9918	struct ctl_lun *lun;
9919	uint64_t ival;
9920
9921	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9922
9923	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9924	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9925	ctsio->kern_sg_entries = 0;
9926
9927	if (sizeof(*bl_ptr) < alloc_len) {
9928		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9929		ctsio->kern_data_len = sizeof(*bl_ptr);
9930		ctsio->kern_total_len = sizeof(*bl_ptr);
9931	} else {
9932		ctsio->residual = 0;
9933		ctsio->kern_data_len = alloc_len;
9934		ctsio->kern_total_len = alloc_len;
9935	}
9936	ctsio->kern_data_resid = 0;
9937	ctsio->kern_rel_offset = 0;
9938	ctsio->kern_sg_entries = 0;
9939
9940	/*
9941	 * The control device is always connected.  The disk device, on the
9942	 * other hand, may not be online all the time.  Need to change this
9943	 * to figure out whether the disk device is actually online or not.
9944	 */
9945	if (lun != NULL)
9946		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9947				  lun->be_lun->lun_type;
9948	else
9949		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9950
9951	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9952	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9953	bl_ptr->max_cmp_write_len = 0xff;
9954	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9955	if (lun != NULL) {
9956		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9957		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9958			ival = 0xffffffff;
9959			ctl_get_opt_number(&lun->be_lun->options,
9960			    "unmap_max_lba", &ival);
9961			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9962			ival = 0xffffffff;
9963			ctl_get_opt_number(&lun->be_lun->options,
9964			    "unmap_max_descr", &ival);
9965			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9966			if (lun->be_lun->ublockexp != 0) {
9967				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9968				    bl_ptr->opt_unmap_grain);
9969				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9970				    bl_ptr->unmap_grain_align);
9971			}
9972		}
9973		scsi_ulto4b(lun->be_lun->atomicblock,
9974		    bl_ptr->max_atomic_transfer_length);
9975		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9976		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9977		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9978		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9979		ival = UINT64_MAX;
9980		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9981		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9982	}
9983
9984	ctl_set_success(ctsio);
9985	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9986	ctsio->be_move_done = ctl_config_move_done;
9987	ctl_datamove((union ctl_io *)ctsio);
9988	return (CTL_RETVAL_COMPLETE);
9989}
9990
9991static int
9992ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9993{
9994	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9995	struct ctl_lun *lun;
9996	const char *value;
9997	u_int i;
9998
9999	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10000
10001	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10002	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10003	ctsio->kern_sg_entries = 0;
10004
10005	if (sizeof(*bdc_ptr) < alloc_len) {
10006		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10007		ctsio->kern_data_len = sizeof(*bdc_ptr);
10008		ctsio->kern_total_len = sizeof(*bdc_ptr);
10009	} else {
10010		ctsio->residual = 0;
10011		ctsio->kern_data_len = alloc_len;
10012		ctsio->kern_total_len = alloc_len;
10013	}
10014	ctsio->kern_data_resid = 0;
10015	ctsio->kern_rel_offset = 0;
10016	ctsio->kern_sg_entries = 0;
10017
10018	/*
10019	 * The control device is always connected.  The disk device, on the
10020	 * other hand, may not be online all the time.  Need to change this
10021	 * to figure out whether the disk device is actually online or not.
10022	 */
10023	if (lun != NULL)
10024		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10025				  lun->be_lun->lun_type;
10026	else
10027		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10028	bdc_ptr->page_code = SVPD_BDC;
10029	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10030	if (lun != NULL &&
10031	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10032		i = strtol(value, NULL, 0);
10033	else
10034		i = CTL_DEFAULT_ROTATION_RATE;
10035	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10036	if (lun != NULL &&
10037	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10038		i = strtol(value, NULL, 0);
10039	else
10040		i = 0;
10041	bdc_ptr->wab_wac_ff = (i & 0x0f);
10042	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10043
10044	ctl_set_success(ctsio);
10045	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10046	ctsio->be_move_done = ctl_config_move_done;
10047	ctl_datamove((union ctl_io *)ctsio);
10048	return (CTL_RETVAL_COMPLETE);
10049}
10050
10051static int
10052ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10053{
10054	struct scsi_vpd_logical_block_prov *lbp_ptr;
10055	struct ctl_lun *lun;
10056	const char *value;
10057
10058	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10059
10060	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10061	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10062	ctsio->kern_sg_entries = 0;
10063
10064	if (sizeof(*lbp_ptr) < alloc_len) {
10065		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10066		ctsio->kern_data_len = sizeof(*lbp_ptr);
10067		ctsio->kern_total_len = sizeof(*lbp_ptr);
10068	} else {
10069		ctsio->residual = 0;
10070		ctsio->kern_data_len = alloc_len;
10071		ctsio->kern_total_len = alloc_len;
10072	}
10073	ctsio->kern_data_resid = 0;
10074	ctsio->kern_rel_offset = 0;
10075	ctsio->kern_sg_entries = 0;
10076
10077	/*
10078	 * The control device is always connected.  The disk device, on the
10079	 * other hand, may not be online all the time.  Need to change this
10080	 * to figure out whether the disk device is actually online or not.
10081	 */
10082	if (lun != NULL)
10083		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10084				  lun->be_lun->lun_type;
10085	else
10086		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10087
10088	lbp_ptr->page_code = SVPD_LBP;
10089	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10090	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10091	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10092		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10093		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10094		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10095		if (value != NULL) {
10096			if (strcmp(value, "resource") == 0)
10097				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10098			else if (strcmp(value, "thin") == 0)
10099				lbp_ptr->prov_type = SVPD_LBP_THIN;
10100		} else
10101			lbp_ptr->prov_type = SVPD_LBP_THIN;
10102	}
10103
10104	ctl_set_success(ctsio);
10105	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10106	ctsio->be_move_done = ctl_config_move_done;
10107	ctl_datamove((union ctl_io *)ctsio);
10108	return (CTL_RETVAL_COMPLETE);
10109}
10110
10111/*
10112 * INQUIRY with the EVPD bit set.
10113 */
10114static int
10115ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10116{
10117	struct ctl_lun *lun;
10118	struct scsi_inquiry *cdb;
10119	int alloc_len, retval;
10120
10121	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10122	cdb = (struct scsi_inquiry *)ctsio->cdb;
10123	alloc_len = scsi_2btoul(cdb->length);
10124
10125	switch (cdb->page_code) {
10126	case SVPD_SUPPORTED_PAGES:
10127		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10128		break;
10129	case SVPD_UNIT_SERIAL_NUMBER:
10130		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10131		break;
10132	case SVPD_DEVICE_ID:
10133		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10134		break;
10135	case SVPD_EXTENDED_INQUIRY_DATA:
10136		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10137		break;
10138	case SVPD_MODE_PAGE_POLICY:
10139		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10140		break;
10141	case SVPD_SCSI_PORTS:
10142		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10143		break;
10144	case SVPD_SCSI_TPC:
10145		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10146		break;
10147	case SVPD_BLOCK_LIMITS:
10148		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10149			goto err;
10150		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10151		break;
10152	case SVPD_BDC:
10153		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10154			goto err;
10155		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10156		break;
10157	case SVPD_LBP:
10158		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10159			goto err;
10160		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10161		break;
10162	default:
10163err:
10164		ctl_set_invalid_field(ctsio,
10165				      /*sks_valid*/ 1,
10166				      /*command*/ 1,
10167				      /*field*/ 2,
10168				      /*bit_valid*/ 0,
10169				      /*bit*/ 0);
10170		ctl_done((union ctl_io *)ctsio);
10171		retval = CTL_RETVAL_COMPLETE;
10172		break;
10173	}
10174
10175	return (retval);
10176}
10177
10178/*
10179 * Standard INQUIRY data.
10180 */
10181static int
10182ctl_inquiry_std(struct ctl_scsiio *ctsio)
10183{
10184	struct scsi_inquiry_data *inq_ptr;
10185	struct scsi_inquiry *cdb;
10186	struct ctl_softc *softc = control_softc;
10187	struct ctl_port *port;
10188	struct ctl_lun *lun;
10189	char *val;
10190	uint32_t alloc_len, data_len;
10191	ctl_port_type port_type;
10192
10193	port = ctl_io_port(&ctsio->io_hdr);
10194	port_type = port->port_type;
10195	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10196		port_type = CTL_PORT_SCSI;
10197
10198	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10199	cdb = (struct scsi_inquiry *)ctsio->cdb;
10200	alloc_len = scsi_2btoul(cdb->length);
10201
10202	/*
10203	 * We malloc the full inquiry data size here and fill it
10204	 * in.  If the user only asks for less, we'll give him
10205	 * that much.
10206	 */
10207	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10208	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10209	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10210	ctsio->kern_sg_entries = 0;
10211	ctsio->kern_data_resid = 0;
10212	ctsio->kern_rel_offset = 0;
10213
10214	if (data_len < alloc_len) {
10215		ctsio->residual = alloc_len - data_len;
10216		ctsio->kern_data_len = data_len;
10217		ctsio->kern_total_len = data_len;
10218	} else {
10219		ctsio->residual = 0;
10220		ctsio->kern_data_len = alloc_len;
10221		ctsio->kern_total_len = alloc_len;
10222	}
10223
10224	if (lun != NULL) {
10225		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10226		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10227			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10228			    lun->be_lun->lun_type;
10229		} else {
10230			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10231			    lun->be_lun->lun_type;
10232		}
10233		if (lun->flags & CTL_LUN_REMOVABLE)
10234			inq_ptr->dev_qual2 |= SID_RMB;
10235	} else
10236		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10237
10238	/* RMB in byte 2 is 0 */
10239	inq_ptr->version = SCSI_REV_SPC4;
10240
10241	/*
10242	 * According to SAM-3, even if a device only supports a single
10243	 * level of LUN addressing, it should still set the HISUP bit:
10244	 *
10245	 * 4.9.1 Logical unit numbers overview
10246	 *
10247	 * All logical unit number formats described in this standard are
10248	 * hierarchical in structure even when only a single level in that
10249	 * hierarchy is used. The HISUP bit shall be set to one in the
10250	 * standard INQUIRY data (see SPC-2) when any logical unit number
10251	 * format described in this standard is used.  Non-hierarchical
10252	 * formats are outside the scope of this standard.
10253	 *
10254	 * Therefore we set the HiSup bit here.
10255	 *
10256	 * The response format is 2, per SPC-3.
10257	 */
10258	inq_ptr->response_format = SID_HiSup | 2;
10259
10260	inq_ptr->additional_length = data_len -
10261	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10262	CTL_DEBUG_PRINT(("additional_length = %d\n",
10263			 inq_ptr->additional_length));
10264
10265	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10266	if (port_type == CTL_PORT_SCSI)
10267		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10268	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10269	inq_ptr->flags = SID_CmdQue;
10270	if (port_type == CTL_PORT_SCSI)
10271		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10272
10273	/*
10274	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10275	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10276	 * name and 4 bytes for the revision.
10277	 */
10278	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10279	    "vendor")) == NULL) {
10280		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10281	} else {
10282		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10283		strncpy(inq_ptr->vendor, val,
10284		    min(sizeof(inq_ptr->vendor), strlen(val)));
10285	}
10286	if (lun == NULL) {
10287		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10288		    sizeof(inq_ptr->product));
10289	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10290		switch (lun->be_lun->lun_type) {
10291		case T_DIRECT:
10292			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10293			    sizeof(inq_ptr->product));
10294			break;
10295		case T_PROCESSOR:
10296			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10297			    sizeof(inq_ptr->product));
10298			break;
10299		case T_CDROM:
10300			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10301			    sizeof(inq_ptr->product));
10302			break;
10303		default:
10304			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10305			    sizeof(inq_ptr->product));
10306			break;
10307		}
10308	} else {
10309		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10310		strncpy(inq_ptr->product, val,
10311		    min(sizeof(inq_ptr->product), strlen(val)));
10312	}
10313
10314	/*
10315	 * XXX make this a macro somewhere so it automatically gets
10316	 * incremented when we make changes.
10317	 */
10318	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10319	    "revision")) == NULL) {
10320		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10321	} else {
10322		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10323		strncpy(inq_ptr->revision, val,
10324		    min(sizeof(inq_ptr->revision), strlen(val)));
10325	}
10326
10327	/*
10328	 * For parallel SCSI, we support double transition and single
10329	 * transition clocking.  We also support QAS (Quick Arbitration
10330	 * and Selection) and Information Unit transfers on both the
10331	 * control and array devices.
10332	 */
10333	if (port_type == CTL_PORT_SCSI)
10334		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10335				    SID_SPI_IUS;
10336
10337	/* SAM-5 (no version claimed) */
10338	scsi_ulto2b(0x00A0, inq_ptr->version1);
10339	/* SPC-4 (no version claimed) */
10340	scsi_ulto2b(0x0460, inq_ptr->version2);
10341	if (port_type == CTL_PORT_FC) {
10342		/* FCP-2 ANSI INCITS.350:2003 */
10343		scsi_ulto2b(0x0917, inq_ptr->version3);
10344	} else if (port_type == CTL_PORT_SCSI) {
10345		/* SPI-4 ANSI INCITS.362:200x */
10346		scsi_ulto2b(0x0B56, inq_ptr->version3);
10347	} else if (port_type == CTL_PORT_ISCSI) {
10348		/* iSCSI (no version claimed) */
10349		scsi_ulto2b(0x0960, inq_ptr->version3);
10350	} else if (port_type == CTL_PORT_SAS) {
10351		/* SAS (no version claimed) */
10352		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10353	}
10354
10355	if (lun == NULL) {
10356		/* SBC-4 (no version claimed) */
10357		scsi_ulto2b(0x0600, inq_ptr->version4);
10358	} else {
10359		switch (lun->be_lun->lun_type) {
10360		case T_DIRECT:
10361			/* SBC-4 (no version claimed) */
10362			scsi_ulto2b(0x0600, inq_ptr->version4);
10363			break;
10364		case T_PROCESSOR:
10365			break;
10366		case T_CDROM:
10367			/* MMC-6 (no version claimed) */
10368			scsi_ulto2b(0x04E0, inq_ptr->version4);
10369			break;
10370		default:
10371			break;
10372		}
10373	}
10374
10375	ctl_set_success(ctsio);
10376	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10377	ctsio->be_move_done = ctl_config_move_done;
10378	ctl_datamove((union ctl_io *)ctsio);
10379	return (CTL_RETVAL_COMPLETE);
10380}
10381
10382int
10383ctl_inquiry(struct ctl_scsiio *ctsio)
10384{
10385	struct scsi_inquiry *cdb;
10386	int retval;
10387
10388	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10389
10390	cdb = (struct scsi_inquiry *)ctsio->cdb;
10391	if (cdb->byte2 & SI_EVPD)
10392		retval = ctl_inquiry_evpd(ctsio);
10393	else if (cdb->page_code == 0)
10394		retval = ctl_inquiry_std(ctsio);
10395	else {
10396		ctl_set_invalid_field(ctsio,
10397				      /*sks_valid*/ 1,
10398				      /*command*/ 1,
10399				      /*field*/ 2,
10400				      /*bit_valid*/ 0,
10401				      /*bit*/ 0);
10402		ctl_done((union ctl_io *)ctsio);
10403		return (CTL_RETVAL_COMPLETE);
10404	}
10405
10406	return (retval);
10407}
10408
10409int
10410ctl_get_config(struct ctl_scsiio *ctsio)
10411{
10412	struct scsi_get_config_header *hdr;
10413	struct scsi_get_config_feature *feature;
10414	struct scsi_get_config *cdb;
10415	struct ctl_lun *lun;
10416	uint32_t alloc_len, data_len;
10417	int rt, starting;
10418
10419	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10420	cdb = (struct scsi_get_config *)ctsio->cdb;
10421	rt = (cdb->rt & SGC_RT_MASK);
10422	starting = scsi_2btoul(cdb->starting_feature);
10423	alloc_len = scsi_2btoul(cdb->length);
10424
10425	data_len = sizeof(struct scsi_get_config_header) +
10426	    sizeof(struct scsi_get_config_feature) + 8 +
10427	    sizeof(struct scsi_get_config_feature) + 8 +
10428	    sizeof(struct scsi_get_config_feature) + 4 +
10429	    sizeof(struct scsi_get_config_feature) + 4 +
10430	    sizeof(struct scsi_get_config_feature) + 8 +
10431	    sizeof(struct scsi_get_config_feature) +
10432	    sizeof(struct scsi_get_config_feature) + 4 +
10433	    sizeof(struct scsi_get_config_feature) + 4 +
10434	    sizeof(struct scsi_get_config_feature) + 4 +
10435	    sizeof(struct scsi_get_config_feature) + 4 +
10436	    sizeof(struct scsi_get_config_feature) + 4 +
10437	    sizeof(struct scsi_get_config_feature) + 4;
10438	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10439	ctsio->kern_sg_entries = 0;
10440	ctsio->kern_data_resid = 0;
10441	ctsio->kern_rel_offset = 0;
10442
10443	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10444	if (lun->flags & CTL_LUN_NO_MEDIA)
10445		scsi_ulto2b(0x0000, hdr->current_profile);
10446	else
10447		scsi_ulto2b(0x0010, hdr->current_profile);
10448	feature = (struct scsi_get_config_feature *)(hdr + 1);
10449
10450	if (starting > 0x003b)
10451		goto done;
10452	if (starting > 0x003a)
10453		goto f3b;
10454	if (starting > 0x002b)
10455		goto f3a;
10456	if (starting > 0x002a)
10457		goto f2b;
10458	if (starting > 0x001f)
10459		goto f2a;
10460	if (starting > 0x001e)
10461		goto f1f;
10462	if (starting > 0x001d)
10463		goto f1e;
10464	if (starting > 0x0010)
10465		goto f1d;
10466	if (starting > 0x0003)
10467		goto f10;
10468	if (starting > 0x0002)
10469		goto f3;
10470	if (starting > 0x0001)
10471		goto f2;
10472	if (starting > 0x0000)
10473		goto f1;
10474
10475	/* Profile List */
10476	scsi_ulto2b(0x0000, feature->feature_code);
10477	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10478	feature->add_length = 8;
10479	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10480	feature->feature_data[2] = 0x00;
10481	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10482	feature->feature_data[6] = 0x01;
10483	feature = (struct scsi_get_config_feature *)
10484	    &feature->feature_data[feature->add_length];
10485
10486f1:	/* Core */
10487	scsi_ulto2b(0x0001, feature->feature_code);
10488	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10489	feature->add_length = 8;
10490	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10491	feature->feature_data[4] = 0x03;
10492	feature = (struct scsi_get_config_feature *)
10493	    &feature->feature_data[feature->add_length];
10494
10495f2:	/* Morphing */
10496	scsi_ulto2b(0x0002, feature->feature_code);
10497	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10498	feature->add_length = 4;
10499	feature->feature_data[0] = 0x02;
10500	feature = (struct scsi_get_config_feature *)
10501	    &feature->feature_data[feature->add_length];
10502
10503f3:	/* Removable Medium */
10504	scsi_ulto2b(0x0003, feature->feature_code);
10505	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10506	feature->add_length = 4;
10507	feature->feature_data[0] = 0x39;
10508	feature = (struct scsi_get_config_feature *)
10509	    &feature->feature_data[feature->add_length];
10510
10511	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10512		goto done;
10513
10514f10:	/* Random Read */
10515	scsi_ulto2b(0x0010, feature->feature_code);
10516	feature->flags = 0x00;
10517	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10518		feature->flags |= SGC_F_CURRENT;
10519	feature->add_length = 8;
10520	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10521	scsi_ulto2b(1, &feature->feature_data[4]);
10522	feature->feature_data[6] = 0x00;
10523	feature = (struct scsi_get_config_feature *)
10524	    &feature->feature_data[feature->add_length];
10525
10526f1d:	/* Multi-Read */
10527	scsi_ulto2b(0x001D, feature->feature_code);
10528	feature->flags = 0x00;
10529	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10530		feature->flags |= SGC_F_CURRENT;
10531	feature->add_length = 0;
10532	feature = (struct scsi_get_config_feature *)
10533	    &feature->feature_data[feature->add_length];
10534
10535f1e:	/* CD Read */
10536	scsi_ulto2b(0x001E, feature->feature_code);
10537	feature->flags = 0x00;
10538	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10539		feature->flags |= SGC_F_CURRENT;
10540	feature->add_length = 4;
10541	feature->feature_data[0] = 0x00;
10542	feature = (struct scsi_get_config_feature *)
10543	    &feature->feature_data[feature->add_length];
10544
10545f1f:	/* DVD Read */
10546	scsi_ulto2b(0x001F, feature->feature_code);
10547	feature->flags = 0x08;
10548	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10549		feature->flags |= SGC_F_CURRENT;
10550	feature->add_length = 4;
10551	feature->feature_data[0] = 0x01;
10552	feature->feature_data[2] = 0x03;
10553	feature = (struct scsi_get_config_feature *)
10554	    &feature->feature_data[feature->add_length];
10555
10556f2a:	/* DVD+RW */
10557	scsi_ulto2b(0x002A, feature->feature_code);
10558	feature->flags = 0x04;
10559	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10560		feature->flags |= SGC_F_CURRENT;
10561	feature->add_length = 4;
10562	feature->feature_data[0] = 0x00;
10563	feature->feature_data[1] = 0x00;
10564	feature = (struct scsi_get_config_feature *)
10565	    &feature->feature_data[feature->add_length];
10566
10567f2b:	/* DVD+R */
10568	scsi_ulto2b(0x002B, feature->feature_code);
10569	feature->flags = 0x00;
10570	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10571		feature->flags |= SGC_F_CURRENT;
10572	feature->add_length = 4;
10573	feature->feature_data[0] = 0x00;
10574	feature = (struct scsi_get_config_feature *)
10575	    &feature->feature_data[feature->add_length];
10576
10577f3a:	/* DVD+RW Dual Layer */
10578	scsi_ulto2b(0x003A, feature->feature_code);
10579	feature->flags = 0x00;
10580	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10581		feature->flags |= SGC_F_CURRENT;
10582	feature->add_length = 4;
10583	feature->feature_data[0] = 0x00;
10584	feature->feature_data[1] = 0x00;
10585	feature = (struct scsi_get_config_feature *)
10586	    &feature->feature_data[feature->add_length];
10587
10588f3b:	/* DVD+R Dual Layer */
10589	scsi_ulto2b(0x003B, feature->feature_code);
10590	feature->flags = 0x00;
10591	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10592		feature->flags |= SGC_F_CURRENT;
10593	feature->add_length = 4;
10594	feature->feature_data[0] = 0x00;
10595	feature = (struct scsi_get_config_feature *)
10596	    &feature->feature_data[feature->add_length];
10597
10598done:
10599	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10600	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10601		feature = (struct scsi_get_config_feature *)(hdr + 1);
10602		if (scsi_2btoul(feature->feature_code) == starting)
10603			feature = (struct scsi_get_config_feature *)
10604			    &feature->feature_data[feature->add_length];
10605		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10606	}
10607	scsi_ulto4b(data_len - 4, hdr->data_length);
10608	if (data_len < alloc_len) {
10609		ctsio->residual = alloc_len - data_len;
10610		ctsio->kern_data_len = data_len;
10611		ctsio->kern_total_len = data_len;
10612	} else {
10613		ctsio->residual = 0;
10614		ctsio->kern_data_len = alloc_len;
10615		ctsio->kern_total_len = alloc_len;
10616	}
10617
10618	ctl_set_success(ctsio);
10619	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10620	ctsio->be_move_done = ctl_config_move_done;
10621	ctl_datamove((union ctl_io *)ctsio);
10622	return (CTL_RETVAL_COMPLETE);
10623}
10624
10625int
10626ctl_get_event_status(struct ctl_scsiio *ctsio)
10627{
10628	struct scsi_get_event_status_header *hdr;
10629	struct scsi_get_event_status *cdb;
10630	struct ctl_lun *lun;
10631	uint32_t alloc_len, data_len;
10632	int notif_class;
10633
10634	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10635	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10636	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10637		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10638		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10639		ctl_done((union ctl_io *)ctsio);
10640		return (CTL_RETVAL_COMPLETE);
10641	}
10642	notif_class = cdb->notif_class;
10643	alloc_len = scsi_2btoul(cdb->length);
10644
10645	data_len = sizeof(struct scsi_get_event_status_header);
10646	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10647	ctsio->kern_sg_entries = 0;
10648	ctsio->kern_data_resid = 0;
10649	ctsio->kern_rel_offset = 0;
10650
10651	if (data_len < alloc_len) {
10652		ctsio->residual = alloc_len - data_len;
10653		ctsio->kern_data_len = data_len;
10654		ctsio->kern_total_len = data_len;
10655	} else {
10656		ctsio->residual = 0;
10657		ctsio->kern_data_len = alloc_len;
10658		ctsio->kern_total_len = alloc_len;
10659	}
10660
10661	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10662	scsi_ulto2b(0, hdr->descr_length);
10663	hdr->nea_class = SGESN_NEA;
10664	hdr->supported_class = 0;
10665
10666	ctl_set_success(ctsio);
10667	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10668	ctsio->be_move_done = ctl_config_move_done;
10669	ctl_datamove((union ctl_io *)ctsio);
10670	return (CTL_RETVAL_COMPLETE);
10671}
10672
10673int
10674ctl_mechanism_status(struct ctl_scsiio *ctsio)
10675{
10676	struct scsi_mechanism_status_header *hdr;
10677	struct scsi_mechanism_status *cdb;
10678	struct ctl_lun *lun;
10679	uint32_t alloc_len, data_len;
10680
10681	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10682	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10683	alloc_len = scsi_2btoul(cdb->length);
10684
10685	data_len = sizeof(struct scsi_mechanism_status_header);
10686	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10687	ctsio->kern_sg_entries = 0;
10688	ctsio->kern_data_resid = 0;
10689	ctsio->kern_rel_offset = 0;
10690
10691	if (data_len < alloc_len) {
10692		ctsio->residual = alloc_len - data_len;
10693		ctsio->kern_data_len = data_len;
10694		ctsio->kern_total_len = data_len;
10695	} else {
10696		ctsio->residual = 0;
10697		ctsio->kern_data_len = alloc_len;
10698		ctsio->kern_total_len = alloc_len;
10699	}
10700
10701	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10702	hdr->state1 = 0x00;
10703	hdr->state2 = 0xe0;
10704	scsi_ulto3b(0, hdr->lba);
10705	hdr->slots_num = 0;
10706	scsi_ulto2b(0, hdr->slots_length);
10707
10708	ctl_set_success(ctsio);
10709	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10710	ctsio->be_move_done = ctl_config_move_done;
10711	ctl_datamove((union ctl_io *)ctsio);
10712	return (CTL_RETVAL_COMPLETE);
10713}
10714
10715static void
10716ctl_ultomsf(uint32_t lba, uint8_t *buf)
10717{
10718
10719	lba += 150;
10720	buf[0] = 0;
10721	buf[1] = bin2bcd((lba / 75) / 60);
10722	buf[2] = bin2bcd((lba / 75) % 60);
10723	buf[3] = bin2bcd(lba % 75);
10724}
10725
10726int
10727ctl_read_toc(struct ctl_scsiio *ctsio)
10728{
10729	struct scsi_read_toc_hdr *hdr;
10730	struct scsi_read_toc_type01_descr *descr;
10731	struct scsi_read_toc *cdb;
10732	struct ctl_lun *lun;
10733	uint32_t alloc_len, data_len;
10734	int format, msf;
10735
10736	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10737	cdb = (struct scsi_read_toc *)ctsio->cdb;
10738	msf = (cdb->byte2 & CD_MSF) != 0;
10739	format = cdb->format;
10740	alloc_len = scsi_2btoul(cdb->data_len);
10741
10742	data_len = sizeof(struct scsi_read_toc_hdr);
10743	if (format == 0)
10744		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10745	else
10746		data_len += sizeof(struct scsi_read_toc_type01_descr);
10747	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10748	ctsio->kern_sg_entries = 0;
10749	ctsio->kern_data_resid = 0;
10750	ctsio->kern_rel_offset = 0;
10751
10752	if (data_len < alloc_len) {
10753		ctsio->residual = alloc_len - data_len;
10754		ctsio->kern_data_len = data_len;
10755		ctsio->kern_total_len = data_len;
10756	} else {
10757		ctsio->residual = 0;
10758		ctsio->kern_data_len = alloc_len;
10759		ctsio->kern_total_len = alloc_len;
10760	}
10761
10762	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10763	if (format == 0) {
10764		scsi_ulto2b(0x12, hdr->data_length);
10765		hdr->first = 1;
10766		hdr->last = 1;
10767		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10768		descr->addr_ctl = 0x14;
10769		descr->track_number = 1;
10770		if (msf)
10771			ctl_ultomsf(0, descr->track_start);
10772		else
10773			scsi_ulto4b(0, descr->track_start);
10774		descr++;
10775		descr->addr_ctl = 0x14;
10776		descr->track_number = 0xaa;
10777		if (msf)
10778			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10779		else
10780			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10781	} else {
10782		scsi_ulto2b(0x0a, hdr->data_length);
10783		hdr->first = 1;
10784		hdr->last = 1;
10785		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10786		descr->addr_ctl = 0x14;
10787		descr->track_number = 1;
10788		if (msf)
10789			ctl_ultomsf(0, descr->track_start);
10790		else
10791			scsi_ulto4b(0, descr->track_start);
10792	}
10793
10794	ctl_set_success(ctsio);
10795	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10796	ctsio->be_move_done = ctl_config_move_done;
10797	ctl_datamove((union ctl_io *)ctsio);
10798	return (CTL_RETVAL_COMPLETE);
10799}
10800
10801/*
10802 * For known CDB types, parse the LBA and length.
10803 */
10804static int
10805ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10806{
10807	if (io->io_hdr.io_type != CTL_IO_SCSI)
10808		return (1);
10809
10810	switch (io->scsiio.cdb[0]) {
10811	case COMPARE_AND_WRITE: {
10812		struct scsi_compare_and_write *cdb;
10813
10814		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10815
10816		*lba = scsi_8btou64(cdb->addr);
10817		*len = cdb->length;
10818		break;
10819	}
10820	case READ_6:
10821	case WRITE_6: {
10822		struct scsi_rw_6 *cdb;
10823
10824		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10825
10826		*lba = scsi_3btoul(cdb->addr);
10827		/* only 5 bits are valid in the most significant address byte */
10828		*lba &= 0x1fffff;
10829		*len = cdb->length;
10830		break;
10831	}
10832	case READ_10:
10833	case WRITE_10: {
10834		struct scsi_rw_10 *cdb;
10835
10836		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10837
10838		*lba = scsi_4btoul(cdb->addr);
10839		*len = scsi_2btoul(cdb->length);
10840		break;
10841	}
10842	case WRITE_VERIFY_10: {
10843		struct scsi_write_verify_10 *cdb;
10844
10845		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10846
10847		*lba = scsi_4btoul(cdb->addr);
10848		*len = scsi_2btoul(cdb->length);
10849		break;
10850	}
10851	case READ_12:
10852	case WRITE_12: {
10853		struct scsi_rw_12 *cdb;
10854
10855		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10856
10857		*lba = scsi_4btoul(cdb->addr);
10858		*len = scsi_4btoul(cdb->length);
10859		break;
10860	}
10861	case WRITE_VERIFY_12: {
10862		struct scsi_write_verify_12 *cdb;
10863
10864		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10865
10866		*lba = scsi_4btoul(cdb->addr);
10867		*len = scsi_4btoul(cdb->length);
10868		break;
10869	}
10870	case READ_16:
10871	case WRITE_16: {
10872		struct scsi_rw_16 *cdb;
10873
10874		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10875
10876		*lba = scsi_8btou64(cdb->addr);
10877		*len = scsi_4btoul(cdb->length);
10878		break;
10879	}
10880	case WRITE_ATOMIC_16: {
10881		struct scsi_write_atomic_16 *cdb;
10882
10883		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10884
10885		*lba = scsi_8btou64(cdb->addr);
10886		*len = scsi_2btoul(cdb->length);
10887		break;
10888	}
10889	case WRITE_VERIFY_16: {
10890		struct scsi_write_verify_16 *cdb;
10891
10892		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10893
10894		*lba = scsi_8btou64(cdb->addr);
10895		*len = scsi_4btoul(cdb->length);
10896		break;
10897	}
10898	case WRITE_SAME_10: {
10899		struct scsi_write_same_10 *cdb;
10900
10901		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10902
10903		*lba = scsi_4btoul(cdb->addr);
10904		*len = scsi_2btoul(cdb->length);
10905		break;
10906	}
10907	case WRITE_SAME_16: {
10908		struct scsi_write_same_16 *cdb;
10909
10910		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10911
10912		*lba = scsi_8btou64(cdb->addr);
10913		*len = scsi_4btoul(cdb->length);
10914		break;
10915	}
10916	case VERIFY_10: {
10917		struct scsi_verify_10 *cdb;
10918
10919		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10920
10921		*lba = scsi_4btoul(cdb->addr);
10922		*len = scsi_2btoul(cdb->length);
10923		break;
10924	}
10925	case VERIFY_12: {
10926		struct scsi_verify_12 *cdb;
10927
10928		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10929
10930		*lba = scsi_4btoul(cdb->addr);
10931		*len = scsi_4btoul(cdb->length);
10932		break;
10933	}
10934	case VERIFY_16: {
10935		struct scsi_verify_16 *cdb;
10936
10937		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10938
10939		*lba = scsi_8btou64(cdb->addr);
10940		*len = scsi_4btoul(cdb->length);
10941		break;
10942	}
10943	case UNMAP: {
10944		*lba = 0;
10945		*len = UINT64_MAX;
10946		break;
10947	}
10948	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10949		struct scsi_get_lba_status *cdb;
10950
10951		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10952		*lba = scsi_8btou64(cdb->addr);
10953		*len = UINT32_MAX;
10954		break;
10955	}
10956	default:
10957		return (1);
10958		break; /* NOTREACHED */
10959	}
10960
10961	return (0);
10962}
10963
10964static ctl_action
10965ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10966    bool seq)
10967{
10968	uint64_t endlba1, endlba2;
10969
10970	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10971	endlba2 = lba2 + len2 - 1;
10972
10973	if ((endlba1 < lba2) || (endlba2 < lba1))
10974		return (CTL_ACTION_PASS);
10975	else
10976		return (CTL_ACTION_BLOCK);
10977}
10978
10979static int
10980ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10981{
10982	struct ctl_ptr_len_flags *ptrlen;
10983	struct scsi_unmap_desc *buf, *end, *range;
10984	uint64_t lba;
10985	uint32_t len;
10986
10987	/* If not UNMAP -- go other way. */
10988	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10989	    io->scsiio.cdb[0] != UNMAP)
10990		return (CTL_ACTION_ERROR);
10991
10992	/* If UNMAP without data -- block and wait for data. */
10993	ptrlen = (struct ctl_ptr_len_flags *)
10994	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10995	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10996	    ptrlen->ptr == NULL)
10997		return (CTL_ACTION_BLOCK);
10998
10999	/* UNMAP with data -- check for collision. */
11000	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
11001	end = buf + ptrlen->len / sizeof(*buf);
11002	for (range = buf; range < end; range++) {
11003		lba = scsi_8btou64(range->lba);
11004		len = scsi_4btoul(range->length);
11005		if ((lba < lba2 + len2) && (lba + len > lba2))
11006			return (CTL_ACTION_BLOCK);
11007	}
11008	return (CTL_ACTION_PASS);
11009}
11010
11011static ctl_action
11012ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
11013{
11014	uint64_t lba1, lba2;
11015	uint64_t len1, len2;
11016	int retval;
11017
11018	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11019		return (CTL_ACTION_ERROR);
11020
11021	retval = ctl_extent_check_unmap(io1, lba2, len2);
11022	if (retval != CTL_ACTION_ERROR)
11023		return (retval);
11024
11025	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11026		return (CTL_ACTION_ERROR);
11027
11028	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
11029		seq = FALSE;
11030	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
11031}
11032
11033static ctl_action
11034ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
11035{
11036	uint64_t lba1, lba2;
11037	uint64_t len1, len2;
11038
11039	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
11040		return (CTL_ACTION_PASS);
11041	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11042		return (CTL_ACTION_ERROR);
11043	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11044		return (CTL_ACTION_ERROR);
11045
11046	if (lba1 + len1 == lba2)
11047		return (CTL_ACTION_BLOCK);
11048	return (CTL_ACTION_PASS);
11049}
11050
11051static ctl_action
11052ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11053    union ctl_io *ooa_io)
11054{
11055	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11056	const ctl_serialize_action *serialize_row;
11057
11058	/*
11059	 * The initiator attempted multiple untagged commands at the same
11060	 * time.  Can't do that.
11061	 */
11062	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11063	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11064	 && ((pending_io->io_hdr.nexus.targ_port ==
11065	      ooa_io->io_hdr.nexus.targ_port)
11066	  && (pending_io->io_hdr.nexus.initid ==
11067	      ooa_io->io_hdr.nexus.initid))
11068	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11069	      CTL_FLAG_STATUS_SENT)) == 0))
11070		return (CTL_ACTION_OVERLAP);
11071
11072	/*
11073	 * The initiator attempted to send multiple tagged commands with
11074	 * the same ID.  (It's fine if different initiators have the same
11075	 * tag ID.)
11076	 *
11077	 * Even if all of those conditions are true, we don't kill the I/O
11078	 * if the command ahead of us has been aborted.  We won't end up
11079	 * sending it to the FETD, and it's perfectly legal to resend a
11080	 * command with the same tag number as long as the previous
11081	 * instance of this tag number has been aborted somehow.
11082	 */
11083	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11084	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11085	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11086	 && ((pending_io->io_hdr.nexus.targ_port ==
11087	      ooa_io->io_hdr.nexus.targ_port)
11088	  && (pending_io->io_hdr.nexus.initid ==
11089	      ooa_io->io_hdr.nexus.initid))
11090	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11091	      CTL_FLAG_STATUS_SENT)) == 0))
11092		return (CTL_ACTION_OVERLAP_TAG);
11093
11094	/*
11095	 * If we get a head of queue tag, SAM-3 says that we should
11096	 * immediately execute it.
11097	 *
11098	 * What happens if this command would normally block for some other
11099	 * reason?  e.g. a request sense with a head of queue tag
11100	 * immediately after a write.  Normally that would block, but this
11101	 * will result in its getting executed immediately...
11102	 *
11103	 * We currently return "pass" instead of "skip", so we'll end up
11104	 * going through the rest of the queue to check for overlapped tags.
11105	 *
11106	 * XXX KDM check for other types of blockage first??
11107	 */
11108	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11109		return (CTL_ACTION_PASS);
11110
11111	/*
11112	 * Ordered tags have to block until all items ahead of them
11113	 * have completed.  If we get called with an ordered tag, we always
11114	 * block, if something else is ahead of us in the queue.
11115	 */
11116	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11117		return (CTL_ACTION_BLOCK);
11118
11119	/*
11120	 * Simple tags get blocked until all head of queue and ordered tags
11121	 * ahead of them have completed.  I'm lumping untagged commands in
11122	 * with simple tags here.  XXX KDM is that the right thing to do?
11123	 */
11124	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11125	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11126	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11127	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11128		return (CTL_ACTION_BLOCK);
11129
11130	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11131	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11132	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11133	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11134	     pending_io->scsiio.cdb[1], pending_io));
11135	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11136	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11137		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11138	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11139	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11140	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11141	     ooa_io->scsiio.cdb[1], ooa_io));
11142
11143	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11144
11145	switch (serialize_row[pending_entry->seridx]) {
11146	case CTL_SER_BLOCK:
11147		return (CTL_ACTION_BLOCK);
11148	case CTL_SER_EXTENT:
11149		return (ctl_extent_check(ooa_io, pending_io,
11150		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11151	case CTL_SER_EXTENTOPT:
11152		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11153		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11154			return (ctl_extent_check(ooa_io, pending_io,
11155			    (lun->be_lun &&
11156			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11157		return (CTL_ACTION_PASS);
11158	case CTL_SER_EXTENTSEQ:
11159		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11160			return (ctl_extent_check_seq(ooa_io, pending_io));
11161		return (CTL_ACTION_PASS);
11162	case CTL_SER_PASS:
11163		return (CTL_ACTION_PASS);
11164	case CTL_SER_BLOCKOPT:
11165		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11166		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11167			return (CTL_ACTION_BLOCK);
11168		return (CTL_ACTION_PASS);
11169	case CTL_SER_SKIP:
11170		return (CTL_ACTION_SKIP);
11171	default:
11172		panic("%s: Invalid serialization value %d for %d => %d",
11173		    __func__, serialize_row[pending_entry->seridx],
11174		    pending_entry->seridx, ooa_entry->seridx);
11175	}
11176
11177	return (CTL_ACTION_ERROR);
11178}
11179
11180/*
11181 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11182 * Assumptions:
11183 * - pending_io is generally either incoming, or on the blocked queue
11184 * - starting I/O is the I/O we want to start the check with.
11185 */
11186static ctl_action
11187ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11188	      union ctl_io *starting_io)
11189{
11190	union ctl_io *ooa_io;
11191	ctl_action action;
11192
11193	mtx_assert(&lun->lun_lock, MA_OWNED);
11194
11195	/*
11196	 * Run back along the OOA queue, starting with the current
11197	 * blocked I/O and going through every I/O before it on the
11198	 * queue.  If starting_io is NULL, we'll just end up returning
11199	 * CTL_ACTION_PASS.
11200	 */
11201	for (ooa_io = starting_io; ooa_io != NULL;
11202	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11203	     ooa_links)){
11204
11205		/*
11206		 * This routine just checks to see whether
11207		 * cur_blocked is blocked by ooa_io, which is ahead
11208		 * of it in the queue.  It doesn't queue/dequeue
11209		 * cur_blocked.
11210		 */
11211		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11212		switch (action) {
11213		case CTL_ACTION_BLOCK:
11214		case CTL_ACTION_OVERLAP:
11215		case CTL_ACTION_OVERLAP_TAG:
11216		case CTL_ACTION_SKIP:
11217		case CTL_ACTION_ERROR:
11218			return (action);
11219			break; /* NOTREACHED */
11220		case CTL_ACTION_PASS:
11221			break;
11222		default:
11223			panic("%s: Invalid action %d\n", __func__, action);
11224		}
11225	}
11226
11227	return (CTL_ACTION_PASS);
11228}
11229
11230/*
11231 * Assumptions:
11232 * - An I/O has just completed, and has been removed from the per-LUN OOA
11233 *   queue, so some items on the blocked queue may now be unblocked.
11234 */
11235static int
11236ctl_check_blocked(struct ctl_lun *lun)
11237{
11238	struct ctl_softc *softc = lun->ctl_softc;
11239	union ctl_io *cur_blocked, *next_blocked;
11240
11241	mtx_assert(&lun->lun_lock, MA_OWNED);
11242
11243	/*
11244	 * Run forward from the head of the blocked queue, checking each
11245	 * entry against the I/Os prior to it on the OOA queue to see if
11246	 * there is still any blockage.
11247	 *
11248	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11249	 * with our removing a variable on it while it is traversing the
11250	 * list.
11251	 */
11252	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11253	     cur_blocked != NULL; cur_blocked = next_blocked) {
11254		union ctl_io *prev_ooa;
11255		ctl_action action;
11256
11257		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11258							  blocked_links);
11259
11260		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11261						      ctl_ooaq, ooa_links);
11262
11263		/*
11264		 * If cur_blocked happens to be the first item in the OOA
11265		 * queue now, prev_ooa will be NULL, and the action
11266		 * returned will just be CTL_ACTION_PASS.
11267		 */
11268		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11269
11270		switch (action) {
11271		case CTL_ACTION_BLOCK:
11272			/* Nothing to do here, still blocked */
11273			break;
11274		case CTL_ACTION_OVERLAP:
11275		case CTL_ACTION_OVERLAP_TAG:
11276			/*
11277			 * This shouldn't happen!  In theory we've already
11278			 * checked this command for overlap...
11279			 */
11280			break;
11281		case CTL_ACTION_PASS:
11282		case CTL_ACTION_SKIP: {
11283			const struct ctl_cmd_entry *entry;
11284
11285			/*
11286			 * The skip case shouldn't happen, this transaction
11287			 * should have never made it onto the blocked queue.
11288			 */
11289			/*
11290			 * This I/O is no longer blocked, we can remove it
11291			 * from the blocked queue.  Since this is a TAILQ
11292			 * (doubly linked list), we can do O(1) removals
11293			 * from any place on the list.
11294			 */
11295			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11296				     blocked_links);
11297			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11298
11299			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11300			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11301				/*
11302				 * Need to send IO back to original side to
11303				 * run
11304				 */
11305				union ctl_ha_msg msg_info;
11306
11307				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11308				msg_info.hdr.original_sc =
11309					cur_blocked->io_hdr.original_sc;
11310				msg_info.hdr.serializing_sc = cur_blocked;
11311				msg_info.hdr.msg_type = CTL_MSG_R2R;
11312				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11313				    sizeof(msg_info.hdr), M_NOWAIT);
11314				break;
11315			}
11316			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11317
11318			/*
11319			 * Check this I/O for LUN state changes that may
11320			 * have happened while this command was blocked.
11321			 * The LUN state may have been changed by a command
11322			 * ahead of us in the queue, so we need to re-check
11323			 * for any states that can be caused by SCSI
11324			 * commands.
11325			 */
11326			if (ctl_scsiio_lun_check(lun, entry,
11327						 &cur_blocked->scsiio) == 0) {
11328				cur_blocked->io_hdr.flags |=
11329				                      CTL_FLAG_IS_WAS_ON_RTR;
11330				ctl_enqueue_rtr(cur_blocked);
11331			} else
11332				ctl_done(cur_blocked);
11333			break;
11334		}
11335		default:
11336			/*
11337			 * This probably shouldn't happen -- we shouldn't
11338			 * get CTL_ACTION_ERROR, or anything else.
11339			 */
11340			break;
11341		}
11342	}
11343
11344	return (CTL_RETVAL_COMPLETE);
11345}
11346
11347/*
11348 * This routine (with one exception) checks LUN flags that can be set by
11349 * commands ahead of us in the OOA queue.  These flags have to be checked
11350 * when a command initially comes in, and when we pull a command off the
11351 * blocked queue and are preparing to execute it.  The reason we have to
11352 * check these flags for commands on the blocked queue is that the LUN
11353 * state may have been changed by a command ahead of us while we're on the
11354 * blocked queue.
11355 *
11356 * Ordering is somewhat important with these checks, so please pay
11357 * careful attention to the placement of any new checks.
11358 */
11359static int
11360ctl_scsiio_lun_check(struct ctl_lun *lun,
11361    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11362{
11363	struct ctl_softc *softc = lun->ctl_softc;
11364	int retval;
11365	uint32_t residx;
11366
11367	retval = 0;
11368
11369	mtx_assert(&lun->lun_lock, MA_OWNED);
11370
11371	/*
11372	 * If this shelf is a secondary shelf controller, we may have to
11373	 * reject some commands disallowed by HA mode and link state.
11374	 */
11375	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11376		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11377		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11378			ctl_set_lun_unavail(ctsio);
11379			retval = 1;
11380			goto bailout;
11381		}
11382		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11383		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11384			ctl_set_lun_transit(ctsio);
11385			retval = 1;
11386			goto bailout;
11387		}
11388		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11389		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11390			ctl_set_lun_standby(ctsio);
11391			retval = 1;
11392			goto bailout;
11393		}
11394
11395		/* The rest of checks are only done on executing side */
11396		if (softc->ha_mode == CTL_HA_MODE_XFER)
11397			goto bailout;
11398	}
11399
11400	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11401		if (lun->be_lun &&
11402		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11403			ctl_set_hw_write_protected(ctsio);
11404			retval = 1;
11405			goto bailout;
11406		}
11407		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11408		    .eca_and_aen & SCP_SWP) != 0) {
11409			ctl_set_sense(ctsio, /*current_error*/ 1,
11410			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11411			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11412			retval = 1;
11413			goto bailout;
11414		}
11415	}
11416
11417	/*
11418	 * Check for a reservation conflict.  If this command isn't allowed
11419	 * even on reserved LUNs, and if this initiator isn't the one who
11420	 * reserved us, reject the command with a reservation conflict.
11421	 */
11422	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11423	if ((lun->flags & CTL_LUN_RESERVED)
11424	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11425		if (lun->res_idx != residx) {
11426			ctl_set_reservation_conflict(ctsio);
11427			retval = 1;
11428			goto bailout;
11429		}
11430	}
11431
11432	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11433	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11434		/* No reservation or command is allowed. */;
11435	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11436	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11437	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11438	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11439		/* The command is allowed for Write Exclusive resv. */;
11440	} else {
11441		/*
11442		 * if we aren't registered or it's a res holder type
11443		 * reservation and this isn't the res holder then set a
11444		 * conflict.
11445		 */
11446		if (ctl_get_prkey(lun, residx) == 0 ||
11447		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11448			ctl_set_reservation_conflict(ctsio);
11449			retval = 1;
11450			goto bailout;
11451		}
11452	}
11453
11454	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11455		if (lun->flags & CTL_LUN_EJECTED)
11456			ctl_set_lun_ejected(ctsio);
11457		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11458			if (lun->flags & CTL_LUN_REMOVABLE)
11459				ctl_set_lun_no_media(ctsio);
11460			else
11461				ctl_set_lun_int_reqd(ctsio);
11462		} else if (lun->flags & CTL_LUN_STOPPED)
11463			ctl_set_lun_stopped(ctsio);
11464		else
11465			goto bailout;
11466		retval = 1;
11467		goto bailout;
11468	}
11469
11470bailout:
11471	return (retval);
11472}
11473
11474static void
11475ctl_failover_io(union ctl_io *io, int have_lock)
11476{
11477	ctl_set_busy(&io->scsiio);
11478	ctl_done(io);
11479}
11480
11481static void
11482ctl_failover_lun(union ctl_io *rio)
11483{
11484	struct ctl_softc *softc = control_softc;
11485	struct ctl_lun *lun;
11486	struct ctl_io_hdr *io, *next_io;
11487	uint32_t targ_lun;
11488
11489	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11490	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11491
11492	/* Find and lock the LUN. */
11493	mtx_lock(&softc->ctl_lock);
11494	if ((targ_lun < CTL_MAX_LUNS) &&
11495	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11496		mtx_lock(&lun->lun_lock);
11497		mtx_unlock(&softc->ctl_lock);
11498		if (lun->flags & CTL_LUN_DISABLED) {
11499			mtx_unlock(&lun->lun_lock);
11500			return;
11501		}
11502	} else {
11503		mtx_unlock(&softc->ctl_lock);
11504		return;
11505	}
11506
11507	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11508		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11509			/* We are master */
11510			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11511				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11512					io->flags |= CTL_FLAG_ABORT;
11513					io->flags |= CTL_FLAG_FAILOVER;
11514				} else { /* This can be only due to DATAMOVE */
11515					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11516					io->flags &= ~CTL_FLAG_DMA_INPROG;
11517					io->flags |= CTL_FLAG_IO_ACTIVE;
11518					io->port_status = 31340;
11519					ctl_enqueue_isc((union ctl_io *)io);
11520				}
11521			}
11522			/* We are slave */
11523			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11524				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11525				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11526					io->flags |= CTL_FLAG_FAILOVER;
11527				} else {
11528					ctl_set_busy(&((union ctl_io *)io)->
11529					    scsiio);
11530					ctl_done((union ctl_io *)io);
11531				}
11532			}
11533		}
11534	} else { /* SERIALIZE modes */
11535		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11536		    next_io) {
11537			/* We are master */
11538			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11539				TAILQ_REMOVE(&lun->blocked_queue, io,
11540				    blocked_links);
11541				io->flags &= ~CTL_FLAG_BLOCKED;
11542				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11543				ctl_free_io((union ctl_io *)io);
11544			}
11545		}
11546		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11547			/* We are master */
11548			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11549				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11550				ctl_free_io((union ctl_io *)io);
11551			}
11552			/* We are slave */
11553			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11554				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11555				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11556					ctl_set_busy(&((union ctl_io *)io)->
11557					    scsiio);
11558					ctl_done((union ctl_io *)io);
11559				}
11560			}
11561		}
11562		ctl_check_blocked(lun);
11563	}
11564	mtx_unlock(&lun->lun_lock);
11565}
11566
11567static int
11568ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11569{
11570	struct ctl_lun *lun;
11571	const struct ctl_cmd_entry *entry;
11572	uint32_t initidx, targ_lun;
11573	int retval;
11574
11575	retval = 0;
11576
11577	lun = NULL;
11578
11579	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11580	if ((targ_lun < CTL_MAX_LUNS)
11581	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11582		/*
11583		 * If the LUN is invalid, pretend that it doesn't exist.
11584		 * It will go away as soon as all pending I/O has been
11585		 * completed.
11586		 */
11587		mtx_lock(&lun->lun_lock);
11588		if (lun->flags & CTL_LUN_DISABLED) {
11589			mtx_unlock(&lun->lun_lock);
11590			lun = NULL;
11591			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11592			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11593		} else {
11594			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11595			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11596				lun->be_lun;
11597
11598			/*
11599			 * Every I/O goes into the OOA queue for a
11600			 * particular LUN, and stays there until completion.
11601			 */
11602#ifdef CTL_TIME_IO
11603			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11604				lun->idle_time += getsbinuptime() -
11605				    lun->last_busy;
11606			}
11607#endif
11608			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11609			    ooa_links);
11610		}
11611	} else {
11612		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11613		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11614	}
11615
11616	/* Get command entry and return error if it is unsuppotyed. */
11617	entry = ctl_validate_command(ctsio);
11618	if (entry == NULL) {
11619		if (lun)
11620			mtx_unlock(&lun->lun_lock);
11621		return (retval);
11622	}
11623
11624	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11625	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11626
11627	/*
11628	 * Check to see whether we can send this command to LUNs that don't
11629	 * exist.  This should pretty much only be the case for inquiry
11630	 * and request sense.  Further checks, below, really require having
11631	 * a LUN, so we can't really check the command anymore.  Just put
11632	 * it on the rtr queue.
11633	 */
11634	if (lun == NULL) {
11635		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11636			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11637			ctl_enqueue_rtr((union ctl_io *)ctsio);
11638			return (retval);
11639		}
11640
11641		ctl_set_unsupported_lun(ctsio);
11642		ctl_done((union ctl_io *)ctsio);
11643		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11644		return (retval);
11645	} else {
11646		/*
11647		 * Make sure we support this particular command on this LUN.
11648		 * e.g., we don't support writes to the control LUN.
11649		 */
11650		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11651			mtx_unlock(&lun->lun_lock);
11652			ctl_set_invalid_opcode(ctsio);
11653			ctl_done((union ctl_io *)ctsio);
11654			return (retval);
11655		}
11656	}
11657
11658	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11659
11660#ifdef CTL_WITH_CA
11661	/*
11662	 * If we've got a request sense, it'll clear the contingent
11663	 * allegiance condition.  Otherwise, if we have a CA condition for
11664	 * this initiator, clear it, because it sent down a command other
11665	 * than request sense.
11666	 */
11667	if ((ctsio->cdb[0] != REQUEST_SENSE)
11668	 && (ctl_is_set(lun->have_ca, initidx)))
11669		ctl_clear_mask(lun->have_ca, initidx);
11670#endif
11671
11672	/*
11673	 * If the command has this flag set, it handles its own unit
11674	 * attention reporting, we shouldn't do anything.  Otherwise we
11675	 * check for any pending unit attentions, and send them back to the
11676	 * initiator.  We only do this when a command initially comes in,
11677	 * not when we pull it off the blocked queue.
11678	 *
11679	 * According to SAM-3, section 5.3.2, the order that things get
11680	 * presented back to the host is basically unit attentions caused
11681	 * by some sort of reset event, busy status, reservation conflicts
11682	 * or task set full, and finally any other status.
11683	 *
11684	 * One issue here is that some of the unit attentions we report
11685	 * don't fall into the "reset" category (e.g. "reported luns data
11686	 * has changed").  So reporting it here, before the reservation
11687	 * check, may be technically wrong.  I guess the only thing to do
11688	 * would be to check for and report the reset events here, and then
11689	 * check for the other unit attention types after we check for a
11690	 * reservation conflict.
11691	 *
11692	 * XXX KDM need to fix this
11693	 */
11694	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11695		ctl_ua_type ua_type;
11696
11697		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11698		    SSD_TYPE_NONE);
11699		if (ua_type != CTL_UA_NONE) {
11700			mtx_unlock(&lun->lun_lock);
11701			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11702			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11703			ctsio->sense_len = SSD_FULL_SIZE;
11704			ctl_done((union ctl_io *)ctsio);
11705			return (retval);
11706		}
11707	}
11708
11709
11710	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11711		mtx_unlock(&lun->lun_lock);
11712		ctl_done((union ctl_io *)ctsio);
11713		return (retval);
11714	}
11715
11716	/*
11717	 * XXX CHD this is where we want to send IO to other side if
11718	 * this LUN is secondary on this SC. We will need to make a copy
11719	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11720	 * the copy we send as FROM_OTHER.
11721	 * We also need to stuff the address of the original IO so we can
11722	 * find it easily. Something similar will need be done on the other
11723	 * side so when we are done we can find the copy.
11724	 */
11725	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11726	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11727	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11728		union ctl_ha_msg msg_info;
11729		int isc_retval;
11730
11731		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11732		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11733		mtx_unlock(&lun->lun_lock);
11734
11735		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11736		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11737		msg_info.hdr.serializing_sc = NULL;
11738		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11739		msg_info.scsi.tag_num = ctsio->tag_num;
11740		msg_info.scsi.tag_type = ctsio->tag_type;
11741		msg_info.scsi.cdb_len = ctsio->cdb_len;
11742		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11743
11744		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11745		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11746		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11747			ctl_set_busy(ctsio);
11748			ctl_done((union ctl_io *)ctsio);
11749			return (retval);
11750		}
11751		return (retval);
11752	}
11753
11754	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11755			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11756			      ctl_ooaq, ooa_links))) {
11757	case CTL_ACTION_BLOCK:
11758		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11759		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11760				  blocked_links);
11761		mtx_unlock(&lun->lun_lock);
11762		return (retval);
11763	case CTL_ACTION_PASS:
11764	case CTL_ACTION_SKIP:
11765		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11766		mtx_unlock(&lun->lun_lock);
11767		ctl_enqueue_rtr((union ctl_io *)ctsio);
11768		break;
11769	case CTL_ACTION_OVERLAP:
11770		mtx_unlock(&lun->lun_lock);
11771		ctl_set_overlapped_cmd(ctsio);
11772		ctl_done((union ctl_io *)ctsio);
11773		break;
11774	case CTL_ACTION_OVERLAP_TAG:
11775		mtx_unlock(&lun->lun_lock);
11776		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11777		ctl_done((union ctl_io *)ctsio);
11778		break;
11779	case CTL_ACTION_ERROR:
11780	default:
11781		mtx_unlock(&lun->lun_lock);
11782		ctl_set_internal_failure(ctsio,
11783					 /*sks_valid*/ 0,
11784					 /*retry_count*/ 0);
11785		ctl_done((union ctl_io *)ctsio);
11786		break;
11787	}
11788	return (retval);
11789}
11790
11791const struct ctl_cmd_entry *
11792ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11793{
11794	const struct ctl_cmd_entry *entry;
11795	int service_action;
11796
11797	entry = &ctl_cmd_table[ctsio->cdb[0]];
11798	if (sa)
11799		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11800	if (entry->flags & CTL_CMD_FLAG_SA5) {
11801		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11802		entry = &((const struct ctl_cmd_entry *)
11803		    entry->execute)[service_action];
11804	}
11805	return (entry);
11806}
11807
11808const struct ctl_cmd_entry *
11809ctl_validate_command(struct ctl_scsiio *ctsio)
11810{
11811	const struct ctl_cmd_entry *entry;
11812	int i, sa;
11813	uint8_t diff;
11814
11815	entry = ctl_get_cmd_entry(ctsio, &sa);
11816	if (entry->execute == NULL) {
11817		if (sa)
11818			ctl_set_invalid_field(ctsio,
11819					      /*sks_valid*/ 1,
11820					      /*command*/ 1,
11821					      /*field*/ 1,
11822					      /*bit_valid*/ 1,
11823					      /*bit*/ 4);
11824		else
11825			ctl_set_invalid_opcode(ctsio);
11826		ctl_done((union ctl_io *)ctsio);
11827		return (NULL);
11828	}
11829	KASSERT(entry->length > 0,
11830	    ("Not defined length for command 0x%02x/0x%02x",
11831	     ctsio->cdb[0], ctsio->cdb[1]));
11832	for (i = 1; i < entry->length; i++) {
11833		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11834		if (diff == 0)
11835			continue;
11836		ctl_set_invalid_field(ctsio,
11837				      /*sks_valid*/ 1,
11838				      /*command*/ 1,
11839				      /*field*/ i,
11840				      /*bit_valid*/ 1,
11841				      /*bit*/ fls(diff) - 1);
11842		ctl_done((union ctl_io *)ctsio);
11843		return (NULL);
11844	}
11845	return (entry);
11846}
11847
11848static int
11849ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11850{
11851
11852	switch (lun_type) {
11853	case T_DIRECT:
11854		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11855			return (0);
11856		break;
11857	case T_PROCESSOR:
11858		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11859			return (0);
11860		break;
11861	case T_CDROM:
11862		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11863			return (0);
11864		break;
11865	default:
11866		return (0);
11867	}
11868	return (1);
11869}
11870
11871static int
11872ctl_scsiio(struct ctl_scsiio *ctsio)
11873{
11874	int retval;
11875	const struct ctl_cmd_entry *entry;
11876
11877	retval = CTL_RETVAL_COMPLETE;
11878
11879	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11880
11881	entry = ctl_get_cmd_entry(ctsio, NULL);
11882
11883	/*
11884	 * If this I/O has been aborted, just send it straight to
11885	 * ctl_done() without executing it.
11886	 */
11887	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11888		ctl_done((union ctl_io *)ctsio);
11889		goto bailout;
11890	}
11891
11892	/*
11893	 * All the checks should have been handled by ctl_scsiio_precheck().
11894	 * We should be clear now to just execute the I/O.
11895	 */
11896	retval = entry->execute(ctsio);
11897
11898bailout:
11899	return (retval);
11900}
11901
11902/*
11903 * Since we only implement one target right now, a bus reset simply resets
11904 * our single target.
11905 */
11906static int
11907ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11908{
11909	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11910}
11911
11912static int
11913ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11914		 ctl_ua_type ua_type)
11915{
11916	struct ctl_port *port;
11917	struct ctl_lun *lun;
11918	int retval;
11919
11920	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11921		union ctl_ha_msg msg_info;
11922
11923		msg_info.hdr.nexus = io->io_hdr.nexus;
11924		if (ua_type==CTL_UA_TARG_RESET)
11925			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11926		else
11927			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11928		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11929		msg_info.hdr.original_sc = NULL;
11930		msg_info.hdr.serializing_sc = NULL;
11931		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11932		    sizeof(msg_info.task), M_WAITOK);
11933	}
11934	retval = 0;
11935
11936	mtx_lock(&softc->ctl_lock);
11937	port = ctl_io_port(&io->io_hdr);
11938	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11939		if (port != NULL &&
11940		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11941			continue;
11942		retval += ctl_do_lun_reset(lun, io, ua_type);
11943	}
11944	mtx_unlock(&softc->ctl_lock);
11945	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11946	return (retval);
11947}
11948
11949/*
11950 * The LUN should always be set.  The I/O is optional, and is used to
11951 * distinguish between I/Os sent by this initiator, and by other
11952 * initiators.  We set unit attention for initiators other than this one.
11953 * SAM-3 is vague on this point.  It does say that a unit attention should
11954 * be established for other initiators when a LUN is reset (see section
11955 * 5.7.3), but it doesn't specifically say that the unit attention should
11956 * be established for this particular initiator when a LUN is reset.  Here
11957 * is the relevant text, from SAM-3 rev 8:
11958 *
11959 * 5.7.2 When a SCSI initiator port aborts its own tasks
11960 *
11961 * When a SCSI initiator port causes its own task(s) to be aborted, no
11962 * notification that the task(s) have been aborted shall be returned to
11963 * the SCSI initiator port other than the completion response for the
11964 * command or task management function action that caused the task(s) to
11965 * be aborted and notification(s) associated with related effects of the
11966 * action (e.g., a reset unit attention condition).
11967 *
11968 * XXX KDM for now, we're setting unit attention for all initiators.
11969 */
11970static int
11971ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11972{
11973	union ctl_io *xio;
11974#if 0
11975	uint32_t initidx;
11976#endif
11977	int i;
11978
11979	mtx_lock(&lun->lun_lock);
11980	/*
11981	 * Run through the OOA queue and abort each I/O.
11982	 */
11983	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11984	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11985		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11986	}
11987
11988	/*
11989	 * This version sets unit attention for every
11990	 */
11991#if 0
11992	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11993	ctl_est_ua_all(lun, initidx, ua_type);
11994#else
11995	ctl_est_ua_all(lun, -1, ua_type);
11996#endif
11997
11998	/*
11999	 * A reset (any kind, really) clears reservations established with
12000	 * RESERVE/RELEASE.  It does not clear reservations established
12001	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12002	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12003	 * reservations made with the RESERVE/RELEASE commands, because
12004	 * those commands are obsolete in SPC-3.
12005	 */
12006	lun->flags &= ~CTL_LUN_RESERVED;
12007
12008#ifdef CTL_WITH_CA
12009	for (i = 0; i < CTL_MAX_INITIATORS; i++)
12010		ctl_clear_mask(lun->have_ca, i);
12011#endif
12012	lun->prevent_count = 0;
12013	for (i = 0; i < CTL_MAX_INITIATORS; i++)
12014		ctl_clear_mask(lun->prevent, i);
12015	mtx_unlock(&lun->lun_lock);
12016
12017	return (0);
12018}
12019
12020static int
12021ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
12022{
12023	struct ctl_lun *lun;
12024	uint32_t targ_lun;
12025	int retval;
12026
12027	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12028	mtx_lock(&softc->ctl_lock);
12029	if ((targ_lun >= CTL_MAX_LUNS) ||
12030	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12031		mtx_unlock(&softc->ctl_lock);
12032		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12033		return (1);
12034	}
12035	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
12036	mtx_unlock(&softc->ctl_lock);
12037	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12038
12039	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
12040		union ctl_ha_msg msg_info;
12041
12042		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12043		msg_info.hdr.nexus = io->io_hdr.nexus;
12044		msg_info.task.task_action = CTL_TASK_LUN_RESET;
12045		msg_info.hdr.original_sc = NULL;
12046		msg_info.hdr.serializing_sc = NULL;
12047		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12048		    sizeof(msg_info.task), M_WAITOK);
12049	}
12050	return (retval);
12051}
12052
12053static void
12054ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12055    int other_sc)
12056{
12057	union ctl_io *xio;
12058
12059	mtx_assert(&lun->lun_lock, MA_OWNED);
12060
12061	/*
12062	 * Run through the OOA queue and attempt to find the given I/O.
12063	 * The target port, initiator ID, tag type and tag number have to
12064	 * match the values that we got from the initiator.  If we have an
12065	 * untagged command to abort, simply abort the first untagged command
12066	 * we come to.  We only allow one untagged command at a time of course.
12067	 */
12068	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12069	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12070
12071		if ((targ_port == UINT32_MAX ||
12072		     targ_port == xio->io_hdr.nexus.targ_port) &&
12073		    (init_id == UINT32_MAX ||
12074		     init_id == xio->io_hdr.nexus.initid)) {
12075			if (targ_port != xio->io_hdr.nexus.targ_port ||
12076			    init_id != xio->io_hdr.nexus.initid)
12077				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12078			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12079			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12080				union ctl_ha_msg msg_info;
12081
12082				msg_info.hdr.nexus = xio->io_hdr.nexus;
12083				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12084				msg_info.task.tag_num = xio->scsiio.tag_num;
12085				msg_info.task.tag_type = xio->scsiio.tag_type;
12086				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12087				msg_info.hdr.original_sc = NULL;
12088				msg_info.hdr.serializing_sc = NULL;
12089				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12090				    sizeof(msg_info.task), M_NOWAIT);
12091			}
12092		}
12093	}
12094}
12095
12096static int
12097ctl_abort_task_set(union ctl_io *io)
12098{
12099	struct ctl_softc *softc = control_softc;
12100	struct ctl_lun *lun;
12101	uint32_t targ_lun;
12102
12103	/*
12104	 * Look up the LUN.
12105	 */
12106	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12107	mtx_lock(&softc->ctl_lock);
12108	if ((targ_lun >= CTL_MAX_LUNS) ||
12109	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12110		mtx_unlock(&softc->ctl_lock);
12111		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12112		return (1);
12113	}
12114
12115	mtx_lock(&lun->lun_lock);
12116	mtx_unlock(&softc->ctl_lock);
12117	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12118		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12119		    io->io_hdr.nexus.initid,
12120		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12121	} else { /* CTL_TASK_CLEAR_TASK_SET */
12122		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12123		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12124	}
12125	mtx_unlock(&lun->lun_lock);
12126	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12127	return (0);
12128}
12129
12130static int
12131ctl_i_t_nexus_reset(union ctl_io *io)
12132{
12133	struct ctl_softc *softc = control_softc;
12134	struct ctl_lun *lun;
12135	uint32_t initidx;
12136
12137	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12138		union ctl_ha_msg msg_info;
12139
12140		msg_info.hdr.nexus = io->io_hdr.nexus;
12141		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12142		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12143		msg_info.hdr.original_sc = NULL;
12144		msg_info.hdr.serializing_sc = NULL;
12145		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12146		    sizeof(msg_info.task), M_WAITOK);
12147	}
12148
12149	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12150	mtx_lock(&softc->ctl_lock);
12151	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12152		mtx_lock(&lun->lun_lock);
12153		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12154		    io->io_hdr.nexus.initid, 1);
12155#ifdef CTL_WITH_CA
12156		ctl_clear_mask(lun->have_ca, initidx);
12157#endif
12158		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12159			lun->flags &= ~CTL_LUN_RESERVED;
12160		if (ctl_is_set(lun->prevent, initidx)) {
12161			ctl_clear_mask(lun->prevent, initidx);
12162			lun->prevent_count--;
12163		}
12164		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12165		mtx_unlock(&lun->lun_lock);
12166	}
12167	mtx_unlock(&softc->ctl_lock);
12168	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12169	return (0);
12170}
12171
12172static int
12173ctl_abort_task(union ctl_io *io)
12174{
12175	union ctl_io *xio;
12176	struct ctl_lun *lun;
12177	struct ctl_softc *softc;
12178#if 0
12179	struct sbuf sb;
12180	char printbuf[128];
12181#endif
12182	int found;
12183	uint32_t targ_lun;
12184
12185	softc = control_softc;
12186	found = 0;
12187
12188	/*
12189	 * Look up the LUN.
12190	 */
12191	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12192	mtx_lock(&softc->ctl_lock);
12193	if ((targ_lun >= CTL_MAX_LUNS) ||
12194	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12195		mtx_unlock(&softc->ctl_lock);
12196		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12197		return (1);
12198	}
12199
12200#if 0
12201	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12202	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12203#endif
12204
12205	mtx_lock(&lun->lun_lock);
12206	mtx_unlock(&softc->ctl_lock);
12207	/*
12208	 * Run through the OOA queue and attempt to find the given I/O.
12209	 * The target port, initiator ID, tag type and tag number have to
12210	 * match the values that we got from the initiator.  If we have an
12211	 * untagged command to abort, simply abort the first untagged command
12212	 * we come to.  We only allow one untagged command at a time of course.
12213	 */
12214	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12215	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12216#if 0
12217		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12218
12219		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12220			    lun->lun, xio->scsiio.tag_num,
12221			    xio->scsiio.tag_type,
12222			    (xio->io_hdr.blocked_links.tqe_prev
12223			    == NULL) ? "" : " BLOCKED",
12224			    (xio->io_hdr.flags &
12225			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12226			    (xio->io_hdr.flags &
12227			    CTL_FLAG_ABORT) ? " ABORT" : "",
12228			    (xio->io_hdr.flags &
12229			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12230		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12231		sbuf_finish(&sb);
12232		printf("%s\n", sbuf_data(&sb));
12233#endif
12234
12235		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12236		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12237		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12238			continue;
12239
12240		/*
12241		 * If the abort says that the task is untagged, the
12242		 * task in the queue must be untagged.  Otherwise,
12243		 * we just check to see whether the tag numbers
12244		 * match.  This is because the QLogic firmware
12245		 * doesn't pass back the tag type in an abort
12246		 * request.
12247		 */
12248#if 0
12249		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12250		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12251		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12252#endif
12253		/*
12254		 * XXX KDM we've got problems with FC, because it
12255		 * doesn't send down a tag type with aborts.  So we
12256		 * can only really go by the tag number...
12257		 * This may cause problems with parallel SCSI.
12258		 * Need to figure that out!!
12259		 */
12260		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12261			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12262			found = 1;
12263			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12264			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12265				union ctl_ha_msg msg_info;
12266
12267				msg_info.hdr.nexus = io->io_hdr.nexus;
12268				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12269				msg_info.task.tag_num = io->taskio.tag_num;
12270				msg_info.task.tag_type = io->taskio.tag_type;
12271				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12272				msg_info.hdr.original_sc = NULL;
12273				msg_info.hdr.serializing_sc = NULL;
12274#if 0
12275				printf("Sent Abort to other side\n");
12276#endif
12277				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12278				    sizeof(msg_info.task), M_NOWAIT);
12279			}
12280#if 0
12281			printf("ctl_abort_task: found I/O to abort\n");
12282#endif
12283		}
12284	}
12285	mtx_unlock(&lun->lun_lock);
12286
12287	if (found == 0) {
12288		/*
12289		 * This isn't really an error.  It's entirely possible for
12290		 * the abort and command completion to cross on the wire.
12291		 * This is more of an informative/diagnostic error.
12292		 */
12293#if 0
12294		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12295		       "%u:%u:%u tag %d type %d\n",
12296		       io->io_hdr.nexus.initid,
12297		       io->io_hdr.nexus.targ_port,
12298		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12299		       io->taskio.tag_type);
12300#endif
12301	}
12302	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12303	return (0);
12304}
12305
12306static int
12307ctl_query_task(union ctl_io *io, int task_set)
12308{
12309	union ctl_io *xio;
12310	struct ctl_lun *lun;
12311	struct ctl_softc *softc;
12312	int found = 0;
12313	uint32_t targ_lun;
12314
12315	softc = control_softc;
12316	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12317	mtx_lock(&softc->ctl_lock);
12318	if ((targ_lun >= CTL_MAX_LUNS) ||
12319	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12320		mtx_unlock(&softc->ctl_lock);
12321		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12322		return (1);
12323	}
12324	mtx_lock(&lun->lun_lock);
12325	mtx_unlock(&softc->ctl_lock);
12326	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12327	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12328
12329		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12330		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12331		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12332			continue;
12333
12334		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12335			found = 1;
12336			break;
12337		}
12338	}
12339	mtx_unlock(&lun->lun_lock);
12340	if (found)
12341		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12342	else
12343		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12344	return (0);
12345}
12346
12347static int
12348ctl_query_async_event(union ctl_io *io)
12349{
12350	struct ctl_lun *lun;
12351	struct ctl_softc *softc;
12352	ctl_ua_type ua;
12353	uint32_t targ_lun, initidx;
12354
12355	softc = control_softc;
12356	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12357	mtx_lock(&softc->ctl_lock);
12358	if ((targ_lun >= CTL_MAX_LUNS) ||
12359	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12360		mtx_unlock(&softc->ctl_lock);
12361		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12362		return (1);
12363	}
12364	mtx_lock(&lun->lun_lock);
12365	mtx_unlock(&softc->ctl_lock);
12366	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12367	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12368	mtx_unlock(&lun->lun_lock);
12369	if (ua != CTL_UA_NONE)
12370		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12371	else
12372		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12373	return (0);
12374}
12375
12376static void
12377ctl_run_task(union ctl_io *io)
12378{
12379	struct ctl_softc *softc = control_softc;
12380	int retval = 1;
12381
12382	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12383	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12384	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12385	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12386	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12387	switch (io->taskio.task_action) {
12388	case CTL_TASK_ABORT_TASK:
12389		retval = ctl_abort_task(io);
12390		break;
12391	case CTL_TASK_ABORT_TASK_SET:
12392	case CTL_TASK_CLEAR_TASK_SET:
12393		retval = ctl_abort_task_set(io);
12394		break;
12395	case CTL_TASK_CLEAR_ACA:
12396		break;
12397	case CTL_TASK_I_T_NEXUS_RESET:
12398		retval = ctl_i_t_nexus_reset(io);
12399		break;
12400	case CTL_TASK_LUN_RESET:
12401		retval = ctl_lun_reset(softc, io);
12402		break;
12403	case CTL_TASK_TARGET_RESET:
12404		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12405		break;
12406	case CTL_TASK_BUS_RESET:
12407		retval = ctl_bus_reset(softc, io);
12408		break;
12409	case CTL_TASK_PORT_LOGIN:
12410		break;
12411	case CTL_TASK_PORT_LOGOUT:
12412		break;
12413	case CTL_TASK_QUERY_TASK:
12414		retval = ctl_query_task(io, 0);
12415		break;
12416	case CTL_TASK_QUERY_TASK_SET:
12417		retval = ctl_query_task(io, 1);
12418		break;
12419	case CTL_TASK_QUERY_ASYNC_EVENT:
12420		retval = ctl_query_async_event(io);
12421		break;
12422	default:
12423		printf("%s: got unknown task management event %d\n",
12424		       __func__, io->taskio.task_action);
12425		break;
12426	}
12427	if (retval == 0)
12428		io->io_hdr.status = CTL_SUCCESS;
12429	else
12430		io->io_hdr.status = CTL_ERROR;
12431	ctl_done(io);
12432}
12433
12434/*
12435 * For HA operation.  Handle commands that come in from the other
12436 * controller.
12437 */
12438static void
12439ctl_handle_isc(union ctl_io *io)
12440{
12441	int free_io;
12442	struct ctl_lun *lun;
12443	struct ctl_softc *softc = control_softc;
12444	uint32_t targ_lun;
12445
12446	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12447	lun = softc->ctl_luns[targ_lun];
12448
12449	switch (io->io_hdr.msg_type) {
12450	case CTL_MSG_SERIALIZE:
12451		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12452		break;
12453	case CTL_MSG_R2R: {
12454		const struct ctl_cmd_entry *entry;
12455
12456		/*
12457		 * This is only used in SER_ONLY mode.
12458		 */
12459		free_io = 0;
12460		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12461		mtx_lock(&lun->lun_lock);
12462		if (ctl_scsiio_lun_check(lun,
12463		    entry, (struct ctl_scsiio *)io) != 0) {
12464			mtx_unlock(&lun->lun_lock);
12465			ctl_done(io);
12466			break;
12467		}
12468		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12469		mtx_unlock(&lun->lun_lock);
12470		ctl_enqueue_rtr(io);
12471		break;
12472	}
12473	case CTL_MSG_FINISH_IO:
12474		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12475			free_io = 0;
12476			ctl_done(io);
12477		} else {
12478			free_io = 1;
12479			mtx_lock(&lun->lun_lock);
12480			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12481				     ooa_links);
12482			ctl_check_blocked(lun);
12483			mtx_unlock(&lun->lun_lock);
12484		}
12485		break;
12486	case CTL_MSG_PERS_ACTION:
12487		ctl_hndl_per_res_out_on_other_sc(
12488			(union ctl_ha_msg *)&io->presio.pr_msg);
12489		free_io = 1;
12490		break;
12491	case CTL_MSG_BAD_JUJU:
12492		free_io = 0;
12493		ctl_done(io);
12494		break;
12495	case CTL_MSG_DATAMOVE:
12496		/* Only used in XFER mode */
12497		free_io = 0;
12498		ctl_datamove_remote(io);
12499		break;
12500	case CTL_MSG_DATAMOVE_DONE:
12501		/* Only used in XFER mode */
12502		free_io = 0;
12503		io->scsiio.be_move_done(io);
12504		break;
12505	case CTL_MSG_FAILOVER:
12506		ctl_failover_lun(io);
12507		free_io = 1;
12508		break;
12509	default:
12510		free_io = 1;
12511		printf("%s: Invalid message type %d\n",
12512		       __func__, io->io_hdr.msg_type);
12513		break;
12514	}
12515	if (free_io)
12516		ctl_free_io(io);
12517
12518}
12519
12520
12521/*
12522 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12523 * there is no match.
12524 */
12525static ctl_lun_error_pattern
12526ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12527{
12528	const struct ctl_cmd_entry *entry;
12529	ctl_lun_error_pattern filtered_pattern, pattern;
12530
12531	pattern = desc->error_pattern;
12532
12533	/*
12534	 * XXX KDM we need more data passed into this function to match a
12535	 * custom pattern, and we actually need to implement custom pattern
12536	 * matching.
12537	 */
12538	if (pattern & CTL_LUN_PAT_CMD)
12539		return (CTL_LUN_PAT_CMD);
12540
12541	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12542		return (CTL_LUN_PAT_ANY);
12543
12544	entry = ctl_get_cmd_entry(ctsio, NULL);
12545
12546	filtered_pattern = entry->pattern & pattern;
12547
12548	/*
12549	 * If the user requested specific flags in the pattern (e.g.
12550	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12551	 * flags.
12552	 *
12553	 * If the user did not specify any flags, it doesn't matter whether
12554	 * or not the command supports the flags.
12555	 */
12556	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12557	     (pattern & ~CTL_LUN_PAT_MASK))
12558		return (CTL_LUN_PAT_NONE);
12559
12560	/*
12561	 * If the user asked for a range check, see if the requested LBA
12562	 * range overlaps with this command's LBA range.
12563	 */
12564	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12565		uint64_t lba1;
12566		uint64_t len1;
12567		ctl_action action;
12568		int retval;
12569
12570		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12571		if (retval != 0)
12572			return (CTL_LUN_PAT_NONE);
12573
12574		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12575					      desc->lba_range.len, FALSE);
12576		/*
12577		 * A "pass" means that the LBA ranges don't overlap, so
12578		 * this doesn't match the user's range criteria.
12579		 */
12580		if (action == CTL_ACTION_PASS)
12581			return (CTL_LUN_PAT_NONE);
12582	}
12583
12584	return (filtered_pattern);
12585}
12586
12587static void
12588ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12589{
12590	struct ctl_error_desc *desc, *desc2;
12591
12592	mtx_assert(&lun->lun_lock, MA_OWNED);
12593
12594	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12595		ctl_lun_error_pattern pattern;
12596		/*
12597		 * Check to see whether this particular command matches
12598		 * the pattern in the descriptor.
12599		 */
12600		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12601		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12602			continue;
12603
12604		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12605		case CTL_LUN_INJ_ABORTED:
12606			ctl_set_aborted(&io->scsiio);
12607			break;
12608		case CTL_LUN_INJ_MEDIUM_ERR:
12609			ctl_set_medium_error(&io->scsiio,
12610			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12611			     CTL_FLAG_DATA_OUT);
12612			break;
12613		case CTL_LUN_INJ_UA:
12614			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12615			 * OCCURRED */
12616			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12617			break;
12618		case CTL_LUN_INJ_CUSTOM:
12619			/*
12620			 * We're assuming the user knows what he is doing.
12621			 * Just copy the sense information without doing
12622			 * checks.
12623			 */
12624			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12625			      MIN(sizeof(desc->custom_sense),
12626				  sizeof(io->scsiio.sense_data)));
12627			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12628			io->scsiio.sense_len = SSD_FULL_SIZE;
12629			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12630			break;
12631		case CTL_LUN_INJ_NONE:
12632		default:
12633			/*
12634			 * If this is an error injection type we don't know
12635			 * about, clear the continuous flag (if it is set)
12636			 * so it will get deleted below.
12637			 */
12638			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12639			break;
12640		}
12641		/*
12642		 * By default, each error injection action is a one-shot
12643		 */
12644		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12645			continue;
12646
12647		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12648
12649		free(desc, M_CTL);
12650	}
12651}
12652
12653#ifdef CTL_IO_DELAY
12654static void
12655ctl_datamove_timer_wakeup(void *arg)
12656{
12657	union ctl_io *io;
12658
12659	io = (union ctl_io *)arg;
12660
12661	ctl_datamove(io);
12662}
12663#endif /* CTL_IO_DELAY */
12664
12665void
12666ctl_datamove(union ctl_io *io)
12667{
12668	struct ctl_lun *lun;
12669	void (*fe_datamove)(union ctl_io *io);
12670
12671	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12672
12673	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12674
12675	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12676#ifdef CTL_TIME_IO
12677	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12678		char str[256];
12679		char path_str[64];
12680		struct sbuf sb;
12681
12682		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12683		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12684
12685		sbuf_cat(&sb, path_str);
12686		switch (io->io_hdr.io_type) {
12687		case CTL_IO_SCSI:
12688			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12689			sbuf_printf(&sb, "\n");
12690			sbuf_cat(&sb, path_str);
12691			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12692				    io->scsiio.tag_num, io->scsiio.tag_type);
12693			break;
12694		case CTL_IO_TASK:
12695			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12696				    "Tag Type: %d\n", io->taskio.task_action,
12697				    io->taskio.tag_num, io->taskio.tag_type);
12698			break;
12699		default:
12700			panic("%s: Invalid CTL I/O type %d\n",
12701			    __func__, io->io_hdr.io_type);
12702		}
12703		sbuf_cat(&sb, path_str);
12704		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12705			    (intmax_t)time_uptime - io->io_hdr.start_time);
12706		sbuf_finish(&sb);
12707		printf("%s", sbuf_data(&sb));
12708	}
12709#endif /* CTL_TIME_IO */
12710
12711#ifdef CTL_IO_DELAY
12712	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12713		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12714	} else {
12715		if ((lun != NULL)
12716		 && (lun->delay_info.datamove_delay > 0)) {
12717
12718			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12719			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12720			callout_reset(&io->io_hdr.delay_callout,
12721				      lun->delay_info.datamove_delay * hz,
12722				      ctl_datamove_timer_wakeup, io);
12723			if (lun->delay_info.datamove_type ==
12724			    CTL_DELAY_TYPE_ONESHOT)
12725				lun->delay_info.datamove_delay = 0;
12726			return;
12727		}
12728	}
12729#endif
12730
12731	/*
12732	 * This command has been aborted.  Set the port status, so we fail
12733	 * the data move.
12734	 */
12735	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12736		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12737		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12738		       io->io_hdr.nexus.targ_port,
12739		       io->io_hdr.nexus.targ_lun);
12740		io->io_hdr.port_status = 31337;
12741		/*
12742		 * Note that the backend, in this case, will get the
12743		 * callback in its context.  In other cases it may get
12744		 * called in the frontend's interrupt thread context.
12745		 */
12746		io->scsiio.be_move_done(io);
12747		return;
12748	}
12749
12750	/* Don't confuse frontend with zero length data move. */
12751	if (io->scsiio.kern_data_len == 0) {
12752		io->scsiio.be_move_done(io);
12753		return;
12754	}
12755
12756	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12757	fe_datamove(io);
12758}
12759
12760static void
12761ctl_send_datamove_done(union ctl_io *io, int have_lock)
12762{
12763	union ctl_ha_msg msg;
12764#ifdef CTL_TIME_IO
12765	struct bintime cur_bt;
12766#endif
12767
12768	memset(&msg, 0, sizeof(msg));
12769	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12770	msg.hdr.original_sc = io;
12771	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12772	msg.hdr.nexus = io->io_hdr.nexus;
12773	msg.hdr.status = io->io_hdr.status;
12774	msg.scsi.tag_num = io->scsiio.tag_num;
12775	msg.scsi.tag_type = io->scsiio.tag_type;
12776	msg.scsi.scsi_status = io->scsiio.scsi_status;
12777	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12778	       io->scsiio.sense_len);
12779	msg.scsi.sense_len = io->scsiio.sense_len;
12780	msg.scsi.sense_residual = io->scsiio.sense_residual;
12781	msg.scsi.fetd_status = io->io_hdr.port_status;
12782	msg.scsi.residual = io->scsiio.residual;
12783	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12784	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12785		ctl_failover_io(io, /*have_lock*/ have_lock);
12786		return;
12787	}
12788	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12789	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12790	    msg.scsi.sense_len, M_WAITOK);
12791
12792#ifdef CTL_TIME_IO
12793	getbinuptime(&cur_bt);
12794	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12795	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12796#endif
12797	io->io_hdr.num_dmas++;
12798}
12799
12800/*
12801 * The DMA to the remote side is done, now we need to tell the other side
12802 * we're done so it can continue with its data movement.
12803 */
12804static void
12805ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12806{
12807	union ctl_io *io;
12808	uint32_t i;
12809
12810	io = rq->context;
12811
12812	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12813		printf("%s: ISC DMA write failed with error %d", __func__,
12814		       rq->ret);
12815		ctl_set_internal_failure(&io->scsiio,
12816					 /*sks_valid*/ 1,
12817					 /*retry_count*/ rq->ret);
12818	}
12819
12820	ctl_dt_req_free(rq);
12821
12822	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12823		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12824	free(io->io_hdr.remote_sglist, M_CTL);
12825	io->io_hdr.remote_sglist = NULL;
12826	io->io_hdr.local_sglist = NULL;
12827
12828	/*
12829	 * The data is in local and remote memory, so now we need to send
12830	 * status (good or back) back to the other side.
12831	 */
12832	ctl_send_datamove_done(io, /*have_lock*/ 0);
12833}
12834
12835/*
12836 * We've moved the data from the host/controller into local memory.  Now we
12837 * need to push it over to the remote controller's memory.
12838 */
12839static int
12840ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12841{
12842	int retval;
12843
12844	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12845					  ctl_datamove_remote_write_cb);
12846	return (retval);
12847}
12848
12849static void
12850ctl_datamove_remote_write(union ctl_io *io)
12851{
12852	int retval;
12853	void (*fe_datamove)(union ctl_io *io);
12854
12855	/*
12856	 * - Get the data from the host/HBA into local memory.
12857	 * - DMA memory from the local controller to the remote controller.
12858	 * - Send status back to the remote controller.
12859	 */
12860
12861	retval = ctl_datamove_remote_sgl_setup(io);
12862	if (retval != 0)
12863		return;
12864
12865	/* Switch the pointer over so the FETD knows what to do */
12866	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12867
12868	/*
12869	 * Use a custom move done callback, since we need to send completion
12870	 * back to the other controller, not to the backend on this side.
12871	 */
12872	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12873
12874	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12875	fe_datamove(io);
12876}
12877
12878static int
12879ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12880{
12881#if 0
12882	char str[256];
12883	char path_str[64];
12884	struct sbuf sb;
12885#endif
12886	uint32_t i;
12887
12888	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12889		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12890	free(io->io_hdr.remote_sglist, M_CTL);
12891	io->io_hdr.remote_sglist = NULL;
12892	io->io_hdr.local_sglist = NULL;
12893
12894#if 0
12895	scsi_path_string(io, path_str, sizeof(path_str));
12896	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12897	sbuf_cat(&sb, path_str);
12898	scsi_command_string(&io->scsiio, NULL, &sb);
12899	sbuf_printf(&sb, "\n");
12900	sbuf_cat(&sb, path_str);
12901	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12902		    io->scsiio.tag_num, io->scsiio.tag_type);
12903	sbuf_cat(&sb, path_str);
12904	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12905		    io->io_hdr.flags, io->io_hdr.status);
12906	sbuf_finish(&sb);
12907	printk("%s", sbuf_data(&sb));
12908#endif
12909
12910
12911	/*
12912	 * The read is done, now we need to send status (good or bad) back
12913	 * to the other side.
12914	 */
12915	ctl_send_datamove_done(io, /*have_lock*/ 0);
12916
12917	return (0);
12918}
12919
12920static void
12921ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12922{
12923	union ctl_io *io;
12924	void (*fe_datamove)(union ctl_io *io);
12925
12926	io = rq->context;
12927
12928	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12929		printf("%s: ISC DMA read failed with error %d\n", __func__,
12930		       rq->ret);
12931		ctl_set_internal_failure(&io->scsiio,
12932					 /*sks_valid*/ 1,
12933					 /*retry_count*/ rq->ret);
12934	}
12935
12936	ctl_dt_req_free(rq);
12937
12938	/* Switch the pointer over so the FETD knows what to do */
12939	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12940
12941	/*
12942	 * Use a custom move done callback, since we need to send completion
12943	 * back to the other controller, not to the backend on this side.
12944	 */
12945	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12946
12947	/* XXX KDM add checks like the ones in ctl_datamove? */
12948
12949	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12950	fe_datamove(io);
12951}
12952
12953static int
12954ctl_datamove_remote_sgl_setup(union ctl_io *io)
12955{
12956	struct ctl_sg_entry *local_sglist;
12957	uint32_t len_to_go;
12958	int retval;
12959	int i;
12960
12961	retval = 0;
12962	local_sglist = io->io_hdr.local_sglist;
12963	len_to_go = io->scsiio.kern_data_len;
12964
12965	/*
12966	 * The difficult thing here is that the size of the various
12967	 * S/G segments may be different than the size from the
12968	 * remote controller.  That'll make it harder when DMAing
12969	 * the data back to the other side.
12970	 */
12971	for (i = 0; len_to_go > 0; i++) {
12972		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12973		local_sglist[i].addr =
12974		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12975
12976		len_to_go -= local_sglist[i].len;
12977	}
12978	/*
12979	 * Reset the number of S/G entries accordingly.  The original
12980	 * number of S/G entries is available in rem_sg_entries.
12981	 */
12982	io->scsiio.kern_sg_entries = i;
12983
12984#if 0
12985	printf("%s: kern_sg_entries = %d\n", __func__,
12986	       io->scsiio.kern_sg_entries);
12987	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12988		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12989		       local_sglist[i].addr, local_sglist[i].len);
12990#endif
12991
12992	return (retval);
12993}
12994
12995static int
12996ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12997			 ctl_ha_dt_cb callback)
12998{
12999	struct ctl_ha_dt_req *rq;
13000	struct ctl_sg_entry *remote_sglist, *local_sglist;
13001	uint32_t local_used, remote_used, total_used;
13002	int i, j, isc_ret;
13003
13004	rq = ctl_dt_req_alloc();
13005
13006	/*
13007	 * If we failed to allocate the request, and if the DMA didn't fail
13008	 * anyway, set busy status.  This is just a resource allocation
13009	 * failure.
13010	 */
13011	if ((rq == NULL)
13012	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
13013	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
13014		ctl_set_busy(&io->scsiio);
13015
13016	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
13017	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
13018
13019		if (rq != NULL)
13020			ctl_dt_req_free(rq);
13021
13022		/*
13023		 * The data move failed.  We need to return status back
13024		 * to the other controller.  No point in trying to DMA
13025		 * data to the remote controller.
13026		 */
13027
13028		ctl_send_datamove_done(io, /*have_lock*/ 0);
13029
13030		return (1);
13031	}
13032
13033	local_sglist = io->io_hdr.local_sglist;
13034	remote_sglist = io->io_hdr.remote_sglist;
13035	local_used = 0;
13036	remote_used = 0;
13037	total_used = 0;
13038
13039	/*
13040	 * Pull/push the data over the wire from/to the other controller.
13041	 * This takes into account the possibility that the local and
13042	 * remote sglists may not be identical in terms of the size of
13043	 * the elements and the number of elements.
13044	 *
13045	 * One fundamental assumption here is that the length allocated for
13046	 * both the local and remote sglists is identical.  Otherwise, we've
13047	 * essentially got a coding error of some sort.
13048	 */
13049	isc_ret = CTL_HA_STATUS_SUCCESS;
13050	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13051		uint32_t cur_len;
13052		uint8_t *tmp_ptr;
13053
13054		rq->command = command;
13055		rq->context = io;
13056
13057		/*
13058		 * Both pointers should be aligned.  But it is possible
13059		 * that the allocation length is not.  They should both
13060		 * also have enough slack left over at the end, though,
13061		 * to round up to the next 8 byte boundary.
13062		 */
13063		cur_len = MIN(local_sglist[i].len - local_used,
13064			      remote_sglist[j].len - remote_used);
13065		rq->size = cur_len;
13066
13067		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13068		tmp_ptr += local_used;
13069
13070#if 0
13071		/* Use physical addresses when talking to ISC hardware */
13072		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13073			/* XXX KDM use busdma */
13074			rq->local = vtophys(tmp_ptr);
13075		} else
13076			rq->local = tmp_ptr;
13077#else
13078		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
13079		    ("HA does not support BUS_ADDR"));
13080		rq->local = tmp_ptr;
13081#endif
13082
13083		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13084		tmp_ptr += remote_used;
13085		rq->remote = tmp_ptr;
13086
13087		rq->callback = NULL;
13088
13089		local_used += cur_len;
13090		if (local_used >= local_sglist[i].len) {
13091			i++;
13092			local_used = 0;
13093		}
13094
13095		remote_used += cur_len;
13096		if (remote_used >= remote_sglist[j].len) {
13097			j++;
13098			remote_used = 0;
13099		}
13100		total_used += cur_len;
13101
13102		if (total_used >= io->scsiio.kern_data_len)
13103			rq->callback = callback;
13104
13105#if 0
13106		printf("%s: %s: local %p remote %p size %d\n", __func__,
13107		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13108		       rq->local, rq->remote, rq->size);
13109#endif
13110
13111		isc_ret = ctl_dt_single(rq);
13112		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13113			break;
13114	}
13115	if (isc_ret != CTL_HA_STATUS_WAIT) {
13116		rq->ret = isc_ret;
13117		callback(rq);
13118	}
13119
13120	return (0);
13121}
13122
13123static void
13124ctl_datamove_remote_read(union ctl_io *io)
13125{
13126	int retval;
13127	uint32_t i;
13128
13129	/*
13130	 * This will send an error to the other controller in the case of a
13131	 * failure.
13132	 */
13133	retval = ctl_datamove_remote_sgl_setup(io);
13134	if (retval != 0)
13135		return;
13136
13137	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13138					  ctl_datamove_remote_read_cb);
13139	if (retval != 0) {
13140		/*
13141		 * Make sure we free memory if there was an error..  The
13142		 * ctl_datamove_remote_xfer() function will send the
13143		 * datamove done message, or call the callback with an
13144		 * error if there is a problem.
13145		 */
13146		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13147			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13148		free(io->io_hdr.remote_sglist, M_CTL);
13149		io->io_hdr.remote_sglist = NULL;
13150		io->io_hdr.local_sglist = NULL;
13151	}
13152}
13153
13154/*
13155 * Process a datamove request from the other controller.  This is used for
13156 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13157 * first.  Once that is complete, the data gets DMAed into the remote
13158 * controller's memory.  For reads, we DMA from the remote controller's
13159 * memory into our memory first, and then move it out to the FETD.
13160 */
13161static void
13162ctl_datamove_remote(union ctl_io *io)
13163{
13164
13165	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13166
13167	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13168		ctl_failover_io(io, /*have_lock*/ 0);
13169		return;
13170	}
13171
13172	/*
13173	 * Note that we look for an aborted I/O here, but don't do some of
13174	 * the other checks that ctl_datamove() normally does.
13175	 * We don't need to run the datamove delay code, since that should
13176	 * have been done if need be on the other controller.
13177	 */
13178	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13179		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13180		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13181		       io->io_hdr.nexus.targ_port,
13182		       io->io_hdr.nexus.targ_lun);
13183		io->io_hdr.port_status = 31338;
13184		ctl_send_datamove_done(io, /*have_lock*/ 0);
13185		return;
13186	}
13187
13188	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13189		ctl_datamove_remote_write(io);
13190	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13191		ctl_datamove_remote_read(io);
13192	else {
13193		io->io_hdr.port_status = 31339;
13194		ctl_send_datamove_done(io, /*have_lock*/ 0);
13195	}
13196}
13197
13198static void
13199ctl_process_done(union ctl_io *io)
13200{
13201	struct ctl_lun *lun;
13202	struct ctl_softc *softc = control_softc;
13203	void (*fe_done)(union ctl_io *io);
13204	union ctl_ha_msg msg;
13205	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13206
13207	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13208	fe_done = softc->ctl_ports[targ_port]->fe_done;
13209
13210#ifdef CTL_TIME_IO
13211	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13212		char str[256];
13213		char path_str[64];
13214		struct sbuf sb;
13215
13216		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13217		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13218
13219		sbuf_cat(&sb, path_str);
13220		switch (io->io_hdr.io_type) {
13221		case CTL_IO_SCSI:
13222			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13223			sbuf_printf(&sb, "\n");
13224			sbuf_cat(&sb, path_str);
13225			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13226				    io->scsiio.tag_num, io->scsiio.tag_type);
13227			break;
13228		case CTL_IO_TASK:
13229			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13230				    "Tag Type: %d\n", io->taskio.task_action,
13231				    io->taskio.tag_num, io->taskio.tag_type);
13232			break;
13233		default:
13234			panic("%s: Invalid CTL I/O type %d\n",
13235			    __func__, io->io_hdr.io_type);
13236		}
13237		sbuf_cat(&sb, path_str);
13238		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13239			    (intmax_t)time_uptime - io->io_hdr.start_time);
13240		sbuf_finish(&sb);
13241		printf("%s", sbuf_data(&sb));
13242	}
13243#endif /* CTL_TIME_IO */
13244
13245	switch (io->io_hdr.io_type) {
13246	case CTL_IO_SCSI:
13247		break;
13248	case CTL_IO_TASK:
13249		if (ctl_debug & CTL_DEBUG_INFO)
13250			ctl_io_error_print(io, NULL);
13251		fe_done(io);
13252		return;
13253	default:
13254		panic("%s: Invalid CTL I/O type %d\n",
13255		    __func__, io->io_hdr.io_type);
13256	}
13257
13258	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13259	if (lun == NULL) {
13260		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13261				 io->io_hdr.nexus.targ_mapped_lun));
13262		goto bailout;
13263	}
13264
13265	mtx_lock(&lun->lun_lock);
13266
13267	/*
13268	 * Check to see if we have any errors to inject here.  We only
13269	 * inject errors for commands that don't already have errors set.
13270	 */
13271	if (!STAILQ_EMPTY(&lun->error_list) &&
13272	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13273	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13274		ctl_inject_error(lun, io);
13275
13276	/*
13277	 * XXX KDM how do we treat commands that aren't completed
13278	 * successfully?
13279	 *
13280	 * XXX KDM should we also track I/O latency?
13281	 */
13282	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13283	    io->io_hdr.io_type == CTL_IO_SCSI) {
13284#ifdef CTL_TIME_IO
13285		struct bintime cur_bt;
13286#endif
13287		int type;
13288
13289		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13290		    CTL_FLAG_DATA_IN)
13291			type = CTL_STATS_READ;
13292		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13293		    CTL_FLAG_DATA_OUT)
13294			type = CTL_STATS_WRITE;
13295		else
13296			type = CTL_STATS_NO_IO;
13297
13298		lun->stats.ports[targ_port].bytes[type] +=
13299		    io->scsiio.kern_total_len;
13300		lun->stats.ports[targ_port].operations[type]++;
13301#ifdef CTL_TIME_IO
13302		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13303		   &io->io_hdr.dma_bt);
13304		getbinuptime(&cur_bt);
13305		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13306		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13307#endif
13308		lun->stats.ports[targ_port].num_dmas[type] +=
13309		    io->io_hdr.num_dmas;
13310	}
13311
13312	/*
13313	 * Remove this from the OOA queue.
13314	 */
13315	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13316#ifdef CTL_TIME_IO
13317	if (TAILQ_EMPTY(&lun->ooa_queue))
13318		lun->last_busy = getsbinuptime();
13319#endif
13320
13321	/*
13322	 * Run through the blocked queue on this LUN and see if anything
13323	 * has become unblocked, now that this transaction is done.
13324	 */
13325	ctl_check_blocked(lun);
13326
13327	/*
13328	 * If the LUN has been invalidated, free it if there is nothing
13329	 * left on its OOA queue.
13330	 */
13331	if ((lun->flags & CTL_LUN_INVALID)
13332	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13333		mtx_unlock(&lun->lun_lock);
13334		mtx_lock(&softc->ctl_lock);
13335		ctl_free_lun(lun);
13336		mtx_unlock(&softc->ctl_lock);
13337	} else
13338		mtx_unlock(&lun->lun_lock);
13339
13340bailout:
13341
13342	/*
13343	 * If this command has been aborted, make sure we set the status
13344	 * properly.  The FETD is responsible for freeing the I/O and doing
13345	 * whatever it needs to do to clean up its state.
13346	 */
13347	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13348		ctl_set_task_aborted(&io->scsiio);
13349
13350	/*
13351	 * If enabled, print command error status.
13352	 */
13353	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13354	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13355		ctl_io_error_print(io, NULL);
13356
13357	/*
13358	 * Tell the FETD or the other shelf controller we're done with this
13359	 * command.  Note that only SCSI commands get to this point.  Task
13360	 * management commands are completed above.
13361	 */
13362	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13363	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13364		memset(&msg, 0, sizeof(msg));
13365		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13366		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13367		msg.hdr.nexus = io->io_hdr.nexus;
13368		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13369		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13370		    M_WAITOK);
13371	}
13372
13373	fe_done(io);
13374}
13375
13376#ifdef CTL_WITH_CA
13377/*
13378 * Front end should call this if it doesn't do autosense.  When the request
13379 * sense comes back in from the initiator, we'll dequeue this and send it.
13380 */
13381int
13382ctl_queue_sense(union ctl_io *io)
13383{
13384	struct ctl_lun *lun;
13385	struct ctl_port *port;
13386	struct ctl_softc *softc;
13387	uint32_t initidx, targ_lun;
13388
13389	softc = control_softc;
13390
13391	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13392
13393	/*
13394	 * LUN lookup will likely move to the ctl_work_thread() once we
13395	 * have our new queueing infrastructure (that doesn't put things on
13396	 * a per-LUN queue initially).  That is so that we can handle
13397	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13398	 * can't deal with that right now.
13399	 */
13400	mtx_lock(&softc->ctl_lock);
13401
13402	/*
13403	 * If we don't have a LUN for this, just toss the sense
13404	 * information.
13405	 */
13406	port = ctl_io_port(&ctsio->io_hdr);
13407	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13408	if ((targ_lun < CTL_MAX_LUNS)
13409	 && (softc->ctl_luns[targ_lun] != NULL))
13410		lun = softc->ctl_luns[targ_lun];
13411	else
13412		goto bailout;
13413
13414	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13415
13416	mtx_lock(&lun->lun_lock);
13417	/*
13418	 * Already have CA set for this LUN...toss the sense information.
13419	 */
13420	if (ctl_is_set(lun->have_ca, initidx)) {
13421		mtx_unlock(&lun->lun_lock);
13422		goto bailout;
13423	}
13424
13425	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13426	       MIN(sizeof(lun->pending_sense[initidx]),
13427	       sizeof(io->scsiio.sense_data)));
13428	ctl_set_mask(lun->have_ca, initidx);
13429	mtx_unlock(&lun->lun_lock);
13430
13431bailout:
13432	mtx_unlock(&softc->ctl_lock);
13433
13434	ctl_free_io(io);
13435
13436	return (CTL_RETVAL_COMPLETE);
13437}
13438#endif
13439
13440/*
13441 * Primary command inlet from frontend ports.  All SCSI and task I/O
13442 * requests must go through this function.
13443 */
13444int
13445ctl_queue(union ctl_io *io)
13446{
13447	struct ctl_port *port;
13448
13449	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13450
13451#ifdef CTL_TIME_IO
13452	io->io_hdr.start_time = time_uptime;
13453	getbinuptime(&io->io_hdr.start_bt);
13454#endif /* CTL_TIME_IO */
13455
13456	/* Map FE-specific LUN ID into global one. */
13457	port = ctl_io_port(&io->io_hdr);
13458	io->io_hdr.nexus.targ_mapped_lun =
13459	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13460
13461	switch (io->io_hdr.io_type) {
13462	case CTL_IO_SCSI:
13463	case CTL_IO_TASK:
13464		if (ctl_debug & CTL_DEBUG_CDB)
13465			ctl_io_print(io);
13466		ctl_enqueue_incoming(io);
13467		break;
13468	default:
13469		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13470		return (EINVAL);
13471	}
13472
13473	return (CTL_RETVAL_COMPLETE);
13474}
13475
13476#ifdef CTL_IO_DELAY
13477static void
13478ctl_done_timer_wakeup(void *arg)
13479{
13480	union ctl_io *io;
13481
13482	io = (union ctl_io *)arg;
13483	ctl_done(io);
13484}
13485#endif /* CTL_IO_DELAY */
13486
13487void
13488ctl_serseq_done(union ctl_io *io)
13489{
13490	struct ctl_lun *lun;
13491
13492	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13493	if (lun->be_lun == NULL ||
13494	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13495		return;
13496	mtx_lock(&lun->lun_lock);
13497	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13498	ctl_check_blocked(lun);
13499	mtx_unlock(&lun->lun_lock);
13500}
13501
13502void
13503ctl_done(union ctl_io *io)
13504{
13505
13506	/*
13507	 * Enable this to catch duplicate completion issues.
13508	 */
13509#if 0
13510	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13511		printf("%s: type %d msg %d cdb %x iptl: "
13512		       "%u:%u:%u tag 0x%04x "
13513		       "flag %#x status %x\n",
13514			__func__,
13515			io->io_hdr.io_type,
13516			io->io_hdr.msg_type,
13517			io->scsiio.cdb[0],
13518			io->io_hdr.nexus.initid,
13519			io->io_hdr.nexus.targ_port,
13520			io->io_hdr.nexus.targ_lun,
13521			(io->io_hdr.io_type ==
13522			CTL_IO_TASK) ?
13523			io->taskio.tag_num :
13524			io->scsiio.tag_num,
13525		        io->io_hdr.flags,
13526			io->io_hdr.status);
13527	} else
13528		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13529#endif
13530
13531	/*
13532	 * This is an internal copy of an I/O, and should not go through
13533	 * the normal done processing logic.
13534	 */
13535	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13536		return;
13537
13538#ifdef CTL_IO_DELAY
13539	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13540		struct ctl_lun *lun;
13541
13542		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13543
13544		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13545	} else {
13546		struct ctl_lun *lun;
13547
13548		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13549
13550		if ((lun != NULL)
13551		 && (lun->delay_info.done_delay > 0)) {
13552
13553			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13554			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13555			callout_reset(&io->io_hdr.delay_callout,
13556				      lun->delay_info.done_delay * hz,
13557				      ctl_done_timer_wakeup, io);
13558			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13559				lun->delay_info.done_delay = 0;
13560			return;
13561		}
13562	}
13563#endif /* CTL_IO_DELAY */
13564
13565	ctl_enqueue_done(io);
13566}
13567
13568static void
13569ctl_work_thread(void *arg)
13570{
13571	struct ctl_thread *thr = (struct ctl_thread *)arg;
13572	struct ctl_softc *softc = thr->ctl_softc;
13573	union ctl_io *io;
13574	int retval;
13575
13576	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13577
13578	for (;;) {
13579		/*
13580		 * We handle the queues in this order:
13581		 * - ISC
13582		 * - done queue (to free up resources, unblock other commands)
13583		 * - RtR queue
13584		 * - incoming queue
13585		 *
13586		 * If those queues are empty, we break out of the loop and
13587		 * go to sleep.
13588		 */
13589		mtx_lock(&thr->queue_lock);
13590		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13591		if (io != NULL) {
13592			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13593			mtx_unlock(&thr->queue_lock);
13594			ctl_handle_isc(io);
13595			continue;
13596		}
13597		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13598		if (io != NULL) {
13599			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13600			/* clear any blocked commands, call fe_done */
13601			mtx_unlock(&thr->queue_lock);
13602			ctl_process_done(io);
13603			continue;
13604		}
13605		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13606		if (io != NULL) {
13607			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13608			mtx_unlock(&thr->queue_lock);
13609			if (io->io_hdr.io_type == CTL_IO_TASK)
13610				ctl_run_task(io);
13611			else
13612				ctl_scsiio_precheck(softc, &io->scsiio);
13613			continue;
13614		}
13615		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13616		if (io != NULL) {
13617			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13618			mtx_unlock(&thr->queue_lock);
13619			retval = ctl_scsiio(&io->scsiio);
13620			if (retval != CTL_RETVAL_COMPLETE)
13621				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13622			continue;
13623		}
13624
13625		/* Sleep until we have something to do. */
13626		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13627	}
13628}
13629
13630static void
13631ctl_lun_thread(void *arg)
13632{
13633	struct ctl_softc *softc = (struct ctl_softc *)arg;
13634	struct ctl_be_lun *be_lun;
13635
13636	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13637
13638	for (;;) {
13639		mtx_lock(&softc->ctl_lock);
13640		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13641		if (be_lun != NULL) {
13642			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13643			mtx_unlock(&softc->ctl_lock);
13644			ctl_create_lun(be_lun);
13645			continue;
13646		}
13647
13648		/* Sleep until we have something to do. */
13649		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13650		    PDROP | PRIBIO, "-", 0);
13651	}
13652}
13653
13654static void
13655ctl_thresh_thread(void *arg)
13656{
13657	struct ctl_softc *softc = (struct ctl_softc *)arg;
13658	struct ctl_lun *lun;
13659	struct scsi_da_rw_recovery_page *rwpage;
13660	struct ctl_logical_block_provisioning_page *page;
13661	const char *attr;
13662	union ctl_ha_msg msg;
13663	uint64_t thres, val;
13664	int i, e, set;
13665
13666	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13667
13668	for (;;) {
13669		mtx_lock(&softc->ctl_lock);
13670		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13671			if ((lun->flags & CTL_LUN_DISABLED) ||
13672			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13673			    lun->backend->lun_attr == NULL)
13674				continue;
13675			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13676			    softc->ha_mode == CTL_HA_MODE_XFER)
13677				continue;
13678			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13679			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13680				continue;
13681			e = 0;
13682			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13683			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13684				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13685					continue;
13686				thres = scsi_4btoul(page->descr[i].count);
13687				thres <<= CTL_LBP_EXPONENT;
13688				switch (page->descr[i].resource) {
13689				case 0x01:
13690					attr = "blocksavail";
13691					break;
13692				case 0x02:
13693					attr = "blocksused";
13694					break;
13695				case 0xf1:
13696					attr = "poolblocksavail";
13697					break;
13698				case 0xf2:
13699					attr = "poolblocksused";
13700					break;
13701				default:
13702					continue;
13703				}
13704				mtx_unlock(&softc->ctl_lock); // XXX
13705				val = lun->backend->lun_attr(
13706				    lun->be_lun->be_lun, attr);
13707				mtx_lock(&softc->ctl_lock);
13708				if (val == UINT64_MAX)
13709					continue;
13710				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13711				    == SLBPPD_ARMING_INC)
13712					e = (val >= thres);
13713				else
13714					e = (val <= thres);
13715				if (e)
13716					break;
13717			}
13718			mtx_lock(&lun->lun_lock);
13719			if (e) {
13720				scsi_u64to8b((uint8_t *)&page->descr[i] -
13721				    (uint8_t *)page, lun->ua_tpt_info);
13722				if (lun->lasttpt == 0 ||
13723				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13724					lun->lasttpt = time_uptime;
13725					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13726					set = 1;
13727				} else
13728					set = 0;
13729			} else {
13730				lun->lasttpt = 0;
13731				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13732				set = -1;
13733			}
13734			mtx_unlock(&lun->lun_lock);
13735			if (set != 0 &&
13736			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13737				/* Send msg to other side. */
13738				bzero(&msg.ua, sizeof(msg.ua));
13739				msg.hdr.msg_type = CTL_MSG_UA;
13740				msg.hdr.nexus.initid = -1;
13741				msg.hdr.nexus.targ_port = -1;
13742				msg.hdr.nexus.targ_lun = lun->lun;
13743				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13744				msg.ua.ua_all = 1;
13745				msg.ua.ua_set = (set > 0);
13746				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13747				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13748				mtx_unlock(&softc->ctl_lock); // XXX
13749				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13750				    sizeof(msg.ua), M_WAITOK);
13751				mtx_lock(&softc->ctl_lock);
13752			}
13753		}
13754		mtx_unlock(&softc->ctl_lock);
13755		pause("-", CTL_LBP_PERIOD * hz);
13756	}
13757}
13758
13759static void
13760ctl_enqueue_incoming(union ctl_io *io)
13761{
13762	struct ctl_softc *softc = control_softc;
13763	struct ctl_thread *thr;
13764	u_int idx;
13765
13766	idx = (io->io_hdr.nexus.targ_port * 127 +
13767	       io->io_hdr.nexus.initid) % worker_threads;
13768	thr = &softc->threads[idx];
13769	mtx_lock(&thr->queue_lock);
13770	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13771	mtx_unlock(&thr->queue_lock);
13772	wakeup(thr);
13773}
13774
13775static void
13776ctl_enqueue_rtr(union ctl_io *io)
13777{
13778	struct ctl_softc *softc = control_softc;
13779	struct ctl_thread *thr;
13780
13781	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13782	mtx_lock(&thr->queue_lock);
13783	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13784	mtx_unlock(&thr->queue_lock);
13785	wakeup(thr);
13786}
13787
13788static void
13789ctl_enqueue_done(union ctl_io *io)
13790{
13791	struct ctl_softc *softc = control_softc;
13792	struct ctl_thread *thr;
13793
13794	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13795	mtx_lock(&thr->queue_lock);
13796	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13797	mtx_unlock(&thr->queue_lock);
13798	wakeup(thr);
13799}
13800
13801static void
13802ctl_enqueue_isc(union ctl_io *io)
13803{
13804	struct ctl_softc *softc = control_softc;
13805	struct ctl_thread *thr;
13806
13807	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13808	mtx_lock(&thr->queue_lock);
13809	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13810	mtx_unlock(&thr->queue_lock);
13811	wakeup(thr);
13812}
13813
13814/*
13815 *  vim: ts=8
13816 */
13817