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