ctl.c revision 288818
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Portions of this software were developed by Edward Tomasz Napierala
8 * under sponsorship from the FreeBSD Foundation.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions, and the following disclaimer,
15 *    without modification.
16 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17 *    substantially similar to the "NO WARRANTY" disclaimer below
18 *    ("Disclaimer") and any redistribution must be conditioned upon
19 *    including a substantially similar Disclaimer requirement for further
20 *    binary redistribution.
21 *
22 * NO WARRANTY
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGES.
34 *
35 * $Id$
36 */
37/*
38 * CAM Target Layer, a SCSI device emulation subsystem.
39 *
40 * Author: Ken Merry <ken@FreeBSD.org>
41 */
42
43#define _CTL_C
44
45#include <sys/cdefs.h>
46__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 288818 2015-10-05 11:46:23Z mav $");
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/ctype.h>
51#include <sys/kernel.h>
52#include <sys/types.h>
53#include <sys/kthread.h>
54#include <sys/bio.h>
55#include <sys/fcntl.h>
56#include <sys/lock.h>
57#include <sys/module.h>
58#include <sys/mutex.h>
59#include <sys/condvar.h>
60#include <sys/malloc.h>
61#include <sys/conf.h>
62#include <sys/ioccom.h>
63#include <sys/queue.h>
64#include <sys/sbuf.h>
65#include <sys/smp.h>
66#include <sys/endian.h>
67#include <sys/sysctl.h>
68#include <vm/uma.h>
69
70#include <cam/cam.h>
71#include <cam/scsi/scsi_all.h>
72#include <cam/scsi/scsi_cd.h>
73#include <cam/scsi/scsi_da.h>
74#include <cam/ctl/ctl_io.h>
75#include <cam/ctl/ctl.h>
76#include <cam/ctl/ctl_frontend.h>
77#include <cam/ctl/ctl_util.h>
78#include <cam/ctl/ctl_backend.h>
79#include <cam/ctl/ctl_ioctl.h>
80#include <cam/ctl/ctl_ha.h>
81#include <cam/ctl/ctl_private.h>
82#include <cam/ctl/ctl_debug.h>
83#include <cam/ctl/ctl_scsi_all.h>
84#include <cam/ctl/ctl_error.h>
85
86struct ctl_softc *control_softc = NULL;
87
88/*
89 * Template mode pages.
90 */
91
92/*
93 * Note that these are default values only.  The actual values will be
94 * filled in when the user does a mode sense.
95 */
96const static struct 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;
405TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407    &worker_threads, 1, "Number of worker threads");
408static int ctl_debug = CTL_DEBUG_NONE;
409TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411    &ctl_debug, 0, "Enabled debug flags");
412
413/*
414 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
415 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
416 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
417 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
418 */
419#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
420
421static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
422				  int param);
423static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
424static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
425static int ctl_init(void);
426void ctl_shutdown(void);
427static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
428static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
429static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
430static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
431			      struct ctl_ooa *ooa_hdr,
432			      struct ctl_ooa_entry *kern_entries);
433static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
434		     struct thread *td);
435static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
436			 struct ctl_be_lun *be_lun);
437static int ctl_free_lun(struct ctl_lun *lun);
438static void ctl_create_lun(struct ctl_be_lun *be_lun);
439static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
440
441static int ctl_do_mode_select(union ctl_io *io);
442static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443			   uint64_t res_key, uint64_t sa_res_key,
444			   uint8_t type, uint32_t residx,
445			   struct ctl_scsiio *ctsio,
446			   struct scsi_per_res_out *cdb,
447			   struct scsi_per_res_out_parms* param);
448static void ctl_pro_preempt_other(struct ctl_lun *lun,
449				  union ctl_ha_msg *msg);
450static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
451static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457					 int alloc_len);
458static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459					 int alloc_len);
460static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466    bool seq);
467static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469    union ctl_io *pending_io, union ctl_io *ooa_io);
470static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471				union ctl_io *starting_io);
472static int ctl_check_blocked(struct ctl_lun *lun);
473static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474				const struct ctl_cmd_entry *entry,
475				struct ctl_scsiio *ctsio);
476static void ctl_failover_lun(union ctl_io *io);
477static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478			       struct ctl_scsiio *ctsio);
479static int ctl_scsiio(struct ctl_scsiio *ctsio);
480
481static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
482static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
483			    ctl_ua_type ua_type);
484static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
485			 ctl_ua_type ua_type);
486static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
487static int ctl_abort_task(union ctl_io *io);
488static int ctl_abort_task_set(union ctl_io *io);
489static int ctl_query_task(union ctl_io *io, int task_set);
490static int ctl_i_t_nexus_reset(union ctl_io *io);
491static int ctl_query_async_event(union ctl_io *io);
492static void ctl_run_task(union ctl_io *io);
493#ifdef CTL_IO_DELAY
494static void ctl_datamove_timer_wakeup(void *arg);
495static void ctl_done_timer_wakeup(void *arg);
496#endif /* CTL_IO_DELAY */
497
498static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501static void ctl_datamove_remote_write(union ctl_io *io);
502static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506				    ctl_ha_dt_cb callback);
507static void ctl_datamove_remote_read(union ctl_io *io);
508static void ctl_datamove_remote(union ctl_io *io);
509static void ctl_process_done(union ctl_io *io);
510static void ctl_lun_thread(void *arg);
511static void ctl_thresh_thread(void *arg);
512static void ctl_work_thread(void *arg);
513static void ctl_enqueue_incoming(union ctl_io *io);
514static void ctl_enqueue_rtr(union ctl_io *io);
515static void ctl_enqueue_done(union ctl_io *io);
516static void ctl_enqueue_isc(union ctl_io *io);
517static const struct ctl_cmd_entry *
518    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519static const struct ctl_cmd_entry *
520    ctl_validate_command(struct ctl_scsiio *ctsio);
521static int ctl_cmd_applicable(uint8_t lun_type,
522    const struct ctl_cmd_entry *entry);
523
524static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
525static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
526static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
527static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
528
529/*
530 * Load the serialization table.  This isn't very pretty, but is probably
531 * the easiest way to do it.
532 */
533#include "ctl_ser_table.c"
534
535/*
536 * We only need to define open, close and ioctl routines for this driver.
537 */
538static struct cdevsw ctl_cdevsw = {
539	.d_version =	D_VERSION,
540	.d_flags =	0,
541	.d_open =	ctl_open,
542	.d_close =	ctl_close,
543	.d_ioctl =	ctl_ioctl,
544	.d_name =	"ctl",
545};
546
547
548MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
549
550static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
551
552static moduledata_t ctl_moduledata = {
553	"ctl",
554	ctl_module_event_handler,
555	NULL
556};
557
558DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
559MODULE_VERSION(ctl, 1);
560
561static struct ctl_frontend ha_frontend =
562{
563	.name = "ha",
564};
565
566static void
567ctl_ha_datamove(union ctl_io *io)
568{
569	struct ctl_lun *lun;
570	struct ctl_sg_entry *sgl;
571	union ctl_ha_msg msg;
572	uint32_t sg_entries_sent;
573	int do_sg_copy, i, j;
574
575	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
576	memset(&msg.dt, 0, sizeof(msg.dt));
577	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
578	msg.hdr.original_sc = io->io_hdr.original_sc;
579	msg.hdr.serializing_sc = io;
580	msg.hdr.nexus = io->io_hdr.nexus;
581	msg.hdr.status = io->io_hdr.status;
582	msg.dt.flags = io->io_hdr.flags;
583
584	/*
585	 * We convert everything into a S/G list here.  We can't
586	 * pass by reference, only by value between controllers.
587	 * So we can't pass a pointer to the S/G list, only as many
588	 * S/G entries as we can fit in here.  If it's possible for
589	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
590	 * then we need to break this up into multiple transfers.
591	 */
592	if (io->scsiio.kern_sg_entries == 0) {
593		msg.dt.kern_sg_entries = 1;
594#if 0
595		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
596			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
597		} else {
598			/* XXX KDM use busdma here! */
599			msg.dt.sg_list[0].addr =
600			    (void *)vtophys(io->scsiio.kern_data_ptr);
601		}
602#else
603		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
604		    ("HA does not support BUS_ADDR"));
605		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
606#endif
607		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
608		do_sg_copy = 0;
609	} else {
610		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
611		do_sg_copy = 1;
612	}
613
614	msg.dt.kern_data_len = io->scsiio.kern_data_len;
615	msg.dt.kern_total_len = io->scsiio.kern_total_len;
616	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
617	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
618	msg.dt.sg_sequence = 0;
619
620	/*
621	 * Loop until we've sent all of the S/G entries.  On the
622	 * other end, we'll recompose these S/G entries into one
623	 * contiguous list before processing.
624	 */
625	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
626	    msg.dt.sg_sequence++) {
627		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
628		    sizeof(msg.dt.sg_list[0])),
629		    msg.dt.kern_sg_entries - sg_entries_sent);
630		if (do_sg_copy != 0) {
631			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
632			for (i = sg_entries_sent, j = 0;
633			     i < msg.dt.cur_sg_entries; i++, j++) {
634#if 0
635				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
636					msg.dt.sg_list[j].addr = sgl[i].addr;
637				} else {
638					/* XXX KDM use busdma here! */
639					msg.dt.sg_list[j].addr =
640					    (void *)vtophys(sgl[i].addr);
641				}
642#else
643				KASSERT((io->io_hdr.flags &
644				    CTL_FLAG_BUS_ADDR) == 0,
645				    ("HA does not support BUS_ADDR"));
646				msg.dt.sg_list[j].addr = sgl[i].addr;
647#endif
648				msg.dt.sg_list[j].len = sgl[i].len;
649			}
650		}
651
652		sg_entries_sent += msg.dt.cur_sg_entries;
653		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
654		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
655		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
656		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
657		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
658			io->io_hdr.port_status = 31341;
659			io->scsiio.be_move_done(io);
660			return;
661		}
662		msg.dt.sent_sg_entries = sg_entries_sent;
663	}
664
665	/*
666	 * Officially handover the request from us to peer.
667	 * If failover has just happened, then we must return error.
668	 * If failover happen just after, then it is not our problem.
669	 */
670	if (lun)
671		mtx_lock(&lun->lun_lock);
672	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
673		if (lun)
674			mtx_unlock(&lun->lun_lock);
675		io->io_hdr.port_status = 31342;
676		io->scsiio.be_move_done(io);
677		return;
678	}
679	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
680	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
681	if (lun)
682		mtx_unlock(&lun->lun_lock);
683}
684
685static void
686ctl_ha_done(union ctl_io *io)
687{
688	union ctl_ha_msg msg;
689
690	if (io->io_hdr.io_type == CTL_IO_SCSI) {
691		memset(&msg, 0, sizeof(msg));
692		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
693		msg.hdr.original_sc = io->io_hdr.original_sc;
694		msg.hdr.nexus = io->io_hdr.nexus;
695		msg.hdr.status = io->io_hdr.status;
696		msg.scsi.scsi_status = io->scsiio.scsi_status;
697		msg.scsi.tag_num = io->scsiio.tag_num;
698		msg.scsi.tag_type = io->scsiio.tag_type;
699		msg.scsi.sense_len = io->scsiio.sense_len;
700		msg.scsi.sense_residual = io->scsiio.sense_residual;
701		msg.scsi.residual = io->scsiio.residual;
702		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
703		    io->scsiio.sense_len);
704		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
705		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
706		    msg.scsi.sense_len, M_WAITOK);
707	}
708	ctl_free_io(io);
709}
710
711static void
712ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
713			    union ctl_ha_msg *msg_info)
714{
715	struct ctl_scsiio *ctsio;
716
717	if (msg_info->hdr.original_sc == NULL) {
718		printf("%s: original_sc == NULL!\n", __func__);
719		/* XXX KDM now what? */
720		return;
721	}
722
723	ctsio = &msg_info->hdr.original_sc->scsiio;
724	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
725	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
726	ctsio->io_hdr.status = msg_info->hdr.status;
727	ctsio->scsi_status = msg_info->scsi.scsi_status;
728	ctsio->sense_len = msg_info->scsi.sense_len;
729	ctsio->sense_residual = msg_info->scsi.sense_residual;
730	ctsio->residual = msg_info->scsi.residual;
731	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
732	       msg_info->scsi.sense_len);
733	ctl_enqueue_isc((union ctl_io *)ctsio);
734}
735
736static void
737ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
738				union ctl_ha_msg *msg_info)
739{
740	struct ctl_scsiio *ctsio;
741
742	if (msg_info->hdr.serializing_sc == NULL) {
743		printf("%s: serializing_sc == NULL!\n", __func__);
744		/* XXX KDM now what? */
745		return;
746	}
747
748	ctsio = &msg_info->hdr.serializing_sc->scsiio;
749	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
750	ctl_enqueue_isc((union ctl_io *)ctsio);
751}
752
753void
754ctl_isc_announce_lun(struct ctl_lun *lun)
755{
756	struct ctl_softc *softc = lun->ctl_softc;
757	union ctl_ha_msg *msg;
758	struct ctl_ha_msg_lun_pr_key pr_key;
759	int i, k;
760
761	if (softc->ha_link != CTL_HA_LINK_ONLINE)
762		return;
763	mtx_lock(&lun->lun_lock);
764	i = sizeof(msg->lun);
765	if (lun->lun_devid)
766		i += lun->lun_devid->len;
767	i += sizeof(pr_key) * lun->pr_key_count;
768alloc:
769	mtx_unlock(&lun->lun_lock);
770	msg = malloc(i, M_CTL, M_WAITOK);
771	mtx_lock(&lun->lun_lock);
772	k = sizeof(msg->lun);
773	if (lun->lun_devid)
774		k += lun->lun_devid->len;
775	k += sizeof(pr_key) * lun->pr_key_count;
776	if (i < k) {
777		free(msg, M_CTL);
778		i = k;
779		goto alloc;
780	}
781	bzero(&msg->lun, sizeof(msg->lun));
782	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
783	msg->hdr.nexus.targ_lun = lun->lun;
784	msg->hdr.nexus.targ_mapped_lun = lun->lun;
785	msg->lun.flags = lun->flags;
786	msg->lun.pr_generation = lun->PRGeneration;
787	msg->lun.pr_res_idx = lun->pr_res_idx;
788	msg->lun.pr_res_type = lun->res_type;
789	msg->lun.pr_key_count = lun->pr_key_count;
790	i = 0;
791	if (lun->lun_devid) {
792		msg->lun.lun_devid_len = lun->lun_devid->len;
793		memcpy(&msg->lun.data[i], lun->lun_devid->data,
794		    msg->lun.lun_devid_len);
795		i += msg->lun.lun_devid_len;
796	}
797	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
798		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
799			continue;
800		pr_key.pr_iid = k;
801		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
802		i += sizeof(pr_key);
803	}
804	mtx_unlock(&lun->lun_lock);
805	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
806	    M_WAITOK);
807	free(msg, M_CTL);
808
809	if (lun->flags & CTL_LUN_PRIMARY_SC) {
810		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
811			ctl_isc_announce_mode(lun, -1,
812			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
813			    lun->mode_pages.index[i].subpage);
814		}
815	}
816}
817
818void
819ctl_isc_announce_port(struct ctl_port *port)
820{
821	struct ctl_softc *softc = port->ctl_softc;
822	union ctl_ha_msg *msg;
823	int i;
824
825	if (port->targ_port < softc->port_min ||
826	    port->targ_port >= softc->port_max ||
827	    softc->ha_link != CTL_HA_LINK_ONLINE)
828		return;
829	i = sizeof(msg->port) + strlen(port->port_name) + 1;
830	if (port->lun_map)
831		i += sizeof(uint32_t) * CTL_MAX_LUNS;
832	if (port->port_devid)
833		i += port->port_devid->len;
834	if (port->target_devid)
835		i += port->target_devid->len;
836	if (port->init_devid)
837		i += port->init_devid->len;
838	msg = malloc(i, M_CTL, M_WAITOK);
839	bzero(&msg->port, sizeof(msg->port));
840	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
841	msg->hdr.nexus.targ_port = port->targ_port;
842	msg->port.port_type = port->port_type;
843	msg->port.physical_port = port->physical_port;
844	msg->port.virtual_port = port->virtual_port;
845	msg->port.status = port->status;
846	i = 0;
847	msg->port.name_len = sprintf(&msg->port.data[i],
848	    "%d:%s", softc->ha_id, port->port_name) + 1;
849	i += msg->port.name_len;
850	if (port->lun_map) {
851		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
852		memcpy(&msg->port.data[i], port->lun_map,
853		    msg->port.lun_map_len);
854		i += msg->port.lun_map_len;
855	}
856	if (port->port_devid) {
857		msg->port.port_devid_len = port->port_devid->len;
858		memcpy(&msg->port.data[i], port->port_devid->data,
859		    msg->port.port_devid_len);
860		i += msg->port.port_devid_len;
861	}
862	if (port->target_devid) {
863		msg->port.target_devid_len = port->target_devid->len;
864		memcpy(&msg->port.data[i], port->target_devid->data,
865		    msg->port.target_devid_len);
866		i += msg->port.target_devid_len;
867	}
868	if (port->init_devid) {
869		msg->port.init_devid_len = port->init_devid->len;
870		memcpy(&msg->port.data[i], port->init_devid->data,
871		    msg->port.init_devid_len);
872		i += msg->port.init_devid_len;
873	}
874	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
875	    M_WAITOK);
876	free(msg, M_CTL);
877}
878
879void
880ctl_isc_announce_iid(struct ctl_port *port, int iid)
881{
882	struct ctl_softc *softc = port->ctl_softc;
883	union ctl_ha_msg *msg;
884	int i, l;
885
886	if (port->targ_port < softc->port_min ||
887	    port->targ_port >= softc->port_max ||
888	    softc->ha_link != CTL_HA_LINK_ONLINE)
889		return;
890	mtx_lock(&softc->ctl_lock);
891	i = sizeof(msg->iid);
892	l = 0;
893	if (port->wwpn_iid[iid].name)
894		l = strlen(port->wwpn_iid[iid].name) + 1;
895	i += l;
896	msg = malloc(i, M_CTL, M_NOWAIT);
897	if (msg == NULL) {
898		mtx_unlock(&softc->ctl_lock);
899		return;
900	}
901	bzero(&msg->iid, sizeof(msg->iid));
902	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
903	msg->hdr.nexus.targ_port = port->targ_port;
904	msg->hdr.nexus.initid = iid;
905	msg->iid.in_use = port->wwpn_iid[iid].in_use;
906	msg->iid.name_len = l;
907	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
908	if (port->wwpn_iid[iid].name)
909		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
910	mtx_unlock(&softc->ctl_lock);
911	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
912	free(msg, M_CTL);
913}
914
915void
916ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
917    uint8_t page, uint8_t subpage)
918{
919	struct ctl_softc *softc = lun->ctl_softc;
920	union ctl_ha_msg msg;
921	int i;
922
923	if (softc->ha_link != CTL_HA_LINK_ONLINE)
924		return;
925	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
926		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
927		    page && lun->mode_pages.index[i].subpage == subpage)
928			break;
929	}
930	if (i == CTL_NUM_MODE_PAGES)
931		return;
932	bzero(&msg.mode, sizeof(msg.mode));
933	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
934	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
935	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
936	msg.hdr.nexus.targ_lun = lun->lun;
937	msg.hdr.nexus.targ_mapped_lun = lun->lun;
938	msg.mode.page_code = page;
939	msg.mode.subpage = subpage;
940	msg.mode.page_len = lun->mode_pages.index[i].page_len;
941	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
942	    msg.mode.page_len);
943	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
944	    M_WAITOK);
945}
946
947static void
948ctl_isc_ha_link_up(struct ctl_softc *softc)
949{
950	struct ctl_port *port;
951	struct ctl_lun *lun;
952	union ctl_ha_msg msg;
953	int i;
954
955	/* Announce this node parameters to peer for validation. */
956	msg.login.msg_type = CTL_MSG_LOGIN;
957	msg.login.version = CTL_HA_VERSION;
958	msg.login.ha_mode = softc->ha_mode;
959	msg.login.ha_id = softc->ha_id;
960	msg.login.max_luns = CTL_MAX_LUNS;
961	msg.login.max_ports = CTL_MAX_PORTS;
962	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
963	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
964	    M_WAITOK);
965
966	STAILQ_FOREACH(port, &softc->port_list, links) {
967		ctl_isc_announce_port(port);
968		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
969			if (port->wwpn_iid[i].in_use)
970				ctl_isc_announce_iid(port, i);
971		}
972	}
973	STAILQ_FOREACH(lun, &softc->lun_list, links)
974		ctl_isc_announce_lun(lun);
975}
976
977static void
978ctl_isc_ha_link_down(struct ctl_softc *softc)
979{
980	struct ctl_port *port;
981	struct ctl_lun *lun;
982	union ctl_io *io;
983	int i;
984
985	mtx_lock(&softc->ctl_lock);
986	STAILQ_FOREACH(lun, &softc->lun_list, links) {
987		mtx_lock(&lun->lun_lock);
988		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
989			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
990			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
991		}
992		mtx_unlock(&lun->lun_lock);
993
994		mtx_unlock(&softc->ctl_lock);
995		io = ctl_alloc_io(softc->othersc_pool);
996		mtx_lock(&softc->ctl_lock);
997		ctl_zero_io(io);
998		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
999		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1000		ctl_enqueue_isc(io);
1001	}
1002
1003	STAILQ_FOREACH(port, &softc->port_list, links) {
1004		if (port->targ_port >= softc->port_min &&
1005		    port->targ_port < softc->port_max)
1006			continue;
1007		port->status &= ~CTL_PORT_STATUS_ONLINE;
1008		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1009			port->wwpn_iid[i].in_use = 0;
1010			free(port->wwpn_iid[i].name, M_CTL);
1011			port->wwpn_iid[i].name = NULL;
1012		}
1013	}
1014	mtx_unlock(&softc->ctl_lock);
1015}
1016
1017static void
1018ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1019{
1020	struct ctl_lun *lun;
1021	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1022
1023	mtx_lock(&softc->ctl_lock);
1024	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1025	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1026		mtx_lock(&lun->lun_lock);
1027		mtx_unlock(&softc->ctl_lock);
1028		if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1029		    msg->ua.ua_set)
1030			memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1031		if (msg->ua.ua_all) {
1032			if (msg->ua.ua_set)
1033				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1034			else
1035				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1036		} else {
1037			if (msg->ua.ua_set)
1038				ctl_est_ua(lun, iid, msg->ua.ua_type);
1039			else
1040				ctl_clr_ua(lun, iid, msg->ua.ua_type);
1041		}
1042		mtx_unlock(&lun->lun_lock);
1043	} else
1044		mtx_unlock(&softc->ctl_lock);
1045}
1046
1047static void
1048ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1049{
1050	struct ctl_lun *lun;
1051	struct ctl_ha_msg_lun_pr_key pr_key;
1052	int i, k;
1053	ctl_lun_flags oflags;
1054	uint32_t targ_lun;
1055
1056	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1057	mtx_lock(&softc->ctl_lock);
1058	if ((targ_lun >= CTL_MAX_LUNS) ||
1059	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1060		mtx_unlock(&softc->ctl_lock);
1061		return;
1062	}
1063	mtx_lock(&lun->lun_lock);
1064	mtx_unlock(&softc->ctl_lock);
1065	if (lun->flags & CTL_LUN_DISABLED) {
1066		mtx_unlock(&lun->lun_lock);
1067		return;
1068	}
1069	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1070	if (msg->lun.lun_devid_len != i || (i > 0 &&
1071	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1072		mtx_unlock(&lun->lun_lock);
1073		printf("%s: Received conflicting HA LUN %d\n",
1074		    __func__, msg->hdr.nexus.targ_lun);
1075		return;
1076	} else {
1077		/* Record whether peer is primary. */
1078		oflags = lun->flags;
1079		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1080		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1081			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1082		else
1083			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1084		if (oflags != lun->flags)
1085			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1086
1087		/* If peer is primary and we are not -- use data */
1088		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1089		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1090			lun->PRGeneration = msg->lun.pr_generation;
1091			lun->pr_res_idx = msg->lun.pr_res_idx;
1092			lun->res_type = msg->lun.pr_res_type;
1093			lun->pr_key_count = msg->lun.pr_key_count;
1094			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1095				ctl_clr_prkey(lun, k);
1096			for (k = 0; k < msg->lun.pr_key_count; k++) {
1097				memcpy(&pr_key, &msg->lun.data[i],
1098				    sizeof(pr_key));
1099				ctl_alloc_prkey(lun, pr_key.pr_iid);
1100				ctl_set_prkey(lun, pr_key.pr_iid,
1101				    pr_key.pr_key);
1102				i += sizeof(pr_key);
1103			}
1104		}
1105
1106		mtx_unlock(&lun->lun_lock);
1107		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1108		    __func__, msg->hdr.nexus.targ_lun,
1109		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1110		    "primary" : "secondary"));
1111
1112		/* If we are primary but peer doesn't know -- notify */
1113		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1114		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1115			ctl_isc_announce_lun(lun);
1116	}
1117}
1118
1119static void
1120ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1121{
1122	struct ctl_port *port;
1123	struct ctl_lun *lun;
1124	int i, new;
1125
1126	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1127	if (port == NULL) {
1128		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1129		    msg->hdr.nexus.targ_port));
1130		new = 1;
1131		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1132		port->frontend = &ha_frontend;
1133		port->targ_port = msg->hdr.nexus.targ_port;
1134		port->fe_datamove = ctl_ha_datamove;
1135		port->fe_done = ctl_ha_done;
1136	} else if (port->frontend == &ha_frontend) {
1137		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1138		    msg->hdr.nexus.targ_port));
1139		new = 0;
1140	} else {
1141		printf("%s: Received conflicting HA port %d\n",
1142		    __func__, msg->hdr.nexus.targ_port);
1143		return;
1144	}
1145	port->port_type = msg->port.port_type;
1146	port->physical_port = msg->port.physical_port;
1147	port->virtual_port = msg->port.virtual_port;
1148	port->status = msg->port.status;
1149	i = 0;
1150	free(port->port_name, M_CTL);
1151	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1152	    M_CTL);
1153	i += msg->port.name_len;
1154	if (msg->port.lun_map_len != 0) {
1155		if (port->lun_map == NULL)
1156			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1157			    M_CTL, M_WAITOK);
1158		memcpy(port->lun_map, &msg->port.data[i],
1159		    sizeof(uint32_t) * CTL_MAX_LUNS);
1160		i += msg->port.lun_map_len;
1161	} else {
1162		free(port->lun_map, M_CTL);
1163		port->lun_map = NULL;
1164	}
1165	if (msg->port.port_devid_len != 0) {
1166		if (port->port_devid == NULL ||
1167		    port->port_devid->len != msg->port.port_devid_len) {
1168			free(port->port_devid, M_CTL);
1169			port->port_devid = malloc(sizeof(struct ctl_devid) +
1170			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1171		}
1172		memcpy(port->port_devid->data, &msg->port.data[i],
1173		    msg->port.port_devid_len);
1174		port->port_devid->len = msg->port.port_devid_len;
1175		i += msg->port.port_devid_len;
1176	} else {
1177		free(port->port_devid, M_CTL);
1178		port->port_devid = NULL;
1179	}
1180	if (msg->port.target_devid_len != 0) {
1181		if (port->target_devid == NULL ||
1182		    port->target_devid->len != msg->port.target_devid_len) {
1183			free(port->target_devid, M_CTL);
1184			port->target_devid = malloc(sizeof(struct ctl_devid) +
1185			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1186		}
1187		memcpy(port->target_devid->data, &msg->port.data[i],
1188		    msg->port.target_devid_len);
1189		port->target_devid->len = msg->port.target_devid_len;
1190		i += msg->port.target_devid_len;
1191	} else {
1192		free(port->target_devid, M_CTL);
1193		port->target_devid = NULL;
1194	}
1195	if (msg->port.init_devid_len != 0) {
1196		if (port->init_devid == NULL ||
1197		    port->init_devid->len != msg->port.init_devid_len) {
1198			free(port->init_devid, M_CTL);
1199			port->init_devid = malloc(sizeof(struct ctl_devid) +
1200			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1201		}
1202		memcpy(port->init_devid->data, &msg->port.data[i],
1203		    msg->port.init_devid_len);
1204		port->init_devid->len = msg->port.init_devid_len;
1205		i += msg->port.init_devid_len;
1206	} else {
1207		free(port->init_devid, M_CTL);
1208		port->init_devid = NULL;
1209	}
1210	if (new) {
1211		if (ctl_port_register(port) != 0) {
1212			printf("%s: ctl_port_register() failed with error\n",
1213			    __func__);
1214		}
1215	}
1216	mtx_lock(&softc->ctl_lock);
1217	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1218		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1219			continue;
1220		mtx_lock(&lun->lun_lock);
1221		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1222		mtx_unlock(&lun->lun_lock);
1223	}
1224	mtx_unlock(&softc->ctl_lock);
1225}
1226
1227static void
1228ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1229{
1230	struct ctl_port *port;
1231	int iid;
1232
1233	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1234	if (port == NULL) {
1235		printf("%s: Received IID for unknown port %d\n",
1236		    __func__, msg->hdr.nexus.targ_port);
1237		return;
1238	}
1239	iid = msg->hdr.nexus.initid;
1240	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1241	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1242	free(port->wwpn_iid[iid].name, M_CTL);
1243	if (msg->iid.name_len) {
1244		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1245		    msg->iid.name_len, M_CTL);
1246	} else
1247		port->wwpn_iid[iid].name = NULL;
1248}
1249
1250static void
1251ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1252{
1253
1254	if (msg->login.version != CTL_HA_VERSION) {
1255		printf("CTL HA peers have different versions %d != %d\n",
1256		    msg->login.version, CTL_HA_VERSION);
1257		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1258		return;
1259	}
1260	if (msg->login.ha_mode != softc->ha_mode) {
1261		printf("CTL HA peers have different ha_mode %d != %d\n",
1262		    msg->login.ha_mode, softc->ha_mode);
1263		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1264		return;
1265	}
1266	if (msg->login.ha_id == softc->ha_id) {
1267		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1268		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1269		return;
1270	}
1271	if (msg->login.max_luns != CTL_MAX_LUNS ||
1272	    msg->login.max_ports != CTL_MAX_PORTS ||
1273	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1274		printf("CTL HA peers have different limits\n");
1275		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1276		return;
1277	}
1278}
1279
1280static void
1281ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1282{
1283	struct ctl_lun *lun;
1284	int i;
1285	uint32_t initidx, targ_lun;
1286
1287	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1288	mtx_lock(&softc->ctl_lock);
1289	if ((targ_lun >= CTL_MAX_LUNS) ||
1290	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1291		mtx_unlock(&softc->ctl_lock);
1292		return;
1293	}
1294	mtx_lock(&lun->lun_lock);
1295	mtx_unlock(&softc->ctl_lock);
1296	if (lun->flags & CTL_LUN_DISABLED) {
1297		mtx_unlock(&lun->lun_lock);
1298		return;
1299	}
1300	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1301		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1302		    msg->mode.page_code &&
1303		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1304			break;
1305	}
1306	if (i == CTL_NUM_MODE_PAGES) {
1307		mtx_unlock(&lun->lun_lock);
1308		return;
1309	}
1310	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1311	    lun->mode_pages.index[i].page_len);
1312	initidx = ctl_get_initindex(&msg->hdr.nexus);
1313	if (initidx != -1)
1314		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1315	mtx_unlock(&lun->lun_lock);
1316}
1317
1318/*
1319 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1320 * subsystem come in here.
1321 */
1322static void
1323ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1324{
1325	struct ctl_softc *softc = control_softc;
1326	union ctl_io *io;
1327	struct ctl_prio *presio;
1328	ctl_ha_status isc_status;
1329
1330	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1331	if (event == CTL_HA_EVT_MSG_RECV) {
1332		union ctl_ha_msg *msg, msgbuf;
1333
1334		if (param > sizeof(msgbuf))
1335			msg = malloc(param, M_CTL, M_WAITOK);
1336		else
1337			msg = &msgbuf;
1338		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1339		    M_WAITOK);
1340		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1341			printf("%s: Error receiving message: %d\n",
1342			    __func__, isc_status);
1343			if (msg != &msgbuf)
1344				free(msg, M_CTL);
1345			return;
1346		}
1347
1348		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1349		switch (msg->hdr.msg_type) {
1350		case CTL_MSG_SERIALIZE:
1351			io = ctl_alloc_io(softc->othersc_pool);
1352			ctl_zero_io(io);
1353			// populate ctsio from msg
1354			io->io_hdr.io_type = CTL_IO_SCSI;
1355			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1356			io->io_hdr.original_sc = msg->hdr.original_sc;
1357			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1358					    CTL_FLAG_IO_ACTIVE;
1359			/*
1360			 * If we're in serialization-only mode, we don't
1361			 * want to go through full done processing.  Thus
1362			 * the COPY flag.
1363			 *
1364			 * XXX KDM add another flag that is more specific.
1365			 */
1366			if (softc->ha_mode != CTL_HA_MODE_XFER)
1367				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1368			io->io_hdr.nexus = msg->hdr.nexus;
1369#if 0
1370			printf("port %u, iid %u, lun %u\n",
1371			       io->io_hdr.nexus.targ_port,
1372			       io->io_hdr.nexus.initid,
1373			       io->io_hdr.nexus.targ_lun);
1374#endif
1375			io->scsiio.tag_num = msg->scsi.tag_num;
1376			io->scsiio.tag_type = msg->scsi.tag_type;
1377#ifdef CTL_TIME_IO
1378			io->io_hdr.start_time = time_uptime;
1379			getbinuptime(&io->io_hdr.start_bt);
1380#endif /* CTL_TIME_IO */
1381			io->scsiio.cdb_len = msg->scsi.cdb_len;
1382			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1383			       CTL_MAX_CDBLEN);
1384			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1385				const struct ctl_cmd_entry *entry;
1386
1387				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1388				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1389				io->io_hdr.flags |=
1390					entry->flags & CTL_FLAG_DATA_MASK;
1391			}
1392			ctl_enqueue_isc(io);
1393			break;
1394
1395		/* Performed on the Originating SC, XFER mode only */
1396		case CTL_MSG_DATAMOVE: {
1397			struct ctl_sg_entry *sgl;
1398			int i, j;
1399
1400			io = msg->hdr.original_sc;
1401			if (io == NULL) {
1402				printf("%s: original_sc == NULL!\n", __func__);
1403				/* XXX KDM do something here */
1404				break;
1405			}
1406			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1407			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1408			/*
1409			 * Keep track of this, we need to send it back over
1410			 * when the datamove is complete.
1411			 */
1412			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1413			if (msg->hdr.status == CTL_SUCCESS)
1414				io->io_hdr.status = msg->hdr.status;
1415
1416			if (msg->dt.sg_sequence == 0) {
1417#ifdef CTL_TIME_IO
1418				getbinuptime(&io->io_hdr.dma_start_bt);
1419#endif
1420				i = msg->dt.kern_sg_entries +
1421				    msg->dt.kern_data_len /
1422				    CTL_HA_DATAMOVE_SEGMENT + 1;
1423				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1424				    M_WAITOK | M_ZERO);
1425				io->io_hdr.remote_sglist = sgl;
1426				io->io_hdr.local_sglist =
1427				    &sgl[msg->dt.kern_sg_entries];
1428
1429				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1430
1431				io->scsiio.kern_sg_entries =
1432					msg->dt.kern_sg_entries;
1433				io->scsiio.rem_sg_entries =
1434					msg->dt.kern_sg_entries;
1435				io->scsiio.kern_data_len =
1436					msg->dt.kern_data_len;
1437				io->scsiio.kern_total_len =
1438					msg->dt.kern_total_len;
1439				io->scsiio.kern_data_resid =
1440					msg->dt.kern_data_resid;
1441				io->scsiio.kern_rel_offset =
1442					msg->dt.kern_rel_offset;
1443				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1444				io->io_hdr.flags |= msg->dt.flags &
1445				    CTL_FLAG_BUS_ADDR;
1446			} else
1447				sgl = (struct ctl_sg_entry *)
1448					io->scsiio.kern_data_ptr;
1449
1450			for (i = msg->dt.sent_sg_entries, j = 0;
1451			     i < (msg->dt.sent_sg_entries +
1452			     msg->dt.cur_sg_entries); i++, j++) {
1453				sgl[i].addr = msg->dt.sg_list[j].addr;
1454				sgl[i].len = msg->dt.sg_list[j].len;
1455
1456#if 0
1457				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1458				    __func__, sgl[i].addr, sgl[i].len, j, i);
1459#endif
1460			}
1461
1462			/*
1463			 * If this is the last piece of the I/O, we've got
1464			 * the full S/G list.  Queue processing in the thread.
1465			 * Otherwise wait for the next piece.
1466			 */
1467			if (msg->dt.sg_last != 0)
1468				ctl_enqueue_isc(io);
1469			break;
1470		}
1471		/* Performed on the Serializing (primary) SC, XFER mode only */
1472		case CTL_MSG_DATAMOVE_DONE: {
1473			if (msg->hdr.serializing_sc == NULL) {
1474				printf("%s: serializing_sc == NULL!\n",
1475				       __func__);
1476				/* XXX KDM now what? */
1477				break;
1478			}
1479			/*
1480			 * We grab the sense information here in case
1481			 * there was a failure, so we can return status
1482			 * back to the initiator.
1483			 */
1484			io = msg->hdr.serializing_sc;
1485			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1486			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1487			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1488			io->io_hdr.port_status = msg->scsi.fetd_status;
1489			io->scsiio.residual = msg->scsi.residual;
1490			if (msg->hdr.status != CTL_STATUS_NONE) {
1491				io->io_hdr.status = msg->hdr.status;
1492				io->scsiio.scsi_status = msg->scsi.scsi_status;
1493				io->scsiio.sense_len = msg->scsi.sense_len;
1494				io->scsiio.sense_residual =msg->scsi.sense_residual;
1495				memcpy(&io->scsiio.sense_data,
1496				    &msg->scsi.sense_data,
1497				    msg->scsi.sense_len);
1498				if (msg->hdr.status == CTL_SUCCESS)
1499					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1500			}
1501			ctl_enqueue_isc(io);
1502			break;
1503		}
1504
1505		/* Preformed on Originating SC, SER_ONLY mode */
1506		case CTL_MSG_R2R:
1507			io = msg->hdr.original_sc;
1508			if (io == NULL) {
1509				printf("%s: original_sc == NULL!\n",
1510				    __func__);
1511				break;
1512			}
1513			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1514			io->io_hdr.msg_type = CTL_MSG_R2R;
1515			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1516			ctl_enqueue_isc(io);
1517			break;
1518
1519		/*
1520		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1521		 * mode.
1522		 * Performed on the Originating (i.e. secondary) SC in XFER
1523		 * mode
1524		 */
1525		case CTL_MSG_FINISH_IO:
1526			if (softc->ha_mode == CTL_HA_MODE_XFER)
1527				ctl_isc_handler_finish_xfer(softc, msg);
1528			else
1529				ctl_isc_handler_finish_ser_only(softc, msg);
1530			break;
1531
1532		/* Preformed on Originating SC */
1533		case CTL_MSG_BAD_JUJU:
1534			io = msg->hdr.original_sc;
1535			if (io == NULL) {
1536				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1537				       __func__);
1538				break;
1539			}
1540			ctl_copy_sense_data(msg, io);
1541			/*
1542			 * IO should have already been cleaned up on other
1543			 * SC so clear this flag so we won't send a message
1544			 * back to finish the IO there.
1545			 */
1546			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1547			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1548
1549			/* io = msg->hdr.serializing_sc; */
1550			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1551			ctl_enqueue_isc(io);
1552			break;
1553
1554		/* Handle resets sent from the other side */
1555		case CTL_MSG_MANAGE_TASKS: {
1556			struct ctl_taskio *taskio;
1557			taskio = (struct ctl_taskio *)ctl_alloc_io(
1558			    softc->othersc_pool);
1559			ctl_zero_io((union ctl_io *)taskio);
1560			taskio->io_hdr.io_type = CTL_IO_TASK;
1561			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1562			taskio->io_hdr.nexus = msg->hdr.nexus;
1563			taskio->task_action = msg->task.task_action;
1564			taskio->tag_num = msg->task.tag_num;
1565			taskio->tag_type = msg->task.tag_type;
1566#ifdef CTL_TIME_IO
1567			taskio->io_hdr.start_time = time_uptime;
1568			getbinuptime(&taskio->io_hdr.start_bt);
1569#endif /* CTL_TIME_IO */
1570			ctl_run_task((union ctl_io *)taskio);
1571			break;
1572		}
1573		/* Persistent Reserve action which needs attention */
1574		case CTL_MSG_PERS_ACTION:
1575			presio = (struct ctl_prio *)ctl_alloc_io(
1576			    softc->othersc_pool);
1577			ctl_zero_io((union ctl_io *)presio);
1578			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1579			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1580			presio->io_hdr.nexus = msg->hdr.nexus;
1581			presio->pr_msg = msg->pr;
1582			ctl_enqueue_isc((union ctl_io *)presio);
1583			break;
1584		case CTL_MSG_UA:
1585			ctl_isc_ua(softc, msg, param);
1586			break;
1587		case CTL_MSG_PORT_SYNC:
1588			ctl_isc_port_sync(softc, msg, param);
1589			break;
1590		case CTL_MSG_LUN_SYNC:
1591			ctl_isc_lun_sync(softc, msg, param);
1592			break;
1593		case CTL_MSG_IID_SYNC:
1594			ctl_isc_iid_sync(softc, msg, param);
1595			break;
1596		case CTL_MSG_LOGIN:
1597			ctl_isc_login(softc, msg, param);
1598			break;
1599		case CTL_MSG_MODE_SYNC:
1600			ctl_isc_mode_sync(softc, msg, param);
1601			break;
1602		default:
1603			printf("Received HA message of unknown type %d\n",
1604			    msg->hdr.msg_type);
1605			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1606			break;
1607		}
1608		if (msg != &msgbuf)
1609			free(msg, M_CTL);
1610	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1611		printf("CTL: HA link status changed from %d to %d\n",
1612		    softc->ha_link, param);
1613		if (param == softc->ha_link)
1614			return;
1615		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1616			softc->ha_link = param;
1617			ctl_isc_ha_link_down(softc);
1618		} else {
1619			softc->ha_link = param;
1620			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1621				ctl_isc_ha_link_up(softc);
1622		}
1623		return;
1624	} else {
1625		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1626		return;
1627	}
1628}
1629
1630static void
1631ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1632{
1633
1634	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1635	    src->scsi.sense_len);
1636	dest->scsiio.scsi_status = src->scsi.scsi_status;
1637	dest->scsiio.sense_len = src->scsi.sense_len;
1638	dest->io_hdr.status = src->hdr.status;
1639}
1640
1641static void
1642ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1643{
1644
1645	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1646	    src->scsiio.sense_len);
1647	dest->scsi.scsi_status = src->scsiio.scsi_status;
1648	dest->scsi.sense_len = src->scsiio.sense_len;
1649	dest->hdr.status = src->io_hdr.status;
1650}
1651
1652void
1653ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1654{
1655	struct ctl_softc *softc = lun->ctl_softc;
1656	ctl_ua_type *pu;
1657
1658	if (initidx < softc->init_min || initidx >= softc->init_max)
1659		return;
1660	mtx_assert(&lun->lun_lock, MA_OWNED);
1661	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1662	if (pu == NULL)
1663		return;
1664	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1665}
1666
1667void
1668ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1669{
1670	int i;
1671
1672	mtx_assert(&lun->lun_lock, MA_OWNED);
1673	if (lun->pending_ua[port] == NULL)
1674		return;
1675	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1676		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1677			continue;
1678		lun->pending_ua[port][i] |= ua;
1679	}
1680}
1681
1682void
1683ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1684{
1685	struct ctl_softc *softc = lun->ctl_softc;
1686	int i;
1687
1688	mtx_assert(&lun->lun_lock, MA_OWNED);
1689	for (i = softc->port_min; i < softc->port_max; i++)
1690		ctl_est_ua_port(lun, i, except, ua);
1691}
1692
1693void
1694ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1695{
1696	struct ctl_softc *softc = lun->ctl_softc;
1697	ctl_ua_type *pu;
1698
1699	if (initidx < softc->init_min || initidx >= softc->init_max)
1700		return;
1701	mtx_assert(&lun->lun_lock, MA_OWNED);
1702	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1703	if (pu == NULL)
1704		return;
1705	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1706}
1707
1708void
1709ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1710{
1711	struct ctl_softc *softc = lun->ctl_softc;
1712	int i, j;
1713
1714	mtx_assert(&lun->lun_lock, MA_OWNED);
1715	for (i = softc->port_min; i < softc->port_max; i++) {
1716		if (lun->pending_ua[i] == NULL)
1717			continue;
1718		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1719			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1720				continue;
1721			lun->pending_ua[i][j] &= ~ua;
1722		}
1723	}
1724}
1725
1726void
1727ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1728    ctl_ua_type ua_type)
1729{
1730	struct ctl_lun *lun;
1731
1732	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1733	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1734		mtx_lock(&lun->lun_lock);
1735		ctl_clr_ua(lun, initidx, ua_type);
1736		mtx_unlock(&lun->lun_lock);
1737	}
1738}
1739
1740static int
1741ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1742{
1743	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1744	struct ctl_lun *lun;
1745	struct ctl_lun_req ireq;
1746	int error, value;
1747
1748	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1749	error = sysctl_handle_int(oidp, &value, 0, req);
1750	if ((error != 0) || (req->newptr == NULL))
1751		return (error);
1752
1753	mtx_lock(&softc->ctl_lock);
1754	if (value == 0)
1755		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1756	else
1757		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1758	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1759		mtx_unlock(&softc->ctl_lock);
1760		bzero(&ireq, sizeof(ireq));
1761		ireq.reqtype = CTL_LUNREQ_MODIFY;
1762		ireq.reqdata.modify.lun_id = lun->lun;
1763		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1764		    curthread);
1765		if (ireq.status != CTL_LUN_OK) {
1766			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1767			    __func__, ireq.status, ireq.error_str);
1768		}
1769		mtx_lock(&softc->ctl_lock);
1770	}
1771	mtx_unlock(&softc->ctl_lock);
1772	return (0);
1773}
1774
1775static int
1776ctl_init(void)
1777{
1778	struct ctl_softc *softc;
1779	void *other_pool;
1780	int i, error;
1781
1782	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1783			       M_WAITOK | M_ZERO);
1784
1785	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1786			      "cam/ctl");
1787	softc->dev->si_drv1 = softc;
1788
1789	sysctl_ctx_init(&softc->sysctl_ctx);
1790	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1791		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1792		CTLFLAG_RD, 0, "CAM Target Layer");
1793
1794	if (softc->sysctl_tree == NULL) {
1795		printf("%s: unable to allocate sysctl tree\n", __func__);
1796		destroy_dev(softc->dev);
1797		free(control_softc, M_DEVBUF);
1798		control_softc = NULL;
1799		return (ENOMEM);
1800	}
1801
1802	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1803	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1804	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1805	softc->flags = 0;
1806
1807	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1808	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1809	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1810
1811	/*
1812	 * In Copan's HA scheme, the "master" and "slave" roles are
1813	 * figured out through the slot the controller is in.  Although it
1814	 * is an active/active system, someone has to be in charge.
1815	 */
1816	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1817	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1818	    "HA head ID (0 - no HA)");
1819	if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1820		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1821		softc->is_single = 1;
1822		softc->port_cnt = CTL_MAX_PORTS;
1823		softc->port_min = 0;
1824	} else {
1825		softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1826		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1827	}
1828	softc->port_max = softc->port_min + softc->port_cnt;
1829	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1830	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1831
1832	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1833	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1834	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1835
1836	STAILQ_INIT(&softc->lun_list);
1837	STAILQ_INIT(&softc->pending_lun_queue);
1838	STAILQ_INIT(&softc->fe_list);
1839	STAILQ_INIT(&softc->port_list);
1840	STAILQ_INIT(&softc->be_list);
1841	ctl_tpc_init(softc);
1842
1843	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1844	                    &other_pool) != 0)
1845	{
1846		printf("ctl: can't allocate %d entry other SC pool, "
1847		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1848		return (ENOMEM);
1849	}
1850	softc->othersc_pool = other_pool;
1851
1852	if (worker_threads <= 0)
1853		worker_threads = max(1, mp_ncpus / 4);
1854	if (worker_threads > CTL_MAX_THREADS)
1855		worker_threads = CTL_MAX_THREADS;
1856
1857	for (i = 0; i < worker_threads; i++) {
1858		struct ctl_thread *thr = &softc->threads[i];
1859
1860		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1861		thr->ctl_softc = softc;
1862		STAILQ_INIT(&thr->incoming_queue);
1863		STAILQ_INIT(&thr->rtr_queue);
1864		STAILQ_INIT(&thr->done_queue);
1865		STAILQ_INIT(&thr->isc_queue);
1866
1867		error = kproc_kthread_add(ctl_work_thread, thr,
1868		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1869		if (error != 0) {
1870			printf("error creating CTL work thread!\n");
1871			ctl_pool_free(other_pool);
1872			return (error);
1873		}
1874	}
1875	error = kproc_kthread_add(ctl_lun_thread, softc,
1876	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1877	if (error != 0) {
1878		printf("error creating CTL lun thread!\n");
1879		ctl_pool_free(other_pool);
1880		return (error);
1881	}
1882	error = kproc_kthread_add(ctl_thresh_thread, softc,
1883	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1884	if (error != 0) {
1885		printf("error creating CTL threshold thread!\n");
1886		ctl_pool_free(other_pool);
1887		return (error);
1888	}
1889
1890	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1891	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1892	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1893
1894	if (softc->is_single == 0) {
1895		ctl_frontend_register(&ha_frontend);
1896		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1897			printf("ctl_init: ctl_ha_msg_init failed.\n");
1898			softc->is_single = 1;
1899		} else
1900		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1901		    != CTL_HA_STATUS_SUCCESS) {
1902			printf("ctl_init: ctl_ha_msg_register failed.\n");
1903			softc->is_single = 1;
1904		}
1905	}
1906	return (0);
1907}
1908
1909void
1910ctl_shutdown(void)
1911{
1912	struct ctl_softc *softc = control_softc;
1913	struct ctl_lun *lun, *next_lun;
1914
1915	if (softc->is_single == 0) {
1916		ctl_ha_msg_shutdown(softc);
1917		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1918		    != CTL_HA_STATUS_SUCCESS)
1919			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1920		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1921			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1922		ctl_frontend_deregister(&ha_frontend);
1923	}
1924
1925	mtx_lock(&softc->ctl_lock);
1926
1927	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1928		ctl_free_lun(lun);
1929
1930	mtx_unlock(&softc->ctl_lock);
1931
1932#if 0
1933	ctl_shutdown_thread(softc->work_thread);
1934	mtx_destroy(&softc->queue_lock);
1935#endif
1936
1937	ctl_tpc_shutdown(softc);
1938	uma_zdestroy(softc->io_zone);
1939	mtx_destroy(&softc->ctl_lock);
1940
1941	destroy_dev(softc->dev);
1942
1943	sysctl_ctx_free(&softc->sysctl_ctx);
1944
1945	free(control_softc, M_DEVBUF);
1946	control_softc = NULL;
1947}
1948
1949static int
1950ctl_module_event_handler(module_t mod, int what, void *arg)
1951{
1952
1953	switch (what) {
1954	case MOD_LOAD:
1955		return (ctl_init());
1956	case MOD_UNLOAD:
1957		return (EBUSY);
1958	default:
1959		return (EOPNOTSUPP);
1960	}
1961}
1962
1963/*
1964 * XXX KDM should we do some access checks here?  Bump a reference count to
1965 * prevent a CTL module from being unloaded while someone has it open?
1966 */
1967static int
1968ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1969{
1970	return (0);
1971}
1972
1973static int
1974ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1975{
1976	return (0);
1977}
1978
1979/*
1980 * Remove an initiator by port number and initiator ID.
1981 * Returns 0 for success, -1 for failure.
1982 */
1983int
1984ctl_remove_initiator(struct ctl_port *port, int iid)
1985{
1986	struct ctl_softc *softc = port->ctl_softc;
1987
1988	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1989
1990	if (iid > CTL_MAX_INIT_PER_PORT) {
1991		printf("%s: initiator ID %u > maximun %u!\n",
1992		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1993		return (-1);
1994	}
1995
1996	mtx_lock(&softc->ctl_lock);
1997	port->wwpn_iid[iid].in_use--;
1998	port->wwpn_iid[iid].last_use = time_uptime;
1999	mtx_unlock(&softc->ctl_lock);
2000	ctl_isc_announce_iid(port, iid);
2001
2002	return (0);
2003}
2004
2005/*
2006 * Add an initiator to the initiator map.
2007 * Returns iid for success, < 0 for failure.
2008 */
2009int
2010ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2011{
2012	struct ctl_softc *softc = port->ctl_softc;
2013	time_t best_time;
2014	int i, best;
2015
2016	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2017
2018	if (iid >= CTL_MAX_INIT_PER_PORT) {
2019		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2020		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2021		free(name, M_CTL);
2022		return (-1);
2023	}
2024
2025	mtx_lock(&softc->ctl_lock);
2026
2027	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2028		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2029			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2030				iid = i;
2031				break;
2032			}
2033			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2034			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2035				iid = i;
2036				break;
2037			}
2038		}
2039	}
2040
2041	if (iid < 0) {
2042		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2043			if (port->wwpn_iid[i].in_use == 0 &&
2044			    port->wwpn_iid[i].wwpn == 0 &&
2045			    port->wwpn_iid[i].name == NULL) {
2046				iid = i;
2047				break;
2048			}
2049		}
2050	}
2051
2052	if (iid < 0) {
2053		best = -1;
2054		best_time = INT32_MAX;
2055		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2056			if (port->wwpn_iid[i].in_use == 0) {
2057				if (port->wwpn_iid[i].last_use < best_time) {
2058					best = i;
2059					best_time = port->wwpn_iid[i].last_use;
2060				}
2061			}
2062		}
2063		iid = best;
2064	}
2065
2066	if (iid < 0) {
2067		mtx_unlock(&softc->ctl_lock);
2068		free(name, M_CTL);
2069		return (-2);
2070	}
2071
2072	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2073		/*
2074		 * This is not an error yet.
2075		 */
2076		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2077#if 0
2078			printf("%s: port %d iid %u WWPN %#jx arrived"
2079			    " again\n", __func__, port->targ_port,
2080			    iid, (uintmax_t)wwpn);
2081#endif
2082			goto take;
2083		}
2084		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2085		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2086#if 0
2087			printf("%s: port %d iid %u name '%s' arrived"
2088			    " again\n", __func__, port->targ_port,
2089			    iid, name);
2090#endif
2091			goto take;
2092		}
2093
2094		/*
2095		 * This is an error, but what do we do about it?  The
2096		 * driver is telling us we have a new WWPN for this
2097		 * initiator ID, so we pretty much need to use it.
2098		 */
2099		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2100		    " but WWPN %#jx '%s' is still at that address\n",
2101		    __func__, port->targ_port, iid, wwpn, name,
2102		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2103		    port->wwpn_iid[iid].name);
2104
2105		/*
2106		 * XXX KDM clear have_ca and ua_pending on each LUN for
2107		 * this initiator.
2108		 */
2109	}
2110take:
2111	free(port->wwpn_iid[iid].name, M_CTL);
2112	port->wwpn_iid[iid].name = name;
2113	port->wwpn_iid[iid].wwpn = wwpn;
2114	port->wwpn_iid[iid].in_use++;
2115	mtx_unlock(&softc->ctl_lock);
2116	ctl_isc_announce_iid(port, iid);
2117
2118	return (iid);
2119}
2120
2121static int
2122ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2123{
2124	int len;
2125
2126	switch (port->port_type) {
2127	case CTL_PORT_FC:
2128	{
2129		struct scsi_transportid_fcp *id =
2130		    (struct scsi_transportid_fcp *)buf;
2131		if (port->wwpn_iid[iid].wwpn == 0)
2132			return (0);
2133		memset(id, 0, sizeof(*id));
2134		id->format_protocol = SCSI_PROTO_FC;
2135		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2136		return (sizeof(*id));
2137	}
2138	case CTL_PORT_ISCSI:
2139	{
2140		struct scsi_transportid_iscsi_port *id =
2141		    (struct scsi_transportid_iscsi_port *)buf;
2142		if (port->wwpn_iid[iid].name == NULL)
2143			return (0);
2144		memset(id, 0, 256);
2145		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2146		    SCSI_PROTO_ISCSI;
2147		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2148		len = roundup2(min(len, 252), 4);
2149		scsi_ulto2b(len, id->additional_length);
2150		return (sizeof(*id) + len);
2151	}
2152	case CTL_PORT_SAS:
2153	{
2154		struct scsi_transportid_sas *id =
2155		    (struct scsi_transportid_sas *)buf;
2156		if (port->wwpn_iid[iid].wwpn == 0)
2157			return (0);
2158		memset(id, 0, sizeof(*id));
2159		id->format_protocol = SCSI_PROTO_SAS;
2160		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2161		return (sizeof(*id));
2162	}
2163	default:
2164	{
2165		struct scsi_transportid_spi *id =
2166		    (struct scsi_transportid_spi *)buf;
2167		memset(id, 0, sizeof(*id));
2168		id->format_protocol = SCSI_PROTO_SPI;
2169		scsi_ulto2b(iid, id->scsi_addr);
2170		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2171		return (sizeof(*id));
2172	}
2173	}
2174}
2175
2176/*
2177 * Serialize a command that went down the "wrong" side, and so was sent to
2178 * this controller for execution.  The logic is a little different than the
2179 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2180 * sent back to the other side, but in the success case, we execute the
2181 * command on this side (XFER mode) or tell the other side to execute it
2182 * (SER_ONLY mode).
2183 */
2184static int
2185ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2186{
2187	struct ctl_softc *softc = control_softc;
2188	union ctl_ha_msg msg_info;
2189	struct ctl_port *port;
2190	struct ctl_lun *lun;
2191	const struct ctl_cmd_entry *entry;
2192	int retval = 0;
2193	uint32_t targ_lun;
2194
2195	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2196	mtx_lock(&softc->ctl_lock);
2197
2198	/* Make sure that we know about this port. */
2199	port = ctl_io_port(&ctsio->io_hdr);
2200	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2201		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2202					 /*retry_count*/ 1);
2203		goto badjuju;
2204	}
2205
2206	/* Make sure that we know about this LUN. */
2207	if ((targ_lun < CTL_MAX_LUNS) &&
2208	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2209		mtx_lock(&lun->lun_lock);
2210		mtx_unlock(&softc->ctl_lock);
2211		/*
2212		 * If the LUN is invalid, pretend that it doesn't exist.
2213		 * It will go away as soon as all pending I/O has been
2214		 * completed.
2215		 */
2216		if (lun->flags & CTL_LUN_DISABLED) {
2217			mtx_unlock(&lun->lun_lock);
2218			lun = NULL;
2219		}
2220	} else {
2221		mtx_unlock(&softc->ctl_lock);
2222		lun = NULL;
2223	}
2224	if (lun == NULL) {
2225		/*
2226		 * The other node would not send this request to us unless
2227		 * received announce that we are primary node for this LUN.
2228		 * If this LUN does not exist now, it is probably result of
2229		 * a race, so respond to initiator in the most opaque way.
2230		 */
2231		ctl_set_busy(ctsio);
2232		goto badjuju;
2233	}
2234
2235	entry = ctl_get_cmd_entry(ctsio, NULL);
2236	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2237		mtx_unlock(&lun->lun_lock);
2238		goto badjuju;
2239	}
2240
2241	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2242	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2243
2244	/*
2245	 * Every I/O goes into the OOA queue for a
2246	 * particular LUN, and stays there until completion.
2247	 */
2248#ifdef CTL_TIME_IO
2249	if (TAILQ_EMPTY(&lun->ooa_queue))
2250		lun->idle_time += getsbinuptime() - lun->last_busy;
2251#endif
2252	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2253
2254	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2255		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2256		 ooa_links))) {
2257	case CTL_ACTION_BLOCK:
2258		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2259		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2260				  blocked_links);
2261		mtx_unlock(&lun->lun_lock);
2262		break;
2263	case CTL_ACTION_PASS:
2264	case CTL_ACTION_SKIP:
2265		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2266			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2267			ctl_enqueue_rtr((union ctl_io *)ctsio);
2268			mtx_unlock(&lun->lun_lock);
2269		} else {
2270			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2271			mtx_unlock(&lun->lun_lock);
2272
2273			/* send msg back to other side */
2274			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2275			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2276			msg_info.hdr.msg_type = CTL_MSG_R2R;
2277			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2278			    sizeof(msg_info.hdr), M_WAITOK);
2279		}
2280		break;
2281	case CTL_ACTION_OVERLAP:
2282		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2283		mtx_unlock(&lun->lun_lock);
2284		ctl_set_overlapped_cmd(ctsio);
2285		goto badjuju;
2286	case CTL_ACTION_OVERLAP_TAG:
2287		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2288		mtx_unlock(&lun->lun_lock);
2289		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2290		goto badjuju;
2291	case CTL_ACTION_ERROR:
2292	default:
2293		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2294		mtx_unlock(&lun->lun_lock);
2295
2296		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2297					 /*retry_count*/ 0);
2298badjuju:
2299		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2300		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2301		msg_info.hdr.serializing_sc = NULL;
2302		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2303		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2304		    sizeof(msg_info.scsi), M_WAITOK);
2305		retval = 1;
2306		break;
2307	}
2308	return (retval);
2309}
2310
2311/*
2312 * Returns 0 for success, errno for failure.
2313 */
2314static void
2315ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2316		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2317{
2318	union ctl_io *io;
2319
2320	mtx_lock(&lun->lun_lock);
2321	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2322	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2323	     ooa_links)) {
2324		struct ctl_ooa_entry *entry;
2325
2326		/*
2327		 * If we've got more than we can fit, just count the
2328		 * remaining entries.
2329		 */
2330		if (*cur_fill_num >= ooa_hdr->alloc_num)
2331			continue;
2332
2333		entry = &kern_entries[*cur_fill_num];
2334
2335		entry->tag_num = io->scsiio.tag_num;
2336		entry->lun_num = lun->lun;
2337#ifdef CTL_TIME_IO
2338		entry->start_bt = io->io_hdr.start_bt;
2339#endif
2340		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2341		entry->cdb_len = io->scsiio.cdb_len;
2342		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2343			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2344
2345		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2346			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2347
2348		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2349			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2350
2351		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2352			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2353
2354		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2355			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2356	}
2357	mtx_unlock(&lun->lun_lock);
2358}
2359
2360static void *
2361ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2362		 size_t error_str_len)
2363{
2364	void *kptr;
2365
2366	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2367
2368	if (copyin(user_addr, kptr, len) != 0) {
2369		snprintf(error_str, error_str_len, "Error copying %d bytes "
2370			 "from user address %p to kernel address %p", len,
2371			 user_addr, kptr);
2372		free(kptr, M_CTL);
2373		return (NULL);
2374	}
2375
2376	return (kptr);
2377}
2378
2379static void
2380ctl_free_args(int num_args, struct ctl_be_arg *args)
2381{
2382	int i;
2383
2384	if (args == NULL)
2385		return;
2386
2387	for (i = 0; i < num_args; i++) {
2388		free(args[i].kname, M_CTL);
2389		free(args[i].kvalue, M_CTL);
2390	}
2391
2392	free(args, M_CTL);
2393}
2394
2395static struct ctl_be_arg *
2396ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2397		char *error_str, size_t error_str_len)
2398{
2399	struct ctl_be_arg *args;
2400	int i;
2401
2402	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2403				error_str, error_str_len);
2404
2405	if (args == NULL)
2406		goto bailout;
2407
2408	for (i = 0; i < num_args; i++) {
2409		args[i].kname = NULL;
2410		args[i].kvalue = NULL;
2411	}
2412
2413	for (i = 0; i < num_args; i++) {
2414		uint8_t *tmpptr;
2415
2416		args[i].kname = ctl_copyin_alloc(args[i].name,
2417			args[i].namelen, error_str, error_str_len);
2418		if (args[i].kname == NULL)
2419			goto bailout;
2420
2421		if (args[i].kname[args[i].namelen - 1] != '\0') {
2422			snprintf(error_str, error_str_len, "Argument %d "
2423				 "name is not NUL-terminated", i);
2424			goto bailout;
2425		}
2426
2427		if (args[i].flags & CTL_BEARG_RD) {
2428			tmpptr = ctl_copyin_alloc(args[i].value,
2429				args[i].vallen, error_str, error_str_len);
2430			if (tmpptr == NULL)
2431				goto bailout;
2432			if ((args[i].flags & CTL_BEARG_ASCII)
2433			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2434				snprintf(error_str, error_str_len, "Argument "
2435				    "%d value is not NUL-terminated", i);
2436				goto bailout;
2437			}
2438			args[i].kvalue = tmpptr;
2439		} else {
2440			args[i].kvalue = malloc(args[i].vallen,
2441			    M_CTL, M_WAITOK | M_ZERO);
2442		}
2443	}
2444
2445	return (args);
2446bailout:
2447
2448	ctl_free_args(num_args, args);
2449
2450	return (NULL);
2451}
2452
2453static void
2454ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2455{
2456	int i;
2457
2458	for (i = 0; i < num_args; i++) {
2459		if (args[i].flags & CTL_BEARG_WR)
2460			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2461	}
2462}
2463
2464/*
2465 * Escape characters that are illegal or not recommended in XML.
2466 */
2467int
2468ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2469{
2470	char *end = str + size;
2471	int retval;
2472
2473	retval = 0;
2474
2475	for (; *str && str < end; str++) {
2476		switch (*str) {
2477		case '&':
2478			retval = sbuf_printf(sb, "&amp;");
2479			break;
2480		case '>':
2481			retval = sbuf_printf(sb, "&gt;");
2482			break;
2483		case '<':
2484			retval = sbuf_printf(sb, "&lt;");
2485			break;
2486		default:
2487			retval = sbuf_putc(sb, *str);
2488			break;
2489		}
2490
2491		if (retval != 0)
2492			break;
2493
2494	}
2495
2496	return (retval);
2497}
2498
2499static void
2500ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2501{
2502	struct scsi_vpd_id_descriptor *desc;
2503	int i;
2504
2505	if (id == NULL || id->len < 4)
2506		return;
2507	desc = (struct scsi_vpd_id_descriptor *)id->data;
2508	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2509	case SVPD_ID_TYPE_T10:
2510		sbuf_printf(sb, "t10.");
2511		break;
2512	case SVPD_ID_TYPE_EUI64:
2513		sbuf_printf(sb, "eui.");
2514		break;
2515	case SVPD_ID_TYPE_NAA:
2516		sbuf_printf(sb, "naa.");
2517		break;
2518	case SVPD_ID_TYPE_SCSI_NAME:
2519		break;
2520	}
2521	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2522	case SVPD_ID_CODESET_BINARY:
2523		for (i = 0; i < desc->length; i++)
2524			sbuf_printf(sb, "%02x", desc->identifier[i]);
2525		break;
2526	case SVPD_ID_CODESET_ASCII:
2527		sbuf_printf(sb, "%.*s", (int)desc->length,
2528		    (char *)desc->identifier);
2529		break;
2530	case SVPD_ID_CODESET_UTF8:
2531		sbuf_printf(sb, "%s", (char *)desc->identifier);
2532		break;
2533	}
2534}
2535
2536static int
2537ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2538	  struct thread *td)
2539{
2540	struct ctl_softc *softc = dev->si_drv1;
2541	struct ctl_lun *lun;
2542	int retval;
2543
2544	retval = 0;
2545
2546	switch (cmd) {
2547	case CTL_IO:
2548		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2549		break;
2550	case CTL_ENABLE_PORT:
2551	case CTL_DISABLE_PORT:
2552	case CTL_SET_PORT_WWNS: {
2553		struct ctl_port *port;
2554		struct ctl_port_entry *entry;
2555
2556		entry = (struct ctl_port_entry *)addr;
2557
2558		mtx_lock(&softc->ctl_lock);
2559		STAILQ_FOREACH(port, &softc->port_list, links) {
2560			int action, done;
2561
2562			if (port->targ_port < softc->port_min ||
2563			    port->targ_port >= softc->port_max)
2564				continue;
2565
2566			action = 0;
2567			done = 0;
2568			if ((entry->port_type == CTL_PORT_NONE)
2569			 && (entry->targ_port == port->targ_port)) {
2570				/*
2571				 * If the user only wants to enable or
2572				 * disable or set WWNs on a specific port,
2573				 * do the operation and we're done.
2574				 */
2575				action = 1;
2576				done = 1;
2577			} else if (entry->port_type & port->port_type) {
2578				/*
2579				 * Compare the user's type mask with the
2580				 * particular frontend type to see if we
2581				 * have a match.
2582				 */
2583				action = 1;
2584				done = 0;
2585
2586				/*
2587				 * Make sure the user isn't trying to set
2588				 * WWNs on multiple ports at the same time.
2589				 */
2590				if (cmd == CTL_SET_PORT_WWNS) {
2591					printf("%s: Can't set WWNs on "
2592					       "multiple ports\n", __func__);
2593					retval = EINVAL;
2594					break;
2595				}
2596			}
2597			if (action == 0)
2598				continue;
2599
2600			/*
2601			 * XXX KDM we have to drop the lock here, because
2602			 * the online/offline operations can potentially
2603			 * block.  We need to reference count the frontends
2604			 * so they can't go away,
2605			 */
2606			if (cmd == CTL_ENABLE_PORT) {
2607				mtx_unlock(&softc->ctl_lock);
2608				ctl_port_online(port);
2609				mtx_lock(&softc->ctl_lock);
2610			} else if (cmd == CTL_DISABLE_PORT) {
2611				mtx_unlock(&softc->ctl_lock);
2612				ctl_port_offline(port);
2613				mtx_lock(&softc->ctl_lock);
2614			} else if (cmd == CTL_SET_PORT_WWNS) {
2615				ctl_port_set_wwns(port,
2616				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2617				    1 : 0, entry->wwnn,
2618				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2619				    1 : 0, entry->wwpn);
2620			}
2621			if (done != 0)
2622				break;
2623		}
2624		mtx_unlock(&softc->ctl_lock);
2625		break;
2626	}
2627	case CTL_GET_OOA: {
2628		struct ctl_ooa *ooa_hdr;
2629		struct ctl_ooa_entry *entries;
2630		uint32_t cur_fill_num;
2631
2632		ooa_hdr = (struct ctl_ooa *)addr;
2633
2634		if ((ooa_hdr->alloc_len == 0)
2635		 || (ooa_hdr->alloc_num == 0)) {
2636			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2637			       "must be non-zero\n", __func__,
2638			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2639			retval = EINVAL;
2640			break;
2641		}
2642
2643		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2644		    sizeof(struct ctl_ooa_entry))) {
2645			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2646			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2647			       __func__, ooa_hdr->alloc_len,
2648			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2649			retval = EINVAL;
2650			break;
2651		}
2652
2653		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2654		if (entries == NULL) {
2655			printf("%s: could not allocate %d bytes for OOA "
2656			       "dump\n", __func__, ooa_hdr->alloc_len);
2657			retval = ENOMEM;
2658			break;
2659		}
2660
2661		mtx_lock(&softc->ctl_lock);
2662		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2663		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2664		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2665			mtx_unlock(&softc->ctl_lock);
2666			free(entries, M_CTL);
2667			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2668			       __func__, (uintmax_t)ooa_hdr->lun_num);
2669			retval = EINVAL;
2670			break;
2671		}
2672
2673		cur_fill_num = 0;
2674
2675		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2676			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2677				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2678				    ooa_hdr, entries);
2679			}
2680		} else {
2681			lun = softc->ctl_luns[ooa_hdr->lun_num];
2682			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2683			    entries);
2684		}
2685		mtx_unlock(&softc->ctl_lock);
2686
2687		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2688		ooa_hdr->fill_len = ooa_hdr->fill_num *
2689			sizeof(struct ctl_ooa_entry);
2690		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2691		if (retval != 0) {
2692			printf("%s: error copying out %d bytes for OOA dump\n",
2693			       __func__, ooa_hdr->fill_len);
2694		}
2695
2696		getbinuptime(&ooa_hdr->cur_bt);
2697
2698		if (cur_fill_num > ooa_hdr->alloc_num) {
2699			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2700			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2701		} else {
2702			ooa_hdr->dropped_num = 0;
2703			ooa_hdr->status = CTL_OOA_OK;
2704		}
2705
2706		free(entries, M_CTL);
2707		break;
2708	}
2709	case CTL_DELAY_IO: {
2710		struct ctl_io_delay_info *delay_info;
2711
2712		delay_info = (struct ctl_io_delay_info *)addr;
2713
2714#ifdef CTL_IO_DELAY
2715		mtx_lock(&softc->ctl_lock);
2716
2717		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2718		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2719			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2720		} else {
2721			lun = softc->ctl_luns[delay_info->lun_id];
2722			mtx_lock(&lun->lun_lock);
2723
2724			delay_info->status = CTL_DELAY_STATUS_OK;
2725
2726			switch (delay_info->delay_type) {
2727			case CTL_DELAY_TYPE_CONT:
2728				break;
2729			case CTL_DELAY_TYPE_ONESHOT:
2730				break;
2731			default:
2732				delay_info->status =
2733					CTL_DELAY_STATUS_INVALID_TYPE;
2734				break;
2735			}
2736
2737			switch (delay_info->delay_loc) {
2738			case CTL_DELAY_LOC_DATAMOVE:
2739				lun->delay_info.datamove_type =
2740					delay_info->delay_type;
2741				lun->delay_info.datamove_delay =
2742					delay_info->delay_secs;
2743				break;
2744			case CTL_DELAY_LOC_DONE:
2745				lun->delay_info.done_type =
2746					delay_info->delay_type;
2747				lun->delay_info.done_delay =
2748					delay_info->delay_secs;
2749				break;
2750			default:
2751				delay_info->status =
2752					CTL_DELAY_STATUS_INVALID_LOC;
2753				break;
2754			}
2755			mtx_unlock(&lun->lun_lock);
2756		}
2757
2758		mtx_unlock(&softc->ctl_lock);
2759#else
2760		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2761#endif /* CTL_IO_DELAY */
2762		break;
2763	}
2764	case CTL_GETSTATS: {
2765		struct ctl_stats *stats;
2766		int i;
2767
2768		stats = (struct ctl_stats *)addr;
2769
2770		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2771		     stats->alloc_len) {
2772			stats->status = CTL_SS_NEED_MORE_SPACE;
2773			stats->num_luns = softc->num_luns;
2774			break;
2775		}
2776		/*
2777		 * XXX KDM no locking here.  If the LUN list changes,
2778		 * things can blow up.
2779		 */
2780		i = 0;
2781		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2782			retval = copyout(&lun->stats, &stats->lun_stats[i++],
2783					 sizeof(lun->stats));
2784			if (retval != 0)
2785				break;
2786		}
2787		stats->num_luns = softc->num_luns;
2788		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2789				 softc->num_luns;
2790		stats->status = CTL_SS_OK;
2791#ifdef CTL_TIME_IO
2792		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2793#else
2794		stats->flags = CTL_STATS_FLAG_NONE;
2795#endif
2796		getnanouptime(&stats->timestamp);
2797		break;
2798	}
2799	case CTL_ERROR_INJECT: {
2800		struct ctl_error_desc *err_desc, *new_err_desc;
2801
2802		err_desc = (struct ctl_error_desc *)addr;
2803
2804		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2805				      M_WAITOK | M_ZERO);
2806		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2807
2808		mtx_lock(&softc->ctl_lock);
2809		lun = softc->ctl_luns[err_desc->lun_id];
2810		if (lun == NULL) {
2811			mtx_unlock(&softc->ctl_lock);
2812			free(new_err_desc, M_CTL);
2813			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2814			       __func__, (uintmax_t)err_desc->lun_id);
2815			retval = EINVAL;
2816			break;
2817		}
2818		mtx_lock(&lun->lun_lock);
2819		mtx_unlock(&softc->ctl_lock);
2820
2821		/*
2822		 * We could do some checking here to verify the validity
2823		 * of the request, but given the complexity of error
2824		 * injection requests, the checking logic would be fairly
2825		 * complex.
2826		 *
2827		 * For now, if the request is invalid, it just won't get
2828		 * executed and might get deleted.
2829		 */
2830		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2831
2832		/*
2833		 * XXX KDM check to make sure the serial number is unique,
2834		 * in case we somehow manage to wrap.  That shouldn't
2835		 * happen for a very long time, but it's the right thing to
2836		 * do.
2837		 */
2838		new_err_desc->serial = lun->error_serial;
2839		err_desc->serial = lun->error_serial;
2840		lun->error_serial++;
2841
2842		mtx_unlock(&lun->lun_lock);
2843		break;
2844	}
2845	case CTL_ERROR_INJECT_DELETE: {
2846		struct ctl_error_desc *delete_desc, *desc, *desc2;
2847		int delete_done;
2848
2849		delete_desc = (struct ctl_error_desc *)addr;
2850		delete_done = 0;
2851
2852		mtx_lock(&softc->ctl_lock);
2853		lun = softc->ctl_luns[delete_desc->lun_id];
2854		if (lun == NULL) {
2855			mtx_unlock(&softc->ctl_lock);
2856			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2857			       __func__, (uintmax_t)delete_desc->lun_id);
2858			retval = EINVAL;
2859			break;
2860		}
2861		mtx_lock(&lun->lun_lock);
2862		mtx_unlock(&softc->ctl_lock);
2863		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2864			if (desc->serial != delete_desc->serial)
2865				continue;
2866
2867			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2868				      links);
2869			free(desc, M_CTL);
2870			delete_done = 1;
2871		}
2872		mtx_unlock(&lun->lun_lock);
2873		if (delete_done == 0) {
2874			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2875			       "error serial %ju on LUN %u\n", __func__,
2876			       delete_desc->serial, delete_desc->lun_id);
2877			retval = EINVAL;
2878			break;
2879		}
2880		break;
2881	}
2882	case CTL_DUMP_STRUCTS: {
2883		int i, j, k;
2884		struct ctl_port *port;
2885		struct ctl_frontend *fe;
2886
2887		mtx_lock(&softc->ctl_lock);
2888		printf("CTL Persistent Reservation information start:\n");
2889		for (i = 0; i < CTL_MAX_LUNS; i++) {
2890			lun = softc->ctl_luns[i];
2891
2892			if ((lun == NULL)
2893			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2894				continue;
2895
2896			for (j = 0; j < CTL_MAX_PORTS; j++) {
2897				if (lun->pr_keys[j] == NULL)
2898					continue;
2899				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2900					if (lun->pr_keys[j][k] == 0)
2901						continue;
2902					printf("  LUN %d port %d iid %d key "
2903					       "%#jx\n", i, j, k,
2904					       (uintmax_t)lun->pr_keys[j][k]);
2905				}
2906			}
2907		}
2908		printf("CTL Persistent Reservation information end\n");
2909		printf("CTL Ports:\n");
2910		STAILQ_FOREACH(port, &softc->port_list, links) {
2911			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2912			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2913			       port->frontend->name, port->port_type,
2914			       port->physical_port, port->virtual_port,
2915			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2916			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2917				if (port->wwpn_iid[j].in_use == 0 &&
2918				    port->wwpn_iid[j].wwpn == 0 &&
2919				    port->wwpn_iid[j].name == NULL)
2920					continue;
2921
2922				printf("    iid %u use %d WWPN %#jx '%s'\n",
2923				    j, port->wwpn_iid[j].in_use,
2924				    (uintmax_t)port->wwpn_iid[j].wwpn,
2925				    port->wwpn_iid[j].name);
2926			}
2927		}
2928		printf("CTL Port information end\n");
2929		mtx_unlock(&softc->ctl_lock);
2930		/*
2931		 * XXX KDM calling this without a lock.  We'd likely want
2932		 * to drop the lock before calling the frontend's dump
2933		 * routine anyway.
2934		 */
2935		printf("CTL Frontends:\n");
2936		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2937			printf("  Frontend '%s'\n", fe->name);
2938			if (fe->fe_dump != NULL)
2939				fe->fe_dump();
2940		}
2941		printf("CTL Frontend information end\n");
2942		break;
2943	}
2944	case CTL_LUN_REQ: {
2945		struct ctl_lun_req *lun_req;
2946		struct ctl_backend_driver *backend;
2947
2948		lun_req = (struct ctl_lun_req *)addr;
2949
2950		backend = ctl_backend_find(lun_req->backend);
2951		if (backend == NULL) {
2952			lun_req->status = CTL_LUN_ERROR;
2953			snprintf(lun_req->error_str,
2954				 sizeof(lun_req->error_str),
2955				 "Backend \"%s\" not found.",
2956				 lun_req->backend);
2957			break;
2958		}
2959		if (lun_req->num_be_args > 0) {
2960			lun_req->kern_be_args = ctl_copyin_args(
2961				lun_req->num_be_args,
2962				lun_req->be_args,
2963				lun_req->error_str,
2964				sizeof(lun_req->error_str));
2965			if (lun_req->kern_be_args == NULL) {
2966				lun_req->status = CTL_LUN_ERROR;
2967				break;
2968			}
2969		}
2970
2971		retval = backend->ioctl(dev, cmd, addr, flag, td);
2972
2973		if (lun_req->num_be_args > 0) {
2974			ctl_copyout_args(lun_req->num_be_args,
2975				      lun_req->kern_be_args);
2976			ctl_free_args(lun_req->num_be_args,
2977				      lun_req->kern_be_args);
2978		}
2979		break;
2980	}
2981	case CTL_LUN_LIST: {
2982		struct sbuf *sb;
2983		struct ctl_lun_list *list;
2984		struct ctl_option *opt;
2985
2986		list = (struct ctl_lun_list *)addr;
2987
2988		/*
2989		 * Allocate a fixed length sbuf here, based on the length
2990		 * of the user's buffer.  We could allocate an auto-extending
2991		 * buffer, and then tell the user how much larger our
2992		 * amount of data is than his buffer, but that presents
2993		 * some problems:
2994		 *
2995		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2996		 *     we can't hold a lock while calling them with an
2997		 *     auto-extending buffer.
2998 		 *
2999		 * 2.  There is not currently a LUN reference counting
3000		 *     mechanism, outside of outstanding transactions on
3001		 *     the LUN's OOA queue.  So a LUN could go away on us
3002		 *     while we're getting the LUN number, backend-specific
3003		 *     information, etc.  Thus, given the way things
3004		 *     currently work, we need to hold the CTL lock while
3005		 *     grabbing LUN information.
3006		 *
3007		 * So, from the user's standpoint, the best thing to do is
3008		 * allocate what he thinks is a reasonable buffer length,
3009		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3010		 * double the buffer length and try again.  (And repeat
3011		 * that until he succeeds.)
3012		 */
3013		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3014		if (sb == NULL) {
3015			list->status = CTL_LUN_LIST_ERROR;
3016			snprintf(list->error_str, sizeof(list->error_str),
3017				 "Unable to allocate %d bytes for LUN list",
3018				 list->alloc_len);
3019			break;
3020		}
3021
3022		sbuf_printf(sb, "<ctllunlist>\n");
3023
3024		mtx_lock(&softc->ctl_lock);
3025		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3026			mtx_lock(&lun->lun_lock);
3027			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3028					     (uintmax_t)lun->lun);
3029
3030			/*
3031			 * Bail out as soon as we see that we've overfilled
3032			 * the buffer.
3033			 */
3034			if (retval != 0)
3035				break;
3036
3037			retval = sbuf_printf(sb, "\t<backend_type>%s"
3038					     "</backend_type>\n",
3039					     (lun->backend == NULL) ?  "none" :
3040					     lun->backend->name);
3041
3042			if (retval != 0)
3043				break;
3044
3045			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3046					     lun->be_lun->lun_type);
3047
3048			if (retval != 0)
3049				break;
3050
3051			if (lun->backend == NULL) {
3052				retval = sbuf_printf(sb, "</lun>\n");
3053				if (retval != 0)
3054					break;
3055				continue;
3056			}
3057
3058			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3059					     (lun->be_lun->maxlba > 0) ?
3060					     lun->be_lun->maxlba + 1 : 0);
3061
3062			if (retval != 0)
3063				break;
3064
3065			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3066					     lun->be_lun->blocksize);
3067
3068			if (retval != 0)
3069				break;
3070
3071			retval = sbuf_printf(sb, "\t<serial_number>");
3072
3073			if (retval != 0)
3074				break;
3075
3076			retval = ctl_sbuf_printf_esc(sb,
3077			    lun->be_lun->serial_num,
3078			    sizeof(lun->be_lun->serial_num));
3079
3080			if (retval != 0)
3081				break;
3082
3083			retval = sbuf_printf(sb, "</serial_number>\n");
3084
3085			if (retval != 0)
3086				break;
3087
3088			retval = sbuf_printf(sb, "\t<device_id>");
3089
3090			if (retval != 0)
3091				break;
3092
3093			retval = ctl_sbuf_printf_esc(sb,
3094			    lun->be_lun->device_id,
3095			    sizeof(lun->be_lun->device_id));
3096
3097			if (retval != 0)
3098				break;
3099
3100			retval = sbuf_printf(sb, "</device_id>\n");
3101
3102			if (retval != 0)
3103				break;
3104
3105			if (lun->backend->lun_info != NULL) {
3106				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3107				if (retval != 0)
3108					break;
3109			}
3110			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3111				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3112				    opt->name, opt->value, opt->name);
3113				if (retval != 0)
3114					break;
3115			}
3116
3117			retval = sbuf_printf(sb, "</lun>\n");
3118
3119			if (retval != 0)
3120				break;
3121			mtx_unlock(&lun->lun_lock);
3122		}
3123		if (lun != NULL)
3124			mtx_unlock(&lun->lun_lock);
3125		mtx_unlock(&softc->ctl_lock);
3126
3127		if ((retval != 0)
3128		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3129			retval = 0;
3130			sbuf_delete(sb);
3131			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3132			snprintf(list->error_str, sizeof(list->error_str),
3133				 "Out of space, %d bytes is too small",
3134				 list->alloc_len);
3135			break;
3136		}
3137
3138		sbuf_finish(sb);
3139
3140		retval = copyout(sbuf_data(sb), list->lun_xml,
3141				 sbuf_len(sb) + 1);
3142
3143		list->fill_len = sbuf_len(sb) + 1;
3144		list->status = CTL_LUN_LIST_OK;
3145		sbuf_delete(sb);
3146		break;
3147	}
3148	case CTL_ISCSI: {
3149		struct ctl_iscsi *ci;
3150		struct ctl_frontend *fe;
3151
3152		ci = (struct ctl_iscsi *)addr;
3153
3154		fe = ctl_frontend_find("iscsi");
3155		if (fe == NULL) {
3156			ci->status = CTL_ISCSI_ERROR;
3157			snprintf(ci->error_str, sizeof(ci->error_str),
3158			    "Frontend \"iscsi\" not found.");
3159			break;
3160		}
3161
3162		retval = fe->ioctl(dev, cmd, addr, flag, td);
3163		break;
3164	}
3165	case CTL_PORT_REQ: {
3166		struct ctl_req *req;
3167		struct ctl_frontend *fe;
3168
3169		req = (struct ctl_req *)addr;
3170
3171		fe = ctl_frontend_find(req->driver);
3172		if (fe == NULL) {
3173			req->status = CTL_LUN_ERROR;
3174			snprintf(req->error_str, sizeof(req->error_str),
3175			    "Frontend \"%s\" not found.", req->driver);
3176			break;
3177		}
3178		if (req->num_args > 0) {
3179			req->kern_args = ctl_copyin_args(req->num_args,
3180			    req->args, req->error_str, sizeof(req->error_str));
3181			if (req->kern_args == NULL) {
3182				req->status = CTL_LUN_ERROR;
3183				break;
3184			}
3185		}
3186
3187		if (fe->ioctl)
3188			retval = fe->ioctl(dev, cmd, addr, flag, td);
3189		else
3190			retval = ENODEV;
3191
3192		if (req->num_args > 0) {
3193			ctl_copyout_args(req->num_args, req->kern_args);
3194			ctl_free_args(req->num_args, req->kern_args);
3195		}
3196		break;
3197	}
3198	case CTL_PORT_LIST: {
3199		struct sbuf *sb;
3200		struct ctl_port *port;
3201		struct ctl_lun_list *list;
3202		struct ctl_option *opt;
3203		int j;
3204		uint32_t plun;
3205
3206		list = (struct ctl_lun_list *)addr;
3207
3208		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3209		if (sb == NULL) {
3210			list->status = CTL_LUN_LIST_ERROR;
3211			snprintf(list->error_str, sizeof(list->error_str),
3212				 "Unable to allocate %d bytes for LUN list",
3213				 list->alloc_len);
3214			break;
3215		}
3216
3217		sbuf_printf(sb, "<ctlportlist>\n");
3218
3219		mtx_lock(&softc->ctl_lock);
3220		STAILQ_FOREACH(port, &softc->port_list, links) {
3221			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3222					     (uintmax_t)port->targ_port);
3223
3224			/*
3225			 * Bail out as soon as we see that we've overfilled
3226			 * the buffer.
3227			 */
3228			if (retval != 0)
3229				break;
3230
3231			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3232			    "</frontend_type>\n", port->frontend->name);
3233			if (retval != 0)
3234				break;
3235
3236			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3237					     port->port_type);
3238			if (retval != 0)
3239				break;
3240
3241			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3242			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3243			if (retval != 0)
3244				break;
3245
3246			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3247			    port->port_name);
3248			if (retval != 0)
3249				break;
3250
3251			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3252			    port->physical_port);
3253			if (retval != 0)
3254				break;
3255
3256			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3257			    port->virtual_port);
3258			if (retval != 0)
3259				break;
3260
3261			if (port->target_devid != NULL) {
3262				sbuf_printf(sb, "\t<target>");
3263				ctl_id_sbuf(port->target_devid, sb);
3264				sbuf_printf(sb, "</target>\n");
3265			}
3266
3267			if (port->port_devid != NULL) {
3268				sbuf_printf(sb, "\t<port>");
3269				ctl_id_sbuf(port->port_devid, sb);
3270				sbuf_printf(sb, "</port>\n");
3271			}
3272
3273			if (port->port_info != NULL) {
3274				retval = port->port_info(port->onoff_arg, sb);
3275				if (retval != 0)
3276					break;
3277			}
3278			STAILQ_FOREACH(opt, &port->options, links) {
3279				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3280				    opt->name, opt->value, opt->name);
3281				if (retval != 0)
3282					break;
3283			}
3284
3285			if (port->lun_map != NULL) {
3286				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3287				for (j = 0; j < CTL_MAX_LUNS; j++) {
3288					plun = ctl_lun_map_from_port(port, j);
3289					if (plun >= CTL_MAX_LUNS)
3290						continue;
3291					sbuf_printf(sb,
3292					    "\t<lun id=\"%u\">%u</lun>\n",
3293					    j, plun);
3294				}
3295			}
3296
3297			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3298				if (port->wwpn_iid[j].in_use == 0 ||
3299				    (port->wwpn_iid[j].wwpn == 0 &&
3300				     port->wwpn_iid[j].name == NULL))
3301					continue;
3302
3303				if (port->wwpn_iid[j].name != NULL)
3304					retval = sbuf_printf(sb,
3305					    "\t<initiator id=\"%u\">%s</initiator>\n",
3306					    j, port->wwpn_iid[j].name);
3307				else
3308					retval = sbuf_printf(sb,
3309					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3310					    j, port->wwpn_iid[j].wwpn);
3311				if (retval != 0)
3312					break;
3313			}
3314			if (retval != 0)
3315				break;
3316
3317			retval = sbuf_printf(sb, "</targ_port>\n");
3318			if (retval != 0)
3319				break;
3320		}
3321		mtx_unlock(&softc->ctl_lock);
3322
3323		if ((retval != 0)
3324		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3325			retval = 0;
3326			sbuf_delete(sb);
3327			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3328			snprintf(list->error_str, sizeof(list->error_str),
3329				 "Out of space, %d bytes is too small",
3330				 list->alloc_len);
3331			break;
3332		}
3333
3334		sbuf_finish(sb);
3335
3336		retval = copyout(sbuf_data(sb), list->lun_xml,
3337				 sbuf_len(sb) + 1);
3338
3339		list->fill_len = sbuf_len(sb) + 1;
3340		list->status = CTL_LUN_LIST_OK;
3341		sbuf_delete(sb);
3342		break;
3343	}
3344	case CTL_LUN_MAP: {
3345		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3346		struct ctl_port *port;
3347
3348		mtx_lock(&softc->ctl_lock);
3349		if (lm->port < softc->port_min ||
3350		    lm->port >= softc->port_max ||
3351		    (port = softc->ctl_ports[lm->port]) == NULL) {
3352			mtx_unlock(&softc->ctl_lock);
3353			return (ENXIO);
3354		}
3355		if (port->status & CTL_PORT_STATUS_ONLINE) {
3356			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3357				if (ctl_lun_map_to_port(port, lun->lun) >=
3358				    CTL_MAX_LUNS)
3359					continue;
3360				mtx_lock(&lun->lun_lock);
3361				ctl_est_ua_port(lun, lm->port, -1,
3362				    CTL_UA_LUN_CHANGE);
3363				mtx_unlock(&lun->lun_lock);
3364			}
3365		}
3366		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3367		if (lm->plun < CTL_MAX_LUNS) {
3368			if (lm->lun == UINT32_MAX)
3369				retval = ctl_lun_map_unset(port, lm->plun);
3370			else if (lm->lun < CTL_MAX_LUNS &&
3371			    softc->ctl_luns[lm->lun] != NULL)
3372				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3373			else
3374				return (ENXIO);
3375		} else if (lm->plun == UINT32_MAX) {
3376			if (lm->lun == UINT32_MAX)
3377				retval = ctl_lun_map_deinit(port);
3378			else
3379				retval = ctl_lun_map_init(port);
3380		} else
3381			return (ENXIO);
3382		if (port->status & CTL_PORT_STATUS_ONLINE)
3383			ctl_isc_announce_port(port);
3384		break;
3385	}
3386	default: {
3387		/* XXX KDM should we fix this? */
3388#if 0
3389		struct ctl_backend_driver *backend;
3390		unsigned int type;
3391		int found;
3392
3393		found = 0;
3394
3395		/*
3396		 * We encode the backend type as the ioctl type for backend
3397		 * ioctls.  So parse it out here, and then search for a
3398		 * backend of this type.
3399		 */
3400		type = _IOC_TYPE(cmd);
3401
3402		STAILQ_FOREACH(backend, &softc->be_list, links) {
3403			if (backend->type == type) {
3404				found = 1;
3405				break;
3406			}
3407		}
3408		if (found == 0) {
3409			printf("ctl: unknown ioctl command %#lx or backend "
3410			       "%d\n", cmd, type);
3411			retval = EINVAL;
3412			break;
3413		}
3414		retval = backend->ioctl(dev, cmd, addr, flag, td);
3415#endif
3416		retval = ENOTTY;
3417		break;
3418	}
3419	}
3420	return (retval);
3421}
3422
3423uint32_t
3424ctl_get_initindex(struct ctl_nexus *nexus)
3425{
3426	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3427}
3428
3429int
3430ctl_lun_map_init(struct ctl_port *port)
3431{
3432	struct ctl_softc *softc = port->ctl_softc;
3433	struct ctl_lun *lun;
3434	uint32_t i;
3435
3436	if (port->lun_map == NULL)
3437		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3438		    M_CTL, M_NOWAIT);
3439	if (port->lun_map == NULL)
3440		return (ENOMEM);
3441	for (i = 0; i < CTL_MAX_LUNS; i++)
3442		port->lun_map[i] = UINT32_MAX;
3443	if (port->status & CTL_PORT_STATUS_ONLINE) {
3444		if (port->lun_disable != NULL) {
3445			STAILQ_FOREACH(lun, &softc->lun_list, links)
3446				port->lun_disable(port->targ_lun_arg, lun->lun);
3447		}
3448		ctl_isc_announce_port(port);
3449	}
3450	return (0);
3451}
3452
3453int
3454ctl_lun_map_deinit(struct ctl_port *port)
3455{
3456	struct ctl_softc *softc = port->ctl_softc;
3457	struct ctl_lun *lun;
3458
3459	if (port->lun_map == NULL)
3460		return (0);
3461	free(port->lun_map, M_CTL);
3462	port->lun_map = NULL;
3463	if (port->status & CTL_PORT_STATUS_ONLINE) {
3464		if (port->lun_enable != NULL) {
3465			STAILQ_FOREACH(lun, &softc->lun_list, links)
3466				port->lun_enable(port->targ_lun_arg, lun->lun);
3467		}
3468		ctl_isc_announce_port(port);
3469	}
3470	return (0);
3471}
3472
3473int
3474ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3475{
3476	int status;
3477	uint32_t old;
3478
3479	if (port->lun_map == NULL) {
3480		status = ctl_lun_map_init(port);
3481		if (status != 0)
3482			return (status);
3483	}
3484	old = port->lun_map[plun];
3485	port->lun_map[plun] = glun;
3486	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3487		if (port->lun_enable != NULL)
3488			port->lun_enable(port->targ_lun_arg, plun);
3489		ctl_isc_announce_port(port);
3490	}
3491	return (0);
3492}
3493
3494int
3495ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3496{
3497	uint32_t old;
3498
3499	if (port->lun_map == NULL)
3500		return (0);
3501	old = port->lun_map[plun];
3502	port->lun_map[plun] = UINT32_MAX;
3503	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3504		if (port->lun_disable != NULL)
3505			port->lun_disable(port->targ_lun_arg, plun);
3506		ctl_isc_announce_port(port);
3507	}
3508	return (0);
3509}
3510
3511uint32_t
3512ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3513{
3514
3515	if (port == NULL)
3516		return (UINT32_MAX);
3517	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3518		return (lun_id);
3519	return (port->lun_map[lun_id]);
3520}
3521
3522uint32_t
3523ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3524{
3525	uint32_t i;
3526
3527	if (port == NULL)
3528		return (UINT32_MAX);
3529	if (port->lun_map == NULL)
3530		return (lun_id);
3531	for (i = 0; i < CTL_MAX_LUNS; i++) {
3532		if (port->lun_map[i] == lun_id)
3533			return (i);
3534	}
3535	return (UINT32_MAX);
3536}
3537
3538static struct ctl_port *
3539ctl_io_port(struct ctl_io_hdr *io_hdr)
3540{
3541
3542	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3543}
3544
3545int
3546ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3547{
3548	int i;
3549
3550	for (i = first; i < last; i++) {
3551		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3552			return (i);
3553	}
3554	return (-1);
3555}
3556
3557int
3558ctl_set_mask(uint32_t *mask, uint32_t bit)
3559{
3560	uint32_t chunk, piece;
3561
3562	chunk = bit >> 5;
3563	piece = bit % (sizeof(uint32_t) * 8);
3564
3565	if ((mask[chunk] & (1 << piece)) != 0)
3566		return (-1);
3567	else
3568		mask[chunk] |= (1 << piece);
3569
3570	return (0);
3571}
3572
3573int
3574ctl_clear_mask(uint32_t *mask, uint32_t bit)
3575{
3576	uint32_t chunk, piece;
3577
3578	chunk = bit >> 5;
3579	piece = bit % (sizeof(uint32_t) * 8);
3580
3581	if ((mask[chunk] & (1 << piece)) == 0)
3582		return (-1);
3583	else
3584		mask[chunk] &= ~(1 << piece);
3585
3586	return (0);
3587}
3588
3589int
3590ctl_is_set(uint32_t *mask, uint32_t bit)
3591{
3592	uint32_t chunk, piece;
3593
3594	chunk = bit >> 5;
3595	piece = bit % (sizeof(uint32_t) * 8);
3596
3597	if ((mask[chunk] & (1 << piece)) == 0)
3598		return (0);
3599	else
3600		return (1);
3601}
3602
3603static uint64_t
3604ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3605{
3606	uint64_t *t;
3607
3608	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3609	if (t == NULL)
3610		return (0);
3611	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3612}
3613
3614static void
3615ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3616{
3617	uint64_t *t;
3618
3619	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3620	if (t == NULL)
3621		return;
3622	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3623}
3624
3625static void
3626ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3627{
3628	uint64_t *p;
3629	u_int i;
3630
3631	i = residx/CTL_MAX_INIT_PER_PORT;
3632	if (lun->pr_keys[i] != NULL)
3633		return;
3634	mtx_unlock(&lun->lun_lock);
3635	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3636	    M_WAITOK | M_ZERO);
3637	mtx_lock(&lun->lun_lock);
3638	if (lun->pr_keys[i] == NULL)
3639		lun->pr_keys[i] = p;
3640	else
3641		free(p, M_CTL);
3642}
3643
3644static void
3645ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3646{
3647	uint64_t *t;
3648
3649	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3650	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3651	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3652}
3653
3654/*
3655 * ctl_softc, pool_name, total_ctl_io are passed in.
3656 * npool is passed out.
3657 */
3658int
3659ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3660		uint32_t total_ctl_io, void **npool)
3661{
3662#ifdef IO_POOLS
3663	struct ctl_io_pool *pool;
3664
3665	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3666					    M_NOWAIT | M_ZERO);
3667	if (pool == NULL)
3668		return (ENOMEM);
3669
3670	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3671	pool->ctl_softc = ctl_softc;
3672	pool->zone = uma_zsecond_create(pool->name, NULL,
3673	    NULL, NULL, NULL, ctl_softc->io_zone);
3674	/* uma_prealloc(pool->zone, total_ctl_io); */
3675
3676	*npool = pool;
3677#else
3678	*npool = ctl_softc->io_zone;
3679#endif
3680	return (0);
3681}
3682
3683void
3684ctl_pool_free(struct ctl_io_pool *pool)
3685{
3686
3687	if (pool == NULL)
3688		return;
3689
3690#ifdef IO_POOLS
3691	uma_zdestroy(pool->zone);
3692	free(pool, M_CTL);
3693#endif
3694}
3695
3696union ctl_io *
3697ctl_alloc_io(void *pool_ref)
3698{
3699	union ctl_io *io;
3700#ifdef IO_POOLS
3701	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3702
3703	io = uma_zalloc(pool->zone, M_WAITOK);
3704#else
3705	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3706#endif
3707	if (io != NULL)
3708		io->io_hdr.pool = pool_ref;
3709	return (io);
3710}
3711
3712union ctl_io *
3713ctl_alloc_io_nowait(void *pool_ref)
3714{
3715	union ctl_io *io;
3716#ifdef IO_POOLS
3717	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3718
3719	io = uma_zalloc(pool->zone, M_NOWAIT);
3720#else
3721	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3722#endif
3723	if (io != NULL)
3724		io->io_hdr.pool = pool_ref;
3725	return (io);
3726}
3727
3728void
3729ctl_free_io(union ctl_io *io)
3730{
3731#ifdef IO_POOLS
3732	struct ctl_io_pool *pool;
3733#endif
3734
3735	if (io == NULL)
3736		return;
3737
3738#ifdef IO_POOLS
3739	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3740	uma_zfree(pool->zone, io);
3741#else
3742	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3743#endif
3744}
3745
3746void
3747ctl_zero_io(union ctl_io *io)
3748{
3749	void *pool_ref;
3750
3751	if (io == NULL)
3752		return;
3753
3754	/*
3755	 * May need to preserve linked list pointers at some point too.
3756	 */
3757	pool_ref = io->io_hdr.pool;
3758	memset(io, 0, sizeof(*io));
3759	io->io_hdr.pool = pool_ref;
3760}
3761
3762int
3763ctl_expand_number(const char *buf, uint64_t *num)
3764{
3765	char *endptr;
3766	uint64_t number;
3767	unsigned shift;
3768
3769	number = strtoq(buf, &endptr, 0);
3770
3771	switch (tolower((unsigned char)*endptr)) {
3772	case 'e':
3773		shift = 60;
3774		break;
3775	case 'p':
3776		shift = 50;
3777		break;
3778	case 't':
3779		shift = 40;
3780		break;
3781	case 'g':
3782		shift = 30;
3783		break;
3784	case 'm':
3785		shift = 20;
3786		break;
3787	case 'k':
3788		shift = 10;
3789		break;
3790	case 'b':
3791	case '\0': /* No unit. */
3792		*num = number;
3793		return (0);
3794	default:
3795		/* Unrecognized unit. */
3796		return (-1);
3797	}
3798
3799	if ((number << shift) >> shift != number) {
3800		/* Overflow */
3801		return (-1);
3802	}
3803	*num = number << shift;
3804	return (0);
3805}
3806
3807
3808/*
3809 * This routine could be used in the future to load default and/or saved
3810 * mode page parameters for a particuar lun.
3811 */
3812static int
3813ctl_init_page_index(struct ctl_lun *lun)
3814{
3815	int i;
3816	struct ctl_page_index *page_index;
3817	const char *value;
3818	uint64_t ival;
3819
3820	memcpy(&lun->mode_pages.index, page_index_template,
3821	       sizeof(page_index_template));
3822
3823	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3824
3825		page_index = &lun->mode_pages.index[i];
3826		if (lun->be_lun->lun_type == T_DIRECT &&
3827		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3828			continue;
3829		if (lun->be_lun->lun_type == T_PROCESSOR &&
3830		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3831			continue;
3832		if (lun->be_lun->lun_type == T_CDROM &&
3833		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3834			continue;
3835
3836		switch (page_index->page_code & SMPH_PC_MASK) {
3837		case SMS_RW_ERROR_RECOVERY_PAGE: {
3838			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3839				panic("subpage is incorrect!");
3840			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3841			       &rw_er_page_default,
3842			       sizeof(rw_er_page_default));
3843			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3844			       &rw_er_page_changeable,
3845			       sizeof(rw_er_page_changeable));
3846			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3847			       &rw_er_page_default,
3848			       sizeof(rw_er_page_default));
3849			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3850			       &rw_er_page_default,
3851			       sizeof(rw_er_page_default));
3852			page_index->page_data =
3853				(uint8_t *)lun->mode_pages.rw_er_page;
3854			break;
3855		}
3856		case SMS_FORMAT_DEVICE_PAGE: {
3857			struct scsi_format_page *format_page;
3858
3859			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3860				panic("subpage is incorrect!");
3861
3862			/*
3863			 * Sectors per track are set above.  Bytes per
3864			 * sector need to be set here on a per-LUN basis.
3865			 */
3866			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3867			       &format_page_default,
3868			       sizeof(format_page_default));
3869			memcpy(&lun->mode_pages.format_page[
3870			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3871			       sizeof(format_page_changeable));
3872			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3873			       &format_page_default,
3874			       sizeof(format_page_default));
3875			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3876			       &format_page_default,
3877			       sizeof(format_page_default));
3878
3879			format_page = &lun->mode_pages.format_page[
3880				CTL_PAGE_CURRENT];
3881			scsi_ulto2b(lun->be_lun->blocksize,
3882				    format_page->bytes_per_sector);
3883
3884			format_page = &lun->mode_pages.format_page[
3885				CTL_PAGE_DEFAULT];
3886			scsi_ulto2b(lun->be_lun->blocksize,
3887				    format_page->bytes_per_sector);
3888
3889			format_page = &lun->mode_pages.format_page[
3890				CTL_PAGE_SAVED];
3891			scsi_ulto2b(lun->be_lun->blocksize,
3892				    format_page->bytes_per_sector);
3893
3894			page_index->page_data =
3895				(uint8_t *)lun->mode_pages.format_page;
3896			break;
3897		}
3898		case SMS_RIGID_DISK_PAGE: {
3899			struct scsi_rigid_disk_page *rigid_disk_page;
3900			uint32_t sectors_per_cylinder;
3901			uint64_t cylinders;
3902#ifndef	__XSCALE__
3903			int shift;
3904#endif /* !__XSCALE__ */
3905
3906			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3907				panic("invalid subpage value %d",
3908				      page_index->subpage);
3909
3910			/*
3911			 * Rotation rate and sectors per track are set
3912			 * above.  We calculate the cylinders here based on
3913			 * capacity.  Due to the number of heads and
3914			 * sectors per track we're using, smaller arrays
3915			 * may turn out to have 0 cylinders.  Linux and
3916			 * FreeBSD don't pay attention to these mode pages
3917			 * to figure out capacity, but Solaris does.  It
3918			 * seems to deal with 0 cylinders just fine, and
3919			 * works out a fake geometry based on the capacity.
3920			 */
3921			memcpy(&lun->mode_pages.rigid_disk_page[
3922			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3923			       sizeof(rigid_disk_page_default));
3924			memcpy(&lun->mode_pages.rigid_disk_page[
3925			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3926			       sizeof(rigid_disk_page_changeable));
3927
3928			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3929				CTL_DEFAULT_HEADS;
3930
3931			/*
3932			 * The divide method here will be more accurate,
3933			 * probably, but results in floating point being
3934			 * used in the kernel on i386 (__udivdi3()).  On the
3935			 * XScale, though, __udivdi3() is implemented in
3936			 * software.
3937			 *
3938			 * The shift method for cylinder calculation is
3939			 * accurate if sectors_per_cylinder is a power of
3940			 * 2.  Otherwise it might be slightly off -- you
3941			 * might have a bit of a truncation problem.
3942			 */
3943#ifdef	__XSCALE__
3944			cylinders = (lun->be_lun->maxlba + 1) /
3945				sectors_per_cylinder;
3946#else
3947			for (shift = 31; shift > 0; shift--) {
3948				if (sectors_per_cylinder & (1 << shift))
3949					break;
3950			}
3951			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3952#endif
3953
3954			/*
3955			 * We've basically got 3 bytes, or 24 bits for the
3956			 * cylinder size in the mode page.  If we're over,
3957			 * just round down to 2^24.
3958			 */
3959			if (cylinders > 0xffffff)
3960				cylinders = 0xffffff;
3961
3962			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3963				CTL_PAGE_DEFAULT];
3964			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3965
3966			if ((value = ctl_get_opt(&lun->be_lun->options,
3967			    "rpm")) != NULL) {
3968				scsi_ulto2b(strtol(value, NULL, 0),
3969				     rigid_disk_page->rotation_rate);
3970			}
3971
3972			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3973			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3974			       sizeof(rigid_disk_page_default));
3975			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3976			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3977			       sizeof(rigid_disk_page_default));
3978
3979			page_index->page_data =
3980				(uint8_t *)lun->mode_pages.rigid_disk_page;
3981			break;
3982		}
3983		case SMS_CACHING_PAGE: {
3984			struct scsi_caching_page *caching_page;
3985
3986			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3987				panic("invalid subpage value %d",
3988				      page_index->subpage);
3989			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3990			       &caching_page_default,
3991			       sizeof(caching_page_default));
3992			memcpy(&lun->mode_pages.caching_page[
3993			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3994			       sizeof(caching_page_changeable));
3995			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3996			       &caching_page_default,
3997			       sizeof(caching_page_default));
3998			caching_page = &lun->mode_pages.caching_page[
3999			    CTL_PAGE_SAVED];
4000			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4001			if (value != NULL && strcmp(value, "off") == 0)
4002				caching_page->flags1 &= ~SCP_WCE;
4003			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4004			if (value != NULL && strcmp(value, "off") == 0)
4005				caching_page->flags1 |= SCP_RCD;
4006			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4007			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4008			       sizeof(caching_page_default));
4009			page_index->page_data =
4010				(uint8_t *)lun->mode_pages.caching_page;
4011			break;
4012		}
4013		case SMS_CONTROL_MODE_PAGE: {
4014			switch (page_index->subpage) {
4015			case SMS_SUBPAGE_PAGE_0: {
4016				struct scsi_control_page *control_page;
4017
4018				memcpy(&lun->mode_pages.control_page[
4019				    CTL_PAGE_DEFAULT],
4020				       &control_page_default,
4021				       sizeof(control_page_default));
4022				memcpy(&lun->mode_pages.control_page[
4023				    CTL_PAGE_CHANGEABLE],
4024				       &control_page_changeable,
4025				       sizeof(control_page_changeable));
4026				memcpy(&lun->mode_pages.control_page[
4027				    CTL_PAGE_SAVED],
4028				       &control_page_default,
4029				       sizeof(control_page_default));
4030				control_page = &lun->mode_pages.control_page[
4031				    CTL_PAGE_SAVED];
4032				value = ctl_get_opt(&lun->be_lun->options,
4033				    "reordering");
4034				if (value != NULL &&
4035				    strcmp(value, "unrestricted") == 0) {
4036					control_page->queue_flags &=
4037					    ~SCP_QUEUE_ALG_MASK;
4038					control_page->queue_flags |=
4039					    SCP_QUEUE_ALG_UNRESTRICTED;
4040				}
4041				memcpy(&lun->mode_pages.control_page[
4042				    CTL_PAGE_CURRENT],
4043				       &lun->mode_pages.control_page[
4044				    CTL_PAGE_SAVED],
4045				       sizeof(control_page_default));
4046				page_index->page_data =
4047				    (uint8_t *)lun->mode_pages.control_page;
4048				break;
4049			}
4050			case 0x01:
4051				memcpy(&lun->mode_pages.control_ext_page[
4052				    CTL_PAGE_DEFAULT],
4053				       &control_ext_page_default,
4054				       sizeof(control_ext_page_default));
4055				memcpy(&lun->mode_pages.control_ext_page[
4056				    CTL_PAGE_CHANGEABLE],
4057				       &control_ext_page_changeable,
4058				       sizeof(control_ext_page_changeable));
4059				memcpy(&lun->mode_pages.control_ext_page[
4060				    CTL_PAGE_SAVED],
4061				       &control_ext_page_default,
4062				       sizeof(control_ext_page_default));
4063				memcpy(&lun->mode_pages.control_ext_page[
4064				    CTL_PAGE_CURRENT],
4065				       &lun->mode_pages.control_ext_page[
4066				    CTL_PAGE_SAVED],
4067				       sizeof(control_ext_page_default));
4068				page_index->page_data =
4069				    (uint8_t *)lun->mode_pages.control_ext_page;
4070				break;
4071			}
4072			break;
4073		}
4074		case SMS_INFO_EXCEPTIONS_PAGE: {
4075			switch (page_index->subpage) {
4076			case SMS_SUBPAGE_PAGE_0:
4077				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4078				       &ie_page_default,
4079				       sizeof(ie_page_default));
4080				memcpy(&lun->mode_pages.ie_page[
4081				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4082				       sizeof(ie_page_changeable));
4083				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4084				       &ie_page_default,
4085				       sizeof(ie_page_default));
4086				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4087				       &ie_page_default,
4088				       sizeof(ie_page_default));
4089				page_index->page_data =
4090					(uint8_t *)lun->mode_pages.ie_page;
4091				break;
4092			case 0x02: {
4093				struct ctl_logical_block_provisioning_page *page;
4094
4095				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4096				       &lbp_page_default,
4097				       sizeof(lbp_page_default));
4098				memcpy(&lun->mode_pages.lbp_page[
4099				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4100				       sizeof(lbp_page_changeable));
4101				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4102				       &lbp_page_default,
4103				       sizeof(lbp_page_default));
4104				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4105				value = ctl_get_opt(&lun->be_lun->options,
4106				    "avail-threshold");
4107				if (value != NULL &&
4108				    ctl_expand_number(value, &ival) == 0) {
4109					page->descr[0].flags |= SLBPPD_ENABLED |
4110					    SLBPPD_ARMING_DEC;
4111					if (lun->be_lun->blocksize)
4112						ival /= lun->be_lun->blocksize;
4113					else
4114						ival /= 512;
4115					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4116					    page->descr[0].count);
4117				}
4118				value = ctl_get_opt(&lun->be_lun->options,
4119				    "used-threshold");
4120				if (value != NULL &&
4121				    ctl_expand_number(value, &ival) == 0) {
4122					page->descr[1].flags |= SLBPPD_ENABLED |
4123					    SLBPPD_ARMING_INC;
4124					if (lun->be_lun->blocksize)
4125						ival /= lun->be_lun->blocksize;
4126					else
4127						ival /= 512;
4128					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4129					    page->descr[1].count);
4130				}
4131				value = ctl_get_opt(&lun->be_lun->options,
4132				    "pool-avail-threshold");
4133				if (value != NULL &&
4134				    ctl_expand_number(value, &ival) == 0) {
4135					page->descr[2].flags |= SLBPPD_ENABLED |
4136					    SLBPPD_ARMING_DEC;
4137					if (lun->be_lun->blocksize)
4138						ival /= lun->be_lun->blocksize;
4139					else
4140						ival /= 512;
4141					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4142					    page->descr[2].count);
4143				}
4144				value = ctl_get_opt(&lun->be_lun->options,
4145				    "pool-used-threshold");
4146				if (value != NULL &&
4147				    ctl_expand_number(value, &ival) == 0) {
4148					page->descr[3].flags |= SLBPPD_ENABLED |
4149					    SLBPPD_ARMING_INC;
4150					if (lun->be_lun->blocksize)
4151						ival /= lun->be_lun->blocksize;
4152					else
4153						ival /= 512;
4154					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4155					    page->descr[3].count);
4156				}
4157				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4158				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4159				       sizeof(lbp_page_default));
4160				page_index->page_data =
4161					(uint8_t *)lun->mode_pages.lbp_page;
4162			}}
4163			break;
4164		}
4165		case SMS_CDDVD_CAPS_PAGE:{
4166			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4167			       &cddvd_page_default,
4168			       sizeof(cddvd_page_default));
4169			memcpy(&lun->mode_pages.cddvd_page[
4170			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4171			       sizeof(cddvd_page_changeable));
4172			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4173			       &cddvd_page_default,
4174			       sizeof(cddvd_page_default));
4175			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4176			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4177			       sizeof(cddvd_page_default));
4178			page_index->page_data =
4179				(uint8_t *)lun->mode_pages.cddvd_page;
4180			break;
4181		}
4182		case SMS_VENDOR_SPECIFIC_PAGE:{
4183			switch (page_index->subpage) {
4184			case DBGCNF_SUBPAGE_CODE: {
4185				memcpy(&lun->mode_pages.debugconf_subpage[
4186				       CTL_PAGE_CURRENT],
4187				       &debugconf_page_default,
4188				       sizeof(debugconf_page_default));
4189				memcpy(&lun->mode_pages.debugconf_subpage[
4190				       CTL_PAGE_CHANGEABLE],
4191				       &debugconf_page_changeable,
4192				       sizeof(debugconf_page_changeable));
4193				memcpy(&lun->mode_pages.debugconf_subpage[
4194				       CTL_PAGE_DEFAULT],
4195				       &debugconf_page_default,
4196				       sizeof(debugconf_page_default));
4197				memcpy(&lun->mode_pages.debugconf_subpage[
4198				       CTL_PAGE_SAVED],
4199				       &debugconf_page_default,
4200				       sizeof(debugconf_page_default));
4201				page_index->page_data =
4202				    (uint8_t *)lun->mode_pages.debugconf_subpage;
4203				break;
4204			}
4205			default:
4206				panic("invalid subpage value %d",
4207				      page_index->subpage);
4208				break;
4209			}
4210   			break;
4211		}
4212		default:
4213			panic("invalid page value %d",
4214			      page_index->page_code & SMPH_PC_MASK);
4215			break;
4216    	}
4217	}
4218
4219	return (CTL_RETVAL_COMPLETE);
4220}
4221
4222static int
4223ctl_init_log_page_index(struct ctl_lun *lun)
4224{
4225	struct ctl_page_index *page_index;
4226	int i, j, k, prev;
4227
4228	memcpy(&lun->log_pages.index, log_page_index_template,
4229	       sizeof(log_page_index_template));
4230
4231	prev = -1;
4232	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4233
4234		page_index = &lun->log_pages.index[i];
4235		if (lun->be_lun->lun_type == T_DIRECT &&
4236		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4237			continue;
4238		if (lun->be_lun->lun_type == T_PROCESSOR &&
4239		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4240			continue;
4241		if (lun->be_lun->lun_type == T_CDROM &&
4242		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4243			continue;
4244
4245		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4246		    lun->backend->lun_attr == NULL)
4247			continue;
4248
4249		if (page_index->page_code != prev) {
4250			lun->log_pages.pages_page[j] = page_index->page_code;
4251			prev = page_index->page_code;
4252			j++;
4253		}
4254		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4255		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4256		k++;
4257	}
4258	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4259	lun->log_pages.index[0].page_len = j;
4260	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4261	lun->log_pages.index[1].page_len = k * 2;
4262	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4263	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4264	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4265	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4266
4267	return (CTL_RETVAL_COMPLETE);
4268}
4269
4270static int
4271hex2bin(const char *str, uint8_t *buf, int buf_size)
4272{
4273	int i;
4274	u_char c;
4275
4276	memset(buf, 0, buf_size);
4277	while (isspace(str[0]))
4278		str++;
4279	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4280		str += 2;
4281	buf_size *= 2;
4282	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4283		c = str[i];
4284		if (isdigit(c))
4285			c -= '0';
4286		else if (isalpha(c))
4287			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4288		else
4289			break;
4290		if (c >= 16)
4291			break;
4292		if ((i & 1) == 0)
4293			buf[i / 2] |= (c << 4);
4294		else
4295			buf[i / 2] |= c;
4296	}
4297	return ((i + 1) / 2);
4298}
4299
4300/*
4301 * LUN allocation.
4302 *
4303 * Requirements:
4304 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4305 *   wants us to allocate the LUN and he can block.
4306 * - ctl_softc is always set
4307 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4308 *
4309 * Returns 0 for success, non-zero (errno) for failure.
4310 */
4311static int
4312ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4313	      struct ctl_be_lun *const be_lun)
4314{
4315	struct ctl_lun *nlun, *lun;
4316	struct scsi_vpd_id_descriptor *desc;
4317	struct scsi_vpd_id_t10 *t10id;
4318	const char *eui, *naa, *scsiname, *vendor, *value;
4319	int lun_number, i, lun_malloced;
4320	int devidlen, idlen1, idlen2 = 0, len;
4321
4322	if (be_lun == NULL)
4323		return (EINVAL);
4324
4325	/*
4326	 * We currently only support Direct Access or Processor LUN types.
4327	 */
4328	switch (be_lun->lun_type) {
4329	case T_DIRECT:
4330	case T_PROCESSOR:
4331	case T_CDROM:
4332		break;
4333	case T_SEQUENTIAL:
4334	case T_CHANGER:
4335	default:
4336		be_lun->lun_config_status(be_lun->be_lun,
4337					  CTL_LUN_CONFIG_FAILURE);
4338		break;
4339	}
4340	if (ctl_lun == NULL) {
4341		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4342		lun_malloced = 1;
4343	} else {
4344		lun_malloced = 0;
4345		lun = ctl_lun;
4346	}
4347
4348	memset(lun, 0, sizeof(*lun));
4349	if (lun_malloced)
4350		lun->flags = CTL_LUN_MALLOCED;
4351
4352	/* Generate LUN ID. */
4353	devidlen = max(CTL_DEVID_MIN_LEN,
4354	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4355	idlen1 = sizeof(*t10id) + devidlen;
4356	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4357	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4358	if (scsiname != NULL) {
4359		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4360		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4361	}
4362	eui = ctl_get_opt(&be_lun->options, "eui");
4363	if (eui != NULL) {
4364		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4365	}
4366	naa = ctl_get_opt(&be_lun->options, "naa");
4367	if (naa != NULL) {
4368		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4369	}
4370	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4371	    M_CTL, M_WAITOK | M_ZERO);
4372	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4373	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4374	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4375	desc->length = idlen1;
4376	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4377	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4378	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4379		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4380	} else {
4381		strncpy(t10id->vendor, vendor,
4382		    min(sizeof(t10id->vendor), strlen(vendor)));
4383	}
4384	strncpy((char *)t10id->vendor_spec_id,
4385	    (char *)be_lun->device_id, devidlen);
4386	if (scsiname != NULL) {
4387		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4388		    desc->length);
4389		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4390		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4391		    SVPD_ID_TYPE_SCSI_NAME;
4392		desc->length = idlen2;
4393		strlcpy(desc->identifier, scsiname, idlen2);
4394	}
4395	if (eui != NULL) {
4396		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4397		    desc->length);
4398		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4399		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4400		    SVPD_ID_TYPE_EUI64;
4401		desc->length = hex2bin(eui, desc->identifier, 16);
4402		desc->length = desc->length > 12 ? 16 :
4403		    (desc->length > 8 ? 12 : 8);
4404		len -= 16 - desc->length;
4405	}
4406	if (naa != NULL) {
4407		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4408		    desc->length);
4409		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4410		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4411		    SVPD_ID_TYPE_NAA;
4412		desc->length = hex2bin(naa, desc->identifier, 16);
4413		desc->length = desc->length > 8 ? 16 : 8;
4414		len -= 16 - desc->length;
4415	}
4416	lun->lun_devid->len = len;
4417
4418	mtx_lock(&ctl_softc->ctl_lock);
4419	/*
4420	 * See if the caller requested a particular LUN number.  If so, see
4421	 * if it is available.  Otherwise, allocate the first available LUN.
4422	 */
4423	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4424		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4425		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4426			mtx_unlock(&ctl_softc->ctl_lock);
4427			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4428				printf("ctl: requested LUN ID %d is higher "
4429				       "than CTL_MAX_LUNS - 1 (%d)\n",
4430				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4431			} else {
4432				/*
4433				 * XXX KDM return an error, or just assign
4434				 * another LUN ID in this case??
4435				 */
4436				printf("ctl: requested LUN ID %d is already "
4437				       "in use\n", be_lun->req_lun_id);
4438			}
4439			if (lun->flags & CTL_LUN_MALLOCED)
4440				free(lun, M_CTL);
4441			be_lun->lun_config_status(be_lun->be_lun,
4442						  CTL_LUN_CONFIG_FAILURE);
4443			return (ENOSPC);
4444		}
4445		lun_number = be_lun->req_lun_id;
4446	} else {
4447		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4448		if (lun_number == -1) {
4449			mtx_unlock(&ctl_softc->ctl_lock);
4450			printf("ctl: can't allocate LUN, out of LUNs\n");
4451			if (lun->flags & CTL_LUN_MALLOCED)
4452				free(lun, M_CTL);
4453			be_lun->lun_config_status(be_lun->be_lun,
4454						  CTL_LUN_CONFIG_FAILURE);
4455			return (ENOSPC);
4456		}
4457	}
4458	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4459
4460	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4461	lun->lun = lun_number;
4462	lun->be_lun = be_lun;
4463	/*
4464	 * The processor LUN is always enabled.  Disk LUNs come on line
4465	 * disabled, and must be enabled by the backend.
4466	 */
4467	lun->flags |= CTL_LUN_DISABLED;
4468	lun->backend = be_lun->be;
4469	be_lun->ctl_lun = lun;
4470	be_lun->lun_id = lun_number;
4471	atomic_add_int(&be_lun->be->num_luns, 1);
4472	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4473		lun->flags |= CTL_LUN_EJECTED;
4474	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4475		lun->flags |= CTL_LUN_NO_MEDIA;
4476	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4477		lun->flags |= CTL_LUN_STOPPED;
4478
4479	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4480		lun->flags |= CTL_LUN_PRIMARY_SC;
4481
4482	value = ctl_get_opt(&be_lun->options, "removable");
4483	if (value != NULL) {
4484		if (strcmp(value, "on") == 0)
4485			lun->flags |= CTL_LUN_REMOVABLE;
4486	} else if (be_lun->lun_type == T_CDROM)
4487		lun->flags |= CTL_LUN_REMOVABLE;
4488
4489	lun->ctl_softc = ctl_softc;
4490#ifdef CTL_TIME_IO
4491	lun->last_busy = getsbinuptime();
4492#endif
4493	TAILQ_INIT(&lun->ooa_queue);
4494	TAILQ_INIT(&lun->blocked_queue);
4495	STAILQ_INIT(&lun->error_list);
4496	ctl_tpc_lun_init(lun);
4497
4498	/*
4499	 * Initialize the mode and log page index.
4500	 */
4501	ctl_init_page_index(lun);
4502	ctl_init_log_page_index(lun);
4503
4504	/*
4505	 * Now, before we insert this lun on the lun list, set the lun
4506	 * inventory changed UA for all other luns.
4507	 */
4508	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4509		mtx_lock(&nlun->lun_lock);
4510		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4511		mtx_unlock(&nlun->lun_lock);
4512	}
4513
4514	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4515
4516	ctl_softc->ctl_luns[lun_number] = lun;
4517
4518	ctl_softc->num_luns++;
4519
4520	/* Setup statistics gathering */
4521	lun->stats.device_type = be_lun->lun_type;
4522	lun->stats.lun_number = lun_number;
4523	lun->stats.blocksize = be_lun->blocksize;
4524	if (be_lun->blocksize == 0)
4525		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4526	for (i = 0;i < CTL_MAX_PORTS;i++)
4527		lun->stats.ports[i].targ_port = i;
4528
4529	mtx_unlock(&ctl_softc->ctl_lock);
4530
4531	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4532	return (0);
4533}
4534
4535/*
4536 * Delete a LUN.
4537 * Assumptions:
4538 * - LUN has already been marked invalid and any pending I/O has been taken
4539 *   care of.
4540 */
4541static int
4542ctl_free_lun(struct ctl_lun *lun)
4543{
4544	struct ctl_softc *softc;
4545	struct ctl_lun *nlun;
4546	int i;
4547
4548	softc = lun->ctl_softc;
4549
4550	mtx_assert(&softc->ctl_lock, MA_OWNED);
4551
4552	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4553
4554	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4555
4556	softc->ctl_luns[lun->lun] = NULL;
4557
4558	if (!TAILQ_EMPTY(&lun->ooa_queue))
4559		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4560
4561	softc->num_luns--;
4562
4563	/*
4564	 * Tell the backend to free resources, if this LUN has a backend.
4565	 */
4566	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4567	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4568
4569	ctl_tpc_lun_shutdown(lun);
4570	mtx_destroy(&lun->lun_lock);
4571	free(lun->lun_devid, M_CTL);
4572	for (i = 0; i < CTL_MAX_PORTS; i++)
4573		free(lun->pending_ua[i], M_CTL);
4574	for (i = 0; i < CTL_MAX_PORTS; i++)
4575		free(lun->pr_keys[i], M_CTL);
4576	free(lun->write_buffer, M_CTL);
4577	if (lun->flags & CTL_LUN_MALLOCED)
4578		free(lun, M_CTL);
4579
4580	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4581		mtx_lock(&nlun->lun_lock);
4582		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4583		mtx_unlock(&nlun->lun_lock);
4584	}
4585
4586	return (0);
4587}
4588
4589static void
4590ctl_create_lun(struct ctl_be_lun *be_lun)
4591{
4592
4593	/*
4594	 * ctl_alloc_lun() should handle all potential failure cases.
4595	 */
4596	ctl_alloc_lun(control_softc, NULL, be_lun);
4597}
4598
4599int
4600ctl_add_lun(struct ctl_be_lun *be_lun)
4601{
4602	struct ctl_softc *softc = control_softc;
4603
4604	mtx_lock(&softc->ctl_lock);
4605	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4606	mtx_unlock(&softc->ctl_lock);
4607	wakeup(&softc->pending_lun_queue);
4608
4609	return (0);
4610}
4611
4612int
4613ctl_enable_lun(struct ctl_be_lun *be_lun)
4614{
4615	struct ctl_softc *softc;
4616	struct ctl_port *port, *nport;
4617	struct ctl_lun *lun;
4618	int retval;
4619
4620	lun = (struct ctl_lun *)be_lun->ctl_lun;
4621	softc = lun->ctl_softc;
4622
4623	mtx_lock(&softc->ctl_lock);
4624	mtx_lock(&lun->lun_lock);
4625	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4626		/*
4627		 * eh?  Why did we get called if the LUN is already
4628		 * enabled?
4629		 */
4630		mtx_unlock(&lun->lun_lock);
4631		mtx_unlock(&softc->ctl_lock);
4632		return (0);
4633	}
4634	lun->flags &= ~CTL_LUN_DISABLED;
4635	mtx_unlock(&lun->lun_lock);
4636
4637	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4638		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4639		    port->lun_map != NULL || port->lun_enable == NULL)
4640			continue;
4641
4642		/*
4643		 * Drop the lock while we call the FETD's enable routine.
4644		 * This can lead to a callback into CTL (at least in the
4645		 * case of the internal initiator frontend.
4646		 */
4647		mtx_unlock(&softc->ctl_lock);
4648		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4649		mtx_lock(&softc->ctl_lock);
4650		if (retval != 0) {
4651			printf("%s: FETD %s port %d returned error "
4652			       "%d for lun_enable on lun %jd\n",
4653			       __func__, port->port_name, port->targ_port,
4654			       retval, (intmax_t)lun->lun);
4655		}
4656	}
4657
4658	mtx_unlock(&softc->ctl_lock);
4659	ctl_isc_announce_lun(lun);
4660
4661	return (0);
4662}
4663
4664int
4665ctl_disable_lun(struct ctl_be_lun *be_lun)
4666{
4667	struct ctl_softc *softc;
4668	struct ctl_port *port;
4669	struct ctl_lun *lun;
4670	int retval;
4671
4672	lun = (struct ctl_lun *)be_lun->ctl_lun;
4673	softc = lun->ctl_softc;
4674
4675	mtx_lock(&softc->ctl_lock);
4676	mtx_lock(&lun->lun_lock);
4677	if (lun->flags & CTL_LUN_DISABLED) {
4678		mtx_unlock(&lun->lun_lock);
4679		mtx_unlock(&softc->ctl_lock);
4680		return (0);
4681	}
4682	lun->flags |= CTL_LUN_DISABLED;
4683	mtx_unlock(&lun->lun_lock);
4684
4685	STAILQ_FOREACH(port, &softc->port_list, links) {
4686		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4687		    port->lun_map != NULL || port->lun_disable == NULL)
4688			continue;
4689
4690		/*
4691		 * Drop the lock before we call the frontend's disable
4692		 * routine, to avoid lock order reversals.
4693		 *
4694		 * XXX KDM what happens if the frontend list changes while
4695		 * we're traversing it?  It's unlikely, but should be handled.
4696		 */
4697		mtx_unlock(&softc->ctl_lock);
4698		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4699		mtx_lock(&softc->ctl_lock);
4700		if (retval != 0) {
4701			printf("%s: FETD %s port %d returned error "
4702			       "%d for lun_disable on lun %jd\n",
4703			       __func__, port->port_name, port->targ_port,
4704			       retval, (intmax_t)lun->lun);
4705		}
4706	}
4707
4708	mtx_unlock(&softc->ctl_lock);
4709	ctl_isc_announce_lun(lun);
4710
4711	return (0);
4712}
4713
4714int
4715ctl_start_lun(struct ctl_be_lun *be_lun)
4716{
4717	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4718
4719	mtx_lock(&lun->lun_lock);
4720	lun->flags &= ~CTL_LUN_STOPPED;
4721	mtx_unlock(&lun->lun_lock);
4722	return (0);
4723}
4724
4725int
4726ctl_stop_lun(struct ctl_be_lun *be_lun)
4727{
4728	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4729
4730	mtx_lock(&lun->lun_lock);
4731	lun->flags |= CTL_LUN_STOPPED;
4732	mtx_unlock(&lun->lun_lock);
4733	return (0);
4734}
4735
4736int
4737ctl_lun_no_media(struct ctl_be_lun *be_lun)
4738{
4739	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4740
4741	mtx_lock(&lun->lun_lock);
4742	lun->flags |= CTL_LUN_NO_MEDIA;
4743	mtx_unlock(&lun->lun_lock);
4744	return (0);
4745}
4746
4747int
4748ctl_lun_has_media(struct ctl_be_lun *be_lun)
4749{
4750	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4751	union ctl_ha_msg msg;
4752
4753	mtx_lock(&lun->lun_lock);
4754	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4755	if (lun->flags & CTL_LUN_REMOVABLE)
4756		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4757	mtx_unlock(&lun->lun_lock);
4758	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4759	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4760		bzero(&msg.ua, sizeof(msg.ua));
4761		msg.hdr.msg_type = CTL_MSG_UA;
4762		msg.hdr.nexus.initid = -1;
4763		msg.hdr.nexus.targ_port = -1;
4764		msg.hdr.nexus.targ_lun = lun->lun;
4765		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4766		msg.ua.ua_all = 1;
4767		msg.ua.ua_set = 1;
4768		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4769		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4770		    M_WAITOK);
4771	}
4772	return (0);
4773}
4774
4775int
4776ctl_lun_ejected(struct ctl_be_lun *be_lun)
4777{
4778	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4779
4780	mtx_lock(&lun->lun_lock);
4781	lun->flags |= CTL_LUN_EJECTED;
4782	mtx_unlock(&lun->lun_lock);
4783	return (0);
4784}
4785
4786int
4787ctl_lun_primary(struct ctl_be_lun *be_lun)
4788{
4789	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4790
4791	mtx_lock(&lun->lun_lock);
4792	lun->flags |= CTL_LUN_PRIMARY_SC;
4793	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4794	mtx_unlock(&lun->lun_lock);
4795	ctl_isc_announce_lun(lun);
4796	return (0);
4797}
4798
4799int
4800ctl_lun_secondary(struct ctl_be_lun *be_lun)
4801{
4802	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4803
4804	mtx_lock(&lun->lun_lock);
4805	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4806	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4807	mtx_unlock(&lun->lun_lock);
4808	ctl_isc_announce_lun(lun);
4809	return (0);
4810}
4811
4812int
4813ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4814{
4815	struct ctl_softc *softc;
4816	struct ctl_lun *lun;
4817
4818	lun = (struct ctl_lun *)be_lun->ctl_lun;
4819	softc = lun->ctl_softc;
4820
4821	mtx_lock(&lun->lun_lock);
4822
4823	/*
4824	 * The LUN needs to be disabled before it can be marked invalid.
4825	 */
4826	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4827		mtx_unlock(&lun->lun_lock);
4828		return (-1);
4829	}
4830	/*
4831	 * Mark the LUN invalid.
4832	 */
4833	lun->flags |= CTL_LUN_INVALID;
4834
4835	/*
4836	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4837	 * If we have something in the OOA queue, we'll free it when the
4838	 * last I/O completes.
4839	 */
4840	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4841		mtx_unlock(&lun->lun_lock);
4842		mtx_lock(&softc->ctl_lock);
4843		ctl_free_lun(lun);
4844		mtx_unlock(&softc->ctl_lock);
4845	} else
4846		mtx_unlock(&lun->lun_lock);
4847
4848	return (0);
4849}
4850
4851void
4852ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4853{
4854	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4855	union ctl_ha_msg msg;
4856
4857	mtx_lock(&lun->lun_lock);
4858	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4859	mtx_unlock(&lun->lun_lock);
4860	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4861		/* Send msg to other side. */
4862		bzero(&msg.ua, sizeof(msg.ua));
4863		msg.hdr.msg_type = CTL_MSG_UA;
4864		msg.hdr.nexus.initid = -1;
4865		msg.hdr.nexus.targ_port = -1;
4866		msg.hdr.nexus.targ_lun = lun->lun;
4867		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4868		msg.ua.ua_all = 1;
4869		msg.ua.ua_set = 1;
4870		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4871		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4872		    M_WAITOK);
4873	}
4874}
4875
4876/*
4877 * Backend "memory move is complete" callback for requests that never
4878 * make it down to say RAIDCore's configuration code.
4879 */
4880int
4881ctl_config_move_done(union ctl_io *io)
4882{
4883	int retval;
4884
4885	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4886	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4887	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4888
4889	if ((io->io_hdr.port_status != 0) &&
4890	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4891	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4892		/*
4893		 * For hardware error sense keys, the sense key
4894		 * specific value is defined to be a retry count,
4895		 * but we use it to pass back an internal FETD
4896		 * error code.  XXX KDM  Hopefully the FETD is only
4897		 * using 16 bits for an error code, since that's
4898		 * all the space we have in the sks field.
4899		 */
4900		ctl_set_internal_failure(&io->scsiio,
4901					 /*sks_valid*/ 1,
4902					 /*retry_count*/
4903					 io->io_hdr.port_status);
4904	}
4905
4906	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4907		ctl_data_print(io);
4908	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4909	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4910	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4911	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4912		/*
4913		 * XXX KDM just assuming a single pointer here, and not a
4914		 * S/G list.  If we start using S/G lists for config data,
4915		 * we'll need to know how to clean them up here as well.
4916		 */
4917		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4918			free(io->scsiio.kern_data_ptr, M_CTL);
4919		ctl_done(io);
4920		retval = CTL_RETVAL_COMPLETE;
4921	} else {
4922		/*
4923		 * XXX KDM now we need to continue data movement.  Some
4924		 * options:
4925		 * - call ctl_scsiio() again?  We don't do this for data
4926		 *   writes, because for those at least we know ahead of
4927		 *   time where the write will go and how long it is.  For
4928		 *   config writes, though, that information is largely
4929		 *   contained within the write itself, thus we need to
4930		 *   parse out the data again.
4931		 *
4932		 * - Call some other function once the data is in?
4933		 */
4934
4935		/*
4936		 * XXX KDM call ctl_scsiio() again for now, and check flag
4937		 * bits to see whether we're allocated or not.
4938		 */
4939		retval = ctl_scsiio(&io->scsiio);
4940	}
4941	return (retval);
4942}
4943
4944/*
4945 * This gets called by a backend driver when it is done with a
4946 * data_submit method.
4947 */
4948void
4949ctl_data_submit_done(union ctl_io *io)
4950{
4951	/*
4952	 * If the IO_CONT flag is set, we need to call the supplied
4953	 * function to continue processing the I/O, instead of completing
4954	 * the I/O just yet.
4955	 *
4956	 * If there is an error, though, we don't want to keep processing.
4957	 * Instead, just send status back to the initiator.
4958	 */
4959	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4960	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4961	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4962	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4963		io->scsiio.io_cont(io);
4964		return;
4965	}
4966	ctl_done(io);
4967}
4968
4969/*
4970 * This gets called by a backend driver when it is done with a
4971 * configuration write.
4972 */
4973void
4974ctl_config_write_done(union ctl_io *io)
4975{
4976	uint8_t *buf;
4977
4978	/*
4979	 * If the IO_CONT flag is set, we need to call the supplied
4980	 * function to continue processing the I/O, instead of completing
4981	 * the I/O just yet.
4982	 *
4983	 * If there is an error, though, we don't want to keep processing.
4984	 * Instead, just send status back to the initiator.
4985	 */
4986	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4987	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4988	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4989	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4990		io->scsiio.io_cont(io);
4991		return;
4992	}
4993	/*
4994	 * Since a configuration write can be done for commands that actually
4995	 * have data allocated, like write buffer, and commands that have
4996	 * no data, like start/stop unit, we need to check here.
4997	 */
4998	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4999		buf = io->scsiio.kern_data_ptr;
5000	else
5001		buf = NULL;
5002	ctl_done(io);
5003	if (buf)
5004		free(buf, M_CTL);
5005}
5006
5007void
5008ctl_config_read_done(union ctl_io *io)
5009{
5010	uint8_t *buf;
5011
5012	/*
5013	 * If there is some error -- we are done, skip data transfer.
5014	 */
5015	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5016	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5017	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5018		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5019			buf = io->scsiio.kern_data_ptr;
5020		else
5021			buf = NULL;
5022		ctl_done(io);
5023		if (buf)
5024			free(buf, M_CTL);
5025		return;
5026	}
5027
5028	/*
5029	 * If the IO_CONT flag is set, we need to call the supplied
5030	 * function to continue processing the I/O, instead of completing
5031	 * the I/O just yet.
5032	 */
5033	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5034		io->scsiio.io_cont(io);
5035		return;
5036	}
5037
5038	ctl_datamove(io);
5039}
5040
5041/*
5042 * SCSI release command.
5043 */
5044int
5045ctl_scsi_release(struct ctl_scsiio *ctsio)
5046{
5047	struct ctl_lun *lun;
5048	uint32_t residx;
5049
5050	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5051
5052	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5053	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5054
5055	/*
5056	 * XXX KDM right now, we only support LUN reservation.  We don't
5057	 * support 3rd party reservations, or extent reservations, which
5058	 * might actually need the parameter list.  If we've gotten this
5059	 * far, we've got a LUN reservation.  Anything else got kicked out
5060	 * above.  So, according to SPC, ignore the length.
5061	 */
5062
5063	mtx_lock(&lun->lun_lock);
5064
5065	/*
5066	 * According to SPC, it is not an error for an intiator to attempt
5067	 * to release a reservation on a LUN that isn't reserved, or that
5068	 * is reserved by another initiator.  The reservation can only be
5069	 * released, though, by the initiator who made it or by one of
5070	 * several reset type events.
5071	 */
5072	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5073			lun->flags &= ~CTL_LUN_RESERVED;
5074
5075	mtx_unlock(&lun->lun_lock);
5076
5077	ctl_set_success(ctsio);
5078	ctl_done((union ctl_io *)ctsio);
5079	return (CTL_RETVAL_COMPLETE);
5080}
5081
5082int
5083ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5084{
5085	struct ctl_lun *lun;
5086	uint32_t residx;
5087
5088	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5089
5090	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5091	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5092
5093	/*
5094	 * XXX KDM right now, we only support LUN reservation.  We don't
5095	 * support 3rd party reservations, or extent reservations, which
5096	 * might actually need the parameter list.  If we've gotten this
5097	 * far, we've got a LUN reservation.  Anything else got kicked out
5098	 * above.  So, according to SPC, ignore the length.
5099	 */
5100
5101	mtx_lock(&lun->lun_lock);
5102	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5103		ctl_set_reservation_conflict(ctsio);
5104		goto bailout;
5105	}
5106	lun->flags |= CTL_LUN_RESERVED;
5107	lun->res_idx = residx;
5108	ctl_set_success(ctsio);
5109
5110bailout:
5111	mtx_unlock(&lun->lun_lock);
5112	ctl_done((union ctl_io *)ctsio);
5113	return (CTL_RETVAL_COMPLETE);
5114}
5115
5116int
5117ctl_start_stop(struct ctl_scsiio *ctsio)
5118{
5119	struct scsi_start_stop_unit *cdb;
5120	struct ctl_lun *lun;
5121	int retval;
5122
5123	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5124
5125	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5126	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5127
5128	if ((cdb->how & SSS_PC_MASK) == 0) {
5129		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5130		    (cdb->how & SSS_START) == 0) {
5131			uint32_t residx;
5132
5133			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5134			if (ctl_get_prkey(lun, residx) == 0 ||
5135			    (lun->pr_res_idx != residx && lun->res_type < 4)) {
5136
5137				ctl_set_reservation_conflict(ctsio);
5138				ctl_done((union ctl_io *)ctsio);
5139				return (CTL_RETVAL_COMPLETE);
5140			}
5141		}
5142
5143		if ((cdb->how & SSS_LOEJ) &&
5144		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5145			ctl_set_invalid_field(ctsio,
5146					      /*sks_valid*/ 1,
5147					      /*command*/ 1,
5148					      /*field*/ 4,
5149					      /*bit_valid*/ 1,
5150					      /*bit*/ 1);
5151			ctl_done((union ctl_io *)ctsio);
5152			return (CTL_RETVAL_COMPLETE);
5153		}
5154
5155		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5156		    lun->prevent_count > 0) {
5157			/* "Medium removal prevented" */
5158			ctl_set_sense(ctsio, /*current_error*/ 1,
5159			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5160			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5161			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5162			ctl_done((union ctl_io *)ctsio);
5163			return (CTL_RETVAL_COMPLETE);
5164		}
5165	}
5166
5167	retval = lun->backend->config_write((union ctl_io *)ctsio);
5168	return (retval);
5169}
5170
5171int
5172ctl_prevent_allow(struct ctl_scsiio *ctsio)
5173{
5174	struct ctl_lun *lun;
5175	struct scsi_prevent *cdb;
5176	int retval;
5177	uint32_t initidx;
5178
5179	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5180
5181	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5182	cdb = (struct scsi_prevent *)ctsio->cdb;
5183
5184	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5185		ctl_set_invalid_opcode(ctsio);
5186		ctl_done((union ctl_io *)ctsio);
5187		return (CTL_RETVAL_COMPLETE);
5188	}
5189
5190	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5191	mtx_lock(&lun->lun_lock);
5192	if ((cdb->how & PR_PREVENT) &&
5193	    ctl_is_set(lun->prevent, initidx) == 0) {
5194		ctl_set_mask(lun->prevent, initidx);
5195		lun->prevent_count++;
5196	} else if ((cdb->how & PR_PREVENT) == 0 &&
5197	    ctl_is_set(lun->prevent, initidx)) {
5198		ctl_clear_mask(lun->prevent, initidx);
5199		lun->prevent_count--;
5200	}
5201	mtx_unlock(&lun->lun_lock);
5202	retval = lun->backend->config_write((union ctl_io *)ctsio);
5203	return (retval);
5204}
5205
5206/*
5207 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5208 * we don't really do anything with the LBA and length fields if the user
5209 * passes them in.  Instead we'll just flush out the cache for the entire
5210 * LUN.
5211 */
5212int
5213ctl_sync_cache(struct ctl_scsiio *ctsio)
5214{
5215	struct ctl_lun *lun;
5216	struct ctl_softc *softc;
5217	struct ctl_lba_len_flags *lbalen;
5218	uint64_t starting_lba;
5219	uint32_t block_count;
5220	int retval;
5221	uint8_t byte2;
5222
5223	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5224
5225	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5226	softc = lun->ctl_softc;
5227	retval = 0;
5228
5229	switch (ctsio->cdb[0]) {
5230	case SYNCHRONIZE_CACHE: {
5231		struct scsi_sync_cache *cdb;
5232		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5233
5234		starting_lba = scsi_4btoul(cdb->begin_lba);
5235		block_count = scsi_2btoul(cdb->lb_count);
5236		byte2 = cdb->byte2;
5237		break;
5238	}
5239	case SYNCHRONIZE_CACHE_16: {
5240		struct scsi_sync_cache_16 *cdb;
5241		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5242
5243		starting_lba = scsi_8btou64(cdb->begin_lba);
5244		block_count = scsi_4btoul(cdb->lb_count);
5245		byte2 = cdb->byte2;
5246		break;
5247	}
5248	default:
5249		ctl_set_invalid_opcode(ctsio);
5250		ctl_done((union ctl_io *)ctsio);
5251		goto bailout;
5252		break; /* NOTREACHED */
5253	}
5254
5255	/*
5256	 * We check the LBA and length, but don't do anything with them.
5257	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5258	 * get flushed.  This check will just help satisfy anyone who wants
5259	 * to see an error for an out of range LBA.
5260	 */
5261	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5262		ctl_set_lba_out_of_range(ctsio);
5263		ctl_done((union ctl_io *)ctsio);
5264		goto bailout;
5265	}
5266
5267	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5268	lbalen->lba = starting_lba;
5269	lbalen->len = block_count;
5270	lbalen->flags = byte2;
5271	retval = lun->backend->config_write((union ctl_io *)ctsio);
5272
5273bailout:
5274	return (retval);
5275}
5276
5277int
5278ctl_format(struct ctl_scsiio *ctsio)
5279{
5280	struct scsi_format *cdb;
5281	struct ctl_lun *lun;
5282	int length, defect_list_len;
5283
5284	CTL_DEBUG_PRINT(("ctl_format\n"));
5285
5286	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5287
5288	cdb = (struct scsi_format *)ctsio->cdb;
5289
5290	length = 0;
5291	if (cdb->byte2 & SF_FMTDATA) {
5292		if (cdb->byte2 & SF_LONGLIST)
5293			length = sizeof(struct scsi_format_header_long);
5294		else
5295			length = sizeof(struct scsi_format_header_short);
5296	}
5297
5298	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5299	 && (length > 0)) {
5300		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5301		ctsio->kern_data_len = length;
5302		ctsio->kern_total_len = length;
5303		ctsio->kern_data_resid = 0;
5304		ctsio->kern_rel_offset = 0;
5305		ctsio->kern_sg_entries = 0;
5306		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5307		ctsio->be_move_done = ctl_config_move_done;
5308		ctl_datamove((union ctl_io *)ctsio);
5309
5310		return (CTL_RETVAL_COMPLETE);
5311	}
5312
5313	defect_list_len = 0;
5314
5315	if (cdb->byte2 & SF_FMTDATA) {
5316		if (cdb->byte2 & SF_LONGLIST) {
5317			struct scsi_format_header_long *header;
5318
5319			header = (struct scsi_format_header_long *)
5320				ctsio->kern_data_ptr;
5321
5322			defect_list_len = scsi_4btoul(header->defect_list_len);
5323			if (defect_list_len != 0) {
5324				ctl_set_invalid_field(ctsio,
5325						      /*sks_valid*/ 1,
5326						      /*command*/ 0,
5327						      /*field*/ 2,
5328						      /*bit_valid*/ 0,
5329						      /*bit*/ 0);
5330				goto bailout;
5331			}
5332		} else {
5333			struct scsi_format_header_short *header;
5334
5335			header = (struct scsi_format_header_short *)
5336				ctsio->kern_data_ptr;
5337
5338			defect_list_len = scsi_2btoul(header->defect_list_len);
5339			if (defect_list_len != 0) {
5340				ctl_set_invalid_field(ctsio,
5341						      /*sks_valid*/ 1,
5342						      /*command*/ 0,
5343						      /*field*/ 2,
5344						      /*bit_valid*/ 0,
5345						      /*bit*/ 0);
5346				goto bailout;
5347			}
5348		}
5349	}
5350
5351	ctl_set_success(ctsio);
5352bailout:
5353
5354	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5355		free(ctsio->kern_data_ptr, M_CTL);
5356		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5357	}
5358
5359	ctl_done((union ctl_io *)ctsio);
5360	return (CTL_RETVAL_COMPLETE);
5361}
5362
5363int
5364ctl_read_buffer(struct ctl_scsiio *ctsio)
5365{
5366	struct ctl_lun *lun;
5367	uint64_t buffer_offset;
5368	uint32_t len;
5369	uint8_t byte2;
5370	static uint8_t descr[4];
5371	static uint8_t echo_descr[4] = { 0 };
5372
5373	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5374	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5375	switch (ctsio->cdb[0]) {
5376	case READ_BUFFER: {
5377		struct scsi_read_buffer *cdb;
5378
5379		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5380		buffer_offset = scsi_3btoul(cdb->offset);
5381		len = scsi_3btoul(cdb->length);
5382		byte2 = cdb->byte2;
5383		break;
5384	}
5385	case READ_BUFFER_16: {
5386		struct scsi_read_buffer_16 *cdb;
5387
5388		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5389		buffer_offset = scsi_8btou64(cdb->offset);
5390		len = scsi_4btoul(cdb->length);
5391		byte2 = cdb->byte2;
5392		break;
5393	}
5394	default: /* This shouldn't happen. */
5395		ctl_set_invalid_opcode(ctsio);
5396		ctl_done((union ctl_io *)ctsio);
5397		return (CTL_RETVAL_COMPLETE);
5398	}
5399
5400	if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5401	    (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5402	    (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5403		ctl_set_invalid_field(ctsio,
5404				      /*sks_valid*/ 1,
5405				      /*command*/ 1,
5406				      /*field*/ 1,
5407				      /*bit_valid*/ 1,
5408				      /*bit*/ 4);
5409		ctl_done((union ctl_io *)ctsio);
5410		return (CTL_RETVAL_COMPLETE);
5411	}
5412
5413	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5414	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5415		ctl_set_invalid_field(ctsio,
5416				      /*sks_valid*/ 1,
5417				      /*command*/ 1,
5418				      /*field*/ 6,
5419				      /*bit_valid*/ 0,
5420				      /*bit*/ 0);
5421		ctl_done((union ctl_io *)ctsio);
5422		return (CTL_RETVAL_COMPLETE);
5423	}
5424
5425	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5426		descr[0] = 0;
5427		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5428		ctsio->kern_data_ptr = descr;
5429		len = min(len, sizeof(descr));
5430	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5431		ctsio->kern_data_ptr = echo_descr;
5432		len = min(len, sizeof(echo_descr));
5433	} else {
5434		if (lun->write_buffer == NULL) {
5435			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5436			    M_CTL, M_WAITOK);
5437		}
5438		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5439	}
5440	ctsio->kern_data_len = len;
5441	ctsio->kern_total_len = len;
5442	ctsio->kern_data_resid = 0;
5443	ctsio->kern_rel_offset = 0;
5444	ctsio->kern_sg_entries = 0;
5445	ctl_set_success(ctsio);
5446	ctsio->be_move_done = ctl_config_move_done;
5447	ctl_datamove((union ctl_io *)ctsio);
5448	return (CTL_RETVAL_COMPLETE);
5449}
5450
5451int
5452ctl_write_buffer(struct ctl_scsiio *ctsio)
5453{
5454	struct scsi_write_buffer *cdb;
5455	struct ctl_lun *lun;
5456	int buffer_offset, len;
5457
5458	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5459
5460	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5461	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5462
5463	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5464		ctl_set_invalid_field(ctsio,
5465				      /*sks_valid*/ 1,
5466				      /*command*/ 1,
5467				      /*field*/ 1,
5468				      /*bit_valid*/ 1,
5469				      /*bit*/ 4);
5470		ctl_done((union ctl_io *)ctsio);
5471		return (CTL_RETVAL_COMPLETE);
5472	}
5473
5474	len = scsi_3btoul(cdb->length);
5475	buffer_offset = scsi_3btoul(cdb->offset);
5476
5477	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5478		ctl_set_invalid_field(ctsio,
5479				      /*sks_valid*/ 1,
5480				      /*command*/ 1,
5481				      /*field*/ 6,
5482				      /*bit_valid*/ 0,
5483				      /*bit*/ 0);
5484		ctl_done((union ctl_io *)ctsio);
5485		return (CTL_RETVAL_COMPLETE);
5486	}
5487
5488	/*
5489	 * If we've got a kernel request that hasn't been malloced yet,
5490	 * malloc it and tell the caller the data buffer is here.
5491	 */
5492	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5493		if (lun->write_buffer == NULL) {
5494			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5495			    M_CTL, M_WAITOK);
5496		}
5497		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5498		ctsio->kern_data_len = len;
5499		ctsio->kern_total_len = len;
5500		ctsio->kern_data_resid = 0;
5501		ctsio->kern_rel_offset = 0;
5502		ctsio->kern_sg_entries = 0;
5503		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5504		ctsio->be_move_done = ctl_config_move_done;
5505		ctl_datamove((union ctl_io *)ctsio);
5506
5507		return (CTL_RETVAL_COMPLETE);
5508	}
5509
5510	ctl_set_success(ctsio);
5511	ctl_done((union ctl_io *)ctsio);
5512	return (CTL_RETVAL_COMPLETE);
5513}
5514
5515int
5516ctl_write_same(struct ctl_scsiio *ctsio)
5517{
5518	struct ctl_lun *lun;
5519	struct ctl_lba_len_flags *lbalen;
5520	uint64_t lba;
5521	uint32_t num_blocks;
5522	int len, retval;
5523	uint8_t byte2;
5524
5525	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5526
5527	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5528
5529	switch (ctsio->cdb[0]) {
5530	case WRITE_SAME_10: {
5531		struct scsi_write_same_10 *cdb;
5532
5533		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5534
5535		lba = scsi_4btoul(cdb->addr);
5536		num_blocks = scsi_2btoul(cdb->length);
5537		byte2 = cdb->byte2;
5538		break;
5539	}
5540	case WRITE_SAME_16: {
5541		struct scsi_write_same_16 *cdb;
5542
5543		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5544
5545		lba = scsi_8btou64(cdb->addr);
5546		num_blocks = scsi_4btoul(cdb->length);
5547		byte2 = cdb->byte2;
5548		break;
5549	}
5550	default:
5551		/*
5552		 * We got a command we don't support.  This shouldn't
5553		 * happen, commands should be filtered out above us.
5554		 */
5555		ctl_set_invalid_opcode(ctsio);
5556		ctl_done((union ctl_io *)ctsio);
5557
5558		return (CTL_RETVAL_COMPLETE);
5559		break; /* NOTREACHED */
5560	}
5561
5562	/* ANCHOR flag can be used only together with UNMAP */
5563	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5564		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5565		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5566		ctl_done((union ctl_io *)ctsio);
5567		return (CTL_RETVAL_COMPLETE);
5568	}
5569
5570	/*
5571	 * The first check is to make sure we're in bounds, the second
5572	 * check is to catch wrap-around problems.  If the lba + num blocks
5573	 * is less than the lba, then we've wrapped around and the block
5574	 * range is invalid anyway.
5575	 */
5576	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5577	 || ((lba + num_blocks) < lba)) {
5578		ctl_set_lba_out_of_range(ctsio);
5579		ctl_done((union ctl_io *)ctsio);
5580		return (CTL_RETVAL_COMPLETE);
5581	}
5582
5583	/* Zero number of blocks means "to the last logical block" */
5584	if (num_blocks == 0) {
5585		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5586			ctl_set_invalid_field(ctsio,
5587					      /*sks_valid*/ 0,
5588					      /*command*/ 1,
5589					      /*field*/ 0,
5590					      /*bit_valid*/ 0,
5591					      /*bit*/ 0);
5592			ctl_done((union ctl_io *)ctsio);
5593			return (CTL_RETVAL_COMPLETE);
5594		}
5595		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5596	}
5597
5598	len = lun->be_lun->blocksize;
5599
5600	/*
5601	 * If we've got a kernel request that hasn't been malloced yet,
5602	 * malloc it and tell the caller the data buffer is here.
5603	 */
5604	if ((byte2 & SWS_NDOB) == 0 &&
5605	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5606		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5607		ctsio->kern_data_len = len;
5608		ctsio->kern_total_len = len;
5609		ctsio->kern_data_resid = 0;
5610		ctsio->kern_rel_offset = 0;
5611		ctsio->kern_sg_entries = 0;
5612		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5613		ctsio->be_move_done = ctl_config_move_done;
5614		ctl_datamove((union ctl_io *)ctsio);
5615
5616		return (CTL_RETVAL_COMPLETE);
5617	}
5618
5619	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5620	lbalen->lba = lba;
5621	lbalen->len = num_blocks;
5622	lbalen->flags = byte2;
5623	retval = lun->backend->config_write((union ctl_io *)ctsio);
5624
5625	return (retval);
5626}
5627
5628int
5629ctl_unmap(struct ctl_scsiio *ctsio)
5630{
5631	struct ctl_lun *lun;
5632	struct scsi_unmap *cdb;
5633	struct ctl_ptr_len_flags *ptrlen;
5634	struct scsi_unmap_header *hdr;
5635	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5636	uint64_t lba;
5637	uint32_t num_blocks;
5638	int len, retval;
5639	uint8_t byte2;
5640
5641	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5642
5643	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5644	cdb = (struct scsi_unmap *)ctsio->cdb;
5645
5646	len = scsi_2btoul(cdb->length);
5647	byte2 = cdb->byte2;
5648
5649	/*
5650	 * If we've got a kernel request that hasn't been malloced yet,
5651	 * malloc it and tell the caller the data buffer is here.
5652	 */
5653	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5654		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5655		ctsio->kern_data_len = len;
5656		ctsio->kern_total_len = len;
5657		ctsio->kern_data_resid = 0;
5658		ctsio->kern_rel_offset = 0;
5659		ctsio->kern_sg_entries = 0;
5660		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5661		ctsio->be_move_done = ctl_config_move_done;
5662		ctl_datamove((union ctl_io *)ctsio);
5663
5664		return (CTL_RETVAL_COMPLETE);
5665	}
5666
5667	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5668	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5669	if (len < sizeof (*hdr) ||
5670	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5671	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5672	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5673		ctl_set_invalid_field(ctsio,
5674				      /*sks_valid*/ 0,
5675				      /*command*/ 0,
5676				      /*field*/ 0,
5677				      /*bit_valid*/ 0,
5678				      /*bit*/ 0);
5679		goto done;
5680	}
5681	len = scsi_2btoul(hdr->desc_length);
5682	buf = (struct scsi_unmap_desc *)(hdr + 1);
5683	end = buf + len / sizeof(*buf);
5684
5685	endnz = buf;
5686	for (range = buf; range < end; range++) {
5687		lba = scsi_8btou64(range->lba);
5688		num_blocks = scsi_4btoul(range->length);
5689		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5690		 || ((lba + num_blocks) < lba)) {
5691			ctl_set_lba_out_of_range(ctsio);
5692			ctl_done((union ctl_io *)ctsio);
5693			return (CTL_RETVAL_COMPLETE);
5694		}
5695		if (num_blocks != 0)
5696			endnz = range + 1;
5697	}
5698
5699	/*
5700	 * Block backend can not handle zero last range.
5701	 * Filter it out and return if there is nothing left.
5702	 */
5703	len = (uint8_t *)endnz - (uint8_t *)buf;
5704	if (len == 0) {
5705		ctl_set_success(ctsio);
5706		goto done;
5707	}
5708
5709	mtx_lock(&lun->lun_lock);
5710	ptrlen = (struct ctl_ptr_len_flags *)
5711	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5712	ptrlen->ptr = (void *)buf;
5713	ptrlen->len = len;
5714	ptrlen->flags = byte2;
5715	ctl_check_blocked(lun);
5716	mtx_unlock(&lun->lun_lock);
5717
5718	retval = lun->backend->config_write((union ctl_io *)ctsio);
5719	return (retval);
5720
5721done:
5722	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5723		free(ctsio->kern_data_ptr, M_CTL);
5724		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5725	}
5726	ctl_done((union ctl_io *)ctsio);
5727	return (CTL_RETVAL_COMPLETE);
5728}
5729
5730/*
5731 * Note that this function currently doesn't actually do anything inside
5732 * CTL to enforce things if the DQue bit is turned on.
5733 *
5734 * Also note that this function can't be used in the default case, because
5735 * the DQue bit isn't set in the changeable mask for the control mode page
5736 * anyway.  This is just here as an example for how to implement a page
5737 * handler, and a placeholder in case we want to allow the user to turn
5738 * tagged queueing on and off.
5739 *
5740 * The D_SENSE bit handling is functional, however, and will turn
5741 * descriptor sense on and off for a given LUN.
5742 */
5743int
5744ctl_control_page_handler(struct ctl_scsiio *ctsio,
5745			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5746{
5747	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5748	struct ctl_lun *lun;
5749	int set_ua;
5750	uint32_t initidx;
5751
5752	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5753	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5754	set_ua = 0;
5755
5756	user_cp = (struct scsi_control_page *)page_ptr;
5757	current_cp = (struct scsi_control_page *)
5758		(page_index->page_data + (page_index->page_len *
5759		CTL_PAGE_CURRENT));
5760	saved_cp = (struct scsi_control_page *)
5761		(page_index->page_data + (page_index->page_len *
5762		CTL_PAGE_SAVED));
5763
5764	mtx_lock(&lun->lun_lock);
5765	if (((current_cp->rlec & SCP_DSENSE) == 0)
5766	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5767		/*
5768		 * Descriptor sense is currently turned off and the user
5769		 * wants to turn it on.
5770		 */
5771		current_cp->rlec |= SCP_DSENSE;
5772		saved_cp->rlec |= SCP_DSENSE;
5773		lun->flags |= CTL_LUN_SENSE_DESC;
5774		set_ua = 1;
5775	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5776		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5777		/*
5778		 * Descriptor sense is currently turned on, and the user
5779		 * wants to turn it off.
5780		 */
5781		current_cp->rlec &= ~SCP_DSENSE;
5782		saved_cp->rlec &= ~SCP_DSENSE;
5783		lun->flags &= ~CTL_LUN_SENSE_DESC;
5784		set_ua = 1;
5785	}
5786	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5787	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5788		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5789		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5790		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5791		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5792		set_ua = 1;
5793	}
5794	if ((current_cp->eca_and_aen & SCP_SWP) !=
5795	    (user_cp->eca_and_aen & SCP_SWP)) {
5796		current_cp->eca_and_aen &= ~SCP_SWP;
5797		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5798		saved_cp->eca_and_aen &= ~SCP_SWP;
5799		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5800		set_ua = 1;
5801	}
5802	if (set_ua != 0)
5803		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5804	mtx_unlock(&lun->lun_lock);
5805	if (set_ua) {
5806		ctl_isc_announce_mode(lun,
5807		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5808		    page_index->page_code, page_index->subpage);
5809	}
5810	return (0);
5811}
5812
5813int
5814ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5815		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5816{
5817	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5818	struct ctl_lun *lun;
5819	int set_ua;
5820	uint32_t initidx;
5821
5822	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5823	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5824	set_ua = 0;
5825
5826	user_cp = (struct scsi_caching_page *)page_ptr;
5827	current_cp = (struct scsi_caching_page *)
5828		(page_index->page_data + (page_index->page_len *
5829		CTL_PAGE_CURRENT));
5830	saved_cp = (struct scsi_caching_page *)
5831		(page_index->page_data + (page_index->page_len *
5832		CTL_PAGE_SAVED));
5833
5834	mtx_lock(&lun->lun_lock);
5835	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5836	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5837		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5838		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5839		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5840		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5841		set_ua = 1;
5842	}
5843	if (set_ua != 0)
5844		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5845	mtx_unlock(&lun->lun_lock);
5846	if (set_ua) {
5847		ctl_isc_announce_mode(lun,
5848		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5849		    page_index->page_code, page_index->subpage);
5850	}
5851	return (0);
5852}
5853
5854int
5855ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5856				struct ctl_page_index *page_index,
5857				uint8_t *page_ptr)
5858{
5859	uint8_t *c;
5860	int i;
5861
5862	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5863	ctl_time_io_secs =
5864		(c[0] << 8) |
5865		(c[1] << 0) |
5866		0;
5867	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5868	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5869	printf("page data:");
5870	for (i=0; i<8; i++)
5871		printf(" %.2x",page_ptr[i]);
5872	printf("\n");
5873	return (0);
5874}
5875
5876int
5877ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5878			       struct ctl_page_index *page_index,
5879			       int pc)
5880{
5881	struct copan_debugconf_subpage *page;
5882
5883	page = (struct copan_debugconf_subpage *)page_index->page_data +
5884		(page_index->page_len * pc);
5885
5886	switch (pc) {
5887	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5888	case SMS_PAGE_CTRL_DEFAULT >> 6:
5889	case SMS_PAGE_CTRL_SAVED >> 6:
5890		/*
5891		 * We don't update the changable or default bits for this page.
5892		 */
5893		break;
5894	case SMS_PAGE_CTRL_CURRENT >> 6:
5895		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5896		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5897		break;
5898	default:
5899		break;
5900	}
5901	return (0);
5902}
5903
5904
5905static int
5906ctl_do_mode_select(union ctl_io *io)
5907{
5908	struct scsi_mode_page_header *page_header;
5909	struct ctl_page_index *page_index;
5910	struct ctl_scsiio *ctsio;
5911	int page_len, page_len_offset, page_len_size;
5912	union ctl_modepage_info *modepage_info;
5913	struct ctl_lun *lun;
5914	int *len_left, *len_used;
5915	int retval, i;
5916
5917	ctsio = &io->scsiio;
5918	page_index = NULL;
5919	page_len = 0;
5920	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5921
5922	modepage_info = (union ctl_modepage_info *)
5923		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5924	len_left = &modepage_info->header.len_left;
5925	len_used = &modepage_info->header.len_used;
5926
5927do_next_page:
5928
5929	page_header = (struct scsi_mode_page_header *)
5930		(ctsio->kern_data_ptr + *len_used);
5931
5932	if (*len_left == 0) {
5933		free(ctsio->kern_data_ptr, M_CTL);
5934		ctl_set_success(ctsio);
5935		ctl_done((union ctl_io *)ctsio);
5936		return (CTL_RETVAL_COMPLETE);
5937	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5938
5939		free(ctsio->kern_data_ptr, M_CTL);
5940		ctl_set_param_len_error(ctsio);
5941		ctl_done((union ctl_io *)ctsio);
5942		return (CTL_RETVAL_COMPLETE);
5943
5944	} else if ((page_header->page_code & SMPH_SPF)
5945		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5946
5947		free(ctsio->kern_data_ptr, M_CTL);
5948		ctl_set_param_len_error(ctsio);
5949		ctl_done((union ctl_io *)ctsio);
5950		return (CTL_RETVAL_COMPLETE);
5951	}
5952
5953
5954	/*
5955	 * XXX KDM should we do something with the block descriptor?
5956	 */
5957	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5958		page_index = &lun->mode_pages.index[i];
5959		if (lun->be_lun->lun_type == T_DIRECT &&
5960		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5961			continue;
5962		if (lun->be_lun->lun_type == T_PROCESSOR &&
5963		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5964			continue;
5965		if (lun->be_lun->lun_type == T_CDROM &&
5966		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5967			continue;
5968
5969		if ((page_index->page_code & SMPH_PC_MASK) !=
5970		    (page_header->page_code & SMPH_PC_MASK))
5971			continue;
5972
5973		/*
5974		 * If neither page has a subpage code, then we've got a
5975		 * match.
5976		 */
5977		if (((page_index->page_code & SMPH_SPF) == 0)
5978		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5979			page_len = page_header->page_length;
5980			break;
5981		}
5982
5983		/*
5984		 * If both pages have subpages, then the subpage numbers
5985		 * have to match.
5986		 */
5987		if ((page_index->page_code & SMPH_SPF)
5988		  && (page_header->page_code & SMPH_SPF)) {
5989			struct scsi_mode_page_header_sp *sph;
5990
5991			sph = (struct scsi_mode_page_header_sp *)page_header;
5992			if (page_index->subpage == sph->subpage) {
5993				page_len = scsi_2btoul(sph->page_length);
5994				break;
5995			}
5996		}
5997	}
5998
5999	/*
6000	 * If we couldn't find the page, or if we don't have a mode select
6001	 * handler for it, send back an error to the user.
6002	 */
6003	if ((i >= CTL_NUM_MODE_PAGES)
6004	 || (page_index->select_handler == NULL)) {
6005		ctl_set_invalid_field(ctsio,
6006				      /*sks_valid*/ 1,
6007				      /*command*/ 0,
6008				      /*field*/ *len_used,
6009				      /*bit_valid*/ 0,
6010				      /*bit*/ 0);
6011		free(ctsio->kern_data_ptr, M_CTL);
6012		ctl_done((union ctl_io *)ctsio);
6013		return (CTL_RETVAL_COMPLETE);
6014	}
6015
6016	if (page_index->page_code & SMPH_SPF) {
6017		page_len_offset = 2;
6018		page_len_size = 2;
6019	} else {
6020		page_len_size = 1;
6021		page_len_offset = 1;
6022	}
6023
6024	/*
6025	 * If the length the initiator gives us isn't the one we specify in
6026	 * the mode page header, or if they didn't specify enough data in
6027	 * the CDB to avoid truncating this page, kick out the request.
6028	 */
6029	if ((page_len != (page_index->page_len - page_len_offset -
6030			  page_len_size))
6031	 || (*len_left < page_index->page_len)) {
6032
6033
6034		ctl_set_invalid_field(ctsio,
6035				      /*sks_valid*/ 1,
6036				      /*command*/ 0,
6037				      /*field*/ *len_used + page_len_offset,
6038				      /*bit_valid*/ 0,
6039				      /*bit*/ 0);
6040		free(ctsio->kern_data_ptr, M_CTL);
6041		ctl_done((union ctl_io *)ctsio);
6042		return (CTL_RETVAL_COMPLETE);
6043	}
6044
6045	/*
6046	 * Run through the mode page, checking to make sure that the bits
6047	 * the user changed are actually legal for him to change.
6048	 */
6049	for (i = 0; i < page_index->page_len; i++) {
6050		uint8_t *user_byte, *change_mask, *current_byte;
6051		int bad_bit;
6052		int j;
6053
6054		user_byte = (uint8_t *)page_header + i;
6055		change_mask = page_index->page_data +
6056			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6057		current_byte = page_index->page_data +
6058			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6059
6060		/*
6061		 * Check to see whether the user set any bits in this byte
6062		 * that he is not allowed to set.
6063		 */
6064		if ((*user_byte & ~(*change_mask)) ==
6065		    (*current_byte & ~(*change_mask)))
6066			continue;
6067
6068		/*
6069		 * Go through bit by bit to determine which one is illegal.
6070		 */
6071		bad_bit = 0;
6072		for (j = 7; j >= 0; j--) {
6073			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6074			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6075				bad_bit = i;
6076				break;
6077			}
6078		}
6079		ctl_set_invalid_field(ctsio,
6080				      /*sks_valid*/ 1,
6081				      /*command*/ 0,
6082				      /*field*/ *len_used + i,
6083				      /*bit_valid*/ 1,
6084				      /*bit*/ bad_bit);
6085		free(ctsio->kern_data_ptr, M_CTL);
6086		ctl_done((union ctl_io *)ctsio);
6087		return (CTL_RETVAL_COMPLETE);
6088	}
6089
6090	/*
6091	 * Decrement these before we call the page handler, since we may
6092	 * end up getting called back one way or another before the handler
6093	 * returns to this context.
6094	 */
6095	*len_left -= page_index->page_len;
6096	*len_used += page_index->page_len;
6097
6098	retval = page_index->select_handler(ctsio, page_index,
6099					    (uint8_t *)page_header);
6100
6101	/*
6102	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6103	 * wait until this queued command completes to finish processing
6104	 * the mode page.  If it returns anything other than
6105	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6106	 * already set the sense information, freed the data pointer, and
6107	 * completed the io for us.
6108	 */
6109	if (retval != CTL_RETVAL_COMPLETE)
6110		goto bailout_no_done;
6111
6112	/*
6113	 * If the initiator sent us more than one page, parse the next one.
6114	 */
6115	if (*len_left > 0)
6116		goto do_next_page;
6117
6118	ctl_set_success(ctsio);
6119	free(ctsio->kern_data_ptr, M_CTL);
6120	ctl_done((union ctl_io *)ctsio);
6121
6122bailout_no_done:
6123
6124	return (CTL_RETVAL_COMPLETE);
6125
6126}
6127
6128int
6129ctl_mode_select(struct ctl_scsiio *ctsio)
6130{
6131	int param_len, pf, sp;
6132	int header_size, bd_len;
6133	union ctl_modepage_info *modepage_info;
6134
6135	switch (ctsio->cdb[0]) {
6136	case MODE_SELECT_6: {
6137		struct scsi_mode_select_6 *cdb;
6138
6139		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6140
6141		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6142		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6143		param_len = cdb->length;
6144		header_size = sizeof(struct scsi_mode_header_6);
6145		break;
6146	}
6147	case MODE_SELECT_10: {
6148		struct scsi_mode_select_10 *cdb;
6149
6150		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6151
6152		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6153		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6154		param_len = scsi_2btoul(cdb->length);
6155		header_size = sizeof(struct scsi_mode_header_10);
6156		break;
6157	}
6158	default:
6159		ctl_set_invalid_opcode(ctsio);
6160		ctl_done((union ctl_io *)ctsio);
6161		return (CTL_RETVAL_COMPLETE);
6162	}
6163
6164	/*
6165	 * From SPC-3:
6166	 * "A parameter list length of zero indicates that the Data-Out Buffer
6167	 * shall be empty. This condition shall not be considered as an error."
6168	 */
6169	if (param_len == 0) {
6170		ctl_set_success(ctsio);
6171		ctl_done((union ctl_io *)ctsio);
6172		return (CTL_RETVAL_COMPLETE);
6173	}
6174
6175	/*
6176	 * Since we'll hit this the first time through, prior to
6177	 * allocation, we don't need to free a data buffer here.
6178	 */
6179	if (param_len < header_size) {
6180		ctl_set_param_len_error(ctsio);
6181		ctl_done((union ctl_io *)ctsio);
6182		return (CTL_RETVAL_COMPLETE);
6183	}
6184
6185	/*
6186	 * Allocate the data buffer and grab the user's data.  In theory,
6187	 * we shouldn't have to sanity check the parameter list length here
6188	 * because the maximum size is 64K.  We should be able to malloc
6189	 * that much without too many problems.
6190	 */
6191	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6192		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6193		ctsio->kern_data_len = param_len;
6194		ctsio->kern_total_len = param_len;
6195		ctsio->kern_data_resid = 0;
6196		ctsio->kern_rel_offset = 0;
6197		ctsio->kern_sg_entries = 0;
6198		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6199		ctsio->be_move_done = ctl_config_move_done;
6200		ctl_datamove((union ctl_io *)ctsio);
6201
6202		return (CTL_RETVAL_COMPLETE);
6203	}
6204
6205	switch (ctsio->cdb[0]) {
6206	case MODE_SELECT_6: {
6207		struct scsi_mode_header_6 *mh6;
6208
6209		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6210		bd_len = mh6->blk_desc_len;
6211		break;
6212	}
6213	case MODE_SELECT_10: {
6214		struct scsi_mode_header_10 *mh10;
6215
6216		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6217		bd_len = scsi_2btoul(mh10->blk_desc_len);
6218		break;
6219	}
6220	default:
6221		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6222		break;
6223	}
6224
6225	if (param_len < (header_size + bd_len)) {
6226		free(ctsio->kern_data_ptr, M_CTL);
6227		ctl_set_param_len_error(ctsio);
6228		ctl_done((union ctl_io *)ctsio);
6229		return (CTL_RETVAL_COMPLETE);
6230	}
6231
6232	/*
6233	 * Set the IO_CONT flag, so that if this I/O gets passed to
6234	 * ctl_config_write_done(), it'll get passed back to
6235	 * ctl_do_mode_select() for further processing, or completion if
6236	 * we're all done.
6237	 */
6238	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6239	ctsio->io_cont = ctl_do_mode_select;
6240
6241	modepage_info = (union ctl_modepage_info *)
6242		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6243	memset(modepage_info, 0, sizeof(*modepage_info));
6244	modepage_info->header.len_left = param_len - header_size - bd_len;
6245	modepage_info->header.len_used = header_size + bd_len;
6246
6247	return (ctl_do_mode_select((union ctl_io *)ctsio));
6248}
6249
6250int
6251ctl_mode_sense(struct ctl_scsiio *ctsio)
6252{
6253	struct ctl_lun *lun;
6254	int pc, page_code, dbd, llba, subpage;
6255	int alloc_len, page_len, header_len, total_len;
6256	struct scsi_mode_block_descr *block_desc;
6257	struct ctl_page_index *page_index;
6258
6259	dbd = 0;
6260	llba = 0;
6261	block_desc = NULL;
6262
6263	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6264
6265	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6266	switch (ctsio->cdb[0]) {
6267	case MODE_SENSE_6: {
6268		struct scsi_mode_sense_6 *cdb;
6269
6270		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6271
6272		header_len = sizeof(struct scsi_mode_hdr_6);
6273		if (cdb->byte2 & SMS_DBD)
6274			dbd = 1;
6275		else
6276			header_len += sizeof(struct scsi_mode_block_descr);
6277
6278		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6279		page_code = cdb->page & SMS_PAGE_CODE;
6280		subpage = cdb->subpage;
6281		alloc_len = cdb->length;
6282		break;
6283	}
6284	case MODE_SENSE_10: {
6285		struct scsi_mode_sense_10 *cdb;
6286
6287		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6288
6289		header_len = sizeof(struct scsi_mode_hdr_10);
6290
6291		if (cdb->byte2 & SMS_DBD)
6292			dbd = 1;
6293		else
6294			header_len += sizeof(struct scsi_mode_block_descr);
6295		if (cdb->byte2 & SMS10_LLBAA)
6296			llba = 1;
6297		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6298		page_code = cdb->page & SMS_PAGE_CODE;
6299		subpage = cdb->subpage;
6300		alloc_len = scsi_2btoul(cdb->length);
6301		break;
6302	}
6303	default:
6304		ctl_set_invalid_opcode(ctsio);
6305		ctl_done((union ctl_io *)ctsio);
6306		return (CTL_RETVAL_COMPLETE);
6307		break; /* NOTREACHED */
6308	}
6309
6310	/*
6311	 * We have to make a first pass through to calculate the size of
6312	 * the pages that match the user's query.  Then we allocate enough
6313	 * memory to hold it, and actually copy the data into the buffer.
6314	 */
6315	switch (page_code) {
6316	case SMS_ALL_PAGES_PAGE: {
6317		int i;
6318
6319		page_len = 0;
6320
6321		/*
6322		 * At the moment, values other than 0 and 0xff here are
6323		 * reserved according to SPC-3.
6324		 */
6325		if ((subpage != SMS_SUBPAGE_PAGE_0)
6326		 && (subpage != SMS_SUBPAGE_ALL)) {
6327			ctl_set_invalid_field(ctsio,
6328					      /*sks_valid*/ 1,
6329					      /*command*/ 1,
6330					      /*field*/ 3,
6331					      /*bit_valid*/ 0,
6332					      /*bit*/ 0);
6333			ctl_done((union ctl_io *)ctsio);
6334			return (CTL_RETVAL_COMPLETE);
6335		}
6336
6337		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6338			page_index = &lun->mode_pages.index[i];
6339
6340			/* Make sure the page is supported for this dev type */
6341			if (lun->be_lun->lun_type == T_DIRECT &&
6342			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6343				continue;
6344			if (lun->be_lun->lun_type == T_PROCESSOR &&
6345			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6346				continue;
6347			if (lun->be_lun->lun_type == T_CDROM &&
6348			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6349				continue;
6350
6351			/*
6352			 * We don't use this subpage if the user didn't
6353			 * request all subpages.
6354			 */
6355			if ((page_index->subpage != 0)
6356			 && (subpage == SMS_SUBPAGE_PAGE_0))
6357				continue;
6358
6359#if 0
6360			printf("found page %#x len %d\n",
6361			       page_index->page_code & SMPH_PC_MASK,
6362			       page_index->page_len);
6363#endif
6364			page_len += page_index->page_len;
6365		}
6366		break;
6367	}
6368	default: {
6369		int i;
6370
6371		page_len = 0;
6372
6373		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6374			page_index = &lun->mode_pages.index[i];
6375
6376			/* Make sure the page is supported for this dev type */
6377			if (lun->be_lun->lun_type == T_DIRECT &&
6378			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6379				continue;
6380			if (lun->be_lun->lun_type == T_PROCESSOR &&
6381			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6382				continue;
6383			if (lun->be_lun->lun_type == T_CDROM &&
6384			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6385				continue;
6386
6387			/* Look for the right page code */
6388			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6389				continue;
6390
6391			/* Look for the right subpage or the subpage wildcard*/
6392			if ((page_index->subpage != subpage)
6393			 && (subpage != SMS_SUBPAGE_ALL))
6394				continue;
6395
6396#if 0
6397			printf("found page %#x len %d\n",
6398			       page_index->page_code & SMPH_PC_MASK,
6399			       page_index->page_len);
6400#endif
6401
6402			page_len += page_index->page_len;
6403		}
6404
6405		if (page_len == 0) {
6406			ctl_set_invalid_field(ctsio,
6407					      /*sks_valid*/ 1,
6408					      /*command*/ 1,
6409					      /*field*/ 2,
6410					      /*bit_valid*/ 1,
6411					      /*bit*/ 5);
6412			ctl_done((union ctl_io *)ctsio);
6413			return (CTL_RETVAL_COMPLETE);
6414		}
6415		break;
6416	}
6417	}
6418
6419	total_len = header_len + page_len;
6420#if 0
6421	printf("header_len = %d, page_len = %d, total_len = %d\n",
6422	       header_len, page_len, total_len);
6423#endif
6424
6425	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6426	ctsio->kern_sg_entries = 0;
6427	ctsio->kern_data_resid = 0;
6428	ctsio->kern_rel_offset = 0;
6429	if (total_len < alloc_len) {
6430		ctsio->residual = alloc_len - total_len;
6431		ctsio->kern_data_len = total_len;
6432		ctsio->kern_total_len = total_len;
6433	} else {
6434		ctsio->residual = 0;
6435		ctsio->kern_data_len = alloc_len;
6436		ctsio->kern_total_len = alloc_len;
6437	}
6438
6439	switch (ctsio->cdb[0]) {
6440	case MODE_SENSE_6: {
6441		struct scsi_mode_hdr_6 *header;
6442
6443		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6444
6445		header->datalen = MIN(total_len - 1, 254);
6446		if (lun->be_lun->lun_type == T_DIRECT) {
6447			header->dev_specific = 0x10; /* DPOFUA */
6448			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6449			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6450			    .eca_and_aen & SCP_SWP) != 0)
6451				    header->dev_specific |= 0x80; /* WP */
6452		}
6453		if (dbd)
6454			header->block_descr_len = 0;
6455		else
6456			header->block_descr_len =
6457				sizeof(struct scsi_mode_block_descr);
6458		block_desc = (struct scsi_mode_block_descr *)&header[1];
6459		break;
6460	}
6461	case MODE_SENSE_10: {
6462		struct scsi_mode_hdr_10 *header;
6463		int datalen;
6464
6465		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6466
6467		datalen = MIN(total_len - 2, 65533);
6468		scsi_ulto2b(datalen, header->datalen);
6469		if (lun->be_lun->lun_type == T_DIRECT) {
6470			header->dev_specific = 0x10; /* DPOFUA */
6471			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6472			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6473			    .eca_and_aen & SCP_SWP) != 0)
6474				    header->dev_specific |= 0x80; /* WP */
6475		}
6476		if (dbd)
6477			scsi_ulto2b(0, header->block_descr_len);
6478		else
6479			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6480				    header->block_descr_len);
6481		block_desc = (struct scsi_mode_block_descr *)&header[1];
6482		break;
6483	}
6484	default:
6485		panic("invalid CDB type %#x", ctsio->cdb[0]);
6486		break; /* NOTREACHED */
6487	}
6488
6489	/*
6490	 * If we've got a disk, use its blocksize in the block
6491	 * descriptor.  Otherwise, just set it to 0.
6492	 */
6493	if (dbd == 0) {
6494		if (lun->be_lun->lun_type == T_DIRECT)
6495			scsi_ulto3b(lun->be_lun->blocksize,
6496				    block_desc->block_len);
6497		else
6498			scsi_ulto3b(0, block_desc->block_len);
6499	}
6500
6501	switch (page_code) {
6502	case SMS_ALL_PAGES_PAGE: {
6503		int i, data_used;
6504
6505		data_used = header_len;
6506		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6507			struct ctl_page_index *page_index;
6508
6509			page_index = &lun->mode_pages.index[i];
6510			if (lun->be_lun->lun_type == T_DIRECT &&
6511			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6512				continue;
6513			if (lun->be_lun->lun_type == T_PROCESSOR &&
6514			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6515				continue;
6516			if (lun->be_lun->lun_type == T_CDROM &&
6517			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6518				continue;
6519
6520			/*
6521			 * We don't use this subpage if the user didn't
6522			 * request all subpages.  We already checked (above)
6523			 * to make sure the user only specified a subpage
6524			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6525			 */
6526			if ((page_index->subpage != 0)
6527			 && (subpage == SMS_SUBPAGE_PAGE_0))
6528				continue;
6529
6530			/*
6531			 * Call the handler, if it exists, to update the
6532			 * page to the latest values.
6533			 */
6534			if (page_index->sense_handler != NULL)
6535				page_index->sense_handler(ctsio, page_index,pc);
6536
6537			memcpy(ctsio->kern_data_ptr + data_used,
6538			       page_index->page_data +
6539			       (page_index->page_len * pc),
6540			       page_index->page_len);
6541			data_used += page_index->page_len;
6542		}
6543		break;
6544	}
6545	default: {
6546		int i, data_used;
6547
6548		data_used = header_len;
6549
6550		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6551			struct ctl_page_index *page_index;
6552
6553			page_index = &lun->mode_pages.index[i];
6554
6555			/* Look for the right page code */
6556			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6557				continue;
6558
6559			/* Look for the right subpage or the subpage wildcard*/
6560			if ((page_index->subpage != subpage)
6561			 && (subpage != SMS_SUBPAGE_ALL))
6562				continue;
6563
6564			/* Make sure the page is supported for this dev type */
6565			if (lun->be_lun->lun_type == T_DIRECT &&
6566			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6567				continue;
6568			if (lun->be_lun->lun_type == T_PROCESSOR &&
6569			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6570				continue;
6571			if (lun->be_lun->lun_type == T_CDROM &&
6572			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6573				continue;
6574
6575			/*
6576			 * Call the handler, if it exists, to update the
6577			 * page to the latest values.
6578			 */
6579			if (page_index->sense_handler != NULL)
6580				page_index->sense_handler(ctsio, page_index,pc);
6581
6582			memcpy(ctsio->kern_data_ptr + data_used,
6583			       page_index->page_data +
6584			       (page_index->page_len * pc),
6585			       page_index->page_len);
6586			data_used += page_index->page_len;
6587		}
6588		break;
6589	}
6590	}
6591
6592	ctl_set_success(ctsio);
6593	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6594	ctsio->be_move_done = ctl_config_move_done;
6595	ctl_datamove((union ctl_io *)ctsio);
6596	return (CTL_RETVAL_COMPLETE);
6597}
6598
6599int
6600ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6601			       struct ctl_page_index *page_index,
6602			       int pc)
6603{
6604	struct ctl_lun *lun;
6605	struct scsi_log_param_header *phdr;
6606	uint8_t *data;
6607	uint64_t val;
6608
6609	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6610	data = page_index->page_data;
6611
6612	if (lun->backend->lun_attr != NULL &&
6613	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6614	     != UINT64_MAX) {
6615		phdr = (struct scsi_log_param_header *)data;
6616		scsi_ulto2b(0x0001, phdr->param_code);
6617		phdr->param_control = SLP_LBIN | SLP_LP;
6618		phdr->param_len = 8;
6619		data = (uint8_t *)(phdr + 1);
6620		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6621		data[4] = 0x02; /* per-pool */
6622		data += phdr->param_len;
6623	}
6624
6625	if (lun->backend->lun_attr != NULL &&
6626	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6627	     != UINT64_MAX) {
6628		phdr = (struct scsi_log_param_header *)data;
6629		scsi_ulto2b(0x0002, phdr->param_code);
6630		phdr->param_control = SLP_LBIN | SLP_LP;
6631		phdr->param_len = 8;
6632		data = (uint8_t *)(phdr + 1);
6633		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6634		data[4] = 0x01; /* per-LUN */
6635		data += phdr->param_len;
6636	}
6637
6638	if (lun->backend->lun_attr != NULL &&
6639	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6640	     != UINT64_MAX) {
6641		phdr = (struct scsi_log_param_header *)data;
6642		scsi_ulto2b(0x00f1, phdr->param_code);
6643		phdr->param_control = SLP_LBIN | SLP_LP;
6644		phdr->param_len = 8;
6645		data = (uint8_t *)(phdr + 1);
6646		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6647		data[4] = 0x02; /* per-pool */
6648		data += phdr->param_len;
6649	}
6650
6651	if (lun->backend->lun_attr != NULL &&
6652	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6653	     != UINT64_MAX) {
6654		phdr = (struct scsi_log_param_header *)data;
6655		scsi_ulto2b(0x00f2, phdr->param_code);
6656		phdr->param_control = SLP_LBIN | SLP_LP;
6657		phdr->param_len = 8;
6658		data = (uint8_t *)(phdr + 1);
6659		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6660		data[4] = 0x02; /* per-pool */
6661		data += phdr->param_len;
6662	}
6663
6664	page_index->page_len = data - page_index->page_data;
6665	return (0);
6666}
6667
6668int
6669ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6670			       struct ctl_page_index *page_index,
6671			       int pc)
6672{
6673	struct ctl_lun *lun;
6674	struct stat_page *data;
6675	uint64_t rn, wn, rb, wb;
6676	struct bintime rt, wt;
6677	int i;
6678
6679	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6680	data = (struct stat_page *)page_index->page_data;
6681
6682	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6683	data->sap.hdr.param_control = SLP_LBIN;
6684	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6685	    sizeof(struct scsi_log_param_header);
6686	rn = wn = rb = wb = 0;
6687	bintime_clear(&rt);
6688	bintime_clear(&wt);
6689	for (i = 0; i < CTL_MAX_PORTS; i++) {
6690		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6691		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6692		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6693		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6694		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6695		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6696	}
6697	scsi_u64to8b(rn, data->sap.read_num);
6698	scsi_u64to8b(wn, data->sap.write_num);
6699	if (lun->stats.blocksize > 0) {
6700		scsi_u64to8b(wb / lun->stats.blocksize,
6701		    data->sap.recvieved_lba);
6702		scsi_u64to8b(rb / lun->stats.blocksize,
6703		    data->sap.transmitted_lba);
6704	}
6705	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6706	    data->sap.read_int);
6707	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6708	    data->sap.write_int);
6709	scsi_u64to8b(0, data->sap.weighted_num);
6710	scsi_u64to8b(0, data->sap.weighted_int);
6711	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6712	data->it.hdr.param_control = SLP_LBIN;
6713	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6714	    sizeof(struct scsi_log_param_header);
6715#ifdef CTL_TIME_IO
6716	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6717#endif
6718	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6719	data->it.hdr.param_control = SLP_LBIN;
6720	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6721	    sizeof(struct scsi_log_param_header);
6722	scsi_ulto4b(3, data->ti.exponent);
6723	scsi_ulto4b(1, data->ti.integer);
6724
6725	page_index->page_len = sizeof(*data);
6726	return (0);
6727}
6728
6729int
6730ctl_log_sense(struct ctl_scsiio *ctsio)
6731{
6732	struct ctl_lun *lun;
6733	int i, pc, page_code, subpage;
6734	int alloc_len, total_len;
6735	struct ctl_page_index *page_index;
6736	struct scsi_log_sense *cdb;
6737	struct scsi_log_header *header;
6738
6739	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6740
6741	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6742	cdb = (struct scsi_log_sense *)ctsio->cdb;
6743	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6744	page_code = cdb->page & SLS_PAGE_CODE;
6745	subpage = cdb->subpage;
6746	alloc_len = scsi_2btoul(cdb->length);
6747
6748	page_index = NULL;
6749	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6750		page_index = &lun->log_pages.index[i];
6751
6752		/* Look for the right page code */
6753		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6754			continue;
6755
6756		/* Look for the right subpage or the subpage wildcard*/
6757		if (page_index->subpage != subpage)
6758			continue;
6759
6760		break;
6761	}
6762	if (i >= CTL_NUM_LOG_PAGES) {
6763		ctl_set_invalid_field(ctsio,
6764				      /*sks_valid*/ 1,
6765				      /*command*/ 1,
6766				      /*field*/ 2,
6767				      /*bit_valid*/ 0,
6768				      /*bit*/ 0);
6769		ctl_done((union ctl_io *)ctsio);
6770		return (CTL_RETVAL_COMPLETE);
6771	}
6772
6773	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6774
6775	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6776	ctsio->kern_sg_entries = 0;
6777	ctsio->kern_data_resid = 0;
6778	ctsio->kern_rel_offset = 0;
6779	if (total_len < alloc_len) {
6780		ctsio->residual = alloc_len - total_len;
6781		ctsio->kern_data_len = total_len;
6782		ctsio->kern_total_len = total_len;
6783	} else {
6784		ctsio->residual = 0;
6785		ctsio->kern_data_len = alloc_len;
6786		ctsio->kern_total_len = alloc_len;
6787	}
6788
6789	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6790	header->page = page_index->page_code;
6791	if (page_index->subpage) {
6792		header->page |= SL_SPF;
6793		header->subpage = page_index->subpage;
6794	}
6795	scsi_ulto2b(page_index->page_len, header->datalen);
6796
6797	/*
6798	 * Call the handler, if it exists, to update the
6799	 * page to the latest values.
6800	 */
6801	if (page_index->sense_handler != NULL)
6802		page_index->sense_handler(ctsio, page_index, pc);
6803
6804	memcpy(header + 1, page_index->page_data, page_index->page_len);
6805
6806	ctl_set_success(ctsio);
6807	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6808	ctsio->be_move_done = ctl_config_move_done;
6809	ctl_datamove((union ctl_io *)ctsio);
6810	return (CTL_RETVAL_COMPLETE);
6811}
6812
6813int
6814ctl_read_capacity(struct ctl_scsiio *ctsio)
6815{
6816	struct scsi_read_capacity *cdb;
6817	struct scsi_read_capacity_data *data;
6818	struct ctl_lun *lun;
6819	uint32_t lba;
6820
6821	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6822
6823	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6824
6825	lba = scsi_4btoul(cdb->addr);
6826	if (((cdb->pmi & SRC_PMI) == 0)
6827	 && (lba != 0)) {
6828		ctl_set_invalid_field(/*ctsio*/ ctsio,
6829				      /*sks_valid*/ 1,
6830				      /*command*/ 1,
6831				      /*field*/ 2,
6832				      /*bit_valid*/ 0,
6833				      /*bit*/ 0);
6834		ctl_done((union ctl_io *)ctsio);
6835		return (CTL_RETVAL_COMPLETE);
6836	}
6837
6838	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6839
6840	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6841	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6842	ctsio->residual = 0;
6843	ctsio->kern_data_len = sizeof(*data);
6844	ctsio->kern_total_len = sizeof(*data);
6845	ctsio->kern_data_resid = 0;
6846	ctsio->kern_rel_offset = 0;
6847	ctsio->kern_sg_entries = 0;
6848
6849	/*
6850	 * If the maximum LBA is greater than 0xfffffffe, the user must
6851	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6852	 * serivce action set.
6853	 */
6854	if (lun->be_lun->maxlba > 0xfffffffe)
6855		scsi_ulto4b(0xffffffff, data->addr);
6856	else
6857		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6858
6859	/*
6860	 * XXX KDM this may not be 512 bytes...
6861	 */
6862	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6863
6864	ctl_set_success(ctsio);
6865	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6866	ctsio->be_move_done = ctl_config_move_done;
6867	ctl_datamove((union ctl_io *)ctsio);
6868	return (CTL_RETVAL_COMPLETE);
6869}
6870
6871int
6872ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6873{
6874	struct scsi_read_capacity_16 *cdb;
6875	struct scsi_read_capacity_data_long *data;
6876	struct ctl_lun *lun;
6877	uint64_t lba;
6878	uint32_t alloc_len;
6879
6880	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6881
6882	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6883
6884	alloc_len = scsi_4btoul(cdb->alloc_len);
6885	lba = scsi_8btou64(cdb->addr);
6886
6887	if ((cdb->reladr & SRC16_PMI)
6888	 && (lba != 0)) {
6889		ctl_set_invalid_field(/*ctsio*/ ctsio,
6890				      /*sks_valid*/ 1,
6891				      /*command*/ 1,
6892				      /*field*/ 2,
6893				      /*bit_valid*/ 0,
6894				      /*bit*/ 0);
6895		ctl_done((union ctl_io *)ctsio);
6896		return (CTL_RETVAL_COMPLETE);
6897	}
6898
6899	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6900
6901	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6902	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6903
6904	if (sizeof(*data) < alloc_len) {
6905		ctsio->residual = alloc_len - sizeof(*data);
6906		ctsio->kern_data_len = sizeof(*data);
6907		ctsio->kern_total_len = sizeof(*data);
6908	} else {
6909		ctsio->residual = 0;
6910		ctsio->kern_data_len = alloc_len;
6911		ctsio->kern_total_len = alloc_len;
6912	}
6913	ctsio->kern_data_resid = 0;
6914	ctsio->kern_rel_offset = 0;
6915	ctsio->kern_sg_entries = 0;
6916
6917	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6918	/* XXX KDM this may not be 512 bytes... */
6919	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6920	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6921	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6922	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6923		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6924
6925	ctl_set_success(ctsio);
6926	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6927	ctsio->be_move_done = ctl_config_move_done;
6928	ctl_datamove((union ctl_io *)ctsio);
6929	return (CTL_RETVAL_COMPLETE);
6930}
6931
6932int
6933ctl_get_lba_status(struct ctl_scsiio *ctsio)
6934{
6935	struct scsi_get_lba_status *cdb;
6936	struct scsi_get_lba_status_data *data;
6937	struct ctl_lun *lun;
6938	struct ctl_lba_len_flags *lbalen;
6939	uint64_t lba;
6940	uint32_t alloc_len, total_len;
6941	int retval;
6942
6943	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6944
6945	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6946	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6947	lba = scsi_8btou64(cdb->addr);
6948	alloc_len = scsi_4btoul(cdb->alloc_len);
6949
6950	if (lba > lun->be_lun->maxlba) {
6951		ctl_set_lba_out_of_range(ctsio);
6952		ctl_done((union ctl_io *)ctsio);
6953		return (CTL_RETVAL_COMPLETE);
6954	}
6955
6956	total_len = sizeof(*data) + sizeof(data->descr[0]);
6957	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6958	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6959
6960	if (total_len < alloc_len) {
6961		ctsio->residual = alloc_len - total_len;
6962		ctsio->kern_data_len = total_len;
6963		ctsio->kern_total_len = total_len;
6964	} else {
6965		ctsio->residual = 0;
6966		ctsio->kern_data_len = alloc_len;
6967		ctsio->kern_total_len = alloc_len;
6968	}
6969	ctsio->kern_data_resid = 0;
6970	ctsio->kern_rel_offset = 0;
6971	ctsio->kern_sg_entries = 0;
6972
6973	/* Fill dummy data in case backend can't tell anything. */
6974	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6975	scsi_u64to8b(lba, data->descr[0].addr);
6976	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6977	    data->descr[0].length);
6978	data->descr[0].status = 0; /* Mapped or unknown. */
6979
6980	ctl_set_success(ctsio);
6981	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6982	ctsio->be_move_done = ctl_config_move_done;
6983
6984	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6985	lbalen->lba = lba;
6986	lbalen->len = total_len;
6987	lbalen->flags = 0;
6988	retval = lun->backend->config_read((union ctl_io *)ctsio);
6989	return (CTL_RETVAL_COMPLETE);
6990}
6991
6992int
6993ctl_read_defect(struct ctl_scsiio *ctsio)
6994{
6995	struct scsi_read_defect_data_10 *ccb10;
6996	struct scsi_read_defect_data_12 *ccb12;
6997	struct scsi_read_defect_data_hdr_10 *data10;
6998	struct scsi_read_defect_data_hdr_12 *data12;
6999	uint32_t alloc_len, data_len;
7000	uint8_t format;
7001
7002	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7003
7004	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7005		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7006		format = ccb10->format;
7007		alloc_len = scsi_2btoul(ccb10->alloc_length);
7008		data_len = sizeof(*data10);
7009	} else {
7010		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7011		format = ccb12->format;
7012		alloc_len = scsi_4btoul(ccb12->alloc_length);
7013		data_len = sizeof(*data12);
7014	}
7015	if (alloc_len == 0) {
7016		ctl_set_success(ctsio);
7017		ctl_done((union ctl_io *)ctsio);
7018		return (CTL_RETVAL_COMPLETE);
7019	}
7020
7021	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7022	if (data_len < alloc_len) {
7023		ctsio->residual = alloc_len - data_len;
7024		ctsio->kern_data_len = data_len;
7025		ctsio->kern_total_len = data_len;
7026	} else {
7027		ctsio->residual = 0;
7028		ctsio->kern_data_len = alloc_len;
7029		ctsio->kern_total_len = alloc_len;
7030	}
7031	ctsio->kern_data_resid = 0;
7032	ctsio->kern_rel_offset = 0;
7033	ctsio->kern_sg_entries = 0;
7034
7035	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7036		data10 = (struct scsi_read_defect_data_hdr_10 *)
7037		    ctsio->kern_data_ptr;
7038		data10->format = format;
7039		scsi_ulto2b(0, data10->length);
7040	} else {
7041		data12 = (struct scsi_read_defect_data_hdr_12 *)
7042		    ctsio->kern_data_ptr;
7043		data12->format = format;
7044		scsi_ulto2b(0, data12->generation);
7045		scsi_ulto4b(0, data12->length);
7046	}
7047
7048	ctl_set_success(ctsio);
7049	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7050	ctsio->be_move_done = ctl_config_move_done;
7051	ctl_datamove((union ctl_io *)ctsio);
7052	return (CTL_RETVAL_COMPLETE);
7053}
7054
7055int
7056ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7057{
7058	struct scsi_maintenance_in *cdb;
7059	int retval;
7060	int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7061	int num_target_port_groups, num_target_ports;
7062	struct ctl_lun *lun;
7063	struct ctl_softc *softc;
7064	struct ctl_port *port;
7065	struct scsi_target_group_data *rtg_ptr;
7066	struct scsi_target_group_data_extended *rtg_ext_ptr;
7067	struct scsi_target_port_group_descriptor *tpg_desc;
7068
7069	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7070
7071	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7072	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7073	softc = lun->ctl_softc;
7074
7075	retval = CTL_RETVAL_COMPLETE;
7076
7077	switch (cdb->byte2 & STG_PDF_MASK) {
7078	case STG_PDF_LENGTH:
7079		ext = 0;
7080		break;
7081	case STG_PDF_EXTENDED:
7082		ext = 1;
7083		break;
7084	default:
7085		ctl_set_invalid_field(/*ctsio*/ ctsio,
7086				      /*sks_valid*/ 1,
7087				      /*command*/ 1,
7088				      /*field*/ 2,
7089				      /*bit_valid*/ 1,
7090				      /*bit*/ 5);
7091		ctl_done((union ctl_io *)ctsio);
7092		return(retval);
7093	}
7094
7095	if (softc->is_single)
7096		num_target_port_groups = 1;
7097	else
7098		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7099	num_target_ports = 0;
7100	mtx_lock(&softc->ctl_lock);
7101	STAILQ_FOREACH(port, &softc->port_list, links) {
7102		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7103			continue;
7104		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7105			continue;
7106		num_target_ports++;
7107	}
7108	mtx_unlock(&softc->ctl_lock);
7109
7110	if (ext)
7111		total_len = sizeof(struct scsi_target_group_data_extended);
7112	else
7113		total_len = sizeof(struct scsi_target_group_data);
7114	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7115		num_target_port_groups +
7116	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7117
7118	alloc_len = scsi_4btoul(cdb->length);
7119
7120	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7121
7122	ctsio->kern_sg_entries = 0;
7123
7124	if (total_len < alloc_len) {
7125		ctsio->residual = alloc_len - total_len;
7126		ctsio->kern_data_len = total_len;
7127		ctsio->kern_total_len = total_len;
7128	} else {
7129		ctsio->residual = 0;
7130		ctsio->kern_data_len = alloc_len;
7131		ctsio->kern_total_len = alloc_len;
7132	}
7133	ctsio->kern_data_resid = 0;
7134	ctsio->kern_rel_offset = 0;
7135
7136	if (ext) {
7137		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7138		    ctsio->kern_data_ptr;
7139		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7140		rtg_ext_ptr->format_type = 0x10;
7141		rtg_ext_ptr->implicit_transition_time = 0;
7142		tpg_desc = &rtg_ext_ptr->groups[0];
7143	} else {
7144		rtg_ptr = (struct scsi_target_group_data *)
7145		    ctsio->kern_data_ptr;
7146		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7147		tpg_desc = &rtg_ptr->groups[0];
7148	}
7149
7150	mtx_lock(&softc->ctl_lock);
7151	pg = softc->port_min / softc->port_cnt;
7152	if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7153		gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7154	else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7155		gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7156	else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7157		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7158	else
7159		gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7160	if (lun->flags & CTL_LUN_PRIMARY_SC) {
7161		os = gs;
7162		gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7163	} else
7164		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7165	for (g = 0; g < num_target_port_groups; g++) {
7166		tpg_desc->pref_state = (g == pg) ? gs : os;
7167		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7168		    TPG_U_SUP | TPG_T_SUP;
7169		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7170		tpg_desc->status = TPG_IMPLICIT;
7171		pc = 0;
7172		STAILQ_FOREACH(port, &softc->port_list, links) {
7173			if (port->targ_port < g * softc->port_cnt ||
7174			    port->targ_port >= (g + 1) * softc->port_cnt)
7175				continue;
7176			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7177				continue;
7178			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7179				continue;
7180			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7181			    relative_target_port_identifier);
7182			pc++;
7183		}
7184		tpg_desc->target_port_count = pc;
7185		tpg_desc = (struct scsi_target_port_group_descriptor *)
7186		    &tpg_desc->descriptors[pc];
7187	}
7188	mtx_unlock(&softc->ctl_lock);
7189
7190	ctl_set_success(ctsio);
7191	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7192	ctsio->be_move_done = ctl_config_move_done;
7193	ctl_datamove((union ctl_io *)ctsio);
7194	return(retval);
7195}
7196
7197int
7198ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7199{
7200	struct ctl_lun *lun;
7201	struct scsi_report_supported_opcodes *cdb;
7202	const struct ctl_cmd_entry *entry, *sentry;
7203	struct scsi_report_supported_opcodes_all *all;
7204	struct scsi_report_supported_opcodes_descr *descr;
7205	struct scsi_report_supported_opcodes_one *one;
7206	int retval;
7207	int alloc_len, total_len;
7208	int opcode, service_action, i, j, num;
7209
7210	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7211
7212	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7213	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7214
7215	retval = CTL_RETVAL_COMPLETE;
7216
7217	opcode = cdb->requested_opcode;
7218	service_action = scsi_2btoul(cdb->requested_service_action);
7219	switch (cdb->options & RSO_OPTIONS_MASK) {
7220	case RSO_OPTIONS_ALL:
7221		num = 0;
7222		for (i = 0; i < 256; i++) {
7223			entry = &ctl_cmd_table[i];
7224			if (entry->flags & CTL_CMD_FLAG_SA5) {
7225				for (j = 0; j < 32; j++) {
7226					sentry = &((const struct ctl_cmd_entry *)
7227					    entry->execute)[j];
7228					if (ctl_cmd_applicable(
7229					    lun->be_lun->lun_type, sentry))
7230						num++;
7231				}
7232			} else {
7233				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7234				    entry))
7235					num++;
7236			}
7237		}
7238		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7239		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7240		break;
7241	case RSO_OPTIONS_OC:
7242		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7243			ctl_set_invalid_field(/*ctsio*/ ctsio,
7244					      /*sks_valid*/ 1,
7245					      /*command*/ 1,
7246					      /*field*/ 2,
7247					      /*bit_valid*/ 1,
7248					      /*bit*/ 2);
7249			ctl_done((union ctl_io *)ctsio);
7250			return (CTL_RETVAL_COMPLETE);
7251		}
7252		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7253		break;
7254	case RSO_OPTIONS_OC_SA:
7255		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7256		    service_action >= 32) {
7257			ctl_set_invalid_field(/*ctsio*/ ctsio,
7258					      /*sks_valid*/ 1,
7259					      /*command*/ 1,
7260					      /*field*/ 2,
7261					      /*bit_valid*/ 1,
7262					      /*bit*/ 2);
7263			ctl_done((union ctl_io *)ctsio);
7264			return (CTL_RETVAL_COMPLETE);
7265		}
7266		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7267		break;
7268	default:
7269		ctl_set_invalid_field(/*ctsio*/ ctsio,
7270				      /*sks_valid*/ 1,
7271				      /*command*/ 1,
7272				      /*field*/ 2,
7273				      /*bit_valid*/ 1,
7274				      /*bit*/ 2);
7275		ctl_done((union ctl_io *)ctsio);
7276		return (CTL_RETVAL_COMPLETE);
7277	}
7278
7279	alloc_len = scsi_4btoul(cdb->length);
7280
7281	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7282
7283	ctsio->kern_sg_entries = 0;
7284
7285	if (total_len < alloc_len) {
7286		ctsio->residual = alloc_len - total_len;
7287		ctsio->kern_data_len = total_len;
7288		ctsio->kern_total_len = total_len;
7289	} else {
7290		ctsio->residual = 0;
7291		ctsio->kern_data_len = alloc_len;
7292		ctsio->kern_total_len = alloc_len;
7293	}
7294	ctsio->kern_data_resid = 0;
7295	ctsio->kern_rel_offset = 0;
7296
7297	switch (cdb->options & RSO_OPTIONS_MASK) {
7298	case RSO_OPTIONS_ALL:
7299		all = (struct scsi_report_supported_opcodes_all *)
7300		    ctsio->kern_data_ptr;
7301		num = 0;
7302		for (i = 0; i < 256; i++) {
7303			entry = &ctl_cmd_table[i];
7304			if (entry->flags & CTL_CMD_FLAG_SA5) {
7305				for (j = 0; j < 32; j++) {
7306					sentry = &((const struct ctl_cmd_entry *)
7307					    entry->execute)[j];
7308					if (!ctl_cmd_applicable(
7309					    lun->be_lun->lun_type, sentry))
7310						continue;
7311					descr = &all->descr[num++];
7312					descr->opcode = i;
7313					scsi_ulto2b(j, descr->service_action);
7314					descr->flags = RSO_SERVACTV;
7315					scsi_ulto2b(sentry->length,
7316					    descr->cdb_length);
7317				}
7318			} else {
7319				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7320				    entry))
7321					continue;
7322				descr = &all->descr[num++];
7323				descr->opcode = i;
7324				scsi_ulto2b(0, descr->service_action);
7325				descr->flags = 0;
7326				scsi_ulto2b(entry->length, descr->cdb_length);
7327			}
7328		}
7329		scsi_ulto4b(
7330		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7331		    all->length);
7332		break;
7333	case RSO_OPTIONS_OC:
7334		one = (struct scsi_report_supported_opcodes_one *)
7335		    ctsio->kern_data_ptr;
7336		entry = &ctl_cmd_table[opcode];
7337		goto fill_one;
7338	case RSO_OPTIONS_OC_SA:
7339		one = (struct scsi_report_supported_opcodes_one *)
7340		    ctsio->kern_data_ptr;
7341		entry = &ctl_cmd_table[opcode];
7342		entry = &((const struct ctl_cmd_entry *)
7343		    entry->execute)[service_action];
7344fill_one:
7345		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7346			one->support = 3;
7347			scsi_ulto2b(entry->length, one->cdb_length);
7348			one->cdb_usage[0] = opcode;
7349			memcpy(&one->cdb_usage[1], entry->usage,
7350			    entry->length - 1);
7351		} else
7352			one->support = 1;
7353		break;
7354	}
7355
7356	ctl_set_success(ctsio);
7357	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7358	ctsio->be_move_done = ctl_config_move_done;
7359	ctl_datamove((union ctl_io *)ctsio);
7360	return(retval);
7361}
7362
7363int
7364ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7365{
7366	struct scsi_report_supported_tmf *cdb;
7367	struct scsi_report_supported_tmf_data *data;
7368	int retval;
7369	int alloc_len, total_len;
7370
7371	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7372
7373	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7374
7375	retval = CTL_RETVAL_COMPLETE;
7376
7377	total_len = sizeof(struct scsi_report_supported_tmf_data);
7378	alloc_len = scsi_4btoul(cdb->length);
7379
7380	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7381
7382	ctsio->kern_sg_entries = 0;
7383
7384	if (total_len < alloc_len) {
7385		ctsio->residual = alloc_len - total_len;
7386		ctsio->kern_data_len = total_len;
7387		ctsio->kern_total_len = total_len;
7388	} else {
7389		ctsio->residual = 0;
7390		ctsio->kern_data_len = alloc_len;
7391		ctsio->kern_total_len = alloc_len;
7392	}
7393	ctsio->kern_data_resid = 0;
7394	ctsio->kern_rel_offset = 0;
7395
7396	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7397	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7398	    RST_TRS;
7399	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7400
7401	ctl_set_success(ctsio);
7402	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7403	ctsio->be_move_done = ctl_config_move_done;
7404	ctl_datamove((union ctl_io *)ctsio);
7405	return (retval);
7406}
7407
7408int
7409ctl_report_timestamp(struct ctl_scsiio *ctsio)
7410{
7411	struct scsi_report_timestamp *cdb;
7412	struct scsi_report_timestamp_data *data;
7413	struct timeval tv;
7414	int64_t timestamp;
7415	int retval;
7416	int alloc_len, total_len;
7417
7418	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7419
7420	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7421
7422	retval = CTL_RETVAL_COMPLETE;
7423
7424	total_len = sizeof(struct scsi_report_timestamp_data);
7425	alloc_len = scsi_4btoul(cdb->length);
7426
7427	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7428
7429	ctsio->kern_sg_entries = 0;
7430
7431	if (total_len < alloc_len) {
7432		ctsio->residual = alloc_len - total_len;
7433		ctsio->kern_data_len = total_len;
7434		ctsio->kern_total_len = total_len;
7435	} else {
7436		ctsio->residual = 0;
7437		ctsio->kern_data_len = alloc_len;
7438		ctsio->kern_total_len = alloc_len;
7439	}
7440	ctsio->kern_data_resid = 0;
7441	ctsio->kern_rel_offset = 0;
7442
7443	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7444	scsi_ulto2b(sizeof(*data) - 2, data->length);
7445	data->origin = RTS_ORIG_OUTSIDE;
7446	getmicrotime(&tv);
7447	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7448	scsi_ulto4b(timestamp >> 16, data->timestamp);
7449	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7450
7451	ctl_set_success(ctsio);
7452	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7453	ctsio->be_move_done = ctl_config_move_done;
7454	ctl_datamove((union ctl_io *)ctsio);
7455	return (retval);
7456}
7457
7458int
7459ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7460{
7461	struct scsi_per_res_in *cdb;
7462	int alloc_len, total_len = 0;
7463	/* struct scsi_per_res_in_rsrv in_data; */
7464	struct ctl_lun *lun;
7465	struct ctl_softc *softc;
7466	uint64_t key;
7467
7468	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7469
7470	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7471
7472	alloc_len = scsi_2btoul(cdb->length);
7473
7474	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7475	softc = lun->ctl_softc;
7476
7477retry:
7478	mtx_lock(&lun->lun_lock);
7479	switch (cdb->action) {
7480	case SPRI_RK: /* read keys */
7481		total_len = sizeof(struct scsi_per_res_in_keys) +
7482			lun->pr_key_count *
7483			sizeof(struct scsi_per_res_key);
7484		break;
7485	case SPRI_RR: /* read reservation */
7486		if (lun->flags & CTL_LUN_PR_RESERVED)
7487			total_len = sizeof(struct scsi_per_res_in_rsrv);
7488		else
7489			total_len = sizeof(struct scsi_per_res_in_header);
7490		break;
7491	case SPRI_RC: /* report capabilities */
7492		total_len = sizeof(struct scsi_per_res_cap);
7493		break;
7494	case SPRI_RS: /* read full status */
7495		total_len = sizeof(struct scsi_per_res_in_header) +
7496		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7497		    lun->pr_key_count;
7498		break;
7499	default:
7500		panic("Invalid PR type %x", cdb->action);
7501	}
7502	mtx_unlock(&lun->lun_lock);
7503
7504	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7505
7506	if (total_len < alloc_len) {
7507		ctsio->residual = alloc_len - total_len;
7508		ctsio->kern_data_len = total_len;
7509		ctsio->kern_total_len = total_len;
7510	} else {
7511		ctsio->residual = 0;
7512		ctsio->kern_data_len = alloc_len;
7513		ctsio->kern_total_len = alloc_len;
7514	}
7515
7516	ctsio->kern_data_resid = 0;
7517	ctsio->kern_rel_offset = 0;
7518	ctsio->kern_sg_entries = 0;
7519
7520	mtx_lock(&lun->lun_lock);
7521	switch (cdb->action) {
7522	case SPRI_RK: { // read keys
7523        struct scsi_per_res_in_keys *res_keys;
7524		int i, key_count;
7525
7526		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7527
7528		/*
7529		 * We had to drop the lock to allocate our buffer, which
7530		 * leaves time for someone to come in with another
7531		 * persistent reservation.  (That is unlikely, though,
7532		 * since this should be the only persistent reservation
7533		 * command active right now.)
7534		 */
7535		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7536		    (lun->pr_key_count *
7537		     sizeof(struct scsi_per_res_key)))){
7538			mtx_unlock(&lun->lun_lock);
7539			free(ctsio->kern_data_ptr, M_CTL);
7540			printf("%s: reservation length changed, retrying\n",
7541			       __func__);
7542			goto retry;
7543		}
7544
7545		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7546
7547		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7548			     lun->pr_key_count, res_keys->header.length);
7549
7550		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7551			if ((key = ctl_get_prkey(lun, i)) == 0)
7552				continue;
7553
7554			/*
7555			 * We used lun->pr_key_count to calculate the
7556			 * size to allocate.  If it turns out the number of
7557			 * initiators with the registered flag set is
7558			 * larger than that (i.e. they haven't been kept in
7559			 * sync), we've got a problem.
7560			 */
7561			if (key_count >= lun->pr_key_count) {
7562				key_count++;
7563				continue;
7564			}
7565			scsi_u64to8b(key, res_keys->keys[key_count].key);
7566			key_count++;
7567		}
7568		break;
7569	}
7570	case SPRI_RR: { // read reservation
7571		struct scsi_per_res_in_rsrv *res;
7572		int tmp_len, header_only;
7573
7574		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7575
7576		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7577
7578		if (lun->flags & CTL_LUN_PR_RESERVED)
7579		{
7580			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7581			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7582				    res->header.length);
7583			header_only = 0;
7584		} else {
7585			tmp_len = sizeof(struct scsi_per_res_in_header);
7586			scsi_ulto4b(0, res->header.length);
7587			header_only = 1;
7588		}
7589
7590		/*
7591		 * We had to drop the lock to allocate our buffer, which
7592		 * leaves time for someone to come in with another
7593		 * persistent reservation.  (That is unlikely, though,
7594		 * since this should be the only persistent reservation
7595		 * command active right now.)
7596		 */
7597		if (tmp_len != total_len) {
7598			mtx_unlock(&lun->lun_lock);
7599			free(ctsio->kern_data_ptr, M_CTL);
7600			printf("%s: reservation status changed, retrying\n",
7601			       __func__);
7602			goto retry;
7603		}
7604
7605		/*
7606		 * No reservation held, so we're done.
7607		 */
7608		if (header_only != 0)
7609			break;
7610
7611		/*
7612		 * If the registration is an All Registrants type, the key
7613		 * is 0, since it doesn't really matter.
7614		 */
7615		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7616			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7617			    res->data.reservation);
7618		}
7619		res->data.scopetype = lun->res_type;
7620		break;
7621	}
7622	case SPRI_RC:     //report capabilities
7623	{
7624		struct scsi_per_res_cap *res_cap;
7625		uint16_t type_mask;
7626
7627		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7628		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7629		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7630		type_mask = SPRI_TM_WR_EX_AR |
7631			    SPRI_TM_EX_AC_RO |
7632			    SPRI_TM_WR_EX_RO |
7633			    SPRI_TM_EX_AC |
7634			    SPRI_TM_WR_EX |
7635			    SPRI_TM_EX_AC_AR;
7636		scsi_ulto2b(type_mask, res_cap->type_mask);
7637		break;
7638	}
7639	case SPRI_RS: { // read full status
7640		struct scsi_per_res_in_full *res_status;
7641		struct scsi_per_res_in_full_desc *res_desc;
7642		struct ctl_port *port;
7643		int i, len;
7644
7645		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7646
7647		/*
7648		 * We had to drop the lock to allocate our buffer, which
7649		 * leaves time for someone to come in with another
7650		 * persistent reservation.  (That is unlikely, though,
7651		 * since this should be the only persistent reservation
7652		 * command active right now.)
7653		 */
7654		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7655		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7656		     lun->pr_key_count)){
7657			mtx_unlock(&lun->lun_lock);
7658			free(ctsio->kern_data_ptr, M_CTL);
7659			printf("%s: reservation length changed, retrying\n",
7660			       __func__);
7661			goto retry;
7662		}
7663
7664		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7665
7666		res_desc = &res_status->desc[0];
7667		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7668			if ((key = ctl_get_prkey(lun, i)) == 0)
7669				continue;
7670
7671			scsi_u64to8b(key, res_desc->res_key.key);
7672			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7673			    (lun->pr_res_idx == i ||
7674			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7675				res_desc->flags = SPRI_FULL_R_HOLDER;
7676				res_desc->scopetype = lun->res_type;
7677			}
7678			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7679			    res_desc->rel_trgt_port_id);
7680			len = 0;
7681			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7682			if (port != NULL)
7683				len = ctl_create_iid(port,
7684				    i % CTL_MAX_INIT_PER_PORT,
7685				    res_desc->transport_id);
7686			scsi_ulto4b(len, res_desc->additional_length);
7687			res_desc = (struct scsi_per_res_in_full_desc *)
7688			    &res_desc->transport_id[len];
7689		}
7690		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7691		    res_status->header.length);
7692		break;
7693	}
7694	default:
7695		/*
7696		 * This is a bug, because we just checked for this above,
7697		 * and should have returned an error.
7698		 */
7699		panic("Invalid PR type %x", cdb->action);
7700		break; /* NOTREACHED */
7701	}
7702	mtx_unlock(&lun->lun_lock);
7703
7704	ctl_set_success(ctsio);
7705	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7706	ctsio->be_move_done = ctl_config_move_done;
7707	ctl_datamove((union ctl_io *)ctsio);
7708	return (CTL_RETVAL_COMPLETE);
7709}
7710
7711/*
7712 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7713 * it should return.
7714 */
7715static int
7716ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7717		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7718		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7719		struct scsi_per_res_out_parms* param)
7720{
7721	union ctl_ha_msg persis_io;
7722	int i;
7723
7724	mtx_lock(&lun->lun_lock);
7725	if (sa_res_key == 0) {
7726		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7727			/* validate scope and type */
7728			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7729			     SPR_LU_SCOPE) {
7730				mtx_unlock(&lun->lun_lock);
7731				ctl_set_invalid_field(/*ctsio*/ ctsio,
7732						      /*sks_valid*/ 1,
7733						      /*command*/ 1,
7734						      /*field*/ 2,
7735						      /*bit_valid*/ 1,
7736						      /*bit*/ 4);
7737				ctl_done((union ctl_io *)ctsio);
7738				return (1);
7739			}
7740
7741		        if (type>8 || type==2 || type==4 || type==0) {
7742				mtx_unlock(&lun->lun_lock);
7743				ctl_set_invalid_field(/*ctsio*/ ctsio,
7744       	           				      /*sks_valid*/ 1,
7745						      /*command*/ 1,
7746						      /*field*/ 2,
7747						      /*bit_valid*/ 1,
7748						      /*bit*/ 0);
7749				ctl_done((union ctl_io *)ctsio);
7750				return (1);
7751		        }
7752
7753			/*
7754			 * Unregister everybody else and build UA for
7755			 * them
7756			 */
7757			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7758				if (i == residx || ctl_get_prkey(lun, i) == 0)
7759					continue;
7760
7761				ctl_clr_prkey(lun, i);
7762				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7763			}
7764			lun->pr_key_count = 1;
7765			lun->res_type = type;
7766			if (lun->res_type != SPR_TYPE_WR_EX_AR
7767			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7768				lun->pr_res_idx = residx;
7769			lun->PRGeneration++;
7770			mtx_unlock(&lun->lun_lock);
7771
7772			/* send msg to other side */
7773			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7774			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7775			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7776			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7777			persis_io.pr.pr_info.res_type = type;
7778			memcpy(persis_io.pr.pr_info.sa_res_key,
7779			       param->serv_act_res_key,
7780			       sizeof(param->serv_act_res_key));
7781			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7782			    sizeof(persis_io.pr), M_WAITOK);
7783		} else {
7784			/* not all registrants */
7785			mtx_unlock(&lun->lun_lock);
7786			free(ctsio->kern_data_ptr, M_CTL);
7787			ctl_set_invalid_field(ctsio,
7788					      /*sks_valid*/ 1,
7789					      /*command*/ 0,
7790					      /*field*/ 8,
7791					      /*bit_valid*/ 0,
7792					      /*bit*/ 0);
7793			ctl_done((union ctl_io *)ctsio);
7794			return (1);
7795		}
7796	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7797		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7798		int found = 0;
7799
7800		if (res_key == sa_res_key) {
7801			/* special case */
7802			/*
7803			 * The spec implies this is not good but doesn't
7804			 * say what to do. There are two choices either
7805			 * generate a res conflict or check condition
7806			 * with illegal field in parameter data. Since
7807			 * that is what is done when the sa_res_key is
7808			 * zero I'll take that approach since this has
7809			 * to do with the sa_res_key.
7810			 */
7811			mtx_unlock(&lun->lun_lock);
7812			free(ctsio->kern_data_ptr, M_CTL);
7813			ctl_set_invalid_field(ctsio,
7814					      /*sks_valid*/ 1,
7815					      /*command*/ 0,
7816					      /*field*/ 8,
7817					      /*bit_valid*/ 0,
7818					      /*bit*/ 0);
7819			ctl_done((union ctl_io *)ctsio);
7820			return (1);
7821		}
7822
7823		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7824			if (ctl_get_prkey(lun, i) != sa_res_key)
7825				continue;
7826
7827			found = 1;
7828			ctl_clr_prkey(lun, i);
7829			lun->pr_key_count--;
7830			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7831		}
7832		if (!found) {
7833			mtx_unlock(&lun->lun_lock);
7834			free(ctsio->kern_data_ptr, M_CTL);
7835			ctl_set_reservation_conflict(ctsio);
7836			ctl_done((union ctl_io *)ctsio);
7837			return (CTL_RETVAL_COMPLETE);
7838		}
7839		lun->PRGeneration++;
7840		mtx_unlock(&lun->lun_lock);
7841
7842		/* send msg to other side */
7843		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7844		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7845		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7846		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7847		persis_io.pr.pr_info.res_type = type;
7848		memcpy(persis_io.pr.pr_info.sa_res_key,
7849		       param->serv_act_res_key,
7850		       sizeof(param->serv_act_res_key));
7851		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7852		    sizeof(persis_io.pr), M_WAITOK);
7853	} else {
7854		/* Reserved but not all registrants */
7855		/* sa_res_key is res holder */
7856		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7857			/* validate scope and type */
7858			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7859			     SPR_LU_SCOPE) {
7860				mtx_unlock(&lun->lun_lock);
7861				ctl_set_invalid_field(/*ctsio*/ ctsio,
7862						      /*sks_valid*/ 1,
7863						      /*command*/ 1,
7864						      /*field*/ 2,
7865						      /*bit_valid*/ 1,
7866						      /*bit*/ 4);
7867				ctl_done((union ctl_io *)ctsio);
7868				return (1);
7869			}
7870
7871			if (type>8 || type==2 || type==4 || type==0) {
7872				mtx_unlock(&lun->lun_lock);
7873				ctl_set_invalid_field(/*ctsio*/ ctsio,
7874						      /*sks_valid*/ 1,
7875						      /*command*/ 1,
7876						      /*field*/ 2,
7877						      /*bit_valid*/ 1,
7878						      /*bit*/ 0);
7879				ctl_done((union ctl_io *)ctsio);
7880				return (1);
7881			}
7882
7883			/*
7884			 * Do the following:
7885			 * if sa_res_key != res_key remove all
7886			 * registrants w/sa_res_key and generate UA
7887			 * for these registrants(Registrations
7888			 * Preempted) if it wasn't an exclusive
7889			 * reservation generate UA(Reservations
7890			 * Preempted) for all other registered nexuses
7891			 * if the type has changed. Establish the new
7892			 * reservation and holder. If res_key and
7893			 * sa_res_key are the same do the above
7894			 * except don't unregister the res holder.
7895			 */
7896
7897			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7898				if (i == residx || ctl_get_prkey(lun, i) == 0)
7899					continue;
7900
7901				if (sa_res_key == ctl_get_prkey(lun, i)) {
7902					ctl_clr_prkey(lun, i);
7903					lun->pr_key_count--;
7904					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7905				} else if (type != lun->res_type
7906					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7907					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7908					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7909				}
7910			}
7911			lun->res_type = type;
7912			if (lun->res_type != SPR_TYPE_WR_EX_AR
7913			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7914				lun->pr_res_idx = residx;
7915			else
7916				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7917			lun->PRGeneration++;
7918			mtx_unlock(&lun->lun_lock);
7919
7920			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7921			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7922			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7923			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7924			persis_io.pr.pr_info.res_type = type;
7925			memcpy(persis_io.pr.pr_info.sa_res_key,
7926			       param->serv_act_res_key,
7927			       sizeof(param->serv_act_res_key));
7928			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7929			    sizeof(persis_io.pr), M_WAITOK);
7930		} else {
7931			/*
7932			 * sa_res_key is not the res holder just
7933			 * remove registrants
7934			 */
7935			int found=0;
7936
7937			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7938				if (sa_res_key != ctl_get_prkey(lun, i))
7939					continue;
7940
7941				found = 1;
7942				ctl_clr_prkey(lun, i);
7943				lun->pr_key_count--;
7944				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7945			}
7946
7947			if (!found) {
7948				mtx_unlock(&lun->lun_lock);
7949				free(ctsio->kern_data_ptr, M_CTL);
7950				ctl_set_reservation_conflict(ctsio);
7951				ctl_done((union ctl_io *)ctsio);
7952		        	return (1);
7953			}
7954			lun->PRGeneration++;
7955			mtx_unlock(&lun->lun_lock);
7956
7957			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7958			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7959			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7960			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7961			persis_io.pr.pr_info.res_type = type;
7962			memcpy(persis_io.pr.pr_info.sa_res_key,
7963			       param->serv_act_res_key,
7964			       sizeof(param->serv_act_res_key));
7965			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7966			    sizeof(persis_io.pr), M_WAITOK);
7967		}
7968	}
7969	return (0);
7970}
7971
7972static void
7973ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7974{
7975	uint64_t sa_res_key;
7976	int i;
7977
7978	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7979
7980	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7981	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7982	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7983		if (sa_res_key == 0) {
7984			/*
7985			 * Unregister everybody else and build UA for
7986			 * them
7987			 */
7988			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7989				if (i == msg->pr.pr_info.residx ||
7990				    ctl_get_prkey(lun, i) == 0)
7991					continue;
7992
7993				ctl_clr_prkey(lun, i);
7994				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7995			}
7996
7997			lun->pr_key_count = 1;
7998			lun->res_type = msg->pr.pr_info.res_type;
7999			if (lun->res_type != SPR_TYPE_WR_EX_AR
8000			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8001				lun->pr_res_idx = msg->pr.pr_info.residx;
8002		} else {
8003		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8004				if (sa_res_key == ctl_get_prkey(lun, i))
8005					continue;
8006
8007				ctl_clr_prkey(lun, i);
8008				lun->pr_key_count--;
8009				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8010			}
8011		}
8012	} else {
8013		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8014			if (i == msg->pr.pr_info.residx ||
8015			    ctl_get_prkey(lun, i) == 0)
8016				continue;
8017
8018			if (sa_res_key == ctl_get_prkey(lun, i)) {
8019				ctl_clr_prkey(lun, i);
8020				lun->pr_key_count--;
8021				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8022			} else if (msg->pr.pr_info.res_type != lun->res_type
8023				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8024				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8025				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8026			}
8027		}
8028		lun->res_type = msg->pr.pr_info.res_type;
8029		if (lun->res_type != SPR_TYPE_WR_EX_AR
8030		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8031			lun->pr_res_idx = msg->pr.pr_info.residx;
8032		else
8033			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8034	}
8035	lun->PRGeneration++;
8036
8037}
8038
8039
8040int
8041ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8042{
8043	int retval;
8044	u_int32_t param_len;
8045	struct scsi_per_res_out *cdb;
8046	struct ctl_lun *lun;
8047	struct scsi_per_res_out_parms* param;
8048	struct ctl_softc *softc;
8049	uint32_t residx;
8050	uint64_t res_key, sa_res_key, key;
8051	uint8_t type;
8052	union ctl_ha_msg persis_io;
8053	int    i;
8054
8055	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8056
8057	retval = CTL_RETVAL_COMPLETE;
8058
8059	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8060	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8061	softc = lun->ctl_softc;
8062
8063	/*
8064	 * We only support whole-LUN scope.  The scope & type are ignored for
8065	 * register, register and ignore existing key and clear.
8066	 * We sometimes ignore scope and type on preempts too!!
8067	 * Verify reservation type here as well.
8068	 */
8069	type = cdb->scope_type & SPR_TYPE_MASK;
8070	if ((cdb->action == SPRO_RESERVE)
8071	 || (cdb->action == SPRO_RELEASE)) {
8072		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8073			ctl_set_invalid_field(/*ctsio*/ ctsio,
8074					      /*sks_valid*/ 1,
8075					      /*command*/ 1,
8076					      /*field*/ 2,
8077					      /*bit_valid*/ 1,
8078					      /*bit*/ 4);
8079			ctl_done((union ctl_io *)ctsio);
8080			return (CTL_RETVAL_COMPLETE);
8081		}
8082
8083		if (type>8 || type==2 || type==4 || type==0) {
8084			ctl_set_invalid_field(/*ctsio*/ ctsio,
8085					      /*sks_valid*/ 1,
8086					      /*command*/ 1,
8087					      /*field*/ 2,
8088					      /*bit_valid*/ 1,
8089					      /*bit*/ 0);
8090			ctl_done((union ctl_io *)ctsio);
8091			return (CTL_RETVAL_COMPLETE);
8092		}
8093	}
8094
8095	param_len = scsi_4btoul(cdb->length);
8096
8097	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8098		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8099		ctsio->kern_data_len = param_len;
8100		ctsio->kern_total_len = param_len;
8101		ctsio->kern_data_resid = 0;
8102		ctsio->kern_rel_offset = 0;
8103		ctsio->kern_sg_entries = 0;
8104		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8105		ctsio->be_move_done = ctl_config_move_done;
8106		ctl_datamove((union ctl_io *)ctsio);
8107
8108		return (CTL_RETVAL_COMPLETE);
8109	}
8110
8111	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8112
8113	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8114	res_key = scsi_8btou64(param->res_key.key);
8115	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8116
8117	/*
8118	 * Validate the reservation key here except for SPRO_REG_IGNO
8119	 * This must be done for all other service actions
8120	 */
8121	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8122		mtx_lock(&lun->lun_lock);
8123		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8124			if (res_key != key) {
8125				/*
8126				 * The current key passed in doesn't match
8127				 * the one the initiator previously
8128				 * registered.
8129				 */
8130				mtx_unlock(&lun->lun_lock);
8131				free(ctsio->kern_data_ptr, M_CTL);
8132				ctl_set_reservation_conflict(ctsio);
8133				ctl_done((union ctl_io *)ctsio);
8134				return (CTL_RETVAL_COMPLETE);
8135			}
8136		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8137			/*
8138			 * We are not registered
8139			 */
8140			mtx_unlock(&lun->lun_lock);
8141			free(ctsio->kern_data_ptr, M_CTL);
8142			ctl_set_reservation_conflict(ctsio);
8143			ctl_done((union ctl_io *)ctsio);
8144			return (CTL_RETVAL_COMPLETE);
8145		} else if (res_key != 0) {
8146			/*
8147			 * We are not registered and trying to register but
8148			 * the register key isn't zero.
8149			 */
8150			mtx_unlock(&lun->lun_lock);
8151			free(ctsio->kern_data_ptr, M_CTL);
8152			ctl_set_reservation_conflict(ctsio);
8153			ctl_done((union ctl_io *)ctsio);
8154			return (CTL_RETVAL_COMPLETE);
8155		}
8156		mtx_unlock(&lun->lun_lock);
8157	}
8158
8159	switch (cdb->action & SPRO_ACTION_MASK) {
8160	case SPRO_REGISTER:
8161	case SPRO_REG_IGNO: {
8162
8163#if 0
8164		printf("Registration received\n");
8165#endif
8166
8167		/*
8168		 * We don't support any of these options, as we report in
8169		 * the read capabilities request (see
8170		 * ctl_persistent_reserve_in(), above).
8171		 */
8172		if ((param->flags & SPR_SPEC_I_PT)
8173		 || (param->flags & SPR_ALL_TG_PT)
8174		 || (param->flags & SPR_APTPL)) {
8175			int bit_ptr;
8176
8177			if (param->flags & SPR_APTPL)
8178				bit_ptr = 0;
8179			else if (param->flags & SPR_ALL_TG_PT)
8180				bit_ptr = 2;
8181			else /* SPR_SPEC_I_PT */
8182				bit_ptr = 3;
8183
8184			free(ctsio->kern_data_ptr, M_CTL);
8185			ctl_set_invalid_field(ctsio,
8186					      /*sks_valid*/ 1,
8187					      /*command*/ 0,
8188					      /*field*/ 20,
8189					      /*bit_valid*/ 1,
8190					      /*bit*/ bit_ptr);
8191			ctl_done((union ctl_io *)ctsio);
8192			return (CTL_RETVAL_COMPLETE);
8193		}
8194
8195		mtx_lock(&lun->lun_lock);
8196
8197		/*
8198		 * The initiator wants to clear the
8199		 * key/unregister.
8200		 */
8201		if (sa_res_key == 0) {
8202			if ((res_key == 0
8203			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8204			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8205			  && ctl_get_prkey(lun, residx) == 0)) {
8206				mtx_unlock(&lun->lun_lock);
8207				goto done;
8208			}
8209
8210			ctl_clr_prkey(lun, residx);
8211			lun->pr_key_count--;
8212
8213			if (residx == lun->pr_res_idx) {
8214				lun->flags &= ~CTL_LUN_PR_RESERVED;
8215				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8216
8217				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8218				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8219				 && lun->pr_key_count) {
8220					/*
8221					 * If the reservation is a registrants
8222					 * only type we need to generate a UA
8223					 * for other registered inits.  The
8224					 * sense code should be RESERVATIONS
8225					 * RELEASED
8226					 */
8227
8228					for (i = softc->init_min; i < softc->init_max; i++){
8229						if (ctl_get_prkey(lun, i) == 0)
8230							continue;
8231						ctl_est_ua(lun, i,
8232						    CTL_UA_RES_RELEASE);
8233					}
8234				}
8235				lun->res_type = 0;
8236			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8237				if (lun->pr_key_count==0) {
8238					lun->flags &= ~CTL_LUN_PR_RESERVED;
8239					lun->res_type = 0;
8240					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8241				}
8242			}
8243			lun->PRGeneration++;
8244			mtx_unlock(&lun->lun_lock);
8245
8246			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8247			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8248			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8249			persis_io.pr.pr_info.residx = residx;
8250			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8251			    sizeof(persis_io.pr), M_WAITOK);
8252		} else /* sa_res_key != 0 */ {
8253
8254			/*
8255			 * If we aren't registered currently then increment
8256			 * the key count and set the registered flag.
8257			 */
8258			ctl_alloc_prkey(lun, residx);
8259			if (ctl_get_prkey(lun, residx) == 0)
8260				lun->pr_key_count++;
8261			ctl_set_prkey(lun, residx, sa_res_key);
8262			lun->PRGeneration++;
8263			mtx_unlock(&lun->lun_lock);
8264
8265			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8266			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8267			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8268			persis_io.pr.pr_info.residx = residx;
8269			memcpy(persis_io.pr.pr_info.sa_res_key,
8270			       param->serv_act_res_key,
8271			       sizeof(param->serv_act_res_key));
8272			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8273			    sizeof(persis_io.pr), M_WAITOK);
8274		}
8275
8276		break;
8277	}
8278	case SPRO_RESERVE:
8279#if 0
8280                printf("Reserve executed type %d\n", type);
8281#endif
8282		mtx_lock(&lun->lun_lock);
8283		if (lun->flags & CTL_LUN_PR_RESERVED) {
8284			/*
8285			 * if this isn't the reservation holder and it's
8286			 * not a "all registrants" type or if the type is
8287			 * different then we have a conflict
8288			 */
8289			if ((lun->pr_res_idx != residx
8290			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8291			 || lun->res_type != type) {
8292				mtx_unlock(&lun->lun_lock);
8293				free(ctsio->kern_data_ptr, M_CTL);
8294				ctl_set_reservation_conflict(ctsio);
8295				ctl_done((union ctl_io *)ctsio);
8296				return (CTL_RETVAL_COMPLETE);
8297			}
8298			mtx_unlock(&lun->lun_lock);
8299		} else /* create a reservation */ {
8300			/*
8301			 * If it's not an "all registrants" type record
8302			 * reservation holder
8303			 */
8304			if (type != SPR_TYPE_WR_EX_AR
8305			 && type != SPR_TYPE_EX_AC_AR)
8306				lun->pr_res_idx = residx; /* Res holder */
8307			else
8308				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8309
8310			lun->flags |= CTL_LUN_PR_RESERVED;
8311			lun->res_type = type;
8312
8313			mtx_unlock(&lun->lun_lock);
8314
8315			/* send msg to other side */
8316			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8317			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8318			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8319			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8320			persis_io.pr.pr_info.res_type = type;
8321			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8322			    sizeof(persis_io.pr), M_WAITOK);
8323		}
8324		break;
8325
8326	case SPRO_RELEASE:
8327		mtx_lock(&lun->lun_lock);
8328		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8329			/* No reservation exists return good status */
8330			mtx_unlock(&lun->lun_lock);
8331			goto done;
8332		}
8333		/*
8334		 * Is this nexus a reservation holder?
8335		 */
8336		if (lun->pr_res_idx != residx
8337		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8338			/*
8339			 * not a res holder return good status but
8340			 * do nothing
8341			 */
8342			mtx_unlock(&lun->lun_lock);
8343			goto done;
8344		}
8345
8346		if (lun->res_type != type) {
8347			mtx_unlock(&lun->lun_lock);
8348			free(ctsio->kern_data_ptr, M_CTL);
8349			ctl_set_illegal_pr_release(ctsio);
8350			ctl_done((union ctl_io *)ctsio);
8351			return (CTL_RETVAL_COMPLETE);
8352		}
8353
8354		/* okay to release */
8355		lun->flags &= ~CTL_LUN_PR_RESERVED;
8356		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8357		lun->res_type = 0;
8358
8359		/*
8360		 * if this isn't an exclusive access
8361		 * res generate UA for all other
8362		 * registrants.
8363		 */
8364		if (type != SPR_TYPE_EX_AC
8365		 && type != SPR_TYPE_WR_EX) {
8366			for (i = softc->init_min; i < softc->init_max; i++) {
8367				if (i == residx || ctl_get_prkey(lun, i) == 0)
8368					continue;
8369				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8370			}
8371		}
8372		mtx_unlock(&lun->lun_lock);
8373
8374		/* Send msg to other side */
8375		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8376		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8377		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8378		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8379		     sizeof(persis_io.pr), M_WAITOK);
8380		break;
8381
8382	case SPRO_CLEAR:
8383		/* send msg to other side */
8384
8385		mtx_lock(&lun->lun_lock);
8386		lun->flags &= ~CTL_LUN_PR_RESERVED;
8387		lun->res_type = 0;
8388		lun->pr_key_count = 0;
8389		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8390
8391		ctl_clr_prkey(lun, residx);
8392		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8393			if (ctl_get_prkey(lun, i) != 0) {
8394				ctl_clr_prkey(lun, i);
8395				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8396			}
8397		lun->PRGeneration++;
8398		mtx_unlock(&lun->lun_lock);
8399
8400		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8401		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8402		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8403		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8404		     sizeof(persis_io.pr), M_WAITOK);
8405		break;
8406
8407	case SPRO_PREEMPT:
8408	case SPRO_PRE_ABO: {
8409		int nretval;
8410
8411		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8412					  residx, ctsio, cdb, param);
8413		if (nretval != 0)
8414			return (CTL_RETVAL_COMPLETE);
8415		break;
8416	}
8417	default:
8418		panic("Invalid PR type %x", cdb->action);
8419	}
8420
8421done:
8422	free(ctsio->kern_data_ptr, M_CTL);
8423	ctl_set_success(ctsio);
8424	ctl_done((union ctl_io *)ctsio);
8425
8426	return (retval);
8427}
8428
8429/*
8430 * This routine is for handling a message from the other SC pertaining to
8431 * persistent reserve out. All the error checking will have been done
8432 * so only perorming the action need be done here to keep the two
8433 * in sync.
8434 */
8435static void
8436ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8437{
8438	struct ctl_softc *softc = control_softc;
8439	struct ctl_lun *lun;
8440	int i;
8441	uint32_t residx, targ_lun;
8442
8443	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8444	mtx_lock(&softc->ctl_lock);
8445	if ((targ_lun >= CTL_MAX_LUNS) ||
8446	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8447		mtx_unlock(&softc->ctl_lock);
8448		return;
8449	}
8450	mtx_lock(&lun->lun_lock);
8451	mtx_unlock(&softc->ctl_lock);
8452	if (lun->flags & CTL_LUN_DISABLED) {
8453		mtx_unlock(&lun->lun_lock);
8454		return;
8455	}
8456	residx = ctl_get_initindex(&msg->hdr.nexus);
8457	switch(msg->pr.pr_info.action) {
8458	case CTL_PR_REG_KEY:
8459		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8460		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8461			lun->pr_key_count++;
8462		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8463		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8464		lun->PRGeneration++;
8465		break;
8466
8467	case CTL_PR_UNREG_KEY:
8468		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8469		lun->pr_key_count--;
8470
8471		/* XXX Need to see if the reservation has been released */
8472		/* if so do we need to generate UA? */
8473		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8474			lun->flags &= ~CTL_LUN_PR_RESERVED;
8475			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8476
8477			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8478			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8479			 && lun->pr_key_count) {
8480				/*
8481				 * If the reservation is a registrants
8482				 * only type we need to generate a UA
8483				 * for other registered inits.  The
8484				 * sense code should be RESERVATIONS
8485				 * RELEASED
8486				 */
8487
8488				for (i = softc->init_min; i < softc->init_max; i++) {
8489					if (ctl_get_prkey(lun, i) == 0)
8490						continue;
8491
8492					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8493				}
8494			}
8495			lun->res_type = 0;
8496		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8497			if (lun->pr_key_count==0) {
8498				lun->flags &= ~CTL_LUN_PR_RESERVED;
8499				lun->res_type = 0;
8500				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8501			}
8502		}
8503		lun->PRGeneration++;
8504		break;
8505
8506	case CTL_PR_RESERVE:
8507		lun->flags |= CTL_LUN_PR_RESERVED;
8508		lun->res_type = msg->pr.pr_info.res_type;
8509		lun->pr_res_idx = msg->pr.pr_info.residx;
8510
8511		break;
8512
8513	case CTL_PR_RELEASE:
8514		/*
8515		 * if this isn't an exclusive access res generate UA for all
8516		 * other registrants.
8517		 */
8518		if (lun->res_type != SPR_TYPE_EX_AC
8519		 && lun->res_type != SPR_TYPE_WR_EX) {
8520			for (i = softc->init_min; i < softc->init_max; i++)
8521				if (i == residx || ctl_get_prkey(lun, i) == 0)
8522					continue;
8523				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8524		}
8525
8526		lun->flags &= ~CTL_LUN_PR_RESERVED;
8527		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8528		lun->res_type = 0;
8529		break;
8530
8531	case CTL_PR_PREEMPT:
8532		ctl_pro_preempt_other(lun, msg);
8533		break;
8534	case CTL_PR_CLEAR:
8535		lun->flags &= ~CTL_LUN_PR_RESERVED;
8536		lun->res_type = 0;
8537		lun->pr_key_count = 0;
8538		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8539
8540		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8541			if (ctl_get_prkey(lun, i) == 0)
8542				continue;
8543			ctl_clr_prkey(lun, i);
8544			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8545		}
8546		lun->PRGeneration++;
8547		break;
8548	}
8549
8550	mtx_unlock(&lun->lun_lock);
8551}
8552
8553int
8554ctl_read_write(struct ctl_scsiio *ctsio)
8555{
8556	struct ctl_lun *lun;
8557	struct ctl_lba_len_flags *lbalen;
8558	uint64_t lba;
8559	uint32_t num_blocks;
8560	int flags, retval;
8561	int isread;
8562
8563	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8564
8565	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8566
8567	flags = 0;
8568	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8569	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8570	switch (ctsio->cdb[0]) {
8571	case READ_6:
8572	case WRITE_6: {
8573		struct scsi_rw_6 *cdb;
8574
8575		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8576
8577		lba = scsi_3btoul(cdb->addr);
8578		/* only 5 bits are valid in the most significant address byte */
8579		lba &= 0x1fffff;
8580		num_blocks = cdb->length;
8581		/*
8582		 * This is correct according to SBC-2.
8583		 */
8584		if (num_blocks == 0)
8585			num_blocks = 256;
8586		break;
8587	}
8588	case READ_10:
8589	case WRITE_10: {
8590		struct scsi_rw_10 *cdb;
8591
8592		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8593		if (cdb->byte2 & SRW10_FUA)
8594			flags |= CTL_LLF_FUA;
8595		if (cdb->byte2 & SRW10_DPO)
8596			flags |= CTL_LLF_DPO;
8597		lba = scsi_4btoul(cdb->addr);
8598		num_blocks = scsi_2btoul(cdb->length);
8599		break;
8600	}
8601	case WRITE_VERIFY_10: {
8602		struct scsi_write_verify_10 *cdb;
8603
8604		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8605		flags |= CTL_LLF_FUA;
8606		if (cdb->byte2 & SWV_DPO)
8607			flags |= CTL_LLF_DPO;
8608		lba = scsi_4btoul(cdb->addr);
8609		num_blocks = scsi_2btoul(cdb->length);
8610		break;
8611	}
8612	case READ_12:
8613	case WRITE_12: {
8614		struct scsi_rw_12 *cdb;
8615
8616		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8617		if (cdb->byte2 & SRW12_FUA)
8618			flags |= CTL_LLF_FUA;
8619		if (cdb->byte2 & SRW12_DPO)
8620			flags |= CTL_LLF_DPO;
8621		lba = scsi_4btoul(cdb->addr);
8622		num_blocks = scsi_4btoul(cdb->length);
8623		break;
8624	}
8625	case WRITE_VERIFY_12: {
8626		struct scsi_write_verify_12 *cdb;
8627
8628		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8629		flags |= CTL_LLF_FUA;
8630		if (cdb->byte2 & SWV_DPO)
8631			flags |= CTL_LLF_DPO;
8632		lba = scsi_4btoul(cdb->addr);
8633		num_blocks = scsi_4btoul(cdb->length);
8634		break;
8635	}
8636	case READ_16:
8637	case WRITE_16: {
8638		struct scsi_rw_16 *cdb;
8639
8640		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8641		if (cdb->byte2 & SRW12_FUA)
8642			flags |= CTL_LLF_FUA;
8643		if (cdb->byte2 & SRW12_DPO)
8644			flags |= CTL_LLF_DPO;
8645		lba = scsi_8btou64(cdb->addr);
8646		num_blocks = scsi_4btoul(cdb->length);
8647		break;
8648	}
8649	case WRITE_ATOMIC_16: {
8650		struct scsi_write_atomic_16 *cdb;
8651
8652		if (lun->be_lun->atomicblock == 0) {
8653			ctl_set_invalid_opcode(ctsio);
8654			ctl_done((union ctl_io *)ctsio);
8655			return (CTL_RETVAL_COMPLETE);
8656		}
8657
8658		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8659		if (cdb->byte2 & SRW12_FUA)
8660			flags |= CTL_LLF_FUA;
8661		if (cdb->byte2 & SRW12_DPO)
8662			flags |= CTL_LLF_DPO;
8663		lba = scsi_8btou64(cdb->addr);
8664		num_blocks = scsi_2btoul(cdb->length);
8665		if (num_blocks > lun->be_lun->atomicblock) {
8666			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8667			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8668			    /*bit*/ 0);
8669			ctl_done((union ctl_io *)ctsio);
8670			return (CTL_RETVAL_COMPLETE);
8671		}
8672		break;
8673	}
8674	case WRITE_VERIFY_16: {
8675		struct scsi_write_verify_16 *cdb;
8676
8677		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8678		flags |= CTL_LLF_FUA;
8679		if (cdb->byte2 & SWV_DPO)
8680			flags |= CTL_LLF_DPO;
8681		lba = scsi_8btou64(cdb->addr);
8682		num_blocks = scsi_4btoul(cdb->length);
8683		break;
8684	}
8685	default:
8686		/*
8687		 * We got a command we don't support.  This shouldn't
8688		 * happen, commands should be filtered out above us.
8689		 */
8690		ctl_set_invalid_opcode(ctsio);
8691		ctl_done((union ctl_io *)ctsio);
8692
8693		return (CTL_RETVAL_COMPLETE);
8694		break; /* NOTREACHED */
8695	}
8696
8697	/*
8698	 * The first check is to make sure we're in bounds, the second
8699	 * check is to catch wrap-around problems.  If the lba + num blocks
8700	 * is less than the lba, then we've wrapped around and the block
8701	 * range is invalid anyway.
8702	 */
8703	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8704	 || ((lba + num_blocks) < lba)) {
8705		ctl_set_lba_out_of_range(ctsio);
8706		ctl_done((union ctl_io *)ctsio);
8707		return (CTL_RETVAL_COMPLETE);
8708	}
8709
8710	/*
8711	 * According to SBC-3, a transfer length of 0 is not an error.
8712	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8713	 * translates to 256 blocks for those commands.
8714	 */
8715	if (num_blocks == 0) {
8716		ctl_set_success(ctsio);
8717		ctl_done((union ctl_io *)ctsio);
8718		return (CTL_RETVAL_COMPLETE);
8719	}
8720
8721	/* Set FUA and/or DPO if caches are disabled. */
8722	if (isread) {
8723		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8724		    SCP_RCD) != 0)
8725			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8726	} else {
8727		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8728		    SCP_WCE) == 0)
8729			flags |= CTL_LLF_FUA;
8730	}
8731
8732	lbalen = (struct ctl_lba_len_flags *)
8733	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8734	lbalen->lba = lba;
8735	lbalen->len = num_blocks;
8736	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8737
8738	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8739	ctsio->kern_rel_offset = 0;
8740
8741	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8742
8743	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8744	return (retval);
8745}
8746
8747static int
8748ctl_cnw_cont(union ctl_io *io)
8749{
8750	struct ctl_scsiio *ctsio;
8751	struct ctl_lun *lun;
8752	struct ctl_lba_len_flags *lbalen;
8753	int retval;
8754
8755	ctsio = &io->scsiio;
8756	ctsio->io_hdr.status = CTL_STATUS_NONE;
8757	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8758	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8759	lbalen = (struct ctl_lba_len_flags *)
8760	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8761	lbalen->flags &= ~CTL_LLF_COMPARE;
8762	lbalen->flags |= CTL_LLF_WRITE;
8763
8764	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8765	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8766	return (retval);
8767}
8768
8769int
8770ctl_cnw(struct ctl_scsiio *ctsio)
8771{
8772	struct ctl_lun *lun;
8773	struct ctl_lba_len_flags *lbalen;
8774	uint64_t lba;
8775	uint32_t num_blocks;
8776	int flags, retval;
8777
8778	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8779
8780	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8781
8782	flags = 0;
8783	switch (ctsio->cdb[0]) {
8784	case COMPARE_AND_WRITE: {
8785		struct scsi_compare_and_write *cdb;
8786
8787		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8788		if (cdb->byte2 & SRW10_FUA)
8789			flags |= CTL_LLF_FUA;
8790		if (cdb->byte2 & SRW10_DPO)
8791			flags |= CTL_LLF_DPO;
8792		lba = scsi_8btou64(cdb->addr);
8793		num_blocks = cdb->length;
8794		break;
8795	}
8796	default:
8797		/*
8798		 * We got a command we don't support.  This shouldn't
8799		 * happen, commands should be filtered out above us.
8800		 */
8801		ctl_set_invalid_opcode(ctsio);
8802		ctl_done((union ctl_io *)ctsio);
8803
8804		return (CTL_RETVAL_COMPLETE);
8805		break; /* NOTREACHED */
8806	}
8807
8808	/*
8809	 * The first check is to make sure we're in bounds, the second
8810	 * check is to catch wrap-around problems.  If the lba + num blocks
8811	 * is less than the lba, then we've wrapped around and the block
8812	 * range is invalid anyway.
8813	 */
8814	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8815	 || ((lba + num_blocks) < lba)) {
8816		ctl_set_lba_out_of_range(ctsio);
8817		ctl_done((union ctl_io *)ctsio);
8818		return (CTL_RETVAL_COMPLETE);
8819	}
8820
8821	/*
8822	 * According to SBC-3, a transfer length of 0 is not an error.
8823	 */
8824	if (num_blocks == 0) {
8825		ctl_set_success(ctsio);
8826		ctl_done((union ctl_io *)ctsio);
8827		return (CTL_RETVAL_COMPLETE);
8828	}
8829
8830	/* Set FUA if write cache is disabled. */
8831	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8832	    SCP_WCE) == 0)
8833		flags |= CTL_LLF_FUA;
8834
8835	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8836	ctsio->kern_rel_offset = 0;
8837
8838	/*
8839	 * Set the IO_CONT flag, so that if this I/O gets passed to
8840	 * ctl_data_submit_done(), it'll get passed back to
8841	 * ctl_ctl_cnw_cont() for further processing.
8842	 */
8843	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8844	ctsio->io_cont = ctl_cnw_cont;
8845
8846	lbalen = (struct ctl_lba_len_flags *)
8847	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8848	lbalen->lba = lba;
8849	lbalen->len = num_blocks;
8850	lbalen->flags = CTL_LLF_COMPARE | flags;
8851
8852	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8853	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8854	return (retval);
8855}
8856
8857int
8858ctl_verify(struct ctl_scsiio *ctsio)
8859{
8860	struct ctl_lun *lun;
8861	struct ctl_lba_len_flags *lbalen;
8862	uint64_t lba;
8863	uint32_t num_blocks;
8864	int bytchk, flags;
8865	int retval;
8866
8867	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8868
8869	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8870
8871	bytchk = 0;
8872	flags = CTL_LLF_FUA;
8873	switch (ctsio->cdb[0]) {
8874	case VERIFY_10: {
8875		struct scsi_verify_10 *cdb;
8876
8877		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8878		if (cdb->byte2 & SVFY_BYTCHK)
8879			bytchk = 1;
8880		if (cdb->byte2 & SVFY_DPO)
8881			flags |= CTL_LLF_DPO;
8882		lba = scsi_4btoul(cdb->addr);
8883		num_blocks = scsi_2btoul(cdb->length);
8884		break;
8885	}
8886	case VERIFY_12: {
8887		struct scsi_verify_12 *cdb;
8888
8889		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8890		if (cdb->byte2 & SVFY_BYTCHK)
8891			bytchk = 1;
8892		if (cdb->byte2 & SVFY_DPO)
8893			flags |= CTL_LLF_DPO;
8894		lba = scsi_4btoul(cdb->addr);
8895		num_blocks = scsi_4btoul(cdb->length);
8896		break;
8897	}
8898	case VERIFY_16: {
8899		struct scsi_rw_16 *cdb;
8900
8901		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8902		if (cdb->byte2 & SVFY_BYTCHK)
8903			bytchk = 1;
8904		if (cdb->byte2 & SVFY_DPO)
8905			flags |= CTL_LLF_DPO;
8906		lba = scsi_8btou64(cdb->addr);
8907		num_blocks = scsi_4btoul(cdb->length);
8908		break;
8909	}
8910	default:
8911		/*
8912		 * We got a command we don't support.  This shouldn't
8913		 * happen, commands should be filtered out above us.
8914		 */
8915		ctl_set_invalid_opcode(ctsio);
8916		ctl_done((union ctl_io *)ctsio);
8917		return (CTL_RETVAL_COMPLETE);
8918	}
8919
8920	/*
8921	 * The first check is to make sure we're in bounds, the second
8922	 * check is to catch wrap-around problems.  If the lba + num blocks
8923	 * is less than the lba, then we've wrapped around and the block
8924	 * range is invalid anyway.
8925	 */
8926	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8927	 || ((lba + num_blocks) < lba)) {
8928		ctl_set_lba_out_of_range(ctsio);
8929		ctl_done((union ctl_io *)ctsio);
8930		return (CTL_RETVAL_COMPLETE);
8931	}
8932
8933	/*
8934	 * According to SBC-3, a transfer length of 0 is not an error.
8935	 */
8936	if (num_blocks == 0) {
8937		ctl_set_success(ctsio);
8938		ctl_done((union ctl_io *)ctsio);
8939		return (CTL_RETVAL_COMPLETE);
8940	}
8941
8942	lbalen = (struct ctl_lba_len_flags *)
8943	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8944	lbalen->lba = lba;
8945	lbalen->len = num_blocks;
8946	if (bytchk) {
8947		lbalen->flags = CTL_LLF_COMPARE | flags;
8948		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8949	} else {
8950		lbalen->flags = CTL_LLF_VERIFY | flags;
8951		ctsio->kern_total_len = 0;
8952	}
8953	ctsio->kern_rel_offset = 0;
8954
8955	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8956	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8957	return (retval);
8958}
8959
8960int
8961ctl_report_luns(struct ctl_scsiio *ctsio)
8962{
8963	struct ctl_softc *softc;
8964	struct scsi_report_luns *cdb;
8965	struct scsi_report_luns_data *lun_data;
8966	struct ctl_lun *lun, *request_lun;
8967	struct ctl_port *port;
8968	int num_luns, retval;
8969	uint32_t alloc_len, lun_datalen;
8970	int num_filled;
8971	uint32_t initidx, targ_lun_id, lun_id;
8972
8973	retval = CTL_RETVAL_COMPLETE;
8974	cdb = (struct scsi_report_luns *)ctsio->cdb;
8975	port = ctl_io_port(&ctsio->io_hdr);
8976	softc = port->ctl_softc;
8977
8978	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8979
8980	mtx_lock(&softc->ctl_lock);
8981	num_luns = 0;
8982	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8983		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8984			num_luns++;
8985	}
8986	mtx_unlock(&softc->ctl_lock);
8987
8988	switch (cdb->select_report) {
8989	case RPL_REPORT_DEFAULT:
8990	case RPL_REPORT_ALL:
8991	case RPL_REPORT_NONSUBSID:
8992		break;
8993	case RPL_REPORT_WELLKNOWN:
8994	case RPL_REPORT_ADMIN:
8995	case RPL_REPORT_CONGLOM:
8996		num_luns = 0;
8997		break;
8998	default:
8999		ctl_set_invalid_field(ctsio,
9000				      /*sks_valid*/ 1,
9001				      /*command*/ 1,
9002				      /*field*/ 2,
9003				      /*bit_valid*/ 0,
9004				      /*bit*/ 0);
9005		ctl_done((union ctl_io *)ctsio);
9006		return (retval);
9007		break; /* NOTREACHED */
9008	}
9009
9010	alloc_len = scsi_4btoul(cdb->length);
9011	/*
9012	 * The initiator has to allocate at least 16 bytes for this request,
9013	 * so he can at least get the header and the first LUN.  Otherwise
9014	 * we reject the request (per SPC-3 rev 14, section 6.21).
9015	 */
9016	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9017	    sizeof(struct scsi_report_luns_lundata))) {
9018		ctl_set_invalid_field(ctsio,
9019				      /*sks_valid*/ 1,
9020				      /*command*/ 1,
9021				      /*field*/ 6,
9022				      /*bit_valid*/ 0,
9023				      /*bit*/ 0);
9024		ctl_done((union ctl_io *)ctsio);
9025		return (retval);
9026	}
9027
9028	request_lun = (struct ctl_lun *)
9029		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9030
9031	lun_datalen = sizeof(*lun_data) +
9032		(num_luns * sizeof(struct scsi_report_luns_lundata));
9033
9034	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9035	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9036	ctsio->kern_sg_entries = 0;
9037
9038	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9039
9040	mtx_lock(&softc->ctl_lock);
9041	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9042		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9043		if (lun_id >= CTL_MAX_LUNS)
9044			continue;
9045		lun = softc->ctl_luns[lun_id];
9046		if (lun == NULL)
9047			continue;
9048
9049		if (targ_lun_id <= 0xff) {
9050			/*
9051			 * Peripheral addressing method, bus number 0.
9052			 */
9053			lun_data->luns[num_filled].lundata[0] =
9054				RPL_LUNDATA_ATYP_PERIPH;
9055			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9056			num_filled++;
9057		} else if (targ_lun_id <= 0x3fff) {
9058			/*
9059			 * Flat addressing method.
9060			 */
9061			lun_data->luns[num_filled].lundata[0] =
9062				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9063			lun_data->luns[num_filled].lundata[1] =
9064				(targ_lun_id & 0xff);
9065			num_filled++;
9066		} else if (targ_lun_id <= 0xffffff) {
9067			/*
9068			 * Extended flat addressing method.
9069			 */
9070			lun_data->luns[num_filled].lundata[0] =
9071			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9072			scsi_ulto3b(targ_lun_id,
9073			    &lun_data->luns[num_filled].lundata[1]);
9074			num_filled++;
9075		} else {
9076			printf("ctl_report_luns: bogus LUN number %jd, "
9077			       "skipping\n", (intmax_t)targ_lun_id);
9078		}
9079		/*
9080		 * According to SPC-3, rev 14 section 6.21:
9081		 *
9082		 * "The execution of a REPORT LUNS command to any valid and
9083		 * installed logical unit shall clear the REPORTED LUNS DATA
9084		 * HAS CHANGED unit attention condition for all logical
9085		 * units of that target with respect to the requesting
9086		 * initiator. A valid and installed logical unit is one
9087		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9088		 * INQUIRY data (see 6.4.2)."
9089		 *
9090		 * If request_lun is NULL, the LUN this report luns command
9091		 * was issued to is either disabled or doesn't exist. In that
9092		 * case, we shouldn't clear any pending lun change unit
9093		 * attention.
9094		 */
9095		if (request_lun != NULL) {
9096			mtx_lock(&lun->lun_lock);
9097			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9098			mtx_unlock(&lun->lun_lock);
9099		}
9100	}
9101	mtx_unlock(&softc->ctl_lock);
9102
9103	/*
9104	 * It's quite possible that we've returned fewer LUNs than we allocated
9105	 * space for.  Trim it.
9106	 */
9107	lun_datalen = sizeof(*lun_data) +
9108		(num_filled * sizeof(struct scsi_report_luns_lundata));
9109
9110	if (lun_datalen < alloc_len) {
9111		ctsio->residual = alloc_len - lun_datalen;
9112		ctsio->kern_data_len = lun_datalen;
9113		ctsio->kern_total_len = lun_datalen;
9114	} else {
9115		ctsio->residual = 0;
9116		ctsio->kern_data_len = alloc_len;
9117		ctsio->kern_total_len = alloc_len;
9118	}
9119	ctsio->kern_data_resid = 0;
9120	ctsio->kern_rel_offset = 0;
9121	ctsio->kern_sg_entries = 0;
9122
9123	/*
9124	 * We set this to the actual data length, regardless of how much
9125	 * space we actually have to return results.  If the user looks at
9126	 * this value, he'll know whether or not he allocated enough space
9127	 * and reissue the command if necessary.  We don't support well
9128	 * known logical units, so if the user asks for that, return none.
9129	 */
9130	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9131
9132	/*
9133	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9134	 * this request.
9135	 */
9136	ctl_set_success(ctsio);
9137	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9138	ctsio->be_move_done = ctl_config_move_done;
9139	ctl_datamove((union ctl_io *)ctsio);
9140	return (retval);
9141}
9142
9143int
9144ctl_request_sense(struct ctl_scsiio *ctsio)
9145{
9146	struct scsi_request_sense *cdb;
9147	struct scsi_sense_data *sense_ptr;
9148	struct ctl_softc *ctl_softc;
9149	struct ctl_lun *lun;
9150	uint32_t initidx;
9151	int have_error;
9152	scsi_sense_data_type sense_format;
9153	ctl_ua_type ua_type;
9154
9155	cdb = (struct scsi_request_sense *)ctsio->cdb;
9156
9157	ctl_softc = control_softc;
9158	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9159
9160	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9161
9162	/*
9163	 * Determine which sense format the user wants.
9164	 */
9165	if (cdb->byte2 & SRS_DESC)
9166		sense_format = SSD_TYPE_DESC;
9167	else
9168		sense_format = SSD_TYPE_FIXED;
9169
9170	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9171	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9172	ctsio->kern_sg_entries = 0;
9173
9174	/*
9175	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9176	 * larger than the largest allowed value for the length field in the
9177	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9178	 */
9179	ctsio->residual = 0;
9180	ctsio->kern_data_len = cdb->length;
9181	ctsio->kern_total_len = cdb->length;
9182
9183	ctsio->kern_data_resid = 0;
9184	ctsio->kern_rel_offset = 0;
9185	ctsio->kern_sg_entries = 0;
9186
9187	/*
9188	 * If we don't have a LUN, we don't have any pending sense.
9189	 */
9190	if (lun == NULL)
9191		goto no_sense;
9192
9193	have_error = 0;
9194	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9195	/*
9196	 * Check for pending sense, and then for pending unit attentions.
9197	 * Pending sense gets returned first, then pending unit attentions.
9198	 */
9199	mtx_lock(&lun->lun_lock);
9200#ifdef CTL_WITH_CA
9201	if (ctl_is_set(lun->have_ca, initidx)) {
9202		scsi_sense_data_type stored_format;
9203
9204		/*
9205		 * Check to see which sense format was used for the stored
9206		 * sense data.
9207		 */
9208		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9209
9210		/*
9211		 * If the user requested a different sense format than the
9212		 * one we stored, then we need to convert it to the other
9213		 * format.  If we're going from descriptor to fixed format
9214		 * sense data, we may lose things in translation, depending
9215		 * on what options were used.
9216		 *
9217		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9218		 * for some reason we'll just copy it out as-is.
9219		 */
9220		if ((stored_format == SSD_TYPE_FIXED)
9221		 && (sense_format == SSD_TYPE_DESC))
9222			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9223			    &lun->pending_sense[initidx],
9224			    (struct scsi_sense_data_desc *)sense_ptr);
9225		else if ((stored_format == SSD_TYPE_DESC)
9226		      && (sense_format == SSD_TYPE_FIXED))
9227			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9228			    &lun->pending_sense[initidx],
9229			    (struct scsi_sense_data_fixed *)sense_ptr);
9230		else
9231			memcpy(sense_ptr, &lun->pending_sense[initidx],
9232			       MIN(sizeof(*sense_ptr),
9233			       sizeof(lun->pending_sense[initidx])));
9234
9235		ctl_clear_mask(lun->have_ca, initidx);
9236		have_error = 1;
9237	} else
9238#endif
9239	{
9240		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9241		if (ua_type != CTL_UA_NONE)
9242			have_error = 1;
9243		if (ua_type == CTL_UA_LUN_CHANGE) {
9244			mtx_unlock(&lun->lun_lock);
9245			mtx_lock(&ctl_softc->ctl_lock);
9246			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9247			mtx_unlock(&ctl_softc->ctl_lock);
9248			mtx_lock(&lun->lun_lock);
9249		}
9250
9251	}
9252	mtx_unlock(&lun->lun_lock);
9253
9254	/*
9255	 * We already have a pending error, return it.
9256	 */
9257	if (have_error != 0) {
9258		/*
9259		 * We report the SCSI status as OK, since the status of the
9260		 * request sense command itself is OK.
9261		 * We report 0 for the sense length, because we aren't doing
9262		 * autosense in this case.  We're reporting sense as
9263		 * parameter data.
9264		 */
9265		ctl_set_success(ctsio);
9266		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9267		ctsio->be_move_done = ctl_config_move_done;
9268		ctl_datamove((union ctl_io *)ctsio);
9269		return (CTL_RETVAL_COMPLETE);
9270	}
9271
9272no_sense:
9273
9274	/*
9275	 * No sense information to report, so we report that everything is
9276	 * okay.
9277	 */
9278	ctl_set_sense_data(sense_ptr,
9279			   lun,
9280			   sense_format,
9281			   /*current_error*/ 1,
9282			   /*sense_key*/ SSD_KEY_NO_SENSE,
9283			   /*asc*/ 0x00,
9284			   /*ascq*/ 0x00,
9285			   SSD_ELEM_NONE);
9286
9287	/*
9288	 * We report 0 for the sense length, because we aren't doing
9289	 * autosense in this case.  We're reporting sense as parameter data.
9290	 */
9291	ctl_set_success(ctsio);
9292	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9293	ctsio->be_move_done = ctl_config_move_done;
9294	ctl_datamove((union ctl_io *)ctsio);
9295	return (CTL_RETVAL_COMPLETE);
9296}
9297
9298int
9299ctl_tur(struct ctl_scsiio *ctsio)
9300{
9301
9302	CTL_DEBUG_PRINT(("ctl_tur\n"));
9303
9304	ctl_set_success(ctsio);
9305	ctl_done((union ctl_io *)ctsio);
9306
9307	return (CTL_RETVAL_COMPLETE);
9308}
9309
9310/*
9311 * SCSI VPD page 0x00, the Supported VPD Pages page.
9312 */
9313static int
9314ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9315{
9316	struct scsi_vpd_supported_pages *pages;
9317	int sup_page_size;
9318	struct ctl_lun *lun;
9319	int p;
9320
9321	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9322
9323	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9324	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9325	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9326	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9327	ctsio->kern_sg_entries = 0;
9328
9329	if (sup_page_size < alloc_len) {
9330		ctsio->residual = alloc_len - sup_page_size;
9331		ctsio->kern_data_len = sup_page_size;
9332		ctsio->kern_total_len = sup_page_size;
9333	} else {
9334		ctsio->residual = 0;
9335		ctsio->kern_data_len = alloc_len;
9336		ctsio->kern_total_len = alloc_len;
9337	}
9338	ctsio->kern_data_resid = 0;
9339	ctsio->kern_rel_offset = 0;
9340	ctsio->kern_sg_entries = 0;
9341
9342	/*
9343	 * The control device is always connected.  The disk device, on the
9344	 * other hand, may not be online all the time.  Need to change this
9345	 * to figure out whether the disk device is actually online or not.
9346	 */
9347	if (lun != NULL)
9348		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9349				lun->be_lun->lun_type;
9350	else
9351		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9352
9353	p = 0;
9354	/* Supported VPD pages */
9355	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9356	/* Serial Number */
9357	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9358	/* Device Identification */
9359	pages->page_list[p++] = SVPD_DEVICE_ID;
9360	/* Extended INQUIRY Data */
9361	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9362	/* Mode Page Policy */
9363	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9364	/* SCSI Ports */
9365	pages->page_list[p++] = SVPD_SCSI_PORTS;
9366	/* Third-party Copy */
9367	pages->page_list[p++] = SVPD_SCSI_TPC;
9368	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9369		/* Block limits */
9370		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9371		/* Block Device Characteristics */
9372		pages->page_list[p++] = SVPD_BDC;
9373		/* Logical Block Provisioning */
9374		pages->page_list[p++] = SVPD_LBP;
9375	}
9376	pages->length = p;
9377
9378	ctl_set_success(ctsio);
9379	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9380	ctsio->be_move_done = ctl_config_move_done;
9381	ctl_datamove((union ctl_io *)ctsio);
9382	return (CTL_RETVAL_COMPLETE);
9383}
9384
9385/*
9386 * SCSI VPD page 0x80, the Unit Serial Number page.
9387 */
9388static int
9389ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9390{
9391	struct scsi_vpd_unit_serial_number *sn_ptr;
9392	struct ctl_lun *lun;
9393	int data_len;
9394
9395	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9396
9397	data_len = 4 + CTL_SN_LEN;
9398	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9399	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9400	if (data_len < alloc_len) {
9401		ctsio->residual = alloc_len - data_len;
9402		ctsio->kern_data_len = data_len;
9403		ctsio->kern_total_len = data_len;
9404	} else {
9405		ctsio->residual = 0;
9406		ctsio->kern_data_len = alloc_len;
9407		ctsio->kern_total_len = alloc_len;
9408	}
9409	ctsio->kern_data_resid = 0;
9410	ctsio->kern_rel_offset = 0;
9411	ctsio->kern_sg_entries = 0;
9412
9413	/*
9414	 * The control device is always connected.  The disk device, on the
9415	 * other hand, may not be online all the time.  Need to change this
9416	 * to figure out whether the disk device is actually online or not.
9417	 */
9418	if (lun != NULL)
9419		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9420				  lun->be_lun->lun_type;
9421	else
9422		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9423
9424	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9425	sn_ptr->length = CTL_SN_LEN;
9426	/*
9427	 * If we don't have a LUN, we just leave the serial number as
9428	 * all spaces.
9429	 */
9430	if (lun != NULL) {
9431		strncpy((char *)sn_ptr->serial_num,
9432			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9433	} else
9434		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9435
9436	ctl_set_success(ctsio);
9437	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9438	ctsio->be_move_done = ctl_config_move_done;
9439	ctl_datamove((union ctl_io *)ctsio);
9440	return (CTL_RETVAL_COMPLETE);
9441}
9442
9443
9444/*
9445 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9446 */
9447static int
9448ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9449{
9450	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9451	struct ctl_lun *lun;
9452	int data_len;
9453
9454	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9455
9456	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9457	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9458	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9459	ctsio->kern_sg_entries = 0;
9460
9461	if (data_len < alloc_len) {
9462		ctsio->residual = alloc_len - data_len;
9463		ctsio->kern_data_len = data_len;
9464		ctsio->kern_total_len = data_len;
9465	} else {
9466		ctsio->residual = 0;
9467		ctsio->kern_data_len = alloc_len;
9468		ctsio->kern_total_len = alloc_len;
9469	}
9470	ctsio->kern_data_resid = 0;
9471	ctsio->kern_rel_offset = 0;
9472	ctsio->kern_sg_entries = 0;
9473
9474	/*
9475	 * The control device is always connected.  The disk device, on the
9476	 * other hand, may not be online all the time.
9477	 */
9478	if (lun != NULL)
9479		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9480				     lun->be_lun->lun_type;
9481	else
9482		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9483	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9484	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9485	/*
9486	 * We support head of queue, ordered and simple tags.
9487	 */
9488	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9489	/*
9490	 * Volatile cache supported.
9491	 */
9492	eid_ptr->flags3 = SVPD_EID_V_SUP;
9493
9494	/*
9495	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9496	 * attention for a particular IT nexus on all LUNs once we report
9497	 * it to that nexus once.  This bit is required as of SPC-4.
9498	 */
9499	eid_ptr->flags4 = SVPD_EID_LUICLT;
9500
9501	/*
9502	 * XXX KDM in order to correctly answer this, we would need
9503	 * information from the SIM to determine how much sense data it
9504	 * can send.  So this would really be a path inquiry field, most
9505	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9506	 * but the hardware may or may not be able to support that much.
9507	 * 0 just means that the maximum sense data length is not reported.
9508	 */
9509	eid_ptr->max_sense_length = 0;
9510
9511	ctl_set_success(ctsio);
9512	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9513	ctsio->be_move_done = ctl_config_move_done;
9514	ctl_datamove((union ctl_io *)ctsio);
9515	return (CTL_RETVAL_COMPLETE);
9516}
9517
9518static int
9519ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9520{
9521	struct scsi_vpd_mode_page_policy *mpp_ptr;
9522	struct ctl_lun *lun;
9523	int data_len;
9524
9525	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9526
9527	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9528	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9529
9530	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9531	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9532	ctsio->kern_sg_entries = 0;
9533
9534	if (data_len < alloc_len) {
9535		ctsio->residual = alloc_len - data_len;
9536		ctsio->kern_data_len = data_len;
9537		ctsio->kern_total_len = data_len;
9538	} else {
9539		ctsio->residual = 0;
9540		ctsio->kern_data_len = alloc_len;
9541		ctsio->kern_total_len = alloc_len;
9542	}
9543	ctsio->kern_data_resid = 0;
9544	ctsio->kern_rel_offset = 0;
9545	ctsio->kern_sg_entries = 0;
9546
9547	/*
9548	 * The control device is always connected.  The disk device, on the
9549	 * other hand, may not be online all the time.
9550	 */
9551	if (lun != NULL)
9552		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9553				     lun->be_lun->lun_type;
9554	else
9555		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9556	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9557	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9558	mpp_ptr->descr[0].page_code = 0x3f;
9559	mpp_ptr->descr[0].subpage_code = 0xff;
9560	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9561
9562	ctl_set_success(ctsio);
9563	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9564	ctsio->be_move_done = ctl_config_move_done;
9565	ctl_datamove((union ctl_io *)ctsio);
9566	return (CTL_RETVAL_COMPLETE);
9567}
9568
9569/*
9570 * SCSI VPD page 0x83, the Device Identification page.
9571 */
9572static int
9573ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9574{
9575	struct scsi_vpd_device_id *devid_ptr;
9576	struct scsi_vpd_id_descriptor *desc;
9577	struct ctl_softc *softc;
9578	struct ctl_lun *lun;
9579	struct ctl_port *port;
9580	int data_len;
9581	uint8_t proto;
9582
9583	softc = control_softc;
9584
9585	port = ctl_io_port(&ctsio->io_hdr);
9586	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9587
9588	data_len = sizeof(struct scsi_vpd_device_id) +
9589	    sizeof(struct scsi_vpd_id_descriptor) +
9590		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9591	    sizeof(struct scsi_vpd_id_descriptor) +
9592		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9593	if (lun && lun->lun_devid)
9594		data_len += lun->lun_devid->len;
9595	if (port && port->port_devid)
9596		data_len += port->port_devid->len;
9597	if (port && port->target_devid)
9598		data_len += port->target_devid->len;
9599
9600	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9601	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9602	ctsio->kern_sg_entries = 0;
9603
9604	if (data_len < alloc_len) {
9605		ctsio->residual = alloc_len - data_len;
9606		ctsio->kern_data_len = data_len;
9607		ctsio->kern_total_len = data_len;
9608	} else {
9609		ctsio->residual = 0;
9610		ctsio->kern_data_len = alloc_len;
9611		ctsio->kern_total_len = alloc_len;
9612	}
9613	ctsio->kern_data_resid = 0;
9614	ctsio->kern_rel_offset = 0;
9615	ctsio->kern_sg_entries = 0;
9616
9617	/*
9618	 * The control device is always connected.  The disk device, on the
9619	 * other hand, may not be online all the time.
9620	 */
9621	if (lun != NULL)
9622		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9623				     lun->be_lun->lun_type;
9624	else
9625		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9626	devid_ptr->page_code = SVPD_DEVICE_ID;
9627	scsi_ulto2b(data_len - 4, devid_ptr->length);
9628
9629	if (port && port->port_type == CTL_PORT_FC)
9630		proto = SCSI_PROTO_FC << 4;
9631	else if (port && port->port_type == CTL_PORT_ISCSI)
9632		proto = SCSI_PROTO_ISCSI << 4;
9633	else
9634		proto = SCSI_PROTO_SPI << 4;
9635	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9636
9637	/*
9638	 * We're using a LUN association here.  i.e., this device ID is a
9639	 * per-LUN identifier.
9640	 */
9641	if (lun && lun->lun_devid) {
9642		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9643		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9644		    lun->lun_devid->len);
9645	}
9646
9647	/*
9648	 * This is for the WWPN which is a port association.
9649	 */
9650	if (port && port->port_devid) {
9651		memcpy(desc, port->port_devid->data, port->port_devid->len);
9652		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9653		    port->port_devid->len);
9654	}
9655
9656	/*
9657	 * This is for the Relative Target Port(type 4h) identifier
9658	 */
9659	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9660	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9661	    SVPD_ID_TYPE_RELTARG;
9662	desc->length = 4;
9663	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9664	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9665	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9666
9667	/*
9668	 * This is for the Target Port Group(type 5h) identifier
9669	 */
9670	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9671	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9672	    SVPD_ID_TYPE_TPORTGRP;
9673	desc->length = 4;
9674	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9675	    &desc->identifier[2]);
9676	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9677	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9678
9679	/*
9680	 * This is for the Target identifier
9681	 */
9682	if (port && port->target_devid) {
9683		memcpy(desc, port->target_devid->data, port->target_devid->len);
9684	}
9685
9686	ctl_set_success(ctsio);
9687	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9688	ctsio->be_move_done = ctl_config_move_done;
9689	ctl_datamove((union ctl_io *)ctsio);
9690	return (CTL_RETVAL_COMPLETE);
9691}
9692
9693static int
9694ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9695{
9696	struct ctl_softc *softc = control_softc;
9697	struct scsi_vpd_scsi_ports *sp;
9698	struct scsi_vpd_port_designation *pd;
9699	struct scsi_vpd_port_designation_cont *pdc;
9700	struct ctl_lun *lun;
9701	struct ctl_port *port;
9702	int data_len, num_target_ports, iid_len, id_len;
9703
9704	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9705
9706	num_target_ports = 0;
9707	iid_len = 0;
9708	id_len = 0;
9709	mtx_lock(&softc->ctl_lock);
9710	STAILQ_FOREACH(port, &softc->port_list, links) {
9711		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9712			continue;
9713		if (lun != NULL &&
9714		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9715			continue;
9716		num_target_ports++;
9717		if (port->init_devid)
9718			iid_len += port->init_devid->len;
9719		if (port->port_devid)
9720			id_len += port->port_devid->len;
9721	}
9722	mtx_unlock(&softc->ctl_lock);
9723
9724	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9725	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9726	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9727	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9728	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9729	ctsio->kern_sg_entries = 0;
9730
9731	if (data_len < alloc_len) {
9732		ctsio->residual = alloc_len - data_len;
9733		ctsio->kern_data_len = data_len;
9734		ctsio->kern_total_len = data_len;
9735	} else {
9736		ctsio->residual = 0;
9737		ctsio->kern_data_len = alloc_len;
9738		ctsio->kern_total_len = alloc_len;
9739	}
9740	ctsio->kern_data_resid = 0;
9741	ctsio->kern_rel_offset = 0;
9742	ctsio->kern_sg_entries = 0;
9743
9744	/*
9745	 * The control device is always connected.  The disk device, on the
9746	 * other hand, may not be online all the time.  Need to change this
9747	 * to figure out whether the disk device is actually online or not.
9748	 */
9749	if (lun != NULL)
9750		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9751				  lun->be_lun->lun_type;
9752	else
9753		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9754
9755	sp->page_code = SVPD_SCSI_PORTS;
9756	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9757	    sp->page_length);
9758	pd = &sp->design[0];
9759
9760	mtx_lock(&softc->ctl_lock);
9761	STAILQ_FOREACH(port, &softc->port_list, links) {
9762		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9763			continue;
9764		if (lun != NULL &&
9765		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9766			continue;
9767		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9768		if (port->init_devid) {
9769			iid_len = port->init_devid->len;
9770			memcpy(pd->initiator_transportid,
9771			    port->init_devid->data, port->init_devid->len);
9772		} else
9773			iid_len = 0;
9774		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9775		pdc = (struct scsi_vpd_port_designation_cont *)
9776		    (&pd->initiator_transportid[iid_len]);
9777		if (port->port_devid) {
9778			id_len = port->port_devid->len;
9779			memcpy(pdc->target_port_descriptors,
9780			    port->port_devid->data, port->port_devid->len);
9781		} else
9782			id_len = 0;
9783		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9784		pd = (struct scsi_vpd_port_designation *)
9785		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9786	}
9787	mtx_unlock(&softc->ctl_lock);
9788
9789	ctl_set_success(ctsio);
9790	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9791	ctsio->be_move_done = ctl_config_move_done;
9792	ctl_datamove((union ctl_io *)ctsio);
9793	return (CTL_RETVAL_COMPLETE);
9794}
9795
9796static int
9797ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9798{
9799	struct scsi_vpd_block_limits *bl_ptr;
9800	struct ctl_lun *lun;
9801
9802	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9803
9804	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9805	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9806	ctsio->kern_sg_entries = 0;
9807
9808	if (sizeof(*bl_ptr) < alloc_len) {
9809		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9810		ctsio->kern_data_len = sizeof(*bl_ptr);
9811		ctsio->kern_total_len = sizeof(*bl_ptr);
9812	} else {
9813		ctsio->residual = 0;
9814		ctsio->kern_data_len = alloc_len;
9815		ctsio->kern_total_len = alloc_len;
9816	}
9817	ctsio->kern_data_resid = 0;
9818	ctsio->kern_rel_offset = 0;
9819	ctsio->kern_sg_entries = 0;
9820
9821	/*
9822	 * The control device is always connected.  The disk device, on the
9823	 * other hand, may not be online all the time.  Need to change this
9824	 * to figure out whether the disk device is actually online or not.
9825	 */
9826	if (lun != NULL)
9827		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9828				  lun->be_lun->lun_type;
9829	else
9830		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9831
9832	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9833	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9834	bl_ptr->max_cmp_write_len = 0xff;
9835	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9836	if (lun != NULL) {
9837		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9838		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9839			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9840			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9841			if (lun->be_lun->ublockexp != 0) {
9842				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9843				    bl_ptr->opt_unmap_grain);
9844				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9845				    bl_ptr->unmap_grain_align);
9846			}
9847		}
9848		scsi_ulto4b(lun->be_lun->atomicblock,
9849		    bl_ptr->max_atomic_transfer_length);
9850		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9851		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9852		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9853		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9854	}
9855	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9856
9857	ctl_set_success(ctsio);
9858	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9859	ctsio->be_move_done = ctl_config_move_done;
9860	ctl_datamove((union ctl_io *)ctsio);
9861	return (CTL_RETVAL_COMPLETE);
9862}
9863
9864static int
9865ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9866{
9867	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9868	struct ctl_lun *lun;
9869	const char *value;
9870	u_int i;
9871
9872	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9873
9874	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9875	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9876	ctsio->kern_sg_entries = 0;
9877
9878	if (sizeof(*bdc_ptr) < alloc_len) {
9879		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9880		ctsio->kern_data_len = sizeof(*bdc_ptr);
9881		ctsio->kern_total_len = sizeof(*bdc_ptr);
9882	} else {
9883		ctsio->residual = 0;
9884		ctsio->kern_data_len = alloc_len;
9885		ctsio->kern_total_len = alloc_len;
9886	}
9887	ctsio->kern_data_resid = 0;
9888	ctsio->kern_rel_offset = 0;
9889	ctsio->kern_sg_entries = 0;
9890
9891	/*
9892	 * The control device is always connected.  The disk device, on the
9893	 * other hand, may not be online all the time.  Need to change this
9894	 * to figure out whether the disk device is actually online or not.
9895	 */
9896	if (lun != NULL)
9897		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9898				  lun->be_lun->lun_type;
9899	else
9900		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9901	bdc_ptr->page_code = SVPD_BDC;
9902	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9903	if (lun != NULL &&
9904	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9905		i = strtol(value, NULL, 0);
9906	else
9907		i = CTL_DEFAULT_ROTATION_RATE;
9908	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9909	if (lun != NULL &&
9910	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9911		i = strtol(value, NULL, 0);
9912	else
9913		i = 0;
9914	bdc_ptr->wab_wac_ff = (i & 0x0f);
9915	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9916
9917	ctl_set_success(ctsio);
9918	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9919	ctsio->be_move_done = ctl_config_move_done;
9920	ctl_datamove((union ctl_io *)ctsio);
9921	return (CTL_RETVAL_COMPLETE);
9922}
9923
9924static int
9925ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9926{
9927	struct scsi_vpd_logical_block_prov *lbp_ptr;
9928	struct ctl_lun *lun;
9929
9930	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9931
9932	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9933	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9934	ctsio->kern_sg_entries = 0;
9935
9936	if (sizeof(*lbp_ptr) < alloc_len) {
9937		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9938		ctsio->kern_data_len = sizeof(*lbp_ptr);
9939		ctsio->kern_total_len = sizeof(*lbp_ptr);
9940	} else {
9941		ctsio->residual = 0;
9942		ctsio->kern_data_len = alloc_len;
9943		ctsio->kern_total_len = alloc_len;
9944	}
9945	ctsio->kern_data_resid = 0;
9946	ctsio->kern_rel_offset = 0;
9947	ctsio->kern_sg_entries = 0;
9948
9949	/*
9950	 * The control device is always connected.  The disk device, on the
9951	 * other hand, may not be online all the time.  Need to change this
9952	 * to figure out whether the disk device is actually online or not.
9953	 */
9954	if (lun != NULL)
9955		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9956				  lun->be_lun->lun_type;
9957	else
9958		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9959
9960	lbp_ptr->page_code = SVPD_LBP;
9961	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9962	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9963	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9964		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9965		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9966		lbp_ptr->prov_type = SVPD_LBP_THIN;
9967	}
9968
9969	ctl_set_success(ctsio);
9970	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9971	ctsio->be_move_done = ctl_config_move_done;
9972	ctl_datamove((union ctl_io *)ctsio);
9973	return (CTL_RETVAL_COMPLETE);
9974}
9975
9976/*
9977 * INQUIRY with the EVPD bit set.
9978 */
9979static int
9980ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9981{
9982	struct ctl_lun *lun;
9983	struct scsi_inquiry *cdb;
9984	int alloc_len, retval;
9985
9986	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9987	cdb = (struct scsi_inquiry *)ctsio->cdb;
9988	alloc_len = scsi_2btoul(cdb->length);
9989
9990	switch (cdb->page_code) {
9991	case SVPD_SUPPORTED_PAGES:
9992		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9993		break;
9994	case SVPD_UNIT_SERIAL_NUMBER:
9995		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9996		break;
9997	case SVPD_DEVICE_ID:
9998		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9999		break;
10000	case SVPD_EXTENDED_INQUIRY_DATA:
10001		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10002		break;
10003	case SVPD_MODE_PAGE_POLICY:
10004		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10005		break;
10006	case SVPD_SCSI_PORTS:
10007		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10008		break;
10009	case SVPD_SCSI_TPC:
10010		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10011		break;
10012	case SVPD_BLOCK_LIMITS:
10013		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10014			goto err;
10015		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10016		break;
10017	case SVPD_BDC:
10018		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10019			goto err;
10020		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10021		break;
10022	case SVPD_LBP:
10023		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10024			goto err;
10025		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10026		break;
10027	default:
10028err:
10029		ctl_set_invalid_field(ctsio,
10030				      /*sks_valid*/ 1,
10031				      /*command*/ 1,
10032				      /*field*/ 2,
10033				      /*bit_valid*/ 0,
10034				      /*bit*/ 0);
10035		ctl_done((union ctl_io *)ctsio);
10036		retval = CTL_RETVAL_COMPLETE;
10037		break;
10038	}
10039
10040	return (retval);
10041}
10042
10043/*
10044 * Standard INQUIRY data.
10045 */
10046static int
10047ctl_inquiry_std(struct ctl_scsiio *ctsio)
10048{
10049	struct scsi_inquiry_data *inq_ptr;
10050	struct scsi_inquiry *cdb;
10051	struct ctl_softc *softc = control_softc;
10052	struct ctl_port *port;
10053	struct ctl_lun *lun;
10054	char *val;
10055	uint32_t alloc_len, data_len;
10056	ctl_port_type port_type;
10057
10058	port = ctl_io_port(&ctsio->io_hdr);
10059	port_type = port->port_type;
10060	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10061		port_type = CTL_PORT_SCSI;
10062
10063	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10064	cdb = (struct scsi_inquiry *)ctsio->cdb;
10065	alloc_len = scsi_2btoul(cdb->length);
10066
10067	/*
10068	 * We malloc the full inquiry data size here and fill it
10069	 * in.  If the user only asks for less, we'll give him
10070	 * that much.
10071	 */
10072	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10073	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10074	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10075	ctsio->kern_sg_entries = 0;
10076	ctsio->kern_data_resid = 0;
10077	ctsio->kern_rel_offset = 0;
10078
10079	if (data_len < alloc_len) {
10080		ctsio->residual = alloc_len - data_len;
10081		ctsio->kern_data_len = data_len;
10082		ctsio->kern_total_len = data_len;
10083	} else {
10084		ctsio->residual = 0;
10085		ctsio->kern_data_len = alloc_len;
10086		ctsio->kern_total_len = alloc_len;
10087	}
10088
10089	if (lun != NULL) {
10090		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10091		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10092			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10093			    lun->be_lun->lun_type;
10094		} else {
10095			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10096			    lun->be_lun->lun_type;
10097		}
10098		if (lun->flags & CTL_LUN_REMOVABLE)
10099			inq_ptr->dev_qual2 |= SID_RMB;
10100	} else
10101		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10102
10103	/* RMB in byte 2 is 0 */
10104	inq_ptr->version = SCSI_REV_SPC4;
10105
10106	/*
10107	 * According to SAM-3, even if a device only supports a single
10108	 * level of LUN addressing, it should still set the HISUP bit:
10109	 *
10110	 * 4.9.1 Logical unit numbers overview
10111	 *
10112	 * All logical unit number formats described in this standard are
10113	 * hierarchical in structure even when only a single level in that
10114	 * hierarchy is used. The HISUP bit shall be set to one in the
10115	 * standard INQUIRY data (see SPC-2) when any logical unit number
10116	 * format described in this standard is used.  Non-hierarchical
10117	 * formats are outside the scope of this standard.
10118	 *
10119	 * Therefore we set the HiSup bit here.
10120	 *
10121	 * The reponse format is 2, per SPC-3.
10122	 */
10123	inq_ptr->response_format = SID_HiSup | 2;
10124
10125	inq_ptr->additional_length = data_len -
10126	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10127	CTL_DEBUG_PRINT(("additional_length = %d\n",
10128			 inq_ptr->additional_length));
10129
10130	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10131	if (port_type == CTL_PORT_SCSI)
10132		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10133	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10134	inq_ptr->flags = SID_CmdQue;
10135	if (port_type == CTL_PORT_SCSI)
10136		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10137
10138	/*
10139	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10140	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10141	 * name and 4 bytes for the revision.
10142	 */
10143	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10144	    "vendor")) == NULL) {
10145		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10146	} else {
10147		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10148		strncpy(inq_ptr->vendor, val,
10149		    min(sizeof(inq_ptr->vendor), strlen(val)));
10150	}
10151	if (lun == NULL) {
10152		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10153		    sizeof(inq_ptr->product));
10154	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10155		switch (lun->be_lun->lun_type) {
10156		case T_DIRECT:
10157			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10158			    sizeof(inq_ptr->product));
10159			break;
10160		case T_PROCESSOR:
10161			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10162			    sizeof(inq_ptr->product));
10163			break;
10164		case T_CDROM:
10165			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10166			    sizeof(inq_ptr->product));
10167			break;
10168		default:
10169			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10170			    sizeof(inq_ptr->product));
10171			break;
10172		}
10173	} else {
10174		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10175		strncpy(inq_ptr->product, val,
10176		    min(sizeof(inq_ptr->product), strlen(val)));
10177	}
10178
10179	/*
10180	 * XXX make this a macro somewhere so it automatically gets
10181	 * incremented when we make changes.
10182	 */
10183	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10184	    "revision")) == NULL) {
10185		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10186	} else {
10187		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10188		strncpy(inq_ptr->revision, val,
10189		    min(sizeof(inq_ptr->revision), strlen(val)));
10190	}
10191
10192	/*
10193	 * For parallel SCSI, we support double transition and single
10194	 * transition clocking.  We also support QAS (Quick Arbitration
10195	 * and Selection) and Information Unit transfers on both the
10196	 * control and array devices.
10197	 */
10198	if (port_type == CTL_PORT_SCSI)
10199		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10200				    SID_SPI_IUS;
10201
10202	/* SAM-5 (no version claimed) */
10203	scsi_ulto2b(0x00A0, inq_ptr->version1);
10204	/* SPC-4 (no version claimed) */
10205	scsi_ulto2b(0x0460, inq_ptr->version2);
10206	if (port_type == CTL_PORT_FC) {
10207		/* FCP-2 ANSI INCITS.350:2003 */
10208		scsi_ulto2b(0x0917, inq_ptr->version3);
10209	} else if (port_type == CTL_PORT_SCSI) {
10210		/* SPI-4 ANSI INCITS.362:200x */
10211		scsi_ulto2b(0x0B56, inq_ptr->version3);
10212	} else if (port_type == CTL_PORT_ISCSI) {
10213		/* iSCSI (no version claimed) */
10214		scsi_ulto2b(0x0960, inq_ptr->version3);
10215	} else if (port_type == CTL_PORT_SAS) {
10216		/* SAS (no version claimed) */
10217		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10218	}
10219
10220	if (lun == NULL) {
10221		/* SBC-4 (no version claimed) */
10222		scsi_ulto2b(0x0600, inq_ptr->version4);
10223	} else {
10224		switch (lun->be_lun->lun_type) {
10225		case T_DIRECT:
10226			/* SBC-4 (no version claimed) */
10227			scsi_ulto2b(0x0600, inq_ptr->version4);
10228			break;
10229		case T_PROCESSOR:
10230			break;
10231		case T_CDROM:
10232			/* MMC-6 (no version claimed) */
10233			scsi_ulto2b(0x04E0, inq_ptr->version4);
10234			break;
10235		default:
10236			break;
10237		}
10238	}
10239
10240	ctl_set_success(ctsio);
10241	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10242	ctsio->be_move_done = ctl_config_move_done;
10243	ctl_datamove((union ctl_io *)ctsio);
10244	return (CTL_RETVAL_COMPLETE);
10245}
10246
10247int
10248ctl_inquiry(struct ctl_scsiio *ctsio)
10249{
10250	struct scsi_inquiry *cdb;
10251	int retval;
10252
10253	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10254
10255	cdb = (struct scsi_inquiry *)ctsio->cdb;
10256	if (cdb->byte2 & SI_EVPD)
10257		retval = ctl_inquiry_evpd(ctsio);
10258	else if (cdb->page_code == 0)
10259		retval = ctl_inquiry_std(ctsio);
10260	else {
10261		ctl_set_invalid_field(ctsio,
10262				      /*sks_valid*/ 1,
10263				      /*command*/ 1,
10264				      /*field*/ 2,
10265				      /*bit_valid*/ 0,
10266				      /*bit*/ 0);
10267		ctl_done((union ctl_io *)ctsio);
10268		return (CTL_RETVAL_COMPLETE);
10269	}
10270
10271	return (retval);
10272}
10273
10274int
10275ctl_get_config(struct ctl_scsiio *ctsio)
10276{
10277	struct scsi_get_config_header *hdr;
10278	struct scsi_get_config_feature *feature;
10279	struct scsi_get_config *cdb;
10280	struct ctl_lun *lun;
10281	uint32_t alloc_len, data_len;
10282	int rt, starting;
10283
10284	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10285	cdb = (struct scsi_get_config *)ctsio->cdb;
10286	rt = (cdb->rt & SGC_RT_MASK);
10287	starting = scsi_2btoul(cdb->starting_feature);
10288	alloc_len = scsi_2btoul(cdb->length);
10289
10290	data_len = sizeof(struct scsi_get_config_header) +
10291	    sizeof(struct scsi_get_config_feature) + 8 +
10292	    sizeof(struct scsi_get_config_feature) + 8 +
10293	    sizeof(struct scsi_get_config_feature) + 4 +
10294	    sizeof(struct scsi_get_config_feature) + 4 +
10295	    sizeof(struct scsi_get_config_feature) + 8 +
10296	    sizeof(struct scsi_get_config_feature) +
10297	    sizeof(struct scsi_get_config_feature) + 4 +
10298	    sizeof(struct scsi_get_config_feature) + 4 +
10299	    sizeof(struct scsi_get_config_feature) + 4 +
10300	    sizeof(struct scsi_get_config_feature) + 4 +
10301	    sizeof(struct scsi_get_config_feature) + 4 +
10302	    sizeof(struct scsi_get_config_feature) + 4;
10303	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10304	ctsio->kern_sg_entries = 0;
10305	ctsio->kern_data_resid = 0;
10306	ctsio->kern_rel_offset = 0;
10307
10308	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10309	if (lun->flags & CTL_LUN_NO_MEDIA)
10310		scsi_ulto2b(0x0000, hdr->current_profile);
10311	else
10312		scsi_ulto2b(0x0010, hdr->current_profile);
10313	feature = (struct scsi_get_config_feature *)(hdr + 1);
10314
10315	if (starting > 0x003b)
10316		goto done;
10317	if (starting > 0x003a)
10318		goto f3b;
10319	if (starting > 0x002b)
10320		goto f3a;
10321	if (starting > 0x002a)
10322		goto f2b;
10323	if (starting > 0x001f)
10324		goto f2a;
10325	if (starting > 0x001e)
10326		goto f1f;
10327	if (starting > 0x001d)
10328		goto f1e;
10329	if (starting > 0x0010)
10330		goto f1d;
10331	if (starting > 0x0003)
10332		goto f10;
10333	if (starting > 0x0002)
10334		goto f3;
10335	if (starting > 0x0001)
10336		goto f2;
10337	if (starting > 0x0000)
10338		goto f1;
10339
10340	/* Profile List */
10341	scsi_ulto2b(0x0000, feature->feature_code);
10342	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10343	feature->add_length = 8;
10344	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10345	feature->feature_data[2] = 0x00;
10346	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10347	feature->feature_data[6] = 0x01;
10348	feature = (struct scsi_get_config_feature *)
10349	    &feature->feature_data[feature->add_length];
10350
10351f1:	/* Core */
10352	scsi_ulto2b(0x0001, feature->feature_code);
10353	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10354	feature->add_length = 8;
10355	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10356	feature->feature_data[4] = 0x03;
10357	feature = (struct scsi_get_config_feature *)
10358	    &feature->feature_data[feature->add_length];
10359
10360f2:	/* Morphing */
10361	scsi_ulto2b(0x0002, feature->feature_code);
10362	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10363	feature->add_length = 4;
10364	feature->feature_data[0] = 0x02;
10365	feature = (struct scsi_get_config_feature *)
10366	    &feature->feature_data[feature->add_length];
10367
10368f3:	/* Removable Medium */
10369	scsi_ulto2b(0x0003, feature->feature_code);
10370	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10371	feature->add_length = 4;
10372	feature->feature_data[0] = 0x39;
10373	feature = (struct scsi_get_config_feature *)
10374	    &feature->feature_data[feature->add_length];
10375
10376	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10377		goto done;
10378
10379f10:	/* Random Read */
10380	scsi_ulto2b(0x0010, feature->feature_code);
10381	feature->flags = 0x00;
10382	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10383		feature->flags |= SGC_F_CURRENT;
10384	feature->add_length = 8;
10385	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10386	scsi_ulto2b(1, &feature->feature_data[4]);
10387	feature->feature_data[6] = 0x00;
10388	feature = (struct scsi_get_config_feature *)
10389	    &feature->feature_data[feature->add_length];
10390
10391f1d:	/* Multi-Read */
10392	scsi_ulto2b(0x001D, feature->feature_code);
10393	feature->flags = 0x00;
10394	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10395		feature->flags |= SGC_F_CURRENT;
10396	feature->add_length = 0;
10397	feature = (struct scsi_get_config_feature *)
10398	    &feature->feature_data[feature->add_length];
10399
10400f1e:	/* CD Read */
10401	scsi_ulto2b(0x001E, feature->feature_code);
10402	feature->flags = 0x00;
10403	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10404		feature->flags |= SGC_F_CURRENT;
10405	feature->add_length = 4;
10406	feature->feature_data[0] = 0x00;
10407	feature = (struct scsi_get_config_feature *)
10408	    &feature->feature_data[feature->add_length];
10409
10410f1f:	/* DVD Read */
10411	scsi_ulto2b(0x001F, feature->feature_code);
10412	feature->flags = 0x08;
10413	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10414		feature->flags |= SGC_F_CURRENT;
10415	feature->add_length = 4;
10416	feature->feature_data[0] = 0x01;
10417	feature->feature_data[2] = 0x03;
10418	feature = (struct scsi_get_config_feature *)
10419	    &feature->feature_data[feature->add_length];
10420
10421f2a:	/* DVD+RW */
10422	scsi_ulto2b(0x002A, feature->feature_code);
10423	feature->flags = 0x04;
10424	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10425		feature->flags |= SGC_F_CURRENT;
10426	feature->add_length = 4;
10427	feature->feature_data[0] = 0x00;
10428	feature->feature_data[1] = 0x00;
10429	feature = (struct scsi_get_config_feature *)
10430	    &feature->feature_data[feature->add_length];
10431
10432f2b:	/* DVD+R */
10433	scsi_ulto2b(0x002B, feature->feature_code);
10434	feature->flags = 0x00;
10435	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10436		feature->flags |= SGC_F_CURRENT;
10437	feature->add_length = 4;
10438	feature->feature_data[0] = 0x00;
10439	feature = (struct scsi_get_config_feature *)
10440	    &feature->feature_data[feature->add_length];
10441
10442f3a:	/* DVD+RW Dual Layer */
10443	scsi_ulto2b(0x003A, feature->feature_code);
10444	feature->flags = 0x00;
10445	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10446		feature->flags |= SGC_F_CURRENT;
10447	feature->add_length = 4;
10448	feature->feature_data[0] = 0x00;
10449	feature->feature_data[1] = 0x00;
10450	feature = (struct scsi_get_config_feature *)
10451	    &feature->feature_data[feature->add_length];
10452
10453f3b:	/* DVD+R Dual Layer */
10454	scsi_ulto2b(0x003B, feature->feature_code);
10455	feature->flags = 0x00;
10456	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10457		feature->flags |= SGC_F_CURRENT;
10458	feature->add_length = 4;
10459	feature->feature_data[0] = 0x00;
10460	feature = (struct scsi_get_config_feature *)
10461	    &feature->feature_data[feature->add_length];
10462
10463done:
10464	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10465	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10466		feature = (struct scsi_get_config_feature *)(hdr + 1);
10467		if (scsi_2btoul(feature->feature_code) == starting)
10468			feature = (struct scsi_get_config_feature *)
10469			    &feature->feature_data[feature->add_length];
10470		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10471	}
10472	scsi_ulto4b(data_len - 4, hdr->data_length);
10473	if (data_len < alloc_len) {
10474		ctsio->residual = alloc_len - data_len;
10475		ctsio->kern_data_len = data_len;
10476		ctsio->kern_total_len = data_len;
10477	} else {
10478		ctsio->residual = 0;
10479		ctsio->kern_data_len = alloc_len;
10480		ctsio->kern_total_len = alloc_len;
10481	}
10482
10483	ctl_set_success(ctsio);
10484	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10485	ctsio->be_move_done = ctl_config_move_done;
10486	ctl_datamove((union ctl_io *)ctsio);
10487	return (CTL_RETVAL_COMPLETE);
10488}
10489
10490int
10491ctl_get_event_status(struct ctl_scsiio *ctsio)
10492{
10493	struct scsi_get_event_status_header *hdr;
10494	struct scsi_get_event_status *cdb;
10495	struct ctl_lun *lun;
10496	uint32_t alloc_len, data_len;
10497	int notif_class;
10498
10499	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10500	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10501	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10502		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10503		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10504		ctl_done((union ctl_io *)ctsio);
10505		return (CTL_RETVAL_COMPLETE);
10506	}
10507	notif_class = cdb->notif_class;
10508	alloc_len = scsi_2btoul(cdb->length);
10509
10510	data_len = sizeof(struct scsi_get_event_status_header);
10511	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10512	ctsio->kern_sg_entries = 0;
10513	ctsio->kern_data_resid = 0;
10514	ctsio->kern_rel_offset = 0;
10515
10516	if (data_len < alloc_len) {
10517		ctsio->residual = alloc_len - data_len;
10518		ctsio->kern_data_len = data_len;
10519		ctsio->kern_total_len = data_len;
10520	} else {
10521		ctsio->residual = 0;
10522		ctsio->kern_data_len = alloc_len;
10523		ctsio->kern_total_len = alloc_len;
10524	}
10525
10526	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10527	scsi_ulto2b(0, hdr->descr_length);
10528	hdr->nea_class = SGESN_NEA;
10529	hdr->supported_class = 0;
10530
10531	ctl_set_success(ctsio);
10532	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10533	ctsio->be_move_done = ctl_config_move_done;
10534	ctl_datamove((union ctl_io *)ctsio);
10535	return (CTL_RETVAL_COMPLETE);
10536}
10537
10538int
10539ctl_mechanism_status(struct ctl_scsiio *ctsio)
10540{
10541	struct scsi_mechanism_status_header *hdr;
10542	struct scsi_mechanism_status *cdb;
10543	struct ctl_lun *lun;
10544	uint32_t alloc_len, data_len;
10545
10546	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10547	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10548	alloc_len = scsi_2btoul(cdb->length);
10549
10550	data_len = sizeof(struct scsi_mechanism_status_header);
10551	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10552	ctsio->kern_sg_entries = 0;
10553	ctsio->kern_data_resid = 0;
10554	ctsio->kern_rel_offset = 0;
10555
10556	if (data_len < alloc_len) {
10557		ctsio->residual = alloc_len - data_len;
10558		ctsio->kern_data_len = data_len;
10559		ctsio->kern_total_len = data_len;
10560	} else {
10561		ctsio->residual = 0;
10562		ctsio->kern_data_len = alloc_len;
10563		ctsio->kern_total_len = alloc_len;
10564	}
10565
10566	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10567	hdr->state1 = 0x00;
10568	hdr->state2 = 0xe0;
10569	scsi_ulto3b(0, hdr->lba);
10570	hdr->slots_num = 0;
10571	scsi_ulto2b(0, hdr->slots_length);
10572
10573	ctl_set_success(ctsio);
10574	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10575	ctsio->be_move_done = ctl_config_move_done;
10576	ctl_datamove((union ctl_io *)ctsio);
10577	return (CTL_RETVAL_COMPLETE);
10578}
10579
10580static void
10581ctl_ultomsf(uint32_t lba, uint8_t *buf)
10582{
10583
10584	lba += 150;
10585	buf[0] = 0;
10586	buf[1] = bin2bcd((lba / 75) / 60);
10587	buf[2] = bin2bcd((lba / 75) % 60);
10588	buf[3] = bin2bcd(lba % 75);
10589}
10590
10591int
10592ctl_read_toc(struct ctl_scsiio *ctsio)
10593{
10594	struct scsi_read_toc_hdr *hdr;
10595	struct scsi_read_toc_type01_descr *descr;
10596	struct scsi_read_toc *cdb;
10597	struct ctl_lun *lun;
10598	uint32_t alloc_len, data_len;
10599	int format, msf;
10600
10601	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10602	cdb = (struct scsi_read_toc *)ctsio->cdb;
10603	msf = (cdb->byte2 & CD_MSF) != 0;
10604	format = cdb->format;
10605	alloc_len = scsi_2btoul(cdb->data_len);
10606
10607	data_len = sizeof(struct scsi_read_toc_hdr);
10608	if (format == 0)
10609		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10610	else
10611		data_len += sizeof(struct scsi_read_toc_type01_descr);
10612	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10613	ctsio->kern_sg_entries = 0;
10614	ctsio->kern_data_resid = 0;
10615	ctsio->kern_rel_offset = 0;
10616
10617	if (data_len < alloc_len) {
10618		ctsio->residual = alloc_len - data_len;
10619		ctsio->kern_data_len = data_len;
10620		ctsio->kern_total_len = data_len;
10621	} else {
10622		ctsio->residual = 0;
10623		ctsio->kern_data_len = alloc_len;
10624		ctsio->kern_total_len = alloc_len;
10625	}
10626
10627	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10628	if (format == 0) {
10629		scsi_ulto2b(0x12, hdr->data_length);
10630		hdr->first = 1;
10631		hdr->last = 1;
10632		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10633		descr->addr_ctl = 0x14;
10634		descr->track_number = 1;
10635		if (msf)
10636			ctl_ultomsf(0, descr->track_start);
10637		else
10638			scsi_ulto4b(0, descr->track_start);
10639		descr++;
10640		descr->addr_ctl = 0x14;
10641		descr->track_number = 0xaa;
10642		if (msf)
10643			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10644		else
10645			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10646	} else {
10647		scsi_ulto2b(0x0a, hdr->data_length);
10648		hdr->first = 1;
10649		hdr->last = 1;
10650		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10651		descr->addr_ctl = 0x14;
10652		descr->track_number = 1;
10653		if (msf)
10654			ctl_ultomsf(0, descr->track_start);
10655		else
10656			scsi_ulto4b(0, descr->track_start);
10657	}
10658
10659	ctl_set_success(ctsio);
10660	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10661	ctsio->be_move_done = ctl_config_move_done;
10662	ctl_datamove((union ctl_io *)ctsio);
10663	return (CTL_RETVAL_COMPLETE);
10664}
10665
10666/*
10667 * For known CDB types, parse the LBA and length.
10668 */
10669static int
10670ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10671{
10672	if (io->io_hdr.io_type != CTL_IO_SCSI)
10673		return (1);
10674
10675	switch (io->scsiio.cdb[0]) {
10676	case COMPARE_AND_WRITE: {
10677		struct scsi_compare_and_write *cdb;
10678
10679		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10680
10681		*lba = scsi_8btou64(cdb->addr);
10682		*len = cdb->length;
10683		break;
10684	}
10685	case READ_6:
10686	case WRITE_6: {
10687		struct scsi_rw_6 *cdb;
10688
10689		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10690
10691		*lba = scsi_3btoul(cdb->addr);
10692		/* only 5 bits are valid in the most significant address byte */
10693		*lba &= 0x1fffff;
10694		*len = cdb->length;
10695		break;
10696	}
10697	case READ_10:
10698	case WRITE_10: {
10699		struct scsi_rw_10 *cdb;
10700
10701		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10702
10703		*lba = scsi_4btoul(cdb->addr);
10704		*len = scsi_2btoul(cdb->length);
10705		break;
10706	}
10707	case WRITE_VERIFY_10: {
10708		struct scsi_write_verify_10 *cdb;
10709
10710		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10711
10712		*lba = scsi_4btoul(cdb->addr);
10713		*len = scsi_2btoul(cdb->length);
10714		break;
10715	}
10716	case READ_12:
10717	case WRITE_12: {
10718		struct scsi_rw_12 *cdb;
10719
10720		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10721
10722		*lba = scsi_4btoul(cdb->addr);
10723		*len = scsi_4btoul(cdb->length);
10724		break;
10725	}
10726	case WRITE_VERIFY_12: {
10727		struct scsi_write_verify_12 *cdb;
10728
10729		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10730
10731		*lba = scsi_4btoul(cdb->addr);
10732		*len = scsi_4btoul(cdb->length);
10733		break;
10734	}
10735	case READ_16:
10736	case WRITE_16: {
10737		struct scsi_rw_16 *cdb;
10738
10739		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10740
10741		*lba = scsi_8btou64(cdb->addr);
10742		*len = scsi_4btoul(cdb->length);
10743		break;
10744	}
10745	case WRITE_ATOMIC_16: {
10746		struct scsi_write_atomic_16 *cdb;
10747
10748		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10749
10750		*lba = scsi_8btou64(cdb->addr);
10751		*len = scsi_2btoul(cdb->length);
10752		break;
10753	}
10754	case WRITE_VERIFY_16: {
10755		struct scsi_write_verify_16 *cdb;
10756
10757		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10758
10759		*lba = scsi_8btou64(cdb->addr);
10760		*len = scsi_4btoul(cdb->length);
10761		break;
10762	}
10763	case WRITE_SAME_10: {
10764		struct scsi_write_same_10 *cdb;
10765
10766		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10767
10768		*lba = scsi_4btoul(cdb->addr);
10769		*len = scsi_2btoul(cdb->length);
10770		break;
10771	}
10772	case WRITE_SAME_16: {
10773		struct scsi_write_same_16 *cdb;
10774
10775		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10776
10777		*lba = scsi_8btou64(cdb->addr);
10778		*len = scsi_4btoul(cdb->length);
10779		break;
10780	}
10781	case VERIFY_10: {
10782		struct scsi_verify_10 *cdb;
10783
10784		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10785
10786		*lba = scsi_4btoul(cdb->addr);
10787		*len = scsi_2btoul(cdb->length);
10788		break;
10789	}
10790	case VERIFY_12: {
10791		struct scsi_verify_12 *cdb;
10792
10793		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10794
10795		*lba = scsi_4btoul(cdb->addr);
10796		*len = scsi_4btoul(cdb->length);
10797		break;
10798	}
10799	case VERIFY_16: {
10800		struct scsi_verify_16 *cdb;
10801
10802		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10803
10804		*lba = scsi_8btou64(cdb->addr);
10805		*len = scsi_4btoul(cdb->length);
10806		break;
10807	}
10808	case UNMAP: {
10809		*lba = 0;
10810		*len = UINT64_MAX;
10811		break;
10812	}
10813	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10814		struct scsi_get_lba_status *cdb;
10815
10816		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10817		*lba = scsi_8btou64(cdb->addr);
10818		*len = UINT32_MAX;
10819		break;
10820	}
10821	default:
10822		return (1);
10823		break; /* NOTREACHED */
10824	}
10825
10826	return (0);
10827}
10828
10829static ctl_action
10830ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10831    bool seq)
10832{
10833	uint64_t endlba1, endlba2;
10834
10835	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10836	endlba2 = lba2 + len2 - 1;
10837
10838	if ((endlba1 < lba2) || (endlba2 < lba1))
10839		return (CTL_ACTION_PASS);
10840	else
10841		return (CTL_ACTION_BLOCK);
10842}
10843
10844static int
10845ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10846{
10847	struct ctl_ptr_len_flags *ptrlen;
10848	struct scsi_unmap_desc *buf, *end, *range;
10849	uint64_t lba;
10850	uint32_t len;
10851
10852	/* If not UNMAP -- go other way. */
10853	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10854	    io->scsiio.cdb[0] != UNMAP)
10855		return (CTL_ACTION_ERROR);
10856
10857	/* If UNMAP without data -- block and wait for data. */
10858	ptrlen = (struct ctl_ptr_len_flags *)
10859	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10860	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10861	    ptrlen->ptr == NULL)
10862		return (CTL_ACTION_BLOCK);
10863
10864	/* UNMAP with data -- check for collision. */
10865	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10866	end = buf + ptrlen->len / sizeof(*buf);
10867	for (range = buf; range < end; range++) {
10868		lba = scsi_8btou64(range->lba);
10869		len = scsi_4btoul(range->length);
10870		if ((lba < lba2 + len2) && (lba + len > lba2))
10871			return (CTL_ACTION_BLOCK);
10872	}
10873	return (CTL_ACTION_PASS);
10874}
10875
10876static ctl_action
10877ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10878{
10879	uint64_t lba1, lba2;
10880	uint64_t len1, len2;
10881	int retval;
10882
10883	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10884		return (CTL_ACTION_ERROR);
10885
10886	retval = ctl_extent_check_unmap(io1, lba2, len2);
10887	if (retval != CTL_ACTION_ERROR)
10888		return (retval);
10889
10890	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10891		return (CTL_ACTION_ERROR);
10892
10893	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10894		seq = FALSE;
10895	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10896}
10897
10898static ctl_action
10899ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10900{
10901	uint64_t lba1, lba2;
10902	uint64_t len1, len2;
10903
10904	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10905		return (CTL_ACTION_PASS);
10906	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10907		return (CTL_ACTION_ERROR);
10908	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10909		return (CTL_ACTION_ERROR);
10910
10911	if (lba1 + len1 == lba2)
10912		return (CTL_ACTION_BLOCK);
10913	return (CTL_ACTION_PASS);
10914}
10915
10916static ctl_action
10917ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10918    union ctl_io *ooa_io)
10919{
10920	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10921	const ctl_serialize_action *serialize_row;
10922
10923	/*
10924	 * The initiator attempted multiple untagged commands at the same
10925	 * time.  Can't do that.
10926	 */
10927	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10928	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10929	 && ((pending_io->io_hdr.nexus.targ_port ==
10930	      ooa_io->io_hdr.nexus.targ_port)
10931	  && (pending_io->io_hdr.nexus.initid ==
10932	      ooa_io->io_hdr.nexus.initid))
10933	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10934	      CTL_FLAG_STATUS_SENT)) == 0))
10935		return (CTL_ACTION_OVERLAP);
10936
10937	/*
10938	 * The initiator attempted to send multiple tagged commands with
10939	 * the same ID.  (It's fine if different initiators have the same
10940	 * tag ID.)
10941	 *
10942	 * Even if all of those conditions are true, we don't kill the I/O
10943	 * if the command ahead of us has been aborted.  We won't end up
10944	 * sending it to the FETD, and it's perfectly legal to resend a
10945	 * command with the same tag number as long as the previous
10946	 * instance of this tag number has been aborted somehow.
10947	 */
10948	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10949	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10950	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10951	 && ((pending_io->io_hdr.nexus.targ_port ==
10952	      ooa_io->io_hdr.nexus.targ_port)
10953	  && (pending_io->io_hdr.nexus.initid ==
10954	      ooa_io->io_hdr.nexus.initid))
10955	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10956	      CTL_FLAG_STATUS_SENT)) == 0))
10957		return (CTL_ACTION_OVERLAP_TAG);
10958
10959	/*
10960	 * If we get a head of queue tag, SAM-3 says that we should
10961	 * immediately execute it.
10962	 *
10963	 * What happens if this command would normally block for some other
10964	 * reason?  e.g. a request sense with a head of queue tag
10965	 * immediately after a write.  Normally that would block, but this
10966	 * will result in its getting executed immediately...
10967	 *
10968	 * We currently return "pass" instead of "skip", so we'll end up
10969	 * going through the rest of the queue to check for overlapped tags.
10970	 *
10971	 * XXX KDM check for other types of blockage first??
10972	 */
10973	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10974		return (CTL_ACTION_PASS);
10975
10976	/*
10977	 * Ordered tags have to block until all items ahead of them
10978	 * have completed.  If we get called with an ordered tag, we always
10979	 * block, if something else is ahead of us in the queue.
10980	 */
10981	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10982		return (CTL_ACTION_BLOCK);
10983
10984	/*
10985	 * Simple tags get blocked until all head of queue and ordered tags
10986	 * ahead of them have completed.  I'm lumping untagged commands in
10987	 * with simple tags here.  XXX KDM is that the right thing to do?
10988	 */
10989	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10990	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10991	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10992	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10993		return (CTL_ACTION_BLOCK);
10994
10995	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10996	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10997
10998	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10999
11000	switch (serialize_row[pending_entry->seridx]) {
11001	case CTL_SER_BLOCK:
11002		return (CTL_ACTION_BLOCK);
11003	case CTL_SER_EXTENT:
11004		return (ctl_extent_check(ooa_io, pending_io,
11005		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11006	case CTL_SER_EXTENTOPT:
11007		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11008		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11009			return (ctl_extent_check(ooa_io, pending_io,
11010			    (lun->be_lun &&
11011			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11012		return (CTL_ACTION_PASS);
11013	case CTL_SER_EXTENTSEQ:
11014		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11015			return (ctl_extent_check_seq(ooa_io, pending_io));
11016		return (CTL_ACTION_PASS);
11017	case CTL_SER_PASS:
11018		return (CTL_ACTION_PASS);
11019	case CTL_SER_BLOCKOPT:
11020		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11021		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11022			return (CTL_ACTION_BLOCK);
11023		return (CTL_ACTION_PASS);
11024	case CTL_SER_SKIP:
11025		return (CTL_ACTION_SKIP);
11026	default:
11027		panic("invalid serialization value %d",
11028		      serialize_row[pending_entry->seridx]);
11029	}
11030
11031	return (CTL_ACTION_ERROR);
11032}
11033
11034/*
11035 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11036 * Assumptions:
11037 * - pending_io is generally either incoming, or on the blocked queue
11038 * - starting I/O is the I/O we want to start the check with.
11039 */
11040static ctl_action
11041ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11042	      union ctl_io *starting_io)
11043{
11044	union ctl_io *ooa_io;
11045	ctl_action action;
11046
11047	mtx_assert(&lun->lun_lock, MA_OWNED);
11048
11049	/*
11050	 * Run back along the OOA queue, starting with the current
11051	 * blocked I/O and going through every I/O before it on the
11052	 * queue.  If starting_io is NULL, we'll just end up returning
11053	 * CTL_ACTION_PASS.
11054	 */
11055	for (ooa_io = starting_io; ooa_io != NULL;
11056	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11057	     ooa_links)){
11058
11059		/*
11060		 * This routine just checks to see whether
11061		 * cur_blocked is blocked by ooa_io, which is ahead
11062		 * of it in the queue.  It doesn't queue/dequeue
11063		 * cur_blocked.
11064		 */
11065		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11066		switch (action) {
11067		case CTL_ACTION_BLOCK:
11068		case CTL_ACTION_OVERLAP:
11069		case CTL_ACTION_OVERLAP_TAG:
11070		case CTL_ACTION_SKIP:
11071		case CTL_ACTION_ERROR:
11072			return (action);
11073			break; /* NOTREACHED */
11074		case CTL_ACTION_PASS:
11075			break;
11076		default:
11077			panic("invalid action %d", action);
11078			break;  /* NOTREACHED */
11079		}
11080	}
11081
11082	return (CTL_ACTION_PASS);
11083}
11084
11085/*
11086 * Assumptions:
11087 * - An I/O has just completed, and has been removed from the per-LUN OOA
11088 *   queue, so some items on the blocked queue may now be unblocked.
11089 */
11090static int
11091ctl_check_blocked(struct ctl_lun *lun)
11092{
11093	struct ctl_softc *softc = lun->ctl_softc;
11094	union ctl_io *cur_blocked, *next_blocked;
11095
11096	mtx_assert(&lun->lun_lock, MA_OWNED);
11097
11098	/*
11099	 * Run forward from the head of the blocked queue, checking each
11100	 * entry against the I/Os prior to it on the OOA queue to see if
11101	 * there is still any blockage.
11102	 *
11103	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11104	 * with our removing a variable on it while it is traversing the
11105	 * list.
11106	 */
11107	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11108	     cur_blocked != NULL; cur_blocked = next_blocked) {
11109		union ctl_io *prev_ooa;
11110		ctl_action action;
11111
11112		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11113							  blocked_links);
11114
11115		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11116						      ctl_ooaq, ooa_links);
11117
11118		/*
11119		 * If cur_blocked happens to be the first item in the OOA
11120		 * queue now, prev_ooa will be NULL, and the action
11121		 * returned will just be CTL_ACTION_PASS.
11122		 */
11123		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11124
11125		switch (action) {
11126		case CTL_ACTION_BLOCK:
11127			/* Nothing to do here, still blocked */
11128			break;
11129		case CTL_ACTION_OVERLAP:
11130		case CTL_ACTION_OVERLAP_TAG:
11131			/*
11132			 * This shouldn't happen!  In theory we've already
11133			 * checked this command for overlap...
11134			 */
11135			break;
11136		case CTL_ACTION_PASS:
11137		case CTL_ACTION_SKIP: {
11138			const struct ctl_cmd_entry *entry;
11139
11140			/*
11141			 * The skip case shouldn't happen, this transaction
11142			 * should have never made it onto the blocked queue.
11143			 */
11144			/*
11145			 * This I/O is no longer blocked, we can remove it
11146			 * from the blocked queue.  Since this is a TAILQ
11147			 * (doubly linked list), we can do O(1) removals
11148			 * from any place on the list.
11149			 */
11150			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11151				     blocked_links);
11152			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11153
11154			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11155			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11156				/*
11157				 * Need to send IO back to original side to
11158				 * run
11159				 */
11160				union ctl_ha_msg msg_info;
11161
11162				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11163				msg_info.hdr.original_sc =
11164					cur_blocked->io_hdr.original_sc;
11165				msg_info.hdr.serializing_sc = cur_blocked;
11166				msg_info.hdr.msg_type = CTL_MSG_R2R;
11167				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11168				    sizeof(msg_info.hdr), M_NOWAIT);
11169				break;
11170			}
11171			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11172
11173			/*
11174			 * Check this I/O for LUN state changes that may
11175			 * have happened while this command was blocked.
11176			 * The LUN state may have been changed by a command
11177			 * ahead of us in the queue, so we need to re-check
11178			 * for any states that can be caused by SCSI
11179			 * commands.
11180			 */
11181			if (ctl_scsiio_lun_check(lun, entry,
11182						 &cur_blocked->scsiio) == 0) {
11183				cur_blocked->io_hdr.flags |=
11184				                      CTL_FLAG_IS_WAS_ON_RTR;
11185				ctl_enqueue_rtr(cur_blocked);
11186			} else
11187				ctl_done(cur_blocked);
11188			break;
11189		}
11190		default:
11191			/*
11192			 * This probably shouldn't happen -- we shouldn't
11193			 * get CTL_ACTION_ERROR, or anything else.
11194			 */
11195			break;
11196		}
11197	}
11198
11199	return (CTL_RETVAL_COMPLETE);
11200}
11201
11202/*
11203 * This routine (with one exception) checks LUN flags that can be set by
11204 * commands ahead of us in the OOA queue.  These flags have to be checked
11205 * when a command initially comes in, and when we pull a command off the
11206 * blocked queue and are preparing to execute it.  The reason we have to
11207 * check these flags for commands on the blocked queue is that the LUN
11208 * state may have been changed by a command ahead of us while we're on the
11209 * blocked queue.
11210 *
11211 * Ordering is somewhat important with these checks, so please pay
11212 * careful attention to the placement of any new checks.
11213 */
11214static int
11215ctl_scsiio_lun_check(struct ctl_lun *lun,
11216    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11217{
11218	struct ctl_softc *softc = lun->ctl_softc;
11219	int retval;
11220	uint32_t residx;
11221
11222	retval = 0;
11223
11224	mtx_assert(&lun->lun_lock, MA_OWNED);
11225
11226	/*
11227	 * If this shelf is a secondary shelf controller, we may have to
11228	 * reject some commands disallowed by HA mode and link state.
11229	 */
11230	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11231		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11232		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11233			ctl_set_lun_unavail(ctsio);
11234			retval = 1;
11235			goto bailout;
11236		}
11237		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11238		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11239			ctl_set_lun_transit(ctsio);
11240			retval = 1;
11241			goto bailout;
11242		}
11243		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11244		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11245			ctl_set_lun_standby(ctsio);
11246			retval = 1;
11247			goto bailout;
11248		}
11249
11250		/* The rest of checks are only done on executing side */
11251		if (softc->ha_mode == CTL_HA_MODE_XFER)
11252			goto bailout;
11253	}
11254
11255	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11256		if (lun->be_lun &&
11257		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11258			ctl_set_hw_write_protected(ctsio);
11259			retval = 1;
11260			goto bailout;
11261		}
11262		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11263		    .eca_and_aen & SCP_SWP) != 0) {
11264			ctl_set_sense(ctsio, /*current_error*/ 1,
11265			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11266			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11267			retval = 1;
11268			goto bailout;
11269		}
11270	}
11271
11272	/*
11273	 * Check for a reservation conflict.  If this command isn't allowed
11274	 * even on reserved LUNs, and if this initiator isn't the one who
11275	 * reserved us, reject the command with a reservation conflict.
11276	 */
11277	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11278	if ((lun->flags & CTL_LUN_RESERVED)
11279	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11280		if (lun->res_idx != residx) {
11281			ctl_set_reservation_conflict(ctsio);
11282			retval = 1;
11283			goto bailout;
11284		}
11285	}
11286
11287	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11288	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11289		/* No reservation or command is allowed. */;
11290	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11291	    (lun->res_type == SPR_TYPE_WR_EX ||
11292	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11293	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11294		/* The command is allowed for Write Exclusive resv. */;
11295	} else {
11296		/*
11297		 * if we aren't registered or it's a res holder type
11298		 * reservation and this isn't the res holder then set a
11299		 * conflict.
11300		 */
11301		if (ctl_get_prkey(lun, residx) == 0
11302		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11303			ctl_set_reservation_conflict(ctsio);
11304			retval = 1;
11305			goto bailout;
11306		}
11307	}
11308
11309	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11310		if (lun->flags & CTL_LUN_EJECTED)
11311			ctl_set_lun_ejected(ctsio);
11312		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11313			if (lun->flags & CTL_LUN_REMOVABLE)
11314				ctl_set_lun_no_media(ctsio);
11315			else
11316				ctl_set_lun_int_reqd(ctsio);
11317		} else if (lun->flags & CTL_LUN_STOPPED)
11318			ctl_set_lun_stopped(ctsio);
11319		else
11320			goto bailout;
11321		retval = 1;
11322		goto bailout;
11323	}
11324
11325bailout:
11326	return (retval);
11327}
11328
11329static void
11330ctl_failover_io(union ctl_io *io, int have_lock)
11331{
11332	ctl_set_busy(&io->scsiio);
11333	ctl_done(io);
11334}
11335
11336static void
11337ctl_failover_lun(union ctl_io *rio)
11338{
11339	struct ctl_softc *softc = control_softc;
11340	struct ctl_lun *lun;
11341	struct ctl_io_hdr *io, *next_io;
11342	uint32_t targ_lun;
11343
11344	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11345	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11346
11347	/* Find and lock the LUN. */
11348	mtx_lock(&softc->ctl_lock);
11349	if ((targ_lun < CTL_MAX_LUNS) &&
11350	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11351		mtx_lock(&lun->lun_lock);
11352		mtx_unlock(&softc->ctl_lock);
11353		if (lun->flags & CTL_LUN_DISABLED) {
11354			mtx_unlock(&lun->lun_lock);
11355			return;
11356		}
11357	} else {
11358		mtx_unlock(&softc->ctl_lock);
11359		return;
11360	}
11361
11362	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11363		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11364			/* We are master */
11365			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11366				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11367					io->flags |= CTL_FLAG_ABORT;
11368					io->flags |= CTL_FLAG_FAILOVER;
11369				} else { /* This can be only due to DATAMOVE */
11370					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11371					io->flags &= ~CTL_FLAG_DMA_INPROG;
11372					io->flags |= CTL_FLAG_IO_ACTIVE;
11373					io->port_status = 31340;
11374					ctl_enqueue_isc((union ctl_io *)io);
11375				}
11376			}
11377			/* We are slave */
11378			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11379				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11380				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11381					io->flags |= CTL_FLAG_FAILOVER;
11382				} else {
11383					ctl_set_busy(&((union ctl_io *)io)->
11384					    scsiio);
11385					ctl_done((union ctl_io *)io);
11386				}
11387			}
11388		}
11389	} else { /* SERIALIZE modes */
11390		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11391		    next_io) {
11392			/* We are master */
11393			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11394				TAILQ_REMOVE(&lun->blocked_queue, io,
11395				    blocked_links);
11396				io->flags &= ~CTL_FLAG_BLOCKED;
11397				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11398				ctl_free_io((union ctl_io *)io);
11399			}
11400		}
11401		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11402			/* We are master */
11403			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11404				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11405				ctl_free_io((union ctl_io *)io);
11406			}
11407			/* We are slave */
11408			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11409				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11410				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11411					ctl_set_busy(&((union ctl_io *)io)->
11412					    scsiio);
11413					ctl_done((union ctl_io *)io);
11414				}
11415			}
11416		}
11417		ctl_check_blocked(lun);
11418	}
11419	mtx_unlock(&lun->lun_lock);
11420}
11421
11422static int
11423ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11424{
11425	struct ctl_lun *lun;
11426	const struct ctl_cmd_entry *entry;
11427	uint32_t initidx, targ_lun;
11428	int retval;
11429
11430	retval = 0;
11431
11432	lun = NULL;
11433
11434	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11435	if ((targ_lun < CTL_MAX_LUNS)
11436	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11437		/*
11438		 * If the LUN is invalid, pretend that it doesn't exist.
11439		 * It will go away as soon as all pending I/O has been
11440		 * completed.
11441		 */
11442		mtx_lock(&lun->lun_lock);
11443		if (lun->flags & CTL_LUN_DISABLED) {
11444			mtx_unlock(&lun->lun_lock);
11445			lun = NULL;
11446			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11447			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11448		} else {
11449			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11450			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11451				lun->be_lun;
11452
11453			/*
11454			 * Every I/O goes into the OOA queue for a
11455			 * particular LUN, and stays there until completion.
11456			 */
11457#ifdef CTL_TIME_IO
11458			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11459				lun->idle_time += getsbinuptime() -
11460				    lun->last_busy;
11461			}
11462#endif
11463			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11464			    ooa_links);
11465		}
11466	} else {
11467		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11468		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11469	}
11470
11471	/* Get command entry and return error if it is unsuppotyed. */
11472	entry = ctl_validate_command(ctsio);
11473	if (entry == NULL) {
11474		if (lun)
11475			mtx_unlock(&lun->lun_lock);
11476		return (retval);
11477	}
11478
11479	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11480	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11481
11482	/*
11483	 * Check to see whether we can send this command to LUNs that don't
11484	 * exist.  This should pretty much only be the case for inquiry
11485	 * and request sense.  Further checks, below, really require having
11486	 * a LUN, so we can't really check the command anymore.  Just put
11487	 * it on the rtr queue.
11488	 */
11489	if (lun == NULL) {
11490		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11491			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11492			ctl_enqueue_rtr((union ctl_io *)ctsio);
11493			return (retval);
11494		}
11495
11496		ctl_set_unsupported_lun(ctsio);
11497		ctl_done((union ctl_io *)ctsio);
11498		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11499		return (retval);
11500	} else {
11501		/*
11502		 * Make sure we support this particular command on this LUN.
11503		 * e.g., we don't support writes to the control LUN.
11504		 */
11505		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11506			mtx_unlock(&lun->lun_lock);
11507			ctl_set_invalid_opcode(ctsio);
11508			ctl_done((union ctl_io *)ctsio);
11509			return (retval);
11510		}
11511	}
11512
11513	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11514
11515#ifdef CTL_WITH_CA
11516	/*
11517	 * If we've got a request sense, it'll clear the contingent
11518	 * allegiance condition.  Otherwise, if we have a CA condition for
11519	 * this initiator, clear it, because it sent down a command other
11520	 * than request sense.
11521	 */
11522	if ((ctsio->cdb[0] != REQUEST_SENSE)
11523	 && (ctl_is_set(lun->have_ca, initidx)))
11524		ctl_clear_mask(lun->have_ca, initidx);
11525#endif
11526
11527	/*
11528	 * If the command has this flag set, it handles its own unit
11529	 * attention reporting, we shouldn't do anything.  Otherwise we
11530	 * check for any pending unit attentions, and send them back to the
11531	 * initiator.  We only do this when a command initially comes in,
11532	 * not when we pull it off the blocked queue.
11533	 *
11534	 * According to SAM-3, section 5.3.2, the order that things get
11535	 * presented back to the host is basically unit attentions caused
11536	 * by some sort of reset event, busy status, reservation conflicts
11537	 * or task set full, and finally any other status.
11538	 *
11539	 * One issue here is that some of the unit attentions we report
11540	 * don't fall into the "reset" category (e.g. "reported luns data
11541	 * has changed").  So reporting it here, before the reservation
11542	 * check, may be technically wrong.  I guess the only thing to do
11543	 * would be to check for and report the reset events here, and then
11544	 * check for the other unit attention types after we check for a
11545	 * reservation conflict.
11546	 *
11547	 * XXX KDM need to fix this
11548	 */
11549	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11550		ctl_ua_type ua_type;
11551
11552		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11553		    SSD_TYPE_NONE);
11554		if (ua_type != CTL_UA_NONE) {
11555			mtx_unlock(&lun->lun_lock);
11556			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11557			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11558			ctsio->sense_len = SSD_FULL_SIZE;
11559			ctl_done((union ctl_io *)ctsio);
11560			return (retval);
11561		}
11562	}
11563
11564
11565	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11566		mtx_unlock(&lun->lun_lock);
11567		ctl_done((union ctl_io *)ctsio);
11568		return (retval);
11569	}
11570
11571	/*
11572	 * XXX CHD this is where we want to send IO to other side if
11573	 * this LUN is secondary on this SC. We will need to make a copy
11574	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11575	 * the copy we send as FROM_OTHER.
11576	 * We also need to stuff the address of the original IO so we can
11577	 * find it easily. Something similar will need be done on the other
11578	 * side so when we are done we can find the copy.
11579	 */
11580	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11581	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11582	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11583		union ctl_ha_msg msg_info;
11584		int isc_retval;
11585
11586		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11587		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11588		mtx_unlock(&lun->lun_lock);
11589
11590		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11591		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11592		msg_info.hdr.serializing_sc = NULL;
11593		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11594		msg_info.scsi.tag_num = ctsio->tag_num;
11595		msg_info.scsi.tag_type = ctsio->tag_type;
11596		msg_info.scsi.cdb_len = ctsio->cdb_len;
11597		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11598
11599		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11600		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11601		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11602			ctl_set_busy(ctsio);
11603			ctl_done((union ctl_io *)ctsio);
11604			return (retval);
11605		}
11606		return (retval);
11607	}
11608
11609	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11610			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11611			      ctl_ooaq, ooa_links))) {
11612	case CTL_ACTION_BLOCK:
11613		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11614		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11615				  blocked_links);
11616		mtx_unlock(&lun->lun_lock);
11617		return (retval);
11618	case CTL_ACTION_PASS:
11619	case CTL_ACTION_SKIP:
11620		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11621		mtx_unlock(&lun->lun_lock);
11622		ctl_enqueue_rtr((union ctl_io *)ctsio);
11623		break;
11624	case CTL_ACTION_OVERLAP:
11625		mtx_unlock(&lun->lun_lock);
11626		ctl_set_overlapped_cmd(ctsio);
11627		ctl_done((union ctl_io *)ctsio);
11628		break;
11629	case CTL_ACTION_OVERLAP_TAG:
11630		mtx_unlock(&lun->lun_lock);
11631		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11632		ctl_done((union ctl_io *)ctsio);
11633		break;
11634	case CTL_ACTION_ERROR:
11635	default:
11636		mtx_unlock(&lun->lun_lock);
11637		ctl_set_internal_failure(ctsio,
11638					 /*sks_valid*/ 0,
11639					 /*retry_count*/ 0);
11640		ctl_done((union ctl_io *)ctsio);
11641		break;
11642	}
11643	return (retval);
11644}
11645
11646const struct ctl_cmd_entry *
11647ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11648{
11649	const struct ctl_cmd_entry *entry;
11650	int service_action;
11651
11652	entry = &ctl_cmd_table[ctsio->cdb[0]];
11653	if (sa)
11654		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11655	if (entry->flags & CTL_CMD_FLAG_SA5) {
11656		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11657		entry = &((const struct ctl_cmd_entry *)
11658		    entry->execute)[service_action];
11659	}
11660	return (entry);
11661}
11662
11663const struct ctl_cmd_entry *
11664ctl_validate_command(struct ctl_scsiio *ctsio)
11665{
11666	const struct ctl_cmd_entry *entry;
11667	int i, sa;
11668	uint8_t diff;
11669
11670	entry = ctl_get_cmd_entry(ctsio, &sa);
11671	if (entry->execute == NULL) {
11672		if (sa)
11673			ctl_set_invalid_field(ctsio,
11674					      /*sks_valid*/ 1,
11675					      /*command*/ 1,
11676					      /*field*/ 1,
11677					      /*bit_valid*/ 1,
11678					      /*bit*/ 4);
11679		else
11680			ctl_set_invalid_opcode(ctsio);
11681		ctl_done((union ctl_io *)ctsio);
11682		return (NULL);
11683	}
11684	KASSERT(entry->length > 0,
11685	    ("Not defined length for command 0x%02x/0x%02x",
11686	     ctsio->cdb[0], ctsio->cdb[1]));
11687	for (i = 1; i < entry->length; i++) {
11688		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11689		if (diff == 0)
11690			continue;
11691		ctl_set_invalid_field(ctsio,
11692				      /*sks_valid*/ 1,
11693				      /*command*/ 1,
11694				      /*field*/ i,
11695				      /*bit_valid*/ 1,
11696				      /*bit*/ fls(diff) - 1);
11697		ctl_done((union ctl_io *)ctsio);
11698		return (NULL);
11699	}
11700	return (entry);
11701}
11702
11703static int
11704ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11705{
11706
11707	switch (lun_type) {
11708	case T_DIRECT:
11709		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11710			return (0);
11711		break;
11712	case T_PROCESSOR:
11713		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11714			return (0);
11715		break;
11716	case T_CDROM:
11717		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11718			return (0);
11719		break;
11720	default:
11721		return (0);
11722	}
11723	return (1);
11724}
11725
11726static int
11727ctl_scsiio(struct ctl_scsiio *ctsio)
11728{
11729	int retval;
11730	const struct ctl_cmd_entry *entry;
11731
11732	retval = CTL_RETVAL_COMPLETE;
11733
11734	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11735
11736	entry = ctl_get_cmd_entry(ctsio, NULL);
11737
11738	/*
11739	 * If this I/O has been aborted, just send it straight to
11740	 * ctl_done() without executing it.
11741	 */
11742	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11743		ctl_done((union ctl_io *)ctsio);
11744		goto bailout;
11745	}
11746
11747	/*
11748	 * All the checks should have been handled by ctl_scsiio_precheck().
11749	 * We should be clear now to just execute the I/O.
11750	 */
11751	retval = entry->execute(ctsio);
11752
11753bailout:
11754	return (retval);
11755}
11756
11757/*
11758 * Since we only implement one target right now, a bus reset simply resets
11759 * our single target.
11760 */
11761static int
11762ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11763{
11764	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11765}
11766
11767static int
11768ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11769		 ctl_ua_type ua_type)
11770{
11771	struct ctl_port *port;
11772	struct ctl_lun *lun;
11773	int retval;
11774
11775	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11776		union ctl_ha_msg msg_info;
11777
11778		msg_info.hdr.nexus = io->io_hdr.nexus;
11779		if (ua_type==CTL_UA_TARG_RESET)
11780			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11781		else
11782			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11783		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11784		msg_info.hdr.original_sc = NULL;
11785		msg_info.hdr.serializing_sc = NULL;
11786		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11787		    sizeof(msg_info.task), M_WAITOK);
11788	}
11789	retval = 0;
11790
11791	mtx_lock(&softc->ctl_lock);
11792	port = ctl_io_port(&io->io_hdr);
11793	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11794		if (port != NULL &&
11795		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11796			continue;
11797		retval += ctl_do_lun_reset(lun, io, ua_type);
11798	}
11799	mtx_unlock(&softc->ctl_lock);
11800	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11801	return (retval);
11802}
11803
11804/*
11805 * The LUN should always be set.  The I/O is optional, and is used to
11806 * distinguish between I/Os sent by this initiator, and by other
11807 * initiators.  We set unit attention for initiators other than this one.
11808 * SAM-3 is vague on this point.  It does say that a unit attention should
11809 * be established for other initiators when a LUN is reset (see section
11810 * 5.7.3), but it doesn't specifically say that the unit attention should
11811 * be established for this particular initiator when a LUN is reset.  Here
11812 * is the relevant text, from SAM-3 rev 8:
11813 *
11814 * 5.7.2 When a SCSI initiator port aborts its own tasks
11815 *
11816 * When a SCSI initiator port causes its own task(s) to be aborted, no
11817 * notification that the task(s) have been aborted shall be returned to
11818 * the SCSI initiator port other than the completion response for the
11819 * command or task management function action that caused the task(s) to
11820 * be aborted and notification(s) associated with related effects of the
11821 * action (e.g., a reset unit attention condition).
11822 *
11823 * XXX KDM for now, we're setting unit attention for all initiators.
11824 */
11825static int
11826ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11827{
11828	union ctl_io *xio;
11829#if 0
11830	uint32_t initidx;
11831#endif
11832	int i;
11833
11834	mtx_lock(&lun->lun_lock);
11835	/*
11836	 * Run through the OOA queue and abort each I/O.
11837	 */
11838	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11839	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11840		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11841	}
11842
11843	/*
11844	 * This version sets unit attention for every
11845	 */
11846#if 0
11847	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11848	ctl_est_ua_all(lun, initidx, ua_type);
11849#else
11850	ctl_est_ua_all(lun, -1, ua_type);
11851#endif
11852
11853	/*
11854	 * A reset (any kind, really) clears reservations established with
11855	 * RESERVE/RELEASE.  It does not clear reservations established
11856	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11857	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11858	 * reservations made with the RESERVE/RELEASE commands, because
11859	 * those commands are obsolete in SPC-3.
11860	 */
11861	lun->flags &= ~CTL_LUN_RESERVED;
11862
11863#ifdef CTL_WITH_CA
11864	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11865		ctl_clear_mask(lun->have_ca, i);
11866#endif
11867	lun->prevent_count = 0;
11868	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11869		ctl_clear_mask(lun->prevent, i);
11870	mtx_unlock(&lun->lun_lock);
11871
11872	return (0);
11873}
11874
11875static int
11876ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11877{
11878	struct ctl_lun *lun;
11879	uint32_t targ_lun;
11880	int retval;
11881
11882	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11883	mtx_lock(&softc->ctl_lock);
11884	if ((targ_lun >= CTL_MAX_LUNS) ||
11885	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11886		mtx_unlock(&softc->ctl_lock);
11887		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11888		return (1);
11889	}
11890	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11891	mtx_unlock(&softc->ctl_lock);
11892	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11893
11894	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11895		union ctl_ha_msg msg_info;
11896
11897		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11898		msg_info.hdr.nexus = io->io_hdr.nexus;
11899		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11900		msg_info.hdr.original_sc = NULL;
11901		msg_info.hdr.serializing_sc = NULL;
11902		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11903		    sizeof(msg_info.task), M_WAITOK);
11904	}
11905	return (retval);
11906}
11907
11908static void
11909ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11910    int other_sc)
11911{
11912	union ctl_io *xio;
11913
11914	mtx_assert(&lun->lun_lock, MA_OWNED);
11915
11916	/*
11917	 * Run through the OOA queue and attempt to find the given I/O.
11918	 * The target port, initiator ID, tag type and tag number have to
11919	 * match the values that we got from the initiator.  If we have an
11920	 * untagged command to abort, simply abort the first untagged command
11921	 * we come to.  We only allow one untagged command at a time of course.
11922	 */
11923	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11924	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11925
11926		if ((targ_port == UINT32_MAX ||
11927		     targ_port == xio->io_hdr.nexus.targ_port) &&
11928		    (init_id == UINT32_MAX ||
11929		     init_id == xio->io_hdr.nexus.initid)) {
11930			if (targ_port != xio->io_hdr.nexus.targ_port ||
11931			    init_id != xio->io_hdr.nexus.initid)
11932				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11933			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11934			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11935				union ctl_ha_msg msg_info;
11936
11937				msg_info.hdr.nexus = xio->io_hdr.nexus;
11938				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11939				msg_info.task.tag_num = xio->scsiio.tag_num;
11940				msg_info.task.tag_type = xio->scsiio.tag_type;
11941				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11942				msg_info.hdr.original_sc = NULL;
11943				msg_info.hdr.serializing_sc = NULL;
11944				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11945				    sizeof(msg_info.task), M_NOWAIT);
11946			}
11947		}
11948	}
11949}
11950
11951static int
11952ctl_abort_task_set(union ctl_io *io)
11953{
11954	struct ctl_softc *softc = control_softc;
11955	struct ctl_lun *lun;
11956	uint32_t targ_lun;
11957
11958	/*
11959	 * Look up the LUN.
11960	 */
11961	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11962	mtx_lock(&softc->ctl_lock);
11963	if ((targ_lun >= CTL_MAX_LUNS) ||
11964	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11965		mtx_unlock(&softc->ctl_lock);
11966		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11967		return (1);
11968	}
11969
11970	mtx_lock(&lun->lun_lock);
11971	mtx_unlock(&softc->ctl_lock);
11972	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11973		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11974		    io->io_hdr.nexus.initid,
11975		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11976	} else { /* CTL_TASK_CLEAR_TASK_SET */
11977		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11978		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11979	}
11980	mtx_unlock(&lun->lun_lock);
11981	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11982	return (0);
11983}
11984
11985static int
11986ctl_i_t_nexus_reset(union ctl_io *io)
11987{
11988	struct ctl_softc *softc = control_softc;
11989	struct ctl_lun *lun;
11990	uint32_t initidx;
11991
11992	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11993		union ctl_ha_msg msg_info;
11994
11995		msg_info.hdr.nexus = io->io_hdr.nexus;
11996		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11997		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11998		msg_info.hdr.original_sc = NULL;
11999		msg_info.hdr.serializing_sc = NULL;
12000		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12001		    sizeof(msg_info.task), M_WAITOK);
12002	}
12003
12004	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12005	mtx_lock(&softc->ctl_lock);
12006	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12007		mtx_lock(&lun->lun_lock);
12008		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12009		    io->io_hdr.nexus.initid, 1);
12010#ifdef CTL_WITH_CA
12011		ctl_clear_mask(lun->have_ca, initidx);
12012#endif
12013		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12014			lun->flags &= ~CTL_LUN_RESERVED;
12015		if (ctl_is_set(lun->prevent, initidx)) {
12016			ctl_clear_mask(lun->prevent, initidx);
12017			lun->prevent_count--;
12018		}
12019		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12020		mtx_unlock(&lun->lun_lock);
12021	}
12022	mtx_unlock(&softc->ctl_lock);
12023	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12024	return (0);
12025}
12026
12027static int
12028ctl_abort_task(union ctl_io *io)
12029{
12030	union ctl_io *xio;
12031	struct ctl_lun *lun;
12032	struct ctl_softc *softc;
12033#if 0
12034	struct sbuf sb;
12035	char printbuf[128];
12036#endif
12037	int found;
12038	uint32_t targ_lun;
12039
12040	softc = control_softc;
12041	found = 0;
12042
12043	/*
12044	 * Look up the LUN.
12045	 */
12046	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12047	mtx_lock(&softc->ctl_lock);
12048	if ((targ_lun >= CTL_MAX_LUNS) ||
12049	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12050		mtx_unlock(&softc->ctl_lock);
12051		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12052		return (1);
12053	}
12054
12055#if 0
12056	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12057	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12058#endif
12059
12060	mtx_lock(&lun->lun_lock);
12061	mtx_unlock(&softc->ctl_lock);
12062	/*
12063	 * Run through the OOA queue and attempt to find the given I/O.
12064	 * The target port, initiator ID, tag type and tag number have to
12065	 * match the values that we got from the initiator.  If we have an
12066	 * untagged command to abort, simply abort the first untagged command
12067	 * we come to.  We only allow one untagged command at a time of course.
12068	 */
12069	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12070	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12071#if 0
12072		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12073
12074		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12075			    lun->lun, xio->scsiio.tag_num,
12076			    xio->scsiio.tag_type,
12077			    (xio->io_hdr.blocked_links.tqe_prev
12078			    == NULL) ? "" : " BLOCKED",
12079			    (xio->io_hdr.flags &
12080			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12081			    (xio->io_hdr.flags &
12082			    CTL_FLAG_ABORT) ? " ABORT" : "",
12083			    (xio->io_hdr.flags &
12084			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12085		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12086		sbuf_finish(&sb);
12087		printf("%s\n", sbuf_data(&sb));
12088#endif
12089
12090		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12091		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12092		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12093			continue;
12094
12095		/*
12096		 * If the abort says that the task is untagged, the
12097		 * task in the queue must be untagged.  Otherwise,
12098		 * we just check to see whether the tag numbers
12099		 * match.  This is because the QLogic firmware
12100		 * doesn't pass back the tag type in an abort
12101		 * request.
12102		 */
12103#if 0
12104		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12105		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12106		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12107#endif
12108		/*
12109		 * XXX KDM we've got problems with FC, because it
12110		 * doesn't send down a tag type with aborts.  So we
12111		 * can only really go by the tag number...
12112		 * This may cause problems with parallel SCSI.
12113		 * Need to figure that out!!
12114		 */
12115		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12116			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12117			found = 1;
12118			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12119			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12120				union ctl_ha_msg msg_info;
12121
12122				msg_info.hdr.nexus = io->io_hdr.nexus;
12123				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12124				msg_info.task.tag_num = io->taskio.tag_num;
12125				msg_info.task.tag_type = io->taskio.tag_type;
12126				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12127				msg_info.hdr.original_sc = NULL;
12128				msg_info.hdr.serializing_sc = NULL;
12129#if 0
12130				printf("Sent Abort to other side\n");
12131#endif
12132				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12133				    sizeof(msg_info.task), M_NOWAIT);
12134			}
12135#if 0
12136			printf("ctl_abort_task: found I/O to abort\n");
12137#endif
12138		}
12139	}
12140	mtx_unlock(&lun->lun_lock);
12141
12142	if (found == 0) {
12143		/*
12144		 * This isn't really an error.  It's entirely possible for
12145		 * the abort and command completion to cross on the wire.
12146		 * This is more of an informative/diagnostic error.
12147		 */
12148#if 0
12149		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12150		       "%u:%u:%u tag %d type %d\n",
12151		       io->io_hdr.nexus.initid,
12152		       io->io_hdr.nexus.targ_port,
12153		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12154		       io->taskio.tag_type);
12155#endif
12156	}
12157	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12158	return (0);
12159}
12160
12161static int
12162ctl_query_task(union ctl_io *io, int task_set)
12163{
12164	union ctl_io *xio;
12165	struct ctl_lun *lun;
12166	struct ctl_softc *softc;
12167	int found = 0;
12168	uint32_t targ_lun;
12169
12170	softc = control_softc;
12171	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12172	mtx_lock(&softc->ctl_lock);
12173	if ((targ_lun >= CTL_MAX_LUNS) ||
12174	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12175		mtx_unlock(&softc->ctl_lock);
12176		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12177		return (1);
12178	}
12179	mtx_lock(&lun->lun_lock);
12180	mtx_unlock(&softc->ctl_lock);
12181	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12182	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12183
12184		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12185		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12186		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12187			continue;
12188
12189		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12190			found = 1;
12191			break;
12192		}
12193	}
12194	mtx_unlock(&lun->lun_lock);
12195	if (found)
12196		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12197	else
12198		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12199	return (0);
12200}
12201
12202static int
12203ctl_query_async_event(union ctl_io *io)
12204{
12205	struct ctl_lun *lun;
12206	struct ctl_softc *softc;
12207	ctl_ua_type ua;
12208	uint32_t targ_lun, initidx;
12209
12210	softc = control_softc;
12211	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12212	mtx_lock(&softc->ctl_lock);
12213	if ((targ_lun >= CTL_MAX_LUNS) ||
12214	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12215		mtx_unlock(&softc->ctl_lock);
12216		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12217		return (1);
12218	}
12219	mtx_lock(&lun->lun_lock);
12220	mtx_unlock(&softc->ctl_lock);
12221	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12222	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12223	mtx_unlock(&lun->lun_lock);
12224	if (ua != CTL_UA_NONE)
12225		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12226	else
12227		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12228	return (0);
12229}
12230
12231static void
12232ctl_run_task(union ctl_io *io)
12233{
12234	struct ctl_softc *softc = control_softc;
12235	int retval = 1;
12236
12237	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12238	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12239	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12240	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12241	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12242	switch (io->taskio.task_action) {
12243	case CTL_TASK_ABORT_TASK:
12244		retval = ctl_abort_task(io);
12245		break;
12246	case CTL_TASK_ABORT_TASK_SET:
12247	case CTL_TASK_CLEAR_TASK_SET:
12248		retval = ctl_abort_task_set(io);
12249		break;
12250	case CTL_TASK_CLEAR_ACA:
12251		break;
12252	case CTL_TASK_I_T_NEXUS_RESET:
12253		retval = ctl_i_t_nexus_reset(io);
12254		break;
12255	case CTL_TASK_LUN_RESET:
12256		retval = ctl_lun_reset(softc, io);
12257		break;
12258	case CTL_TASK_TARGET_RESET:
12259		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12260		break;
12261	case CTL_TASK_BUS_RESET:
12262		retval = ctl_bus_reset(softc, io);
12263		break;
12264	case CTL_TASK_PORT_LOGIN:
12265		break;
12266	case CTL_TASK_PORT_LOGOUT:
12267		break;
12268	case CTL_TASK_QUERY_TASK:
12269		retval = ctl_query_task(io, 0);
12270		break;
12271	case CTL_TASK_QUERY_TASK_SET:
12272		retval = ctl_query_task(io, 1);
12273		break;
12274	case CTL_TASK_QUERY_ASYNC_EVENT:
12275		retval = ctl_query_async_event(io);
12276		break;
12277	default:
12278		printf("%s: got unknown task management event %d\n",
12279		       __func__, io->taskio.task_action);
12280		break;
12281	}
12282	if (retval == 0)
12283		io->io_hdr.status = CTL_SUCCESS;
12284	else
12285		io->io_hdr.status = CTL_ERROR;
12286	ctl_done(io);
12287}
12288
12289/*
12290 * For HA operation.  Handle commands that come in from the other
12291 * controller.
12292 */
12293static void
12294ctl_handle_isc(union ctl_io *io)
12295{
12296	int free_io;
12297	struct ctl_lun *lun;
12298	struct ctl_softc *softc = control_softc;
12299	uint32_t targ_lun;
12300
12301	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12302	lun = softc->ctl_luns[targ_lun];
12303
12304	switch (io->io_hdr.msg_type) {
12305	case CTL_MSG_SERIALIZE:
12306		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12307		break;
12308	case CTL_MSG_R2R: {
12309		const struct ctl_cmd_entry *entry;
12310
12311		/*
12312		 * This is only used in SER_ONLY mode.
12313		 */
12314		free_io = 0;
12315		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12316		mtx_lock(&lun->lun_lock);
12317		if (ctl_scsiio_lun_check(lun,
12318		    entry, (struct ctl_scsiio *)io) != 0) {
12319			mtx_unlock(&lun->lun_lock);
12320			ctl_done(io);
12321			break;
12322		}
12323		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12324		mtx_unlock(&lun->lun_lock);
12325		ctl_enqueue_rtr(io);
12326		break;
12327	}
12328	case CTL_MSG_FINISH_IO:
12329		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12330			free_io = 0;
12331			ctl_done(io);
12332		} else {
12333			free_io = 1;
12334			mtx_lock(&lun->lun_lock);
12335			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12336				     ooa_links);
12337			ctl_check_blocked(lun);
12338			mtx_unlock(&lun->lun_lock);
12339		}
12340		break;
12341	case CTL_MSG_PERS_ACTION:
12342		ctl_hndl_per_res_out_on_other_sc(
12343			(union ctl_ha_msg *)&io->presio.pr_msg);
12344		free_io = 1;
12345		break;
12346	case CTL_MSG_BAD_JUJU:
12347		free_io = 0;
12348		ctl_done(io);
12349		break;
12350	case CTL_MSG_DATAMOVE:
12351		/* Only used in XFER mode */
12352		free_io = 0;
12353		ctl_datamove_remote(io);
12354		break;
12355	case CTL_MSG_DATAMOVE_DONE:
12356		/* Only used in XFER mode */
12357		free_io = 0;
12358		io->scsiio.be_move_done(io);
12359		break;
12360	case CTL_MSG_FAILOVER:
12361		ctl_failover_lun(io);
12362		free_io = 1;
12363		break;
12364	default:
12365		free_io = 1;
12366		printf("%s: Invalid message type %d\n",
12367		       __func__, io->io_hdr.msg_type);
12368		break;
12369	}
12370	if (free_io)
12371		ctl_free_io(io);
12372
12373}
12374
12375
12376/*
12377 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12378 * there is no match.
12379 */
12380static ctl_lun_error_pattern
12381ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12382{
12383	const struct ctl_cmd_entry *entry;
12384	ctl_lun_error_pattern filtered_pattern, pattern;
12385
12386	pattern = desc->error_pattern;
12387
12388	/*
12389	 * XXX KDM we need more data passed into this function to match a
12390	 * custom pattern, and we actually need to implement custom pattern
12391	 * matching.
12392	 */
12393	if (pattern & CTL_LUN_PAT_CMD)
12394		return (CTL_LUN_PAT_CMD);
12395
12396	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12397		return (CTL_LUN_PAT_ANY);
12398
12399	entry = ctl_get_cmd_entry(ctsio, NULL);
12400
12401	filtered_pattern = entry->pattern & pattern;
12402
12403	/*
12404	 * If the user requested specific flags in the pattern (e.g.
12405	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12406	 * flags.
12407	 *
12408	 * If the user did not specify any flags, it doesn't matter whether
12409	 * or not the command supports the flags.
12410	 */
12411	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12412	     (pattern & ~CTL_LUN_PAT_MASK))
12413		return (CTL_LUN_PAT_NONE);
12414
12415	/*
12416	 * If the user asked for a range check, see if the requested LBA
12417	 * range overlaps with this command's LBA range.
12418	 */
12419	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12420		uint64_t lba1;
12421		uint64_t len1;
12422		ctl_action action;
12423		int retval;
12424
12425		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12426		if (retval != 0)
12427			return (CTL_LUN_PAT_NONE);
12428
12429		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12430					      desc->lba_range.len, FALSE);
12431		/*
12432		 * A "pass" means that the LBA ranges don't overlap, so
12433		 * this doesn't match the user's range criteria.
12434		 */
12435		if (action == CTL_ACTION_PASS)
12436			return (CTL_LUN_PAT_NONE);
12437	}
12438
12439	return (filtered_pattern);
12440}
12441
12442static void
12443ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12444{
12445	struct ctl_error_desc *desc, *desc2;
12446
12447	mtx_assert(&lun->lun_lock, MA_OWNED);
12448
12449	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12450		ctl_lun_error_pattern pattern;
12451		/*
12452		 * Check to see whether this particular command matches
12453		 * the pattern in the descriptor.
12454		 */
12455		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12456		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12457			continue;
12458
12459		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12460		case CTL_LUN_INJ_ABORTED:
12461			ctl_set_aborted(&io->scsiio);
12462			break;
12463		case CTL_LUN_INJ_MEDIUM_ERR:
12464			ctl_set_medium_error(&io->scsiio,
12465			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12466			     CTL_FLAG_DATA_OUT);
12467			break;
12468		case CTL_LUN_INJ_UA:
12469			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12470			 * OCCURRED */
12471			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12472			break;
12473		case CTL_LUN_INJ_CUSTOM:
12474			/*
12475			 * We're assuming the user knows what he is doing.
12476			 * Just copy the sense information without doing
12477			 * checks.
12478			 */
12479			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12480			      MIN(sizeof(desc->custom_sense),
12481				  sizeof(io->scsiio.sense_data)));
12482			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12483			io->scsiio.sense_len = SSD_FULL_SIZE;
12484			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12485			break;
12486		case CTL_LUN_INJ_NONE:
12487		default:
12488			/*
12489			 * If this is an error injection type we don't know
12490			 * about, clear the continuous flag (if it is set)
12491			 * so it will get deleted below.
12492			 */
12493			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12494			break;
12495		}
12496		/*
12497		 * By default, each error injection action is a one-shot
12498		 */
12499		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12500			continue;
12501
12502		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12503
12504		free(desc, M_CTL);
12505	}
12506}
12507
12508#ifdef CTL_IO_DELAY
12509static void
12510ctl_datamove_timer_wakeup(void *arg)
12511{
12512	union ctl_io *io;
12513
12514	io = (union ctl_io *)arg;
12515
12516	ctl_datamove(io);
12517}
12518#endif /* CTL_IO_DELAY */
12519
12520void
12521ctl_datamove(union ctl_io *io)
12522{
12523	struct ctl_lun *lun;
12524	void (*fe_datamove)(union ctl_io *io);
12525
12526	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12527
12528	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12529
12530	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12531#ifdef CTL_TIME_IO
12532	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12533		char str[256];
12534		char path_str[64];
12535		struct sbuf sb;
12536
12537		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12538		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12539
12540		sbuf_cat(&sb, path_str);
12541		switch (io->io_hdr.io_type) {
12542		case CTL_IO_SCSI:
12543			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12544			sbuf_printf(&sb, "\n");
12545			sbuf_cat(&sb, path_str);
12546			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12547				    io->scsiio.tag_num, io->scsiio.tag_type);
12548			break;
12549		case CTL_IO_TASK:
12550			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12551				    "Tag Type: %d\n", io->taskio.task_action,
12552				    io->taskio.tag_num, io->taskio.tag_type);
12553			break;
12554		default:
12555			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12556			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12557			break;
12558		}
12559		sbuf_cat(&sb, path_str);
12560		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12561			    (intmax_t)time_uptime - io->io_hdr.start_time);
12562		sbuf_finish(&sb);
12563		printf("%s", sbuf_data(&sb));
12564	}
12565#endif /* CTL_TIME_IO */
12566
12567#ifdef CTL_IO_DELAY
12568	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12569		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12570	} else {
12571		if ((lun != NULL)
12572		 && (lun->delay_info.datamove_delay > 0)) {
12573
12574			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12575			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12576			callout_reset(&io->io_hdr.delay_callout,
12577				      lun->delay_info.datamove_delay * hz,
12578				      ctl_datamove_timer_wakeup, io);
12579			if (lun->delay_info.datamove_type ==
12580			    CTL_DELAY_TYPE_ONESHOT)
12581				lun->delay_info.datamove_delay = 0;
12582			return;
12583		}
12584	}
12585#endif
12586
12587	/*
12588	 * This command has been aborted.  Set the port status, so we fail
12589	 * the data move.
12590	 */
12591	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12592		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12593		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12594		       io->io_hdr.nexus.targ_port,
12595		       io->io_hdr.nexus.targ_lun);
12596		io->io_hdr.port_status = 31337;
12597		/*
12598		 * Note that the backend, in this case, will get the
12599		 * callback in its context.  In other cases it may get
12600		 * called in the frontend's interrupt thread context.
12601		 */
12602		io->scsiio.be_move_done(io);
12603		return;
12604	}
12605
12606	/* Don't confuse frontend with zero length data move. */
12607	if (io->scsiio.kern_data_len == 0) {
12608		io->scsiio.be_move_done(io);
12609		return;
12610	}
12611
12612	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12613	fe_datamove(io);
12614}
12615
12616static void
12617ctl_send_datamove_done(union ctl_io *io, int have_lock)
12618{
12619	union ctl_ha_msg msg;
12620#ifdef CTL_TIME_IO
12621	struct bintime cur_bt;
12622#endif
12623
12624	memset(&msg, 0, sizeof(msg));
12625	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12626	msg.hdr.original_sc = io;
12627	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12628	msg.hdr.nexus = io->io_hdr.nexus;
12629	msg.hdr.status = io->io_hdr.status;
12630	msg.scsi.tag_num = io->scsiio.tag_num;
12631	msg.scsi.tag_type = io->scsiio.tag_type;
12632	msg.scsi.scsi_status = io->scsiio.scsi_status;
12633	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12634	       io->scsiio.sense_len);
12635	msg.scsi.sense_len = io->scsiio.sense_len;
12636	msg.scsi.sense_residual = io->scsiio.sense_residual;
12637	msg.scsi.fetd_status = io->io_hdr.port_status;
12638	msg.scsi.residual = io->scsiio.residual;
12639	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12640	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12641		ctl_failover_io(io, /*have_lock*/ have_lock);
12642		return;
12643	}
12644	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12645	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12646	    msg.scsi.sense_len, M_WAITOK);
12647
12648#ifdef CTL_TIME_IO
12649	getbinuptime(&cur_bt);
12650	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12651	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12652#endif
12653	io->io_hdr.num_dmas++;
12654}
12655
12656/*
12657 * The DMA to the remote side is done, now we need to tell the other side
12658 * we're done so it can continue with its data movement.
12659 */
12660static void
12661ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12662{
12663	union ctl_io *io;
12664	int i;
12665
12666	io = rq->context;
12667
12668	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12669		printf("%s: ISC DMA write failed with error %d", __func__,
12670		       rq->ret);
12671		ctl_set_internal_failure(&io->scsiio,
12672					 /*sks_valid*/ 1,
12673					 /*retry_count*/ rq->ret);
12674	}
12675
12676	ctl_dt_req_free(rq);
12677
12678	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12679		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12680	free(io->io_hdr.remote_sglist, M_CTL);
12681	io->io_hdr.remote_sglist = NULL;
12682	io->io_hdr.local_sglist = NULL;
12683
12684	/*
12685	 * The data is in local and remote memory, so now we need to send
12686	 * status (good or back) back to the other side.
12687	 */
12688	ctl_send_datamove_done(io, /*have_lock*/ 0);
12689}
12690
12691/*
12692 * We've moved the data from the host/controller into local memory.  Now we
12693 * need to push it over to the remote controller's memory.
12694 */
12695static int
12696ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12697{
12698	int retval;
12699
12700	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12701					  ctl_datamove_remote_write_cb);
12702	return (retval);
12703}
12704
12705static void
12706ctl_datamove_remote_write(union ctl_io *io)
12707{
12708	int retval;
12709	void (*fe_datamove)(union ctl_io *io);
12710
12711	/*
12712	 * - Get the data from the host/HBA into local memory.
12713	 * - DMA memory from the local controller to the remote controller.
12714	 * - Send status back to the remote controller.
12715	 */
12716
12717	retval = ctl_datamove_remote_sgl_setup(io);
12718	if (retval != 0)
12719		return;
12720
12721	/* Switch the pointer over so the FETD knows what to do */
12722	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12723
12724	/*
12725	 * Use a custom move done callback, since we need to send completion
12726	 * back to the other controller, not to the backend on this side.
12727	 */
12728	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12729
12730	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12731	fe_datamove(io);
12732}
12733
12734static int
12735ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12736{
12737#if 0
12738	char str[256];
12739	char path_str[64];
12740	struct sbuf sb;
12741#endif
12742	int i;
12743
12744	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12745		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12746	free(io->io_hdr.remote_sglist, M_CTL);
12747	io->io_hdr.remote_sglist = NULL;
12748	io->io_hdr.local_sglist = NULL;
12749
12750#if 0
12751	scsi_path_string(io, path_str, sizeof(path_str));
12752	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12753	sbuf_cat(&sb, path_str);
12754	scsi_command_string(&io->scsiio, NULL, &sb);
12755	sbuf_printf(&sb, "\n");
12756	sbuf_cat(&sb, path_str);
12757	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12758		    io->scsiio.tag_num, io->scsiio.tag_type);
12759	sbuf_cat(&sb, path_str);
12760	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12761		    io->io_hdr.flags, io->io_hdr.status);
12762	sbuf_finish(&sb);
12763	printk("%s", sbuf_data(&sb));
12764#endif
12765
12766
12767	/*
12768	 * The read is done, now we need to send status (good or bad) back
12769	 * to the other side.
12770	 */
12771	ctl_send_datamove_done(io, /*have_lock*/ 0);
12772
12773	return (0);
12774}
12775
12776static void
12777ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12778{
12779	union ctl_io *io;
12780	void (*fe_datamove)(union ctl_io *io);
12781
12782	io = rq->context;
12783
12784	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12785		printf("%s: ISC DMA read failed with error %d\n", __func__,
12786		       rq->ret);
12787		ctl_set_internal_failure(&io->scsiio,
12788					 /*sks_valid*/ 1,
12789					 /*retry_count*/ rq->ret);
12790	}
12791
12792	ctl_dt_req_free(rq);
12793
12794	/* Switch the pointer over so the FETD knows what to do */
12795	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12796
12797	/*
12798	 * Use a custom move done callback, since we need to send completion
12799	 * back to the other controller, not to the backend on this side.
12800	 */
12801	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12802
12803	/* XXX KDM add checks like the ones in ctl_datamove? */
12804
12805	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12806	fe_datamove(io);
12807}
12808
12809static int
12810ctl_datamove_remote_sgl_setup(union ctl_io *io)
12811{
12812	struct ctl_sg_entry *local_sglist;
12813	uint32_t len_to_go;
12814	int retval;
12815	int i;
12816
12817	retval = 0;
12818	local_sglist = io->io_hdr.local_sglist;
12819	len_to_go = io->scsiio.kern_data_len;
12820
12821	/*
12822	 * The difficult thing here is that the size of the various
12823	 * S/G segments may be different than the size from the
12824	 * remote controller.  That'll make it harder when DMAing
12825	 * the data back to the other side.
12826	 */
12827	for (i = 0; len_to_go > 0; i++) {
12828		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12829		local_sglist[i].addr =
12830		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12831
12832		len_to_go -= local_sglist[i].len;
12833	}
12834	/*
12835	 * Reset the number of S/G entries accordingly.  The original
12836	 * number of S/G entries is available in rem_sg_entries.
12837	 */
12838	io->scsiio.kern_sg_entries = i;
12839
12840#if 0
12841	printf("%s: kern_sg_entries = %d\n", __func__,
12842	       io->scsiio.kern_sg_entries);
12843	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12844		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12845		       local_sglist[i].addr, local_sglist[i].len);
12846#endif
12847
12848	return (retval);
12849}
12850
12851static int
12852ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12853			 ctl_ha_dt_cb callback)
12854{
12855	struct ctl_ha_dt_req *rq;
12856	struct ctl_sg_entry *remote_sglist, *local_sglist;
12857	uint32_t local_used, remote_used, total_used;
12858	int i, j, isc_ret;
12859
12860	rq = ctl_dt_req_alloc();
12861
12862	/*
12863	 * If we failed to allocate the request, and if the DMA didn't fail
12864	 * anyway, set busy status.  This is just a resource allocation
12865	 * failure.
12866	 */
12867	if ((rq == NULL)
12868	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12869	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12870		ctl_set_busy(&io->scsiio);
12871
12872	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12873	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12874
12875		if (rq != NULL)
12876			ctl_dt_req_free(rq);
12877
12878		/*
12879		 * The data move failed.  We need to return status back
12880		 * to the other controller.  No point in trying to DMA
12881		 * data to the remote controller.
12882		 */
12883
12884		ctl_send_datamove_done(io, /*have_lock*/ 0);
12885
12886		return (1);
12887	}
12888
12889	local_sglist = io->io_hdr.local_sglist;
12890	remote_sglist = io->io_hdr.remote_sglist;
12891	local_used = 0;
12892	remote_used = 0;
12893	total_used = 0;
12894
12895	/*
12896	 * Pull/push the data over the wire from/to the other controller.
12897	 * This takes into account the possibility that the local and
12898	 * remote sglists may not be identical in terms of the size of
12899	 * the elements and the number of elements.
12900	 *
12901	 * One fundamental assumption here is that the length allocated for
12902	 * both the local and remote sglists is identical.  Otherwise, we've
12903	 * essentially got a coding error of some sort.
12904	 */
12905	isc_ret = CTL_HA_STATUS_SUCCESS;
12906	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12907		uint32_t cur_len;
12908		uint8_t *tmp_ptr;
12909
12910		rq->command = command;
12911		rq->context = io;
12912
12913		/*
12914		 * Both pointers should be aligned.  But it is possible
12915		 * that the allocation length is not.  They should both
12916		 * also have enough slack left over at the end, though,
12917		 * to round up to the next 8 byte boundary.
12918		 */
12919		cur_len = MIN(local_sglist[i].len - local_used,
12920			      remote_sglist[j].len - remote_used);
12921		rq->size = cur_len;
12922
12923		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12924		tmp_ptr += local_used;
12925
12926#if 0
12927		/* Use physical addresses when talking to ISC hardware */
12928		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12929			/* XXX KDM use busdma */
12930			rq->local = vtophys(tmp_ptr);
12931		} else
12932			rq->local = tmp_ptr;
12933#else
12934		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12935		    ("HA does not support BUS_ADDR"));
12936		rq->local = tmp_ptr;
12937#endif
12938
12939		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12940		tmp_ptr += remote_used;
12941		rq->remote = tmp_ptr;
12942
12943		rq->callback = NULL;
12944
12945		local_used += cur_len;
12946		if (local_used >= local_sglist[i].len) {
12947			i++;
12948			local_used = 0;
12949		}
12950
12951		remote_used += cur_len;
12952		if (remote_used >= remote_sglist[j].len) {
12953			j++;
12954			remote_used = 0;
12955		}
12956		total_used += cur_len;
12957
12958		if (total_used >= io->scsiio.kern_data_len)
12959			rq->callback = callback;
12960
12961#if 0
12962		printf("%s: %s: local %p remote %p size %d\n", __func__,
12963		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12964		       rq->local, rq->remote, rq->size);
12965#endif
12966
12967		isc_ret = ctl_dt_single(rq);
12968		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12969			break;
12970	}
12971	if (isc_ret != CTL_HA_STATUS_WAIT) {
12972		rq->ret = isc_ret;
12973		callback(rq);
12974	}
12975
12976	return (0);
12977}
12978
12979static void
12980ctl_datamove_remote_read(union ctl_io *io)
12981{
12982	int retval;
12983	int i;
12984
12985	/*
12986	 * This will send an error to the other controller in the case of a
12987	 * failure.
12988	 */
12989	retval = ctl_datamove_remote_sgl_setup(io);
12990	if (retval != 0)
12991		return;
12992
12993	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12994					  ctl_datamove_remote_read_cb);
12995	if (retval != 0) {
12996		/*
12997		 * Make sure we free memory if there was an error..  The
12998		 * ctl_datamove_remote_xfer() function will send the
12999		 * datamove done message, or call the callback with an
13000		 * error if there is a problem.
13001		 */
13002		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13003			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13004		free(io->io_hdr.remote_sglist, M_CTL);
13005		io->io_hdr.remote_sglist = NULL;
13006		io->io_hdr.local_sglist = NULL;
13007	}
13008}
13009
13010/*
13011 * Process a datamove request from the other controller.  This is used for
13012 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13013 * first.  Once that is complete, the data gets DMAed into the remote
13014 * controller's memory.  For reads, we DMA from the remote controller's
13015 * memory into our memory first, and then move it out to the FETD.
13016 */
13017static void
13018ctl_datamove_remote(union ctl_io *io)
13019{
13020
13021	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13022
13023	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13024		ctl_failover_io(io, /*have_lock*/ 0);
13025		return;
13026	}
13027
13028	/*
13029	 * Note that we look for an aborted I/O here, but don't do some of
13030	 * the other checks that ctl_datamove() normally does.
13031	 * We don't need to run the datamove delay code, since that should
13032	 * have been done if need be on the other controller.
13033	 */
13034	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13035		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13036		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13037		       io->io_hdr.nexus.targ_port,
13038		       io->io_hdr.nexus.targ_lun);
13039		io->io_hdr.port_status = 31338;
13040		ctl_send_datamove_done(io, /*have_lock*/ 0);
13041		return;
13042	}
13043
13044	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13045		ctl_datamove_remote_write(io);
13046	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13047		ctl_datamove_remote_read(io);
13048	else {
13049		io->io_hdr.port_status = 31339;
13050		ctl_send_datamove_done(io, /*have_lock*/ 0);
13051	}
13052}
13053
13054static void
13055ctl_process_done(union ctl_io *io)
13056{
13057	struct ctl_lun *lun;
13058	struct ctl_softc *softc = control_softc;
13059	void (*fe_done)(union ctl_io *io);
13060	union ctl_ha_msg msg;
13061	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13062
13063	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13064	fe_done = softc->ctl_ports[targ_port]->fe_done;
13065
13066#ifdef CTL_TIME_IO
13067	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13068		char str[256];
13069		char path_str[64];
13070		struct sbuf sb;
13071
13072		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13073		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13074
13075		sbuf_cat(&sb, path_str);
13076		switch (io->io_hdr.io_type) {
13077		case CTL_IO_SCSI:
13078			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13079			sbuf_printf(&sb, "\n");
13080			sbuf_cat(&sb, path_str);
13081			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13082				    io->scsiio.tag_num, io->scsiio.tag_type);
13083			break;
13084		case CTL_IO_TASK:
13085			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13086				    "Tag Type: %d\n", io->taskio.task_action,
13087				    io->taskio.tag_num, io->taskio.tag_type);
13088			break;
13089		default:
13090			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13091			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13092			break;
13093		}
13094		sbuf_cat(&sb, path_str);
13095		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13096			    (intmax_t)time_uptime - io->io_hdr.start_time);
13097		sbuf_finish(&sb);
13098		printf("%s", sbuf_data(&sb));
13099	}
13100#endif /* CTL_TIME_IO */
13101
13102	switch (io->io_hdr.io_type) {
13103	case CTL_IO_SCSI:
13104		break;
13105	case CTL_IO_TASK:
13106		if (ctl_debug & CTL_DEBUG_INFO)
13107			ctl_io_error_print(io, NULL);
13108		fe_done(io);
13109		return;
13110	default:
13111		panic("ctl_process_done: invalid io type %d\n",
13112		      io->io_hdr.io_type);
13113		break; /* NOTREACHED */
13114	}
13115
13116	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13117	if (lun == NULL) {
13118		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13119				 io->io_hdr.nexus.targ_mapped_lun));
13120		goto bailout;
13121	}
13122
13123	mtx_lock(&lun->lun_lock);
13124
13125	/*
13126	 * Check to see if we have any errors to inject here.  We only
13127	 * inject errors for commands that don't already have errors set.
13128	 */
13129	if (!STAILQ_EMPTY(&lun->error_list) &&
13130	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13131	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13132		ctl_inject_error(lun, io);
13133
13134	/*
13135	 * XXX KDM how do we treat commands that aren't completed
13136	 * successfully?
13137	 *
13138	 * XXX KDM should we also track I/O latency?
13139	 */
13140	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13141	    io->io_hdr.io_type == CTL_IO_SCSI) {
13142#ifdef CTL_TIME_IO
13143		struct bintime cur_bt;
13144#endif
13145		int type;
13146
13147		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13148		    CTL_FLAG_DATA_IN)
13149			type = CTL_STATS_READ;
13150		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13151		    CTL_FLAG_DATA_OUT)
13152			type = CTL_STATS_WRITE;
13153		else
13154			type = CTL_STATS_NO_IO;
13155
13156		lun->stats.ports[targ_port].bytes[type] +=
13157		    io->scsiio.kern_total_len;
13158		lun->stats.ports[targ_port].operations[type]++;
13159#ifdef CTL_TIME_IO
13160		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13161		   &io->io_hdr.dma_bt);
13162		getbinuptime(&cur_bt);
13163		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13164		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13165#endif
13166		lun->stats.ports[targ_port].num_dmas[type] +=
13167		    io->io_hdr.num_dmas;
13168	}
13169
13170	/*
13171	 * Remove this from the OOA queue.
13172	 */
13173	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13174#ifdef CTL_TIME_IO
13175	if (TAILQ_EMPTY(&lun->ooa_queue))
13176		lun->last_busy = getsbinuptime();
13177#endif
13178
13179	/*
13180	 * Run through the blocked queue on this LUN and see if anything
13181	 * has become unblocked, now that this transaction is done.
13182	 */
13183	ctl_check_blocked(lun);
13184
13185	/*
13186	 * If the LUN has been invalidated, free it if there is nothing
13187	 * left on its OOA queue.
13188	 */
13189	if ((lun->flags & CTL_LUN_INVALID)
13190	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13191		mtx_unlock(&lun->lun_lock);
13192		mtx_lock(&softc->ctl_lock);
13193		ctl_free_lun(lun);
13194		mtx_unlock(&softc->ctl_lock);
13195	} else
13196		mtx_unlock(&lun->lun_lock);
13197
13198bailout:
13199
13200	/*
13201	 * If this command has been aborted, make sure we set the status
13202	 * properly.  The FETD is responsible for freeing the I/O and doing
13203	 * whatever it needs to do to clean up its state.
13204	 */
13205	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13206		ctl_set_task_aborted(&io->scsiio);
13207
13208	/*
13209	 * If enabled, print command error status.
13210	 */
13211	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13212	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13213		ctl_io_error_print(io, NULL);
13214
13215	/*
13216	 * Tell the FETD or the other shelf controller we're done with this
13217	 * command.  Note that only SCSI commands get to this point.  Task
13218	 * management commands are completed above.
13219	 */
13220	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13221	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13222		memset(&msg, 0, sizeof(msg));
13223		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13224		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13225		msg.hdr.nexus = io->io_hdr.nexus;
13226		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13227		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13228		    M_WAITOK);
13229	}
13230
13231	fe_done(io);
13232}
13233
13234#ifdef CTL_WITH_CA
13235/*
13236 * Front end should call this if it doesn't do autosense.  When the request
13237 * sense comes back in from the initiator, we'll dequeue this and send it.
13238 */
13239int
13240ctl_queue_sense(union ctl_io *io)
13241{
13242	struct ctl_lun *lun;
13243	struct ctl_port *port;
13244	struct ctl_softc *softc;
13245	uint32_t initidx, targ_lun;
13246
13247	softc = control_softc;
13248
13249	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13250
13251	/*
13252	 * LUN lookup will likely move to the ctl_work_thread() once we
13253	 * have our new queueing infrastructure (that doesn't put things on
13254	 * a per-LUN queue initially).  That is so that we can handle
13255	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13256	 * can't deal with that right now.
13257	 */
13258	mtx_lock(&softc->ctl_lock);
13259
13260	/*
13261	 * If we don't have a LUN for this, just toss the sense
13262	 * information.
13263	 */
13264	port = ctl_io_port(&ctsio->io_hdr);
13265	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13266	if ((targ_lun < CTL_MAX_LUNS)
13267	 && (softc->ctl_luns[targ_lun] != NULL))
13268		lun = softc->ctl_luns[targ_lun];
13269	else
13270		goto bailout;
13271
13272	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13273
13274	mtx_lock(&lun->lun_lock);
13275	/*
13276	 * Already have CA set for this LUN...toss the sense information.
13277	 */
13278	if (ctl_is_set(lun->have_ca, initidx)) {
13279		mtx_unlock(&lun->lun_lock);
13280		goto bailout;
13281	}
13282
13283	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13284	       MIN(sizeof(lun->pending_sense[initidx]),
13285	       sizeof(io->scsiio.sense_data)));
13286	ctl_set_mask(lun->have_ca, initidx);
13287	mtx_unlock(&lun->lun_lock);
13288
13289bailout:
13290	mtx_unlock(&softc->ctl_lock);
13291
13292	ctl_free_io(io);
13293
13294	return (CTL_RETVAL_COMPLETE);
13295}
13296#endif
13297
13298/*
13299 * Primary command inlet from frontend ports.  All SCSI and task I/O
13300 * requests must go through this function.
13301 */
13302int
13303ctl_queue(union ctl_io *io)
13304{
13305	struct ctl_port *port;
13306
13307	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13308
13309#ifdef CTL_TIME_IO
13310	io->io_hdr.start_time = time_uptime;
13311	getbinuptime(&io->io_hdr.start_bt);
13312#endif /* CTL_TIME_IO */
13313
13314	/* Map FE-specific LUN ID into global one. */
13315	port = ctl_io_port(&io->io_hdr);
13316	io->io_hdr.nexus.targ_mapped_lun =
13317	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13318
13319	switch (io->io_hdr.io_type) {
13320	case CTL_IO_SCSI:
13321	case CTL_IO_TASK:
13322		if (ctl_debug & CTL_DEBUG_CDB)
13323			ctl_io_print(io);
13324		ctl_enqueue_incoming(io);
13325		break;
13326	default:
13327		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13328		return (EINVAL);
13329	}
13330
13331	return (CTL_RETVAL_COMPLETE);
13332}
13333
13334#ifdef CTL_IO_DELAY
13335static void
13336ctl_done_timer_wakeup(void *arg)
13337{
13338	union ctl_io *io;
13339
13340	io = (union ctl_io *)arg;
13341	ctl_done(io);
13342}
13343#endif /* CTL_IO_DELAY */
13344
13345void
13346ctl_serseq_done(union ctl_io *io)
13347{
13348	struct ctl_lun *lun;
13349
13350	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13351	if (lun->be_lun == NULL ||
13352	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13353		return;
13354	mtx_lock(&lun->lun_lock);
13355	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13356	ctl_check_blocked(lun);
13357	mtx_unlock(&lun->lun_lock);
13358}
13359
13360void
13361ctl_done(union ctl_io *io)
13362{
13363
13364	/*
13365	 * Enable this to catch duplicate completion issues.
13366	 */
13367#if 0
13368	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13369		printf("%s: type %d msg %d cdb %x iptl: "
13370		       "%u:%u:%u tag 0x%04x "
13371		       "flag %#x status %x\n",
13372			__func__,
13373			io->io_hdr.io_type,
13374			io->io_hdr.msg_type,
13375			io->scsiio.cdb[0],
13376			io->io_hdr.nexus.initid,
13377			io->io_hdr.nexus.targ_port,
13378			io->io_hdr.nexus.targ_lun,
13379			(io->io_hdr.io_type ==
13380			CTL_IO_TASK) ?
13381			io->taskio.tag_num :
13382			io->scsiio.tag_num,
13383		        io->io_hdr.flags,
13384			io->io_hdr.status);
13385	} else
13386		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13387#endif
13388
13389	/*
13390	 * This is an internal copy of an I/O, and should not go through
13391	 * the normal done processing logic.
13392	 */
13393	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13394		return;
13395
13396#ifdef CTL_IO_DELAY
13397	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13398		struct ctl_lun *lun;
13399
13400		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13401
13402		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13403	} else {
13404		struct ctl_lun *lun;
13405
13406		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13407
13408		if ((lun != NULL)
13409		 && (lun->delay_info.done_delay > 0)) {
13410
13411			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13412			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13413			callout_reset(&io->io_hdr.delay_callout,
13414				      lun->delay_info.done_delay * hz,
13415				      ctl_done_timer_wakeup, io);
13416			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13417				lun->delay_info.done_delay = 0;
13418			return;
13419		}
13420	}
13421#endif /* CTL_IO_DELAY */
13422
13423	ctl_enqueue_done(io);
13424}
13425
13426static void
13427ctl_work_thread(void *arg)
13428{
13429	struct ctl_thread *thr = (struct ctl_thread *)arg;
13430	struct ctl_softc *softc = thr->ctl_softc;
13431	union ctl_io *io;
13432	int retval;
13433
13434	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13435
13436	for (;;) {
13437		/*
13438		 * We handle the queues in this order:
13439		 * - ISC
13440		 * - done queue (to free up resources, unblock other commands)
13441		 * - RtR queue
13442		 * - incoming queue
13443		 *
13444		 * If those queues are empty, we break out of the loop and
13445		 * go to sleep.
13446		 */
13447		mtx_lock(&thr->queue_lock);
13448		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13449		if (io != NULL) {
13450			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13451			mtx_unlock(&thr->queue_lock);
13452			ctl_handle_isc(io);
13453			continue;
13454		}
13455		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13456		if (io != NULL) {
13457			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13458			/* clear any blocked commands, call fe_done */
13459			mtx_unlock(&thr->queue_lock);
13460			ctl_process_done(io);
13461			continue;
13462		}
13463		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13464		if (io != NULL) {
13465			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13466			mtx_unlock(&thr->queue_lock);
13467			if (io->io_hdr.io_type == CTL_IO_TASK)
13468				ctl_run_task(io);
13469			else
13470				ctl_scsiio_precheck(softc, &io->scsiio);
13471			continue;
13472		}
13473		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13474		if (io != NULL) {
13475			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13476			mtx_unlock(&thr->queue_lock);
13477			retval = ctl_scsiio(&io->scsiio);
13478			if (retval != CTL_RETVAL_COMPLETE)
13479				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13480			continue;
13481		}
13482
13483		/* Sleep until we have something to do. */
13484		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13485	}
13486}
13487
13488static void
13489ctl_lun_thread(void *arg)
13490{
13491	struct ctl_softc *softc = (struct ctl_softc *)arg;
13492	struct ctl_be_lun *be_lun;
13493
13494	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13495
13496	for (;;) {
13497		mtx_lock(&softc->ctl_lock);
13498		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13499		if (be_lun != NULL) {
13500			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13501			mtx_unlock(&softc->ctl_lock);
13502			ctl_create_lun(be_lun);
13503			continue;
13504		}
13505
13506		/* Sleep until we have something to do. */
13507		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13508		    PDROP | PRIBIO, "-", 0);
13509	}
13510}
13511
13512static void
13513ctl_thresh_thread(void *arg)
13514{
13515	struct ctl_softc *softc = (struct ctl_softc *)arg;
13516	struct ctl_lun *lun;
13517	struct scsi_da_rw_recovery_page *rwpage;
13518	struct ctl_logical_block_provisioning_page *page;
13519	const char *attr;
13520	union ctl_ha_msg msg;
13521	uint64_t thres, val;
13522	int i, e, set;
13523
13524	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13525
13526	for (;;) {
13527		mtx_lock(&softc->ctl_lock);
13528		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13529			if ((lun->flags & CTL_LUN_DISABLED) ||
13530			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13531			    lun->backend->lun_attr == NULL)
13532				continue;
13533			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13534			    softc->ha_mode == CTL_HA_MODE_XFER)
13535				continue;
13536			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13537			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13538				continue;
13539			e = 0;
13540			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13541			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13542				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13543					continue;
13544				thres = scsi_4btoul(page->descr[i].count);
13545				thres <<= CTL_LBP_EXPONENT;
13546				switch (page->descr[i].resource) {
13547				case 0x01:
13548					attr = "blocksavail";
13549					break;
13550				case 0x02:
13551					attr = "blocksused";
13552					break;
13553				case 0xf1:
13554					attr = "poolblocksavail";
13555					break;
13556				case 0xf2:
13557					attr = "poolblocksused";
13558					break;
13559				default:
13560					continue;
13561				}
13562				mtx_unlock(&softc->ctl_lock); // XXX
13563				val = lun->backend->lun_attr(
13564				    lun->be_lun->be_lun, attr);
13565				mtx_lock(&softc->ctl_lock);
13566				if (val == UINT64_MAX)
13567					continue;
13568				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13569				    == SLBPPD_ARMING_INC)
13570					e = (val >= thres);
13571				else
13572					e = (val <= thres);
13573				if (e)
13574					break;
13575			}
13576			mtx_lock(&lun->lun_lock);
13577			if (e) {
13578				scsi_u64to8b((uint8_t *)&page->descr[i] -
13579				    (uint8_t *)page, lun->ua_tpt_info);
13580				if (lun->lasttpt == 0 ||
13581				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13582					lun->lasttpt = time_uptime;
13583					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13584					set = 1;
13585				} else
13586					set = 0;
13587			} else {
13588				lun->lasttpt = 0;
13589				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13590				set = -1;
13591			}
13592			mtx_unlock(&lun->lun_lock);
13593			if (set != 0 &&
13594			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13595				/* Send msg to other side. */
13596				bzero(&msg.ua, sizeof(msg.ua));
13597				msg.hdr.msg_type = CTL_MSG_UA;
13598				msg.hdr.nexus.initid = -1;
13599				msg.hdr.nexus.targ_port = -1;
13600				msg.hdr.nexus.targ_lun = lun->lun;
13601				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13602				msg.ua.ua_all = 1;
13603				msg.ua.ua_set = (set > 0);
13604				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13605				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13606				mtx_unlock(&softc->ctl_lock); // XXX
13607				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13608				    sizeof(msg.ua), M_WAITOK);
13609				mtx_lock(&softc->ctl_lock);
13610			}
13611		}
13612		mtx_unlock(&softc->ctl_lock);
13613		pause("-", CTL_LBP_PERIOD * hz);
13614	}
13615}
13616
13617static void
13618ctl_enqueue_incoming(union ctl_io *io)
13619{
13620	struct ctl_softc *softc = control_softc;
13621	struct ctl_thread *thr;
13622	u_int idx;
13623
13624	idx = (io->io_hdr.nexus.targ_port * 127 +
13625	       io->io_hdr.nexus.initid) % worker_threads;
13626	thr = &softc->threads[idx];
13627	mtx_lock(&thr->queue_lock);
13628	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13629	mtx_unlock(&thr->queue_lock);
13630	wakeup(thr);
13631}
13632
13633static void
13634ctl_enqueue_rtr(union ctl_io *io)
13635{
13636	struct ctl_softc *softc = control_softc;
13637	struct ctl_thread *thr;
13638
13639	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13640	mtx_lock(&thr->queue_lock);
13641	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13642	mtx_unlock(&thr->queue_lock);
13643	wakeup(thr);
13644}
13645
13646static void
13647ctl_enqueue_done(union ctl_io *io)
13648{
13649	struct ctl_softc *softc = control_softc;
13650	struct ctl_thread *thr;
13651
13652	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13653	mtx_lock(&thr->queue_lock);
13654	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13655	mtx_unlock(&thr->queue_lock);
13656	wakeup(thr);
13657}
13658
13659static void
13660ctl_enqueue_isc(union ctl_io *io)
13661{
13662	struct ctl_softc *softc = control_softc;
13663	struct ctl_thread *thr;
13664
13665	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13666	mtx_lock(&thr->queue_lock);
13667	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13668	mtx_unlock(&thr->queue_lock);
13669	wakeup(thr);
13670}
13671
13672/*
13673 *  vim: ts=8
13674 */
13675