ctl.c revision 288449
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: head/sys/cam/ctl/ctl.c 288449 2015-10-01 12:57:37Z 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;
405SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
406    &worker_threads, 1, "Number of worker threads");
407static int ctl_debug = CTL_DEBUG_NONE;
408SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
409    &ctl_debug, 0, "Enabled debug flags");
410
411/*
412 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
413 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
414 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
415 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
416 */
417#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
418
419static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
420				  int param);
421static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
422static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
423static int ctl_init(void);
424void ctl_shutdown(void);
425static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
426static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
427static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
428static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
429			      struct ctl_ooa *ooa_hdr,
430			      struct ctl_ooa_entry *kern_entries);
431static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
432		     struct thread *td);
433static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
434			 struct ctl_be_lun *be_lun);
435static int ctl_free_lun(struct ctl_lun *lun);
436static void ctl_create_lun(struct ctl_be_lun *be_lun);
437static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
438
439static int ctl_do_mode_select(union ctl_io *io);
440static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
441			   uint64_t res_key, uint64_t sa_res_key,
442			   uint8_t type, uint32_t residx,
443			   struct ctl_scsiio *ctsio,
444			   struct scsi_per_res_out *cdb,
445			   struct scsi_per_res_out_parms* param);
446static void ctl_pro_preempt_other(struct ctl_lun *lun,
447				  union ctl_ha_msg *msg);
448static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
449static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
450static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
451static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
452static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
453static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
455					 int alloc_len);
456static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
457					 int alloc_len);
458static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
459static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
460static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
461static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
462static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
463static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
464    bool seq);
465static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
466static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
467    union ctl_io *pending_io, union ctl_io *ooa_io);
468static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
469				union ctl_io *starting_io);
470static int ctl_check_blocked(struct ctl_lun *lun);
471static int ctl_scsiio_lun_check(struct ctl_lun *lun,
472				const struct ctl_cmd_entry *entry,
473				struct ctl_scsiio *ctsio);
474static void ctl_failover_lun(union ctl_io *io);
475static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
476			       struct ctl_scsiio *ctsio);
477static int ctl_scsiio(struct ctl_scsiio *ctsio);
478
479static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
480static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
481			    ctl_ua_type ua_type);
482static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
483			 ctl_ua_type ua_type);
484static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
485static int ctl_abort_task(union ctl_io *io);
486static int ctl_abort_task_set(union ctl_io *io);
487static int ctl_query_task(union ctl_io *io, int task_set);
488static int ctl_i_t_nexus_reset(union ctl_io *io);
489static int ctl_query_async_event(union ctl_io *io);
490static void ctl_run_task(union ctl_io *io);
491#ifdef CTL_IO_DELAY
492static void ctl_datamove_timer_wakeup(void *arg);
493static void ctl_done_timer_wakeup(void *arg);
494#endif /* CTL_IO_DELAY */
495
496static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
497static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
498static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
499static void ctl_datamove_remote_write(union ctl_io *io);
500static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
501static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
502static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
503static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
504				    ctl_ha_dt_cb callback);
505static void ctl_datamove_remote_read(union ctl_io *io);
506static void ctl_datamove_remote(union ctl_io *io);
507static void ctl_process_done(union ctl_io *io);
508static void ctl_lun_thread(void *arg);
509static void ctl_thresh_thread(void *arg);
510static void ctl_work_thread(void *arg);
511static void ctl_enqueue_incoming(union ctl_io *io);
512static void ctl_enqueue_rtr(union ctl_io *io);
513static void ctl_enqueue_done(union ctl_io *io);
514static void ctl_enqueue_isc(union ctl_io *io);
515static const struct ctl_cmd_entry *
516    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
517static const struct ctl_cmd_entry *
518    ctl_validate_command(struct ctl_scsiio *ctsio);
519static int ctl_cmd_applicable(uint8_t lun_type,
520    const struct ctl_cmd_entry *entry);
521
522static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
523static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
524static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
525static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
526
527/*
528 * Load the serialization table.  This isn't very pretty, but is probably
529 * the easiest way to do it.
530 */
531#include "ctl_ser_table.c"
532
533/*
534 * We only need to define open, close and ioctl routines for this driver.
535 */
536static struct cdevsw ctl_cdevsw = {
537	.d_version =	D_VERSION,
538	.d_flags =	0,
539	.d_open =	ctl_open,
540	.d_close =	ctl_close,
541	.d_ioctl =	ctl_ioctl,
542	.d_name =	"ctl",
543};
544
545
546MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
547
548static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
549
550static moduledata_t ctl_moduledata = {
551	"ctl",
552	ctl_module_event_handler,
553	NULL
554};
555
556DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
557MODULE_VERSION(ctl, 1);
558
559static struct ctl_frontend ha_frontend =
560{
561	.name = "ha",
562};
563
564static void
565ctl_ha_datamove(union ctl_io *io)
566{
567	struct ctl_lun *lun;
568	struct ctl_sg_entry *sgl;
569	union ctl_ha_msg msg;
570	uint32_t sg_entries_sent;
571	int do_sg_copy, i, j;
572
573	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
574	memset(&msg.dt, 0, sizeof(msg.dt));
575	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
576	msg.hdr.original_sc = io->io_hdr.original_sc;
577	msg.hdr.serializing_sc = io;
578	msg.hdr.nexus = io->io_hdr.nexus;
579	msg.hdr.status = io->io_hdr.status;
580	msg.dt.flags = io->io_hdr.flags;
581
582	/*
583	 * We convert everything into a S/G list here.  We can't
584	 * pass by reference, only by value between controllers.
585	 * So we can't pass a pointer to the S/G list, only as many
586	 * S/G entries as we can fit in here.  If it's possible for
587	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
588	 * then we need to break this up into multiple transfers.
589	 */
590	if (io->scsiio.kern_sg_entries == 0) {
591		msg.dt.kern_sg_entries = 1;
592#if 0
593		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
594			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
595		} else {
596			/* XXX KDM use busdma here! */
597			msg.dt.sg_list[0].addr =
598			    (void *)vtophys(io->scsiio.kern_data_ptr);
599		}
600#else
601		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
602		    ("HA does not support BUS_ADDR"));
603		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
604#endif
605		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
606		do_sg_copy = 0;
607	} else {
608		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
609		do_sg_copy = 1;
610	}
611
612	msg.dt.kern_data_len = io->scsiio.kern_data_len;
613	msg.dt.kern_total_len = io->scsiio.kern_total_len;
614	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
615	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
616	msg.dt.sg_sequence = 0;
617
618	/*
619	 * Loop until we've sent all of the S/G entries.  On the
620	 * other end, we'll recompose these S/G entries into one
621	 * contiguous list before processing.
622	 */
623	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
624	    msg.dt.sg_sequence++) {
625		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
626		    sizeof(msg.dt.sg_list[0])),
627		    msg.dt.kern_sg_entries - sg_entries_sent);
628		if (do_sg_copy != 0) {
629			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
630			for (i = sg_entries_sent, j = 0;
631			     i < msg.dt.cur_sg_entries; i++, j++) {
632#if 0
633				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
634					msg.dt.sg_list[j].addr = sgl[i].addr;
635				} else {
636					/* XXX KDM use busdma here! */
637					msg.dt.sg_list[j].addr =
638					    (void *)vtophys(sgl[i].addr);
639				}
640#else
641				KASSERT((io->io_hdr.flags &
642				    CTL_FLAG_BUS_ADDR) == 0,
643				    ("HA does not support BUS_ADDR"));
644				msg.dt.sg_list[j].addr = sgl[i].addr;
645#endif
646				msg.dt.sg_list[j].len = sgl[i].len;
647			}
648		}
649
650		sg_entries_sent += msg.dt.cur_sg_entries;
651		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
652		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
653		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
654		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
655		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
656			io->io_hdr.port_status = 31341;
657			io->scsiio.be_move_done(io);
658			return;
659		}
660		msg.dt.sent_sg_entries = sg_entries_sent;
661	}
662
663	/*
664	 * Officially handover the request from us to peer.
665	 * If failover has just happened, then we must return error.
666	 * If failover happen just after, then it is not our problem.
667	 */
668	if (lun)
669		mtx_lock(&lun->lun_lock);
670	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
671		if (lun)
672			mtx_unlock(&lun->lun_lock);
673		io->io_hdr.port_status = 31342;
674		io->scsiio.be_move_done(io);
675		return;
676	}
677	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
678	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
679	if (lun)
680		mtx_unlock(&lun->lun_lock);
681}
682
683static void
684ctl_ha_done(union ctl_io *io)
685{
686	union ctl_ha_msg msg;
687
688	if (io->io_hdr.io_type == CTL_IO_SCSI) {
689		memset(&msg, 0, sizeof(msg));
690		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
691		msg.hdr.original_sc = io->io_hdr.original_sc;
692		msg.hdr.nexus = io->io_hdr.nexus;
693		msg.hdr.status = io->io_hdr.status;
694		msg.scsi.scsi_status = io->scsiio.scsi_status;
695		msg.scsi.tag_num = io->scsiio.tag_num;
696		msg.scsi.tag_type = io->scsiio.tag_type;
697		msg.scsi.sense_len = io->scsiio.sense_len;
698		msg.scsi.sense_residual = io->scsiio.sense_residual;
699		msg.scsi.residual = io->scsiio.residual;
700		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
701		    io->scsiio.sense_len);
702		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
703		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
704		    msg.scsi.sense_len, M_WAITOK);
705	}
706	ctl_free_io(io);
707}
708
709static void
710ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
711			    union ctl_ha_msg *msg_info)
712{
713	struct ctl_scsiio *ctsio;
714
715	if (msg_info->hdr.original_sc == NULL) {
716		printf("%s: original_sc == NULL!\n", __func__);
717		/* XXX KDM now what? */
718		return;
719	}
720
721	ctsio = &msg_info->hdr.original_sc->scsiio;
722	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
723	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
724	ctsio->io_hdr.status = msg_info->hdr.status;
725	ctsio->scsi_status = msg_info->scsi.scsi_status;
726	ctsio->sense_len = msg_info->scsi.sense_len;
727	ctsio->sense_residual = msg_info->scsi.sense_residual;
728	ctsio->residual = msg_info->scsi.residual;
729	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
730	       msg_info->scsi.sense_len);
731	ctl_enqueue_isc((union ctl_io *)ctsio);
732}
733
734static void
735ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
736				union ctl_ha_msg *msg_info)
737{
738	struct ctl_scsiio *ctsio;
739
740	if (msg_info->hdr.serializing_sc == NULL) {
741		printf("%s: serializing_sc == NULL!\n", __func__);
742		/* XXX KDM now what? */
743		return;
744	}
745
746	ctsio = &msg_info->hdr.serializing_sc->scsiio;
747	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
748	ctl_enqueue_isc((union ctl_io *)ctsio);
749}
750
751void
752ctl_isc_announce_lun(struct ctl_lun *lun)
753{
754	struct ctl_softc *softc = lun->ctl_softc;
755	union ctl_ha_msg *msg;
756	struct ctl_ha_msg_lun_pr_key pr_key;
757	int i, k;
758
759	if (softc->ha_link != CTL_HA_LINK_ONLINE)
760		return;
761	mtx_lock(&lun->lun_lock);
762	i = sizeof(msg->lun);
763	if (lun->lun_devid)
764		i += lun->lun_devid->len;
765	i += sizeof(pr_key) * lun->pr_key_count;
766alloc:
767	mtx_unlock(&lun->lun_lock);
768	msg = malloc(i, M_CTL, M_WAITOK);
769	mtx_lock(&lun->lun_lock);
770	k = sizeof(msg->lun);
771	if (lun->lun_devid)
772		k += lun->lun_devid->len;
773	k += sizeof(pr_key) * lun->pr_key_count;
774	if (i < k) {
775		free(msg, M_CTL);
776		i = k;
777		goto alloc;
778	}
779	bzero(&msg->lun, sizeof(msg->lun));
780	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
781	msg->hdr.nexus.targ_lun = lun->lun;
782	msg->hdr.nexus.targ_mapped_lun = lun->lun;
783	msg->lun.flags = lun->flags;
784	msg->lun.pr_generation = lun->pr_generation;
785	msg->lun.pr_res_idx = lun->pr_res_idx;
786	msg->lun.pr_res_type = lun->pr_res_type;
787	msg->lun.pr_key_count = lun->pr_key_count;
788	i = 0;
789	if (lun->lun_devid) {
790		msg->lun.lun_devid_len = lun->lun_devid->len;
791		memcpy(&msg->lun.data[i], lun->lun_devid->data,
792		    msg->lun.lun_devid_len);
793		i += msg->lun.lun_devid_len;
794	}
795	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
796		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
797			continue;
798		pr_key.pr_iid = k;
799		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
800		i += sizeof(pr_key);
801	}
802	mtx_unlock(&lun->lun_lock);
803	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
804	    M_WAITOK);
805	free(msg, M_CTL);
806
807	if (lun->flags & CTL_LUN_PRIMARY_SC) {
808		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
809			ctl_isc_announce_mode(lun, -1,
810			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
811			    lun->mode_pages.index[i].subpage);
812		}
813	}
814}
815
816void
817ctl_isc_announce_port(struct ctl_port *port)
818{
819	struct ctl_softc *softc = port->ctl_softc;
820	union ctl_ha_msg *msg;
821	int i;
822
823	if (port->targ_port < softc->port_min ||
824	    port->targ_port >= softc->port_max ||
825	    softc->ha_link != CTL_HA_LINK_ONLINE)
826		return;
827	i = sizeof(msg->port) + strlen(port->port_name) + 1;
828	if (port->lun_map)
829		i += sizeof(uint32_t) * CTL_MAX_LUNS;
830	if (port->port_devid)
831		i += port->port_devid->len;
832	if (port->target_devid)
833		i += port->target_devid->len;
834	if (port->init_devid)
835		i += port->init_devid->len;
836	msg = malloc(i, M_CTL, M_WAITOK);
837	bzero(&msg->port, sizeof(msg->port));
838	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
839	msg->hdr.nexus.targ_port = port->targ_port;
840	msg->port.port_type = port->port_type;
841	msg->port.physical_port = port->physical_port;
842	msg->port.virtual_port = port->virtual_port;
843	msg->port.status = port->status;
844	i = 0;
845	msg->port.name_len = sprintf(&msg->port.data[i],
846	    "%d:%s", softc->ha_id, port->port_name) + 1;
847	i += msg->port.name_len;
848	if (port->lun_map) {
849		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
850		memcpy(&msg->port.data[i], port->lun_map,
851		    msg->port.lun_map_len);
852		i += msg->port.lun_map_len;
853	}
854	if (port->port_devid) {
855		msg->port.port_devid_len = port->port_devid->len;
856		memcpy(&msg->port.data[i], port->port_devid->data,
857		    msg->port.port_devid_len);
858		i += msg->port.port_devid_len;
859	}
860	if (port->target_devid) {
861		msg->port.target_devid_len = port->target_devid->len;
862		memcpy(&msg->port.data[i], port->target_devid->data,
863		    msg->port.target_devid_len);
864		i += msg->port.target_devid_len;
865	}
866	if (port->init_devid) {
867		msg->port.init_devid_len = port->init_devid->len;
868		memcpy(&msg->port.data[i], port->init_devid->data,
869		    msg->port.init_devid_len);
870		i += msg->port.init_devid_len;
871	}
872	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
873	    M_WAITOK);
874	free(msg, M_CTL);
875}
876
877void
878ctl_isc_announce_iid(struct ctl_port *port, int iid)
879{
880	struct ctl_softc *softc = port->ctl_softc;
881	union ctl_ha_msg *msg;
882	int i, l;
883
884	if (port->targ_port < softc->port_min ||
885	    port->targ_port >= softc->port_max ||
886	    softc->ha_link != CTL_HA_LINK_ONLINE)
887		return;
888	mtx_lock(&softc->ctl_lock);
889	i = sizeof(msg->iid);
890	l = 0;
891	if (port->wwpn_iid[iid].name)
892		l = strlen(port->wwpn_iid[iid].name) + 1;
893	i += l;
894	msg = malloc(i, M_CTL, M_NOWAIT);
895	if (msg == NULL) {
896		mtx_unlock(&softc->ctl_lock);
897		return;
898	}
899	bzero(&msg->iid, sizeof(msg->iid));
900	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
901	msg->hdr.nexus.targ_port = port->targ_port;
902	msg->hdr.nexus.initid = iid;
903	msg->iid.in_use = port->wwpn_iid[iid].in_use;
904	msg->iid.name_len = l;
905	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
906	if (port->wwpn_iid[iid].name)
907		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
908	mtx_unlock(&softc->ctl_lock);
909	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
910	free(msg, M_CTL);
911}
912
913void
914ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
915    uint8_t page, uint8_t subpage)
916{
917	struct ctl_softc *softc = lun->ctl_softc;
918	union ctl_ha_msg msg;
919	int i;
920
921	if (softc->ha_link != CTL_HA_LINK_ONLINE)
922		return;
923	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
924		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
925		    page && lun->mode_pages.index[i].subpage == subpage)
926			break;
927	}
928	if (i == CTL_NUM_MODE_PAGES)
929		return;
930	bzero(&msg.mode, sizeof(msg.mode));
931	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
932	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
933	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
934	msg.hdr.nexus.targ_lun = lun->lun;
935	msg.hdr.nexus.targ_mapped_lun = lun->lun;
936	msg.mode.page_code = page;
937	msg.mode.subpage = subpage;
938	msg.mode.page_len = lun->mode_pages.index[i].page_len;
939	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
940	    msg.mode.page_len);
941	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
942	    M_WAITOK);
943}
944
945static void
946ctl_isc_ha_link_up(struct ctl_softc *softc)
947{
948	struct ctl_port *port;
949	struct ctl_lun *lun;
950	union ctl_ha_msg msg;
951	int i;
952
953	/* Announce this node parameters to peer for validation. */
954	msg.login.msg_type = CTL_MSG_LOGIN;
955	msg.login.version = CTL_HA_VERSION;
956	msg.login.ha_mode = softc->ha_mode;
957	msg.login.ha_id = softc->ha_id;
958	msg.login.max_luns = CTL_MAX_LUNS;
959	msg.login.max_ports = CTL_MAX_PORTS;
960	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
961	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
962	    M_WAITOK);
963
964	STAILQ_FOREACH(port, &softc->port_list, links) {
965		ctl_isc_announce_port(port);
966		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
967			if (port->wwpn_iid[i].in_use)
968				ctl_isc_announce_iid(port, i);
969		}
970	}
971	STAILQ_FOREACH(lun, &softc->lun_list, links)
972		ctl_isc_announce_lun(lun);
973}
974
975static void
976ctl_isc_ha_link_down(struct ctl_softc *softc)
977{
978	struct ctl_port *port;
979	struct ctl_lun *lun;
980	union ctl_io *io;
981	int i;
982
983	mtx_lock(&softc->ctl_lock);
984	STAILQ_FOREACH(lun, &softc->lun_list, links) {
985		mtx_lock(&lun->lun_lock);
986		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
987			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
988			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
989		}
990		mtx_unlock(&lun->lun_lock);
991
992		mtx_unlock(&softc->ctl_lock);
993		io = ctl_alloc_io(softc->othersc_pool);
994		mtx_lock(&softc->ctl_lock);
995		ctl_zero_io(io);
996		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
997		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
998		ctl_enqueue_isc(io);
999	}
1000
1001	STAILQ_FOREACH(port, &softc->port_list, links) {
1002		if (port->targ_port >= softc->port_min &&
1003		    port->targ_port < softc->port_max)
1004			continue;
1005		port->status &= ~CTL_PORT_STATUS_ONLINE;
1006		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1007			port->wwpn_iid[i].in_use = 0;
1008			free(port->wwpn_iid[i].name, M_CTL);
1009			port->wwpn_iid[i].name = NULL;
1010		}
1011	}
1012	mtx_unlock(&softc->ctl_lock);
1013}
1014
1015static void
1016ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1017{
1018	struct ctl_lun *lun;
1019	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1020
1021	mtx_lock(&softc->ctl_lock);
1022	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1023	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1024		mtx_lock(&lun->lun_lock);
1025		mtx_unlock(&softc->ctl_lock);
1026		if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1027		    msg->ua.ua_set)
1028			memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1029		if (msg->ua.ua_all) {
1030			if (msg->ua.ua_set)
1031				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1032			else
1033				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1034		} else {
1035			if (msg->ua.ua_set)
1036				ctl_est_ua(lun, iid, msg->ua.ua_type);
1037			else
1038				ctl_clr_ua(lun, iid, msg->ua.ua_type);
1039		}
1040		mtx_unlock(&lun->lun_lock);
1041	} else
1042		mtx_unlock(&softc->ctl_lock);
1043}
1044
1045static void
1046ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1047{
1048	struct ctl_lun *lun;
1049	struct ctl_ha_msg_lun_pr_key pr_key;
1050	int i, k;
1051	ctl_lun_flags oflags;
1052	uint32_t targ_lun;
1053
1054	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1055	mtx_lock(&softc->ctl_lock);
1056	if ((targ_lun >= CTL_MAX_LUNS) ||
1057	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1058		mtx_unlock(&softc->ctl_lock);
1059		return;
1060	}
1061	mtx_lock(&lun->lun_lock);
1062	mtx_unlock(&softc->ctl_lock);
1063	if (lun->flags & CTL_LUN_DISABLED) {
1064		mtx_unlock(&lun->lun_lock);
1065		return;
1066	}
1067	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1068	if (msg->lun.lun_devid_len != i || (i > 0 &&
1069	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1070		mtx_unlock(&lun->lun_lock);
1071		printf("%s: Received conflicting HA LUN %d\n",
1072		    __func__, msg->hdr.nexus.targ_lun);
1073		return;
1074	} else {
1075		/* Record whether peer is primary. */
1076		oflags = lun->flags;
1077		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1078		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1079			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1080		else
1081			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1082		if (oflags != lun->flags)
1083			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1084
1085		/* If peer is primary and we are not -- use data */
1086		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1087		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1088			lun->pr_generation = msg->lun.pr_generation;
1089			lun->pr_res_idx = msg->lun.pr_res_idx;
1090			lun->pr_res_type = msg->lun.pr_res_type;
1091			lun->pr_key_count = msg->lun.pr_key_count;
1092			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1093				ctl_clr_prkey(lun, k);
1094			for (k = 0; k < msg->lun.pr_key_count; k++) {
1095				memcpy(&pr_key, &msg->lun.data[i],
1096				    sizeof(pr_key));
1097				ctl_alloc_prkey(lun, pr_key.pr_iid);
1098				ctl_set_prkey(lun, pr_key.pr_iid,
1099				    pr_key.pr_key);
1100				i += sizeof(pr_key);
1101			}
1102		}
1103
1104		mtx_unlock(&lun->lun_lock);
1105		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1106		    __func__, msg->hdr.nexus.targ_lun,
1107		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1108		    "primary" : "secondary"));
1109
1110		/* If we are primary but peer doesn't know -- notify */
1111		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1112		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1113			ctl_isc_announce_lun(lun);
1114	}
1115}
1116
1117static void
1118ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1119{
1120	struct ctl_port *port;
1121	struct ctl_lun *lun;
1122	int i, new;
1123
1124	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1125	if (port == NULL) {
1126		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1127		    msg->hdr.nexus.targ_port));
1128		new = 1;
1129		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1130		port->frontend = &ha_frontend;
1131		port->targ_port = msg->hdr.nexus.targ_port;
1132		port->fe_datamove = ctl_ha_datamove;
1133		port->fe_done = ctl_ha_done;
1134	} else if (port->frontend == &ha_frontend) {
1135		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1136		    msg->hdr.nexus.targ_port));
1137		new = 0;
1138	} else {
1139		printf("%s: Received conflicting HA port %d\n",
1140		    __func__, msg->hdr.nexus.targ_port);
1141		return;
1142	}
1143	port->port_type = msg->port.port_type;
1144	port->physical_port = msg->port.physical_port;
1145	port->virtual_port = msg->port.virtual_port;
1146	port->status = msg->port.status;
1147	i = 0;
1148	free(port->port_name, M_CTL);
1149	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1150	    M_CTL);
1151	i += msg->port.name_len;
1152	if (msg->port.lun_map_len != 0) {
1153		if (port->lun_map == NULL)
1154			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1155			    M_CTL, M_WAITOK);
1156		memcpy(port->lun_map, &msg->port.data[i],
1157		    sizeof(uint32_t) * CTL_MAX_LUNS);
1158		i += msg->port.lun_map_len;
1159	} else {
1160		free(port->lun_map, M_CTL);
1161		port->lun_map = NULL;
1162	}
1163	if (msg->port.port_devid_len != 0) {
1164		if (port->port_devid == NULL ||
1165		    port->port_devid->len != msg->port.port_devid_len) {
1166			free(port->port_devid, M_CTL);
1167			port->port_devid = malloc(sizeof(struct ctl_devid) +
1168			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1169		}
1170		memcpy(port->port_devid->data, &msg->port.data[i],
1171		    msg->port.port_devid_len);
1172		port->port_devid->len = msg->port.port_devid_len;
1173		i += msg->port.port_devid_len;
1174	} else {
1175		free(port->port_devid, M_CTL);
1176		port->port_devid = NULL;
1177	}
1178	if (msg->port.target_devid_len != 0) {
1179		if (port->target_devid == NULL ||
1180		    port->target_devid->len != msg->port.target_devid_len) {
1181			free(port->target_devid, M_CTL);
1182			port->target_devid = malloc(sizeof(struct ctl_devid) +
1183			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1184		}
1185		memcpy(port->target_devid->data, &msg->port.data[i],
1186		    msg->port.target_devid_len);
1187		port->target_devid->len = msg->port.target_devid_len;
1188		i += msg->port.target_devid_len;
1189	} else {
1190		free(port->target_devid, M_CTL);
1191		port->target_devid = NULL;
1192	}
1193	if (msg->port.init_devid_len != 0) {
1194		if (port->init_devid == NULL ||
1195		    port->init_devid->len != msg->port.init_devid_len) {
1196			free(port->init_devid, M_CTL);
1197			port->init_devid = malloc(sizeof(struct ctl_devid) +
1198			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1199		}
1200		memcpy(port->init_devid->data, &msg->port.data[i],
1201		    msg->port.init_devid_len);
1202		port->init_devid->len = msg->port.init_devid_len;
1203		i += msg->port.init_devid_len;
1204	} else {
1205		free(port->init_devid, M_CTL);
1206		port->init_devid = NULL;
1207	}
1208	if (new) {
1209		if (ctl_port_register(port) != 0) {
1210			printf("%s: ctl_port_register() failed with error\n",
1211			    __func__);
1212		}
1213	}
1214	mtx_lock(&softc->ctl_lock);
1215	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1216		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1217			continue;
1218		mtx_lock(&lun->lun_lock);
1219		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1220		mtx_unlock(&lun->lun_lock);
1221	}
1222	mtx_unlock(&softc->ctl_lock);
1223}
1224
1225static void
1226ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1227{
1228	struct ctl_port *port;
1229	int iid;
1230
1231	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1232	if (port == NULL) {
1233		printf("%s: Received IID for unknown port %d\n",
1234		    __func__, msg->hdr.nexus.targ_port);
1235		return;
1236	}
1237	iid = msg->hdr.nexus.initid;
1238	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1239	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1240	free(port->wwpn_iid[iid].name, M_CTL);
1241	if (msg->iid.name_len) {
1242		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1243		    msg->iid.name_len, M_CTL);
1244	} else
1245		port->wwpn_iid[iid].name = NULL;
1246}
1247
1248static void
1249ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1250{
1251
1252	if (msg->login.version != CTL_HA_VERSION) {
1253		printf("CTL HA peers have different versions %d != %d\n",
1254		    msg->login.version, CTL_HA_VERSION);
1255		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1256		return;
1257	}
1258	if (msg->login.ha_mode != softc->ha_mode) {
1259		printf("CTL HA peers have different ha_mode %d != %d\n",
1260		    msg->login.ha_mode, softc->ha_mode);
1261		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1262		return;
1263	}
1264	if (msg->login.ha_id == softc->ha_id) {
1265		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1266		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1267		return;
1268	}
1269	if (msg->login.max_luns != CTL_MAX_LUNS ||
1270	    msg->login.max_ports != CTL_MAX_PORTS ||
1271	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1272		printf("CTL HA peers have different limits\n");
1273		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1274		return;
1275	}
1276}
1277
1278static void
1279ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1280{
1281	struct ctl_lun *lun;
1282	int i;
1283	uint32_t initidx, targ_lun;
1284
1285	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1286	mtx_lock(&softc->ctl_lock);
1287	if ((targ_lun >= CTL_MAX_LUNS) ||
1288	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1289		mtx_unlock(&softc->ctl_lock);
1290		return;
1291	}
1292	mtx_lock(&lun->lun_lock);
1293	mtx_unlock(&softc->ctl_lock);
1294	if (lun->flags & CTL_LUN_DISABLED) {
1295		mtx_unlock(&lun->lun_lock);
1296		return;
1297	}
1298	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1299		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1300		    msg->mode.page_code &&
1301		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1302			break;
1303	}
1304	if (i == CTL_NUM_MODE_PAGES) {
1305		mtx_unlock(&lun->lun_lock);
1306		return;
1307	}
1308	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1309	    lun->mode_pages.index[i].page_len);
1310	initidx = ctl_get_initindex(&msg->hdr.nexus);
1311	if (initidx != -1)
1312		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1313	mtx_unlock(&lun->lun_lock);
1314}
1315
1316/*
1317 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1318 * subsystem come in here.
1319 */
1320static void
1321ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1322{
1323	struct ctl_softc *softc = control_softc;
1324	union ctl_io *io;
1325	struct ctl_prio *presio;
1326	ctl_ha_status isc_status;
1327
1328	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1329	if (event == CTL_HA_EVT_MSG_RECV) {
1330		union ctl_ha_msg *msg, msgbuf;
1331
1332		if (param > sizeof(msgbuf))
1333			msg = malloc(param, M_CTL, M_WAITOK);
1334		else
1335			msg = &msgbuf;
1336		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1337		    M_WAITOK);
1338		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1339			printf("%s: Error receiving message: %d\n",
1340			    __func__, isc_status);
1341			if (msg != &msgbuf)
1342				free(msg, M_CTL);
1343			return;
1344		}
1345
1346		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1347		switch (msg->hdr.msg_type) {
1348		case CTL_MSG_SERIALIZE:
1349			io = ctl_alloc_io(softc->othersc_pool);
1350			ctl_zero_io(io);
1351			// populate ctsio from msg
1352			io->io_hdr.io_type = CTL_IO_SCSI;
1353			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1354			io->io_hdr.original_sc = msg->hdr.original_sc;
1355			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1356					    CTL_FLAG_IO_ACTIVE;
1357			/*
1358			 * If we're in serialization-only mode, we don't
1359			 * want to go through full done processing.  Thus
1360			 * the COPY flag.
1361			 *
1362			 * XXX KDM add another flag that is more specific.
1363			 */
1364			if (softc->ha_mode != CTL_HA_MODE_XFER)
1365				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1366			io->io_hdr.nexus = msg->hdr.nexus;
1367#if 0
1368			printf("port %u, iid %u, lun %u\n",
1369			       io->io_hdr.nexus.targ_port,
1370			       io->io_hdr.nexus.initid,
1371			       io->io_hdr.nexus.targ_lun);
1372#endif
1373			io->scsiio.tag_num = msg->scsi.tag_num;
1374			io->scsiio.tag_type = msg->scsi.tag_type;
1375#ifdef CTL_TIME_IO
1376			io->io_hdr.start_time = time_uptime;
1377			getbinuptime(&io->io_hdr.start_bt);
1378#endif /* CTL_TIME_IO */
1379			io->scsiio.cdb_len = msg->scsi.cdb_len;
1380			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1381			       CTL_MAX_CDBLEN);
1382			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1383				const struct ctl_cmd_entry *entry;
1384
1385				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1386				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1387				io->io_hdr.flags |=
1388					entry->flags & CTL_FLAG_DATA_MASK;
1389			}
1390			ctl_enqueue_isc(io);
1391			break;
1392
1393		/* Performed on the Originating SC, XFER mode only */
1394		case CTL_MSG_DATAMOVE: {
1395			struct ctl_sg_entry *sgl;
1396			int i, j;
1397
1398			io = msg->hdr.original_sc;
1399			if (io == NULL) {
1400				printf("%s: original_sc == NULL!\n", __func__);
1401				/* XXX KDM do something here */
1402				break;
1403			}
1404			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1405			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1406			/*
1407			 * Keep track of this, we need to send it back over
1408			 * when the datamove is complete.
1409			 */
1410			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1411			if (msg->hdr.status == CTL_SUCCESS)
1412				io->io_hdr.status = msg->hdr.status;
1413
1414			if (msg->dt.sg_sequence == 0) {
1415#ifdef CTL_TIME_IO
1416				getbinuptime(&io->io_hdr.dma_start_bt);
1417#endif
1418				i = msg->dt.kern_sg_entries +
1419				    msg->dt.kern_data_len /
1420				    CTL_HA_DATAMOVE_SEGMENT + 1;
1421				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1422				    M_WAITOK | M_ZERO);
1423				io->io_hdr.remote_sglist = sgl;
1424				io->io_hdr.local_sglist =
1425				    &sgl[msg->dt.kern_sg_entries];
1426
1427				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1428
1429				io->scsiio.kern_sg_entries =
1430					msg->dt.kern_sg_entries;
1431				io->scsiio.rem_sg_entries =
1432					msg->dt.kern_sg_entries;
1433				io->scsiio.kern_data_len =
1434					msg->dt.kern_data_len;
1435				io->scsiio.kern_total_len =
1436					msg->dt.kern_total_len;
1437				io->scsiio.kern_data_resid =
1438					msg->dt.kern_data_resid;
1439				io->scsiio.kern_rel_offset =
1440					msg->dt.kern_rel_offset;
1441				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1442				io->io_hdr.flags |= msg->dt.flags &
1443				    CTL_FLAG_BUS_ADDR;
1444			} else
1445				sgl = (struct ctl_sg_entry *)
1446					io->scsiio.kern_data_ptr;
1447
1448			for (i = msg->dt.sent_sg_entries, j = 0;
1449			     i < (msg->dt.sent_sg_entries +
1450			     msg->dt.cur_sg_entries); i++, j++) {
1451				sgl[i].addr = msg->dt.sg_list[j].addr;
1452				sgl[i].len = msg->dt.sg_list[j].len;
1453
1454#if 0
1455				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1456				    __func__, sgl[i].addr, sgl[i].len, j, i);
1457#endif
1458			}
1459
1460			/*
1461			 * If this is the last piece of the I/O, we've got
1462			 * the full S/G list.  Queue processing in the thread.
1463			 * Otherwise wait for the next piece.
1464			 */
1465			if (msg->dt.sg_last != 0)
1466				ctl_enqueue_isc(io);
1467			break;
1468		}
1469		/* Performed on the Serializing (primary) SC, XFER mode only */
1470		case CTL_MSG_DATAMOVE_DONE: {
1471			if (msg->hdr.serializing_sc == NULL) {
1472				printf("%s: serializing_sc == NULL!\n",
1473				       __func__);
1474				/* XXX KDM now what? */
1475				break;
1476			}
1477			/*
1478			 * We grab the sense information here in case
1479			 * there was a failure, so we can return status
1480			 * back to the initiator.
1481			 */
1482			io = msg->hdr.serializing_sc;
1483			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1484			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1485			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1486			io->io_hdr.port_status = msg->scsi.fetd_status;
1487			io->scsiio.residual = msg->scsi.residual;
1488			if (msg->hdr.status != CTL_STATUS_NONE) {
1489				io->io_hdr.status = msg->hdr.status;
1490				io->scsiio.scsi_status = msg->scsi.scsi_status;
1491				io->scsiio.sense_len = msg->scsi.sense_len;
1492				io->scsiio.sense_residual =msg->scsi.sense_residual;
1493				memcpy(&io->scsiio.sense_data,
1494				    &msg->scsi.sense_data,
1495				    msg->scsi.sense_len);
1496				if (msg->hdr.status == CTL_SUCCESS)
1497					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1498			}
1499			ctl_enqueue_isc(io);
1500			break;
1501		}
1502
1503		/* Preformed on Originating SC, SER_ONLY mode */
1504		case CTL_MSG_R2R:
1505			io = msg->hdr.original_sc;
1506			if (io == NULL) {
1507				printf("%s: original_sc == NULL!\n",
1508				    __func__);
1509				break;
1510			}
1511			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1512			io->io_hdr.msg_type = CTL_MSG_R2R;
1513			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1514			ctl_enqueue_isc(io);
1515			break;
1516
1517		/*
1518		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1519		 * mode.
1520		 * Performed on the Originating (i.e. secondary) SC in XFER
1521		 * mode
1522		 */
1523		case CTL_MSG_FINISH_IO:
1524			if (softc->ha_mode == CTL_HA_MODE_XFER)
1525				ctl_isc_handler_finish_xfer(softc, msg);
1526			else
1527				ctl_isc_handler_finish_ser_only(softc, msg);
1528			break;
1529
1530		/* Preformed on Originating SC */
1531		case CTL_MSG_BAD_JUJU:
1532			io = msg->hdr.original_sc;
1533			if (io == NULL) {
1534				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1535				       __func__);
1536				break;
1537			}
1538			ctl_copy_sense_data(msg, io);
1539			/*
1540			 * IO should have already been cleaned up on other
1541			 * SC so clear this flag so we won't send a message
1542			 * back to finish the IO there.
1543			 */
1544			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1545			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1546
1547			/* io = msg->hdr.serializing_sc; */
1548			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1549			ctl_enqueue_isc(io);
1550			break;
1551
1552		/* Handle resets sent from the other side */
1553		case CTL_MSG_MANAGE_TASKS: {
1554			struct ctl_taskio *taskio;
1555			taskio = (struct ctl_taskio *)ctl_alloc_io(
1556			    softc->othersc_pool);
1557			ctl_zero_io((union ctl_io *)taskio);
1558			taskio->io_hdr.io_type = CTL_IO_TASK;
1559			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1560			taskio->io_hdr.nexus = msg->hdr.nexus;
1561			taskio->task_action = msg->task.task_action;
1562			taskio->tag_num = msg->task.tag_num;
1563			taskio->tag_type = msg->task.tag_type;
1564#ifdef CTL_TIME_IO
1565			taskio->io_hdr.start_time = time_uptime;
1566			getbinuptime(&taskio->io_hdr.start_bt);
1567#endif /* CTL_TIME_IO */
1568			ctl_run_task((union ctl_io *)taskio);
1569			break;
1570		}
1571		/* Persistent Reserve action which needs attention */
1572		case CTL_MSG_PERS_ACTION:
1573			presio = (struct ctl_prio *)ctl_alloc_io(
1574			    softc->othersc_pool);
1575			ctl_zero_io((union ctl_io *)presio);
1576			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1577			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1578			presio->io_hdr.nexus = msg->hdr.nexus;
1579			presio->pr_msg = msg->pr;
1580			ctl_enqueue_isc((union ctl_io *)presio);
1581			break;
1582		case CTL_MSG_UA:
1583			ctl_isc_ua(softc, msg, param);
1584			break;
1585		case CTL_MSG_PORT_SYNC:
1586			ctl_isc_port_sync(softc, msg, param);
1587			break;
1588		case CTL_MSG_LUN_SYNC:
1589			ctl_isc_lun_sync(softc, msg, param);
1590			break;
1591		case CTL_MSG_IID_SYNC:
1592			ctl_isc_iid_sync(softc, msg, param);
1593			break;
1594		case CTL_MSG_LOGIN:
1595			ctl_isc_login(softc, msg, param);
1596			break;
1597		case CTL_MSG_MODE_SYNC:
1598			ctl_isc_mode_sync(softc, msg, param);
1599			break;
1600		default:
1601			printf("Received HA message of unknown type %d\n",
1602			    msg->hdr.msg_type);
1603			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1604			break;
1605		}
1606		if (msg != &msgbuf)
1607			free(msg, M_CTL);
1608	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1609		printf("CTL: HA link status changed from %d to %d\n",
1610		    softc->ha_link, param);
1611		if (param == softc->ha_link)
1612			return;
1613		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1614			softc->ha_link = param;
1615			ctl_isc_ha_link_down(softc);
1616		} else {
1617			softc->ha_link = param;
1618			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1619				ctl_isc_ha_link_up(softc);
1620		}
1621		return;
1622	} else {
1623		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1624		return;
1625	}
1626}
1627
1628static void
1629ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1630{
1631
1632	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1633	    src->scsi.sense_len);
1634	dest->scsiio.scsi_status = src->scsi.scsi_status;
1635	dest->scsiio.sense_len = src->scsi.sense_len;
1636	dest->io_hdr.status = src->hdr.status;
1637}
1638
1639static void
1640ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1641{
1642
1643	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1644	    src->scsiio.sense_len);
1645	dest->scsi.scsi_status = src->scsiio.scsi_status;
1646	dest->scsi.sense_len = src->scsiio.sense_len;
1647	dest->hdr.status = src->io_hdr.status;
1648}
1649
1650void
1651ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1652{
1653	struct ctl_softc *softc = lun->ctl_softc;
1654	ctl_ua_type *pu;
1655
1656	if (initidx < softc->init_min || initidx >= softc->init_max)
1657		return;
1658	mtx_assert(&lun->lun_lock, MA_OWNED);
1659	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1660	if (pu == NULL)
1661		return;
1662	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1663}
1664
1665void
1666ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1667{
1668	int i;
1669
1670	mtx_assert(&lun->lun_lock, MA_OWNED);
1671	if (lun->pending_ua[port] == NULL)
1672		return;
1673	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1674		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1675			continue;
1676		lun->pending_ua[port][i] |= ua;
1677	}
1678}
1679
1680void
1681ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1682{
1683	struct ctl_softc *softc = lun->ctl_softc;
1684	int i;
1685
1686	mtx_assert(&lun->lun_lock, MA_OWNED);
1687	for (i = softc->port_min; i < softc->port_max; i++)
1688		ctl_est_ua_port(lun, i, except, ua);
1689}
1690
1691void
1692ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1693{
1694	struct ctl_softc *softc = lun->ctl_softc;
1695	ctl_ua_type *pu;
1696
1697	if (initidx < softc->init_min || initidx >= softc->init_max)
1698		return;
1699	mtx_assert(&lun->lun_lock, MA_OWNED);
1700	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1701	if (pu == NULL)
1702		return;
1703	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1704}
1705
1706void
1707ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1708{
1709	struct ctl_softc *softc = lun->ctl_softc;
1710	int i, j;
1711
1712	mtx_assert(&lun->lun_lock, MA_OWNED);
1713	for (i = softc->port_min; i < softc->port_max; i++) {
1714		if (lun->pending_ua[i] == NULL)
1715			continue;
1716		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1717			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1718				continue;
1719			lun->pending_ua[i][j] &= ~ua;
1720		}
1721	}
1722}
1723
1724void
1725ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1726    ctl_ua_type ua_type)
1727{
1728	struct ctl_lun *lun;
1729
1730	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1731	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1732		mtx_lock(&lun->lun_lock);
1733		ctl_clr_ua(lun, initidx, ua_type);
1734		mtx_unlock(&lun->lun_lock);
1735	}
1736}
1737
1738static int
1739ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1740{
1741	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1742	struct ctl_lun *lun;
1743	struct ctl_lun_req ireq;
1744	int error, value;
1745
1746	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1747	error = sysctl_handle_int(oidp, &value, 0, req);
1748	if ((error != 0) || (req->newptr == NULL))
1749		return (error);
1750
1751	mtx_lock(&softc->ctl_lock);
1752	if (value == 0)
1753		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1754	else
1755		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1756	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1757		mtx_unlock(&softc->ctl_lock);
1758		bzero(&ireq, sizeof(ireq));
1759		ireq.reqtype = CTL_LUNREQ_MODIFY;
1760		ireq.reqdata.modify.lun_id = lun->lun;
1761		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1762		    curthread);
1763		if (ireq.status != CTL_LUN_OK) {
1764			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1765			    __func__, ireq.status, ireq.error_str);
1766		}
1767		mtx_lock(&softc->ctl_lock);
1768	}
1769	mtx_unlock(&softc->ctl_lock);
1770	return (0);
1771}
1772
1773static int
1774ctl_init(void)
1775{
1776	struct ctl_softc *softc;
1777	void *other_pool;
1778	int i, error;
1779
1780	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1781			       M_WAITOK | M_ZERO);
1782
1783	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1784			      "cam/ctl");
1785	softc->dev->si_drv1 = softc;
1786
1787	sysctl_ctx_init(&softc->sysctl_ctx);
1788	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1789		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1790		CTLFLAG_RD, 0, "CAM Target Layer");
1791
1792	if (softc->sysctl_tree == NULL) {
1793		printf("%s: unable to allocate sysctl tree\n", __func__);
1794		destroy_dev(softc->dev);
1795		free(control_softc, M_DEVBUF);
1796		control_softc = NULL;
1797		return (ENOMEM);
1798	}
1799
1800	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1801	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1802	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1803	softc->flags = 0;
1804
1805	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1806	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1807	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1808
1809	/*
1810	 * In Copan's HA scheme, the "master" and "slave" roles are
1811	 * figured out through the slot the controller is in.  Although it
1812	 * is an active/active system, someone has to be in charge.
1813	 */
1814	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1815	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1816	    "HA head ID (0 - no HA)");
1817	if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1818		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1819		softc->is_single = 1;
1820		softc->port_cnt = CTL_MAX_PORTS;
1821		softc->port_min = 0;
1822	} else {
1823		softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1824		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1825	}
1826	softc->port_max = softc->port_min + softc->port_cnt;
1827	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1828	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1829
1830	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1831	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1832	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1833
1834	STAILQ_INIT(&softc->lun_list);
1835	STAILQ_INIT(&softc->pending_lun_queue);
1836	STAILQ_INIT(&softc->fe_list);
1837	STAILQ_INIT(&softc->port_list);
1838	STAILQ_INIT(&softc->be_list);
1839	ctl_tpc_init(softc);
1840
1841	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1842	                    &other_pool) != 0)
1843	{
1844		printf("ctl: can't allocate %d entry other SC pool, "
1845		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1846		return (ENOMEM);
1847	}
1848	softc->othersc_pool = other_pool;
1849
1850	if (worker_threads <= 0)
1851		worker_threads = max(1, mp_ncpus / 4);
1852	if (worker_threads > CTL_MAX_THREADS)
1853		worker_threads = CTL_MAX_THREADS;
1854
1855	for (i = 0; i < worker_threads; i++) {
1856		struct ctl_thread *thr = &softc->threads[i];
1857
1858		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1859		thr->ctl_softc = softc;
1860		STAILQ_INIT(&thr->incoming_queue);
1861		STAILQ_INIT(&thr->rtr_queue);
1862		STAILQ_INIT(&thr->done_queue);
1863		STAILQ_INIT(&thr->isc_queue);
1864
1865		error = kproc_kthread_add(ctl_work_thread, thr,
1866		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1867		if (error != 0) {
1868			printf("error creating CTL work thread!\n");
1869			ctl_pool_free(other_pool);
1870			return (error);
1871		}
1872	}
1873	error = kproc_kthread_add(ctl_lun_thread, softc,
1874	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1875	if (error != 0) {
1876		printf("error creating CTL lun thread!\n");
1877		ctl_pool_free(other_pool);
1878		return (error);
1879	}
1880	error = kproc_kthread_add(ctl_thresh_thread, softc,
1881	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1882	if (error != 0) {
1883		printf("error creating CTL threshold thread!\n");
1884		ctl_pool_free(other_pool);
1885		return (error);
1886	}
1887
1888	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1889	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1890	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1891
1892	if (softc->is_single == 0) {
1893		ctl_frontend_register(&ha_frontend);
1894		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1895			printf("ctl_init: ctl_ha_msg_init failed.\n");
1896			softc->is_single = 1;
1897		} else
1898		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1899		    != CTL_HA_STATUS_SUCCESS) {
1900			printf("ctl_init: ctl_ha_msg_register failed.\n");
1901			softc->is_single = 1;
1902		}
1903	}
1904	return (0);
1905}
1906
1907void
1908ctl_shutdown(void)
1909{
1910	struct ctl_softc *softc = control_softc;
1911	struct ctl_lun *lun, *next_lun;
1912
1913	if (softc->is_single == 0) {
1914		ctl_ha_msg_shutdown(softc);
1915		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1916		    != CTL_HA_STATUS_SUCCESS)
1917			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1918		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1919			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1920		ctl_frontend_deregister(&ha_frontend);
1921	}
1922
1923	mtx_lock(&softc->ctl_lock);
1924
1925	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1926		ctl_free_lun(lun);
1927
1928	mtx_unlock(&softc->ctl_lock);
1929
1930#if 0
1931	ctl_shutdown_thread(softc->work_thread);
1932	mtx_destroy(&softc->queue_lock);
1933#endif
1934
1935	ctl_tpc_shutdown(softc);
1936	uma_zdestroy(softc->io_zone);
1937	mtx_destroy(&softc->ctl_lock);
1938
1939	destroy_dev(softc->dev);
1940
1941	sysctl_ctx_free(&softc->sysctl_ctx);
1942
1943	free(control_softc, M_DEVBUF);
1944	control_softc = NULL;
1945}
1946
1947static int
1948ctl_module_event_handler(module_t mod, int what, void *arg)
1949{
1950
1951	switch (what) {
1952	case MOD_LOAD:
1953		return (ctl_init());
1954	case MOD_UNLOAD:
1955		return (EBUSY);
1956	default:
1957		return (EOPNOTSUPP);
1958	}
1959}
1960
1961/*
1962 * XXX KDM should we do some access checks here?  Bump a reference count to
1963 * prevent a CTL module from being unloaded while someone has it open?
1964 */
1965static int
1966ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1967{
1968	return (0);
1969}
1970
1971static int
1972ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1973{
1974	return (0);
1975}
1976
1977/*
1978 * Remove an initiator by port number and initiator ID.
1979 * Returns 0 for success, -1 for failure.
1980 */
1981int
1982ctl_remove_initiator(struct ctl_port *port, int iid)
1983{
1984	struct ctl_softc *softc = port->ctl_softc;
1985
1986	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1987
1988	if (iid > CTL_MAX_INIT_PER_PORT) {
1989		printf("%s: initiator ID %u > maximun %u!\n",
1990		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1991		return (-1);
1992	}
1993
1994	mtx_lock(&softc->ctl_lock);
1995	port->wwpn_iid[iid].in_use--;
1996	port->wwpn_iid[iid].last_use = time_uptime;
1997	mtx_unlock(&softc->ctl_lock);
1998	ctl_isc_announce_iid(port, iid);
1999
2000	return (0);
2001}
2002
2003/*
2004 * Add an initiator to the initiator map.
2005 * Returns iid for success, < 0 for failure.
2006 */
2007int
2008ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2009{
2010	struct ctl_softc *softc = port->ctl_softc;
2011	time_t best_time;
2012	int i, best;
2013
2014	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2015
2016	if (iid >= CTL_MAX_INIT_PER_PORT) {
2017		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2018		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2019		free(name, M_CTL);
2020		return (-1);
2021	}
2022
2023	mtx_lock(&softc->ctl_lock);
2024
2025	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2026		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2027			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2028				iid = i;
2029				break;
2030			}
2031			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2032			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2033				iid = i;
2034				break;
2035			}
2036		}
2037	}
2038
2039	if (iid < 0) {
2040		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2041			if (port->wwpn_iid[i].in_use == 0 &&
2042			    port->wwpn_iid[i].wwpn == 0 &&
2043			    port->wwpn_iid[i].name == NULL) {
2044				iid = i;
2045				break;
2046			}
2047		}
2048	}
2049
2050	if (iid < 0) {
2051		best = -1;
2052		best_time = INT32_MAX;
2053		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2054			if (port->wwpn_iid[i].in_use == 0) {
2055				if (port->wwpn_iid[i].last_use < best_time) {
2056					best = i;
2057					best_time = port->wwpn_iid[i].last_use;
2058				}
2059			}
2060		}
2061		iid = best;
2062	}
2063
2064	if (iid < 0) {
2065		mtx_unlock(&softc->ctl_lock);
2066		free(name, M_CTL);
2067		return (-2);
2068	}
2069
2070	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2071		/*
2072		 * This is not an error yet.
2073		 */
2074		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2075#if 0
2076			printf("%s: port %d iid %u WWPN %#jx arrived"
2077			    " again\n", __func__, port->targ_port,
2078			    iid, (uintmax_t)wwpn);
2079#endif
2080			goto take;
2081		}
2082		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2083		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2084#if 0
2085			printf("%s: port %d iid %u name '%s' arrived"
2086			    " again\n", __func__, port->targ_port,
2087			    iid, name);
2088#endif
2089			goto take;
2090		}
2091
2092		/*
2093		 * This is an error, but what do we do about it?  The
2094		 * driver is telling us we have a new WWPN for this
2095		 * initiator ID, so we pretty much need to use it.
2096		 */
2097		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2098		    " but WWPN %#jx '%s' is still at that address\n",
2099		    __func__, port->targ_port, iid, wwpn, name,
2100		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2101		    port->wwpn_iid[iid].name);
2102
2103		/*
2104		 * XXX KDM clear have_ca and ua_pending on each LUN for
2105		 * this initiator.
2106		 */
2107	}
2108take:
2109	free(port->wwpn_iid[iid].name, M_CTL);
2110	port->wwpn_iid[iid].name = name;
2111	port->wwpn_iid[iid].wwpn = wwpn;
2112	port->wwpn_iid[iid].in_use++;
2113	mtx_unlock(&softc->ctl_lock);
2114	ctl_isc_announce_iid(port, iid);
2115
2116	return (iid);
2117}
2118
2119static int
2120ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2121{
2122	int len;
2123
2124	switch (port->port_type) {
2125	case CTL_PORT_FC:
2126	{
2127		struct scsi_transportid_fcp *id =
2128		    (struct scsi_transportid_fcp *)buf;
2129		if (port->wwpn_iid[iid].wwpn == 0)
2130			return (0);
2131		memset(id, 0, sizeof(*id));
2132		id->format_protocol = SCSI_PROTO_FC;
2133		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2134		return (sizeof(*id));
2135	}
2136	case CTL_PORT_ISCSI:
2137	{
2138		struct scsi_transportid_iscsi_port *id =
2139		    (struct scsi_transportid_iscsi_port *)buf;
2140		if (port->wwpn_iid[iid].name == NULL)
2141			return (0);
2142		memset(id, 0, 256);
2143		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2144		    SCSI_PROTO_ISCSI;
2145		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2146		len = roundup2(min(len, 252), 4);
2147		scsi_ulto2b(len, id->additional_length);
2148		return (sizeof(*id) + len);
2149	}
2150	case CTL_PORT_SAS:
2151	{
2152		struct scsi_transportid_sas *id =
2153		    (struct scsi_transportid_sas *)buf;
2154		if (port->wwpn_iid[iid].wwpn == 0)
2155			return (0);
2156		memset(id, 0, sizeof(*id));
2157		id->format_protocol = SCSI_PROTO_SAS;
2158		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2159		return (sizeof(*id));
2160	}
2161	default:
2162	{
2163		struct scsi_transportid_spi *id =
2164		    (struct scsi_transportid_spi *)buf;
2165		memset(id, 0, sizeof(*id));
2166		id->format_protocol = SCSI_PROTO_SPI;
2167		scsi_ulto2b(iid, id->scsi_addr);
2168		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2169		return (sizeof(*id));
2170	}
2171	}
2172}
2173
2174/*
2175 * Serialize a command that went down the "wrong" side, and so was sent to
2176 * this controller for execution.  The logic is a little different than the
2177 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2178 * sent back to the other side, but in the success case, we execute the
2179 * command on this side (XFER mode) or tell the other side to execute it
2180 * (SER_ONLY mode).
2181 */
2182static int
2183ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2184{
2185	struct ctl_softc *softc = control_softc;
2186	union ctl_ha_msg msg_info;
2187	struct ctl_port *port;
2188	struct ctl_lun *lun;
2189	const struct ctl_cmd_entry *entry;
2190	int retval = 0;
2191	uint32_t targ_lun;
2192
2193	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2194	mtx_lock(&softc->ctl_lock);
2195
2196	/* Make sure that we know about this port. */
2197	port = ctl_io_port(&ctsio->io_hdr);
2198	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2199		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2200					 /*retry_count*/ 1);
2201		goto badjuju;
2202	}
2203
2204	/* Make sure that we know about this LUN. */
2205	if ((targ_lun < CTL_MAX_LUNS) &&
2206	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2207		mtx_lock(&lun->lun_lock);
2208		mtx_unlock(&softc->ctl_lock);
2209		/*
2210		 * If the LUN is invalid, pretend that it doesn't exist.
2211		 * It will go away as soon as all pending I/O has been
2212		 * completed.
2213		 */
2214		if (lun->flags & CTL_LUN_DISABLED) {
2215			mtx_unlock(&lun->lun_lock);
2216			lun = NULL;
2217		}
2218	} else {
2219		mtx_unlock(&softc->ctl_lock);
2220		lun = NULL;
2221	}
2222	if (lun == NULL) {
2223		/*
2224		 * The other node would not send this request to us unless
2225		 * received announce that we are primary node for this LUN.
2226		 * If this LUN does not exist now, it is probably result of
2227		 * a race, so respond to initiator in the most opaque way.
2228		 */
2229		ctl_set_busy(ctsio);
2230		goto badjuju;
2231	}
2232
2233	entry = ctl_get_cmd_entry(ctsio, NULL);
2234	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2235		mtx_unlock(&lun->lun_lock);
2236		goto badjuju;
2237	}
2238
2239	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2240	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2241
2242	/*
2243	 * Every I/O goes into the OOA queue for a
2244	 * particular LUN, and stays there until completion.
2245	 */
2246#ifdef CTL_TIME_IO
2247	if (TAILQ_EMPTY(&lun->ooa_queue))
2248		lun->idle_time += getsbinuptime() - lun->last_busy;
2249#endif
2250	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2251
2252	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2253		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2254		 ooa_links))) {
2255	case CTL_ACTION_BLOCK:
2256		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2257		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2258				  blocked_links);
2259		mtx_unlock(&lun->lun_lock);
2260		break;
2261	case CTL_ACTION_PASS:
2262	case CTL_ACTION_SKIP:
2263		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2264			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2265			ctl_enqueue_rtr((union ctl_io *)ctsio);
2266			mtx_unlock(&lun->lun_lock);
2267		} else {
2268			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2269			mtx_unlock(&lun->lun_lock);
2270
2271			/* send msg back to other side */
2272			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2273			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2274			msg_info.hdr.msg_type = CTL_MSG_R2R;
2275			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2276			    sizeof(msg_info.hdr), M_WAITOK);
2277		}
2278		break;
2279	case CTL_ACTION_OVERLAP:
2280		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2281		mtx_unlock(&lun->lun_lock);
2282		ctl_set_overlapped_cmd(ctsio);
2283		goto badjuju;
2284	case CTL_ACTION_OVERLAP_TAG:
2285		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2286		mtx_unlock(&lun->lun_lock);
2287		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2288		goto badjuju;
2289	case CTL_ACTION_ERROR:
2290	default:
2291		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2292		mtx_unlock(&lun->lun_lock);
2293
2294		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2295					 /*retry_count*/ 0);
2296badjuju:
2297		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2298		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2299		msg_info.hdr.serializing_sc = NULL;
2300		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2301		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2302		    sizeof(msg_info.scsi), M_WAITOK);
2303		retval = 1;
2304		break;
2305	}
2306	return (retval);
2307}
2308
2309/*
2310 * Returns 0 for success, errno for failure.
2311 */
2312static void
2313ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2314		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2315{
2316	union ctl_io *io;
2317
2318	mtx_lock(&lun->lun_lock);
2319	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2320	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2321	     ooa_links)) {
2322		struct ctl_ooa_entry *entry;
2323
2324		/*
2325		 * If we've got more than we can fit, just count the
2326		 * remaining entries.
2327		 */
2328		if (*cur_fill_num >= ooa_hdr->alloc_num)
2329			continue;
2330
2331		entry = &kern_entries[*cur_fill_num];
2332
2333		entry->tag_num = io->scsiio.tag_num;
2334		entry->lun_num = lun->lun;
2335#ifdef CTL_TIME_IO
2336		entry->start_bt = io->io_hdr.start_bt;
2337#endif
2338		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2339		entry->cdb_len = io->scsiio.cdb_len;
2340		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2341			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2342
2343		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2344			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2345
2346		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2347			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2348
2349		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2350			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2351
2352		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2353			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2354	}
2355	mtx_unlock(&lun->lun_lock);
2356}
2357
2358static void *
2359ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2360		 size_t error_str_len)
2361{
2362	void *kptr;
2363
2364	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2365
2366	if (copyin(user_addr, kptr, len) != 0) {
2367		snprintf(error_str, error_str_len, "Error copying %d bytes "
2368			 "from user address %p to kernel address %p", len,
2369			 user_addr, kptr);
2370		free(kptr, M_CTL);
2371		return (NULL);
2372	}
2373
2374	return (kptr);
2375}
2376
2377static void
2378ctl_free_args(int num_args, struct ctl_be_arg *args)
2379{
2380	int i;
2381
2382	if (args == NULL)
2383		return;
2384
2385	for (i = 0; i < num_args; i++) {
2386		free(args[i].kname, M_CTL);
2387		free(args[i].kvalue, M_CTL);
2388	}
2389
2390	free(args, M_CTL);
2391}
2392
2393static struct ctl_be_arg *
2394ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2395		char *error_str, size_t error_str_len)
2396{
2397	struct ctl_be_arg *args;
2398	int i;
2399
2400	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2401				error_str, error_str_len);
2402
2403	if (args == NULL)
2404		goto bailout;
2405
2406	for (i = 0; i < num_args; i++) {
2407		args[i].kname = NULL;
2408		args[i].kvalue = NULL;
2409	}
2410
2411	for (i = 0; i < num_args; i++) {
2412		uint8_t *tmpptr;
2413
2414		args[i].kname = ctl_copyin_alloc(args[i].name,
2415			args[i].namelen, error_str, error_str_len);
2416		if (args[i].kname == NULL)
2417			goto bailout;
2418
2419		if (args[i].kname[args[i].namelen - 1] != '\0') {
2420			snprintf(error_str, error_str_len, "Argument %d "
2421				 "name is not NUL-terminated", i);
2422			goto bailout;
2423		}
2424
2425		if (args[i].flags & CTL_BEARG_RD) {
2426			tmpptr = ctl_copyin_alloc(args[i].value,
2427				args[i].vallen, error_str, error_str_len);
2428			if (tmpptr == NULL)
2429				goto bailout;
2430			if ((args[i].flags & CTL_BEARG_ASCII)
2431			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2432				snprintf(error_str, error_str_len, "Argument "
2433				    "%d value is not NUL-terminated", i);
2434				goto bailout;
2435			}
2436			args[i].kvalue = tmpptr;
2437		} else {
2438			args[i].kvalue = malloc(args[i].vallen,
2439			    M_CTL, M_WAITOK | M_ZERO);
2440		}
2441	}
2442
2443	return (args);
2444bailout:
2445
2446	ctl_free_args(num_args, args);
2447
2448	return (NULL);
2449}
2450
2451static void
2452ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2453{
2454	int i;
2455
2456	for (i = 0; i < num_args; i++) {
2457		if (args[i].flags & CTL_BEARG_WR)
2458			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2459	}
2460}
2461
2462/*
2463 * Escape characters that are illegal or not recommended in XML.
2464 */
2465int
2466ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2467{
2468	char *end = str + size;
2469	int retval;
2470
2471	retval = 0;
2472
2473	for (; *str && str < end; str++) {
2474		switch (*str) {
2475		case '&':
2476			retval = sbuf_printf(sb, "&amp;");
2477			break;
2478		case '>':
2479			retval = sbuf_printf(sb, "&gt;");
2480			break;
2481		case '<':
2482			retval = sbuf_printf(sb, "&lt;");
2483			break;
2484		default:
2485			retval = sbuf_putc(sb, *str);
2486			break;
2487		}
2488
2489		if (retval != 0)
2490			break;
2491
2492	}
2493
2494	return (retval);
2495}
2496
2497static void
2498ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2499{
2500	struct scsi_vpd_id_descriptor *desc;
2501	int i;
2502
2503	if (id == NULL || id->len < 4)
2504		return;
2505	desc = (struct scsi_vpd_id_descriptor *)id->data;
2506	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2507	case SVPD_ID_TYPE_T10:
2508		sbuf_printf(sb, "t10.");
2509		break;
2510	case SVPD_ID_TYPE_EUI64:
2511		sbuf_printf(sb, "eui.");
2512		break;
2513	case SVPD_ID_TYPE_NAA:
2514		sbuf_printf(sb, "naa.");
2515		break;
2516	case SVPD_ID_TYPE_SCSI_NAME:
2517		break;
2518	}
2519	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2520	case SVPD_ID_CODESET_BINARY:
2521		for (i = 0; i < desc->length; i++)
2522			sbuf_printf(sb, "%02x", desc->identifier[i]);
2523		break;
2524	case SVPD_ID_CODESET_ASCII:
2525		sbuf_printf(sb, "%.*s", (int)desc->length,
2526		    (char *)desc->identifier);
2527		break;
2528	case SVPD_ID_CODESET_UTF8:
2529		sbuf_printf(sb, "%s", (char *)desc->identifier);
2530		break;
2531	}
2532}
2533
2534static int
2535ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2536	  struct thread *td)
2537{
2538	struct ctl_softc *softc = dev->si_drv1;
2539	struct ctl_lun *lun;
2540	int retval;
2541
2542	retval = 0;
2543
2544	switch (cmd) {
2545	case CTL_IO:
2546		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2547		break;
2548	case CTL_ENABLE_PORT:
2549	case CTL_DISABLE_PORT:
2550	case CTL_SET_PORT_WWNS: {
2551		struct ctl_port *port;
2552		struct ctl_port_entry *entry;
2553
2554		entry = (struct ctl_port_entry *)addr;
2555
2556		mtx_lock(&softc->ctl_lock);
2557		STAILQ_FOREACH(port, &softc->port_list, links) {
2558			int action, done;
2559
2560			if (port->targ_port < softc->port_min ||
2561			    port->targ_port >= softc->port_max)
2562				continue;
2563
2564			action = 0;
2565			done = 0;
2566			if ((entry->port_type == CTL_PORT_NONE)
2567			 && (entry->targ_port == port->targ_port)) {
2568				/*
2569				 * If the user only wants to enable or
2570				 * disable or set WWNs on a specific port,
2571				 * do the operation and we're done.
2572				 */
2573				action = 1;
2574				done = 1;
2575			} else if (entry->port_type & port->port_type) {
2576				/*
2577				 * Compare the user's type mask with the
2578				 * particular frontend type to see if we
2579				 * have a match.
2580				 */
2581				action = 1;
2582				done = 0;
2583
2584				/*
2585				 * Make sure the user isn't trying to set
2586				 * WWNs on multiple ports at the same time.
2587				 */
2588				if (cmd == CTL_SET_PORT_WWNS) {
2589					printf("%s: Can't set WWNs on "
2590					       "multiple ports\n", __func__);
2591					retval = EINVAL;
2592					break;
2593				}
2594			}
2595			if (action == 0)
2596				continue;
2597
2598			/*
2599			 * XXX KDM we have to drop the lock here, because
2600			 * the online/offline operations can potentially
2601			 * block.  We need to reference count the frontends
2602			 * so they can't go away,
2603			 */
2604			if (cmd == CTL_ENABLE_PORT) {
2605				mtx_unlock(&softc->ctl_lock);
2606				ctl_port_online(port);
2607				mtx_lock(&softc->ctl_lock);
2608			} else if (cmd == CTL_DISABLE_PORT) {
2609				mtx_unlock(&softc->ctl_lock);
2610				ctl_port_offline(port);
2611				mtx_lock(&softc->ctl_lock);
2612			} else if (cmd == CTL_SET_PORT_WWNS) {
2613				ctl_port_set_wwns(port,
2614				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2615				    1 : 0, entry->wwnn,
2616				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2617				    1 : 0, entry->wwpn);
2618			}
2619			if (done != 0)
2620				break;
2621		}
2622		mtx_unlock(&softc->ctl_lock);
2623		break;
2624	}
2625	case CTL_GET_OOA: {
2626		struct ctl_ooa *ooa_hdr;
2627		struct ctl_ooa_entry *entries;
2628		uint32_t cur_fill_num;
2629
2630		ooa_hdr = (struct ctl_ooa *)addr;
2631
2632		if ((ooa_hdr->alloc_len == 0)
2633		 || (ooa_hdr->alloc_num == 0)) {
2634			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2635			       "must be non-zero\n", __func__,
2636			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2637			retval = EINVAL;
2638			break;
2639		}
2640
2641		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2642		    sizeof(struct ctl_ooa_entry))) {
2643			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2644			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2645			       __func__, ooa_hdr->alloc_len,
2646			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2647			retval = EINVAL;
2648			break;
2649		}
2650
2651		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2652		if (entries == NULL) {
2653			printf("%s: could not allocate %d bytes for OOA "
2654			       "dump\n", __func__, ooa_hdr->alloc_len);
2655			retval = ENOMEM;
2656			break;
2657		}
2658
2659		mtx_lock(&softc->ctl_lock);
2660		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2661		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2662		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2663			mtx_unlock(&softc->ctl_lock);
2664			free(entries, M_CTL);
2665			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2666			       __func__, (uintmax_t)ooa_hdr->lun_num);
2667			retval = EINVAL;
2668			break;
2669		}
2670
2671		cur_fill_num = 0;
2672
2673		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2674			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2675				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2676				    ooa_hdr, entries);
2677			}
2678		} else {
2679			lun = softc->ctl_luns[ooa_hdr->lun_num];
2680			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2681			    entries);
2682		}
2683		mtx_unlock(&softc->ctl_lock);
2684
2685		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2686		ooa_hdr->fill_len = ooa_hdr->fill_num *
2687			sizeof(struct ctl_ooa_entry);
2688		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2689		if (retval != 0) {
2690			printf("%s: error copying out %d bytes for OOA dump\n",
2691			       __func__, ooa_hdr->fill_len);
2692		}
2693
2694		getbinuptime(&ooa_hdr->cur_bt);
2695
2696		if (cur_fill_num > ooa_hdr->alloc_num) {
2697			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2698			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2699		} else {
2700			ooa_hdr->dropped_num = 0;
2701			ooa_hdr->status = CTL_OOA_OK;
2702		}
2703
2704		free(entries, M_CTL);
2705		break;
2706	}
2707	case CTL_DELAY_IO: {
2708		struct ctl_io_delay_info *delay_info;
2709
2710		delay_info = (struct ctl_io_delay_info *)addr;
2711
2712#ifdef CTL_IO_DELAY
2713		mtx_lock(&softc->ctl_lock);
2714
2715		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2716		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2717			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2718		} else {
2719			lun = softc->ctl_luns[delay_info->lun_id];
2720			mtx_lock(&lun->lun_lock);
2721
2722			delay_info->status = CTL_DELAY_STATUS_OK;
2723
2724			switch (delay_info->delay_type) {
2725			case CTL_DELAY_TYPE_CONT:
2726				break;
2727			case CTL_DELAY_TYPE_ONESHOT:
2728				break;
2729			default:
2730				delay_info->status =
2731					CTL_DELAY_STATUS_INVALID_TYPE;
2732				break;
2733			}
2734
2735			switch (delay_info->delay_loc) {
2736			case CTL_DELAY_LOC_DATAMOVE:
2737				lun->delay_info.datamove_type =
2738					delay_info->delay_type;
2739				lun->delay_info.datamove_delay =
2740					delay_info->delay_secs;
2741				break;
2742			case CTL_DELAY_LOC_DONE:
2743				lun->delay_info.done_type =
2744					delay_info->delay_type;
2745				lun->delay_info.done_delay =
2746					delay_info->delay_secs;
2747				break;
2748			default:
2749				delay_info->status =
2750					CTL_DELAY_STATUS_INVALID_LOC;
2751				break;
2752			}
2753			mtx_unlock(&lun->lun_lock);
2754		}
2755
2756		mtx_unlock(&softc->ctl_lock);
2757#else
2758		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2759#endif /* CTL_IO_DELAY */
2760		break;
2761	}
2762	case CTL_GETSTATS: {
2763		struct ctl_stats *stats;
2764		int i;
2765
2766		stats = (struct ctl_stats *)addr;
2767
2768		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2769		     stats->alloc_len) {
2770			stats->status = CTL_SS_NEED_MORE_SPACE;
2771			stats->num_luns = softc->num_luns;
2772			break;
2773		}
2774		/*
2775		 * XXX KDM no locking here.  If the LUN list changes,
2776		 * things can blow up.
2777		 */
2778		i = 0;
2779		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2780			retval = copyout(&lun->stats, &stats->lun_stats[i++],
2781					 sizeof(lun->stats));
2782			if (retval != 0)
2783				break;
2784		}
2785		stats->num_luns = softc->num_luns;
2786		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2787				 softc->num_luns;
2788		stats->status = CTL_SS_OK;
2789#ifdef CTL_TIME_IO
2790		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2791#else
2792		stats->flags = CTL_STATS_FLAG_NONE;
2793#endif
2794		getnanouptime(&stats->timestamp);
2795		break;
2796	}
2797	case CTL_ERROR_INJECT: {
2798		struct ctl_error_desc *err_desc, *new_err_desc;
2799
2800		err_desc = (struct ctl_error_desc *)addr;
2801
2802		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2803				      M_WAITOK | M_ZERO);
2804		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2805
2806		mtx_lock(&softc->ctl_lock);
2807		lun = softc->ctl_luns[err_desc->lun_id];
2808		if (lun == NULL) {
2809			mtx_unlock(&softc->ctl_lock);
2810			free(new_err_desc, M_CTL);
2811			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2812			       __func__, (uintmax_t)err_desc->lun_id);
2813			retval = EINVAL;
2814			break;
2815		}
2816		mtx_lock(&lun->lun_lock);
2817		mtx_unlock(&softc->ctl_lock);
2818
2819		/*
2820		 * We could do some checking here to verify the validity
2821		 * of the request, but given the complexity of error
2822		 * injection requests, the checking logic would be fairly
2823		 * complex.
2824		 *
2825		 * For now, if the request is invalid, it just won't get
2826		 * executed and might get deleted.
2827		 */
2828		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2829
2830		/*
2831		 * XXX KDM check to make sure the serial number is unique,
2832		 * in case we somehow manage to wrap.  That shouldn't
2833		 * happen for a very long time, but it's the right thing to
2834		 * do.
2835		 */
2836		new_err_desc->serial = lun->error_serial;
2837		err_desc->serial = lun->error_serial;
2838		lun->error_serial++;
2839
2840		mtx_unlock(&lun->lun_lock);
2841		break;
2842	}
2843	case CTL_ERROR_INJECT_DELETE: {
2844		struct ctl_error_desc *delete_desc, *desc, *desc2;
2845		int delete_done;
2846
2847		delete_desc = (struct ctl_error_desc *)addr;
2848		delete_done = 0;
2849
2850		mtx_lock(&softc->ctl_lock);
2851		lun = softc->ctl_luns[delete_desc->lun_id];
2852		if (lun == NULL) {
2853			mtx_unlock(&softc->ctl_lock);
2854			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2855			       __func__, (uintmax_t)delete_desc->lun_id);
2856			retval = EINVAL;
2857			break;
2858		}
2859		mtx_lock(&lun->lun_lock);
2860		mtx_unlock(&softc->ctl_lock);
2861		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2862			if (desc->serial != delete_desc->serial)
2863				continue;
2864
2865			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2866				      links);
2867			free(desc, M_CTL);
2868			delete_done = 1;
2869		}
2870		mtx_unlock(&lun->lun_lock);
2871		if (delete_done == 0) {
2872			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2873			       "error serial %ju on LUN %u\n", __func__,
2874			       delete_desc->serial, delete_desc->lun_id);
2875			retval = EINVAL;
2876			break;
2877		}
2878		break;
2879	}
2880	case CTL_DUMP_STRUCTS: {
2881		int i, j, k;
2882		struct ctl_port *port;
2883		struct ctl_frontend *fe;
2884
2885		mtx_lock(&softc->ctl_lock);
2886		printf("CTL Persistent Reservation information start:\n");
2887		for (i = 0; i < CTL_MAX_LUNS; i++) {
2888			lun = softc->ctl_luns[i];
2889
2890			if ((lun == NULL)
2891			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2892				continue;
2893
2894			for (j = 0; j < CTL_MAX_PORTS; j++) {
2895				if (lun->pr_keys[j] == NULL)
2896					continue;
2897				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2898					if (lun->pr_keys[j][k] == 0)
2899						continue;
2900					printf("  LUN %d port %d iid %d key "
2901					       "%#jx\n", i, j, k,
2902					       (uintmax_t)lun->pr_keys[j][k]);
2903				}
2904			}
2905		}
2906		printf("CTL Persistent Reservation information end\n");
2907		printf("CTL Ports:\n");
2908		STAILQ_FOREACH(port, &softc->port_list, links) {
2909			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2910			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2911			       port->frontend->name, port->port_type,
2912			       port->physical_port, port->virtual_port,
2913			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2914			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2915				if (port->wwpn_iid[j].in_use == 0 &&
2916				    port->wwpn_iid[j].wwpn == 0 &&
2917				    port->wwpn_iid[j].name == NULL)
2918					continue;
2919
2920				printf("    iid %u use %d WWPN %#jx '%s'\n",
2921				    j, port->wwpn_iid[j].in_use,
2922				    (uintmax_t)port->wwpn_iid[j].wwpn,
2923				    port->wwpn_iid[j].name);
2924			}
2925		}
2926		printf("CTL Port information end\n");
2927		mtx_unlock(&softc->ctl_lock);
2928		/*
2929		 * XXX KDM calling this without a lock.  We'd likely want
2930		 * to drop the lock before calling the frontend's dump
2931		 * routine anyway.
2932		 */
2933		printf("CTL Frontends:\n");
2934		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2935			printf("  Frontend '%s'\n", fe->name);
2936			if (fe->fe_dump != NULL)
2937				fe->fe_dump();
2938		}
2939		printf("CTL Frontend information end\n");
2940		break;
2941	}
2942	case CTL_LUN_REQ: {
2943		struct ctl_lun_req *lun_req;
2944		struct ctl_backend_driver *backend;
2945
2946		lun_req = (struct ctl_lun_req *)addr;
2947
2948		backend = ctl_backend_find(lun_req->backend);
2949		if (backend == NULL) {
2950			lun_req->status = CTL_LUN_ERROR;
2951			snprintf(lun_req->error_str,
2952				 sizeof(lun_req->error_str),
2953				 "Backend \"%s\" not found.",
2954				 lun_req->backend);
2955			break;
2956		}
2957		if (lun_req->num_be_args > 0) {
2958			lun_req->kern_be_args = ctl_copyin_args(
2959				lun_req->num_be_args,
2960				lun_req->be_args,
2961				lun_req->error_str,
2962				sizeof(lun_req->error_str));
2963			if (lun_req->kern_be_args == NULL) {
2964				lun_req->status = CTL_LUN_ERROR;
2965				break;
2966			}
2967		}
2968
2969		retval = backend->ioctl(dev, cmd, addr, flag, td);
2970
2971		if (lun_req->num_be_args > 0) {
2972			ctl_copyout_args(lun_req->num_be_args,
2973				      lun_req->kern_be_args);
2974			ctl_free_args(lun_req->num_be_args,
2975				      lun_req->kern_be_args);
2976		}
2977		break;
2978	}
2979	case CTL_LUN_LIST: {
2980		struct sbuf *sb;
2981		struct ctl_lun_list *list;
2982		struct ctl_option *opt;
2983
2984		list = (struct ctl_lun_list *)addr;
2985
2986		/*
2987		 * Allocate a fixed length sbuf here, based on the length
2988		 * of the user's buffer.  We could allocate an auto-extending
2989		 * buffer, and then tell the user how much larger our
2990		 * amount of data is than his buffer, but that presents
2991		 * some problems:
2992		 *
2993		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2994		 *     we can't hold a lock while calling them with an
2995		 *     auto-extending buffer.
2996 		 *
2997		 * 2.  There is not currently a LUN reference counting
2998		 *     mechanism, outside of outstanding transactions on
2999		 *     the LUN's OOA queue.  So a LUN could go away on us
3000		 *     while we're getting the LUN number, backend-specific
3001		 *     information, etc.  Thus, given the way things
3002		 *     currently work, we need to hold the CTL lock while
3003		 *     grabbing LUN information.
3004		 *
3005		 * So, from the user's standpoint, the best thing to do is
3006		 * allocate what he thinks is a reasonable buffer length,
3007		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3008		 * double the buffer length and try again.  (And repeat
3009		 * that until he succeeds.)
3010		 */
3011		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3012		if (sb == NULL) {
3013			list->status = CTL_LUN_LIST_ERROR;
3014			snprintf(list->error_str, sizeof(list->error_str),
3015				 "Unable to allocate %d bytes for LUN list",
3016				 list->alloc_len);
3017			break;
3018		}
3019
3020		sbuf_printf(sb, "<ctllunlist>\n");
3021
3022		mtx_lock(&softc->ctl_lock);
3023		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3024			mtx_lock(&lun->lun_lock);
3025			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3026					     (uintmax_t)lun->lun);
3027
3028			/*
3029			 * Bail out as soon as we see that we've overfilled
3030			 * the buffer.
3031			 */
3032			if (retval != 0)
3033				break;
3034
3035			retval = sbuf_printf(sb, "\t<backend_type>%s"
3036					     "</backend_type>\n",
3037					     (lun->backend == NULL) ?  "none" :
3038					     lun->backend->name);
3039
3040			if (retval != 0)
3041				break;
3042
3043			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3044					     lun->be_lun->lun_type);
3045
3046			if (retval != 0)
3047				break;
3048
3049			if (lun->backend == NULL) {
3050				retval = sbuf_printf(sb, "</lun>\n");
3051				if (retval != 0)
3052					break;
3053				continue;
3054			}
3055
3056			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3057					     (lun->be_lun->maxlba > 0) ?
3058					     lun->be_lun->maxlba + 1 : 0);
3059
3060			if (retval != 0)
3061				break;
3062
3063			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3064					     lun->be_lun->blocksize);
3065
3066			if (retval != 0)
3067				break;
3068
3069			retval = sbuf_printf(sb, "\t<serial_number>");
3070
3071			if (retval != 0)
3072				break;
3073
3074			retval = ctl_sbuf_printf_esc(sb,
3075			    lun->be_lun->serial_num,
3076			    sizeof(lun->be_lun->serial_num));
3077
3078			if (retval != 0)
3079				break;
3080
3081			retval = sbuf_printf(sb, "</serial_number>\n");
3082
3083			if (retval != 0)
3084				break;
3085
3086			retval = sbuf_printf(sb, "\t<device_id>");
3087
3088			if (retval != 0)
3089				break;
3090
3091			retval = ctl_sbuf_printf_esc(sb,
3092			    lun->be_lun->device_id,
3093			    sizeof(lun->be_lun->device_id));
3094
3095			if (retval != 0)
3096				break;
3097
3098			retval = sbuf_printf(sb, "</device_id>\n");
3099
3100			if (retval != 0)
3101				break;
3102
3103			if (lun->backend->lun_info != NULL) {
3104				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3105				if (retval != 0)
3106					break;
3107			}
3108			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3109				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3110				    opt->name, opt->value, opt->name);
3111				if (retval != 0)
3112					break;
3113			}
3114
3115			retval = sbuf_printf(sb, "</lun>\n");
3116
3117			if (retval != 0)
3118				break;
3119			mtx_unlock(&lun->lun_lock);
3120		}
3121		if (lun != NULL)
3122			mtx_unlock(&lun->lun_lock);
3123		mtx_unlock(&softc->ctl_lock);
3124
3125		if ((retval != 0)
3126		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3127			retval = 0;
3128			sbuf_delete(sb);
3129			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3130			snprintf(list->error_str, sizeof(list->error_str),
3131				 "Out of space, %d bytes is too small",
3132				 list->alloc_len);
3133			break;
3134		}
3135
3136		sbuf_finish(sb);
3137
3138		retval = copyout(sbuf_data(sb), list->lun_xml,
3139				 sbuf_len(sb) + 1);
3140
3141		list->fill_len = sbuf_len(sb) + 1;
3142		list->status = CTL_LUN_LIST_OK;
3143		sbuf_delete(sb);
3144		break;
3145	}
3146	case CTL_ISCSI: {
3147		struct ctl_iscsi *ci;
3148		struct ctl_frontend *fe;
3149
3150		ci = (struct ctl_iscsi *)addr;
3151
3152		fe = ctl_frontend_find("iscsi");
3153		if (fe == NULL) {
3154			ci->status = CTL_ISCSI_ERROR;
3155			snprintf(ci->error_str, sizeof(ci->error_str),
3156			    "Frontend \"iscsi\" not found.");
3157			break;
3158		}
3159
3160		retval = fe->ioctl(dev, cmd, addr, flag, td);
3161		break;
3162	}
3163	case CTL_PORT_REQ: {
3164		struct ctl_req *req;
3165		struct ctl_frontend *fe;
3166
3167		req = (struct ctl_req *)addr;
3168
3169		fe = ctl_frontend_find(req->driver);
3170		if (fe == NULL) {
3171			req->status = CTL_LUN_ERROR;
3172			snprintf(req->error_str, sizeof(req->error_str),
3173			    "Frontend \"%s\" not found.", req->driver);
3174			break;
3175		}
3176		if (req->num_args > 0) {
3177			req->kern_args = ctl_copyin_args(req->num_args,
3178			    req->args, req->error_str, sizeof(req->error_str));
3179			if (req->kern_args == NULL) {
3180				req->status = CTL_LUN_ERROR;
3181				break;
3182			}
3183		}
3184
3185		if (fe->ioctl)
3186			retval = fe->ioctl(dev, cmd, addr, flag, td);
3187		else
3188			retval = ENODEV;
3189
3190		if (req->num_args > 0) {
3191			ctl_copyout_args(req->num_args, req->kern_args);
3192			ctl_free_args(req->num_args, req->kern_args);
3193		}
3194		break;
3195	}
3196	case CTL_PORT_LIST: {
3197		struct sbuf *sb;
3198		struct ctl_port *port;
3199		struct ctl_lun_list *list;
3200		struct ctl_option *opt;
3201		int j;
3202		uint32_t plun;
3203
3204		list = (struct ctl_lun_list *)addr;
3205
3206		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3207		if (sb == NULL) {
3208			list->status = CTL_LUN_LIST_ERROR;
3209			snprintf(list->error_str, sizeof(list->error_str),
3210				 "Unable to allocate %d bytes for LUN list",
3211				 list->alloc_len);
3212			break;
3213		}
3214
3215		sbuf_printf(sb, "<ctlportlist>\n");
3216
3217		mtx_lock(&softc->ctl_lock);
3218		STAILQ_FOREACH(port, &softc->port_list, links) {
3219			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3220					     (uintmax_t)port->targ_port);
3221
3222			/*
3223			 * Bail out as soon as we see that we've overfilled
3224			 * the buffer.
3225			 */
3226			if (retval != 0)
3227				break;
3228
3229			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3230			    "</frontend_type>\n", port->frontend->name);
3231			if (retval != 0)
3232				break;
3233
3234			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3235					     port->port_type);
3236			if (retval != 0)
3237				break;
3238
3239			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3240			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3241			if (retval != 0)
3242				break;
3243
3244			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3245			    port->port_name);
3246			if (retval != 0)
3247				break;
3248
3249			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3250			    port->physical_port);
3251			if (retval != 0)
3252				break;
3253
3254			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3255			    port->virtual_port);
3256			if (retval != 0)
3257				break;
3258
3259			if (port->target_devid != NULL) {
3260				sbuf_printf(sb, "\t<target>");
3261				ctl_id_sbuf(port->target_devid, sb);
3262				sbuf_printf(sb, "</target>\n");
3263			}
3264
3265			if (port->port_devid != NULL) {
3266				sbuf_printf(sb, "\t<port>");
3267				ctl_id_sbuf(port->port_devid, sb);
3268				sbuf_printf(sb, "</port>\n");
3269			}
3270
3271			if (port->port_info != NULL) {
3272				retval = port->port_info(port->onoff_arg, sb);
3273				if (retval != 0)
3274					break;
3275			}
3276			STAILQ_FOREACH(opt, &port->options, links) {
3277				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3278				    opt->name, opt->value, opt->name);
3279				if (retval != 0)
3280					break;
3281			}
3282
3283			if (port->lun_map != NULL) {
3284				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3285				for (j = 0; j < CTL_MAX_LUNS; j++) {
3286					plun = ctl_lun_map_from_port(port, j);
3287					if (plun >= CTL_MAX_LUNS)
3288						continue;
3289					sbuf_printf(sb,
3290					    "\t<lun id=\"%u\">%u</lun>\n",
3291					    j, plun);
3292				}
3293			}
3294
3295			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3296				if (port->wwpn_iid[j].in_use == 0 ||
3297				    (port->wwpn_iid[j].wwpn == 0 &&
3298				     port->wwpn_iid[j].name == NULL))
3299					continue;
3300
3301				if (port->wwpn_iid[j].name != NULL)
3302					retval = sbuf_printf(sb,
3303					    "\t<initiator id=\"%u\">%s</initiator>\n",
3304					    j, port->wwpn_iid[j].name);
3305				else
3306					retval = sbuf_printf(sb,
3307					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3308					    j, port->wwpn_iid[j].wwpn);
3309				if (retval != 0)
3310					break;
3311			}
3312			if (retval != 0)
3313				break;
3314
3315			retval = sbuf_printf(sb, "</targ_port>\n");
3316			if (retval != 0)
3317				break;
3318		}
3319		mtx_unlock(&softc->ctl_lock);
3320
3321		if ((retval != 0)
3322		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3323			retval = 0;
3324			sbuf_delete(sb);
3325			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3326			snprintf(list->error_str, sizeof(list->error_str),
3327				 "Out of space, %d bytes is too small",
3328				 list->alloc_len);
3329			break;
3330		}
3331
3332		sbuf_finish(sb);
3333
3334		retval = copyout(sbuf_data(sb), list->lun_xml,
3335				 sbuf_len(sb) + 1);
3336
3337		list->fill_len = sbuf_len(sb) + 1;
3338		list->status = CTL_LUN_LIST_OK;
3339		sbuf_delete(sb);
3340		break;
3341	}
3342	case CTL_LUN_MAP: {
3343		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3344		struct ctl_port *port;
3345
3346		mtx_lock(&softc->ctl_lock);
3347		if (lm->port < softc->port_min ||
3348		    lm->port >= softc->port_max ||
3349		    (port = softc->ctl_ports[lm->port]) == NULL) {
3350			mtx_unlock(&softc->ctl_lock);
3351			return (ENXIO);
3352		}
3353		if (port->status & CTL_PORT_STATUS_ONLINE) {
3354			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3355				if (ctl_lun_map_to_port(port, lun->lun) >=
3356				    CTL_MAX_LUNS)
3357					continue;
3358				mtx_lock(&lun->lun_lock);
3359				ctl_est_ua_port(lun, lm->port, -1,
3360				    CTL_UA_LUN_CHANGE);
3361				mtx_unlock(&lun->lun_lock);
3362			}
3363		}
3364		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3365		if (lm->plun < CTL_MAX_LUNS) {
3366			if (lm->lun == UINT32_MAX)
3367				retval = ctl_lun_map_unset(port, lm->plun);
3368			else if (lm->lun < CTL_MAX_LUNS &&
3369			    softc->ctl_luns[lm->lun] != NULL)
3370				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3371			else
3372				return (ENXIO);
3373		} else if (lm->plun == UINT32_MAX) {
3374			if (lm->lun == UINT32_MAX)
3375				retval = ctl_lun_map_deinit(port);
3376			else
3377				retval = ctl_lun_map_init(port);
3378		} else
3379			return (ENXIO);
3380		if (port->status & CTL_PORT_STATUS_ONLINE)
3381			ctl_isc_announce_port(port);
3382		break;
3383	}
3384	default: {
3385		/* XXX KDM should we fix this? */
3386#if 0
3387		struct ctl_backend_driver *backend;
3388		unsigned int type;
3389		int found;
3390
3391		found = 0;
3392
3393		/*
3394		 * We encode the backend type as the ioctl type for backend
3395		 * ioctls.  So parse it out here, and then search for a
3396		 * backend of this type.
3397		 */
3398		type = _IOC_TYPE(cmd);
3399
3400		STAILQ_FOREACH(backend, &softc->be_list, links) {
3401			if (backend->type == type) {
3402				found = 1;
3403				break;
3404			}
3405		}
3406		if (found == 0) {
3407			printf("ctl: unknown ioctl command %#lx or backend "
3408			       "%d\n", cmd, type);
3409			retval = EINVAL;
3410			break;
3411		}
3412		retval = backend->ioctl(dev, cmd, addr, flag, td);
3413#endif
3414		retval = ENOTTY;
3415		break;
3416	}
3417	}
3418	return (retval);
3419}
3420
3421uint32_t
3422ctl_get_initindex(struct ctl_nexus *nexus)
3423{
3424	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3425}
3426
3427int
3428ctl_lun_map_init(struct ctl_port *port)
3429{
3430	struct ctl_softc *softc = port->ctl_softc;
3431	struct ctl_lun *lun;
3432	uint32_t i;
3433
3434	if (port->lun_map == NULL)
3435		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3436		    M_CTL, M_NOWAIT);
3437	if (port->lun_map == NULL)
3438		return (ENOMEM);
3439	for (i = 0; i < CTL_MAX_LUNS; i++)
3440		port->lun_map[i] = UINT32_MAX;
3441	if (port->status & CTL_PORT_STATUS_ONLINE) {
3442		if (port->lun_disable != NULL) {
3443			STAILQ_FOREACH(lun, &softc->lun_list, links)
3444				port->lun_disable(port->targ_lun_arg, lun->lun);
3445		}
3446		ctl_isc_announce_port(port);
3447	}
3448	return (0);
3449}
3450
3451int
3452ctl_lun_map_deinit(struct ctl_port *port)
3453{
3454	struct ctl_softc *softc = port->ctl_softc;
3455	struct ctl_lun *lun;
3456
3457	if (port->lun_map == NULL)
3458		return (0);
3459	free(port->lun_map, M_CTL);
3460	port->lun_map = NULL;
3461	if (port->status & CTL_PORT_STATUS_ONLINE) {
3462		if (port->lun_enable != NULL) {
3463			STAILQ_FOREACH(lun, &softc->lun_list, links)
3464				port->lun_enable(port->targ_lun_arg, lun->lun);
3465		}
3466		ctl_isc_announce_port(port);
3467	}
3468	return (0);
3469}
3470
3471int
3472ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3473{
3474	int status;
3475	uint32_t old;
3476
3477	if (port->lun_map == NULL) {
3478		status = ctl_lun_map_init(port);
3479		if (status != 0)
3480			return (status);
3481	}
3482	old = port->lun_map[plun];
3483	port->lun_map[plun] = glun;
3484	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3485		if (port->lun_enable != NULL)
3486			port->lun_enable(port->targ_lun_arg, plun);
3487		ctl_isc_announce_port(port);
3488	}
3489	return (0);
3490}
3491
3492int
3493ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3494{
3495	uint32_t old;
3496
3497	if (port->lun_map == NULL)
3498		return (0);
3499	old = port->lun_map[plun];
3500	port->lun_map[plun] = UINT32_MAX;
3501	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3502		if (port->lun_disable != NULL)
3503			port->lun_disable(port->targ_lun_arg, plun);
3504		ctl_isc_announce_port(port);
3505	}
3506	return (0);
3507}
3508
3509uint32_t
3510ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3511{
3512
3513	if (port == NULL)
3514		return (UINT32_MAX);
3515	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3516		return (lun_id);
3517	return (port->lun_map[lun_id]);
3518}
3519
3520uint32_t
3521ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3522{
3523	uint32_t i;
3524
3525	if (port == NULL)
3526		return (UINT32_MAX);
3527	if (port->lun_map == NULL)
3528		return (lun_id);
3529	for (i = 0; i < CTL_MAX_LUNS; i++) {
3530		if (port->lun_map[i] == lun_id)
3531			return (i);
3532	}
3533	return (UINT32_MAX);
3534}
3535
3536static struct ctl_port *
3537ctl_io_port(struct ctl_io_hdr *io_hdr)
3538{
3539
3540	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3541}
3542
3543int
3544ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3545{
3546	int i;
3547
3548	for (i = first; i < last; i++) {
3549		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3550			return (i);
3551	}
3552	return (-1);
3553}
3554
3555int
3556ctl_set_mask(uint32_t *mask, uint32_t bit)
3557{
3558	uint32_t chunk, piece;
3559
3560	chunk = bit >> 5;
3561	piece = bit % (sizeof(uint32_t) * 8);
3562
3563	if ((mask[chunk] & (1 << piece)) != 0)
3564		return (-1);
3565	else
3566		mask[chunk] |= (1 << piece);
3567
3568	return (0);
3569}
3570
3571int
3572ctl_clear_mask(uint32_t *mask, uint32_t bit)
3573{
3574	uint32_t chunk, piece;
3575
3576	chunk = bit >> 5;
3577	piece = bit % (sizeof(uint32_t) * 8);
3578
3579	if ((mask[chunk] & (1 << piece)) == 0)
3580		return (-1);
3581	else
3582		mask[chunk] &= ~(1 << piece);
3583
3584	return (0);
3585}
3586
3587int
3588ctl_is_set(uint32_t *mask, uint32_t bit)
3589{
3590	uint32_t chunk, piece;
3591
3592	chunk = bit >> 5;
3593	piece = bit % (sizeof(uint32_t) * 8);
3594
3595	if ((mask[chunk] & (1 << piece)) == 0)
3596		return (0);
3597	else
3598		return (1);
3599}
3600
3601static uint64_t
3602ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3603{
3604	uint64_t *t;
3605
3606	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3607	if (t == NULL)
3608		return (0);
3609	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3610}
3611
3612static void
3613ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3614{
3615	uint64_t *t;
3616
3617	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3618	if (t == NULL)
3619		return;
3620	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3621}
3622
3623static void
3624ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3625{
3626	uint64_t *p;
3627	u_int i;
3628
3629	i = residx/CTL_MAX_INIT_PER_PORT;
3630	if (lun->pr_keys[i] != NULL)
3631		return;
3632	mtx_unlock(&lun->lun_lock);
3633	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3634	    M_WAITOK | M_ZERO);
3635	mtx_lock(&lun->lun_lock);
3636	if (lun->pr_keys[i] == NULL)
3637		lun->pr_keys[i] = p;
3638	else
3639		free(p, M_CTL);
3640}
3641
3642static void
3643ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3644{
3645	uint64_t *t;
3646
3647	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3648	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3649	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3650}
3651
3652/*
3653 * ctl_softc, pool_name, total_ctl_io are passed in.
3654 * npool is passed out.
3655 */
3656int
3657ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3658		uint32_t total_ctl_io, void **npool)
3659{
3660#ifdef IO_POOLS
3661	struct ctl_io_pool *pool;
3662
3663	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3664					    M_NOWAIT | M_ZERO);
3665	if (pool == NULL)
3666		return (ENOMEM);
3667
3668	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3669	pool->ctl_softc = ctl_softc;
3670	pool->zone = uma_zsecond_create(pool->name, NULL,
3671	    NULL, NULL, NULL, ctl_softc->io_zone);
3672	/* uma_prealloc(pool->zone, total_ctl_io); */
3673
3674	*npool = pool;
3675#else
3676	*npool = ctl_softc->io_zone;
3677#endif
3678	return (0);
3679}
3680
3681void
3682ctl_pool_free(struct ctl_io_pool *pool)
3683{
3684
3685	if (pool == NULL)
3686		return;
3687
3688#ifdef IO_POOLS
3689	uma_zdestroy(pool->zone);
3690	free(pool, M_CTL);
3691#endif
3692}
3693
3694union ctl_io *
3695ctl_alloc_io(void *pool_ref)
3696{
3697	union ctl_io *io;
3698#ifdef IO_POOLS
3699	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3700
3701	io = uma_zalloc(pool->zone, M_WAITOK);
3702#else
3703	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3704#endif
3705	if (io != NULL)
3706		io->io_hdr.pool = pool_ref;
3707	return (io);
3708}
3709
3710union ctl_io *
3711ctl_alloc_io_nowait(void *pool_ref)
3712{
3713	union ctl_io *io;
3714#ifdef IO_POOLS
3715	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3716
3717	io = uma_zalloc(pool->zone, M_NOWAIT);
3718#else
3719	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3720#endif
3721	if (io != NULL)
3722		io->io_hdr.pool = pool_ref;
3723	return (io);
3724}
3725
3726void
3727ctl_free_io(union ctl_io *io)
3728{
3729#ifdef IO_POOLS
3730	struct ctl_io_pool *pool;
3731#endif
3732
3733	if (io == NULL)
3734		return;
3735
3736#ifdef IO_POOLS
3737	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3738	uma_zfree(pool->zone, io);
3739#else
3740	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3741#endif
3742}
3743
3744void
3745ctl_zero_io(union ctl_io *io)
3746{
3747	void *pool_ref;
3748
3749	if (io == NULL)
3750		return;
3751
3752	/*
3753	 * May need to preserve linked list pointers at some point too.
3754	 */
3755	pool_ref = io->io_hdr.pool;
3756	memset(io, 0, sizeof(*io));
3757	io->io_hdr.pool = pool_ref;
3758}
3759
3760int
3761ctl_expand_number(const char *buf, uint64_t *num)
3762{
3763	char *endptr;
3764	uint64_t number;
3765	unsigned shift;
3766
3767	number = strtoq(buf, &endptr, 0);
3768
3769	switch (tolower((unsigned char)*endptr)) {
3770	case 'e':
3771		shift = 60;
3772		break;
3773	case 'p':
3774		shift = 50;
3775		break;
3776	case 't':
3777		shift = 40;
3778		break;
3779	case 'g':
3780		shift = 30;
3781		break;
3782	case 'm':
3783		shift = 20;
3784		break;
3785	case 'k':
3786		shift = 10;
3787		break;
3788	case 'b':
3789	case '\0': /* No unit. */
3790		*num = number;
3791		return (0);
3792	default:
3793		/* Unrecognized unit. */
3794		return (-1);
3795	}
3796
3797	if ((number << shift) >> shift != number) {
3798		/* Overflow */
3799		return (-1);
3800	}
3801	*num = number << shift;
3802	return (0);
3803}
3804
3805
3806/*
3807 * This routine could be used in the future to load default and/or saved
3808 * mode page parameters for a particuar lun.
3809 */
3810static int
3811ctl_init_page_index(struct ctl_lun *lun)
3812{
3813	int i;
3814	struct ctl_page_index *page_index;
3815	const char *value;
3816	uint64_t ival;
3817
3818	memcpy(&lun->mode_pages.index, page_index_template,
3819	       sizeof(page_index_template));
3820
3821	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3822
3823		page_index = &lun->mode_pages.index[i];
3824		if (lun->be_lun->lun_type == T_DIRECT &&
3825		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3826			continue;
3827		if (lun->be_lun->lun_type == T_PROCESSOR &&
3828		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3829			continue;
3830		if (lun->be_lun->lun_type == T_CDROM &&
3831		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3832			continue;
3833
3834		switch (page_index->page_code & SMPH_PC_MASK) {
3835		case SMS_RW_ERROR_RECOVERY_PAGE: {
3836			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3837				panic("subpage is incorrect!");
3838			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3839			       &rw_er_page_default,
3840			       sizeof(rw_er_page_default));
3841			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3842			       &rw_er_page_changeable,
3843			       sizeof(rw_er_page_changeable));
3844			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3845			       &rw_er_page_default,
3846			       sizeof(rw_er_page_default));
3847			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3848			       &rw_er_page_default,
3849			       sizeof(rw_er_page_default));
3850			page_index->page_data =
3851				(uint8_t *)lun->mode_pages.rw_er_page;
3852			break;
3853		}
3854		case SMS_FORMAT_DEVICE_PAGE: {
3855			struct scsi_format_page *format_page;
3856
3857			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3858				panic("subpage is incorrect!");
3859
3860			/*
3861			 * Sectors per track are set above.  Bytes per
3862			 * sector need to be set here on a per-LUN basis.
3863			 */
3864			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3865			       &format_page_default,
3866			       sizeof(format_page_default));
3867			memcpy(&lun->mode_pages.format_page[
3868			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3869			       sizeof(format_page_changeable));
3870			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3871			       &format_page_default,
3872			       sizeof(format_page_default));
3873			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3874			       &format_page_default,
3875			       sizeof(format_page_default));
3876
3877			format_page = &lun->mode_pages.format_page[
3878				CTL_PAGE_CURRENT];
3879			scsi_ulto2b(lun->be_lun->blocksize,
3880				    format_page->bytes_per_sector);
3881
3882			format_page = &lun->mode_pages.format_page[
3883				CTL_PAGE_DEFAULT];
3884			scsi_ulto2b(lun->be_lun->blocksize,
3885				    format_page->bytes_per_sector);
3886
3887			format_page = &lun->mode_pages.format_page[
3888				CTL_PAGE_SAVED];
3889			scsi_ulto2b(lun->be_lun->blocksize,
3890				    format_page->bytes_per_sector);
3891
3892			page_index->page_data =
3893				(uint8_t *)lun->mode_pages.format_page;
3894			break;
3895		}
3896		case SMS_RIGID_DISK_PAGE: {
3897			struct scsi_rigid_disk_page *rigid_disk_page;
3898			uint32_t sectors_per_cylinder;
3899			uint64_t cylinders;
3900#ifndef	__XSCALE__
3901			int shift;
3902#endif /* !__XSCALE__ */
3903
3904			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3905				panic("invalid subpage value %d",
3906				      page_index->subpage);
3907
3908			/*
3909			 * Rotation rate and sectors per track are set
3910			 * above.  We calculate the cylinders here based on
3911			 * capacity.  Due to the number of heads and
3912			 * sectors per track we're using, smaller arrays
3913			 * may turn out to have 0 cylinders.  Linux and
3914			 * FreeBSD don't pay attention to these mode pages
3915			 * to figure out capacity, but Solaris does.  It
3916			 * seems to deal with 0 cylinders just fine, and
3917			 * works out a fake geometry based on the capacity.
3918			 */
3919			memcpy(&lun->mode_pages.rigid_disk_page[
3920			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3921			       sizeof(rigid_disk_page_default));
3922			memcpy(&lun->mode_pages.rigid_disk_page[
3923			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3924			       sizeof(rigid_disk_page_changeable));
3925
3926			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3927				CTL_DEFAULT_HEADS;
3928
3929			/*
3930			 * The divide method here will be more accurate,
3931			 * probably, but results in floating point being
3932			 * used in the kernel on i386 (__udivdi3()).  On the
3933			 * XScale, though, __udivdi3() is implemented in
3934			 * software.
3935			 *
3936			 * The shift method for cylinder calculation is
3937			 * accurate if sectors_per_cylinder is a power of
3938			 * 2.  Otherwise it might be slightly off -- you
3939			 * might have a bit of a truncation problem.
3940			 */
3941#ifdef	__XSCALE__
3942			cylinders = (lun->be_lun->maxlba + 1) /
3943				sectors_per_cylinder;
3944#else
3945			for (shift = 31; shift > 0; shift--) {
3946				if (sectors_per_cylinder & (1 << shift))
3947					break;
3948			}
3949			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3950#endif
3951
3952			/*
3953			 * We've basically got 3 bytes, or 24 bits for the
3954			 * cylinder size in the mode page.  If we're over,
3955			 * just round down to 2^24.
3956			 */
3957			if (cylinders > 0xffffff)
3958				cylinders = 0xffffff;
3959
3960			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3961				CTL_PAGE_DEFAULT];
3962			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3963
3964			if ((value = ctl_get_opt(&lun->be_lun->options,
3965			    "rpm")) != NULL) {
3966				scsi_ulto2b(strtol(value, NULL, 0),
3967				     rigid_disk_page->rotation_rate);
3968			}
3969
3970			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3971			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3972			       sizeof(rigid_disk_page_default));
3973			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3974			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3975			       sizeof(rigid_disk_page_default));
3976
3977			page_index->page_data =
3978				(uint8_t *)lun->mode_pages.rigid_disk_page;
3979			break;
3980		}
3981		case SMS_CACHING_PAGE: {
3982			struct scsi_caching_page *caching_page;
3983
3984			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3985				panic("invalid subpage value %d",
3986				      page_index->subpage);
3987			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3988			       &caching_page_default,
3989			       sizeof(caching_page_default));
3990			memcpy(&lun->mode_pages.caching_page[
3991			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3992			       sizeof(caching_page_changeable));
3993			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3994			       &caching_page_default,
3995			       sizeof(caching_page_default));
3996			caching_page = &lun->mode_pages.caching_page[
3997			    CTL_PAGE_SAVED];
3998			value = ctl_get_opt(&lun->be_lun->options, "writecache");
3999			if (value != NULL && strcmp(value, "off") == 0)
4000				caching_page->flags1 &= ~SCP_WCE;
4001			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4002			if (value != NULL && strcmp(value, "off") == 0)
4003				caching_page->flags1 |= SCP_RCD;
4004			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4005			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4006			       sizeof(caching_page_default));
4007			page_index->page_data =
4008				(uint8_t *)lun->mode_pages.caching_page;
4009			break;
4010		}
4011		case SMS_CONTROL_MODE_PAGE: {
4012			switch (page_index->subpage) {
4013			case SMS_SUBPAGE_PAGE_0: {
4014				struct scsi_control_page *control_page;
4015
4016				memcpy(&lun->mode_pages.control_page[
4017				    CTL_PAGE_DEFAULT],
4018				       &control_page_default,
4019				       sizeof(control_page_default));
4020				memcpy(&lun->mode_pages.control_page[
4021				    CTL_PAGE_CHANGEABLE],
4022				       &control_page_changeable,
4023				       sizeof(control_page_changeable));
4024				memcpy(&lun->mode_pages.control_page[
4025				    CTL_PAGE_SAVED],
4026				       &control_page_default,
4027				       sizeof(control_page_default));
4028				control_page = &lun->mode_pages.control_page[
4029				    CTL_PAGE_SAVED];
4030				value = ctl_get_opt(&lun->be_lun->options,
4031				    "reordering");
4032				if (value != NULL &&
4033				    strcmp(value, "unrestricted") == 0) {
4034					control_page->queue_flags &=
4035					    ~SCP_QUEUE_ALG_MASK;
4036					control_page->queue_flags |=
4037					    SCP_QUEUE_ALG_UNRESTRICTED;
4038				}
4039				memcpy(&lun->mode_pages.control_page[
4040				    CTL_PAGE_CURRENT],
4041				       &lun->mode_pages.control_page[
4042				    CTL_PAGE_SAVED],
4043				       sizeof(control_page_default));
4044				page_index->page_data =
4045				    (uint8_t *)lun->mode_pages.control_page;
4046				break;
4047			}
4048			case 0x01:
4049				memcpy(&lun->mode_pages.control_ext_page[
4050				    CTL_PAGE_DEFAULT],
4051				       &control_ext_page_default,
4052				       sizeof(control_ext_page_default));
4053				memcpy(&lun->mode_pages.control_ext_page[
4054				    CTL_PAGE_CHANGEABLE],
4055				       &control_ext_page_changeable,
4056				       sizeof(control_ext_page_changeable));
4057				memcpy(&lun->mode_pages.control_ext_page[
4058				    CTL_PAGE_SAVED],
4059				       &control_ext_page_default,
4060				       sizeof(control_ext_page_default));
4061				memcpy(&lun->mode_pages.control_ext_page[
4062				    CTL_PAGE_CURRENT],
4063				       &lun->mode_pages.control_ext_page[
4064				    CTL_PAGE_SAVED],
4065				       sizeof(control_ext_page_default));
4066				page_index->page_data =
4067				    (uint8_t *)lun->mode_pages.control_ext_page;
4068				break;
4069			}
4070			break;
4071		}
4072		case SMS_INFO_EXCEPTIONS_PAGE: {
4073			switch (page_index->subpage) {
4074			case SMS_SUBPAGE_PAGE_0:
4075				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4076				       &ie_page_default,
4077				       sizeof(ie_page_default));
4078				memcpy(&lun->mode_pages.ie_page[
4079				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4080				       sizeof(ie_page_changeable));
4081				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4082				       &ie_page_default,
4083				       sizeof(ie_page_default));
4084				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4085				       &ie_page_default,
4086				       sizeof(ie_page_default));
4087				page_index->page_data =
4088					(uint8_t *)lun->mode_pages.ie_page;
4089				break;
4090			case 0x02: {
4091				struct ctl_logical_block_provisioning_page *page;
4092
4093				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4094				       &lbp_page_default,
4095				       sizeof(lbp_page_default));
4096				memcpy(&lun->mode_pages.lbp_page[
4097				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4098				       sizeof(lbp_page_changeable));
4099				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4100				       &lbp_page_default,
4101				       sizeof(lbp_page_default));
4102				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4103				value = ctl_get_opt(&lun->be_lun->options,
4104				    "avail-threshold");
4105				if (value != NULL &&
4106				    ctl_expand_number(value, &ival) == 0) {
4107					page->descr[0].flags |= SLBPPD_ENABLED |
4108					    SLBPPD_ARMING_DEC;
4109					if (lun->be_lun->blocksize)
4110						ival /= lun->be_lun->blocksize;
4111					else
4112						ival /= 512;
4113					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4114					    page->descr[0].count);
4115				}
4116				value = ctl_get_opt(&lun->be_lun->options,
4117				    "used-threshold");
4118				if (value != NULL &&
4119				    ctl_expand_number(value, &ival) == 0) {
4120					page->descr[1].flags |= SLBPPD_ENABLED |
4121					    SLBPPD_ARMING_INC;
4122					if (lun->be_lun->blocksize)
4123						ival /= lun->be_lun->blocksize;
4124					else
4125						ival /= 512;
4126					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4127					    page->descr[1].count);
4128				}
4129				value = ctl_get_opt(&lun->be_lun->options,
4130				    "pool-avail-threshold");
4131				if (value != NULL &&
4132				    ctl_expand_number(value, &ival) == 0) {
4133					page->descr[2].flags |= SLBPPD_ENABLED |
4134					    SLBPPD_ARMING_DEC;
4135					if (lun->be_lun->blocksize)
4136						ival /= lun->be_lun->blocksize;
4137					else
4138						ival /= 512;
4139					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4140					    page->descr[2].count);
4141				}
4142				value = ctl_get_opt(&lun->be_lun->options,
4143				    "pool-used-threshold");
4144				if (value != NULL &&
4145				    ctl_expand_number(value, &ival) == 0) {
4146					page->descr[3].flags |= SLBPPD_ENABLED |
4147					    SLBPPD_ARMING_INC;
4148					if (lun->be_lun->blocksize)
4149						ival /= lun->be_lun->blocksize;
4150					else
4151						ival /= 512;
4152					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4153					    page->descr[3].count);
4154				}
4155				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4156				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4157				       sizeof(lbp_page_default));
4158				page_index->page_data =
4159					(uint8_t *)lun->mode_pages.lbp_page;
4160			}}
4161			break;
4162		}
4163		case SMS_CDDVD_CAPS_PAGE:{
4164			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4165			       &cddvd_page_default,
4166			       sizeof(cddvd_page_default));
4167			memcpy(&lun->mode_pages.cddvd_page[
4168			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4169			       sizeof(cddvd_page_changeable));
4170			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4171			       &cddvd_page_default,
4172			       sizeof(cddvd_page_default));
4173			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4174			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4175			       sizeof(cddvd_page_default));
4176			page_index->page_data =
4177				(uint8_t *)lun->mode_pages.cddvd_page;
4178			break;
4179		}
4180		case SMS_VENDOR_SPECIFIC_PAGE:{
4181			switch (page_index->subpage) {
4182			case DBGCNF_SUBPAGE_CODE: {
4183				memcpy(&lun->mode_pages.debugconf_subpage[
4184				       CTL_PAGE_CURRENT],
4185				       &debugconf_page_default,
4186				       sizeof(debugconf_page_default));
4187				memcpy(&lun->mode_pages.debugconf_subpage[
4188				       CTL_PAGE_CHANGEABLE],
4189				       &debugconf_page_changeable,
4190				       sizeof(debugconf_page_changeable));
4191				memcpy(&lun->mode_pages.debugconf_subpage[
4192				       CTL_PAGE_DEFAULT],
4193				       &debugconf_page_default,
4194				       sizeof(debugconf_page_default));
4195				memcpy(&lun->mode_pages.debugconf_subpage[
4196				       CTL_PAGE_SAVED],
4197				       &debugconf_page_default,
4198				       sizeof(debugconf_page_default));
4199				page_index->page_data =
4200				    (uint8_t *)lun->mode_pages.debugconf_subpage;
4201				break;
4202			}
4203			default:
4204				panic("invalid subpage value %d",
4205				      page_index->subpage);
4206				break;
4207			}
4208   			break;
4209		}
4210		default:
4211			panic("invalid page value %d",
4212			      page_index->page_code & SMPH_PC_MASK);
4213			break;
4214    	}
4215	}
4216
4217	return (CTL_RETVAL_COMPLETE);
4218}
4219
4220static int
4221ctl_init_log_page_index(struct ctl_lun *lun)
4222{
4223	struct ctl_page_index *page_index;
4224	int i, j, k, prev;
4225
4226	memcpy(&lun->log_pages.index, log_page_index_template,
4227	       sizeof(log_page_index_template));
4228
4229	prev = -1;
4230	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4231
4232		page_index = &lun->log_pages.index[i];
4233		if (lun->be_lun->lun_type == T_DIRECT &&
4234		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4235			continue;
4236		if (lun->be_lun->lun_type == T_PROCESSOR &&
4237		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4238			continue;
4239		if (lun->be_lun->lun_type == T_CDROM &&
4240		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4241			continue;
4242
4243		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4244		    lun->backend->lun_attr == NULL)
4245			continue;
4246
4247		if (page_index->page_code != prev) {
4248			lun->log_pages.pages_page[j] = page_index->page_code;
4249			prev = page_index->page_code;
4250			j++;
4251		}
4252		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4253		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4254		k++;
4255	}
4256	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4257	lun->log_pages.index[0].page_len = j;
4258	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4259	lun->log_pages.index[1].page_len = k * 2;
4260	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4261	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4262	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4263	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4264
4265	return (CTL_RETVAL_COMPLETE);
4266}
4267
4268static int
4269hex2bin(const char *str, uint8_t *buf, int buf_size)
4270{
4271	int i;
4272	u_char c;
4273
4274	memset(buf, 0, buf_size);
4275	while (isspace(str[0]))
4276		str++;
4277	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4278		str += 2;
4279	buf_size *= 2;
4280	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4281		c = str[i];
4282		if (isdigit(c))
4283			c -= '0';
4284		else if (isalpha(c))
4285			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4286		else
4287			break;
4288		if (c >= 16)
4289			break;
4290		if ((i & 1) == 0)
4291			buf[i / 2] |= (c << 4);
4292		else
4293			buf[i / 2] |= c;
4294	}
4295	return ((i + 1) / 2);
4296}
4297
4298/*
4299 * LUN allocation.
4300 *
4301 * Requirements:
4302 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4303 *   wants us to allocate the LUN and he can block.
4304 * - ctl_softc is always set
4305 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4306 *
4307 * Returns 0 for success, non-zero (errno) for failure.
4308 */
4309static int
4310ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4311	      struct ctl_be_lun *const be_lun)
4312{
4313	struct ctl_lun *nlun, *lun;
4314	struct scsi_vpd_id_descriptor *desc;
4315	struct scsi_vpd_id_t10 *t10id;
4316	const char *eui, *naa, *scsiname, *vendor, *value;
4317	int lun_number, i, lun_malloced;
4318	int devidlen, idlen1, idlen2 = 0, len;
4319
4320	if (be_lun == NULL)
4321		return (EINVAL);
4322
4323	/*
4324	 * We currently only support Direct Access or Processor LUN types.
4325	 */
4326	switch (be_lun->lun_type) {
4327	case T_DIRECT:
4328	case T_PROCESSOR:
4329	case T_CDROM:
4330		break;
4331	case T_SEQUENTIAL:
4332	case T_CHANGER:
4333	default:
4334		be_lun->lun_config_status(be_lun->be_lun,
4335					  CTL_LUN_CONFIG_FAILURE);
4336		break;
4337	}
4338	if (ctl_lun == NULL) {
4339		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4340		lun_malloced = 1;
4341	} else {
4342		lun_malloced = 0;
4343		lun = ctl_lun;
4344	}
4345
4346	memset(lun, 0, sizeof(*lun));
4347	if (lun_malloced)
4348		lun->flags = CTL_LUN_MALLOCED;
4349
4350	/* Generate LUN ID. */
4351	devidlen = max(CTL_DEVID_MIN_LEN,
4352	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4353	idlen1 = sizeof(*t10id) + devidlen;
4354	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4355	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4356	if (scsiname != NULL) {
4357		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4358		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4359	}
4360	eui = ctl_get_opt(&be_lun->options, "eui");
4361	if (eui != NULL) {
4362		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4363	}
4364	naa = ctl_get_opt(&be_lun->options, "naa");
4365	if (naa != NULL) {
4366		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4367	}
4368	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4369	    M_CTL, M_WAITOK | M_ZERO);
4370	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4371	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4372	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4373	desc->length = idlen1;
4374	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4375	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4376	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4377		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4378	} else {
4379		strncpy(t10id->vendor, vendor,
4380		    min(sizeof(t10id->vendor), strlen(vendor)));
4381	}
4382	strncpy((char *)t10id->vendor_spec_id,
4383	    (char *)be_lun->device_id, devidlen);
4384	if (scsiname != NULL) {
4385		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4386		    desc->length);
4387		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4388		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4389		    SVPD_ID_TYPE_SCSI_NAME;
4390		desc->length = idlen2;
4391		strlcpy(desc->identifier, scsiname, idlen2);
4392	}
4393	if (eui != NULL) {
4394		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4395		    desc->length);
4396		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4397		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4398		    SVPD_ID_TYPE_EUI64;
4399		desc->length = hex2bin(eui, desc->identifier, 16);
4400		desc->length = desc->length > 12 ? 16 :
4401		    (desc->length > 8 ? 12 : 8);
4402		len -= 16 - desc->length;
4403	}
4404	if (naa != NULL) {
4405		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4406		    desc->length);
4407		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4408		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4409		    SVPD_ID_TYPE_NAA;
4410		desc->length = hex2bin(naa, desc->identifier, 16);
4411		desc->length = desc->length > 8 ? 16 : 8;
4412		len -= 16 - desc->length;
4413	}
4414	lun->lun_devid->len = len;
4415
4416	mtx_lock(&ctl_softc->ctl_lock);
4417	/*
4418	 * See if the caller requested a particular LUN number.  If so, see
4419	 * if it is available.  Otherwise, allocate the first available LUN.
4420	 */
4421	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4422		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4423		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4424			mtx_unlock(&ctl_softc->ctl_lock);
4425			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4426				printf("ctl: requested LUN ID %d is higher "
4427				       "than CTL_MAX_LUNS - 1 (%d)\n",
4428				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4429			} else {
4430				/*
4431				 * XXX KDM return an error, or just assign
4432				 * another LUN ID in this case??
4433				 */
4434				printf("ctl: requested LUN ID %d is already "
4435				       "in use\n", be_lun->req_lun_id);
4436			}
4437			if (lun->flags & CTL_LUN_MALLOCED)
4438				free(lun, M_CTL);
4439			be_lun->lun_config_status(be_lun->be_lun,
4440						  CTL_LUN_CONFIG_FAILURE);
4441			return (ENOSPC);
4442		}
4443		lun_number = be_lun->req_lun_id;
4444	} else {
4445		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4446		if (lun_number == -1) {
4447			mtx_unlock(&ctl_softc->ctl_lock);
4448			printf("ctl: can't allocate LUN, out of LUNs\n");
4449			if (lun->flags & CTL_LUN_MALLOCED)
4450				free(lun, M_CTL);
4451			be_lun->lun_config_status(be_lun->be_lun,
4452						  CTL_LUN_CONFIG_FAILURE);
4453			return (ENOSPC);
4454		}
4455	}
4456	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4457
4458	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4459	lun->lun = lun_number;
4460	lun->be_lun = be_lun;
4461	/*
4462	 * The processor LUN is always enabled.  Disk LUNs come on line
4463	 * disabled, and must be enabled by the backend.
4464	 */
4465	lun->flags |= CTL_LUN_DISABLED;
4466	lun->backend = be_lun->be;
4467	be_lun->ctl_lun = lun;
4468	be_lun->lun_id = lun_number;
4469	atomic_add_int(&be_lun->be->num_luns, 1);
4470	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4471		lun->flags |= CTL_LUN_EJECTED;
4472	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4473		lun->flags |= CTL_LUN_NO_MEDIA;
4474	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4475		lun->flags |= CTL_LUN_STOPPED;
4476
4477	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4478		lun->flags |= CTL_LUN_PRIMARY_SC;
4479
4480	value = ctl_get_opt(&be_lun->options, "removable");
4481	if (value != NULL) {
4482		if (strcmp(value, "on") == 0)
4483			lun->flags |= CTL_LUN_REMOVABLE;
4484	} else if (be_lun->lun_type == T_CDROM)
4485		lun->flags |= CTL_LUN_REMOVABLE;
4486
4487	lun->ctl_softc = ctl_softc;
4488#ifdef CTL_TIME_IO
4489	lun->last_busy = getsbinuptime();
4490#endif
4491	TAILQ_INIT(&lun->ooa_queue);
4492	TAILQ_INIT(&lun->blocked_queue);
4493	STAILQ_INIT(&lun->error_list);
4494	ctl_tpc_lun_init(lun);
4495
4496	/*
4497	 * Initialize the mode and log page index.
4498	 */
4499	ctl_init_page_index(lun);
4500	ctl_init_log_page_index(lun);
4501
4502	/*
4503	 * Now, before we insert this lun on the lun list, set the lun
4504	 * inventory changed UA for all other luns.
4505	 */
4506	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4507		mtx_lock(&nlun->lun_lock);
4508		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4509		mtx_unlock(&nlun->lun_lock);
4510	}
4511
4512	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4513
4514	ctl_softc->ctl_luns[lun_number] = lun;
4515
4516	ctl_softc->num_luns++;
4517
4518	/* Setup statistics gathering */
4519	lun->stats.device_type = be_lun->lun_type;
4520	lun->stats.lun_number = lun_number;
4521	lun->stats.blocksize = be_lun->blocksize;
4522	if (be_lun->blocksize == 0)
4523		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4524	for (i = 0;i < CTL_MAX_PORTS;i++)
4525		lun->stats.ports[i].targ_port = i;
4526
4527	mtx_unlock(&ctl_softc->ctl_lock);
4528
4529	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4530	return (0);
4531}
4532
4533/*
4534 * Delete a LUN.
4535 * Assumptions:
4536 * - LUN has already been marked invalid and any pending I/O has been taken
4537 *   care of.
4538 */
4539static int
4540ctl_free_lun(struct ctl_lun *lun)
4541{
4542	struct ctl_softc *softc;
4543	struct ctl_lun *nlun;
4544	int i;
4545
4546	softc = lun->ctl_softc;
4547
4548	mtx_assert(&softc->ctl_lock, MA_OWNED);
4549
4550	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4551
4552	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4553
4554	softc->ctl_luns[lun->lun] = NULL;
4555
4556	if (!TAILQ_EMPTY(&lun->ooa_queue))
4557		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4558
4559	softc->num_luns--;
4560
4561	/*
4562	 * Tell the backend to free resources, if this LUN has a backend.
4563	 */
4564	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4565	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4566
4567	ctl_tpc_lun_shutdown(lun);
4568	mtx_destroy(&lun->lun_lock);
4569	free(lun->lun_devid, M_CTL);
4570	for (i = 0; i < CTL_MAX_PORTS; i++)
4571		free(lun->pending_ua[i], M_CTL);
4572	for (i = 0; i < CTL_MAX_PORTS; i++)
4573		free(lun->pr_keys[i], M_CTL);
4574	free(lun->write_buffer, M_CTL);
4575	if (lun->flags & CTL_LUN_MALLOCED)
4576		free(lun, M_CTL);
4577
4578	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4579		mtx_lock(&nlun->lun_lock);
4580		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4581		mtx_unlock(&nlun->lun_lock);
4582	}
4583
4584	return (0);
4585}
4586
4587static void
4588ctl_create_lun(struct ctl_be_lun *be_lun)
4589{
4590
4591	/*
4592	 * ctl_alloc_lun() should handle all potential failure cases.
4593	 */
4594	ctl_alloc_lun(control_softc, NULL, be_lun);
4595}
4596
4597int
4598ctl_add_lun(struct ctl_be_lun *be_lun)
4599{
4600	struct ctl_softc *softc = control_softc;
4601
4602	mtx_lock(&softc->ctl_lock);
4603	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4604	mtx_unlock(&softc->ctl_lock);
4605	wakeup(&softc->pending_lun_queue);
4606
4607	return (0);
4608}
4609
4610int
4611ctl_enable_lun(struct ctl_be_lun *be_lun)
4612{
4613	struct ctl_softc *softc;
4614	struct ctl_port *port, *nport;
4615	struct ctl_lun *lun;
4616	int retval;
4617
4618	lun = (struct ctl_lun *)be_lun->ctl_lun;
4619	softc = lun->ctl_softc;
4620
4621	mtx_lock(&softc->ctl_lock);
4622	mtx_lock(&lun->lun_lock);
4623	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4624		/*
4625		 * eh?  Why did we get called if the LUN is already
4626		 * enabled?
4627		 */
4628		mtx_unlock(&lun->lun_lock);
4629		mtx_unlock(&softc->ctl_lock);
4630		return (0);
4631	}
4632	lun->flags &= ~CTL_LUN_DISABLED;
4633	mtx_unlock(&lun->lun_lock);
4634
4635	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4636		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4637		    port->lun_map != NULL || port->lun_enable == NULL)
4638			continue;
4639
4640		/*
4641		 * Drop the lock while we call the FETD's enable routine.
4642		 * This can lead to a callback into CTL (at least in the
4643		 * case of the internal initiator frontend.
4644		 */
4645		mtx_unlock(&softc->ctl_lock);
4646		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4647		mtx_lock(&softc->ctl_lock);
4648		if (retval != 0) {
4649			printf("%s: FETD %s port %d returned error "
4650			       "%d for lun_enable on lun %jd\n",
4651			       __func__, port->port_name, port->targ_port,
4652			       retval, (intmax_t)lun->lun);
4653		}
4654	}
4655
4656	mtx_unlock(&softc->ctl_lock);
4657	ctl_isc_announce_lun(lun);
4658
4659	return (0);
4660}
4661
4662int
4663ctl_disable_lun(struct ctl_be_lun *be_lun)
4664{
4665	struct ctl_softc *softc;
4666	struct ctl_port *port;
4667	struct ctl_lun *lun;
4668	int retval;
4669
4670	lun = (struct ctl_lun *)be_lun->ctl_lun;
4671	softc = lun->ctl_softc;
4672
4673	mtx_lock(&softc->ctl_lock);
4674	mtx_lock(&lun->lun_lock);
4675	if (lun->flags & CTL_LUN_DISABLED) {
4676		mtx_unlock(&lun->lun_lock);
4677		mtx_unlock(&softc->ctl_lock);
4678		return (0);
4679	}
4680	lun->flags |= CTL_LUN_DISABLED;
4681	mtx_unlock(&lun->lun_lock);
4682
4683	STAILQ_FOREACH(port, &softc->port_list, links) {
4684		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4685		    port->lun_map != NULL || port->lun_disable == NULL)
4686			continue;
4687
4688		/*
4689		 * Drop the lock before we call the frontend's disable
4690		 * routine, to avoid lock order reversals.
4691		 *
4692		 * XXX KDM what happens if the frontend list changes while
4693		 * we're traversing it?  It's unlikely, but should be handled.
4694		 */
4695		mtx_unlock(&softc->ctl_lock);
4696		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4697		mtx_lock(&softc->ctl_lock);
4698		if (retval != 0) {
4699			printf("%s: FETD %s port %d returned error "
4700			       "%d for lun_disable on lun %jd\n",
4701			       __func__, port->port_name, port->targ_port,
4702			       retval, (intmax_t)lun->lun);
4703		}
4704	}
4705
4706	mtx_unlock(&softc->ctl_lock);
4707	ctl_isc_announce_lun(lun);
4708
4709	return (0);
4710}
4711
4712int
4713ctl_start_lun(struct ctl_be_lun *be_lun)
4714{
4715	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4716
4717	mtx_lock(&lun->lun_lock);
4718	lun->flags &= ~CTL_LUN_STOPPED;
4719	mtx_unlock(&lun->lun_lock);
4720	return (0);
4721}
4722
4723int
4724ctl_stop_lun(struct ctl_be_lun *be_lun)
4725{
4726	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4727
4728	mtx_lock(&lun->lun_lock);
4729	lun->flags |= CTL_LUN_STOPPED;
4730	mtx_unlock(&lun->lun_lock);
4731	return (0);
4732}
4733
4734int
4735ctl_lun_no_media(struct ctl_be_lun *be_lun)
4736{
4737	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4738
4739	mtx_lock(&lun->lun_lock);
4740	lun->flags |= CTL_LUN_NO_MEDIA;
4741	mtx_unlock(&lun->lun_lock);
4742	return (0);
4743}
4744
4745int
4746ctl_lun_has_media(struct ctl_be_lun *be_lun)
4747{
4748	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4749	union ctl_ha_msg msg;
4750
4751	mtx_lock(&lun->lun_lock);
4752	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4753	if (lun->flags & CTL_LUN_REMOVABLE)
4754		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4755	mtx_unlock(&lun->lun_lock);
4756	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4757	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4758		bzero(&msg.ua, sizeof(msg.ua));
4759		msg.hdr.msg_type = CTL_MSG_UA;
4760		msg.hdr.nexus.initid = -1;
4761		msg.hdr.nexus.targ_port = -1;
4762		msg.hdr.nexus.targ_lun = lun->lun;
4763		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4764		msg.ua.ua_all = 1;
4765		msg.ua.ua_set = 1;
4766		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4767		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4768		    M_WAITOK);
4769	}
4770	return (0);
4771}
4772
4773int
4774ctl_lun_ejected(struct ctl_be_lun *be_lun)
4775{
4776	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4777
4778	mtx_lock(&lun->lun_lock);
4779	lun->flags |= CTL_LUN_EJECTED;
4780	mtx_unlock(&lun->lun_lock);
4781	return (0);
4782}
4783
4784int
4785ctl_lun_primary(struct ctl_be_lun *be_lun)
4786{
4787	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4788
4789	mtx_lock(&lun->lun_lock);
4790	lun->flags |= CTL_LUN_PRIMARY_SC;
4791	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4792	mtx_unlock(&lun->lun_lock);
4793	ctl_isc_announce_lun(lun);
4794	return (0);
4795}
4796
4797int
4798ctl_lun_secondary(struct ctl_be_lun *be_lun)
4799{
4800	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4801
4802	mtx_lock(&lun->lun_lock);
4803	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4804	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4805	mtx_unlock(&lun->lun_lock);
4806	ctl_isc_announce_lun(lun);
4807	return (0);
4808}
4809
4810int
4811ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4812{
4813	struct ctl_softc *softc;
4814	struct ctl_lun *lun;
4815
4816	lun = (struct ctl_lun *)be_lun->ctl_lun;
4817	softc = lun->ctl_softc;
4818
4819	mtx_lock(&lun->lun_lock);
4820
4821	/*
4822	 * The LUN needs to be disabled before it can be marked invalid.
4823	 */
4824	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4825		mtx_unlock(&lun->lun_lock);
4826		return (-1);
4827	}
4828	/*
4829	 * Mark the LUN invalid.
4830	 */
4831	lun->flags |= CTL_LUN_INVALID;
4832
4833	/*
4834	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4835	 * If we have something in the OOA queue, we'll free it when the
4836	 * last I/O completes.
4837	 */
4838	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4839		mtx_unlock(&lun->lun_lock);
4840		mtx_lock(&softc->ctl_lock);
4841		ctl_free_lun(lun);
4842		mtx_unlock(&softc->ctl_lock);
4843	} else
4844		mtx_unlock(&lun->lun_lock);
4845
4846	return (0);
4847}
4848
4849void
4850ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4851{
4852	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4853	union ctl_ha_msg msg;
4854
4855	mtx_lock(&lun->lun_lock);
4856	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4857	mtx_unlock(&lun->lun_lock);
4858	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4859		/* Send msg to other side. */
4860		bzero(&msg.ua, sizeof(msg.ua));
4861		msg.hdr.msg_type = CTL_MSG_UA;
4862		msg.hdr.nexus.initid = -1;
4863		msg.hdr.nexus.targ_port = -1;
4864		msg.hdr.nexus.targ_lun = lun->lun;
4865		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4866		msg.ua.ua_all = 1;
4867		msg.ua.ua_set = 1;
4868		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4869		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4870		    M_WAITOK);
4871	}
4872}
4873
4874/*
4875 * Backend "memory move is complete" callback for requests that never
4876 * make it down to say RAIDCore's configuration code.
4877 */
4878int
4879ctl_config_move_done(union ctl_io *io)
4880{
4881	int retval;
4882
4883	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4884	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4885	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4886
4887	if ((io->io_hdr.port_status != 0) &&
4888	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4889	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4890		/*
4891		 * For hardware error sense keys, the sense key
4892		 * specific value is defined to be a retry count,
4893		 * but we use it to pass back an internal FETD
4894		 * error code.  XXX KDM  Hopefully the FETD is only
4895		 * using 16 bits for an error code, since that's
4896		 * all the space we have in the sks field.
4897		 */
4898		ctl_set_internal_failure(&io->scsiio,
4899					 /*sks_valid*/ 1,
4900					 /*retry_count*/
4901					 io->io_hdr.port_status);
4902	}
4903
4904	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4905		ctl_data_print(io);
4906	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4907	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4908	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4909	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4910		/*
4911		 * XXX KDM just assuming a single pointer here, and not a
4912		 * S/G list.  If we start using S/G lists for config data,
4913		 * we'll need to know how to clean them up here as well.
4914		 */
4915		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4916			free(io->scsiio.kern_data_ptr, M_CTL);
4917		ctl_done(io);
4918		retval = CTL_RETVAL_COMPLETE;
4919	} else {
4920		/*
4921		 * XXX KDM now we need to continue data movement.  Some
4922		 * options:
4923		 * - call ctl_scsiio() again?  We don't do this for data
4924		 *   writes, because for those at least we know ahead of
4925		 *   time where the write will go and how long it is.  For
4926		 *   config writes, though, that information is largely
4927		 *   contained within the write itself, thus we need to
4928		 *   parse out the data again.
4929		 *
4930		 * - Call some other function once the data is in?
4931		 */
4932
4933		/*
4934		 * XXX KDM call ctl_scsiio() again for now, and check flag
4935		 * bits to see whether we're allocated or not.
4936		 */
4937		retval = ctl_scsiio(&io->scsiio);
4938	}
4939	return (retval);
4940}
4941
4942/*
4943 * This gets called by a backend driver when it is done with a
4944 * data_submit method.
4945 */
4946void
4947ctl_data_submit_done(union ctl_io *io)
4948{
4949	/*
4950	 * If the IO_CONT flag is set, we need to call the supplied
4951	 * function to continue processing the I/O, instead of completing
4952	 * the I/O just yet.
4953	 *
4954	 * If there is an error, though, we don't want to keep processing.
4955	 * Instead, just send status back to the initiator.
4956	 */
4957	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4958	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4959	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4960	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4961		io->scsiio.io_cont(io);
4962		return;
4963	}
4964	ctl_done(io);
4965}
4966
4967/*
4968 * This gets called by a backend driver when it is done with a
4969 * configuration write.
4970 */
4971void
4972ctl_config_write_done(union ctl_io *io)
4973{
4974	uint8_t *buf;
4975
4976	/*
4977	 * If the IO_CONT flag is set, we need to call the supplied
4978	 * function to continue processing the I/O, instead of completing
4979	 * the I/O just yet.
4980	 *
4981	 * If there is an error, though, we don't want to keep processing.
4982	 * Instead, just send status back to the initiator.
4983	 */
4984	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4985	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4986	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4987	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4988		io->scsiio.io_cont(io);
4989		return;
4990	}
4991	/*
4992	 * Since a configuration write can be done for commands that actually
4993	 * have data allocated, like write buffer, and commands that have
4994	 * no data, like start/stop unit, we need to check here.
4995	 */
4996	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4997		buf = io->scsiio.kern_data_ptr;
4998	else
4999		buf = NULL;
5000	ctl_done(io);
5001	if (buf)
5002		free(buf, M_CTL);
5003}
5004
5005void
5006ctl_config_read_done(union ctl_io *io)
5007{
5008	uint8_t *buf;
5009
5010	/*
5011	 * If there is some error -- we are done, skip data transfer.
5012	 */
5013	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5014	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5015	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5016		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5017			buf = io->scsiio.kern_data_ptr;
5018		else
5019			buf = NULL;
5020		ctl_done(io);
5021		if (buf)
5022			free(buf, M_CTL);
5023		return;
5024	}
5025
5026	/*
5027	 * If the IO_CONT flag is set, we need to call the supplied
5028	 * function to continue processing the I/O, instead of completing
5029	 * the I/O just yet.
5030	 */
5031	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5032		io->scsiio.io_cont(io);
5033		return;
5034	}
5035
5036	ctl_datamove(io);
5037}
5038
5039/*
5040 * SCSI release command.
5041 */
5042int
5043ctl_scsi_release(struct ctl_scsiio *ctsio)
5044{
5045	struct ctl_lun *lun;
5046	uint32_t residx;
5047
5048	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5049
5050	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5051	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5052
5053	/*
5054	 * XXX KDM right now, we only support LUN reservation.  We don't
5055	 * support 3rd party reservations, or extent reservations, which
5056	 * might actually need the parameter list.  If we've gotten this
5057	 * far, we've got a LUN reservation.  Anything else got kicked out
5058	 * above.  So, according to SPC, ignore the length.
5059	 */
5060
5061	mtx_lock(&lun->lun_lock);
5062
5063	/*
5064	 * According to SPC, it is not an error for an intiator to attempt
5065	 * to release a reservation on a LUN that isn't reserved, or that
5066	 * is reserved by another initiator.  The reservation can only be
5067	 * released, though, by the initiator who made it or by one of
5068	 * several reset type events.
5069	 */
5070	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5071			lun->flags &= ~CTL_LUN_RESERVED;
5072
5073	mtx_unlock(&lun->lun_lock);
5074
5075	ctl_set_success(ctsio);
5076	ctl_done((union ctl_io *)ctsio);
5077	return (CTL_RETVAL_COMPLETE);
5078}
5079
5080int
5081ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5082{
5083	struct ctl_lun *lun;
5084	uint32_t residx;
5085
5086	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5087
5088	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5089	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5090
5091	/*
5092	 * XXX KDM right now, we only support LUN reservation.  We don't
5093	 * support 3rd party reservations, or extent reservations, which
5094	 * might actually need the parameter list.  If we've gotten this
5095	 * far, we've got a LUN reservation.  Anything else got kicked out
5096	 * above.  So, according to SPC, ignore the length.
5097	 */
5098
5099	mtx_lock(&lun->lun_lock);
5100	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5101		ctl_set_reservation_conflict(ctsio);
5102		goto bailout;
5103	}
5104
5105	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5106	if (lun->flags & CTL_LUN_PR_RESERVED) {
5107		ctl_set_success(ctsio);
5108		goto bailout;
5109	}
5110
5111	lun->flags |= CTL_LUN_RESERVED;
5112	lun->res_idx = residx;
5113	ctl_set_success(ctsio);
5114
5115bailout:
5116	mtx_unlock(&lun->lun_lock);
5117	ctl_done((union ctl_io *)ctsio);
5118	return (CTL_RETVAL_COMPLETE);
5119}
5120
5121int
5122ctl_start_stop(struct ctl_scsiio *ctsio)
5123{
5124	struct scsi_start_stop_unit *cdb;
5125	struct ctl_lun *lun;
5126	int retval;
5127
5128	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5129
5130	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5131	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5132
5133	if ((cdb->how & SSS_PC_MASK) == 0) {
5134		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5135		    (cdb->how & SSS_START) == 0) {
5136			uint32_t residx;
5137
5138			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5139			if (ctl_get_prkey(lun, residx) == 0 ||
5140			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5141
5142				ctl_set_reservation_conflict(ctsio);
5143				ctl_done((union ctl_io *)ctsio);
5144				return (CTL_RETVAL_COMPLETE);
5145			}
5146		}
5147
5148		if ((cdb->how & SSS_LOEJ) &&
5149		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5150			ctl_set_invalid_field(ctsio,
5151					      /*sks_valid*/ 1,
5152					      /*command*/ 1,
5153					      /*field*/ 4,
5154					      /*bit_valid*/ 1,
5155					      /*bit*/ 1);
5156			ctl_done((union ctl_io *)ctsio);
5157			return (CTL_RETVAL_COMPLETE);
5158		}
5159
5160		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5161		    lun->prevent_count > 0) {
5162			/* "Medium removal prevented" */
5163			ctl_set_sense(ctsio, /*current_error*/ 1,
5164			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5165			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5166			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5167			ctl_done((union ctl_io *)ctsio);
5168			return (CTL_RETVAL_COMPLETE);
5169		}
5170	}
5171
5172	retval = lun->backend->config_write((union ctl_io *)ctsio);
5173	return (retval);
5174}
5175
5176int
5177ctl_prevent_allow(struct ctl_scsiio *ctsio)
5178{
5179	struct ctl_lun *lun;
5180	struct scsi_prevent *cdb;
5181	int retval;
5182	uint32_t initidx;
5183
5184	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5185
5186	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5187	cdb = (struct scsi_prevent *)ctsio->cdb;
5188
5189	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5190		ctl_set_invalid_opcode(ctsio);
5191		ctl_done((union ctl_io *)ctsio);
5192		return (CTL_RETVAL_COMPLETE);
5193	}
5194
5195	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5196	mtx_lock(&lun->lun_lock);
5197	if ((cdb->how & PR_PREVENT) &&
5198	    ctl_is_set(lun->prevent, initidx) == 0) {
5199		ctl_set_mask(lun->prevent, initidx);
5200		lun->prevent_count++;
5201	} else if ((cdb->how & PR_PREVENT) == 0 &&
5202	    ctl_is_set(lun->prevent, initidx)) {
5203		ctl_clear_mask(lun->prevent, initidx);
5204		lun->prevent_count--;
5205	}
5206	mtx_unlock(&lun->lun_lock);
5207	retval = lun->backend->config_write((union ctl_io *)ctsio);
5208	return (retval);
5209}
5210
5211/*
5212 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5213 * we don't really do anything with the LBA and length fields if the user
5214 * passes them in.  Instead we'll just flush out the cache for the entire
5215 * LUN.
5216 */
5217int
5218ctl_sync_cache(struct ctl_scsiio *ctsio)
5219{
5220	struct ctl_lun *lun;
5221	struct ctl_softc *softc;
5222	struct ctl_lba_len_flags *lbalen;
5223	uint64_t starting_lba;
5224	uint32_t block_count;
5225	int retval;
5226	uint8_t byte2;
5227
5228	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5229
5230	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5231	softc = lun->ctl_softc;
5232	retval = 0;
5233
5234	switch (ctsio->cdb[0]) {
5235	case SYNCHRONIZE_CACHE: {
5236		struct scsi_sync_cache *cdb;
5237		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5238
5239		starting_lba = scsi_4btoul(cdb->begin_lba);
5240		block_count = scsi_2btoul(cdb->lb_count);
5241		byte2 = cdb->byte2;
5242		break;
5243	}
5244	case SYNCHRONIZE_CACHE_16: {
5245		struct scsi_sync_cache_16 *cdb;
5246		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5247
5248		starting_lba = scsi_8btou64(cdb->begin_lba);
5249		block_count = scsi_4btoul(cdb->lb_count);
5250		byte2 = cdb->byte2;
5251		break;
5252	}
5253	default:
5254		ctl_set_invalid_opcode(ctsio);
5255		ctl_done((union ctl_io *)ctsio);
5256		goto bailout;
5257		break; /* NOTREACHED */
5258	}
5259
5260	/*
5261	 * We check the LBA and length, but don't do anything with them.
5262	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5263	 * get flushed.  This check will just help satisfy anyone who wants
5264	 * to see an error for an out of range LBA.
5265	 */
5266	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5267		ctl_set_lba_out_of_range(ctsio);
5268		ctl_done((union ctl_io *)ctsio);
5269		goto bailout;
5270	}
5271
5272	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5273	lbalen->lba = starting_lba;
5274	lbalen->len = block_count;
5275	lbalen->flags = byte2;
5276	retval = lun->backend->config_write((union ctl_io *)ctsio);
5277
5278bailout:
5279	return (retval);
5280}
5281
5282int
5283ctl_format(struct ctl_scsiio *ctsio)
5284{
5285	struct scsi_format *cdb;
5286	struct ctl_lun *lun;
5287	int length, defect_list_len;
5288
5289	CTL_DEBUG_PRINT(("ctl_format\n"));
5290
5291	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5292
5293	cdb = (struct scsi_format *)ctsio->cdb;
5294
5295	length = 0;
5296	if (cdb->byte2 & SF_FMTDATA) {
5297		if (cdb->byte2 & SF_LONGLIST)
5298			length = sizeof(struct scsi_format_header_long);
5299		else
5300			length = sizeof(struct scsi_format_header_short);
5301	}
5302
5303	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5304	 && (length > 0)) {
5305		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5306		ctsio->kern_data_len = length;
5307		ctsio->kern_total_len = length;
5308		ctsio->kern_data_resid = 0;
5309		ctsio->kern_rel_offset = 0;
5310		ctsio->kern_sg_entries = 0;
5311		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5312		ctsio->be_move_done = ctl_config_move_done;
5313		ctl_datamove((union ctl_io *)ctsio);
5314
5315		return (CTL_RETVAL_COMPLETE);
5316	}
5317
5318	defect_list_len = 0;
5319
5320	if (cdb->byte2 & SF_FMTDATA) {
5321		if (cdb->byte2 & SF_LONGLIST) {
5322			struct scsi_format_header_long *header;
5323
5324			header = (struct scsi_format_header_long *)
5325				ctsio->kern_data_ptr;
5326
5327			defect_list_len = scsi_4btoul(header->defect_list_len);
5328			if (defect_list_len != 0) {
5329				ctl_set_invalid_field(ctsio,
5330						      /*sks_valid*/ 1,
5331						      /*command*/ 0,
5332						      /*field*/ 2,
5333						      /*bit_valid*/ 0,
5334						      /*bit*/ 0);
5335				goto bailout;
5336			}
5337		} else {
5338			struct scsi_format_header_short *header;
5339
5340			header = (struct scsi_format_header_short *)
5341				ctsio->kern_data_ptr;
5342
5343			defect_list_len = scsi_2btoul(header->defect_list_len);
5344			if (defect_list_len != 0) {
5345				ctl_set_invalid_field(ctsio,
5346						      /*sks_valid*/ 1,
5347						      /*command*/ 0,
5348						      /*field*/ 2,
5349						      /*bit_valid*/ 0,
5350						      /*bit*/ 0);
5351				goto bailout;
5352			}
5353		}
5354	}
5355
5356	ctl_set_success(ctsio);
5357bailout:
5358
5359	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5360		free(ctsio->kern_data_ptr, M_CTL);
5361		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5362	}
5363
5364	ctl_done((union ctl_io *)ctsio);
5365	return (CTL_RETVAL_COMPLETE);
5366}
5367
5368int
5369ctl_read_buffer(struct ctl_scsiio *ctsio)
5370{
5371	struct ctl_lun *lun;
5372	uint64_t buffer_offset;
5373	uint32_t len;
5374	uint8_t byte2;
5375	static uint8_t descr[4];
5376	static uint8_t echo_descr[4] = { 0 };
5377
5378	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5379	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5380	switch (ctsio->cdb[0]) {
5381	case READ_BUFFER: {
5382		struct scsi_read_buffer *cdb;
5383
5384		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5385		buffer_offset = scsi_3btoul(cdb->offset);
5386		len = scsi_3btoul(cdb->length);
5387		byte2 = cdb->byte2;
5388		break;
5389	}
5390	case READ_BUFFER_16: {
5391		struct scsi_read_buffer_16 *cdb;
5392
5393		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5394		buffer_offset = scsi_8btou64(cdb->offset);
5395		len = scsi_4btoul(cdb->length);
5396		byte2 = cdb->byte2;
5397		break;
5398	}
5399	default: /* This shouldn't happen. */
5400		ctl_set_invalid_opcode(ctsio);
5401		ctl_done((union ctl_io *)ctsio);
5402		return (CTL_RETVAL_COMPLETE);
5403	}
5404
5405	if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5406	    (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5407	    (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5408		ctl_set_invalid_field(ctsio,
5409				      /*sks_valid*/ 1,
5410				      /*command*/ 1,
5411				      /*field*/ 1,
5412				      /*bit_valid*/ 1,
5413				      /*bit*/ 4);
5414		ctl_done((union ctl_io *)ctsio);
5415		return (CTL_RETVAL_COMPLETE);
5416	}
5417
5418	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5419	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5420		ctl_set_invalid_field(ctsio,
5421				      /*sks_valid*/ 1,
5422				      /*command*/ 1,
5423				      /*field*/ 6,
5424				      /*bit_valid*/ 0,
5425				      /*bit*/ 0);
5426		ctl_done((union ctl_io *)ctsio);
5427		return (CTL_RETVAL_COMPLETE);
5428	}
5429
5430	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5431		descr[0] = 0;
5432		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5433		ctsio->kern_data_ptr = descr;
5434		len = min(len, sizeof(descr));
5435	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5436		ctsio->kern_data_ptr = echo_descr;
5437		len = min(len, sizeof(echo_descr));
5438	} else {
5439		if (lun->write_buffer == NULL) {
5440			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5441			    M_CTL, M_WAITOK);
5442		}
5443		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5444	}
5445	ctsio->kern_data_len = len;
5446	ctsio->kern_total_len = len;
5447	ctsio->kern_data_resid = 0;
5448	ctsio->kern_rel_offset = 0;
5449	ctsio->kern_sg_entries = 0;
5450	ctl_set_success(ctsio);
5451	ctsio->be_move_done = ctl_config_move_done;
5452	ctl_datamove((union ctl_io *)ctsio);
5453	return (CTL_RETVAL_COMPLETE);
5454}
5455
5456int
5457ctl_write_buffer(struct ctl_scsiio *ctsio)
5458{
5459	struct scsi_write_buffer *cdb;
5460	struct ctl_lun *lun;
5461	int buffer_offset, len;
5462
5463	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5464
5465	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5466	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5467
5468	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5469		ctl_set_invalid_field(ctsio,
5470				      /*sks_valid*/ 1,
5471				      /*command*/ 1,
5472				      /*field*/ 1,
5473				      /*bit_valid*/ 1,
5474				      /*bit*/ 4);
5475		ctl_done((union ctl_io *)ctsio);
5476		return (CTL_RETVAL_COMPLETE);
5477	}
5478
5479	len = scsi_3btoul(cdb->length);
5480	buffer_offset = scsi_3btoul(cdb->offset);
5481
5482	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5483		ctl_set_invalid_field(ctsio,
5484				      /*sks_valid*/ 1,
5485				      /*command*/ 1,
5486				      /*field*/ 6,
5487				      /*bit_valid*/ 0,
5488				      /*bit*/ 0);
5489		ctl_done((union ctl_io *)ctsio);
5490		return (CTL_RETVAL_COMPLETE);
5491	}
5492
5493	/*
5494	 * If we've got a kernel request that hasn't been malloced yet,
5495	 * malloc it and tell the caller the data buffer is here.
5496	 */
5497	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5498		if (lun->write_buffer == NULL) {
5499			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5500			    M_CTL, M_WAITOK);
5501		}
5502		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5503		ctsio->kern_data_len = len;
5504		ctsio->kern_total_len = len;
5505		ctsio->kern_data_resid = 0;
5506		ctsio->kern_rel_offset = 0;
5507		ctsio->kern_sg_entries = 0;
5508		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5509		ctsio->be_move_done = ctl_config_move_done;
5510		ctl_datamove((union ctl_io *)ctsio);
5511
5512		return (CTL_RETVAL_COMPLETE);
5513	}
5514
5515	ctl_set_success(ctsio);
5516	ctl_done((union ctl_io *)ctsio);
5517	return (CTL_RETVAL_COMPLETE);
5518}
5519
5520int
5521ctl_write_same(struct ctl_scsiio *ctsio)
5522{
5523	struct ctl_lun *lun;
5524	struct ctl_lba_len_flags *lbalen;
5525	uint64_t lba;
5526	uint32_t num_blocks;
5527	int len, retval;
5528	uint8_t byte2;
5529
5530	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5531
5532	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5533
5534	switch (ctsio->cdb[0]) {
5535	case WRITE_SAME_10: {
5536		struct scsi_write_same_10 *cdb;
5537
5538		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5539
5540		lba = scsi_4btoul(cdb->addr);
5541		num_blocks = scsi_2btoul(cdb->length);
5542		byte2 = cdb->byte2;
5543		break;
5544	}
5545	case WRITE_SAME_16: {
5546		struct scsi_write_same_16 *cdb;
5547
5548		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5549
5550		lba = scsi_8btou64(cdb->addr);
5551		num_blocks = scsi_4btoul(cdb->length);
5552		byte2 = cdb->byte2;
5553		break;
5554	}
5555	default:
5556		/*
5557		 * We got a command we don't support.  This shouldn't
5558		 * happen, commands should be filtered out above us.
5559		 */
5560		ctl_set_invalid_opcode(ctsio);
5561		ctl_done((union ctl_io *)ctsio);
5562
5563		return (CTL_RETVAL_COMPLETE);
5564		break; /* NOTREACHED */
5565	}
5566
5567	/* ANCHOR flag can be used only together with UNMAP */
5568	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5569		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5570		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5571		ctl_done((union ctl_io *)ctsio);
5572		return (CTL_RETVAL_COMPLETE);
5573	}
5574
5575	/*
5576	 * The first check is to make sure we're in bounds, the second
5577	 * check is to catch wrap-around problems.  If the lba + num blocks
5578	 * is less than the lba, then we've wrapped around and the block
5579	 * range is invalid anyway.
5580	 */
5581	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5582	 || ((lba + num_blocks) < lba)) {
5583		ctl_set_lba_out_of_range(ctsio);
5584		ctl_done((union ctl_io *)ctsio);
5585		return (CTL_RETVAL_COMPLETE);
5586	}
5587
5588	/* Zero number of blocks means "to the last logical block" */
5589	if (num_blocks == 0) {
5590		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5591			ctl_set_invalid_field(ctsio,
5592					      /*sks_valid*/ 0,
5593					      /*command*/ 1,
5594					      /*field*/ 0,
5595					      /*bit_valid*/ 0,
5596					      /*bit*/ 0);
5597			ctl_done((union ctl_io *)ctsio);
5598			return (CTL_RETVAL_COMPLETE);
5599		}
5600		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5601	}
5602
5603	len = lun->be_lun->blocksize;
5604
5605	/*
5606	 * If we've got a kernel request that hasn't been malloced yet,
5607	 * malloc it and tell the caller the data buffer is here.
5608	 */
5609	if ((byte2 & SWS_NDOB) == 0 &&
5610	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5611		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5612		ctsio->kern_data_len = len;
5613		ctsio->kern_total_len = len;
5614		ctsio->kern_data_resid = 0;
5615		ctsio->kern_rel_offset = 0;
5616		ctsio->kern_sg_entries = 0;
5617		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5618		ctsio->be_move_done = ctl_config_move_done;
5619		ctl_datamove((union ctl_io *)ctsio);
5620
5621		return (CTL_RETVAL_COMPLETE);
5622	}
5623
5624	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5625	lbalen->lba = lba;
5626	lbalen->len = num_blocks;
5627	lbalen->flags = byte2;
5628	retval = lun->backend->config_write((union ctl_io *)ctsio);
5629
5630	return (retval);
5631}
5632
5633int
5634ctl_unmap(struct ctl_scsiio *ctsio)
5635{
5636	struct ctl_lun *lun;
5637	struct scsi_unmap *cdb;
5638	struct ctl_ptr_len_flags *ptrlen;
5639	struct scsi_unmap_header *hdr;
5640	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5641	uint64_t lba;
5642	uint32_t num_blocks;
5643	int len, retval;
5644	uint8_t byte2;
5645
5646	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5647
5648	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5649	cdb = (struct scsi_unmap *)ctsio->cdb;
5650
5651	len = scsi_2btoul(cdb->length);
5652	byte2 = cdb->byte2;
5653
5654	/*
5655	 * If we've got a kernel request that hasn't been malloced yet,
5656	 * malloc it and tell the caller the data buffer is here.
5657	 */
5658	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5659		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5660		ctsio->kern_data_len = len;
5661		ctsio->kern_total_len = len;
5662		ctsio->kern_data_resid = 0;
5663		ctsio->kern_rel_offset = 0;
5664		ctsio->kern_sg_entries = 0;
5665		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5666		ctsio->be_move_done = ctl_config_move_done;
5667		ctl_datamove((union ctl_io *)ctsio);
5668
5669		return (CTL_RETVAL_COMPLETE);
5670	}
5671
5672	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5673	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5674	if (len < sizeof (*hdr) ||
5675	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5676	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5677	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5678		ctl_set_invalid_field(ctsio,
5679				      /*sks_valid*/ 0,
5680				      /*command*/ 0,
5681				      /*field*/ 0,
5682				      /*bit_valid*/ 0,
5683				      /*bit*/ 0);
5684		goto done;
5685	}
5686	len = scsi_2btoul(hdr->desc_length);
5687	buf = (struct scsi_unmap_desc *)(hdr + 1);
5688	end = buf + len / sizeof(*buf);
5689
5690	endnz = buf;
5691	for (range = buf; range < end; range++) {
5692		lba = scsi_8btou64(range->lba);
5693		num_blocks = scsi_4btoul(range->length);
5694		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5695		 || ((lba + num_blocks) < lba)) {
5696			ctl_set_lba_out_of_range(ctsio);
5697			ctl_done((union ctl_io *)ctsio);
5698			return (CTL_RETVAL_COMPLETE);
5699		}
5700		if (num_blocks != 0)
5701			endnz = range + 1;
5702	}
5703
5704	/*
5705	 * Block backend can not handle zero last range.
5706	 * Filter it out and return if there is nothing left.
5707	 */
5708	len = (uint8_t *)endnz - (uint8_t *)buf;
5709	if (len == 0) {
5710		ctl_set_success(ctsio);
5711		goto done;
5712	}
5713
5714	mtx_lock(&lun->lun_lock);
5715	ptrlen = (struct ctl_ptr_len_flags *)
5716	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5717	ptrlen->ptr = (void *)buf;
5718	ptrlen->len = len;
5719	ptrlen->flags = byte2;
5720	ctl_check_blocked(lun);
5721	mtx_unlock(&lun->lun_lock);
5722
5723	retval = lun->backend->config_write((union ctl_io *)ctsio);
5724	return (retval);
5725
5726done:
5727	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5728		free(ctsio->kern_data_ptr, M_CTL);
5729		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5730	}
5731	ctl_done((union ctl_io *)ctsio);
5732	return (CTL_RETVAL_COMPLETE);
5733}
5734
5735/*
5736 * Note that this function currently doesn't actually do anything inside
5737 * CTL to enforce things if the DQue bit is turned on.
5738 *
5739 * Also note that this function can't be used in the default case, because
5740 * the DQue bit isn't set in the changeable mask for the control mode page
5741 * anyway.  This is just here as an example for how to implement a page
5742 * handler, and a placeholder in case we want to allow the user to turn
5743 * tagged queueing on and off.
5744 *
5745 * The D_SENSE bit handling is functional, however, and will turn
5746 * descriptor sense on and off for a given LUN.
5747 */
5748int
5749ctl_control_page_handler(struct ctl_scsiio *ctsio,
5750			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5751{
5752	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5753	struct ctl_lun *lun;
5754	int set_ua;
5755	uint32_t initidx;
5756
5757	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5758	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5759	set_ua = 0;
5760
5761	user_cp = (struct scsi_control_page *)page_ptr;
5762	current_cp = (struct scsi_control_page *)
5763		(page_index->page_data + (page_index->page_len *
5764		CTL_PAGE_CURRENT));
5765	saved_cp = (struct scsi_control_page *)
5766		(page_index->page_data + (page_index->page_len *
5767		CTL_PAGE_SAVED));
5768
5769	mtx_lock(&lun->lun_lock);
5770	if (((current_cp->rlec & SCP_DSENSE) == 0)
5771	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5772		/*
5773		 * Descriptor sense is currently turned off and the user
5774		 * wants to turn it on.
5775		 */
5776		current_cp->rlec |= SCP_DSENSE;
5777		saved_cp->rlec |= SCP_DSENSE;
5778		lun->flags |= CTL_LUN_SENSE_DESC;
5779		set_ua = 1;
5780	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5781		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5782		/*
5783		 * Descriptor sense is currently turned on, and the user
5784		 * wants to turn it off.
5785		 */
5786		current_cp->rlec &= ~SCP_DSENSE;
5787		saved_cp->rlec &= ~SCP_DSENSE;
5788		lun->flags &= ~CTL_LUN_SENSE_DESC;
5789		set_ua = 1;
5790	}
5791	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5792	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5793		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5794		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5795		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5796		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5797		set_ua = 1;
5798	}
5799	if ((current_cp->eca_and_aen & SCP_SWP) !=
5800	    (user_cp->eca_and_aen & SCP_SWP)) {
5801		current_cp->eca_and_aen &= ~SCP_SWP;
5802		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5803		saved_cp->eca_and_aen &= ~SCP_SWP;
5804		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5805		set_ua = 1;
5806	}
5807	if (set_ua != 0)
5808		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5809	mtx_unlock(&lun->lun_lock);
5810	if (set_ua) {
5811		ctl_isc_announce_mode(lun,
5812		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5813		    page_index->page_code, page_index->subpage);
5814	}
5815	return (0);
5816}
5817
5818int
5819ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5820		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5821{
5822	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5823	struct ctl_lun *lun;
5824	int set_ua;
5825	uint32_t initidx;
5826
5827	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5828	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5829	set_ua = 0;
5830
5831	user_cp = (struct scsi_caching_page *)page_ptr;
5832	current_cp = (struct scsi_caching_page *)
5833		(page_index->page_data + (page_index->page_len *
5834		CTL_PAGE_CURRENT));
5835	saved_cp = (struct scsi_caching_page *)
5836		(page_index->page_data + (page_index->page_len *
5837		CTL_PAGE_SAVED));
5838
5839	mtx_lock(&lun->lun_lock);
5840	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5841	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5842		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5843		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5844		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5845		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5846		set_ua = 1;
5847	}
5848	if (set_ua != 0)
5849		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5850	mtx_unlock(&lun->lun_lock);
5851	if (set_ua) {
5852		ctl_isc_announce_mode(lun,
5853		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5854		    page_index->page_code, page_index->subpage);
5855	}
5856	return (0);
5857}
5858
5859int
5860ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5861				struct ctl_page_index *page_index,
5862				uint8_t *page_ptr)
5863{
5864	uint8_t *c;
5865	int i;
5866
5867	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5868	ctl_time_io_secs =
5869		(c[0] << 8) |
5870		(c[1] << 0) |
5871		0;
5872	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5873	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5874	printf("page data:");
5875	for (i=0; i<8; i++)
5876		printf(" %.2x",page_ptr[i]);
5877	printf("\n");
5878	return (0);
5879}
5880
5881int
5882ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5883			       struct ctl_page_index *page_index,
5884			       int pc)
5885{
5886	struct copan_debugconf_subpage *page;
5887
5888	page = (struct copan_debugconf_subpage *)page_index->page_data +
5889		(page_index->page_len * pc);
5890
5891	switch (pc) {
5892	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5893	case SMS_PAGE_CTRL_DEFAULT >> 6:
5894	case SMS_PAGE_CTRL_SAVED >> 6:
5895		/*
5896		 * We don't update the changable or default bits for this page.
5897		 */
5898		break;
5899	case SMS_PAGE_CTRL_CURRENT >> 6:
5900		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5901		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5902		break;
5903	default:
5904		break;
5905	}
5906	return (0);
5907}
5908
5909
5910static int
5911ctl_do_mode_select(union ctl_io *io)
5912{
5913	struct scsi_mode_page_header *page_header;
5914	struct ctl_page_index *page_index;
5915	struct ctl_scsiio *ctsio;
5916	int page_len, page_len_offset, page_len_size;
5917	union ctl_modepage_info *modepage_info;
5918	struct ctl_lun *lun;
5919	int *len_left, *len_used;
5920	int retval, i;
5921
5922	ctsio = &io->scsiio;
5923	page_index = NULL;
5924	page_len = 0;
5925	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5926
5927	modepage_info = (union ctl_modepage_info *)
5928		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5929	len_left = &modepage_info->header.len_left;
5930	len_used = &modepage_info->header.len_used;
5931
5932do_next_page:
5933
5934	page_header = (struct scsi_mode_page_header *)
5935		(ctsio->kern_data_ptr + *len_used);
5936
5937	if (*len_left == 0) {
5938		free(ctsio->kern_data_ptr, M_CTL);
5939		ctl_set_success(ctsio);
5940		ctl_done((union ctl_io *)ctsio);
5941		return (CTL_RETVAL_COMPLETE);
5942	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5943
5944		free(ctsio->kern_data_ptr, M_CTL);
5945		ctl_set_param_len_error(ctsio);
5946		ctl_done((union ctl_io *)ctsio);
5947		return (CTL_RETVAL_COMPLETE);
5948
5949	} else if ((page_header->page_code & SMPH_SPF)
5950		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5951
5952		free(ctsio->kern_data_ptr, M_CTL);
5953		ctl_set_param_len_error(ctsio);
5954		ctl_done((union ctl_io *)ctsio);
5955		return (CTL_RETVAL_COMPLETE);
5956	}
5957
5958
5959	/*
5960	 * XXX KDM should we do something with the block descriptor?
5961	 */
5962	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5963		page_index = &lun->mode_pages.index[i];
5964		if (lun->be_lun->lun_type == T_DIRECT &&
5965		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5966			continue;
5967		if (lun->be_lun->lun_type == T_PROCESSOR &&
5968		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5969			continue;
5970		if (lun->be_lun->lun_type == T_CDROM &&
5971		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5972			continue;
5973
5974		if ((page_index->page_code & SMPH_PC_MASK) !=
5975		    (page_header->page_code & SMPH_PC_MASK))
5976			continue;
5977
5978		/*
5979		 * If neither page has a subpage code, then we've got a
5980		 * match.
5981		 */
5982		if (((page_index->page_code & SMPH_SPF) == 0)
5983		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5984			page_len = page_header->page_length;
5985			break;
5986		}
5987
5988		/*
5989		 * If both pages have subpages, then the subpage numbers
5990		 * have to match.
5991		 */
5992		if ((page_index->page_code & SMPH_SPF)
5993		  && (page_header->page_code & SMPH_SPF)) {
5994			struct scsi_mode_page_header_sp *sph;
5995
5996			sph = (struct scsi_mode_page_header_sp *)page_header;
5997			if (page_index->subpage == sph->subpage) {
5998				page_len = scsi_2btoul(sph->page_length);
5999				break;
6000			}
6001		}
6002	}
6003
6004	/*
6005	 * If we couldn't find the page, or if we don't have a mode select
6006	 * handler for it, send back an error to the user.
6007	 */
6008	if ((i >= CTL_NUM_MODE_PAGES)
6009	 || (page_index->select_handler == NULL)) {
6010		ctl_set_invalid_field(ctsio,
6011				      /*sks_valid*/ 1,
6012				      /*command*/ 0,
6013				      /*field*/ *len_used,
6014				      /*bit_valid*/ 0,
6015				      /*bit*/ 0);
6016		free(ctsio->kern_data_ptr, M_CTL);
6017		ctl_done((union ctl_io *)ctsio);
6018		return (CTL_RETVAL_COMPLETE);
6019	}
6020
6021	if (page_index->page_code & SMPH_SPF) {
6022		page_len_offset = 2;
6023		page_len_size = 2;
6024	} else {
6025		page_len_size = 1;
6026		page_len_offset = 1;
6027	}
6028
6029	/*
6030	 * If the length the initiator gives us isn't the one we specify in
6031	 * the mode page header, or if they didn't specify enough data in
6032	 * the CDB to avoid truncating this page, kick out the request.
6033	 */
6034	if ((page_len != (page_index->page_len - page_len_offset -
6035			  page_len_size))
6036	 || (*len_left < page_index->page_len)) {
6037
6038
6039		ctl_set_invalid_field(ctsio,
6040				      /*sks_valid*/ 1,
6041				      /*command*/ 0,
6042				      /*field*/ *len_used + page_len_offset,
6043				      /*bit_valid*/ 0,
6044				      /*bit*/ 0);
6045		free(ctsio->kern_data_ptr, M_CTL);
6046		ctl_done((union ctl_io *)ctsio);
6047		return (CTL_RETVAL_COMPLETE);
6048	}
6049
6050	/*
6051	 * Run through the mode page, checking to make sure that the bits
6052	 * the user changed are actually legal for him to change.
6053	 */
6054	for (i = 0; i < page_index->page_len; i++) {
6055		uint8_t *user_byte, *change_mask, *current_byte;
6056		int bad_bit;
6057		int j;
6058
6059		user_byte = (uint8_t *)page_header + i;
6060		change_mask = page_index->page_data +
6061			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6062		current_byte = page_index->page_data +
6063			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6064
6065		/*
6066		 * Check to see whether the user set any bits in this byte
6067		 * that he is not allowed to set.
6068		 */
6069		if ((*user_byte & ~(*change_mask)) ==
6070		    (*current_byte & ~(*change_mask)))
6071			continue;
6072
6073		/*
6074		 * Go through bit by bit to determine which one is illegal.
6075		 */
6076		bad_bit = 0;
6077		for (j = 7; j >= 0; j--) {
6078			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6079			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6080				bad_bit = i;
6081				break;
6082			}
6083		}
6084		ctl_set_invalid_field(ctsio,
6085				      /*sks_valid*/ 1,
6086				      /*command*/ 0,
6087				      /*field*/ *len_used + i,
6088				      /*bit_valid*/ 1,
6089				      /*bit*/ bad_bit);
6090		free(ctsio->kern_data_ptr, M_CTL);
6091		ctl_done((union ctl_io *)ctsio);
6092		return (CTL_RETVAL_COMPLETE);
6093	}
6094
6095	/*
6096	 * Decrement these before we call the page handler, since we may
6097	 * end up getting called back one way or another before the handler
6098	 * returns to this context.
6099	 */
6100	*len_left -= page_index->page_len;
6101	*len_used += page_index->page_len;
6102
6103	retval = page_index->select_handler(ctsio, page_index,
6104					    (uint8_t *)page_header);
6105
6106	/*
6107	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6108	 * wait until this queued command completes to finish processing
6109	 * the mode page.  If it returns anything other than
6110	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6111	 * already set the sense information, freed the data pointer, and
6112	 * completed the io for us.
6113	 */
6114	if (retval != CTL_RETVAL_COMPLETE)
6115		goto bailout_no_done;
6116
6117	/*
6118	 * If the initiator sent us more than one page, parse the next one.
6119	 */
6120	if (*len_left > 0)
6121		goto do_next_page;
6122
6123	ctl_set_success(ctsio);
6124	free(ctsio->kern_data_ptr, M_CTL);
6125	ctl_done((union ctl_io *)ctsio);
6126
6127bailout_no_done:
6128
6129	return (CTL_RETVAL_COMPLETE);
6130
6131}
6132
6133int
6134ctl_mode_select(struct ctl_scsiio *ctsio)
6135{
6136	int param_len, pf, sp;
6137	int header_size, bd_len;
6138	union ctl_modepage_info *modepage_info;
6139
6140	switch (ctsio->cdb[0]) {
6141	case MODE_SELECT_6: {
6142		struct scsi_mode_select_6 *cdb;
6143
6144		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6145
6146		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6147		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6148		param_len = cdb->length;
6149		header_size = sizeof(struct scsi_mode_header_6);
6150		break;
6151	}
6152	case MODE_SELECT_10: {
6153		struct scsi_mode_select_10 *cdb;
6154
6155		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6156
6157		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6158		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6159		param_len = scsi_2btoul(cdb->length);
6160		header_size = sizeof(struct scsi_mode_header_10);
6161		break;
6162	}
6163	default:
6164		ctl_set_invalid_opcode(ctsio);
6165		ctl_done((union ctl_io *)ctsio);
6166		return (CTL_RETVAL_COMPLETE);
6167	}
6168
6169	/*
6170	 * From SPC-3:
6171	 * "A parameter list length of zero indicates that the Data-Out Buffer
6172	 * shall be empty. This condition shall not be considered as an error."
6173	 */
6174	if (param_len == 0) {
6175		ctl_set_success(ctsio);
6176		ctl_done((union ctl_io *)ctsio);
6177		return (CTL_RETVAL_COMPLETE);
6178	}
6179
6180	/*
6181	 * Since we'll hit this the first time through, prior to
6182	 * allocation, we don't need to free a data buffer here.
6183	 */
6184	if (param_len < header_size) {
6185		ctl_set_param_len_error(ctsio);
6186		ctl_done((union ctl_io *)ctsio);
6187		return (CTL_RETVAL_COMPLETE);
6188	}
6189
6190	/*
6191	 * Allocate the data buffer and grab the user's data.  In theory,
6192	 * we shouldn't have to sanity check the parameter list length here
6193	 * because the maximum size is 64K.  We should be able to malloc
6194	 * that much without too many problems.
6195	 */
6196	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6197		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6198		ctsio->kern_data_len = param_len;
6199		ctsio->kern_total_len = param_len;
6200		ctsio->kern_data_resid = 0;
6201		ctsio->kern_rel_offset = 0;
6202		ctsio->kern_sg_entries = 0;
6203		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6204		ctsio->be_move_done = ctl_config_move_done;
6205		ctl_datamove((union ctl_io *)ctsio);
6206
6207		return (CTL_RETVAL_COMPLETE);
6208	}
6209
6210	switch (ctsio->cdb[0]) {
6211	case MODE_SELECT_6: {
6212		struct scsi_mode_header_6 *mh6;
6213
6214		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6215		bd_len = mh6->blk_desc_len;
6216		break;
6217	}
6218	case MODE_SELECT_10: {
6219		struct scsi_mode_header_10 *mh10;
6220
6221		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6222		bd_len = scsi_2btoul(mh10->blk_desc_len);
6223		break;
6224	}
6225	default:
6226		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6227		break;
6228	}
6229
6230	if (param_len < (header_size + bd_len)) {
6231		free(ctsio->kern_data_ptr, M_CTL);
6232		ctl_set_param_len_error(ctsio);
6233		ctl_done((union ctl_io *)ctsio);
6234		return (CTL_RETVAL_COMPLETE);
6235	}
6236
6237	/*
6238	 * Set the IO_CONT flag, so that if this I/O gets passed to
6239	 * ctl_config_write_done(), it'll get passed back to
6240	 * ctl_do_mode_select() for further processing, or completion if
6241	 * we're all done.
6242	 */
6243	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6244	ctsio->io_cont = ctl_do_mode_select;
6245
6246	modepage_info = (union ctl_modepage_info *)
6247		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6248	memset(modepage_info, 0, sizeof(*modepage_info));
6249	modepage_info->header.len_left = param_len - header_size - bd_len;
6250	modepage_info->header.len_used = header_size + bd_len;
6251
6252	return (ctl_do_mode_select((union ctl_io *)ctsio));
6253}
6254
6255int
6256ctl_mode_sense(struct ctl_scsiio *ctsio)
6257{
6258	struct ctl_lun *lun;
6259	int pc, page_code, dbd, llba, subpage;
6260	int alloc_len, page_len, header_len, total_len;
6261	struct scsi_mode_block_descr *block_desc;
6262	struct ctl_page_index *page_index;
6263
6264	dbd = 0;
6265	llba = 0;
6266	block_desc = NULL;
6267
6268	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6269
6270	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6271	switch (ctsio->cdb[0]) {
6272	case MODE_SENSE_6: {
6273		struct scsi_mode_sense_6 *cdb;
6274
6275		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6276
6277		header_len = sizeof(struct scsi_mode_hdr_6);
6278		if (cdb->byte2 & SMS_DBD)
6279			dbd = 1;
6280		else
6281			header_len += sizeof(struct scsi_mode_block_descr);
6282
6283		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6284		page_code = cdb->page & SMS_PAGE_CODE;
6285		subpage = cdb->subpage;
6286		alloc_len = cdb->length;
6287		break;
6288	}
6289	case MODE_SENSE_10: {
6290		struct scsi_mode_sense_10 *cdb;
6291
6292		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6293
6294		header_len = sizeof(struct scsi_mode_hdr_10);
6295
6296		if (cdb->byte2 & SMS_DBD)
6297			dbd = 1;
6298		else
6299			header_len += sizeof(struct scsi_mode_block_descr);
6300		if (cdb->byte2 & SMS10_LLBAA)
6301			llba = 1;
6302		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6303		page_code = cdb->page & SMS_PAGE_CODE;
6304		subpage = cdb->subpage;
6305		alloc_len = scsi_2btoul(cdb->length);
6306		break;
6307	}
6308	default:
6309		ctl_set_invalid_opcode(ctsio);
6310		ctl_done((union ctl_io *)ctsio);
6311		return (CTL_RETVAL_COMPLETE);
6312		break; /* NOTREACHED */
6313	}
6314
6315	/*
6316	 * We have to make a first pass through to calculate the size of
6317	 * the pages that match the user's query.  Then we allocate enough
6318	 * memory to hold it, and actually copy the data into the buffer.
6319	 */
6320	switch (page_code) {
6321	case SMS_ALL_PAGES_PAGE: {
6322		int i;
6323
6324		page_len = 0;
6325
6326		/*
6327		 * At the moment, values other than 0 and 0xff here are
6328		 * reserved according to SPC-3.
6329		 */
6330		if ((subpage != SMS_SUBPAGE_PAGE_0)
6331		 && (subpage != SMS_SUBPAGE_ALL)) {
6332			ctl_set_invalid_field(ctsio,
6333					      /*sks_valid*/ 1,
6334					      /*command*/ 1,
6335					      /*field*/ 3,
6336					      /*bit_valid*/ 0,
6337					      /*bit*/ 0);
6338			ctl_done((union ctl_io *)ctsio);
6339			return (CTL_RETVAL_COMPLETE);
6340		}
6341
6342		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6343			page_index = &lun->mode_pages.index[i];
6344
6345			/* Make sure the page is supported for this dev type */
6346			if (lun->be_lun->lun_type == T_DIRECT &&
6347			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6348				continue;
6349			if (lun->be_lun->lun_type == T_PROCESSOR &&
6350			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6351				continue;
6352			if (lun->be_lun->lun_type == T_CDROM &&
6353			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6354				continue;
6355
6356			/*
6357			 * We don't use this subpage if the user didn't
6358			 * request all subpages.
6359			 */
6360			if ((page_index->subpage != 0)
6361			 && (subpage == SMS_SUBPAGE_PAGE_0))
6362				continue;
6363
6364#if 0
6365			printf("found page %#x len %d\n",
6366			       page_index->page_code & SMPH_PC_MASK,
6367			       page_index->page_len);
6368#endif
6369			page_len += page_index->page_len;
6370		}
6371		break;
6372	}
6373	default: {
6374		int i;
6375
6376		page_len = 0;
6377
6378		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6379			page_index = &lun->mode_pages.index[i];
6380
6381			/* Make sure the page is supported for this dev type */
6382			if (lun->be_lun->lun_type == T_DIRECT &&
6383			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6384				continue;
6385			if (lun->be_lun->lun_type == T_PROCESSOR &&
6386			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6387				continue;
6388			if (lun->be_lun->lun_type == T_CDROM &&
6389			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6390				continue;
6391
6392			/* Look for the right page code */
6393			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6394				continue;
6395
6396			/* Look for the right subpage or the subpage wildcard*/
6397			if ((page_index->subpage != subpage)
6398			 && (subpage != SMS_SUBPAGE_ALL))
6399				continue;
6400
6401#if 0
6402			printf("found page %#x len %d\n",
6403			       page_index->page_code & SMPH_PC_MASK,
6404			       page_index->page_len);
6405#endif
6406
6407			page_len += page_index->page_len;
6408		}
6409
6410		if (page_len == 0) {
6411			ctl_set_invalid_field(ctsio,
6412					      /*sks_valid*/ 1,
6413					      /*command*/ 1,
6414					      /*field*/ 2,
6415					      /*bit_valid*/ 1,
6416					      /*bit*/ 5);
6417			ctl_done((union ctl_io *)ctsio);
6418			return (CTL_RETVAL_COMPLETE);
6419		}
6420		break;
6421	}
6422	}
6423
6424	total_len = header_len + page_len;
6425#if 0
6426	printf("header_len = %d, page_len = %d, total_len = %d\n",
6427	       header_len, page_len, total_len);
6428#endif
6429
6430	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6431	ctsio->kern_sg_entries = 0;
6432	ctsio->kern_data_resid = 0;
6433	ctsio->kern_rel_offset = 0;
6434	if (total_len < alloc_len) {
6435		ctsio->residual = alloc_len - total_len;
6436		ctsio->kern_data_len = total_len;
6437		ctsio->kern_total_len = total_len;
6438	} else {
6439		ctsio->residual = 0;
6440		ctsio->kern_data_len = alloc_len;
6441		ctsio->kern_total_len = alloc_len;
6442	}
6443
6444	switch (ctsio->cdb[0]) {
6445	case MODE_SENSE_6: {
6446		struct scsi_mode_hdr_6 *header;
6447
6448		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6449
6450		header->datalen = MIN(total_len - 1, 254);
6451		if (lun->be_lun->lun_type == T_DIRECT) {
6452			header->dev_specific = 0x10; /* DPOFUA */
6453			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6454			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6455			    .eca_and_aen & SCP_SWP) != 0)
6456				    header->dev_specific |= 0x80; /* WP */
6457		}
6458		if (dbd)
6459			header->block_descr_len = 0;
6460		else
6461			header->block_descr_len =
6462				sizeof(struct scsi_mode_block_descr);
6463		block_desc = (struct scsi_mode_block_descr *)&header[1];
6464		break;
6465	}
6466	case MODE_SENSE_10: {
6467		struct scsi_mode_hdr_10 *header;
6468		int datalen;
6469
6470		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6471
6472		datalen = MIN(total_len - 2, 65533);
6473		scsi_ulto2b(datalen, header->datalen);
6474		if (lun->be_lun->lun_type == T_DIRECT) {
6475			header->dev_specific = 0x10; /* DPOFUA */
6476			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6477			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6478			    .eca_and_aen & SCP_SWP) != 0)
6479				    header->dev_specific |= 0x80; /* WP */
6480		}
6481		if (dbd)
6482			scsi_ulto2b(0, header->block_descr_len);
6483		else
6484			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6485				    header->block_descr_len);
6486		block_desc = (struct scsi_mode_block_descr *)&header[1];
6487		break;
6488	}
6489	default:
6490		panic("invalid CDB type %#x", ctsio->cdb[0]);
6491		break; /* NOTREACHED */
6492	}
6493
6494	/*
6495	 * If we've got a disk, use its blocksize in the block
6496	 * descriptor.  Otherwise, just set it to 0.
6497	 */
6498	if (dbd == 0) {
6499		if (lun->be_lun->lun_type == T_DIRECT)
6500			scsi_ulto3b(lun->be_lun->blocksize,
6501				    block_desc->block_len);
6502		else
6503			scsi_ulto3b(0, block_desc->block_len);
6504	}
6505
6506	switch (page_code) {
6507	case SMS_ALL_PAGES_PAGE: {
6508		int i, data_used;
6509
6510		data_used = header_len;
6511		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6512			struct ctl_page_index *page_index;
6513
6514			page_index = &lun->mode_pages.index[i];
6515			if (lun->be_lun->lun_type == T_DIRECT &&
6516			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6517				continue;
6518			if (lun->be_lun->lun_type == T_PROCESSOR &&
6519			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6520				continue;
6521			if (lun->be_lun->lun_type == T_CDROM &&
6522			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6523				continue;
6524
6525			/*
6526			 * We don't use this subpage if the user didn't
6527			 * request all subpages.  We already checked (above)
6528			 * to make sure the user only specified a subpage
6529			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6530			 */
6531			if ((page_index->subpage != 0)
6532			 && (subpage == SMS_SUBPAGE_PAGE_0))
6533				continue;
6534
6535			/*
6536			 * Call the handler, if it exists, to update the
6537			 * page to the latest values.
6538			 */
6539			if (page_index->sense_handler != NULL)
6540				page_index->sense_handler(ctsio, page_index,pc);
6541
6542			memcpy(ctsio->kern_data_ptr + data_used,
6543			       page_index->page_data +
6544			       (page_index->page_len * pc),
6545			       page_index->page_len);
6546			data_used += page_index->page_len;
6547		}
6548		break;
6549	}
6550	default: {
6551		int i, data_used;
6552
6553		data_used = header_len;
6554
6555		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6556			struct ctl_page_index *page_index;
6557
6558			page_index = &lun->mode_pages.index[i];
6559
6560			/* Look for the right page code */
6561			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6562				continue;
6563
6564			/* Look for the right subpage or the subpage wildcard*/
6565			if ((page_index->subpage != subpage)
6566			 && (subpage != SMS_SUBPAGE_ALL))
6567				continue;
6568
6569			/* Make sure the page is supported for this dev type */
6570			if (lun->be_lun->lun_type == T_DIRECT &&
6571			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6572				continue;
6573			if (lun->be_lun->lun_type == T_PROCESSOR &&
6574			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6575				continue;
6576			if (lun->be_lun->lun_type == T_CDROM &&
6577			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6578				continue;
6579
6580			/*
6581			 * Call the handler, if it exists, to update the
6582			 * page to the latest values.
6583			 */
6584			if (page_index->sense_handler != NULL)
6585				page_index->sense_handler(ctsio, page_index,pc);
6586
6587			memcpy(ctsio->kern_data_ptr + data_used,
6588			       page_index->page_data +
6589			       (page_index->page_len * pc),
6590			       page_index->page_len);
6591			data_used += page_index->page_len;
6592		}
6593		break;
6594	}
6595	}
6596
6597	ctl_set_success(ctsio);
6598	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6599	ctsio->be_move_done = ctl_config_move_done;
6600	ctl_datamove((union ctl_io *)ctsio);
6601	return (CTL_RETVAL_COMPLETE);
6602}
6603
6604int
6605ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6606			       struct ctl_page_index *page_index,
6607			       int pc)
6608{
6609	struct ctl_lun *lun;
6610	struct scsi_log_param_header *phdr;
6611	uint8_t *data;
6612	uint64_t val;
6613
6614	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6615	data = page_index->page_data;
6616
6617	if (lun->backend->lun_attr != NULL &&
6618	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6619	     != UINT64_MAX) {
6620		phdr = (struct scsi_log_param_header *)data;
6621		scsi_ulto2b(0x0001, phdr->param_code);
6622		phdr->param_control = SLP_LBIN | SLP_LP;
6623		phdr->param_len = 8;
6624		data = (uint8_t *)(phdr + 1);
6625		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6626		data[4] = 0x02; /* per-pool */
6627		data += phdr->param_len;
6628	}
6629
6630	if (lun->backend->lun_attr != NULL &&
6631	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6632	     != UINT64_MAX) {
6633		phdr = (struct scsi_log_param_header *)data;
6634		scsi_ulto2b(0x0002, phdr->param_code);
6635		phdr->param_control = SLP_LBIN | SLP_LP;
6636		phdr->param_len = 8;
6637		data = (uint8_t *)(phdr + 1);
6638		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6639		data[4] = 0x01; /* per-LUN */
6640		data += phdr->param_len;
6641	}
6642
6643	if (lun->backend->lun_attr != NULL &&
6644	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6645	     != UINT64_MAX) {
6646		phdr = (struct scsi_log_param_header *)data;
6647		scsi_ulto2b(0x00f1, phdr->param_code);
6648		phdr->param_control = SLP_LBIN | SLP_LP;
6649		phdr->param_len = 8;
6650		data = (uint8_t *)(phdr + 1);
6651		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6652		data[4] = 0x02; /* per-pool */
6653		data += phdr->param_len;
6654	}
6655
6656	if (lun->backend->lun_attr != NULL &&
6657	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6658	     != UINT64_MAX) {
6659		phdr = (struct scsi_log_param_header *)data;
6660		scsi_ulto2b(0x00f2, phdr->param_code);
6661		phdr->param_control = SLP_LBIN | SLP_LP;
6662		phdr->param_len = 8;
6663		data = (uint8_t *)(phdr + 1);
6664		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6665		data[4] = 0x02; /* per-pool */
6666		data += phdr->param_len;
6667	}
6668
6669	page_index->page_len = data - page_index->page_data;
6670	return (0);
6671}
6672
6673int
6674ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6675			       struct ctl_page_index *page_index,
6676			       int pc)
6677{
6678	struct ctl_lun *lun;
6679	struct stat_page *data;
6680	uint64_t rn, wn, rb, wb;
6681	struct bintime rt, wt;
6682	int i;
6683
6684	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6685	data = (struct stat_page *)page_index->page_data;
6686
6687	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6688	data->sap.hdr.param_control = SLP_LBIN;
6689	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6690	    sizeof(struct scsi_log_param_header);
6691	rn = wn = rb = wb = 0;
6692	bintime_clear(&rt);
6693	bintime_clear(&wt);
6694	for (i = 0; i < CTL_MAX_PORTS; i++) {
6695		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6696		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6697		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6698		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6699		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6700		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6701	}
6702	scsi_u64to8b(rn, data->sap.read_num);
6703	scsi_u64to8b(wn, data->sap.write_num);
6704	if (lun->stats.blocksize > 0) {
6705		scsi_u64to8b(wb / lun->stats.blocksize,
6706		    data->sap.recvieved_lba);
6707		scsi_u64to8b(rb / lun->stats.blocksize,
6708		    data->sap.transmitted_lba);
6709	}
6710	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6711	    data->sap.read_int);
6712	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6713	    data->sap.write_int);
6714	scsi_u64to8b(0, data->sap.weighted_num);
6715	scsi_u64to8b(0, data->sap.weighted_int);
6716	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6717	data->it.hdr.param_control = SLP_LBIN;
6718	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6719	    sizeof(struct scsi_log_param_header);
6720#ifdef CTL_TIME_IO
6721	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6722#endif
6723	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6724	data->it.hdr.param_control = SLP_LBIN;
6725	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6726	    sizeof(struct scsi_log_param_header);
6727	scsi_ulto4b(3, data->ti.exponent);
6728	scsi_ulto4b(1, data->ti.integer);
6729
6730	page_index->page_len = sizeof(*data);
6731	return (0);
6732}
6733
6734int
6735ctl_log_sense(struct ctl_scsiio *ctsio)
6736{
6737	struct ctl_lun *lun;
6738	int i, pc, page_code, subpage;
6739	int alloc_len, total_len;
6740	struct ctl_page_index *page_index;
6741	struct scsi_log_sense *cdb;
6742	struct scsi_log_header *header;
6743
6744	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6745
6746	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6747	cdb = (struct scsi_log_sense *)ctsio->cdb;
6748	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6749	page_code = cdb->page & SLS_PAGE_CODE;
6750	subpage = cdb->subpage;
6751	alloc_len = scsi_2btoul(cdb->length);
6752
6753	page_index = NULL;
6754	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6755		page_index = &lun->log_pages.index[i];
6756
6757		/* Look for the right page code */
6758		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6759			continue;
6760
6761		/* Look for the right subpage or the subpage wildcard*/
6762		if (page_index->subpage != subpage)
6763			continue;
6764
6765		break;
6766	}
6767	if (i >= CTL_NUM_LOG_PAGES) {
6768		ctl_set_invalid_field(ctsio,
6769				      /*sks_valid*/ 1,
6770				      /*command*/ 1,
6771				      /*field*/ 2,
6772				      /*bit_valid*/ 0,
6773				      /*bit*/ 0);
6774		ctl_done((union ctl_io *)ctsio);
6775		return (CTL_RETVAL_COMPLETE);
6776	}
6777
6778	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6779
6780	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6781	ctsio->kern_sg_entries = 0;
6782	ctsio->kern_data_resid = 0;
6783	ctsio->kern_rel_offset = 0;
6784	if (total_len < alloc_len) {
6785		ctsio->residual = alloc_len - total_len;
6786		ctsio->kern_data_len = total_len;
6787		ctsio->kern_total_len = total_len;
6788	} else {
6789		ctsio->residual = 0;
6790		ctsio->kern_data_len = alloc_len;
6791		ctsio->kern_total_len = alloc_len;
6792	}
6793
6794	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6795	header->page = page_index->page_code;
6796	if (page_index->subpage) {
6797		header->page |= SL_SPF;
6798		header->subpage = page_index->subpage;
6799	}
6800	scsi_ulto2b(page_index->page_len, header->datalen);
6801
6802	/*
6803	 * Call the handler, if it exists, to update the
6804	 * page to the latest values.
6805	 */
6806	if (page_index->sense_handler != NULL)
6807		page_index->sense_handler(ctsio, page_index, pc);
6808
6809	memcpy(header + 1, page_index->page_data, page_index->page_len);
6810
6811	ctl_set_success(ctsio);
6812	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6813	ctsio->be_move_done = ctl_config_move_done;
6814	ctl_datamove((union ctl_io *)ctsio);
6815	return (CTL_RETVAL_COMPLETE);
6816}
6817
6818int
6819ctl_read_capacity(struct ctl_scsiio *ctsio)
6820{
6821	struct scsi_read_capacity *cdb;
6822	struct scsi_read_capacity_data *data;
6823	struct ctl_lun *lun;
6824	uint32_t lba;
6825
6826	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6827
6828	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6829
6830	lba = scsi_4btoul(cdb->addr);
6831	if (((cdb->pmi & SRC_PMI) == 0)
6832	 && (lba != 0)) {
6833		ctl_set_invalid_field(/*ctsio*/ ctsio,
6834				      /*sks_valid*/ 1,
6835				      /*command*/ 1,
6836				      /*field*/ 2,
6837				      /*bit_valid*/ 0,
6838				      /*bit*/ 0);
6839		ctl_done((union ctl_io *)ctsio);
6840		return (CTL_RETVAL_COMPLETE);
6841	}
6842
6843	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6844
6845	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6846	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6847	ctsio->residual = 0;
6848	ctsio->kern_data_len = sizeof(*data);
6849	ctsio->kern_total_len = sizeof(*data);
6850	ctsio->kern_data_resid = 0;
6851	ctsio->kern_rel_offset = 0;
6852	ctsio->kern_sg_entries = 0;
6853
6854	/*
6855	 * If the maximum LBA is greater than 0xfffffffe, the user must
6856	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6857	 * serivce action set.
6858	 */
6859	if (lun->be_lun->maxlba > 0xfffffffe)
6860		scsi_ulto4b(0xffffffff, data->addr);
6861	else
6862		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6863
6864	/*
6865	 * XXX KDM this may not be 512 bytes...
6866	 */
6867	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6868
6869	ctl_set_success(ctsio);
6870	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6871	ctsio->be_move_done = ctl_config_move_done;
6872	ctl_datamove((union ctl_io *)ctsio);
6873	return (CTL_RETVAL_COMPLETE);
6874}
6875
6876int
6877ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6878{
6879	struct scsi_read_capacity_16 *cdb;
6880	struct scsi_read_capacity_data_long *data;
6881	struct ctl_lun *lun;
6882	uint64_t lba;
6883	uint32_t alloc_len;
6884
6885	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6886
6887	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6888
6889	alloc_len = scsi_4btoul(cdb->alloc_len);
6890	lba = scsi_8btou64(cdb->addr);
6891
6892	if ((cdb->reladr & SRC16_PMI)
6893	 && (lba != 0)) {
6894		ctl_set_invalid_field(/*ctsio*/ ctsio,
6895				      /*sks_valid*/ 1,
6896				      /*command*/ 1,
6897				      /*field*/ 2,
6898				      /*bit_valid*/ 0,
6899				      /*bit*/ 0);
6900		ctl_done((union ctl_io *)ctsio);
6901		return (CTL_RETVAL_COMPLETE);
6902	}
6903
6904	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6905
6906	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6907	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6908
6909	if (sizeof(*data) < alloc_len) {
6910		ctsio->residual = alloc_len - sizeof(*data);
6911		ctsio->kern_data_len = sizeof(*data);
6912		ctsio->kern_total_len = sizeof(*data);
6913	} else {
6914		ctsio->residual = 0;
6915		ctsio->kern_data_len = alloc_len;
6916		ctsio->kern_total_len = alloc_len;
6917	}
6918	ctsio->kern_data_resid = 0;
6919	ctsio->kern_rel_offset = 0;
6920	ctsio->kern_sg_entries = 0;
6921
6922	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6923	/* XXX KDM this may not be 512 bytes... */
6924	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6925	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6926	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6927	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6928		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6929
6930	ctl_set_success(ctsio);
6931	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6932	ctsio->be_move_done = ctl_config_move_done;
6933	ctl_datamove((union ctl_io *)ctsio);
6934	return (CTL_RETVAL_COMPLETE);
6935}
6936
6937int
6938ctl_get_lba_status(struct ctl_scsiio *ctsio)
6939{
6940	struct scsi_get_lba_status *cdb;
6941	struct scsi_get_lba_status_data *data;
6942	struct ctl_lun *lun;
6943	struct ctl_lba_len_flags *lbalen;
6944	uint64_t lba;
6945	uint32_t alloc_len, total_len;
6946	int retval;
6947
6948	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6949
6950	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6951	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6952	lba = scsi_8btou64(cdb->addr);
6953	alloc_len = scsi_4btoul(cdb->alloc_len);
6954
6955	if (lba > lun->be_lun->maxlba) {
6956		ctl_set_lba_out_of_range(ctsio);
6957		ctl_done((union ctl_io *)ctsio);
6958		return (CTL_RETVAL_COMPLETE);
6959	}
6960
6961	total_len = sizeof(*data) + sizeof(data->descr[0]);
6962	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6963	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6964
6965	if (total_len < alloc_len) {
6966		ctsio->residual = alloc_len - total_len;
6967		ctsio->kern_data_len = total_len;
6968		ctsio->kern_total_len = total_len;
6969	} else {
6970		ctsio->residual = 0;
6971		ctsio->kern_data_len = alloc_len;
6972		ctsio->kern_total_len = alloc_len;
6973	}
6974	ctsio->kern_data_resid = 0;
6975	ctsio->kern_rel_offset = 0;
6976	ctsio->kern_sg_entries = 0;
6977
6978	/* Fill dummy data in case backend can't tell anything. */
6979	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6980	scsi_u64to8b(lba, data->descr[0].addr);
6981	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6982	    data->descr[0].length);
6983	data->descr[0].status = 0; /* Mapped or unknown. */
6984
6985	ctl_set_success(ctsio);
6986	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6987	ctsio->be_move_done = ctl_config_move_done;
6988
6989	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6990	lbalen->lba = lba;
6991	lbalen->len = total_len;
6992	lbalen->flags = 0;
6993	retval = lun->backend->config_read((union ctl_io *)ctsio);
6994	return (CTL_RETVAL_COMPLETE);
6995}
6996
6997int
6998ctl_read_defect(struct ctl_scsiio *ctsio)
6999{
7000	struct scsi_read_defect_data_10 *ccb10;
7001	struct scsi_read_defect_data_12 *ccb12;
7002	struct scsi_read_defect_data_hdr_10 *data10;
7003	struct scsi_read_defect_data_hdr_12 *data12;
7004	uint32_t alloc_len, data_len;
7005	uint8_t format;
7006
7007	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7008
7009	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7010		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7011		format = ccb10->format;
7012		alloc_len = scsi_2btoul(ccb10->alloc_length);
7013		data_len = sizeof(*data10);
7014	} else {
7015		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7016		format = ccb12->format;
7017		alloc_len = scsi_4btoul(ccb12->alloc_length);
7018		data_len = sizeof(*data12);
7019	}
7020	if (alloc_len == 0) {
7021		ctl_set_success(ctsio);
7022		ctl_done((union ctl_io *)ctsio);
7023		return (CTL_RETVAL_COMPLETE);
7024	}
7025
7026	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7027	if (data_len < alloc_len) {
7028		ctsio->residual = alloc_len - data_len;
7029		ctsio->kern_data_len = data_len;
7030		ctsio->kern_total_len = data_len;
7031	} else {
7032		ctsio->residual = 0;
7033		ctsio->kern_data_len = alloc_len;
7034		ctsio->kern_total_len = alloc_len;
7035	}
7036	ctsio->kern_data_resid = 0;
7037	ctsio->kern_rel_offset = 0;
7038	ctsio->kern_sg_entries = 0;
7039
7040	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7041		data10 = (struct scsi_read_defect_data_hdr_10 *)
7042		    ctsio->kern_data_ptr;
7043		data10->format = format;
7044		scsi_ulto2b(0, data10->length);
7045	} else {
7046		data12 = (struct scsi_read_defect_data_hdr_12 *)
7047		    ctsio->kern_data_ptr;
7048		data12->format = format;
7049		scsi_ulto2b(0, data12->generation);
7050		scsi_ulto4b(0, data12->length);
7051	}
7052
7053	ctl_set_success(ctsio);
7054	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7055	ctsio->be_move_done = ctl_config_move_done;
7056	ctl_datamove((union ctl_io *)ctsio);
7057	return (CTL_RETVAL_COMPLETE);
7058}
7059
7060int
7061ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7062{
7063	struct scsi_maintenance_in *cdb;
7064	int retval;
7065	int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7066	int num_target_port_groups, num_target_ports;
7067	struct ctl_lun *lun;
7068	struct ctl_softc *softc;
7069	struct ctl_port *port;
7070	struct scsi_target_group_data *rtg_ptr;
7071	struct scsi_target_group_data_extended *rtg_ext_ptr;
7072	struct scsi_target_port_group_descriptor *tpg_desc;
7073
7074	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7075
7076	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7077	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7078	softc = lun->ctl_softc;
7079
7080	retval = CTL_RETVAL_COMPLETE;
7081
7082	switch (cdb->byte2 & STG_PDF_MASK) {
7083	case STG_PDF_LENGTH:
7084		ext = 0;
7085		break;
7086	case STG_PDF_EXTENDED:
7087		ext = 1;
7088		break;
7089	default:
7090		ctl_set_invalid_field(/*ctsio*/ ctsio,
7091				      /*sks_valid*/ 1,
7092				      /*command*/ 1,
7093				      /*field*/ 2,
7094				      /*bit_valid*/ 1,
7095				      /*bit*/ 5);
7096		ctl_done((union ctl_io *)ctsio);
7097		return(retval);
7098	}
7099
7100	if (softc->is_single)
7101		num_target_port_groups = 1;
7102	else
7103		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7104	num_target_ports = 0;
7105	mtx_lock(&softc->ctl_lock);
7106	STAILQ_FOREACH(port, &softc->port_list, links) {
7107		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7108			continue;
7109		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7110			continue;
7111		num_target_ports++;
7112	}
7113	mtx_unlock(&softc->ctl_lock);
7114
7115	if (ext)
7116		total_len = sizeof(struct scsi_target_group_data_extended);
7117	else
7118		total_len = sizeof(struct scsi_target_group_data);
7119	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7120		num_target_port_groups +
7121	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7122
7123	alloc_len = scsi_4btoul(cdb->length);
7124
7125	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7126
7127	ctsio->kern_sg_entries = 0;
7128
7129	if (total_len < alloc_len) {
7130		ctsio->residual = alloc_len - total_len;
7131		ctsio->kern_data_len = total_len;
7132		ctsio->kern_total_len = total_len;
7133	} else {
7134		ctsio->residual = 0;
7135		ctsio->kern_data_len = alloc_len;
7136		ctsio->kern_total_len = alloc_len;
7137	}
7138	ctsio->kern_data_resid = 0;
7139	ctsio->kern_rel_offset = 0;
7140
7141	if (ext) {
7142		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7143		    ctsio->kern_data_ptr;
7144		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7145		rtg_ext_ptr->format_type = 0x10;
7146		rtg_ext_ptr->implicit_transition_time = 0;
7147		tpg_desc = &rtg_ext_ptr->groups[0];
7148	} else {
7149		rtg_ptr = (struct scsi_target_group_data *)
7150		    ctsio->kern_data_ptr;
7151		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7152		tpg_desc = &rtg_ptr->groups[0];
7153	}
7154
7155	mtx_lock(&softc->ctl_lock);
7156	pg = softc->port_min / softc->port_cnt;
7157	if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7158		gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7159	else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7160		gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7161	else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7162		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7163	else
7164		gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7165	if (lun->flags & CTL_LUN_PRIMARY_SC) {
7166		os = gs;
7167		gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7168	} else
7169		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7170	for (g = 0; g < num_target_port_groups; g++) {
7171		tpg_desc->pref_state = (g == pg) ? gs : os;
7172		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7173		    TPG_U_SUP | TPG_T_SUP;
7174		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7175		tpg_desc->status = TPG_IMPLICIT;
7176		pc = 0;
7177		STAILQ_FOREACH(port, &softc->port_list, links) {
7178			if (port->targ_port < g * softc->port_cnt ||
7179			    port->targ_port >= (g + 1) * softc->port_cnt)
7180				continue;
7181			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7182				continue;
7183			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7184				continue;
7185			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7186			    relative_target_port_identifier);
7187			pc++;
7188		}
7189		tpg_desc->target_port_count = pc;
7190		tpg_desc = (struct scsi_target_port_group_descriptor *)
7191		    &tpg_desc->descriptors[pc];
7192	}
7193	mtx_unlock(&softc->ctl_lock);
7194
7195	ctl_set_success(ctsio);
7196	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7197	ctsio->be_move_done = ctl_config_move_done;
7198	ctl_datamove((union ctl_io *)ctsio);
7199	return(retval);
7200}
7201
7202int
7203ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7204{
7205	struct ctl_lun *lun;
7206	struct scsi_report_supported_opcodes *cdb;
7207	const struct ctl_cmd_entry *entry, *sentry;
7208	struct scsi_report_supported_opcodes_all *all;
7209	struct scsi_report_supported_opcodes_descr *descr;
7210	struct scsi_report_supported_opcodes_one *one;
7211	int retval;
7212	int alloc_len, total_len;
7213	int opcode, service_action, i, j, num;
7214
7215	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7216
7217	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7218	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7219
7220	retval = CTL_RETVAL_COMPLETE;
7221
7222	opcode = cdb->requested_opcode;
7223	service_action = scsi_2btoul(cdb->requested_service_action);
7224	switch (cdb->options & RSO_OPTIONS_MASK) {
7225	case RSO_OPTIONS_ALL:
7226		num = 0;
7227		for (i = 0; i < 256; i++) {
7228			entry = &ctl_cmd_table[i];
7229			if (entry->flags & CTL_CMD_FLAG_SA5) {
7230				for (j = 0; j < 32; j++) {
7231					sentry = &((const struct ctl_cmd_entry *)
7232					    entry->execute)[j];
7233					if (ctl_cmd_applicable(
7234					    lun->be_lun->lun_type, sentry))
7235						num++;
7236				}
7237			} else {
7238				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7239				    entry))
7240					num++;
7241			}
7242		}
7243		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7244		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7245		break;
7246	case RSO_OPTIONS_OC:
7247		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7248			ctl_set_invalid_field(/*ctsio*/ ctsio,
7249					      /*sks_valid*/ 1,
7250					      /*command*/ 1,
7251					      /*field*/ 2,
7252					      /*bit_valid*/ 1,
7253					      /*bit*/ 2);
7254			ctl_done((union ctl_io *)ctsio);
7255			return (CTL_RETVAL_COMPLETE);
7256		}
7257		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7258		break;
7259	case RSO_OPTIONS_OC_SA:
7260		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7261		    service_action >= 32) {
7262			ctl_set_invalid_field(/*ctsio*/ ctsio,
7263					      /*sks_valid*/ 1,
7264					      /*command*/ 1,
7265					      /*field*/ 2,
7266					      /*bit_valid*/ 1,
7267					      /*bit*/ 2);
7268			ctl_done((union ctl_io *)ctsio);
7269			return (CTL_RETVAL_COMPLETE);
7270		}
7271		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7272		break;
7273	default:
7274		ctl_set_invalid_field(/*ctsio*/ ctsio,
7275				      /*sks_valid*/ 1,
7276				      /*command*/ 1,
7277				      /*field*/ 2,
7278				      /*bit_valid*/ 1,
7279				      /*bit*/ 2);
7280		ctl_done((union ctl_io *)ctsio);
7281		return (CTL_RETVAL_COMPLETE);
7282	}
7283
7284	alloc_len = scsi_4btoul(cdb->length);
7285
7286	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7287
7288	ctsio->kern_sg_entries = 0;
7289
7290	if (total_len < alloc_len) {
7291		ctsio->residual = alloc_len - total_len;
7292		ctsio->kern_data_len = total_len;
7293		ctsio->kern_total_len = total_len;
7294	} else {
7295		ctsio->residual = 0;
7296		ctsio->kern_data_len = alloc_len;
7297		ctsio->kern_total_len = alloc_len;
7298	}
7299	ctsio->kern_data_resid = 0;
7300	ctsio->kern_rel_offset = 0;
7301
7302	switch (cdb->options & RSO_OPTIONS_MASK) {
7303	case RSO_OPTIONS_ALL:
7304		all = (struct scsi_report_supported_opcodes_all *)
7305		    ctsio->kern_data_ptr;
7306		num = 0;
7307		for (i = 0; i < 256; i++) {
7308			entry = &ctl_cmd_table[i];
7309			if (entry->flags & CTL_CMD_FLAG_SA5) {
7310				for (j = 0; j < 32; j++) {
7311					sentry = &((const struct ctl_cmd_entry *)
7312					    entry->execute)[j];
7313					if (!ctl_cmd_applicable(
7314					    lun->be_lun->lun_type, sentry))
7315						continue;
7316					descr = &all->descr[num++];
7317					descr->opcode = i;
7318					scsi_ulto2b(j, descr->service_action);
7319					descr->flags = RSO_SERVACTV;
7320					scsi_ulto2b(sentry->length,
7321					    descr->cdb_length);
7322				}
7323			} else {
7324				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7325				    entry))
7326					continue;
7327				descr = &all->descr[num++];
7328				descr->opcode = i;
7329				scsi_ulto2b(0, descr->service_action);
7330				descr->flags = 0;
7331				scsi_ulto2b(entry->length, descr->cdb_length);
7332			}
7333		}
7334		scsi_ulto4b(
7335		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7336		    all->length);
7337		break;
7338	case RSO_OPTIONS_OC:
7339		one = (struct scsi_report_supported_opcodes_one *)
7340		    ctsio->kern_data_ptr;
7341		entry = &ctl_cmd_table[opcode];
7342		goto fill_one;
7343	case RSO_OPTIONS_OC_SA:
7344		one = (struct scsi_report_supported_opcodes_one *)
7345		    ctsio->kern_data_ptr;
7346		entry = &ctl_cmd_table[opcode];
7347		entry = &((const struct ctl_cmd_entry *)
7348		    entry->execute)[service_action];
7349fill_one:
7350		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7351			one->support = 3;
7352			scsi_ulto2b(entry->length, one->cdb_length);
7353			one->cdb_usage[0] = opcode;
7354			memcpy(&one->cdb_usage[1], entry->usage,
7355			    entry->length - 1);
7356		} else
7357			one->support = 1;
7358		break;
7359	}
7360
7361	ctl_set_success(ctsio);
7362	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7363	ctsio->be_move_done = ctl_config_move_done;
7364	ctl_datamove((union ctl_io *)ctsio);
7365	return(retval);
7366}
7367
7368int
7369ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7370{
7371	struct scsi_report_supported_tmf *cdb;
7372	struct scsi_report_supported_tmf_data *data;
7373	int retval;
7374	int alloc_len, total_len;
7375
7376	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7377
7378	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7379
7380	retval = CTL_RETVAL_COMPLETE;
7381
7382	total_len = sizeof(struct scsi_report_supported_tmf_data);
7383	alloc_len = scsi_4btoul(cdb->length);
7384
7385	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7386
7387	ctsio->kern_sg_entries = 0;
7388
7389	if (total_len < alloc_len) {
7390		ctsio->residual = alloc_len - total_len;
7391		ctsio->kern_data_len = total_len;
7392		ctsio->kern_total_len = total_len;
7393	} else {
7394		ctsio->residual = 0;
7395		ctsio->kern_data_len = alloc_len;
7396		ctsio->kern_total_len = alloc_len;
7397	}
7398	ctsio->kern_data_resid = 0;
7399	ctsio->kern_rel_offset = 0;
7400
7401	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7402	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7403	    RST_TRS;
7404	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7405
7406	ctl_set_success(ctsio);
7407	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7408	ctsio->be_move_done = ctl_config_move_done;
7409	ctl_datamove((union ctl_io *)ctsio);
7410	return (retval);
7411}
7412
7413int
7414ctl_report_timestamp(struct ctl_scsiio *ctsio)
7415{
7416	struct scsi_report_timestamp *cdb;
7417	struct scsi_report_timestamp_data *data;
7418	struct timeval tv;
7419	int64_t timestamp;
7420	int retval;
7421	int alloc_len, total_len;
7422
7423	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7424
7425	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7426
7427	retval = CTL_RETVAL_COMPLETE;
7428
7429	total_len = sizeof(struct scsi_report_timestamp_data);
7430	alloc_len = scsi_4btoul(cdb->length);
7431
7432	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7433
7434	ctsio->kern_sg_entries = 0;
7435
7436	if (total_len < alloc_len) {
7437		ctsio->residual = alloc_len - total_len;
7438		ctsio->kern_data_len = total_len;
7439		ctsio->kern_total_len = total_len;
7440	} else {
7441		ctsio->residual = 0;
7442		ctsio->kern_data_len = alloc_len;
7443		ctsio->kern_total_len = alloc_len;
7444	}
7445	ctsio->kern_data_resid = 0;
7446	ctsio->kern_rel_offset = 0;
7447
7448	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7449	scsi_ulto2b(sizeof(*data) - 2, data->length);
7450	data->origin = RTS_ORIG_OUTSIDE;
7451	getmicrotime(&tv);
7452	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7453	scsi_ulto4b(timestamp >> 16, data->timestamp);
7454	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7455
7456	ctl_set_success(ctsio);
7457	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7458	ctsio->be_move_done = ctl_config_move_done;
7459	ctl_datamove((union ctl_io *)ctsio);
7460	return (retval);
7461}
7462
7463int
7464ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7465{
7466	struct scsi_per_res_in *cdb;
7467	int alloc_len, total_len = 0;
7468	/* struct scsi_per_res_in_rsrv in_data; */
7469	struct ctl_lun *lun;
7470	struct ctl_softc *softc;
7471	uint64_t key;
7472
7473	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7474
7475	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7476
7477	alloc_len = scsi_2btoul(cdb->length);
7478
7479	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7480	softc = lun->ctl_softc;
7481
7482retry:
7483	mtx_lock(&lun->lun_lock);
7484	switch (cdb->action) {
7485	case SPRI_RK: /* read keys */
7486		total_len = sizeof(struct scsi_per_res_in_keys) +
7487			lun->pr_key_count *
7488			sizeof(struct scsi_per_res_key);
7489		break;
7490	case SPRI_RR: /* read reservation */
7491		if (lun->flags & CTL_LUN_PR_RESERVED)
7492			total_len = sizeof(struct scsi_per_res_in_rsrv);
7493		else
7494			total_len = sizeof(struct scsi_per_res_in_header);
7495		break;
7496	case SPRI_RC: /* report capabilities */
7497		total_len = sizeof(struct scsi_per_res_cap);
7498		break;
7499	case SPRI_RS: /* read full status */
7500		total_len = sizeof(struct scsi_per_res_in_header) +
7501		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7502		    lun->pr_key_count;
7503		break;
7504	default:
7505		panic("Invalid PR type %x", cdb->action);
7506	}
7507	mtx_unlock(&lun->lun_lock);
7508
7509	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7510
7511	if (total_len < alloc_len) {
7512		ctsio->residual = alloc_len - total_len;
7513		ctsio->kern_data_len = total_len;
7514		ctsio->kern_total_len = total_len;
7515	} else {
7516		ctsio->residual = 0;
7517		ctsio->kern_data_len = alloc_len;
7518		ctsio->kern_total_len = alloc_len;
7519	}
7520
7521	ctsio->kern_data_resid = 0;
7522	ctsio->kern_rel_offset = 0;
7523	ctsio->kern_sg_entries = 0;
7524
7525	mtx_lock(&lun->lun_lock);
7526	switch (cdb->action) {
7527	case SPRI_RK: { // read keys
7528        struct scsi_per_res_in_keys *res_keys;
7529		int i, key_count;
7530
7531		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7532
7533		/*
7534		 * We had to drop the lock to allocate our buffer, which
7535		 * leaves time for someone to come in with another
7536		 * persistent reservation.  (That is unlikely, though,
7537		 * since this should be the only persistent reservation
7538		 * command active right now.)
7539		 */
7540		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7541		    (lun->pr_key_count *
7542		     sizeof(struct scsi_per_res_key)))){
7543			mtx_unlock(&lun->lun_lock);
7544			free(ctsio->kern_data_ptr, M_CTL);
7545			printf("%s: reservation length changed, retrying\n",
7546			       __func__);
7547			goto retry;
7548		}
7549
7550		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7551
7552		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7553			     lun->pr_key_count, res_keys->header.length);
7554
7555		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7556			if ((key = ctl_get_prkey(lun, i)) == 0)
7557				continue;
7558
7559			/*
7560			 * We used lun->pr_key_count to calculate the
7561			 * size to allocate.  If it turns out the number of
7562			 * initiators with the registered flag set is
7563			 * larger than that (i.e. they haven't been kept in
7564			 * sync), we've got a problem.
7565			 */
7566			if (key_count >= lun->pr_key_count) {
7567				key_count++;
7568				continue;
7569			}
7570			scsi_u64to8b(key, res_keys->keys[key_count].key);
7571			key_count++;
7572		}
7573		break;
7574	}
7575	case SPRI_RR: { // read reservation
7576		struct scsi_per_res_in_rsrv *res;
7577		int tmp_len, header_only;
7578
7579		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7580
7581		scsi_ulto4b(lun->pr_generation, res->header.generation);
7582
7583		if (lun->flags & CTL_LUN_PR_RESERVED)
7584		{
7585			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7586			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7587				    res->header.length);
7588			header_only = 0;
7589		} else {
7590			tmp_len = sizeof(struct scsi_per_res_in_header);
7591			scsi_ulto4b(0, res->header.length);
7592			header_only = 1;
7593		}
7594
7595		/*
7596		 * We had to drop the lock to allocate our buffer, which
7597		 * leaves time for someone to come in with another
7598		 * persistent reservation.  (That is unlikely, though,
7599		 * since this should be the only persistent reservation
7600		 * command active right now.)
7601		 */
7602		if (tmp_len != total_len) {
7603			mtx_unlock(&lun->lun_lock);
7604			free(ctsio->kern_data_ptr, M_CTL);
7605			printf("%s: reservation status changed, retrying\n",
7606			       __func__);
7607			goto retry;
7608		}
7609
7610		/*
7611		 * No reservation held, so we're done.
7612		 */
7613		if (header_only != 0)
7614			break;
7615
7616		/*
7617		 * If the registration is an All Registrants type, the key
7618		 * is 0, since it doesn't really matter.
7619		 */
7620		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7621			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7622			    res->data.reservation);
7623		}
7624		res->data.scopetype = lun->pr_res_type;
7625		break;
7626	}
7627	case SPRI_RC:     //report capabilities
7628	{
7629		struct scsi_per_res_cap *res_cap;
7630		uint16_t type_mask;
7631
7632		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7633		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7634		res_cap->flags1 = SPRI_CRH;
7635		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7636		type_mask = SPRI_TM_WR_EX_AR |
7637			    SPRI_TM_EX_AC_RO |
7638			    SPRI_TM_WR_EX_RO |
7639			    SPRI_TM_EX_AC |
7640			    SPRI_TM_WR_EX |
7641			    SPRI_TM_EX_AC_AR;
7642		scsi_ulto2b(type_mask, res_cap->type_mask);
7643		break;
7644	}
7645	case SPRI_RS: { // read full status
7646		struct scsi_per_res_in_full *res_status;
7647		struct scsi_per_res_in_full_desc *res_desc;
7648		struct ctl_port *port;
7649		int i, len;
7650
7651		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7652
7653		/*
7654		 * We had to drop the lock to allocate our buffer, which
7655		 * leaves time for someone to come in with another
7656		 * persistent reservation.  (That is unlikely, though,
7657		 * since this should be the only persistent reservation
7658		 * command active right now.)
7659		 */
7660		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7661		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7662		     lun->pr_key_count)){
7663			mtx_unlock(&lun->lun_lock);
7664			free(ctsio->kern_data_ptr, M_CTL);
7665			printf("%s: reservation length changed, retrying\n",
7666			       __func__);
7667			goto retry;
7668		}
7669
7670		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7671
7672		res_desc = &res_status->desc[0];
7673		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7674			if ((key = ctl_get_prkey(lun, i)) == 0)
7675				continue;
7676
7677			scsi_u64to8b(key, res_desc->res_key.key);
7678			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7679			    (lun->pr_res_idx == i ||
7680			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7681				res_desc->flags = SPRI_FULL_R_HOLDER;
7682				res_desc->scopetype = lun->pr_res_type;
7683			}
7684			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7685			    res_desc->rel_trgt_port_id);
7686			len = 0;
7687			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7688			if (port != NULL)
7689				len = ctl_create_iid(port,
7690				    i % CTL_MAX_INIT_PER_PORT,
7691				    res_desc->transport_id);
7692			scsi_ulto4b(len, res_desc->additional_length);
7693			res_desc = (struct scsi_per_res_in_full_desc *)
7694			    &res_desc->transport_id[len];
7695		}
7696		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7697		    res_status->header.length);
7698		break;
7699	}
7700	default:
7701		/*
7702		 * This is a bug, because we just checked for this above,
7703		 * and should have returned an error.
7704		 */
7705		panic("Invalid PR type %x", cdb->action);
7706		break; /* NOTREACHED */
7707	}
7708	mtx_unlock(&lun->lun_lock);
7709
7710	ctl_set_success(ctsio);
7711	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7712	ctsio->be_move_done = ctl_config_move_done;
7713	ctl_datamove((union ctl_io *)ctsio);
7714	return (CTL_RETVAL_COMPLETE);
7715}
7716
7717/*
7718 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7719 * it should return.
7720 */
7721static int
7722ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7723		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7724		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7725		struct scsi_per_res_out_parms* param)
7726{
7727	union ctl_ha_msg persis_io;
7728	int i;
7729
7730	mtx_lock(&lun->lun_lock);
7731	if (sa_res_key == 0) {
7732		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7733			/* validate scope and type */
7734			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7735			     SPR_LU_SCOPE) {
7736				mtx_unlock(&lun->lun_lock);
7737				ctl_set_invalid_field(/*ctsio*/ ctsio,
7738						      /*sks_valid*/ 1,
7739						      /*command*/ 1,
7740						      /*field*/ 2,
7741						      /*bit_valid*/ 1,
7742						      /*bit*/ 4);
7743				ctl_done((union ctl_io *)ctsio);
7744				return (1);
7745			}
7746
7747		        if (type>8 || type==2 || type==4 || type==0) {
7748				mtx_unlock(&lun->lun_lock);
7749				ctl_set_invalid_field(/*ctsio*/ ctsio,
7750       	           				      /*sks_valid*/ 1,
7751						      /*command*/ 1,
7752						      /*field*/ 2,
7753						      /*bit_valid*/ 1,
7754						      /*bit*/ 0);
7755				ctl_done((union ctl_io *)ctsio);
7756				return (1);
7757		        }
7758
7759			/*
7760			 * Unregister everybody else and build UA for
7761			 * them
7762			 */
7763			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7764				if (i == residx || ctl_get_prkey(lun, i) == 0)
7765					continue;
7766
7767				ctl_clr_prkey(lun, i);
7768				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7769			}
7770			lun->pr_key_count = 1;
7771			lun->pr_res_type = type;
7772			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7773			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7774				lun->pr_res_idx = residx;
7775			lun->pr_generation++;
7776			mtx_unlock(&lun->lun_lock);
7777
7778			/* send msg to other side */
7779			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7780			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7781			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7782			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7783			persis_io.pr.pr_info.res_type = type;
7784			memcpy(persis_io.pr.pr_info.sa_res_key,
7785			       param->serv_act_res_key,
7786			       sizeof(param->serv_act_res_key));
7787			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7788			    sizeof(persis_io.pr), M_WAITOK);
7789		} else {
7790			/* not all registrants */
7791			mtx_unlock(&lun->lun_lock);
7792			free(ctsio->kern_data_ptr, M_CTL);
7793			ctl_set_invalid_field(ctsio,
7794					      /*sks_valid*/ 1,
7795					      /*command*/ 0,
7796					      /*field*/ 8,
7797					      /*bit_valid*/ 0,
7798					      /*bit*/ 0);
7799			ctl_done((union ctl_io *)ctsio);
7800			return (1);
7801		}
7802	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7803		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7804		int found = 0;
7805
7806		if (res_key == sa_res_key) {
7807			/* special case */
7808			/*
7809			 * The spec implies this is not good but doesn't
7810			 * say what to do. There are two choices either
7811			 * generate a res conflict or check condition
7812			 * with illegal field in parameter data. Since
7813			 * that is what is done when the sa_res_key is
7814			 * zero I'll take that approach since this has
7815			 * to do with the sa_res_key.
7816			 */
7817			mtx_unlock(&lun->lun_lock);
7818			free(ctsio->kern_data_ptr, M_CTL);
7819			ctl_set_invalid_field(ctsio,
7820					      /*sks_valid*/ 1,
7821					      /*command*/ 0,
7822					      /*field*/ 8,
7823					      /*bit_valid*/ 0,
7824					      /*bit*/ 0);
7825			ctl_done((union ctl_io *)ctsio);
7826			return (1);
7827		}
7828
7829		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7830			if (ctl_get_prkey(lun, i) != sa_res_key)
7831				continue;
7832
7833			found = 1;
7834			ctl_clr_prkey(lun, i);
7835			lun->pr_key_count--;
7836			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7837		}
7838		if (!found) {
7839			mtx_unlock(&lun->lun_lock);
7840			free(ctsio->kern_data_ptr, M_CTL);
7841			ctl_set_reservation_conflict(ctsio);
7842			ctl_done((union ctl_io *)ctsio);
7843			return (CTL_RETVAL_COMPLETE);
7844		}
7845		lun->pr_generation++;
7846		mtx_unlock(&lun->lun_lock);
7847
7848		/* send msg to other side */
7849		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7850		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7851		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7852		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7853		persis_io.pr.pr_info.res_type = type;
7854		memcpy(persis_io.pr.pr_info.sa_res_key,
7855		       param->serv_act_res_key,
7856		       sizeof(param->serv_act_res_key));
7857		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7858		    sizeof(persis_io.pr), M_WAITOK);
7859	} else {
7860		/* Reserved but not all registrants */
7861		/* sa_res_key is res holder */
7862		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7863			/* validate scope and type */
7864			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7865			     SPR_LU_SCOPE) {
7866				mtx_unlock(&lun->lun_lock);
7867				ctl_set_invalid_field(/*ctsio*/ ctsio,
7868						      /*sks_valid*/ 1,
7869						      /*command*/ 1,
7870						      /*field*/ 2,
7871						      /*bit_valid*/ 1,
7872						      /*bit*/ 4);
7873				ctl_done((union ctl_io *)ctsio);
7874				return (1);
7875			}
7876
7877			if (type>8 || type==2 || type==4 || type==0) {
7878				mtx_unlock(&lun->lun_lock);
7879				ctl_set_invalid_field(/*ctsio*/ ctsio,
7880						      /*sks_valid*/ 1,
7881						      /*command*/ 1,
7882						      /*field*/ 2,
7883						      /*bit_valid*/ 1,
7884						      /*bit*/ 0);
7885				ctl_done((union ctl_io *)ctsio);
7886				return (1);
7887			}
7888
7889			/*
7890			 * Do the following:
7891			 * if sa_res_key != res_key remove all
7892			 * registrants w/sa_res_key and generate UA
7893			 * for these registrants(Registrations
7894			 * Preempted) if it wasn't an exclusive
7895			 * reservation generate UA(Reservations
7896			 * Preempted) for all other registered nexuses
7897			 * if the type has changed. Establish the new
7898			 * reservation and holder. If res_key and
7899			 * sa_res_key are the same do the above
7900			 * except don't unregister the res holder.
7901			 */
7902
7903			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7904				if (i == residx || ctl_get_prkey(lun, i) == 0)
7905					continue;
7906
7907				if (sa_res_key == ctl_get_prkey(lun, i)) {
7908					ctl_clr_prkey(lun, i);
7909					lun->pr_key_count--;
7910					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7911				} else if (type != lun->pr_res_type &&
7912				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7913				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7914					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7915				}
7916			}
7917			lun->pr_res_type = type;
7918			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7919			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7920				lun->pr_res_idx = residx;
7921			else
7922				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7923			lun->pr_generation++;
7924			mtx_unlock(&lun->lun_lock);
7925
7926			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7927			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7928			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7929			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7930			persis_io.pr.pr_info.res_type = type;
7931			memcpy(persis_io.pr.pr_info.sa_res_key,
7932			       param->serv_act_res_key,
7933			       sizeof(param->serv_act_res_key));
7934			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7935			    sizeof(persis_io.pr), M_WAITOK);
7936		} else {
7937			/*
7938			 * sa_res_key is not the res holder just
7939			 * remove registrants
7940			 */
7941			int found=0;
7942
7943			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7944				if (sa_res_key != ctl_get_prkey(lun, i))
7945					continue;
7946
7947				found = 1;
7948				ctl_clr_prkey(lun, i);
7949				lun->pr_key_count--;
7950				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7951			}
7952
7953			if (!found) {
7954				mtx_unlock(&lun->lun_lock);
7955				free(ctsio->kern_data_ptr, M_CTL);
7956				ctl_set_reservation_conflict(ctsio);
7957				ctl_done((union ctl_io *)ctsio);
7958		        	return (1);
7959			}
7960			lun->pr_generation++;
7961			mtx_unlock(&lun->lun_lock);
7962
7963			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7964			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7965			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7966			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7967			persis_io.pr.pr_info.res_type = type;
7968			memcpy(persis_io.pr.pr_info.sa_res_key,
7969			       param->serv_act_res_key,
7970			       sizeof(param->serv_act_res_key));
7971			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7972			    sizeof(persis_io.pr), M_WAITOK);
7973		}
7974	}
7975	return (0);
7976}
7977
7978static void
7979ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7980{
7981	uint64_t sa_res_key;
7982	int i;
7983
7984	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7985
7986	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7987	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7988	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7989		if (sa_res_key == 0) {
7990			/*
7991			 * Unregister everybody else and build UA for
7992			 * them
7993			 */
7994			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7995				if (i == msg->pr.pr_info.residx ||
7996				    ctl_get_prkey(lun, i) == 0)
7997					continue;
7998
7999				ctl_clr_prkey(lun, i);
8000				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8001			}
8002
8003			lun->pr_key_count = 1;
8004			lun->pr_res_type = msg->pr.pr_info.res_type;
8005			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8006			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8007				lun->pr_res_idx = msg->pr.pr_info.residx;
8008		} else {
8009		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8010				if (sa_res_key == ctl_get_prkey(lun, i))
8011					continue;
8012
8013				ctl_clr_prkey(lun, i);
8014				lun->pr_key_count--;
8015				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8016			}
8017		}
8018	} else {
8019		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8020			if (i == msg->pr.pr_info.residx ||
8021			    ctl_get_prkey(lun, i) == 0)
8022				continue;
8023
8024			if (sa_res_key == ctl_get_prkey(lun, i)) {
8025				ctl_clr_prkey(lun, i);
8026				lun->pr_key_count--;
8027				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8028			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8029			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8030			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8031				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8032			}
8033		}
8034		lun->pr_res_type = msg->pr.pr_info.res_type;
8035		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8036		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8037			lun->pr_res_idx = msg->pr.pr_info.residx;
8038		else
8039			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8040	}
8041	lun->pr_generation++;
8042
8043}
8044
8045
8046int
8047ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8048{
8049	int retval;
8050	u_int32_t param_len;
8051	struct scsi_per_res_out *cdb;
8052	struct ctl_lun *lun;
8053	struct scsi_per_res_out_parms* param;
8054	struct ctl_softc *softc;
8055	uint32_t residx;
8056	uint64_t res_key, sa_res_key, key;
8057	uint8_t type;
8058	union ctl_ha_msg persis_io;
8059	int    i;
8060
8061	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8062
8063	retval = CTL_RETVAL_COMPLETE;
8064
8065	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8066	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8067	softc = lun->ctl_softc;
8068
8069	/*
8070	 * We only support whole-LUN scope.  The scope & type are ignored for
8071	 * register, register and ignore existing key and clear.
8072	 * We sometimes ignore scope and type on preempts too!!
8073	 * Verify reservation type here as well.
8074	 */
8075	type = cdb->scope_type & SPR_TYPE_MASK;
8076	if ((cdb->action == SPRO_RESERVE)
8077	 || (cdb->action == SPRO_RELEASE)) {
8078		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8079			ctl_set_invalid_field(/*ctsio*/ ctsio,
8080					      /*sks_valid*/ 1,
8081					      /*command*/ 1,
8082					      /*field*/ 2,
8083					      /*bit_valid*/ 1,
8084					      /*bit*/ 4);
8085			ctl_done((union ctl_io *)ctsio);
8086			return (CTL_RETVAL_COMPLETE);
8087		}
8088
8089		if (type>8 || type==2 || type==4 || type==0) {
8090			ctl_set_invalid_field(/*ctsio*/ ctsio,
8091					      /*sks_valid*/ 1,
8092					      /*command*/ 1,
8093					      /*field*/ 2,
8094					      /*bit_valid*/ 1,
8095					      /*bit*/ 0);
8096			ctl_done((union ctl_io *)ctsio);
8097			return (CTL_RETVAL_COMPLETE);
8098		}
8099	}
8100
8101	param_len = scsi_4btoul(cdb->length);
8102
8103	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8104		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8105		ctsio->kern_data_len = param_len;
8106		ctsio->kern_total_len = param_len;
8107		ctsio->kern_data_resid = 0;
8108		ctsio->kern_rel_offset = 0;
8109		ctsio->kern_sg_entries = 0;
8110		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8111		ctsio->be_move_done = ctl_config_move_done;
8112		ctl_datamove((union ctl_io *)ctsio);
8113
8114		return (CTL_RETVAL_COMPLETE);
8115	}
8116
8117	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8118
8119	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8120	res_key = scsi_8btou64(param->res_key.key);
8121	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8122
8123	/*
8124	 * Validate the reservation key here except for SPRO_REG_IGNO
8125	 * This must be done for all other service actions
8126	 */
8127	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8128		mtx_lock(&lun->lun_lock);
8129		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8130			if (res_key != key) {
8131				/*
8132				 * The current key passed in doesn't match
8133				 * the one the initiator previously
8134				 * registered.
8135				 */
8136				mtx_unlock(&lun->lun_lock);
8137				free(ctsio->kern_data_ptr, M_CTL);
8138				ctl_set_reservation_conflict(ctsio);
8139				ctl_done((union ctl_io *)ctsio);
8140				return (CTL_RETVAL_COMPLETE);
8141			}
8142		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8143			/*
8144			 * We are not registered
8145			 */
8146			mtx_unlock(&lun->lun_lock);
8147			free(ctsio->kern_data_ptr, M_CTL);
8148			ctl_set_reservation_conflict(ctsio);
8149			ctl_done((union ctl_io *)ctsio);
8150			return (CTL_RETVAL_COMPLETE);
8151		} else if (res_key != 0) {
8152			/*
8153			 * We are not registered and trying to register but
8154			 * the register key isn't zero.
8155			 */
8156			mtx_unlock(&lun->lun_lock);
8157			free(ctsio->kern_data_ptr, M_CTL);
8158			ctl_set_reservation_conflict(ctsio);
8159			ctl_done((union ctl_io *)ctsio);
8160			return (CTL_RETVAL_COMPLETE);
8161		}
8162		mtx_unlock(&lun->lun_lock);
8163	}
8164
8165	switch (cdb->action & SPRO_ACTION_MASK) {
8166	case SPRO_REGISTER:
8167	case SPRO_REG_IGNO: {
8168
8169#if 0
8170		printf("Registration received\n");
8171#endif
8172
8173		/*
8174		 * We don't support any of these options, as we report in
8175		 * the read capabilities request (see
8176		 * ctl_persistent_reserve_in(), above).
8177		 */
8178		if ((param->flags & SPR_SPEC_I_PT)
8179		 || (param->flags & SPR_ALL_TG_PT)
8180		 || (param->flags & SPR_APTPL)) {
8181			int bit_ptr;
8182
8183			if (param->flags & SPR_APTPL)
8184				bit_ptr = 0;
8185			else if (param->flags & SPR_ALL_TG_PT)
8186				bit_ptr = 2;
8187			else /* SPR_SPEC_I_PT */
8188				bit_ptr = 3;
8189
8190			free(ctsio->kern_data_ptr, M_CTL);
8191			ctl_set_invalid_field(ctsio,
8192					      /*sks_valid*/ 1,
8193					      /*command*/ 0,
8194					      /*field*/ 20,
8195					      /*bit_valid*/ 1,
8196					      /*bit*/ bit_ptr);
8197			ctl_done((union ctl_io *)ctsio);
8198			return (CTL_RETVAL_COMPLETE);
8199		}
8200
8201		mtx_lock(&lun->lun_lock);
8202
8203		/*
8204		 * The initiator wants to clear the
8205		 * key/unregister.
8206		 */
8207		if (sa_res_key == 0) {
8208			if ((res_key == 0
8209			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8210			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8211			  && ctl_get_prkey(lun, residx) == 0)) {
8212				mtx_unlock(&lun->lun_lock);
8213				goto done;
8214			}
8215
8216			ctl_clr_prkey(lun, residx);
8217			lun->pr_key_count--;
8218
8219			if (residx == lun->pr_res_idx) {
8220				lun->flags &= ~CTL_LUN_PR_RESERVED;
8221				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8222
8223				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8224				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8225				    lun->pr_key_count) {
8226					/*
8227					 * If the reservation is a registrants
8228					 * only type we need to generate a UA
8229					 * for other registered inits.  The
8230					 * sense code should be RESERVATIONS
8231					 * RELEASED
8232					 */
8233
8234					for (i = softc->init_min; i < softc->init_max; i++){
8235						if (ctl_get_prkey(lun, i) == 0)
8236							continue;
8237						ctl_est_ua(lun, i,
8238						    CTL_UA_RES_RELEASE);
8239					}
8240				}
8241				lun->pr_res_type = 0;
8242			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8243				if (lun->pr_key_count==0) {
8244					lun->flags &= ~CTL_LUN_PR_RESERVED;
8245					lun->pr_res_type = 0;
8246					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8247				}
8248			}
8249			lun->pr_generation++;
8250			mtx_unlock(&lun->lun_lock);
8251
8252			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8253			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8254			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8255			persis_io.pr.pr_info.residx = residx;
8256			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8257			    sizeof(persis_io.pr), M_WAITOK);
8258		} else /* sa_res_key != 0 */ {
8259
8260			/*
8261			 * If we aren't registered currently then increment
8262			 * the key count and set the registered flag.
8263			 */
8264			ctl_alloc_prkey(lun, residx);
8265			if (ctl_get_prkey(lun, residx) == 0)
8266				lun->pr_key_count++;
8267			ctl_set_prkey(lun, residx, sa_res_key);
8268			lun->pr_generation++;
8269			mtx_unlock(&lun->lun_lock);
8270
8271			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8272			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8273			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8274			persis_io.pr.pr_info.residx = residx;
8275			memcpy(persis_io.pr.pr_info.sa_res_key,
8276			       param->serv_act_res_key,
8277			       sizeof(param->serv_act_res_key));
8278			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8279			    sizeof(persis_io.pr), M_WAITOK);
8280		}
8281
8282		break;
8283	}
8284	case SPRO_RESERVE:
8285#if 0
8286                printf("Reserve executed type %d\n", type);
8287#endif
8288		mtx_lock(&lun->lun_lock);
8289		if (lun->flags & CTL_LUN_PR_RESERVED) {
8290			/*
8291			 * if this isn't the reservation holder and it's
8292			 * not a "all registrants" type or if the type is
8293			 * different then we have a conflict
8294			 */
8295			if ((lun->pr_res_idx != residx
8296			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8297			 || lun->pr_res_type != type) {
8298				mtx_unlock(&lun->lun_lock);
8299				free(ctsio->kern_data_ptr, M_CTL);
8300				ctl_set_reservation_conflict(ctsio);
8301				ctl_done((union ctl_io *)ctsio);
8302				return (CTL_RETVAL_COMPLETE);
8303			}
8304			mtx_unlock(&lun->lun_lock);
8305		} else /* create a reservation */ {
8306			/*
8307			 * If it's not an "all registrants" type record
8308			 * reservation holder
8309			 */
8310			if (type != SPR_TYPE_WR_EX_AR
8311			 && type != SPR_TYPE_EX_AC_AR)
8312				lun->pr_res_idx = residx; /* Res holder */
8313			else
8314				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8315
8316			lun->flags |= CTL_LUN_PR_RESERVED;
8317			lun->pr_res_type = type;
8318
8319			mtx_unlock(&lun->lun_lock);
8320
8321			/* send msg to other side */
8322			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8323			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8324			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8325			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8326			persis_io.pr.pr_info.res_type = type;
8327			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8328			    sizeof(persis_io.pr), M_WAITOK);
8329		}
8330		break;
8331
8332	case SPRO_RELEASE:
8333		mtx_lock(&lun->lun_lock);
8334		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8335			/* No reservation exists return good status */
8336			mtx_unlock(&lun->lun_lock);
8337			goto done;
8338		}
8339		/*
8340		 * Is this nexus a reservation holder?
8341		 */
8342		if (lun->pr_res_idx != residx
8343		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8344			/*
8345			 * not a res holder return good status but
8346			 * do nothing
8347			 */
8348			mtx_unlock(&lun->lun_lock);
8349			goto done;
8350		}
8351
8352		if (lun->pr_res_type != type) {
8353			mtx_unlock(&lun->lun_lock);
8354			free(ctsio->kern_data_ptr, M_CTL);
8355			ctl_set_illegal_pr_release(ctsio);
8356			ctl_done((union ctl_io *)ctsio);
8357			return (CTL_RETVAL_COMPLETE);
8358		}
8359
8360		/* okay to release */
8361		lun->flags &= ~CTL_LUN_PR_RESERVED;
8362		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8363		lun->pr_res_type = 0;
8364
8365		/*
8366		 * if this isn't an exclusive access
8367		 * res generate UA for all other
8368		 * registrants.
8369		 */
8370		if (type != SPR_TYPE_EX_AC
8371		 && type != SPR_TYPE_WR_EX) {
8372			for (i = softc->init_min; i < softc->init_max; i++) {
8373				if (i == residx || ctl_get_prkey(lun, i) == 0)
8374					continue;
8375				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8376			}
8377		}
8378		mtx_unlock(&lun->lun_lock);
8379
8380		/* Send msg to other side */
8381		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8382		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8383		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8384		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8385		     sizeof(persis_io.pr), M_WAITOK);
8386		break;
8387
8388	case SPRO_CLEAR:
8389		/* send msg to other side */
8390
8391		mtx_lock(&lun->lun_lock);
8392		lun->flags &= ~CTL_LUN_PR_RESERVED;
8393		lun->pr_res_type = 0;
8394		lun->pr_key_count = 0;
8395		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8396
8397		ctl_clr_prkey(lun, residx);
8398		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8399			if (ctl_get_prkey(lun, i) != 0) {
8400				ctl_clr_prkey(lun, i);
8401				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8402			}
8403		lun->pr_generation++;
8404		mtx_unlock(&lun->lun_lock);
8405
8406		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8407		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8408		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8409		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8410		     sizeof(persis_io.pr), M_WAITOK);
8411		break;
8412
8413	case SPRO_PREEMPT:
8414	case SPRO_PRE_ABO: {
8415		int nretval;
8416
8417		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8418					  residx, ctsio, cdb, param);
8419		if (nretval != 0)
8420			return (CTL_RETVAL_COMPLETE);
8421		break;
8422	}
8423	default:
8424		panic("Invalid PR type %x", cdb->action);
8425	}
8426
8427done:
8428	free(ctsio->kern_data_ptr, M_CTL);
8429	ctl_set_success(ctsio);
8430	ctl_done((union ctl_io *)ctsio);
8431
8432	return (retval);
8433}
8434
8435/*
8436 * This routine is for handling a message from the other SC pertaining to
8437 * persistent reserve out. All the error checking will have been done
8438 * so only perorming the action need be done here to keep the two
8439 * in sync.
8440 */
8441static void
8442ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8443{
8444	struct ctl_softc *softc = control_softc;
8445	struct ctl_lun *lun;
8446	int i;
8447	uint32_t residx, targ_lun;
8448
8449	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8450	mtx_lock(&softc->ctl_lock);
8451	if ((targ_lun >= CTL_MAX_LUNS) ||
8452	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8453		mtx_unlock(&softc->ctl_lock);
8454		return;
8455	}
8456	mtx_lock(&lun->lun_lock);
8457	mtx_unlock(&softc->ctl_lock);
8458	if (lun->flags & CTL_LUN_DISABLED) {
8459		mtx_unlock(&lun->lun_lock);
8460		return;
8461	}
8462	residx = ctl_get_initindex(&msg->hdr.nexus);
8463	switch(msg->pr.pr_info.action) {
8464	case CTL_PR_REG_KEY:
8465		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8466		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8467			lun->pr_key_count++;
8468		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8469		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8470		lun->pr_generation++;
8471		break;
8472
8473	case CTL_PR_UNREG_KEY:
8474		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8475		lun->pr_key_count--;
8476
8477		/* XXX Need to see if the reservation has been released */
8478		/* if so do we need to generate UA? */
8479		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8480			lun->flags &= ~CTL_LUN_PR_RESERVED;
8481			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8482
8483			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8484			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8485			    lun->pr_key_count) {
8486				/*
8487				 * If the reservation is a registrants
8488				 * only type we need to generate a UA
8489				 * for other registered inits.  The
8490				 * sense code should be RESERVATIONS
8491				 * RELEASED
8492				 */
8493
8494				for (i = softc->init_min; i < softc->init_max; i++) {
8495					if (ctl_get_prkey(lun, i) == 0)
8496						continue;
8497
8498					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8499				}
8500			}
8501			lun->pr_res_type = 0;
8502		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8503			if (lun->pr_key_count==0) {
8504				lun->flags &= ~CTL_LUN_PR_RESERVED;
8505				lun->pr_res_type = 0;
8506				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8507			}
8508		}
8509		lun->pr_generation++;
8510		break;
8511
8512	case CTL_PR_RESERVE:
8513		lun->flags |= CTL_LUN_PR_RESERVED;
8514		lun->pr_res_type = msg->pr.pr_info.res_type;
8515		lun->pr_res_idx = msg->pr.pr_info.residx;
8516
8517		break;
8518
8519	case CTL_PR_RELEASE:
8520		/*
8521		 * if this isn't an exclusive access res generate UA for all
8522		 * other registrants.
8523		 */
8524		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8525		    lun->pr_res_type != SPR_TYPE_WR_EX) {
8526			for (i = softc->init_min; i < softc->init_max; i++)
8527				if (i == residx || ctl_get_prkey(lun, i) == 0)
8528					continue;
8529				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8530		}
8531
8532		lun->flags &= ~CTL_LUN_PR_RESERVED;
8533		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8534		lun->pr_res_type = 0;
8535		break;
8536
8537	case CTL_PR_PREEMPT:
8538		ctl_pro_preempt_other(lun, msg);
8539		break;
8540	case CTL_PR_CLEAR:
8541		lun->flags &= ~CTL_LUN_PR_RESERVED;
8542		lun->pr_res_type = 0;
8543		lun->pr_key_count = 0;
8544		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8545
8546		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8547			if (ctl_get_prkey(lun, i) == 0)
8548				continue;
8549			ctl_clr_prkey(lun, i);
8550			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8551		}
8552		lun->pr_generation++;
8553		break;
8554	}
8555
8556	mtx_unlock(&lun->lun_lock);
8557}
8558
8559int
8560ctl_read_write(struct ctl_scsiio *ctsio)
8561{
8562	struct ctl_lun *lun;
8563	struct ctl_lba_len_flags *lbalen;
8564	uint64_t lba;
8565	uint32_t num_blocks;
8566	int flags, retval;
8567	int isread;
8568
8569	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8570
8571	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8572
8573	flags = 0;
8574	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8575	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8576	switch (ctsio->cdb[0]) {
8577	case READ_6:
8578	case WRITE_6: {
8579		struct scsi_rw_6 *cdb;
8580
8581		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8582
8583		lba = scsi_3btoul(cdb->addr);
8584		/* only 5 bits are valid in the most significant address byte */
8585		lba &= 0x1fffff;
8586		num_blocks = cdb->length;
8587		/*
8588		 * This is correct according to SBC-2.
8589		 */
8590		if (num_blocks == 0)
8591			num_blocks = 256;
8592		break;
8593	}
8594	case READ_10:
8595	case WRITE_10: {
8596		struct scsi_rw_10 *cdb;
8597
8598		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8599		if (cdb->byte2 & SRW10_FUA)
8600			flags |= CTL_LLF_FUA;
8601		if (cdb->byte2 & SRW10_DPO)
8602			flags |= CTL_LLF_DPO;
8603		lba = scsi_4btoul(cdb->addr);
8604		num_blocks = scsi_2btoul(cdb->length);
8605		break;
8606	}
8607	case WRITE_VERIFY_10: {
8608		struct scsi_write_verify_10 *cdb;
8609
8610		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8611		flags |= CTL_LLF_FUA;
8612		if (cdb->byte2 & SWV_DPO)
8613			flags |= CTL_LLF_DPO;
8614		lba = scsi_4btoul(cdb->addr);
8615		num_blocks = scsi_2btoul(cdb->length);
8616		break;
8617	}
8618	case READ_12:
8619	case WRITE_12: {
8620		struct scsi_rw_12 *cdb;
8621
8622		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8623		if (cdb->byte2 & SRW12_FUA)
8624			flags |= CTL_LLF_FUA;
8625		if (cdb->byte2 & SRW12_DPO)
8626			flags |= CTL_LLF_DPO;
8627		lba = scsi_4btoul(cdb->addr);
8628		num_blocks = scsi_4btoul(cdb->length);
8629		break;
8630	}
8631	case WRITE_VERIFY_12: {
8632		struct scsi_write_verify_12 *cdb;
8633
8634		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8635		flags |= CTL_LLF_FUA;
8636		if (cdb->byte2 & SWV_DPO)
8637			flags |= CTL_LLF_DPO;
8638		lba = scsi_4btoul(cdb->addr);
8639		num_blocks = scsi_4btoul(cdb->length);
8640		break;
8641	}
8642	case READ_16:
8643	case WRITE_16: {
8644		struct scsi_rw_16 *cdb;
8645
8646		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8647		if (cdb->byte2 & SRW12_FUA)
8648			flags |= CTL_LLF_FUA;
8649		if (cdb->byte2 & SRW12_DPO)
8650			flags |= CTL_LLF_DPO;
8651		lba = scsi_8btou64(cdb->addr);
8652		num_blocks = scsi_4btoul(cdb->length);
8653		break;
8654	}
8655	case WRITE_ATOMIC_16: {
8656		struct scsi_write_atomic_16 *cdb;
8657
8658		if (lun->be_lun->atomicblock == 0) {
8659			ctl_set_invalid_opcode(ctsio);
8660			ctl_done((union ctl_io *)ctsio);
8661			return (CTL_RETVAL_COMPLETE);
8662		}
8663
8664		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8665		if (cdb->byte2 & SRW12_FUA)
8666			flags |= CTL_LLF_FUA;
8667		if (cdb->byte2 & SRW12_DPO)
8668			flags |= CTL_LLF_DPO;
8669		lba = scsi_8btou64(cdb->addr);
8670		num_blocks = scsi_2btoul(cdb->length);
8671		if (num_blocks > lun->be_lun->atomicblock) {
8672			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8673			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8674			    /*bit*/ 0);
8675			ctl_done((union ctl_io *)ctsio);
8676			return (CTL_RETVAL_COMPLETE);
8677		}
8678		break;
8679	}
8680	case WRITE_VERIFY_16: {
8681		struct scsi_write_verify_16 *cdb;
8682
8683		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8684		flags |= CTL_LLF_FUA;
8685		if (cdb->byte2 & SWV_DPO)
8686			flags |= CTL_LLF_DPO;
8687		lba = scsi_8btou64(cdb->addr);
8688		num_blocks = scsi_4btoul(cdb->length);
8689		break;
8690	}
8691	default:
8692		/*
8693		 * We got a command we don't support.  This shouldn't
8694		 * happen, commands should be filtered out above us.
8695		 */
8696		ctl_set_invalid_opcode(ctsio);
8697		ctl_done((union ctl_io *)ctsio);
8698
8699		return (CTL_RETVAL_COMPLETE);
8700		break; /* NOTREACHED */
8701	}
8702
8703	/*
8704	 * The first check is to make sure we're in bounds, the second
8705	 * check is to catch wrap-around problems.  If the lba + num blocks
8706	 * is less than the lba, then we've wrapped around and the block
8707	 * range is invalid anyway.
8708	 */
8709	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8710	 || ((lba + num_blocks) < lba)) {
8711		ctl_set_lba_out_of_range(ctsio);
8712		ctl_done((union ctl_io *)ctsio);
8713		return (CTL_RETVAL_COMPLETE);
8714	}
8715
8716	/*
8717	 * According to SBC-3, a transfer length of 0 is not an error.
8718	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8719	 * translates to 256 blocks for those commands.
8720	 */
8721	if (num_blocks == 0) {
8722		ctl_set_success(ctsio);
8723		ctl_done((union ctl_io *)ctsio);
8724		return (CTL_RETVAL_COMPLETE);
8725	}
8726
8727	/* Set FUA and/or DPO if caches are disabled. */
8728	if (isread) {
8729		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8730		    SCP_RCD) != 0)
8731			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8732	} else {
8733		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8734		    SCP_WCE) == 0)
8735			flags |= CTL_LLF_FUA;
8736	}
8737
8738	lbalen = (struct ctl_lba_len_flags *)
8739	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8740	lbalen->lba = lba;
8741	lbalen->len = num_blocks;
8742	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8743
8744	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8745	ctsio->kern_rel_offset = 0;
8746
8747	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8748
8749	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8750	return (retval);
8751}
8752
8753static int
8754ctl_cnw_cont(union ctl_io *io)
8755{
8756	struct ctl_scsiio *ctsio;
8757	struct ctl_lun *lun;
8758	struct ctl_lba_len_flags *lbalen;
8759	int retval;
8760
8761	ctsio = &io->scsiio;
8762	ctsio->io_hdr.status = CTL_STATUS_NONE;
8763	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8764	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8765	lbalen = (struct ctl_lba_len_flags *)
8766	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8767	lbalen->flags &= ~CTL_LLF_COMPARE;
8768	lbalen->flags |= CTL_LLF_WRITE;
8769
8770	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8771	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8772	return (retval);
8773}
8774
8775int
8776ctl_cnw(struct ctl_scsiio *ctsio)
8777{
8778	struct ctl_lun *lun;
8779	struct ctl_lba_len_flags *lbalen;
8780	uint64_t lba;
8781	uint32_t num_blocks;
8782	int flags, retval;
8783
8784	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8785
8786	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8787
8788	flags = 0;
8789	switch (ctsio->cdb[0]) {
8790	case COMPARE_AND_WRITE: {
8791		struct scsi_compare_and_write *cdb;
8792
8793		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8794		if (cdb->byte2 & SRW10_FUA)
8795			flags |= CTL_LLF_FUA;
8796		if (cdb->byte2 & SRW10_DPO)
8797			flags |= CTL_LLF_DPO;
8798		lba = scsi_8btou64(cdb->addr);
8799		num_blocks = cdb->length;
8800		break;
8801	}
8802	default:
8803		/*
8804		 * We got a command we don't support.  This shouldn't
8805		 * happen, commands should be filtered out above us.
8806		 */
8807		ctl_set_invalid_opcode(ctsio);
8808		ctl_done((union ctl_io *)ctsio);
8809
8810		return (CTL_RETVAL_COMPLETE);
8811		break; /* NOTREACHED */
8812	}
8813
8814	/*
8815	 * The first check is to make sure we're in bounds, the second
8816	 * check is to catch wrap-around problems.  If the lba + num blocks
8817	 * is less than the lba, then we've wrapped around and the block
8818	 * range is invalid anyway.
8819	 */
8820	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8821	 || ((lba + num_blocks) < lba)) {
8822		ctl_set_lba_out_of_range(ctsio);
8823		ctl_done((union ctl_io *)ctsio);
8824		return (CTL_RETVAL_COMPLETE);
8825	}
8826
8827	/*
8828	 * According to SBC-3, a transfer length of 0 is not an error.
8829	 */
8830	if (num_blocks == 0) {
8831		ctl_set_success(ctsio);
8832		ctl_done((union ctl_io *)ctsio);
8833		return (CTL_RETVAL_COMPLETE);
8834	}
8835
8836	/* Set FUA if write cache is disabled. */
8837	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8838	    SCP_WCE) == 0)
8839		flags |= CTL_LLF_FUA;
8840
8841	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8842	ctsio->kern_rel_offset = 0;
8843
8844	/*
8845	 * Set the IO_CONT flag, so that if this I/O gets passed to
8846	 * ctl_data_submit_done(), it'll get passed back to
8847	 * ctl_ctl_cnw_cont() for further processing.
8848	 */
8849	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8850	ctsio->io_cont = ctl_cnw_cont;
8851
8852	lbalen = (struct ctl_lba_len_flags *)
8853	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8854	lbalen->lba = lba;
8855	lbalen->len = num_blocks;
8856	lbalen->flags = CTL_LLF_COMPARE | flags;
8857
8858	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8859	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8860	return (retval);
8861}
8862
8863int
8864ctl_verify(struct ctl_scsiio *ctsio)
8865{
8866	struct ctl_lun *lun;
8867	struct ctl_lba_len_flags *lbalen;
8868	uint64_t lba;
8869	uint32_t num_blocks;
8870	int bytchk, flags;
8871	int retval;
8872
8873	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8874
8875	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8876
8877	bytchk = 0;
8878	flags = CTL_LLF_FUA;
8879	switch (ctsio->cdb[0]) {
8880	case VERIFY_10: {
8881		struct scsi_verify_10 *cdb;
8882
8883		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8884		if (cdb->byte2 & SVFY_BYTCHK)
8885			bytchk = 1;
8886		if (cdb->byte2 & SVFY_DPO)
8887			flags |= CTL_LLF_DPO;
8888		lba = scsi_4btoul(cdb->addr);
8889		num_blocks = scsi_2btoul(cdb->length);
8890		break;
8891	}
8892	case VERIFY_12: {
8893		struct scsi_verify_12 *cdb;
8894
8895		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8896		if (cdb->byte2 & SVFY_BYTCHK)
8897			bytchk = 1;
8898		if (cdb->byte2 & SVFY_DPO)
8899			flags |= CTL_LLF_DPO;
8900		lba = scsi_4btoul(cdb->addr);
8901		num_blocks = scsi_4btoul(cdb->length);
8902		break;
8903	}
8904	case VERIFY_16: {
8905		struct scsi_rw_16 *cdb;
8906
8907		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8908		if (cdb->byte2 & SVFY_BYTCHK)
8909			bytchk = 1;
8910		if (cdb->byte2 & SVFY_DPO)
8911			flags |= CTL_LLF_DPO;
8912		lba = scsi_8btou64(cdb->addr);
8913		num_blocks = scsi_4btoul(cdb->length);
8914		break;
8915	}
8916	default:
8917		/*
8918		 * We got a command we don't support.  This shouldn't
8919		 * happen, commands should be filtered out above us.
8920		 */
8921		ctl_set_invalid_opcode(ctsio);
8922		ctl_done((union ctl_io *)ctsio);
8923		return (CTL_RETVAL_COMPLETE);
8924	}
8925
8926	/*
8927	 * The first check is to make sure we're in bounds, the second
8928	 * check is to catch wrap-around problems.  If the lba + num blocks
8929	 * is less than the lba, then we've wrapped around and the block
8930	 * range is invalid anyway.
8931	 */
8932	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8933	 || ((lba + num_blocks) < lba)) {
8934		ctl_set_lba_out_of_range(ctsio);
8935		ctl_done((union ctl_io *)ctsio);
8936		return (CTL_RETVAL_COMPLETE);
8937	}
8938
8939	/*
8940	 * According to SBC-3, a transfer length of 0 is not an error.
8941	 */
8942	if (num_blocks == 0) {
8943		ctl_set_success(ctsio);
8944		ctl_done((union ctl_io *)ctsio);
8945		return (CTL_RETVAL_COMPLETE);
8946	}
8947
8948	lbalen = (struct ctl_lba_len_flags *)
8949	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8950	lbalen->lba = lba;
8951	lbalen->len = num_blocks;
8952	if (bytchk) {
8953		lbalen->flags = CTL_LLF_COMPARE | flags;
8954		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8955	} else {
8956		lbalen->flags = CTL_LLF_VERIFY | flags;
8957		ctsio->kern_total_len = 0;
8958	}
8959	ctsio->kern_rel_offset = 0;
8960
8961	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8962	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8963	return (retval);
8964}
8965
8966int
8967ctl_report_luns(struct ctl_scsiio *ctsio)
8968{
8969	struct ctl_softc *softc;
8970	struct scsi_report_luns *cdb;
8971	struct scsi_report_luns_data *lun_data;
8972	struct ctl_lun *lun, *request_lun;
8973	struct ctl_port *port;
8974	int num_luns, retval;
8975	uint32_t alloc_len, lun_datalen;
8976	int num_filled;
8977	uint32_t initidx, targ_lun_id, lun_id;
8978
8979	retval = CTL_RETVAL_COMPLETE;
8980	cdb = (struct scsi_report_luns *)ctsio->cdb;
8981	port = ctl_io_port(&ctsio->io_hdr);
8982	softc = port->ctl_softc;
8983
8984	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8985
8986	mtx_lock(&softc->ctl_lock);
8987	num_luns = 0;
8988	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8989		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8990			num_luns++;
8991	}
8992	mtx_unlock(&softc->ctl_lock);
8993
8994	switch (cdb->select_report) {
8995	case RPL_REPORT_DEFAULT:
8996	case RPL_REPORT_ALL:
8997	case RPL_REPORT_NONSUBSID:
8998		break;
8999	case RPL_REPORT_WELLKNOWN:
9000	case RPL_REPORT_ADMIN:
9001	case RPL_REPORT_CONGLOM:
9002		num_luns = 0;
9003		break;
9004	default:
9005		ctl_set_invalid_field(ctsio,
9006				      /*sks_valid*/ 1,
9007				      /*command*/ 1,
9008				      /*field*/ 2,
9009				      /*bit_valid*/ 0,
9010				      /*bit*/ 0);
9011		ctl_done((union ctl_io *)ctsio);
9012		return (retval);
9013		break; /* NOTREACHED */
9014	}
9015
9016	alloc_len = scsi_4btoul(cdb->length);
9017	/*
9018	 * The initiator has to allocate at least 16 bytes for this request,
9019	 * so he can at least get the header and the first LUN.  Otherwise
9020	 * we reject the request (per SPC-3 rev 14, section 6.21).
9021	 */
9022	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9023	    sizeof(struct scsi_report_luns_lundata))) {
9024		ctl_set_invalid_field(ctsio,
9025				      /*sks_valid*/ 1,
9026				      /*command*/ 1,
9027				      /*field*/ 6,
9028				      /*bit_valid*/ 0,
9029				      /*bit*/ 0);
9030		ctl_done((union ctl_io *)ctsio);
9031		return (retval);
9032	}
9033
9034	request_lun = (struct ctl_lun *)
9035		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9036
9037	lun_datalen = sizeof(*lun_data) +
9038		(num_luns * sizeof(struct scsi_report_luns_lundata));
9039
9040	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9041	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9042	ctsio->kern_sg_entries = 0;
9043
9044	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9045
9046	mtx_lock(&softc->ctl_lock);
9047	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9048		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9049		if (lun_id >= CTL_MAX_LUNS)
9050			continue;
9051		lun = softc->ctl_luns[lun_id];
9052		if (lun == NULL)
9053			continue;
9054
9055		if (targ_lun_id <= 0xff) {
9056			/*
9057			 * Peripheral addressing method, bus number 0.
9058			 */
9059			lun_data->luns[num_filled].lundata[0] =
9060				RPL_LUNDATA_ATYP_PERIPH;
9061			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9062			num_filled++;
9063		} else if (targ_lun_id <= 0x3fff) {
9064			/*
9065			 * Flat addressing method.
9066			 */
9067			lun_data->luns[num_filled].lundata[0] =
9068				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9069			lun_data->luns[num_filled].lundata[1] =
9070				(targ_lun_id & 0xff);
9071			num_filled++;
9072		} else if (targ_lun_id <= 0xffffff) {
9073			/*
9074			 * Extended flat addressing method.
9075			 */
9076			lun_data->luns[num_filled].lundata[0] =
9077			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9078			scsi_ulto3b(targ_lun_id,
9079			    &lun_data->luns[num_filled].lundata[1]);
9080			num_filled++;
9081		} else {
9082			printf("ctl_report_luns: bogus LUN number %jd, "
9083			       "skipping\n", (intmax_t)targ_lun_id);
9084		}
9085		/*
9086		 * According to SPC-3, rev 14 section 6.21:
9087		 *
9088		 * "The execution of a REPORT LUNS command to any valid and
9089		 * installed logical unit shall clear the REPORTED LUNS DATA
9090		 * HAS CHANGED unit attention condition for all logical
9091		 * units of that target with respect to the requesting
9092		 * initiator. A valid and installed logical unit is one
9093		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9094		 * INQUIRY data (see 6.4.2)."
9095		 *
9096		 * If request_lun is NULL, the LUN this report luns command
9097		 * was issued to is either disabled or doesn't exist. In that
9098		 * case, we shouldn't clear any pending lun change unit
9099		 * attention.
9100		 */
9101		if (request_lun != NULL) {
9102			mtx_lock(&lun->lun_lock);
9103			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9104			mtx_unlock(&lun->lun_lock);
9105		}
9106	}
9107	mtx_unlock(&softc->ctl_lock);
9108
9109	/*
9110	 * It's quite possible that we've returned fewer LUNs than we allocated
9111	 * space for.  Trim it.
9112	 */
9113	lun_datalen = sizeof(*lun_data) +
9114		(num_filled * sizeof(struct scsi_report_luns_lundata));
9115
9116	if (lun_datalen < alloc_len) {
9117		ctsio->residual = alloc_len - lun_datalen;
9118		ctsio->kern_data_len = lun_datalen;
9119		ctsio->kern_total_len = lun_datalen;
9120	} else {
9121		ctsio->residual = 0;
9122		ctsio->kern_data_len = alloc_len;
9123		ctsio->kern_total_len = alloc_len;
9124	}
9125	ctsio->kern_data_resid = 0;
9126	ctsio->kern_rel_offset = 0;
9127	ctsio->kern_sg_entries = 0;
9128
9129	/*
9130	 * We set this to the actual data length, regardless of how much
9131	 * space we actually have to return results.  If the user looks at
9132	 * this value, he'll know whether or not he allocated enough space
9133	 * and reissue the command if necessary.  We don't support well
9134	 * known logical units, so if the user asks for that, return none.
9135	 */
9136	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9137
9138	/*
9139	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9140	 * this request.
9141	 */
9142	ctl_set_success(ctsio);
9143	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9144	ctsio->be_move_done = ctl_config_move_done;
9145	ctl_datamove((union ctl_io *)ctsio);
9146	return (retval);
9147}
9148
9149int
9150ctl_request_sense(struct ctl_scsiio *ctsio)
9151{
9152	struct scsi_request_sense *cdb;
9153	struct scsi_sense_data *sense_ptr;
9154	struct ctl_softc *ctl_softc;
9155	struct ctl_lun *lun;
9156	uint32_t initidx;
9157	int have_error;
9158	scsi_sense_data_type sense_format;
9159	ctl_ua_type ua_type;
9160
9161	cdb = (struct scsi_request_sense *)ctsio->cdb;
9162
9163	ctl_softc = control_softc;
9164	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9165
9166	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9167
9168	/*
9169	 * Determine which sense format the user wants.
9170	 */
9171	if (cdb->byte2 & SRS_DESC)
9172		sense_format = SSD_TYPE_DESC;
9173	else
9174		sense_format = SSD_TYPE_FIXED;
9175
9176	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9177	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9178	ctsio->kern_sg_entries = 0;
9179
9180	/*
9181	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9182	 * larger than the largest allowed value for the length field in the
9183	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9184	 */
9185	ctsio->residual = 0;
9186	ctsio->kern_data_len = cdb->length;
9187	ctsio->kern_total_len = cdb->length;
9188
9189	ctsio->kern_data_resid = 0;
9190	ctsio->kern_rel_offset = 0;
9191	ctsio->kern_sg_entries = 0;
9192
9193	/*
9194	 * If we don't have a LUN, we don't have any pending sense.
9195	 */
9196	if (lun == NULL)
9197		goto no_sense;
9198
9199	have_error = 0;
9200	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9201	/*
9202	 * Check for pending sense, and then for pending unit attentions.
9203	 * Pending sense gets returned first, then pending unit attentions.
9204	 */
9205	mtx_lock(&lun->lun_lock);
9206#ifdef CTL_WITH_CA
9207	if (ctl_is_set(lun->have_ca, initidx)) {
9208		scsi_sense_data_type stored_format;
9209
9210		/*
9211		 * Check to see which sense format was used for the stored
9212		 * sense data.
9213		 */
9214		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9215
9216		/*
9217		 * If the user requested a different sense format than the
9218		 * one we stored, then we need to convert it to the other
9219		 * format.  If we're going from descriptor to fixed format
9220		 * sense data, we may lose things in translation, depending
9221		 * on what options were used.
9222		 *
9223		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9224		 * for some reason we'll just copy it out as-is.
9225		 */
9226		if ((stored_format == SSD_TYPE_FIXED)
9227		 && (sense_format == SSD_TYPE_DESC))
9228			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9229			    &lun->pending_sense[initidx],
9230			    (struct scsi_sense_data_desc *)sense_ptr);
9231		else if ((stored_format == SSD_TYPE_DESC)
9232		      && (sense_format == SSD_TYPE_FIXED))
9233			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9234			    &lun->pending_sense[initidx],
9235			    (struct scsi_sense_data_fixed *)sense_ptr);
9236		else
9237			memcpy(sense_ptr, &lun->pending_sense[initidx],
9238			       MIN(sizeof(*sense_ptr),
9239			       sizeof(lun->pending_sense[initidx])));
9240
9241		ctl_clear_mask(lun->have_ca, initidx);
9242		have_error = 1;
9243	} else
9244#endif
9245	{
9246		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9247		if (ua_type != CTL_UA_NONE)
9248			have_error = 1;
9249		if (ua_type == CTL_UA_LUN_CHANGE) {
9250			mtx_unlock(&lun->lun_lock);
9251			mtx_lock(&ctl_softc->ctl_lock);
9252			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9253			mtx_unlock(&ctl_softc->ctl_lock);
9254			mtx_lock(&lun->lun_lock);
9255		}
9256
9257	}
9258	mtx_unlock(&lun->lun_lock);
9259
9260	/*
9261	 * We already have a pending error, return it.
9262	 */
9263	if (have_error != 0) {
9264		/*
9265		 * We report the SCSI status as OK, since the status of the
9266		 * request sense command itself is OK.
9267		 * We report 0 for the sense length, because we aren't doing
9268		 * autosense in this case.  We're reporting sense as
9269		 * parameter data.
9270		 */
9271		ctl_set_success(ctsio);
9272		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9273		ctsio->be_move_done = ctl_config_move_done;
9274		ctl_datamove((union ctl_io *)ctsio);
9275		return (CTL_RETVAL_COMPLETE);
9276	}
9277
9278no_sense:
9279
9280	/*
9281	 * No sense information to report, so we report that everything is
9282	 * okay.
9283	 */
9284	ctl_set_sense_data(sense_ptr,
9285			   lun,
9286			   sense_format,
9287			   /*current_error*/ 1,
9288			   /*sense_key*/ SSD_KEY_NO_SENSE,
9289			   /*asc*/ 0x00,
9290			   /*ascq*/ 0x00,
9291			   SSD_ELEM_NONE);
9292
9293	/*
9294	 * We report 0 for the sense length, because we aren't doing
9295	 * autosense in this case.  We're reporting sense as parameter data.
9296	 */
9297	ctl_set_success(ctsio);
9298	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9299	ctsio->be_move_done = ctl_config_move_done;
9300	ctl_datamove((union ctl_io *)ctsio);
9301	return (CTL_RETVAL_COMPLETE);
9302}
9303
9304int
9305ctl_tur(struct ctl_scsiio *ctsio)
9306{
9307
9308	CTL_DEBUG_PRINT(("ctl_tur\n"));
9309
9310	ctl_set_success(ctsio);
9311	ctl_done((union ctl_io *)ctsio);
9312
9313	return (CTL_RETVAL_COMPLETE);
9314}
9315
9316/*
9317 * SCSI VPD page 0x00, the Supported VPD Pages page.
9318 */
9319static int
9320ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9321{
9322	struct scsi_vpd_supported_pages *pages;
9323	int sup_page_size;
9324	struct ctl_lun *lun;
9325	int p;
9326
9327	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9328
9329	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9330	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9331	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9332	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9333	ctsio->kern_sg_entries = 0;
9334
9335	if (sup_page_size < alloc_len) {
9336		ctsio->residual = alloc_len - sup_page_size;
9337		ctsio->kern_data_len = sup_page_size;
9338		ctsio->kern_total_len = sup_page_size;
9339	} else {
9340		ctsio->residual = 0;
9341		ctsio->kern_data_len = alloc_len;
9342		ctsio->kern_total_len = alloc_len;
9343	}
9344	ctsio->kern_data_resid = 0;
9345	ctsio->kern_rel_offset = 0;
9346	ctsio->kern_sg_entries = 0;
9347
9348	/*
9349	 * The control device is always connected.  The disk device, on the
9350	 * other hand, may not be online all the time.  Need to change this
9351	 * to figure out whether the disk device is actually online or not.
9352	 */
9353	if (lun != NULL)
9354		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9355				lun->be_lun->lun_type;
9356	else
9357		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9358
9359	p = 0;
9360	/* Supported VPD pages */
9361	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9362	/* Serial Number */
9363	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9364	/* Device Identification */
9365	pages->page_list[p++] = SVPD_DEVICE_ID;
9366	/* Extended INQUIRY Data */
9367	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9368	/* Mode Page Policy */
9369	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9370	/* SCSI Ports */
9371	pages->page_list[p++] = SVPD_SCSI_PORTS;
9372	/* Third-party Copy */
9373	pages->page_list[p++] = SVPD_SCSI_TPC;
9374	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9375		/* Block limits */
9376		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9377		/* Block Device Characteristics */
9378		pages->page_list[p++] = SVPD_BDC;
9379		/* Logical Block Provisioning */
9380		pages->page_list[p++] = SVPD_LBP;
9381	}
9382	pages->length = p;
9383
9384	ctl_set_success(ctsio);
9385	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9386	ctsio->be_move_done = ctl_config_move_done;
9387	ctl_datamove((union ctl_io *)ctsio);
9388	return (CTL_RETVAL_COMPLETE);
9389}
9390
9391/*
9392 * SCSI VPD page 0x80, the Unit Serial Number page.
9393 */
9394static int
9395ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9396{
9397	struct scsi_vpd_unit_serial_number *sn_ptr;
9398	struct ctl_lun *lun;
9399	int data_len;
9400
9401	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9402
9403	data_len = 4 + CTL_SN_LEN;
9404	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9405	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9406	if (data_len < alloc_len) {
9407		ctsio->residual = alloc_len - data_len;
9408		ctsio->kern_data_len = data_len;
9409		ctsio->kern_total_len = data_len;
9410	} else {
9411		ctsio->residual = 0;
9412		ctsio->kern_data_len = alloc_len;
9413		ctsio->kern_total_len = alloc_len;
9414	}
9415	ctsio->kern_data_resid = 0;
9416	ctsio->kern_rel_offset = 0;
9417	ctsio->kern_sg_entries = 0;
9418
9419	/*
9420	 * The control device is always connected.  The disk device, on the
9421	 * other hand, may not be online all the time.  Need to change this
9422	 * to figure out whether the disk device is actually online or not.
9423	 */
9424	if (lun != NULL)
9425		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9426				  lun->be_lun->lun_type;
9427	else
9428		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9429
9430	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9431	sn_ptr->length = CTL_SN_LEN;
9432	/*
9433	 * If we don't have a LUN, we just leave the serial number as
9434	 * all spaces.
9435	 */
9436	if (lun != NULL) {
9437		strncpy((char *)sn_ptr->serial_num,
9438			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9439	} else
9440		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9441
9442	ctl_set_success(ctsio);
9443	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9444	ctsio->be_move_done = ctl_config_move_done;
9445	ctl_datamove((union ctl_io *)ctsio);
9446	return (CTL_RETVAL_COMPLETE);
9447}
9448
9449
9450/*
9451 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9452 */
9453static int
9454ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9455{
9456	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9457	struct ctl_lun *lun;
9458	int data_len;
9459
9460	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9461
9462	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9463	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9464	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9465	ctsio->kern_sg_entries = 0;
9466
9467	if (data_len < alloc_len) {
9468		ctsio->residual = alloc_len - data_len;
9469		ctsio->kern_data_len = data_len;
9470		ctsio->kern_total_len = data_len;
9471	} else {
9472		ctsio->residual = 0;
9473		ctsio->kern_data_len = alloc_len;
9474		ctsio->kern_total_len = alloc_len;
9475	}
9476	ctsio->kern_data_resid = 0;
9477	ctsio->kern_rel_offset = 0;
9478	ctsio->kern_sg_entries = 0;
9479
9480	/*
9481	 * The control device is always connected.  The disk device, on the
9482	 * other hand, may not be online all the time.
9483	 */
9484	if (lun != NULL)
9485		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9486				     lun->be_lun->lun_type;
9487	else
9488		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9489	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9490	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9491	/*
9492	 * We support head of queue, ordered and simple tags.
9493	 */
9494	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9495	/*
9496	 * Volatile cache supported.
9497	 */
9498	eid_ptr->flags3 = SVPD_EID_V_SUP;
9499
9500	/*
9501	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9502	 * attention for a particular IT nexus on all LUNs once we report
9503	 * it to that nexus once.  This bit is required as of SPC-4.
9504	 */
9505	eid_ptr->flags4 = SVPD_EID_LUICLT;
9506
9507	/*
9508	 * XXX KDM in order to correctly answer this, we would need
9509	 * information from the SIM to determine how much sense data it
9510	 * can send.  So this would really be a path inquiry field, most
9511	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9512	 * but the hardware may or may not be able to support that much.
9513	 * 0 just means that the maximum sense data length is not reported.
9514	 */
9515	eid_ptr->max_sense_length = 0;
9516
9517	ctl_set_success(ctsio);
9518	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9519	ctsio->be_move_done = ctl_config_move_done;
9520	ctl_datamove((union ctl_io *)ctsio);
9521	return (CTL_RETVAL_COMPLETE);
9522}
9523
9524static int
9525ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9526{
9527	struct scsi_vpd_mode_page_policy *mpp_ptr;
9528	struct ctl_lun *lun;
9529	int data_len;
9530
9531	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9532
9533	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9534	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9535
9536	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9537	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9538	ctsio->kern_sg_entries = 0;
9539
9540	if (data_len < alloc_len) {
9541		ctsio->residual = alloc_len - data_len;
9542		ctsio->kern_data_len = data_len;
9543		ctsio->kern_total_len = data_len;
9544	} else {
9545		ctsio->residual = 0;
9546		ctsio->kern_data_len = alloc_len;
9547		ctsio->kern_total_len = alloc_len;
9548	}
9549	ctsio->kern_data_resid = 0;
9550	ctsio->kern_rel_offset = 0;
9551	ctsio->kern_sg_entries = 0;
9552
9553	/*
9554	 * The control device is always connected.  The disk device, on the
9555	 * other hand, may not be online all the time.
9556	 */
9557	if (lun != NULL)
9558		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9559				     lun->be_lun->lun_type;
9560	else
9561		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9562	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9563	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9564	mpp_ptr->descr[0].page_code = 0x3f;
9565	mpp_ptr->descr[0].subpage_code = 0xff;
9566	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9567
9568	ctl_set_success(ctsio);
9569	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9570	ctsio->be_move_done = ctl_config_move_done;
9571	ctl_datamove((union ctl_io *)ctsio);
9572	return (CTL_RETVAL_COMPLETE);
9573}
9574
9575/*
9576 * SCSI VPD page 0x83, the Device Identification page.
9577 */
9578static int
9579ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9580{
9581	struct scsi_vpd_device_id *devid_ptr;
9582	struct scsi_vpd_id_descriptor *desc;
9583	struct ctl_softc *softc;
9584	struct ctl_lun *lun;
9585	struct ctl_port *port;
9586	int data_len;
9587	uint8_t proto;
9588
9589	softc = control_softc;
9590
9591	port = ctl_io_port(&ctsio->io_hdr);
9592	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9593
9594	data_len = sizeof(struct scsi_vpd_device_id) +
9595	    sizeof(struct scsi_vpd_id_descriptor) +
9596		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9597	    sizeof(struct scsi_vpd_id_descriptor) +
9598		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9599	if (lun && lun->lun_devid)
9600		data_len += lun->lun_devid->len;
9601	if (port && port->port_devid)
9602		data_len += port->port_devid->len;
9603	if (port && port->target_devid)
9604		data_len += port->target_devid->len;
9605
9606	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9607	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9608	ctsio->kern_sg_entries = 0;
9609
9610	if (data_len < alloc_len) {
9611		ctsio->residual = alloc_len - data_len;
9612		ctsio->kern_data_len = data_len;
9613		ctsio->kern_total_len = data_len;
9614	} else {
9615		ctsio->residual = 0;
9616		ctsio->kern_data_len = alloc_len;
9617		ctsio->kern_total_len = alloc_len;
9618	}
9619	ctsio->kern_data_resid = 0;
9620	ctsio->kern_rel_offset = 0;
9621	ctsio->kern_sg_entries = 0;
9622
9623	/*
9624	 * The control device is always connected.  The disk device, on the
9625	 * other hand, may not be online all the time.
9626	 */
9627	if (lun != NULL)
9628		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9629				     lun->be_lun->lun_type;
9630	else
9631		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9632	devid_ptr->page_code = SVPD_DEVICE_ID;
9633	scsi_ulto2b(data_len - 4, devid_ptr->length);
9634
9635	if (port && port->port_type == CTL_PORT_FC)
9636		proto = SCSI_PROTO_FC << 4;
9637	else if (port && port->port_type == CTL_PORT_ISCSI)
9638		proto = SCSI_PROTO_ISCSI << 4;
9639	else
9640		proto = SCSI_PROTO_SPI << 4;
9641	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9642
9643	/*
9644	 * We're using a LUN association here.  i.e., this device ID is a
9645	 * per-LUN identifier.
9646	 */
9647	if (lun && lun->lun_devid) {
9648		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9649		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9650		    lun->lun_devid->len);
9651	}
9652
9653	/*
9654	 * This is for the WWPN which is a port association.
9655	 */
9656	if (port && port->port_devid) {
9657		memcpy(desc, port->port_devid->data, port->port_devid->len);
9658		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9659		    port->port_devid->len);
9660	}
9661
9662	/*
9663	 * This is for the Relative Target Port(type 4h) identifier
9664	 */
9665	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9666	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9667	    SVPD_ID_TYPE_RELTARG;
9668	desc->length = 4;
9669	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9670	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9671	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9672
9673	/*
9674	 * This is for the Target Port Group(type 5h) identifier
9675	 */
9676	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9677	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9678	    SVPD_ID_TYPE_TPORTGRP;
9679	desc->length = 4;
9680	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9681	    &desc->identifier[2]);
9682	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9683	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9684
9685	/*
9686	 * This is for the Target identifier
9687	 */
9688	if (port && port->target_devid) {
9689		memcpy(desc, port->target_devid->data, port->target_devid->len);
9690	}
9691
9692	ctl_set_success(ctsio);
9693	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9694	ctsio->be_move_done = ctl_config_move_done;
9695	ctl_datamove((union ctl_io *)ctsio);
9696	return (CTL_RETVAL_COMPLETE);
9697}
9698
9699static int
9700ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9701{
9702	struct ctl_softc *softc = control_softc;
9703	struct scsi_vpd_scsi_ports *sp;
9704	struct scsi_vpd_port_designation *pd;
9705	struct scsi_vpd_port_designation_cont *pdc;
9706	struct ctl_lun *lun;
9707	struct ctl_port *port;
9708	int data_len, num_target_ports, iid_len, id_len;
9709
9710	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9711
9712	num_target_ports = 0;
9713	iid_len = 0;
9714	id_len = 0;
9715	mtx_lock(&softc->ctl_lock);
9716	STAILQ_FOREACH(port, &softc->port_list, links) {
9717		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9718			continue;
9719		if (lun != NULL &&
9720		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9721			continue;
9722		num_target_ports++;
9723		if (port->init_devid)
9724			iid_len += port->init_devid->len;
9725		if (port->port_devid)
9726			id_len += port->port_devid->len;
9727	}
9728	mtx_unlock(&softc->ctl_lock);
9729
9730	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9731	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9732	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9733	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9734	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9735	ctsio->kern_sg_entries = 0;
9736
9737	if (data_len < alloc_len) {
9738		ctsio->residual = alloc_len - data_len;
9739		ctsio->kern_data_len = data_len;
9740		ctsio->kern_total_len = data_len;
9741	} else {
9742		ctsio->residual = 0;
9743		ctsio->kern_data_len = alloc_len;
9744		ctsio->kern_total_len = alloc_len;
9745	}
9746	ctsio->kern_data_resid = 0;
9747	ctsio->kern_rel_offset = 0;
9748	ctsio->kern_sg_entries = 0;
9749
9750	/*
9751	 * The control device is always connected.  The disk device, on the
9752	 * other hand, may not be online all the time.  Need to change this
9753	 * to figure out whether the disk device is actually online or not.
9754	 */
9755	if (lun != NULL)
9756		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9757				  lun->be_lun->lun_type;
9758	else
9759		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9760
9761	sp->page_code = SVPD_SCSI_PORTS;
9762	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9763	    sp->page_length);
9764	pd = &sp->design[0];
9765
9766	mtx_lock(&softc->ctl_lock);
9767	STAILQ_FOREACH(port, &softc->port_list, links) {
9768		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9769			continue;
9770		if (lun != NULL &&
9771		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9772			continue;
9773		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9774		if (port->init_devid) {
9775			iid_len = port->init_devid->len;
9776			memcpy(pd->initiator_transportid,
9777			    port->init_devid->data, port->init_devid->len);
9778		} else
9779			iid_len = 0;
9780		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9781		pdc = (struct scsi_vpd_port_designation_cont *)
9782		    (&pd->initiator_transportid[iid_len]);
9783		if (port->port_devid) {
9784			id_len = port->port_devid->len;
9785			memcpy(pdc->target_port_descriptors,
9786			    port->port_devid->data, port->port_devid->len);
9787		} else
9788			id_len = 0;
9789		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9790		pd = (struct scsi_vpd_port_designation *)
9791		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9792	}
9793	mtx_unlock(&softc->ctl_lock);
9794
9795	ctl_set_success(ctsio);
9796	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9797	ctsio->be_move_done = ctl_config_move_done;
9798	ctl_datamove((union ctl_io *)ctsio);
9799	return (CTL_RETVAL_COMPLETE);
9800}
9801
9802static int
9803ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9804{
9805	struct scsi_vpd_block_limits *bl_ptr;
9806	struct ctl_lun *lun;
9807
9808	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9809
9810	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9811	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9812	ctsio->kern_sg_entries = 0;
9813
9814	if (sizeof(*bl_ptr) < alloc_len) {
9815		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9816		ctsio->kern_data_len = sizeof(*bl_ptr);
9817		ctsio->kern_total_len = sizeof(*bl_ptr);
9818	} else {
9819		ctsio->residual = 0;
9820		ctsio->kern_data_len = alloc_len;
9821		ctsio->kern_total_len = alloc_len;
9822	}
9823	ctsio->kern_data_resid = 0;
9824	ctsio->kern_rel_offset = 0;
9825	ctsio->kern_sg_entries = 0;
9826
9827	/*
9828	 * The control device is always connected.  The disk device, on the
9829	 * other hand, may not be online all the time.  Need to change this
9830	 * to figure out whether the disk device is actually online or not.
9831	 */
9832	if (lun != NULL)
9833		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9834				  lun->be_lun->lun_type;
9835	else
9836		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9837
9838	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9839	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9840	bl_ptr->max_cmp_write_len = 0xff;
9841	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9842	if (lun != NULL) {
9843		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9844		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9845			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9846			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9847			if (lun->be_lun->ublockexp != 0) {
9848				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9849				    bl_ptr->opt_unmap_grain);
9850				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9851				    bl_ptr->unmap_grain_align);
9852			}
9853		}
9854		scsi_ulto4b(lun->be_lun->atomicblock,
9855		    bl_ptr->max_atomic_transfer_length);
9856		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9857		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9858		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9859		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9860	}
9861	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9862
9863	ctl_set_success(ctsio);
9864	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9865	ctsio->be_move_done = ctl_config_move_done;
9866	ctl_datamove((union ctl_io *)ctsio);
9867	return (CTL_RETVAL_COMPLETE);
9868}
9869
9870static int
9871ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9872{
9873	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9874	struct ctl_lun *lun;
9875	const char *value;
9876	u_int i;
9877
9878	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9879
9880	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9881	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9882	ctsio->kern_sg_entries = 0;
9883
9884	if (sizeof(*bdc_ptr) < alloc_len) {
9885		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9886		ctsio->kern_data_len = sizeof(*bdc_ptr);
9887		ctsio->kern_total_len = sizeof(*bdc_ptr);
9888	} else {
9889		ctsio->residual = 0;
9890		ctsio->kern_data_len = alloc_len;
9891		ctsio->kern_total_len = alloc_len;
9892	}
9893	ctsio->kern_data_resid = 0;
9894	ctsio->kern_rel_offset = 0;
9895	ctsio->kern_sg_entries = 0;
9896
9897	/*
9898	 * The control device is always connected.  The disk device, on the
9899	 * other hand, may not be online all the time.  Need to change this
9900	 * to figure out whether the disk device is actually online or not.
9901	 */
9902	if (lun != NULL)
9903		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9904				  lun->be_lun->lun_type;
9905	else
9906		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9907	bdc_ptr->page_code = SVPD_BDC;
9908	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9909	if (lun != NULL &&
9910	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9911		i = strtol(value, NULL, 0);
9912	else
9913		i = CTL_DEFAULT_ROTATION_RATE;
9914	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9915	if (lun != NULL &&
9916	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9917		i = strtol(value, NULL, 0);
9918	else
9919		i = 0;
9920	bdc_ptr->wab_wac_ff = (i & 0x0f);
9921	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9922
9923	ctl_set_success(ctsio);
9924	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9925	ctsio->be_move_done = ctl_config_move_done;
9926	ctl_datamove((union ctl_io *)ctsio);
9927	return (CTL_RETVAL_COMPLETE);
9928}
9929
9930static int
9931ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9932{
9933	struct scsi_vpd_logical_block_prov *lbp_ptr;
9934	struct ctl_lun *lun;
9935
9936	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9937
9938	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9939	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9940	ctsio->kern_sg_entries = 0;
9941
9942	if (sizeof(*lbp_ptr) < alloc_len) {
9943		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9944		ctsio->kern_data_len = sizeof(*lbp_ptr);
9945		ctsio->kern_total_len = sizeof(*lbp_ptr);
9946	} else {
9947		ctsio->residual = 0;
9948		ctsio->kern_data_len = alloc_len;
9949		ctsio->kern_total_len = alloc_len;
9950	}
9951	ctsio->kern_data_resid = 0;
9952	ctsio->kern_rel_offset = 0;
9953	ctsio->kern_sg_entries = 0;
9954
9955	/*
9956	 * The control device is always connected.  The disk device, on the
9957	 * other hand, may not be online all the time.  Need to change this
9958	 * to figure out whether the disk device is actually online or not.
9959	 */
9960	if (lun != NULL)
9961		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9962				  lun->be_lun->lun_type;
9963	else
9964		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9965
9966	lbp_ptr->page_code = SVPD_LBP;
9967	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9968	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9969	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9970		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9971		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9972		lbp_ptr->prov_type = SVPD_LBP_THIN;
9973	}
9974
9975	ctl_set_success(ctsio);
9976	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9977	ctsio->be_move_done = ctl_config_move_done;
9978	ctl_datamove((union ctl_io *)ctsio);
9979	return (CTL_RETVAL_COMPLETE);
9980}
9981
9982/*
9983 * INQUIRY with the EVPD bit set.
9984 */
9985static int
9986ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9987{
9988	struct ctl_lun *lun;
9989	struct scsi_inquiry *cdb;
9990	int alloc_len, retval;
9991
9992	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9993	cdb = (struct scsi_inquiry *)ctsio->cdb;
9994	alloc_len = scsi_2btoul(cdb->length);
9995
9996	switch (cdb->page_code) {
9997	case SVPD_SUPPORTED_PAGES:
9998		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9999		break;
10000	case SVPD_UNIT_SERIAL_NUMBER:
10001		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10002		break;
10003	case SVPD_DEVICE_ID:
10004		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10005		break;
10006	case SVPD_EXTENDED_INQUIRY_DATA:
10007		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10008		break;
10009	case SVPD_MODE_PAGE_POLICY:
10010		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10011		break;
10012	case SVPD_SCSI_PORTS:
10013		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10014		break;
10015	case SVPD_SCSI_TPC:
10016		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10017		break;
10018	case SVPD_BLOCK_LIMITS:
10019		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10020			goto err;
10021		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10022		break;
10023	case SVPD_BDC:
10024		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10025			goto err;
10026		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10027		break;
10028	case SVPD_LBP:
10029		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10030			goto err;
10031		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10032		break;
10033	default:
10034err:
10035		ctl_set_invalid_field(ctsio,
10036				      /*sks_valid*/ 1,
10037				      /*command*/ 1,
10038				      /*field*/ 2,
10039				      /*bit_valid*/ 0,
10040				      /*bit*/ 0);
10041		ctl_done((union ctl_io *)ctsio);
10042		retval = CTL_RETVAL_COMPLETE;
10043		break;
10044	}
10045
10046	return (retval);
10047}
10048
10049/*
10050 * Standard INQUIRY data.
10051 */
10052static int
10053ctl_inquiry_std(struct ctl_scsiio *ctsio)
10054{
10055	struct scsi_inquiry_data *inq_ptr;
10056	struct scsi_inquiry *cdb;
10057	struct ctl_softc *softc = control_softc;
10058	struct ctl_port *port;
10059	struct ctl_lun *lun;
10060	char *val;
10061	uint32_t alloc_len, data_len;
10062	ctl_port_type port_type;
10063
10064	port = ctl_io_port(&ctsio->io_hdr);
10065	port_type = port->port_type;
10066	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10067		port_type = CTL_PORT_SCSI;
10068
10069	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10070	cdb = (struct scsi_inquiry *)ctsio->cdb;
10071	alloc_len = scsi_2btoul(cdb->length);
10072
10073	/*
10074	 * We malloc the full inquiry data size here and fill it
10075	 * in.  If the user only asks for less, we'll give him
10076	 * that much.
10077	 */
10078	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10079	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10080	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10081	ctsio->kern_sg_entries = 0;
10082	ctsio->kern_data_resid = 0;
10083	ctsio->kern_rel_offset = 0;
10084
10085	if (data_len < alloc_len) {
10086		ctsio->residual = alloc_len - data_len;
10087		ctsio->kern_data_len = data_len;
10088		ctsio->kern_total_len = data_len;
10089	} else {
10090		ctsio->residual = 0;
10091		ctsio->kern_data_len = alloc_len;
10092		ctsio->kern_total_len = alloc_len;
10093	}
10094
10095	if (lun != NULL) {
10096		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10097		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10098			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10099			    lun->be_lun->lun_type;
10100		} else {
10101			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10102			    lun->be_lun->lun_type;
10103		}
10104		if (lun->flags & CTL_LUN_REMOVABLE)
10105			inq_ptr->dev_qual2 |= SID_RMB;
10106	} else
10107		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10108
10109	/* RMB in byte 2 is 0 */
10110	inq_ptr->version = SCSI_REV_SPC4;
10111
10112	/*
10113	 * According to SAM-3, even if a device only supports a single
10114	 * level of LUN addressing, it should still set the HISUP bit:
10115	 *
10116	 * 4.9.1 Logical unit numbers overview
10117	 *
10118	 * All logical unit number formats described in this standard are
10119	 * hierarchical in structure even when only a single level in that
10120	 * hierarchy is used. The HISUP bit shall be set to one in the
10121	 * standard INQUIRY data (see SPC-2) when any logical unit number
10122	 * format described in this standard is used.  Non-hierarchical
10123	 * formats are outside the scope of this standard.
10124	 *
10125	 * Therefore we set the HiSup bit here.
10126	 *
10127	 * The reponse format is 2, per SPC-3.
10128	 */
10129	inq_ptr->response_format = SID_HiSup | 2;
10130
10131	inq_ptr->additional_length = data_len -
10132	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10133	CTL_DEBUG_PRINT(("additional_length = %d\n",
10134			 inq_ptr->additional_length));
10135
10136	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10137	if (port_type == CTL_PORT_SCSI)
10138		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10139	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10140	inq_ptr->flags = SID_CmdQue;
10141	if (port_type == CTL_PORT_SCSI)
10142		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10143
10144	/*
10145	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10146	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10147	 * name and 4 bytes for the revision.
10148	 */
10149	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10150	    "vendor")) == NULL) {
10151		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10152	} else {
10153		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10154		strncpy(inq_ptr->vendor, val,
10155		    min(sizeof(inq_ptr->vendor), strlen(val)));
10156	}
10157	if (lun == NULL) {
10158		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10159		    sizeof(inq_ptr->product));
10160	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10161		switch (lun->be_lun->lun_type) {
10162		case T_DIRECT:
10163			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10164			    sizeof(inq_ptr->product));
10165			break;
10166		case T_PROCESSOR:
10167			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10168			    sizeof(inq_ptr->product));
10169			break;
10170		case T_CDROM:
10171			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10172			    sizeof(inq_ptr->product));
10173			break;
10174		default:
10175			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10176			    sizeof(inq_ptr->product));
10177			break;
10178		}
10179	} else {
10180		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10181		strncpy(inq_ptr->product, val,
10182		    min(sizeof(inq_ptr->product), strlen(val)));
10183	}
10184
10185	/*
10186	 * XXX make this a macro somewhere so it automatically gets
10187	 * incremented when we make changes.
10188	 */
10189	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10190	    "revision")) == NULL) {
10191		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10192	} else {
10193		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10194		strncpy(inq_ptr->revision, val,
10195		    min(sizeof(inq_ptr->revision), strlen(val)));
10196	}
10197
10198	/*
10199	 * For parallel SCSI, we support double transition and single
10200	 * transition clocking.  We also support QAS (Quick Arbitration
10201	 * and Selection) and Information Unit transfers on both the
10202	 * control and array devices.
10203	 */
10204	if (port_type == CTL_PORT_SCSI)
10205		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10206				    SID_SPI_IUS;
10207
10208	/* SAM-5 (no version claimed) */
10209	scsi_ulto2b(0x00A0, inq_ptr->version1);
10210	/* SPC-4 (no version claimed) */
10211	scsi_ulto2b(0x0460, inq_ptr->version2);
10212	if (port_type == CTL_PORT_FC) {
10213		/* FCP-2 ANSI INCITS.350:2003 */
10214		scsi_ulto2b(0x0917, inq_ptr->version3);
10215	} else if (port_type == CTL_PORT_SCSI) {
10216		/* SPI-4 ANSI INCITS.362:200x */
10217		scsi_ulto2b(0x0B56, inq_ptr->version3);
10218	} else if (port_type == CTL_PORT_ISCSI) {
10219		/* iSCSI (no version claimed) */
10220		scsi_ulto2b(0x0960, inq_ptr->version3);
10221	} else if (port_type == CTL_PORT_SAS) {
10222		/* SAS (no version claimed) */
10223		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10224	}
10225
10226	if (lun == NULL) {
10227		/* SBC-4 (no version claimed) */
10228		scsi_ulto2b(0x0600, inq_ptr->version4);
10229	} else {
10230		switch (lun->be_lun->lun_type) {
10231		case T_DIRECT:
10232			/* SBC-4 (no version claimed) */
10233			scsi_ulto2b(0x0600, inq_ptr->version4);
10234			break;
10235		case T_PROCESSOR:
10236			break;
10237		case T_CDROM:
10238			/* MMC-6 (no version claimed) */
10239			scsi_ulto2b(0x04E0, inq_ptr->version4);
10240			break;
10241		default:
10242			break;
10243		}
10244	}
10245
10246	ctl_set_success(ctsio);
10247	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10248	ctsio->be_move_done = ctl_config_move_done;
10249	ctl_datamove((union ctl_io *)ctsio);
10250	return (CTL_RETVAL_COMPLETE);
10251}
10252
10253int
10254ctl_inquiry(struct ctl_scsiio *ctsio)
10255{
10256	struct scsi_inquiry *cdb;
10257	int retval;
10258
10259	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10260
10261	cdb = (struct scsi_inquiry *)ctsio->cdb;
10262	if (cdb->byte2 & SI_EVPD)
10263		retval = ctl_inquiry_evpd(ctsio);
10264	else if (cdb->page_code == 0)
10265		retval = ctl_inquiry_std(ctsio);
10266	else {
10267		ctl_set_invalid_field(ctsio,
10268				      /*sks_valid*/ 1,
10269				      /*command*/ 1,
10270				      /*field*/ 2,
10271				      /*bit_valid*/ 0,
10272				      /*bit*/ 0);
10273		ctl_done((union ctl_io *)ctsio);
10274		return (CTL_RETVAL_COMPLETE);
10275	}
10276
10277	return (retval);
10278}
10279
10280int
10281ctl_get_config(struct ctl_scsiio *ctsio)
10282{
10283	struct scsi_get_config_header *hdr;
10284	struct scsi_get_config_feature *feature;
10285	struct scsi_get_config *cdb;
10286	struct ctl_lun *lun;
10287	uint32_t alloc_len, data_len;
10288	int rt, starting;
10289
10290	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10291	cdb = (struct scsi_get_config *)ctsio->cdb;
10292	rt = (cdb->rt & SGC_RT_MASK);
10293	starting = scsi_2btoul(cdb->starting_feature);
10294	alloc_len = scsi_2btoul(cdb->length);
10295
10296	data_len = sizeof(struct scsi_get_config_header) +
10297	    sizeof(struct scsi_get_config_feature) + 8 +
10298	    sizeof(struct scsi_get_config_feature) + 8 +
10299	    sizeof(struct scsi_get_config_feature) + 4 +
10300	    sizeof(struct scsi_get_config_feature) + 4 +
10301	    sizeof(struct scsi_get_config_feature) + 8 +
10302	    sizeof(struct scsi_get_config_feature) +
10303	    sizeof(struct scsi_get_config_feature) + 4 +
10304	    sizeof(struct scsi_get_config_feature) + 4 +
10305	    sizeof(struct scsi_get_config_feature) + 4 +
10306	    sizeof(struct scsi_get_config_feature) + 4 +
10307	    sizeof(struct scsi_get_config_feature) + 4 +
10308	    sizeof(struct scsi_get_config_feature) + 4;
10309	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10310	ctsio->kern_sg_entries = 0;
10311	ctsio->kern_data_resid = 0;
10312	ctsio->kern_rel_offset = 0;
10313
10314	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10315	if (lun->flags & CTL_LUN_NO_MEDIA)
10316		scsi_ulto2b(0x0000, hdr->current_profile);
10317	else
10318		scsi_ulto2b(0x0010, hdr->current_profile);
10319	feature = (struct scsi_get_config_feature *)(hdr + 1);
10320
10321	if (starting > 0x003b)
10322		goto done;
10323	if (starting > 0x003a)
10324		goto f3b;
10325	if (starting > 0x002b)
10326		goto f3a;
10327	if (starting > 0x002a)
10328		goto f2b;
10329	if (starting > 0x001f)
10330		goto f2a;
10331	if (starting > 0x001e)
10332		goto f1f;
10333	if (starting > 0x001d)
10334		goto f1e;
10335	if (starting > 0x0010)
10336		goto f1d;
10337	if (starting > 0x0003)
10338		goto f10;
10339	if (starting > 0x0002)
10340		goto f3;
10341	if (starting > 0x0001)
10342		goto f2;
10343	if (starting > 0x0000)
10344		goto f1;
10345
10346	/* Profile List */
10347	scsi_ulto2b(0x0000, feature->feature_code);
10348	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10349	feature->add_length = 8;
10350	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10351	feature->feature_data[2] = 0x00;
10352	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10353	feature->feature_data[6] = 0x01;
10354	feature = (struct scsi_get_config_feature *)
10355	    &feature->feature_data[feature->add_length];
10356
10357f1:	/* Core */
10358	scsi_ulto2b(0x0001, feature->feature_code);
10359	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10360	feature->add_length = 8;
10361	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10362	feature->feature_data[4] = 0x03;
10363	feature = (struct scsi_get_config_feature *)
10364	    &feature->feature_data[feature->add_length];
10365
10366f2:	/* Morphing */
10367	scsi_ulto2b(0x0002, feature->feature_code);
10368	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10369	feature->add_length = 4;
10370	feature->feature_data[0] = 0x02;
10371	feature = (struct scsi_get_config_feature *)
10372	    &feature->feature_data[feature->add_length];
10373
10374f3:	/* Removable Medium */
10375	scsi_ulto2b(0x0003, feature->feature_code);
10376	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10377	feature->add_length = 4;
10378	feature->feature_data[0] = 0x39;
10379	feature = (struct scsi_get_config_feature *)
10380	    &feature->feature_data[feature->add_length];
10381
10382	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10383		goto done;
10384
10385f10:	/* Random Read */
10386	scsi_ulto2b(0x0010, feature->feature_code);
10387	feature->flags = 0x00;
10388	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10389		feature->flags |= SGC_F_CURRENT;
10390	feature->add_length = 8;
10391	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10392	scsi_ulto2b(1, &feature->feature_data[4]);
10393	feature->feature_data[6] = 0x00;
10394	feature = (struct scsi_get_config_feature *)
10395	    &feature->feature_data[feature->add_length];
10396
10397f1d:	/* Multi-Read */
10398	scsi_ulto2b(0x001D, feature->feature_code);
10399	feature->flags = 0x00;
10400	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10401		feature->flags |= SGC_F_CURRENT;
10402	feature->add_length = 0;
10403	feature = (struct scsi_get_config_feature *)
10404	    &feature->feature_data[feature->add_length];
10405
10406f1e:	/* CD Read */
10407	scsi_ulto2b(0x001E, feature->feature_code);
10408	feature->flags = 0x00;
10409	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10410		feature->flags |= SGC_F_CURRENT;
10411	feature->add_length = 4;
10412	feature->feature_data[0] = 0x00;
10413	feature = (struct scsi_get_config_feature *)
10414	    &feature->feature_data[feature->add_length];
10415
10416f1f:	/* DVD Read */
10417	scsi_ulto2b(0x001F, feature->feature_code);
10418	feature->flags = 0x08;
10419	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10420		feature->flags |= SGC_F_CURRENT;
10421	feature->add_length = 4;
10422	feature->feature_data[0] = 0x01;
10423	feature->feature_data[2] = 0x03;
10424	feature = (struct scsi_get_config_feature *)
10425	    &feature->feature_data[feature->add_length];
10426
10427f2a:	/* DVD+RW */
10428	scsi_ulto2b(0x002A, feature->feature_code);
10429	feature->flags = 0x04;
10430	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10431		feature->flags |= SGC_F_CURRENT;
10432	feature->add_length = 4;
10433	feature->feature_data[0] = 0x00;
10434	feature->feature_data[1] = 0x00;
10435	feature = (struct scsi_get_config_feature *)
10436	    &feature->feature_data[feature->add_length];
10437
10438f2b:	/* DVD+R */
10439	scsi_ulto2b(0x002B, feature->feature_code);
10440	feature->flags = 0x00;
10441	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10442		feature->flags |= SGC_F_CURRENT;
10443	feature->add_length = 4;
10444	feature->feature_data[0] = 0x00;
10445	feature = (struct scsi_get_config_feature *)
10446	    &feature->feature_data[feature->add_length];
10447
10448f3a:	/* DVD+RW Dual Layer */
10449	scsi_ulto2b(0x003A, feature->feature_code);
10450	feature->flags = 0x00;
10451	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10452		feature->flags |= SGC_F_CURRENT;
10453	feature->add_length = 4;
10454	feature->feature_data[0] = 0x00;
10455	feature->feature_data[1] = 0x00;
10456	feature = (struct scsi_get_config_feature *)
10457	    &feature->feature_data[feature->add_length];
10458
10459f3b:	/* DVD+R Dual Layer */
10460	scsi_ulto2b(0x003B, feature->feature_code);
10461	feature->flags = 0x00;
10462	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10463		feature->flags |= SGC_F_CURRENT;
10464	feature->add_length = 4;
10465	feature->feature_data[0] = 0x00;
10466	feature = (struct scsi_get_config_feature *)
10467	    &feature->feature_data[feature->add_length];
10468
10469done:
10470	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10471	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10472		feature = (struct scsi_get_config_feature *)(hdr + 1);
10473		if (scsi_2btoul(feature->feature_code) == starting)
10474			feature = (struct scsi_get_config_feature *)
10475			    &feature->feature_data[feature->add_length];
10476		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10477	}
10478	scsi_ulto4b(data_len - 4, hdr->data_length);
10479	if (data_len < alloc_len) {
10480		ctsio->residual = alloc_len - data_len;
10481		ctsio->kern_data_len = data_len;
10482		ctsio->kern_total_len = data_len;
10483	} else {
10484		ctsio->residual = 0;
10485		ctsio->kern_data_len = alloc_len;
10486		ctsio->kern_total_len = alloc_len;
10487	}
10488
10489	ctl_set_success(ctsio);
10490	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10491	ctsio->be_move_done = ctl_config_move_done;
10492	ctl_datamove((union ctl_io *)ctsio);
10493	return (CTL_RETVAL_COMPLETE);
10494}
10495
10496int
10497ctl_get_event_status(struct ctl_scsiio *ctsio)
10498{
10499	struct scsi_get_event_status_header *hdr;
10500	struct scsi_get_event_status *cdb;
10501	struct ctl_lun *lun;
10502	uint32_t alloc_len, data_len;
10503	int notif_class;
10504
10505	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10506	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10507	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10508		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10509		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10510		ctl_done((union ctl_io *)ctsio);
10511		return (CTL_RETVAL_COMPLETE);
10512	}
10513	notif_class = cdb->notif_class;
10514	alloc_len = scsi_2btoul(cdb->length);
10515
10516	data_len = sizeof(struct scsi_get_event_status_header);
10517	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10518	ctsio->kern_sg_entries = 0;
10519	ctsio->kern_data_resid = 0;
10520	ctsio->kern_rel_offset = 0;
10521
10522	if (data_len < alloc_len) {
10523		ctsio->residual = alloc_len - data_len;
10524		ctsio->kern_data_len = data_len;
10525		ctsio->kern_total_len = data_len;
10526	} else {
10527		ctsio->residual = 0;
10528		ctsio->kern_data_len = alloc_len;
10529		ctsio->kern_total_len = alloc_len;
10530	}
10531
10532	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10533	scsi_ulto2b(0, hdr->descr_length);
10534	hdr->nea_class = SGESN_NEA;
10535	hdr->supported_class = 0;
10536
10537	ctl_set_success(ctsio);
10538	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10539	ctsio->be_move_done = ctl_config_move_done;
10540	ctl_datamove((union ctl_io *)ctsio);
10541	return (CTL_RETVAL_COMPLETE);
10542}
10543
10544int
10545ctl_mechanism_status(struct ctl_scsiio *ctsio)
10546{
10547	struct scsi_mechanism_status_header *hdr;
10548	struct scsi_mechanism_status *cdb;
10549	struct ctl_lun *lun;
10550	uint32_t alloc_len, data_len;
10551
10552	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10553	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10554	alloc_len = scsi_2btoul(cdb->length);
10555
10556	data_len = sizeof(struct scsi_mechanism_status_header);
10557	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10558	ctsio->kern_sg_entries = 0;
10559	ctsio->kern_data_resid = 0;
10560	ctsio->kern_rel_offset = 0;
10561
10562	if (data_len < alloc_len) {
10563		ctsio->residual = alloc_len - data_len;
10564		ctsio->kern_data_len = data_len;
10565		ctsio->kern_total_len = data_len;
10566	} else {
10567		ctsio->residual = 0;
10568		ctsio->kern_data_len = alloc_len;
10569		ctsio->kern_total_len = alloc_len;
10570	}
10571
10572	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10573	hdr->state1 = 0x00;
10574	hdr->state2 = 0xe0;
10575	scsi_ulto3b(0, hdr->lba);
10576	hdr->slots_num = 0;
10577	scsi_ulto2b(0, hdr->slots_length);
10578
10579	ctl_set_success(ctsio);
10580	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10581	ctsio->be_move_done = ctl_config_move_done;
10582	ctl_datamove((union ctl_io *)ctsio);
10583	return (CTL_RETVAL_COMPLETE);
10584}
10585
10586static void
10587ctl_ultomsf(uint32_t lba, uint8_t *buf)
10588{
10589
10590	lba += 150;
10591	buf[0] = 0;
10592	buf[1] = bin2bcd((lba / 75) / 60);
10593	buf[2] = bin2bcd((lba / 75) % 60);
10594	buf[3] = bin2bcd(lba % 75);
10595}
10596
10597int
10598ctl_read_toc(struct ctl_scsiio *ctsio)
10599{
10600	struct scsi_read_toc_hdr *hdr;
10601	struct scsi_read_toc_type01_descr *descr;
10602	struct scsi_read_toc *cdb;
10603	struct ctl_lun *lun;
10604	uint32_t alloc_len, data_len;
10605	int format, msf;
10606
10607	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10608	cdb = (struct scsi_read_toc *)ctsio->cdb;
10609	msf = (cdb->byte2 & CD_MSF) != 0;
10610	format = cdb->format;
10611	alloc_len = scsi_2btoul(cdb->data_len);
10612
10613	data_len = sizeof(struct scsi_read_toc_hdr);
10614	if (format == 0)
10615		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10616	else
10617		data_len += sizeof(struct scsi_read_toc_type01_descr);
10618	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10619	ctsio->kern_sg_entries = 0;
10620	ctsio->kern_data_resid = 0;
10621	ctsio->kern_rel_offset = 0;
10622
10623	if (data_len < alloc_len) {
10624		ctsio->residual = alloc_len - data_len;
10625		ctsio->kern_data_len = data_len;
10626		ctsio->kern_total_len = data_len;
10627	} else {
10628		ctsio->residual = 0;
10629		ctsio->kern_data_len = alloc_len;
10630		ctsio->kern_total_len = alloc_len;
10631	}
10632
10633	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10634	if (format == 0) {
10635		scsi_ulto2b(0x12, hdr->data_length);
10636		hdr->first = 1;
10637		hdr->last = 1;
10638		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10639		descr->addr_ctl = 0x14;
10640		descr->track_number = 1;
10641		if (msf)
10642			ctl_ultomsf(0, descr->track_start);
10643		else
10644			scsi_ulto4b(0, descr->track_start);
10645		descr++;
10646		descr->addr_ctl = 0x14;
10647		descr->track_number = 0xaa;
10648		if (msf)
10649			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10650		else
10651			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10652	} else {
10653		scsi_ulto2b(0x0a, hdr->data_length);
10654		hdr->first = 1;
10655		hdr->last = 1;
10656		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10657		descr->addr_ctl = 0x14;
10658		descr->track_number = 1;
10659		if (msf)
10660			ctl_ultomsf(0, descr->track_start);
10661		else
10662			scsi_ulto4b(0, descr->track_start);
10663	}
10664
10665	ctl_set_success(ctsio);
10666	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10667	ctsio->be_move_done = ctl_config_move_done;
10668	ctl_datamove((union ctl_io *)ctsio);
10669	return (CTL_RETVAL_COMPLETE);
10670}
10671
10672/*
10673 * For known CDB types, parse the LBA and length.
10674 */
10675static int
10676ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10677{
10678	if (io->io_hdr.io_type != CTL_IO_SCSI)
10679		return (1);
10680
10681	switch (io->scsiio.cdb[0]) {
10682	case COMPARE_AND_WRITE: {
10683		struct scsi_compare_and_write *cdb;
10684
10685		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10686
10687		*lba = scsi_8btou64(cdb->addr);
10688		*len = cdb->length;
10689		break;
10690	}
10691	case READ_6:
10692	case WRITE_6: {
10693		struct scsi_rw_6 *cdb;
10694
10695		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10696
10697		*lba = scsi_3btoul(cdb->addr);
10698		/* only 5 bits are valid in the most significant address byte */
10699		*lba &= 0x1fffff;
10700		*len = cdb->length;
10701		break;
10702	}
10703	case READ_10:
10704	case WRITE_10: {
10705		struct scsi_rw_10 *cdb;
10706
10707		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10708
10709		*lba = scsi_4btoul(cdb->addr);
10710		*len = scsi_2btoul(cdb->length);
10711		break;
10712	}
10713	case WRITE_VERIFY_10: {
10714		struct scsi_write_verify_10 *cdb;
10715
10716		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10717
10718		*lba = scsi_4btoul(cdb->addr);
10719		*len = scsi_2btoul(cdb->length);
10720		break;
10721	}
10722	case READ_12:
10723	case WRITE_12: {
10724		struct scsi_rw_12 *cdb;
10725
10726		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10727
10728		*lba = scsi_4btoul(cdb->addr);
10729		*len = scsi_4btoul(cdb->length);
10730		break;
10731	}
10732	case WRITE_VERIFY_12: {
10733		struct scsi_write_verify_12 *cdb;
10734
10735		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10736
10737		*lba = scsi_4btoul(cdb->addr);
10738		*len = scsi_4btoul(cdb->length);
10739		break;
10740	}
10741	case READ_16:
10742	case WRITE_16: {
10743		struct scsi_rw_16 *cdb;
10744
10745		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10746
10747		*lba = scsi_8btou64(cdb->addr);
10748		*len = scsi_4btoul(cdb->length);
10749		break;
10750	}
10751	case WRITE_ATOMIC_16: {
10752		struct scsi_write_atomic_16 *cdb;
10753
10754		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10755
10756		*lba = scsi_8btou64(cdb->addr);
10757		*len = scsi_2btoul(cdb->length);
10758		break;
10759	}
10760	case WRITE_VERIFY_16: {
10761		struct scsi_write_verify_16 *cdb;
10762
10763		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10764
10765		*lba = scsi_8btou64(cdb->addr);
10766		*len = scsi_4btoul(cdb->length);
10767		break;
10768	}
10769	case WRITE_SAME_10: {
10770		struct scsi_write_same_10 *cdb;
10771
10772		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10773
10774		*lba = scsi_4btoul(cdb->addr);
10775		*len = scsi_2btoul(cdb->length);
10776		break;
10777	}
10778	case WRITE_SAME_16: {
10779		struct scsi_write_same_16 *cdb;
10780
10781		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10782
10783		*lba = scsi_8btou64(cdb->addr);
10784		*len = scsi_4btoul(cdb->length);
10785		break;
10786	}
10787	case VERIFY_10: {
10788		struct scsi_verify_10 *cdb;
10789
10790		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10791
10792		*lba = scsi_4btoul(cdb->addr);
10793		*len = scsi_2btoul(cdb->length);
10794		break;
10795	}
10796	case VERIFY_12: {
10797		struct scsi_verify_12 *cdb;
10798
10799		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10800
10801		*lba = scsi_4btoul(cdb->addr);
10802		*len = scsi_4btoul(cdb->length);
10803		break;
10804	}
10805	case VERIFY_16: {
10806		struct scsi_verify_16 *cdb;
10807
10808		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10809
10810		*lba = scsi_8btou64(cdb->addr);
10811		*len = scsi_4btoul(cdb->length);
10812		break;
10813	}
10814	case UNMAP: {
10815		*lba = 0;
10816		*len = UINT64_MAX;
10817		break;
10818	}
10819	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10820		struct scsi_get_lba_status *cdb;
10821
10822		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10823		*lba = scsi_8btou64(cdb->addr);
10824		*len = UINT32_MAX;
10825		break;
10826	}
10827	default:
10828		return (1);
10829		break; /* NOTREACHED */
10830	}
10831
10832	return (0);
10833}
10834
10835static ctl_action
10836ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10837    bool seq)
10838{
10839	uint64_t endlba1, endlba2;
10840
10841	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10842	endlba2 = lba2 + len2 - 1;
10843
10844	if ((endlba1 < lba2) || (endlba2 < lba1))
10845		return (CTL_ACTION_PASS);
10846	else
10847		return (CTL_ACTION_BLOCK);
10848}
10849
10850static int
10851ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10852{
10853	struct ctl_ptr_len_flags *ptrlen;
10854	struct scsi_unmap_desc *buf, *end, *range;
10855	uint64_t lba;
10856	uint32_t len;
10857
10858	/* If not UNMAP -- go other way. */
10859	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10860	    io->scsiio.cdb[0] != UNMAP)
10861		return (CTL_ACTION_ERROR);
10862
10863	/* If UNMAP without data -- block and wait for data. */
10864	ptrlen = (struct ctl_ptr_len_flags *)
10865	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10866	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10867	    ptrlen->ptr == NULL)
10868		return (CTL_ACTION_BLOCK);
10869
10870	/* UNMAP with data -- check for collision. */
10871	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10872	end = buf + ptrlen->len / sizeof(*buf);
10873	for (range = buf; range < end; range++) {
10874		lba = scsi_8btou64(range->lba);
10875		len = scsi_4btoul(range->length);
10876		if ((lba < lba2 + len2) && (lba + len > lba2))
10877			return (CTL_ACTION_BLOCK);
10878	}
10879	return (CTL_ACTION_PASS);
10880}
10881
10882static ctl_action
10883ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10884{
10885	uint64_t lba1, lba2;
10886	uint64_t len1, len2;
10887	int retval;
10888
10889	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10890		return (CTL_ACTION_ERROR);
10891
10892	retval = ctl_extent_check_unmap(io1, lba2, len2);
10893	if (retval != CTL_ACTION_ERROR)
10894		return (retval);
10895
10896	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10897		return (CTL_ACTION_ERROR);
10898
10899	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10900		seq = FALSE;
10901	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10902}
10903
10904static ctl_action
10905ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10906{
10907	uint64_t lba1, lba2;
10908	uint64_t len1, len2;
10909
10910	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10911		return (CTL_ACTION_PASS);
10912	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10913		return (CTL_ACTION_ERROR);
10914	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10915		return (CTL_ACTION_ERROR);
10916
10917	if (lba1 + len1 == lba2)
10918		return (CTL_ACTION_BLOCK);
10919	return (CTL_ACTION_PASS);
10920}
10921
10922static ctl_action
10923ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10924    union ctl_io *ooa_io)
10925{
10926	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10927	const ctl_serialize_action *serialize_row;
10928
10929	/*
10930	 * The initiator attempted multiple untagged commands at the same
10931	 * time.  Can't do that.
10932	 */
10933	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10934	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10935	 && ((pending_io->io_hdr.nexus.targ_port ==
10936	      ooa_io->io_hdr.nexus.targ_port)
10937	  && (pending_io->io_hdr.nexus.initid ==
10938	      ooa_io->io_hdr.nexus.initid))
10939	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10940	      CTL_FLAG_STATUS_SENT)) == 0))
10941		return (CTL_ACTION_OVERLAP);
10942
10943	/*
10944	 * The initiator attempted to send multiple tagged commands with
10945	 * the same ID.  (It's fine if different initiators have the same
10946	 * tag ID.)
10947	 *
10948	 * Even if all of those conditions are true, we don't kill the I/O
10949	 * if the command ahead of us has been aborted.  We won't end up
10950	 * sending it to the FETD, and it's perfectly legal to resend a
10951	 * command with the same tag number as long as the previous
10952	 * instance of this tag number has been aborted somehow.
10953	 */
10954	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10955	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10956	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10957	 && ((pending_io->io_hdr.nexus.targ_port ==
10958	      ooa_io->io_hdr.nexus.targ_port)
10959	  && (pending_io->io_hdr.nexus.initid ==
10960	      ooa_io->io_hdr.nexus.initid))
10961	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10962	      CTL_FLAG_STATUS_SENT)) == 0))
10963		return (CTL_ACTION_OVERLAP_TAG);
10964
10965	/*
10966	 * If we get a head of queue tag, SAM-3 says that we should
10967	 * immediately execute it.
10968	 *
10969	 * What happens if this command would normally block for some other
10970	 * reason?  e.g. a request sense with a head of queue tag
10971	 * immediately after a write.  Normally that would block, but this
10972	 * will result in its getting executed immediately...
10973	 *
10974	 * We currently return "pass" instead of "skip", so we'll end up
10975	 * going through the rest of the queue to check for overlapped tags.
10976	 *
10977	 * XXX KDM check for other types of blockage first??
10978	 */
10979	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10980		return (CTL_ACTION_PASS);
10981
10982	/*
10983	 * Ordered tags have to block until all items ahead of them
10984	 * have completed.  If we get called with an ordered tag, we always
10985	 * block, if something else is ahead of us in the queue.
10986	 */
10987	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10988		return (CTL_ACTION_BLOCK);
10989
10990	/*
10991	 * Simple tags get blocked until all head of queue and ordered tags
10992	 * ahead of them have completed.  I'm lumping untagged commands in
10993	 * with simple tags here.  XXX KDM is that the right thing to do?
10994	 */
10995	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10996	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10997	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10998	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10999		return (CTL_ACTION_BLOCK);
11000
11001	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11002	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11003
11004	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11005
11006	switch (serialize_row[pending_entry->seridx]) {
11007	case CTL_SER_BLOCK:
11008		return (CTL_ACTION_BLOCK);
11009	case CTL_SER_EXTENT:
11010		return (ctl_extent_check(ooa_io, pending_io,
11011		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11012	case CTL_SER_EXTENTOPT:
11013		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11014		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11015			return (ctl_extent_check(ooa_io, pending_io,
11016			    (lun->be_lun &&
11017			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11018		return (CTL_ACTION_PASS);
11019	case CTL_SER_EXTENTSEQ:
11020		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11021			return (ctl_extent_check_seq(ooa_io, pending_io));
11022		return (CTL_ACTION_PASS);
11023	case CTL_SER_PASS:
11024		return (CTL_ACTION_PASS);
11025	case CTL_SER_BLOCKOPT:
11026		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11027		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11028			return (CTL_ACTION_BLOCK);
11029		return (CTL_ACTION_PASS);
11030	case CTL_SER_SKIP:
11031		return (CTL_ACTION_SKIP);
11032	default:
11033		panic("invalid serialization value %d",
11034		      serialize_row[pending_entry->seridx]);
11035	}
11036
11037	return (CTL_ACTION_ERROR);
11038}
11039
11040/*
11041 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11042 * Assumptions:
11043 * - pending_io is generally either incoming, or on the blocked queue
11044 * - starting I/O is the I/O we want to start the check with.
11045 */
11046static ctl_action
11047ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11048	      union ctl_io *starting_io)
11049{
11050	union ctl_io *ooa_io;
11051	ctl_action action;
11052
11053	mtx_assert(&lun->lun_lock, MA_OWNED);
11054
11055	/*
11056	 * Run back along the OOA queue, starting with the current
11057	 * blocked I/O and going through every I/O before it on the
11058	 * queue.  If starting_io is NULL, we'll just end up returning
11059	 * CTL_ACTION_PASS.
11060	 */
11061	for (ooa_io = starting_io; ooa_io != NULL;
11062	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11063	     ooa_links)){
11064
11065		/*
11066		 * This routine just checks to see whether
11067		 * cur_blocked is blocked by ooa_io, which is ahead
11068		 * of it in the queue.  It doesn't queue/dequeue
11069		 * cur_blocked.
11070		 */
11071		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11072		switch (action) {
11073		case CTL_ACTION_BLOCK:
11074		case CTL_ACTION_OVERLAP:
11075		case CTL_ACTION_OVERLAP_TAG:
11076		case CTL_ACTION_SKIP:
11077		case CTL_ACTION_ERROR:
11078			return (action);
11079			break; /* NOTREACHED */
11080		case CTL_ACTION_PASS:
11081			break;
11082		default:
11083			panic("invalid action %d", action);
11084			break;  /* NOTREACHED */
11085		}
11086	}
11087
11088	return (CTL_ACTION_PASS);
11089}
11090
11091/*
11092 * Assumptions:
11093 * - An I/O has just completed, and has been removed from the per-LUN OOA
11094 *   queue, so some items on the blocked queue may now be unblocked.
11095 */
11096static int
11097ctl_check_blocked(struct ctl_lun *lun)
11098{
11099	struct ctl_softc *softc = lun->ctl_softc;
11100	union ctl_io *cur_blocked, *next_blocked;
11101
11102	mtx_assert(&lun->lun_lock, MA_OWNED);
11103
11104	/*
11105	 * Run forward from the head of the blocked queue, checking each
11106	 * entry against the I/Os prior to it on the OOA queue to see if
11107	 * there is still any blockage.
11108	 *
11109	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11110	 * with our removing a variable on it while it is traversing the
11111	 * list.
11112	 */
11113	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11114	     cur_blocked != NULL; cur_blocked = next_blocked) {
11115		union ctl_io *prev_ooa;
11116		ctl_action action;
11117
11118		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11119							  blocked_links);
11120
11121		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11122						      ctl_ooaq, ooa_links);
11123
11124		/*
11125		 * If cur_blocked happens to be the first item in the OOA
11126		 * queue now, prev_ooa will be NULL, and the action
11127		 * returned will just be CTL_ACTION_PASS.
11128		 */
11129		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11130
11131		switch (action) {
11132		case CTL_ACTION_BLOCK:
11133			/* Nothing to do here, still blocked */
11134			break;
11135		case CTL_ACTION_OVERLAP:
11136		case CTL_ACTION_OVERLAP_TAG:
11137			/*
11138			 * This shouldn't happen!  In theory we've already
11139			 * checked this command for overlap...
11140			 */
11141			break;
11142		case CTL_ACTION_PASS:
11143		case CTL_ACTION_SKIP: {
11144			const struct ctl_cmd_entry *entry;
11145
11146			/*
11147			 * The skip case shouldn't happen, this transaction
11148			 * should have never made it onto the blocked queue.
11149			 */
11150			/*
11151			 * This I/O is no longer blocked, we can remove it
11152			 * from the blocked queue.  Since this is a TAILQ
11153			 * (doubly linked list), we can do O(1) removals
11154			 * from any place on the list.
11155			 */
11156			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11157				     blocked_links);
11158			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11159
11160			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11161			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11162				/*
11163				 * Need to send IO back to original side to
11164				 * run
11165				 */
11166				union ctl_ha_msg msg_info;
11167
11168				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11169				msg_info.hdr.original_sc =
11170					cur_blocked->io_hdr.original_sc;
11171				msg_info.hdr.serializing_sc = cur_blocked;
11172				msg_info.hdr.msg_type = CTL_MSG_R2R;
11173				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11174				    sizeof(msg_info.hdr), M_NOWAIT);
11175				break;
11176			}
11177			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11178
11179			/*
11180			 * Check this I/O for LUN state changes that may
11181			 * have happened while this command was blocked.
11182			 * The LUN state may have been changed by a command
11183			 * ahead of us in the queue, so we need to re-check
11184			 * for any states that can be caused by SCSI
11185			 * commands.
11186			 */
11187			if (ctl_scsiio_lun_check(lun, entry,
11188						 &cur_blocked->scsiio) == 0) {
11189				cur_blocked->io_hdr.flags |=
11190				                      CTL_FLAG_IS_WAS_ON_RTR;
11191				ctl_enqueue_rtr(cur_blocked);
11192			} else
11193				ctl_done(cur_blocked);
11194			break;
11195		}
11196		default:
11197			/*
11198			 * This probably shouldn't happen -- we shouldn't
11199			 * get CTL_ACTION_ERROR, or anything else.
11200			 */
11201			break;
11202		}
11203	}
11204
11205	return (CTL_RETVAL_COMPLETE);
11206}
11207
11208/*
11209 * This routine (with one exception) checks LUN flags that can be set by
11210 * commands ahead of us in the OOA queue.  These flags have to be checked
11211 * when a command initially comes in, and when we pull a command off the
11212 * blocked queue and are preparing to execute it.  The reason we have to
11213 * check these flags for commands on the blocked queue is that the LUN
11214 * state may have been changed by a command ahead of us while we're on the
11215 * blocked queue.
11216 *
11217 * Ordering is somewhat important with these checks, so please pay
11218 * careful attention to the placement of any new checks.
11219 */
11220static int
11221ctl_scsiio_lun_check(struct ctl_lun *lun,
11222    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11223{
11224	struct ctl_softc *softc = lun->ctl_softc;
11225	int retval;
11226	uint32_t residx;
11227
11228	retval = 0;
11229
11230	mtx_assert(&lun->lun_lock, MA_OWNED);
11231
11232	/*
11233	 * If this shelf is a secondary shelf controller, we may have to
11234	 * reject some commands disallowed by HA mode and link state.
11235	 */
11236	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11237		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11238		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11239			ctl_set_lun_unavail(ctsio);
11240			retval = 1;
11241			goto bailout;
11242		}
11243		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11244		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11245			ctl_set_lun_transit(ctsio);
11246			retval = 1;
11247			goto bailout;
11248		}
11249		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11250		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11251			ctl_set_lun_standby(ctsio);
11252			retval = 1;
11253			goto bailout;
11254		}
11255
11256		/* The rest of checks are only done on executing side */
11257		if (softc->ha_mode == CTL_HA_MODE_XFER)
11258			goto bailout;
11259	}
11260
11261	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11262		if (lun->be_lun &&
11263		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11264			ctl_set_hw_write_protected(ctsio);
11265			retval = 1;
11266			goto bailout;
11267		}
11268		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11269		    .eca_and_aen & SCP_SWP) != 0) {
11270			ctl_set_sense(ctsio, /*current_error*/ 1,
11271			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11272			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11273			retval = 1;
11274			goto bailout;
11275		}
11276	}
11277
11278	/*
11279	 * Check for a reservation conflict.  If this command isn't allowed
11280	 * even on reserved LUNs, and if this initiator isn't the one who
11281	 * reserved us, reject the command with a reservation conflict.
11282	 */
11283	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11284	if ((lun->flags & CTL_LUN_RESERVED)
11285	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11286		if (lun->res_idx != residx) {
11287			ctl_set_reservation_conflict(ctsio);
11288			retval = 1;
11289			goto bailout;
11290		}
11291	}
11292
11293	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11294	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11295		/* No reservation or command is allowed. */;
11296	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11297	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11298	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11299	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11300		/* The command is allowed for Write Exclusive resv. */;
11301	} else {
11302		/*
11303		 * if we aren't registered or it's a res holder type
11304		 * reservation and this isn't the res holder then set a
11305		 * conflict.
11306		 */
11307		if (ctl_get_prkey(lun, residx) == 0 ||
11308		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11309			ctl_set_reservation_conflict(ctsio);
11310			retval = 1;
11311			goto bailout;
11312		}
11313	}
11314
11315	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11316		if (lun->flags & CTL_LUN_EJECTED)
11317			ctl_set_lun_ejected(ctsio);
11318		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11319			if (lun->flags & CTL_LUN_REMOVABLE)
11320				ctl_set_lun_no_media(ctsio);
11321			else
11322				ctl_set_lun_int_reqd(ctsio);
11323		} else if (lun->flags & CTL_LUN_STOPPED)
11324			ctl_set_lun_stopped(ctsio);
11325		else
11326			goto bailout;
11327		retval = 1;
11328		goto bailout;
11329	}
11330
11331bailout:
11332	return (retval);
11333}
11334
11335static void
11336ctl_failover_io(union ctl_io *io, int have_lock)
11337{
11338	ctl_set_busy(&io->scsiio);
11339	ctl_done(io);
11340}
11341
11342static void
11343ctl_failover_lun(union ctl_io *rio)
11344{
11345	struct ctl_softc *softc = control_softc;
11346	struct ctl_lun *lun;
11347	struct ctl_io_hdr *io, *next_io;
11348	uint32_t targ_lun;
11349
11350	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11351	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11352
11353	/* Find and lock the LUN. */
11354	mtx_lock(&softc->ctl_lock);
11355	if ((targ_lun < CTL_MAX_LUNS) &&
11356	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11357		mtx_lock(&lun->lun_lock);
11358		mtx_unlock(&softc->ctl_lock);
11359		if (lun->flags & CTL_LUN_DISABLED) {
11360			mtx_unlock(&lun->lun_lock);
11361			return;
11362		}
11363	} else {
11364		mtx_unlock(&softc->ctl_lock);
11365		return;
11366	}
11367
11368	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11369		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11370			/* We are master */
11371			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11372				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11373					io->flags |= CTL_FLAG_ABORT;
11374					io->flags |= CTL_FLAG_FAILOVER;
11375				} else { /* This can be only due to DATAMOVE */
11376					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11377					io->flags &= ~CTL_FLAG_DMA_INPROG;
11378					io->flags |= CTL_FLAG_IO_ACTIVE;
11379					io->port_status = 31340;
11380					ctl_enqueue_isc((union ctl_io *)io);
11381				}
11382			}
11383			/* We are slave */
11384			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11385				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11386				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11387					io->flags |= CTL_FLAG_FAILOVER;
11388				} else {
11389					ctl_set_busy(&((union ctl_io *)io)->
11390					    scsiio);
11391					ctl_done((union ctl_io *)io);
11392				}
11393			}
11394		}
11395	} else { /* SERIALIZE modes */
11396		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11397		    next_io) {
11398			/* We are master */
11399			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11400				TAILQ_REMOVE(&lun->blocked_queue, io,
11401				    blocked_links);
11402				io->flags &= ~CTL_FLAG_BLOCKED;
11403				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11404				ctl_free_io((union ctl_io *)io);
11405			}
11406		}
11407		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11408			/* We are master */
11409			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11410				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11411				ctl_free_io((union ctl_io *)io);
11412			}
11413			/* We are slave */
11414			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11415				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11416				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11417					ctl_set_busy(&((union ctl_io *)io)->
11418					    scsiio);
11419					ctl_done((union ctl_io *)io);
11420				}
11421			}
11422		}
11423		ctl_check_blocked(lun);
11424	}
11425	mtx_unlock(&lun->lun_lock);
11426}
11427
11428static int
11429ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11430{
11431	struct ctl_lun *lun;
11432	const struct ctl_cmd_entry *entry;
11433	uint32_t initidx, targ_lun;
11434	int retval;
11435
11436	retval = 0;
11437
11438	lun = NULL;
11439
11440	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11441	if ((targ_lun < CTL_MAX_LUNS)
11442	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11443		/*
11444		 * If the LUN is invalid, pretend that it doesn't exist.
11445		 * It will go away as soon as all pending I/O has been
11446		 * completed.
11447		 */
11448		mtx_lock(&lun->lun_lock);
11449		if (lun->flags & CTL_LUN_DISABLED) {
11450			mtx_unlock(&lun->lun_lock);
11451			lun = NULL;
11452			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11453			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11454		} else {
11455			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11456			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11457				lun->be_lun;
11458
11459			/*
11460			 * Every I/O goes into the OOA queue for a
11461			 * particular LUN, and stays there until completion.
11462			 */
11463#ifdef CTL_TIME_IO
11464			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11465				lun->idle_time += getsbinuptime() -
11466				    lun->last_busy;
11467			}
11468#endif
11469			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11470			    ooa_links);
11471		}
11472	} else {
11473		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11474		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11475	}
11476
11477	/* Get command entry and return error if it is unsuppotyed. */
11478	entry = ctl_validate_command(ctsio);
11479	if (entry == NULL) {
11480		if (lun)
11481			mtx_unlock(&lun->lun_lock);
11482		return (retval);
11483	}
11484
11485	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11486	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11487
11488	/*
11489	 * Check to see whether we can send this command to LUNs that don't
11490	 * exist.  This should pretty much only be the case for inquiry
11491	 * and request sense.  Further checks, below, really require having
11492	 * a LUN, so we can't really check the command anymore.  Just put
11493	 * it on the rtr queue.
11494	 */
11495	if (lun == NULL) {
11496		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11497			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11498			ctl_enqueue_rtr((union ctl_io *)ctsio);
11499			return (retval);
11500		}
11501
11502		ctl_set_unsupported_lun(ctsio);
11503		ctl_done((union ctl_io *)ctsio);
11504		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11505		return (retval);
11506	} else {
11507		/*
11508		 * Make sure we support this particular command on this LUN.
11509		 * e.g., we don't support writes to the control LUN.
11510		 */
11511		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11512			mtx_unlock(&lun->lun_lock);
11513			ctl_set_invalid_opcode(ctsio);
11514			ctl_done((union ctl_io *)ctsio);
11515			return (retval);
11516		}
11517	}
11518
11519	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11520
11521#ifdef CTL_WITH_CA
11522	/*
11523	 * If we've got a request sense, it'll clear the contingent
11524	 * allegiance condition.  Otherwise, if we have a CA condition for
11525	 * this initiator, clear it, because it sent down a command other
11526	 * than request sense.
11527	 */
11528	if ((ctsio->cdb[0] != REQUEST_SENSE)
11529	 && (ctl_is_set(lun->have_ca, initidx)))
11530		ctl_clear_mask(lun->have_ca, initidx);
11531#endif
11532
11533	/*
11534	 * If the command has this flag set, it handles its own unit
11535	 * attention reporting, we shouldn't do anything.  Otherwise we
11536	 * check for any pending unit attentions, and send them back to the
11537	 * initiator.  We only do this when a command initially comes in,
11538	 * not when we pull it off the blocked queue.
11539	 *
11540	 * According to SAM-3, section 5.3.2, the order that things get
11541	 * presented back to the host is basically unit attentions caused
11542	 * by some sort of reset event, busy status, reservation conflicts
11543	 * or task set full, and finally any other status.
11544	 *
11545	 * One issue here is that some of the unit attentions we report
11546	 * don't fall into the "reset" category (e.g. "reported luns data
11547	 * has changed").  So reporting it here, before the reservation
11548	 * check, may be technically wrong.  I guess the only thing to do
11549	 * would be to check for and report the reset events here, and then
11550	 * check for the other unit attention types after we check for a
11551	 * reservation conflict.
11552	 *
11553	 * XXX KDM need to fix this
11554	 */
11555	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11556		ctl_ua_type ua_type;
11557
11558		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11559		    SSD_TYPE_NONE);
11560		if (ua_type != CTL_UA_NONE) {
11561			mtx_unlock(&lun->lun_lock);
11562			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11563			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11564			ctsio->sense_len = SSD_FULL_SIZE;
11565			ctl_done((union ctl_io *)ctsio);
11566			return (retval);
11567		}
11568	}
11569
11570
11571	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11572		mtx_unlock(&lun->lun_lock);
11573		ctl_done((union ctl_io *)ctsio);
11574		return (retval);
11575	}
11576
11577	/*
11578	 * XXX CHD this is where we want to send IO to other side if
11579	 * this LUN is secondary on this SC. We will need to make a copy
11580	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11581	 * the copy we send as FROM_OTHER.
11582	 * We also need to stuff the address of the original IO so we can
11583	 * find it easily. Something similar will need be done on the other
11584	 * side so when we are done we can find the copy.
11585	 */
11586	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11587	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11588	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11589		union ctl_ha_msg msg_info;
11590		int isc_retval;
11591
11592		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11593		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11594		mtx_unlock(&lun->lun_lock);
11595
11596		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11597		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11598		msg_info.hdr.serializing_sc = NULL;
11599		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11600		msg_info.scsi.tag_num = ctsio->tag_num;
11601		msg_info.scsi.tag_type = ctsio->tag_type;
11602		msg_info.scsi.cdb_len = ctsio->cdb_len;
11603		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11604
11605		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11606		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11607		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11608			ctl_set_busy(ctsio);
11609			ctl_done((union ctl_io *)ctsio);
11610			return (retval);
11611		}
11612		return (retval);
11613	}
11614
11615	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11616			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11617			      ctl_ooaq, ooa_links))) {
11618	case CTL_ACTION_BLOCK:
11619		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11620		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11621				  blocked_links);
11622		mtx_unlock(&lun->lun_lock);
11623		return (retval);
11624	case CTL_ACTION_PASS:
11625	case CTL_ACTION_SKIP:
11626		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11627		mtx_unlock(&lun->lun_lock);
11628		ctl_enqueue_rtr((union ctl_io *)ctsio);
11629		break;
11630	case CTL_ACTION_OVERLAP:
11631		mtx_unlock(&lun->lun_lock);
11632		ctl_set_overlapped_cmd(ctsio);
11633		ctl_done((union ctl_io *)ctsio);
11634		break;
11635	case CTL_ACTION_OVERLAP_TAG:
11636		mtx_unlock(&lun->lun_lock);
11637		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11638		ctl_done((union ctl_io *)ctsio);
11639		break;
11640	case CTL_ACTION_ERROR:
11641	default:
11642		mtx_unlock(&lun->lun_lock);
11643		ctl_set_internal_failure(ctsio,
11644					 /*sks_valid*/ 0,
11645					 /*retry_count*/ 0);
11646		ctl_done((union ctl_io *)ctsio);
11647		break;
11648	}
11649	return (retval);
11650}
11651
11652const struct ctl_cmd_entry *
11653ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11654{
11655	const struct ctl_cmd_entry *entry;
11656	int service_action;
11657
11658	entry = &ctl_cmd_table[ctsio->cdb[0]];
11659	if (sa)
11660		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11661	if (entry->flags & CTL_CMD_FLAG_SA5) {
11662		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11663		entry = &((const struct ctl_cmd_entry *)
11664		    entry->execute)[service_action];
11665	}
11666	return (entry);
11667}
11668
11669const struct ctl_cmd_entry *
11670ctl_validate_command(struct ctl_scsiio *ctsio)
11671{
11672	const struct ctl_cmd_entry *entry;
11673	int i, sa;
11674	uint8_t diff;
11675
11676	entry = ctl_get_cmd_entry(ctsio, &sa);
11677	if (entry->execute == NULL) {
11678		if (sa)
11679			ctl_set_invalid_field(ctsio,
11680					      /*sks_valid*/ 1,
11681					      /*command*/ 1,
11682					      /*field*/ 1,
11683					      /*bit_valid*/ 1,
11684					      /*bit*/ 4);
11685		else
11686			ctl_set_invalid_opcode(ctsio);
11687		ctl_done((union ctl_io *)ctsio);
11688		return (NULL);
11689	}
11690	KASSERT(entry->length > 0,
11691	    ("Not defined length for command 0x%02x/0x%02x",
11692	     ctsio->cdb[0], ctsio->cdb[1]));
11693	for (i = 1; i < entry->length; i++) {
11694		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11695		if (diff == 0)
11696			continue;
11697		ctl_set_invalid_field(ctsio,
11698				      /*sks_valid*/ 1,
11699				      /*command*/ 1,
11700				      /*field*/ i,
11701				      /*bit_valid*/ 1,
11702				      /*bit*/ fls(diff) - 1);
11703		ctl_done((union ctl_io *)ctsio);
11704		return (NULL);
11705	}
11706	return (entry);
11707}
11708
11709static int
11710ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11711{
11712
11713	switch (lun_type) {
11714	case T_DIRECT:
11715		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11716			return (0);
11717		break;
11718	case T_PROCESSOR:
11719		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11720			return (0);
11721		break;
11722	case T_CDROM:
11723		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11724			return (0);
11725		break;
11726	default:
11727		return (0);
11728	}
11729	return (1);
11730}
11731
11732static int
11733ctl_scsiio(struct ctl_scsiio *ctsio)
11734{
11735	int retval;
11736	const struct ctl_cmd_entry *entry;
11737
11738	retval = CTL_RETVAL_COMPLETE;
11739
11740	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11741
11742	entry = ctl_get_cmd_entry(ctsio, NULL);
11743
11744	/*
11745	 * If this I/O has been aborted, just send it straight to
11746	 * ctl_done() without executing it.
11747	 */
11748	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11749		ctl_done((union ctl_io *)ctsio);
11750		goto bailout;
11751	}
11752
11753	/*
11754	 * All the checks should have been handled by ctl_scsiio_precheck().
11755	 * We should be clear now to just execute the I/O.
11756	 */
11757	retval = entry->execute(ctsio);
11758
11759bailout:
11760	return (retval);
11761}
11762
11763/*
11764 * Since we only implement one target right now, a bus reset simply resets
11765 * our single target.
11766 */
11767static int
11768ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11769{
11770	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11771}
11772
11773static int
11774ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11775		 ctl_ua_type ua_type)
11776{
11777	struct ctl_port *port;
11778	struct ctl_lun *lun;
11779	int retval;
11780
11781	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11782		union ctl_ha_msg msg_info;
11783
11784		msg_info.hdr.nexus = io->io_hdr.nexus;
11785		if (ua_type==CTL_UA_TARG_RESET)
11786			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11787		else
11788			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11789		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11790		msg_info.hdr.original_sc = NULL;
11791		msg_info.hdr.serializing_sc = NULL;
11792		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11793		    sizeof(msg_info.task), M_WAITOK);
11794	}
11795	retval = 0;
11796
11797	mtx_lock(&softc->ctl_lock);
11798	port = ctl_io_port(&io->io_hdr);
11799	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11800		if (port != NULL &&
11801		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11802			continue;
11803		retval += ctl_do_lun_reset(lun, io, ua_type);
11804	}
11805	mtx_unlock(&softc->ctl_lock);
11806	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11807	return (retval);
11808}
11809
11810/*
11811 * The LUN should always be set.  The I/O is optional, and is used to
11812 * distinguish between I/Os sent by this initiator, and by other
11813 * initiators.  We set unit attention for initiators other than this one.
11814 * SAM-3 is vague on this point.  It does say that a unit attention should
11815 * be established for other initiators when a LUN is reset (see section
11816 * 5.7.3), but it doesn't specifically say that the unit attention should
11817 * be established for this particular initiator when a LUN is reset.  Here
11818 * is the relevant text, from SAM-3 rev 8:
11819 *
11820 * 5.7.2 When a SCSI initiator port aborts its own tasks
11821 *
11822 * When a SCSI initiator port causes its own task(s) to be aborted, no
11823 * notification that the task(s) have been aborted shall be returned to
11824 * the SCSI initiator port other than the completion response for the
11825 * command or task management function action that caused the task(s) to
11826 * be aborted and notification(s) associated with related effects of the
11827 * action (e.g., a reset unit attention condition).
11828 *
11829 * XXX KDM for now, we're setting unit attention for all initiators.
11830 */
11831static int
11832ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11833{
11834	union ctl_io *xio;
11835#if 0
11836	uint32_t initidx;
11837#endif
11838	int i;
11839
11840	mtx_lock(&lun->lun_lock);
11841	/*
11842	 * Run through the OOA queue and abort each I/O.
11843	 */
11844	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11845	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11846		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11847	}
11848
11849	/*
11850	 * This version sets unit attention for every
11851	 */
11852#if 0
11853	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11854	ctl_est_ua_all(lun, initidx, ua_type);
11855#else
11856	ctl_est_ua_all(lun, -1, ua_type);
11857#endif
11858
11859	/*
11860	 * A reset (any kind, really) clears reservations established with
11861	 * RESERVE/RELEASE.  It does not clear reservations established
11862	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11863	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11864	 * reservations made with the RESERVE/RELEASE commands, because
11865	 * those commands are obsolete in SPC-3.
11866	 */
11867	lun->flags &= ~CTL_LUN_RESERVED;
11868
11869#ifdef CTL_WITH_CA
11870	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11871		ctl_clear_mask(lun->have_ca, i);
11872#endif
11873	lun->prevent_count = 0;
11874	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11875		ctl_clear_mask(lun->prevent, i);
11876	mtx_unlock(&lun->lun_lock);
11877
11878	return (0);
11879}
11880
11881static int
11882ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11883{
11884	struct ctl_lun *lun;
11885	uint32_t targ_lun;
11886	int retval;
11887
11888	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11889	mtx_lock(&softc->ctl_lock);
11890	if ((targ_lun >= CTL_MAX_LUNS) ||
11891	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11892		mtx_unlock(&softc->ctl_lock);
11893		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11894		return (1);
11895	}
11896	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11897	mtx_unlock(&softc->ctl_lock);
11898	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11899
11900	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11901		union ctl_ha_msg msg_info;
11902
11903		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11904		msg_info.hdr.nexus = io->io_hdr.nexus;
11905		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11906		msg_info.hdr.original_sc = NULL;
11907		msg_info.hdr.serializing_sc = NULL;
11908		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11909		    sizeof(msg_info.task), M_WAITOK);
11910	}
11911	return (retval);
11912}
11913
11914static void
11915ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11916    int other_sc)
11917{
11918	union ctl_io *xio;
11919
11920	mtx_assert(&lun->lun_lock, MA_OWNED);
11921
11922	/*
11923	 * Run through the OOA queue and attempt to find the given I/O.
11924	 * The target port, initiator ID, tag type and tag number have to
11925	 * match the values that we got from the initiator.  If we have an
11926	 * untagged command to abort, simply abort the first untagged command
11927	 * we come to.  We only allow one untagged command at a time of course.
11928	 */
11929	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11930	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11931
11932		if ((targ_port == UINT32_MAX ||
11933		     targ_port == xio->io_hdr.nexus.targ_port) &&
11934		    (init_id == UINT32_MAX ||
11935		     init_id == xio->io_hdr.nexus.initid)) {
11936			if (targ_port != xio->io_hdr.nexus.targ_port ||
11937			    init_id != xio->io_hdr.nexus.initid)
11938				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11939			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11940			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11941				union ctl_ha_msg msg_info;
11942
11943				msg_info.hdr.nexus = xio->io_hdr.nexus;
11944				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11945				msg_info.task.tag_num = xio->scsiio.tag_num;
11946				msg_info.task.tag_type = xio->scsiio.tag_type;
11947				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11948				msg_info.hdr.original_sc = NULL;
11949				msg_info.hdr.serializing_sc = NULL;
11950				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11951				    sizeof(msg_info.task), M_NOWAIT);
11952			}
11953		}
11954	}
11955}
11956
11957static int
11958ctl_abort_task_set(union ctl_io *io)
11959{
11960	struct ctl_softc *softc = control_softc;
11961	struct ctl_lun *lun;
11962	uint32_t targ_lun;
11963
11964	/*
11965	 * Look up the LUN.
11966	 */
11967	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11968	mtx_lock(&softc->ctl_lock);
11969	if ((targ_lun >= CTL_MAX_LUNS) ||
11970	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11971		mtx_unlock(&softc->ctl_lock);
11972		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11973		return (1);
11974	}
11975
11976	mtx_lock(&lun->lun_lock);
11977	mtx_unlock(&softc->ctl_lock);
11978	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11979		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11980		    io->io_hdr.nexus.initid,
11981		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11982	} else { /* CTL_TASK_CLEAR_TASK_SET */
11983		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11984		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11985	}
11986	mtx_unlock(&lun->lun_lock);
11987	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11988	return (0);
11989}
11990
11991static int
11992ctl_i_t_nexus_reset(union ctl_io *io)
11993{
11994	struct ctl_softc *softc = control_softc;
11995	struct ctl_lun *lun;
11996	uint32_t initidx;
11997
11998	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11999		union ctl_ha_msg msg_info;
12000
12001		msg_info.hdr.nexus = io->io_hdr.nexus;
12002		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12003		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12004		msg_info.hdr.original_sc = NULL;
12005		msg_info.hdr.serializing_sc = NULL;
12006		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12007		    sizeof(msg_info.task), M_WAITOK);
12008	}
12009
12010	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12011	mtx_lock(&softc->ctl_lock);
12012	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12013		mtx_lock(&lun->lun_lock);
12014		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12015		    io->io_hdr.nexus.initid, 1);
12016#ifdef CTL_WITH_CA
12017		ctl_clear_mask(lun->have_ca, initidx);
12018#endif
12019		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12020			lun->flags &= ~CTL_LUN_RESERVED;
12021		if (ctl_is_set(lun->prevent, initidx)) {
12022			ctl_clear_mask(lun->prevent, initidx);
12023			lun->prevent_count--;
12024		}
12025		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12026		mtx_unlock(&lun->lun_lock);
12027	}
12028	mtx_unlock(&softc->ctl_lock);
12029	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12030	return (0);
12031}
12032
12033static int
12034ctl_abort_task(union ctl_io *io)
12035{
12036	union ctl_io *xio;
12037	struct ctl_lun *lun;
12038	struct ctl_softc *softc;
12039#if 0
12040	struct sbuf sb;
12041	char printbuf[128];
12042#endif
12043	int found;
12044	uint32_t targ_lun;
12045
12046	softc = control_softc;
12047	found = 0;
12048
12049	/*
12050	 * Look up the LUN.
12051	 */
12052	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12053	mtx_lock(&softc->ctl_lock);
12054	if ((targ_lun >= CTL_MAX_LUNS) ||
12055	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12056		mtx_unlock(&softc->ctl_lock);
12057		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12058		return (1);
12059	}
12060
12061#if 0
12062	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12063	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12064#endif
12065
12066	mtx_lock(&lun->lun_lock);
12067	mtx_unlock(&softc->ctl_lock);
12068	/*
12069	 * Run through the OOA queue and attempt to find the given I/O.
12070	 * The target port, initiator ID, tag type and tag number have to
12071	 * match the values that we got from the initiator.  If we have an
12072	 * untagged command to abort, simply abort the first untagged command
12073	 * we come to.  We only allow one untagged command at a time of course.
12074	 */
12075	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12076	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12077#if 0
12078		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12079
12080		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12081			    lun->lun, xio->scsiio.tag_num,
12082			    xio->scsiio.tag_type,
12083			    (xio->io_hdr.blocked_links.tqe_prev
12084			    == NULL) ? "" : " BLOCKED",
12085			    (xio->io_hdr.flags &
12086			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12087			    (xio->io_hdr.flags &
12088			    CTL_FLAG_ABORT) ? " ABORT" : "",
12089			    (xio->io_hdr.flags &
12090			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12091		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12092		sbuf_finish(&sb);
12093		printf("%s\n", sbuf_data(&sb));
12094#endif
12095
12096		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12097		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12098		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12099			continue;
12100
12101		/*
12102		 * If the abort says that the task is untagged, the
12103		 * task in the queue must be untagged.  Otherwise,
12104		 * we just check to see whether the tag numbers
12105		 * match.  This is because the QLogic firmware
12106		 * doesn't pass back the tag type in an abort
12107		 * request.
12108		 */
12109#if 0
12110		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12111		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12112		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12113#endif
12114		/*
12115		 * XXX KDM we've got problems with FC, because it
12116		 * doesn't send down a tag type with aborts.  So we
12117		 * can only really go by the tag number...
12118		 * This may cause problems with parallel SCSI.
12119		 * Need to figure that out!!
12120		 */
12121		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12122			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12123			found = 1;
12124			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12125			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12126				union ctl_ha_msg msg_info;
12127
12128				msg_info.hdr.nexus = io->io_hdr.nexus;
12129				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12130				msg_info.task.tag_num = io->taskio.tag_num;
12131				msg_info.task.tag_type = io->taskio.tag_type;
12132				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12133				msg_info.hdr.original_sc = NULL;
12134				msg_info.hdr.serializing_sc = NULL;
12135#if 0
12136				printf("Sent Abort to other side\n");
12137#endif
12138				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12139				    sizeof(msg_info.task), M_NOWAIT);
12140			}
12141#if 0
12142			printf("ctl_abort_task: found I/O to abort\n");
12143#endif
12144		}
12145	}
12146	mtx_unlock(&lun->lun_lock);
12147
12148	if (found == 0) {
12149		/*
12150		 * This isn't really an error.  It's entirely possible for
12151		 * the abort and command completion to cross on the wire.
12152		 * This is more of an informative/diagnostic error.
12153		 */
12154#if 0
12155		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12156		       "%u:%u:%u tag %d type %d\n",
12157		       io->io_hdr.nexus.initid,
12158		       io->io_hdr.nexus.targ_port,
12159		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12160		       io->taskio.tag_type);
12161#endif
12162	}
12163	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12164	return (0);
12165}
12166
12167static int
12168ctl_query_task(union ctl_io *io, int task_set)
12169{
12170	union ctl_io *xio;
12171	struct ctl_lun *lun;
12172	struct ctl_softc *softc;
12173	int found = 0;
12174	uint32_t targ_lun;
12175
12176	softc = control_softc;
12177	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12178	mtx_lock(&softc->ctl_lock);
12179	if ((targ_lun >= CTL_MAX_LUNS) ||
12180	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12181		mtx_unlock(&softc->ctl_lock);
12182		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12183		return (1);
12184	}
12185	mtx_lock(&lun->lun_lock);
12186	mtx_unlock(&softc->ctl_lock);
12187	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12188	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12189
12190		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12191		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12192		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12193			continue;
12194
12195		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12196			found = 1;
12197			break;
12198		}
12199	}
12200	mtx_unlock(&lun->lun_lock);
12201	if (found)
12202		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12203	else
12204		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12205	return (0);
12206}
12207
12208static int
12209ctl_query_async_event(union ctl_io *io)
12210{
12211	struct ctl_lun *lun;
12212	struct ctl_softc *softc;
12213	ctl_ua_type ua;
12214	uint32_t targ_lun, initidx;
12215
12216	softc = control_softc;
12217	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12218	mtx_lock(&softc->ctl_lock);
12219	if ((targ_lun >= CTL_MAX_LUNS) ||
12220	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12221		mtx_unlock(&softc->ctl_lock);
12222		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12223		return (1);
12224	}
12225	mtx_lock(&lun->lun_lock);
12226	mtx_unlock(&softc->ctl_lock);
12227	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12228	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12229	mtx_unlock(&lun->lun_lock);
12230	if (ua != CTL_UA_NONE)
12231		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12232	else
12233		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12234	return (0);
12235}
12236
12237static void
12238ctl_run_task(union ctl_io *io)
12239{
12240	struct ctl_softc *softc = control_softc;
12241	int retval = 1;
12242
12243	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12244	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12245	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12246	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12247	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12248	switch (io->taskio.task_action) {
12249	case CTL_TASK_ABORT_TASK:
12250		retval = ctl_abort_task(io);
12251		break;
12252	case CTL_TASK_ABORT_TASK_SET:
12253	case CTL_TASK_CLEAR_TASK_SET:
12254		retval = ctl_abort_task_set(io);
12255		break;
12256	case CTL_TASK_CLEAR_ACA:
12257		break;
12258	case CTL_TASK_I_T_NEXUS_RESET:
12259		retval = ctl_i_t_nexus_reset(io);
12260		break;
12261	case CTL_TASK_LUN_RESET:
12262		retval = ctl_lun_reset(softc, io);
12263		break;
12264	case CTL_TASK_TARGET_RESET:
12265		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12266		break;
12267	case CTL_TASK_BUS_RESET:
12268		retval = ctl_bus_reset(softc, io);
12269		break;
12270	case CTL_TASK_PORT_LOGIN:
12271		break;
12272	case CTL_TASK_PORT_LOGOUT:
12273		break;
12274	case CTL_TASK_QUERY_TASK:
12275		retval = ctl_query_task(io, 0);
12276		break;
12277	case CTL_TASK_QUERY_TASK_SET:
12278		retval = ctl_query_task(io, 1);
12279		break;
12280	case CTL_TASK_QUERY_ASYNC_EVENT:
12281		retval = ctl_query_async_event(io);
12282		break;
12283	default:
12284		printf("%s: got unknown task management event %d\n",
12285		       __func__, io->taskio.task_action);
12286		break;
12287	}
12288	if (retval == 0)
12289		io->io_hdr.status = CTL_SUCCESS;
12290	else
12291		io->io_hdr.status = CTL_ERROR;
12292	ctl_done(io);
12293}
12294
12295/*
12296 * For HA operation.  Handle commands that come in from the other
12297 * controller.
12298 */
12299static void
12300ctl_handle_isc(union ctl_io *io)
12301{
12302	int free_io;
12303	struct ctl_lun *lun;
12304	struct ctl_softc *softc = control_softc;
12305	uint32_t targ_lun;
12306
12307	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12308	lun = softc->ctl_luns[targ_lun];
12309
12310	switch (io->io_hdr.msg_type) {
12311	case CTL_MSG_SERIALIZE:
12312		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12313		break;
12314	case CTL_MSG_R2R: {
12315		const struct ctl_cmd_entry *entry;
12316
12317		/*
12318		 * This is only used in SER_ONLY mode.
12319		 */
12320		free_io = 0;
12321		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12322		mtx_lock(&lun->lun_lock);
12323		if (ctl_scsiio_lun_check(lun,
12324		    entry, (struct ctl_scsiio *)io) != 0) {
12325			mtx_unlock(&lun->lun_lock);
12326			ctl_done(io);
12327			break;
12328		}
12329		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12330		mtx_unlock(&lun->lun_lock);
12331		ctl_enqueue_rtr(io);
12332		break;
12333	}
12334	case CTL_MSG_FINISH_IO:
12335		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12336			free_io = 0;
12337			ctl_done(io);
12338		} else {
12339			free_io = 1;
12340			mtx_lock(&lun->lun_lock);
12341			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12342				     ooa_links);
12343			ctl_check_blocked(lun);
12344			mtx_unlock(&lun->lun_lock);
12345		}
12346		break;
12347	case CTL_MSG_PERS_ACTION:
12348		ctl_hndl_per_res_out_on_other_sc(
12349			(union ctl_ha_msg *)&io->presio.pr_msg);
12350		free_io = 1;
12351		break;
12352	case CTL_MSG_BAD_JUJU:
12353		free_io = 0;
12354		ctl_done(io);
12355		break;
12356	case CTL_MSG_DATAMOVE:
12357		/* Only used in XFER mode */
12358		free_io = 0;
12359		ctl_datamove_remote(io);
12360		break;
12361	case CTL_MSG_DATAMOVE_DONE:
12362		/* Only used in XFER mode */
12363		free_io = 0;
12364		io->scsiio.be_move_done(io);
12365		break;
12366	case CTL_MSG_FAILOVER:
12367		ctl_failover_lun(io);
12368		free_io = 1;
12369		break;
12370	default:
12371		free_io = 1;
12372		printf("%s: Invalid message type %d\n",
12373		       __func__, io->io_hdr.msg_type);
12374		break;
12375	}
12376	if (free_io)
12377		ctl_free_io(io);
12378
12379}
12380
12381
12382/*
12383 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12384 * there is no match.
12385 */
12386static ctl_lun_error_pattern
12387ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12388{
12389	const struct ctl_cmd_entry *entry;
12390	ctl_lun_error_pattern filtered_pattern, pattern;
12391
12392	pattern = desc->error_pattern;
12393
12394	/*
12395	 * XXX KDM we need more data passed into this function to match a
12396	 * custom pattern, and we actually need to implement custom pattern
12397	 * matching.
12398	 */
12399	if (pattern & CTL_LUN_PAT_CMD)
12400		return (CTL_LUN_PAT_CMD);
12401
12402	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12403		return (CTL_LUN_PAT_ANY);
12404
12405	entry = ctl_get_cmd_entry(ctsio, NULL);
12406
12407	filtered_pattern = entry->pattern & pattern;
12408
12409	/*
12410	 * If the user requested specific flags in the pattern (e.g.
12411	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12412	 * flags.
12413	 *
12414	 * If the user did not specify any flags, it doesn't matter whether
12415	 * or not the command supports the flags.
12416	 */
12417	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12418	     (pattern & ~CTL_LUN_PAT_MASK))
12419		return (CTL_LUN_PAT_NONE);
12420
12421	/*
12422	 * If the user asked for a range check, see if the requested LBA
12423	 * range overlaps with this command's LBA range.
12424	 */
12425	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12426		uint64_t lba1;
12427		uint64_t len1;
12428		ctl_action action;
12429		int retval;
12430
12431		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12432		if (retval != 0)
12433			return (CTL_LUN_PAT_NONE);
12434
12435		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12436					      desc->lba_range.len, FALSE);
12437		/*
12438		 * A "pass" means that the LBA ranges don't overlap, so
12439		 * this doesn't match the user's range criteria.
12440		 */
12441		if (action == CTL_ACTION_PASS)
12442			return (CTL_LUN_PAT_NONE);
12443	}
12444
12445	return (filtered_pattern);
12446}
12447
12448static void
12449ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12450{
12451	struct ctl_error_desc *desc, *desc2;
12452
12453	mtx_assert(&lun->lun_lock, MA_OWNED);
12454
12455	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12456		ctl_lun_error_pattern pattern;
12457		/*
12458		 * Check to see whether this particular command matches
12459		 * the pattern in the descriptor.
12460		 */
12461		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12462		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12463			continue;
12464
12465		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12466		case CTL_LUN_INJ_ABORTED:
12467			ctl_set_aborted(&io->scsiio);
12468			break;
12469		case CTL_LUN_INJ_MEDIUM_ERR:
12470			ctl_set_medium_error(&io->scsiio,
12471			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12472			     CTL_FLAG_DATA_OUT);
12473			break;
12474		case CTL_LUN_INJ_UA:
12475			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12476			 * OCCURRED */
12477			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12478			break;
12479		case CTL_LUN_INJ_CUSTOM:
12480			/*
12481			 * We're assuming the user knows what he is doing.
12482			 * Just copy the sense information without doing
12483			 * checks.
12484			 */
12485			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12486			      MIN(sizeof(desc->custom_sense),
12487				  sizeof(io->scsiio.sense_data)));
12488			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12489			io->scsiio.sense_len = SSD_FULL_SIZE;
12490			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12491			break;
12492		case CTL_LUN_INJ_NONE:
12493		default:
12494			/*
12495			 * If this is an error injection type we don't know
12496			 * about, clear the continuous flag (if it is set)
12497			 * so it will get deleted below.
12498			 */
12499			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12500			break;
12501		}
12502		/*
12503		 * By default, each error injection action is a one-shot
12504		 */
12505		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12506			continue;
12507
12508		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12509
12510		free(desc, M_CTL);
12511	}
12512}
12513
12514#ifdef CTL_IO_DELAY
12515static void
12516ctl_datamove_timer_wakeup(void *arg)
12517{
12518	union ctl_io *io;
12519
12520	io = (union ctl_io *)arg;
12521
12522	ctl_datamove(io);
12523}
12524#endif /* CTL_IO_DELAY */
12525
12526void
12527ctl_datamove(union ctl_io *io)
12528{
12529	struct ctl_lun *lun;
12530	void (*fe_datamove)(union ctl_io *io);
12531
12532	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12533
12534	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12535
12536	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12537#ifdef CTL_TIME_IO
12538	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12539		char str[256];
12540		char path_str[64];
12541		struct sbuf sb;
12542
12543		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12544		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12545
12546		sbuf_cat(&sb, path_str);
12547		switch (io->io_hdr.io_type) {
12548		case CTL_IO_SCSI:
12549			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12550			sbuf_printf(&sb, "\n");
12551			sbuf_cat(&sb, path_str);
12552			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12553				    io->scsiio.tag_num, io->scsiio.tag_type);
12554			break;
12555		case CTL_IO_TASK:
12556			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12557				    "Tag Type: %d\n", io->taskio.task_action,
12558				    io->taskio.tag_num, io->taskio.tag_type);
12559			break;
12560		default:
12561			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12562			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12563			break;
12564		}
12565		sbuf_cat(&sb, path_str);
12566		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12567			    (intmax_t)time_uptime - io->io_hdr.start_time);
12568		sbuf_finish(&sb);
12569		printf("%s", sbuf_data(&sb));
12570	}
12571#endif /* CTL_TIME_IO */
12572
12573#ifdef CTL_IO_DELAY
12574	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12575		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12576	} else {
12577		if ((lun != NULL)
12578		 && (lun->delay_info.datamove_delay > 0)) {
12579
12580			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12581			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12582			callout_reset(&io->io_hdr.delay_callout,
12583				      lun->delay_info.datamove_delay * hz,
12584				      ctl_datamove_timer_wakeup, io);
12585			if (lun->delay_info.datamove_type ==
12586			    CTL_DELAY_TYPE_ONESHOT)
12587				lun->delay_info.datamove_delay = 0;
12588			return;
12589		}
12590	}
12591#endif
12592
12593	/*
12594	 * This command has been aborted.  Set the port status, so we fail
12595	 * the data move.
12596	 */
12597	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12598		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12599		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12600		       io->io_hdr.nexus.targ_port,
12601		       io->io_hdr.nexus.targ_lun);
12602		io->io_hdr.port_status = 31337;
12603		/*
12604		 * Note that the backend, in this case, will get the
12605		 * callback in its context.  In other cases it may get
12606		 * called in the frontend's interrupt thread context.
12607		 */
12608		io->scsiio.be_move_done(io);
12609		return;
12610	}
12611
12612	/* Don't confuse frontend with zero length data move. */
12613	if (io->scsiio.kern_data_len == 0) {
12614		io->scsiio.be_move_done(io);
12615		return;
12616	}
12617
12618	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12619	fe_datamove(io);
12620}
12621
12622static void
12623ctl_send_datamove_done(union ctl_io *io, int have_lock)
12624{
12625	union ctl_ha_msg msg;
12626#ifdef CTL_TIME_IO
12627	struct bintime cur_bt;
12628#endif
12629
12630	memset(&msg, 0, sizeof(msg));
12631	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12632	msg.hdr.original_sc = io;
12633	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12634	msg.hdr.nexus = io->io_hdr.nexus;
12635	msg.hdr.status = io->io_hdr.status;
12636	msg.scsi.tag_num = io->scsiio.tag_num;
12637	msg.scsi.tag_type = io->scsiio.tag_type;
12638	msg.scsi.scsi_status = io->scsiio.scsi_status;
12639	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12640	       io->scsiio.sense_len);
12641	msg.scsi.sense_len = io->scsiio.sense_len;
12642	msg.scsi.sense_residual = io->scsiio.sense_residual;
12643	msg.scsi.fetd_status = io->io_hdr.port_status;
12644	msg.scsi.residual = io->scsiio.residual;
12645	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12646	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12647		ctl_failover_io(io, /*have_lock*/ have_lock);
12648		return;
12649	}
12650	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12651	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12652	    msg.scsi.sense_len, M_WAITOK);
12653
12654#ifdef CTL_TIME_IO
12655	getbinuptime(&cur_bt);
12656	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12657	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12658#endif
12659	io->io_hdr.num_dmas++;
12660}
12661
12662/*
12663 * The DMA to the remote side is done, now we need to tell the other side
12664 * we're done so it can continue with its data movement.
12665 */
12666static void
12667ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12668{
12669	union ctl_io *io;
12670	int i;
12671
12672	io = rq->context;
12673
12674	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12675		printf("%s: ISC DMA write failed with error %d", __func__,
12676		       rq->ret);
12677		ctl_set_internal_failure(&io->scsiio,
12678					 /*sks_valid*/ 1,
12679					 /*retry_count*/ rq->ret);
12680	}
12681
12682	ctl_dt_req_free(rq);
12683
12684	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12685		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12686	free(io->io_hdr.remote_sglist, M_CTL);
12687	io->io_hdr.remote_sglist = NULL;
12688	io->io_hdr.local_sglist = NULL;
12689
12690	/*
12691	 * The data is in local and remote memory, so now we need to send
12692	 * status (good or back) back to the other side.
12693	 */
12694	ctl_send_datamove_done(io, /*have_lock*/ 0);
12695}
12696
12697/*
12698 * We've moved the data from the host/controller into local memory.  Now we
12699 * need to push it over to the remote controller's memory.
12700 */
12701static int
12702ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12703{
12704	int retval;
12705
12706	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12707					  ctl_datamove_remote_write_cb);
12708	return (retval);
12709}
12710
12711static void
12712ctl_datamove_remote_write(union ctl_io *io)
12713{
12714	int retval;
12715	void (*fe_datamove)(union ctl_io *io);
12716
12717	/*
12718	 * - Get the data from the host/HBA into local memory.
12719	 * - DMA memory from the local controller to the remote controller.
12720	 * - Send status back to the remote controller.
12721	 */
12722
12723	retval = ctl_datamove_remote_sgl_setup(io);
12724	if (retval != 0)
12725		return;
12726
12727	/* Switch the pointer over so the FETD knows what to do */
12728	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12729
12730	/*
12731	 * Use a custom move done callback, since we need to send completion
12732	 * back to the other controller, not to the backend on this side.
12733	 */
12734	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12735
12736	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12737	fe_datamove(io);
12738}
12739
12740static int
12741ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12742{
12743#if 0
12744	char str[256];
12745	char path_str[64];
12746	struct sbuf sb;
12747#endif
12748	int i;
12749
12750	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12751		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12752	free(io->io_hdr.remote_sglist, M_CTL);
12753	io->io_hdr.remote_sglist = NULL;
12754	io->io_hdr.local_sglist = NULL;
12755
12756#if 0
12757	scsi_path_string(io, path_str, sizeof(path_str));
12758	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12759	sbuf_cat(&sb, path_str);
12760	scsi_command_string(&io->scsiio, NULL, &sb);
12761	sbuf_printf(&sb, "\n");
12762	sbuf_cat(&sb, path_str);
12763	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12764		    io->scsiio.tag_num, io->scsiio.tag_type);
12765	sbuf_cat(&sb, path_str);
12766	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12767		    io->io_hdr.flags, io->io_hdr.status);
12768	sbuf_finish(&sb);
12769	printk("%s", sbuf_data(&sb));
12770#endif
12771
12772
12773	/*
12774	 * The read is done, now we need to send status (good or bad) back
12775	 * to the other side.
12776	 */
12777	ctl_send_datamove_done(io, /*have_lock*/ 0);
12778
12779	return (0);
12780}
12781
12782static void
12783ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12784{
12785	union ctl_io *io;
12786	void (*fe_datamove)(union ctl_io *io);
12787
12788	io = rq->context;
12789
12790	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12791		printf("%s: ISC DMA read failed with error %d\n", __func__,
12792		       rq->ret);
12793		ctl_set_internal_failure(&io->scsiio,
12794					 /*sks_valid*/ 1,
12795					 /*retry_count*/ rq->ret);
12796	}
12797
12798	ctl_dt_req_free(rq);
12799
12800	/* Switch the pointer over so the FETD knows what to do */
12801	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12802
12803	/*
12804	 * Use a custom move done callback, since we need to send completion
12805	 * back to the other controller, not to the backend on this side.
12806	 */
12807	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12808
12809	/* XXX KDM add checks like the ones in ctl_datamove? */
12810
12811	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12812	fe_datamove(io);
12813}
12814
12815static int
12816ctl_datamove_remote_sgl_setup(union ctl_io *io)
12817{
12818	struct ctl_sg_entry *local_sglist;
12819	uint32_t len_to_go;
12820	int retval;
12821	int i;
12822
12823	retval = 0;
12824	local_sglist = io->io_hdr.local_sglist;
12825	len_to_go = io->scsiio.kern_data_len;
12826
12827	/*
12828	 * The difficult thing here is that the size of the various
12829	 * S/G segments may be different than the size from the
12830	 * remote controller.  That'll make it harder when DMAing
12831	 * the data back to the other side.
12832	 */
12833	for (i = 0; len_to_go > 0; i++) {
12834		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12835		local_sglist[i].addr =
12836		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12837
12838		len_to_go -= local_sglist[i].len;
12839	}
12840	/*
12841	 * Reset the number of S/G entries accordingly.  The original
12842	 * number of S/G entries is available in rem_sg_entries.
12843	 */
12844	io->scsiio.kern_sg_entries = i;
12845
12846#if 0
12847	printf("%s: kern_sg_entries = %d\n", __func__,
12848	       io->scsiio.kern_sg_entries);
12849	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12850		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12851		       local_sglist[i].addr, local_sglist[i].len);
12852#endif
12853
12854	return (retval);
12855}
12856
12857static int
12858ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12859			 ctl_ha_dt_cb callback)
12860{
12861	struct ctl_ha_dt_req *rq;
12862	struct ctl_sg_entry *remote_sglist, *local_sglist;
12863	uint32_t local_used, remote_used, total_used;
12864	int i, j, isc_ret;
12865
12866	rq = ctl_dt_req_alloc();
12867
12868	/*
12869	 * If we failed to allocate the request, and if the DMA didn't fail
12870	 * anyway, set busy status.  This is just a resource allocation
12871	 * failure.
12872	 */
12873	if ((rq == NULL)
12874	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12875	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12876		ctl_set_busy(&io->scsiio);
12877
12878	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12879	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12880
12881		if (rq != NULL)
12882			ctl_dt_req_free(rq);
12883
12884		/*
12885		 * The data move failed.  We need to return status back
12886		 * to the other controller.  No point in trying to DMA
12887		 * data to the remote controller.
12888		 */
12889
12890		ctl_send_datamove_done(io, /*have_lock*/ 0);
12891
12892		return (1);
12893	}
12894
12895	local_sglist = io->io_hdr.local_sglist;
12896	remote_sglist = io->io_hdr.remote_sglist;
12897	local_used = 0;
12898	remote_used = 0;
12899	total_used = 0;
12900
12901	/*
12902	 * Pull/push the data over the wire from/to the other controller.
12903	 * This takes into account the possibility that the local and
12904	 * remote sglists may not be identical in terms of the size of
12905	 * the elements and the number of elements.
12906	 *
12907	 * One fundamental assumption here is that the length allocated for
12908	 * both the local and remote sglists is identical.  Otherwise, we've
12909	 * essentially got a coding error of some sort.
12910	 */
12911	isc_ret = CTL_HA_STATUS_SUCCESS;
12912	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12913		uint32_t cur_len;
12914		uint8_t *tmp_ptr;
12915
12916		rq->command = command;
12917		rq->context = io;
12918
12919		/*
12920		 * Both pointers should be aligned.  But it is possible
12921		 * that the allocation length is not.  They should both
12922		 * also have enough slack left over at the end, though,
12923		 * to round up to the next 8 byte boundary.
12924		 */
12925		cur_len = MIN(local_sglist[i].len - local_used,
12926			      remote_sglist[j].len - remote_used);
12927		rq->size = cur_len;
12928
12929		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12930		tmp_ptr += local_used;
12931
12932#if 0
12933		/* Use physical addresses when talking to ISC hardware */
12934		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12935			/* XXX KDM use busdma */
12936			rq->local = vtophys(tmp_ptr);
12937		} else
12938			rq->local = tmp_ptr;
12939#else
12940		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12941		    ("HA does not support BUS_ADDR"));
12942		rq->local = tmp_ptr;
12943#endif
12944
12945		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12946		tmp_ptr += remote_used;
12947		rq->remote = tmp_ptr;
12948
12949		rq->callback = NULL;
12950
12951		local_used += cur_len;
12952		if (local_used >= local_sglist[i].len) {
12953			i++;
12954			local_used = 0;
12955		}
12956
12957		remote_used += cur_len;
12958		if (remote_used >= remote_sglist[j].len) {
12959			j++;
12960			remote_used = 0;
12961		}
12962		total_used += cur_len;
12963
12964		if (total_used >= io->scsiio.kern_data_len)
12965			rq->callback = callback;
12966
12967#if 0
12968		printf("%s: %s: local %p remote %p size %d\n", __func__,
12969		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12970		       rq->local, rq->remote, rq->size);
12971#endif
12972
12973		isc_ret = ctl_dt_single(rq);
12974		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12975			break;
12976	}
12977	if (isc_ret != CTL_HA_STATUS_WAIT) {
12978		rq->ret = isc_ret;
12979		callback(rq);
12980	}
12981
12982	return (0);
12983}
12984
12985static void
12986ctl_datamove_remote_read(union ctl_io *io)
12987{
12988	int retval;
12989	int i;
12990
12991	/*
12992	 * This will send an error to the other controller in the case of a
12993	 * failure.
12994	 */
12995	retval = ctl_datamove_remote_sgl_setup(io);
12996	if (retval != 0)
12997		return;
12998
12999	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13000					  ctl_datamove_remote_read_cb);
13001	if (retval != 0) {
13002		/*
13003		 * Make sure we free memory if there was an error..  The
13004		 * ctl_datamove_remote_xfer() function will send the
13005		 * datamove done message, or call the callback with an
13006		 * error if there is a problem.
13007		 */
13008		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13009			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13010		free(io->io_hdr.remote_sglist, M_CTL);
13011		io->io_hdr.remote_sglist = NULL;
13012		io->io_hdr.local_sglist = NULL;
13013	}
13014}
13015
13016/*
13017 * Process a datamove request from the other controller.  This is used for
13018 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13019 * first.  Once that is complete, the data gets DMAed into the remote
13020 * controller's memory.  For reads, we DMA from the remote controller's
13021 * memory into our memory first, and then move it out to the FETD.
13022 */
13023static void
13024ctl_datamove_remote(union ctl_io *io)
13025{
13026
13027	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13028
13029	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13030		ctl_failover_io(io, /*have_lock*/ 0);
13031		return;
13032	}
13033
13034	/*
13035	 * Note that we look for an aborted I/O here, but don't do some of
13036	 * the other checks that ctl_datamove() normally does.
13037	 * We don't need to run the datamove delay code, since that should
13038	 * have been done if need be on the other controller.
13039	 */
13040	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13041		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13042		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13043		       io->io_hdr.nexus.targ_port,
13044		       io->io_hdr.nexus.targ_lun);
13045		io->io_hdr.port_status = 31338;
13046		ctl_send_datamove_done(io, /*have_lock*/ 0);
13047		return;
13048	}
13049
13050	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13051		ctl_datamove_remote_write(io);
13052	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13053		ctl_datamove_remote_read(io);
13054	else {
13055		io->io_hdr.port_status = 31339;
13056		ctl_send_datamove_done(io, /*have_lock*/ 0);
13057	}
13058}
13059
13060static void
13061ctl_process_done(union ctl_io *io)
13062{
13063	struct ctl_lun *lun;
13064	struct ctl_softc *softc = control_softc;
13065	void (*fe_done)(union ctl_io *io);
13066	union ctl_ha_msg msg;
13067	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13068
13069	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13070	fe_done = softc->ctl_ports[targ_port]->fe_done;
13071
13072#ifdef CTL_TIME_IO
13073	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13074		char str[256];
13075		char path_str[64];
13076		struct sbuf sb;
13077
13078		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13079		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13080
13081		sbuf_cat(&sb, path_str);
13082		switch (io->io_hdr.io_type) {
13083		case CTL_IO_SCSI:
13084			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13085			sbuf_printf(&sb, "\n");
13086			sbuf_cat(&sb, path_str);
13087			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13088				    io->scsiio.tag_num, io->scsiio.tag_type);
13089			break;
13090		case CTL_IO_TASK:
13091			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13092				    "Tag Type: %d\n", io->taskio.task_action,
13093				    io->taskio.tag_num, io->taskio.tag_type);
13094			break;
13095		default:
13096			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13097			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13098			break;
13099		}
13100		sbuf_cat(&sb, path_str);
13101		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13102			    (intmax_t)time_uptime - io->io_hdr.start_time);
13103		sbuf_finish(&sb);
13104		printf("%s", sbuf_data(&sb));
13105	}
13106#endif /* CTL_TIME_IO */
13107
13108	switch (io->io_hdr.io_type) {
13109	case CTL_IO_SCSI:
13110		break;
13111	case CTL_IO_TASK:
13112		if (ctl_debug & CTL_DEBUG_INFO)
13113			ctl_io_error_print(io, NULL);
13114		fe_done(io);
13115		return;
13116	default:
13117		panic("ctl_process_done: invalid io type %d\n",
13118		      io->io_hdr.io_type);
13119		break; /* NOTREACHED */
13120	}
13121
13122	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13123	if (lun == NULL) {
13124		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13125				 io->io_hdr.nexus.targ_mapped_lun));
13126		goto bailout;
13127	}
13128
13129	mtx_lock(&lun->lun_lock);
13130
13131	/*
13132	 * Check to see if we have any errors to inject here.  We only
13133	 * inject errors for commands that don't already have errors set.
13134	 */
13135	if (!STAILQ_EMPTY(&lun->error_list) &&
13136	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13137	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13138		ctl_inject_error(lun, io);
13139
13140	/*
13141	 * XXX KDM how do we treat commands that aren't completed
13142	 * successfully?
13143	 *
13144	 * XXX KDM should we also track I/O latency?
13145	 */
13146	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13147	    io->io_hdr.io_type == CTL_IO_SCSI) {
13148#ifdef CTL_TIME_IO
13149		struct bintime cur_bt;
13150#endif
13151		int type;
13152
13153		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13154		    CTL_FLAG_DATA_IN)
13155			type = CTL_STATS_READ;
13156		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13157		    CTL_FLAG_DATA_OUT)
13158			type = CTL_STATS_WRITE;
13159		else
13160			type = CTL_STATS_NO_IO;
13161
13162		lun->stats.ports[targ_port].bytes[type] +=
13163		    io->scsiio.kern_total_len;
13164		lun->stats.ports[targ_port].operations[type]++;
13165#ifdef CTL_TIME_IO
13166		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13167		   &io->io_hdr.dma_bt);
13168		getbinuptime(&cur_bt);
13169		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13170		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13171#endif
13172		lun->stats.ports[targ_port].num_dmas[type] +=
13173		    io->io_hdr.num_dmas;
13174	}
13175
13176	/*
13177	 * Remove this from the OOA queue.
13178	 */
13179	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13180#ifdef CTL_TIME_IO
13181	if (TAILQ_EMPTY(&lun->ooa_queue))
13182		lun->last_busy = getsbinuptime();
13183#endif
13184
13185	/*
13186	 * Run through the blocked queue on this LUN and see if anything
13187	 * has become unblocked, now that this transaction is done.
13188	 */
13189	ctl_check_blocked(lun);
13190
13191	/*
13192	 * If the LUN has been invalidated, free it if there is nothing
13193	 * left on its OOA queue.
13194	 */
13195	if ((lun->flags & CTL_LUN_INVALID)
13196	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13197		mtx_unlock(&lun->lun_lock);
13198		mtx_lock(&softc->ctl_lock);
13199		ctl_free_lun(lun);
13200		mtx_unlock(&softc->ctl_lock);
13201	} else
13202		mtx_unlock(&lun->lun_lock);
13203
13204bailout:
13205
13206	/*
13207	 * If this command has been aborted, make sure we set the status
13208	 * properly.  The FETD is responsible for freeing the I/O and doing
13209	 * whatever it needs to do to clean up its state.
13210	 */
13211	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13212		ctl_set_task_aborted(&io->scsiio);
13213
13214	/*
13215	 * If enabled, print command error status.
13216	 */
13217	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13218	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13219		ctl_io_error_print(io, NULL);
13220
13221	/*
13222	 * Tell the FETD or the other shelf controller we're done with this
13223	 * command.  Note that only SCSI commands get to this point.  Task
13224	 * management commands are completed above.
13225	 */
13226	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13227	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13228		memset(&msg, 0, sizeof(msg));
13229		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13230		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13231		msg.hdr.nexus = io->io_hdr.nexus;
13232		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13233		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13234		    M_WAITOK);
13235	}
13236
13237	fe_done(io);
13238}
13239
13240#ifdef CTL_WITH_CA
13241/*
13242 * Front end should call this if it doesn't do autosense.  When the request
13243 * sense comes back in from the initiator, we'll dequeue this and send it.
13244 */
13245int
13246ctl_queue_sense(union ctl_io *io)
13247{
13248	struct ctl_lun *lun;
13249	struct ctl_port *port;
13250	struct ctl_softc *softc;
13251	uint32_t initidx, targ_lun;
13252
13253	softc = control_softc;
13254
13255	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13256
13257	/*
13258	 * LUN lookup will likely move to the ctl_work_thread() once we
13259	 * have our new queueing infrastructure (that doesn't put things on
13260	 * a per-LUN queue initially).  That is so that we can handle
13261	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13262	 * can't deal with that right now.
13263	 */
13264	mtx_lock(&softc->ctl_lock);
13265
13266	/*
13267	 * If we don't have a LUN for this, just toss the sense
13268	 * information.
13269	 */
13270	port = ctl_io_port(&ctsio->io_hdr);
13271	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13272	if ((targ_lun < CTL_MAX_LUNS)
13273	 && (softc->ctl_luns[targ_lun] != NULL))
13274		lun = softc->ctl_luns[targ_lun];
13275	else
13276		goto bailout;
13277
13278	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13279
13280	mtx_lock(&lun->lun_lock);
13281	/*
13282	 * Already have CA set for this LUN...toss the sense information.
13283	 */
13284	if (ctl_is_set(lun->have_ca, initidx)) {
13285		mtx_unlock(&lun->lun_lock);
13286		goto bailout;
13287	}
13288
13289	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13290	       MIN(sizeof(lun->pending_sense[initidx]),
13291	       sizeof(io->scsiio.sense_data)));
13292	ctl_set_mask(lun->have_ca, initidx);
13293	mtx_unlock(&lun->lun_lock);
13294
13295bailout:
13296	mtx_unlock(&softc->ctl_lock);
13297
13298	ctl_free_io(io);
13299
13300	return (CTL_RETVAL_COMPLETE);
13301}
13302#endif
13303
13304/*
13305 * Primary command inlet from frontend ports.  All SCSI and task I/O
13306 * requests must go through this function.
13307 */
13308int
13309ctl_queue(union ctl_io *io)
13310{
13311	struct ctl_port *port;
13312
13313	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13314
13315#ifdef CTL_TIME_IO
13316	io->io_hdr.start_time = time_uptime;
13317	getbinuptime(&io->io_hdr.start_bt);
13318#endif /* CTL_TIME_IO */
13319
13320	/* Map FE-specific LUN ID into global one. */
13321	port = ctl_io_port(&io->io_hdr);
13322	io->io_hdr.nexus.targ_mapped_lun =
13323	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13324
13325	switch (io->io_hdr.io_type) {
13326	case CTL_IO_SCSI:
13327	case CTL_IO_TASK:
13328		if (ctl_debug & CTL_DEBUG_CDB)
13329			ctl_io_print(io);
13330		ctl_enqueue_incoming(io);
13331		break;
13332	default:
13333		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13334		return (EINVAL);
13335	}
13336
13337	return (CTL_RETVAL_COMPLETE);
13338}
13339
13340#ifdef CTL_IO_DELAY
13341static void
13342ctl_done_timer_wakeup(void *arg)
13343{
13344	union ctl_io *io;
13345
13346	io = (union ctl_io *)arg;
13347	ctl_done(io);
13348}
13349#endif /* CTL_IO_DELAY */
13350
13351void
13352ctl_serseq_done(union ctl_io *io)
13353{
13354	struct ctl_lun *lun;
13355
13356	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13357	if (lun->be_lun == NULL ||
13358	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13359		return;
13360	mtx_lock(&lun->lun_lock);
13361	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13362	ctl_check_blocked(lun);
13363	mtx_unlock(&lun->lun_lock);
13364}
13365
13366void
13367ctl_done(union ctl_io *io)
13368{
13369
13370	/*
13371	 * Enable this to catch duplicate completion issues.
13372	 */
13373#if 0
13374	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13375		printf("%s: type %d msg %d cdb %x iptl: "
13376		       "%u:%u:%u tag 0x%04x "
13377		       "flag %#x status %x\n",
13378			__func__,
13379			io->io_hdr.io_type,
13380			io->io_hdr.msg_type,
13381			io->scsiio.cdb[0],
13382			io->io_hdr.nexus.initid,
13383			io->io_hdr.nexus.targ_port,
13384			io->io_hdr.nexus.targ_lun,
13385			(io->io_hdr.io_type ==
13386			CTL_IO_TASK) ?
13387			io->taskio.tag_num :
13388			io->scsiio.tag_num,
13389		        io->io_hdr.flags,
13390			io->io_hdr.status);
13391	} else
13392		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13393#endif
13394
13395	/*
13396	 * This is an internal copy of an I/O, and should not go through
13397	 * the normal done processing logic.
13398	 */
13399	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13400		return;
13401
13402#ifdef CTL_IO_DELAY
13403	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13404		struct ctl_lun *lun;
13405
13406		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13407
13408		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13409	} else {
13410		struct ctl_lun *lun;
13411
13412		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13413
13414		if ((lun != NULL)
13415		 && (lun->delay_info.done_delay > 0)) {
13416
13417			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13418			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13419			callout_reset(&io->io_hdr.delay_callout,
13420				      lun->delay_info.done_delay * hz,
13421				      ctl_done_timer_wakeup, io);
13422			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13423				lun->delay_info.done_delay = 0;
13424			return;
13425		}
13426	}
13427#endif /* CTL_IO_DELAY */
13428
13429	ctl_enqueue_done(io);
13430}
13431
13432static void
13433ctl_work_thread(void *arg)
13434{
13435	struct ctl_thread *thr = (struct ctl_thread *)arg;
13436	struct ctl_softc *softc = thr->ctl_softc;
13437	union ctl_io *io;
13438	int retval;
13439
13440	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13441
13442	for (;;) {
13443		/*
13444		 * We handle the queues in this order:
13445		 * - ISC
13446		 * - done queue (to free up resources, unblock other commands)
13447		 * - RtR queue
13448		 * - incoming queue
13449		 *
13450		 * If those queues are empty, we break out of the loop and
13451		 * go to sleep.
13452		 */
13453		mtx_lock(&thr->queue_lock);
13454		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13455		if (io != NULL) {
13456			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13457			mtx_unlock(&thr->queue_lock);
13458			ctl_handle_isc(io);
13459			continue;
13460		}
13461		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13462		if (io != NULL) {
13463			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13464			/* clear any blocked commands, call fe_done */
13465			mtx_unlock(&thr->queue_lock);
13466			ctl_process_done(io);
13467			continue;
13468		}
13469		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13470		if (io != NULL) {
13471			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13472			mtx_unlock(&thr->queue_lock);
13473			if (io->io_hdr.io_type == CTL_IO_TASK)
13474				ctl_run_task(io);
13475			else
13476				ctl_scsiio_precheck(softc, &io->scsiio);
13477			continue;
13478		}
13479		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13480		if (io != NULL) {
13481			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13482			mtx_unlock(&thr->queue_lock);
13483			retval = ctl_scsiio(&io->scsiio);
13484			if (retval != CTL_RETVAL_COMPLETE)
13485				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13486			continue;
13487		}
13488
13489		/* Sleep until we have something to do. */
13490		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13491	}
13492}
13493
13494static void
13495ctl_lun_thread(void *arg)
13496{
13497	struct ctl_softc *softc = (struct ctl_softc *)arg;
13498	struct ctl_be_lun *be_lun;
13499
13500	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13501
13502	for (;;) {
13503		mtx_lock(&softc->ctl_lock);
13504		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13505		if (be_lun != NULL) {
13506			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13507			mtx_unlock(&softc->ctl_lock);
13508			ctl_create_lun(be_lun);
13509			continue;
13510		}
13511
13512		/* Sleep until we have something to do. */
13513		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13514		    PDROP | PRIBIO, "-", 0);
13515	}
13516}
13517
13518static void
13519ctl_thresh_thread(void *arg)
13520{
13521	struct ctl_softc *softc = (struct ctl_softc *)arg;
13522	struct ctl_lun *lun;
13523	struct scsi_da_rw_recovery_page *rwpage;
13524	struct ctl_logical_block_provisioning_page *page;
13525	const char *attr;
13526	union ctl_ha_msg msg;
13527	uint64_t thres, val;
13528	int i, e, set;
13529
13530	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13531
13532	for (;;) {
13533		mtx_lock(&softc->ctl_lock);
13534		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13535			if ((lun->flags & CTL_LUN_DISABLED) ||
13536			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13537			    lun->backend->lun_attr == NULL)
13538				continue;
13539			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13540			    softc->ha_mode == CTL_HA_MODE_XFER)
13541				continue;
13542			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13543			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13544				continue;
13545			e = 0;
13546			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13547			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13548				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13549					continue;
13550				thres = scsi_4btoul(page->descr[i].count);
13551				thres <<= CTL_LBP_EXPONENT;
13552				switch (page->descr[i].resource) {
13553				case 0x01:
13554					attr = "blocksavail";
13555					break;
13556				case 0x02:
13557					attr = "blocksused";
13558					break;
13559				case 0xf1:
13560					attr = "poolblocksavail";
13561					break;
13562				case 0xf2:
13563					attr = "poolblocksused";
13564					break;
13565				default:
13566					continue;
13567				}
13568				mtx_unlock(&softc->ctl_lock); // XXX
13569				val = lun->backend->lun_attr(
13570				    lun->be_lun->be_lun, attr);
13571				mtx_lock(&softc->ctl_lock);
13572				if (val == UINT64_MAX)
13573					continue;
13574				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13575				    == SLBPPD_ARMING_INC)
13576					e = (val >= thres);
13577				else
13578					e = (val <= thres);
13579				if (e)
13580					break;
13581			}
13582			mtx_lock(&lun->lun_lock);
13583			if (e) {
13584				scsi_u64to8b((uint8_t *)&page->descr[i] -
13585				    (uint8_t *)page, lun->ua_tpt_info);
13586				if (lun->lasttpt == 0 ||
13587				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13588					lun->lasttpt = time_uptime;
13589					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13590					set = 1;
13591				} else
13592					set = 0;
13593			} else {
13594				lun->lasttpt = 0;
13595				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13596				set = -1;
13597			}
13598			mtx_unlock(&lun->lun_lock);
13599			if (set != 0 &&
13600			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13601				/* Send msg to other side. */
13602				bzero(&msg.ua, sizeof(msg.ua));
13603				msg.hdr.msg_type = CTL_MSG_UA;
13604				msg.hdr.nexus.initid = -1;
13605				msg.hdr.nexus.targ_port = -1;
13606				msg.hdr.nexus.targ_lun = lun->lun;
13607				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13608				msg.ua.ua_all = 1;
13609				msg.ua.ua_set = (set > 0);
13610				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13611				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13612				mtx_unlock(&softc->ctl_lock); // XXX
13613				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13614				    sizeof(msg.ua), M_WAITOK);
13615				mtx_lock(&softc->ctl_lock);
13616			}
13617		}
13618		mtx_unlock(&softc->ctl_lock);
13619		pause("-", CTL_LBP_PERIOD * hz);
13620	}
13621}
13622
13623static void
13624ctl_enqueue_incoming(union ctl_io *io)
13625{
13626	struct ctl_softc *softc = control_softc;
13627	struct ctl_thread *thr;
13628	u_int idx;
13629
13630	idx = (io->io_hdr.nexus.targ_port * 127 +
13631	       io->io_hdr.nexus.initid) % worker_threads;
13632	thr = &softc->threads[idx];
13633	mtx_lock(&thr->queue_lock);
13634	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13635	mtx_unlock(&thr->queue_lock);
13636	wakeup(thr);
13637}
13638
13639static void
13640ctl_enqueue_rtr(union ctl_io *io)
13641{
13642	struct ctl_softc *softc = control_softc;
13643	struct ctl_thread *thr;
13644
13645	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13646	mtx_lock(&thr->queue_lock);
13647	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13648	mtx_unlock(&thr->queue_lock);
13649	wakeup(thr);
13650}
13651
13652static void
13653ctl_enqueue_done(union ctl_io *io)
13654{
13655	struct ctl_softc *softc = control_softc;
13656	struct ctl_thread *thr;
13657
13658	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13659	mtx_lock(&thr->queue_lock);
13660	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13661	mtx_unlock(&thr->queue_lock);
13662	wakeup(thr);
13663}
13664
13665static void
13666ctl_enqueue_isc(union ctl_io *io)
13667{
13668	struct ctl_softc *softc = control_softc;
13669	struct ctl_thread *thr;
13670
13671	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13672	mtx_lock(&thr->queue_lock);
13673	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13674	mtx_unlock(&thr->queue_lock);
13675	wakeup(thr);
13676}
13677
13678/*
13679 *  vim: ts=8
13680 */
13681