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