ctl.c revision 312837
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Portions of this software were developed by Edward Tomasz Napierala
8 * under sponsorship from the FreeBSD Foundation.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions, and the following disclaimer,
15 *    without modification.
16 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17 *    substantially similar to the "NO WARRANTY" disclaimer below
18 *    ("Disclaimer") and any redistribution must be conditioned upon
19 *    including a substantially similar Disclaimer requirement for further
20 *    binary redistribution.
21 *
22 * NO WARRANTY
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGES.
34 *
35 * $Id$
36 */
37/*
38 * CAM Target Layer, a SCSI device emulation subsystem.
39 *
40 * Author: Ken Merry <ken@FreeBSD.org>
41 */
42
43#define _CTL_C
44
45#include <sys/cdefs.h>
46__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 312837 2017-01-26 20:51:50Z 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 scsi_da_rw_recovery_page rw_er_page_default = {
97	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
98	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
99	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
100	/*read_retry_count*/0,
101	/*correction_span*/0,
102	/*head_offset_count*/0,
103	/*data_strobe_offset_cnt*/0,
104	/*byte8*/SMS_RWER_LBPERE,
105	/*write_retry_count*/0,
106	/*reserved2*/0,
107	/*recovery_time_limit*/{0, 0},
108};
109
110const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
111	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
112	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
113	/*byte3*/SMS_RWER_PER,
114	/*read_retry_count*/0,
115	/*correction_span*/0,
116	/*head_offset_count*/0,
117	/*data_strobe_offset_cnt*/0,
118	/*byte8*/SMS_RWER_LBPERE,
119	/*write_retry_count*/0,
120	/*reserved2*/0,
121	/*recovery_time_limit*/{0, 0},
122};
123
124const static struct scsi_format_page format_page_default = {
125	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
126	/*page_length*/sizeof(struct scsi_format_page) - 2,
127	/*tracks_per_zone*/ {0, 0},
128	/*alt_sectors_per_zone*/ {0, 0},
129	/*alt_tracks_per_zone*/ {0, 0},
130	/*alt_tracks_per_lun*/ {0, 0},
131	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
132			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
133	/*bytes_per_sector*/ {0, 0},
134	/*interleave*/ {0, 0},
135	/*track_skew*/ {0, 0},
136	/*cylinder_skew*/ {0, 0},
137	/*flags*/ SFP_HSEC,
138	/*reserved*/ {0, 0, 0}
139};
140
141const static struct scsi_format_page format_page_changeable = {
142	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
143	/*page_length*/sizeof(struct scsi_format_page) - 2,
144	/*tracks_per_zone*/ {0, 0},
145	/*alt_sectors_per_zone*/ {0, 0},
146	/*alt_tracks_per_zone*/ {0, 0},
147	/*alt_tracks_per_lun*/ {0, 0},
148	/*sectors_per_track*/ {0, 0},
149	/*bytes_per_sector*/ {0, 0},
150	/*interleave*/ {0, 0},
151	/*track_skew*/ {0, 0},
152	/*cylinder_skew*/ {0, 0},
153	/*flags*/ 0,
154	/*reserved*/ {0, 0, 0}
155};
156
157const static struct scsi_rigid_disk_page rigid_disk_page_default = {
158	/*page_code*/SMS_RIGID_DISK_PAGE,
159	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
160	/*cylinders*/ {0, 0, 0},
161	/*heads*/ CTL_DEFAULT_HEADS,
162	/*start_write_precomp*/ {0, 0, 0},
163	/*start_reduced_current*/ {0, 0, 0},
164	/*step_rate*/ {0, 0},
165	/*landing_zone_cylinder*/ {0, 0, 0},
166	/*rpl*/ SRDP_RPL_DISABLED,
167	/*rotational_offset*/ 0,
168	/*reserved1*/ 0,
169	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
170			   CTL_DEFAULT_ROTATION_RATE & 0xff},
171	/*reserved2*/ {0, 0}
172};
173
174const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
175	/*page_code*/SMS_RIGID_DISK_PAGE,
176	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
177	/*cylinders*/ {0, 0, 0},
178	/*heads*/ 0,
179	/*start_write_precomp*/ {0, 0, 0},
180	/*start_reduced_current*/ {0, 0, 0},
181	/*step_rate*/ {0, 0},
182	/*landing_zone_cylinder*/ {0, 0, 0},
183	/*rpl*/ 0,
184	/*rotational_offset*/ 0,
185	/*reserved1*/ 0,
186	/*rotation_rate*/ {0, 0},
187	/*reserved2*/ {0, 0}
188};
189
190const static struct scsi_da_verify_recovery_page verify_er_page_default = {
191	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
192	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
193	/*byte3*/0,
194	/*read_retry_count*/0,
195	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
196	/*recovery_time_limit*/{0, 0},
197};
198
199const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
200	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
201	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
202	/*byte3*/SMS_VER_PER,
203	/*read_retry_count*/0,
204	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
205	/*recovery_time_limit*/{0, 0},
206};
207
208const static struct scsi_caching_page caching_page_default = {
209	/*page_code*/SMS_CACHING_PAGE,
210	/*page_length*/sizeof(struct scsi_caching_page) - 2,
211	/*flags1*/ SCP_DISC | SCP_WCE,
212	/*ret_priority*/ 0,
213	/*disable_pf_transfer_len*/ {0xff, 0xff},
214	/*min_prefetch*/ {0, 0},
215	/*max_prefetch*/ {0xff, 0xff},
216	/*max_pf_ceiling*/ {0xff, 0xff},
217	/*flags2*/ 0,
218	/*cache_segments*/ 0,
219	/*cache_seg_size*/ {0, 0},
220	/*reserved*/ 0,
221	/*non_cache_seg_size*/ {0, 0, 0}
222};
223
224const static struct scsi_caching_page caching_page_changeable = {
225	/*page_code*/SMS_CACHING_PAGE,
226	/*page_length*/sizeof(struct scsi_caching_page) - 2,
227	/*flags1*/ SCP_WCE | SCP_RCD,
228	/*ret_priority*/ 0,
229	/*disable_pf_transfer_len*/ {0, 0},
230	/*min_prefetch*/ {0, 0},
231	/*max_prefetch*/ {0, 0},
232	/*max_pf_ceiling*/ {0, 0},
233	/*flags2*/ 0,
234	/*cache_segments*/ 0,
235	/*cache_seg_size*/ {0, 0},
236	/*reserved*/ 0,
237	/*non_cache_seg_size*/ {0, 0, 0}
238};
239
240const static struct scsi_control_page control_page_default = {
241	/*page_code*/SMS_CONTROL_MODE_PAGE,
242	/*page_length*/sizeof(struct scsi_control_page) - 2,
243	/*rlec*/0,
244	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245	/*eca_and_aen*/0,
246	/*flags4*/SCP_TAS,
247	/*aen_holdoff_period*/{0, 0},
248	/*busy_timeout_period*/{0, 0},
249	/*extended_selftest_completion_time*/{0, 0}
250};
251
252const static struct scsi_control_page control_page_changeable = {
253	/*page_code*/SMS_CONTROL_MODE_PAGE,
254	/*page_length*/sizeof(struct scsi_control_page) - 2,
255	/*rlec*/SCP_DSENSE,
256	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
257	/*eca_and_aen*/SCP_SWP,
258	/*flags4*/0,
259	/*aen_holdoff_period*/{0, 0},
260	/*busy_timeout_period*/{0, 0},
261	/*extended_selftest_completion_time*/{0, 0}
262};
263
264#define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
265
266const static struct scsi_control_ext_page control_ext_page_default = {
267	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268	/*subpage_code*/0x01,
269	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270	/*flags*/0,
271	/*prio*/0,
272	/*max_sense*/0
273};
274
275const static struct scsi_control_ext_page control_ext_page_changeable = {
276	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277	/*subpage_code*/0x01,
278	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279	/*flags*/0,
280	/*prio*/0,
281	/*max_sense*/0xff
282};
283
284const static struct scsi_info_exceptions_page ie_page_default = {
285	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287	/*info_flags*/SIEP_FLAGS_EWASC,
288	/*mrie*/SIEP_MRIE_NO,
289	/*interval_timer*/{0, 0, 0, 0},
290	/*report_count*/{0, 0, 0, 1}
291};
292
293const static struct scsi_info_exceptions_page ie_page_changeable = {
294	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
297	    SIEP_FLAGS_LOGERR,
298	/*mrie*/0x0f,
299	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
300	/*report_count*/{0xff, 0xff, 0xff, 0xff}
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*/SLBPP_SITUA,
336	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337	/*descr*/{}},
338	{{/*flags*/0,
339	  /*resource*/0,
340	  /*reserved*/{0, 0},
341	  /*count*/{0, 0, 0, 0}},
342	 {/*flags*/0,
343	  /*resource*/0,
344	  /*reserved*/{0, 0},
345	  /*count*/{0, 0, 0, 0}},
346	 {/*flags*/0,
347	  /*resource*/0,
348	  /*reserved*/{0, 0},
349	  /*count*/{0, 0, 0, 0}},
350	 {/*flags*/0,
351	  /*resource*/0,
352	  /*reserved*/{0, 0},
353	  /*count*/{0, 0, 0, 0}}
354	}
355};
356
357const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358	/*page_code*/SMS_CDDVD_CAPS_PAGE,
359	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360	/*caps1*/0x3f,
361	/*caps2*/0x00,
362	/*caps3*/0xf0,
363	/*caps4*/0x00,
364	/*caps5*/0x29,
365	/*caps6*/0x00,
366	/*obsolete*/{0, 0},
367	/*nvol_levels*/{0, 0},
368	/*buffer_size*/{8, 0},
369	/*obsolete2*/{0, 0},
370	/*reserved*/0,
371	/*digital*/0,
372	/*obsolete3*/0,
373	/*copy_management*/0,
374	/*reserved2*/0,
375	/*rotation_control*/0,
376	/*cur_write_speed*/0,
377	/*num_speed_descr*/0,
378};
379
380const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381	/*page_code*/SMS_CDDVD_CAPS_PAGE,
382	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383	/*caps1*/0,
384	/*caps2*/0,
385	/*caps3*/0,
386	/*caps4*/0,
387	/*caps5*/0,
388	/*caps6*/0,
389	/*obsolete*/{0, 0},
390	/*nvol_levels*/{0, 0},
391	/*buffer_size*/{0, 0},
392	/*obsolete2*/{0, 0},
393	/*reserved*/0,
394	/*digital*/0,
395	/*obsolete3*/0,
396	/*copy_management*/0,
397	/*reserved2*/0,
398	/*rotation_control*/0,
399	/*cur_write_speed*/0,
400	/*num_speed_descr*/0,
401};
402
403SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404static int worker_threads = -1;
405TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407    &worker_threads, 1, "Number of worker threads");
408static int ctl_debug = CTL_DEBUG_NONE;
409TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411    &ctl_debug, 0, "Enabled debug flags");
412static int ctl_lun_map_size = 1024;
413SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
414    &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
415
416/*
417 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
418 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
419 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
420 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
421 */
422#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
423
424static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
425				  int param);
426static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
427static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
428static int ctl_init(void);
429void ctl_shutdown(void);
430static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
431static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
432static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
433static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
434			      struct ctl_ooa *ooa_hdr,
435			      struct ctl_ooa_entry *kern_entries);
436static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
437		     struct thread *td);
438static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
439			 struct ctl_be_lun *be_lun);
440static int ctl_free_lun(struct ctl_lun *lun);
441static void ctl_create_lun(struct ctl_be_lun *be_lun);
442
443static int ctl_do_mode_select(union ctl_io *io);
444static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
445			   uint64_t res_key, uint64_t sa_res_key,
446			   uint8_t type, uint32_t residx,
447			   struct ctl_scsiio *ctsio,
448			   struct scsi_per_res_out *cdb,
449			   struct scsi_per_res_out_parms* param);
450static void ctl_pro_preempt_other(struct ctl_lun *lun,
451				  union ctl_ha_msg *msg);
452static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
453static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
455static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
456static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
457static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
458static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
459					 int alloc_len);
460static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
461					 int alloc_len);
462static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
463static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
464static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
465static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
466static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
467static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
468    bool seq);
469static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
470static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
471    union ctl_io *pending_io, union ctl_io *ooa_io);
472static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
473				union ctl_io *starting_io);
474static int ctl_check_blocked(struct ctl_lun *lun);
475static int ctl_scsiio_lun_check(struct ctl_lun *lun,
476				const struct ctl_cmd_entry *entry,
477				struct ctl_scsiio *ctsio);
478static void ctl_failover_lun(union ctl_io *io);
479static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
480			       struct ctl_scsiio *ctsio);
481static int ctl_scsiio(struct ctl_scsiio *ctsio);
482
483static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
484static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
485			    ctl_ua_type ua_type);
486static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
487			 ctl_ua_type ua_type);
488static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
489static int ctl_abort_task(union ctl_io *io);
490static int ctl_abort_task_set(union ctl_io *io);
491static int ctl_query_task(union ctl_io *io, int task_set);
492static int ctl_i_t_nexus_reset(union ctl_io *io);
493static int ctl_query_async_event(union ctl_io *io);
494static void ctl_run_task(union ctl_io *io);
495#ifdef CTL_IO_DELAY
496static void ctl_datamove_timer_wakeup(void *arg);
497static void ctl_done_timer_wakeup(void *arg);
498#endif /* CTL_IO_DELAY */
499
500static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
501static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
502static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
503static void ctl_datamove_remote_write(union ctl_io *io);
504static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
505static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
506static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
507static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
508				    ctl_ha_dt_cb callback);
509static void ctl_datamove_remote_read(union ctl_io *io);
510static void ctl_datamove_remote(union ctl_io *io);
511static void ctl_process_done(union ctl_io *io);
512static void ctl_lun_thread(void *arg);
513static void ctl_thresh_thread(void *arg);
514static void ctl_work_thread(void *arg);
515static void ctl_enqueue_incoming(union ctl_io *io);
516static void ctl_enqueue_rtr(union ctl_io *io);
517static void ctl_enqueue_done(union ctl_io *io);
518static void ctl_enqueue_isc(union ctl_io *io);
519static const struct ctl_cmd_entry *
520    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
521static const struct ctl_cmd_entry *
522    ctl_validate_command(struct ctl_scsiio *ctsio);
523static int ctl_cmd_applicable(uint8_t lun_type,
524    const struct ctl_cmd_entry *entry);
525
526static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
527static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
528static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
529static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
530
531/*
532 * Load the serialization table.  This isn't very pretty, but is probably
533 * the easiest way to do it.
534 */
535#include "ctl_ser_table.c"
536
537/*
538 * We only need to define open, close and ioctl routines for this driver.
539 */
540static struct cdevsw ctl_cdevsw = {
541	.d_version =	D_VERSION,
542	.d_flags =	0,
543	.d_open =	ctl_open,
544	.d_close =	ctl_close,
545	.d_ioctl =	ctl_ioctl,
546	.d_name =	"ctl",
547};
548
549
550MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
551
552static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
553
554static moduledata_t ctl_moduledata = {
555	"ctl",
556	ctl_module_event_handler,
557	NULL
558};
559
560DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
561MODULE_VERSION(ctl, 1);
562
563static struct ctl_frontend ha_frontend =
564{
565	.name = "ha",
566};
567
568static void
569ctl_ha_datamove(union ctl_io *io)
570{
571	struct ctl_lun *lun = CTL_LUN(io);
572	struct ctl_sg_entry *sgl;
573	union ctl_ha_msg msg;
574	uint32_t sg_entries_sent;
575	int do_sg_copy, i, j;
576
577	memset(&msg.dt, 0, sizeof(msg.dt));
578	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
579	msg.hdr.original_sc = io->io_hdr.original_sc;
580	msg.hdr.serializing_sc = io;
581	msg.hdr.nexus = io->io_hdr.nexus;
582	msg.hdr.status = io->io_hdr.status;
583	msg.dt.flags = io->io_hdr.flags;
584
585	/*
586	 * We convert everything into a S/G list here.  We can't
587	 * pass by reference, only by value between controllers.
588	 * So we can't pass a pointer to the S/G list, only as many
589	 * S/G entries as we can fit in here.  If it's possible for
590	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
591	 * then we need to break this up into multiple transfers.
592	 */
593	if (io->scsiio.kern_sg_entries == 0) {
594		msg.dt.kern_sg_entries = 1;
595#if 0
596		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
597			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
598		} else {
599			/* XXX KDM use busdma here! */
600			msg.dt.sg_list[0].addr =
601			    (void *)vtophys(io->scsiio.kern_data_ptr);
602		}
603#else
604		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
605		    ("HA does not support BUS_ADDR"));
606		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
607#endif
608		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
609		do_sg_copy = 0;
610	} else {
611		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
612		do_sg_copy = 1;
613	}
614
615	msg.dt.kern_data_len = io->scsiio.kern_data_len;
616	msg.dt.kern_total_len = io->scsiio.kern_total_len;
617	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
618	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
619	msg.dt.sg_sequence = 0;
620
621	/*
622	 * Loop until we've sent all of the S/G entries.  On the
623	 * other end, we'll recompose these S/G entries into one
624	 * contiguous list before processing.
625	 */
626	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
627	    msg.dt.sg_sequence++) {
628		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
629		    sizeof(msg.dt.sg_list[0])),
630		    msg.dt.kern_sg_entries - sg_entries_sent);
631		if (do_sg_copy != 0) {
632			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
633			for (i = sg_entries_sent, j = 0;
634			     i < msg.dt.cur_sg_entries; i++, j++) {
635#if 0
636				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
637					msg.dt.sg_list[j].addr = sgl[i].addr;
638				} else {
639					/* XXX KDM use busdma here! */
640					msg.dt.sg_list[j].addr =
641					    (void *)vtophys(sgl[i].addr);
642				}
643#else
644				KASSERT((io->io_hdr.flags &
645				    CTL_FLAG_BUS_ADDR) == 0,
646				    ("HA does not support BUS_ADDR"));
647				msg.dt.sg_list[j].addr = sgl[i].addr;
648#endif
649				msg.dt.sg_list[j].len = sgl[i].len;
650			}
651		}
652
653		sg_entries_sent += msg.dt.cur_sg_entries;
654		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
655		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
656		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
657		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
658		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
659			io->io_hdr.port_status = 31341;
660			io->scsiio.be_move_done(io);
661			return;
662		}
663		msg.dt.sent_sg_entries = sg_entries_sent;
664	}
665
666	/*
667	 * Officially handover the request from us to peer.
668	 * If failover has just happened, then we must return error.
669	 * If failover happen just after, then it is not our problem.
670	 */
671	if (lun)
672		mtx_lock(&lun->lun_lock);
673	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
674		if (lun)
675			mtx_unlock(&lun->lun_lock);
676		io->io_hdr.port_status = 31342;
677		io->scsiio.be_move_done(io);
678		return;
679	}
680	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
681	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
682	if (lun)
683		mtx_unlock(&lun->lun_lock);
684}
685
686static void
687ctl_ha_done(union ctl_io *io)
688{
689	union ctl_ha_msg msg;
690
691	if (io->io_hdr.io_type == CTL_IO_SCSI) {
692		memset(&msg, 0, sizeof(msg));
693		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
694		msg.hdr.original_sc = io->io_hdr.original_sc;
695		msg.hdr.nexus = io->io_hdr.nexus;
696		msg.hdr.status = io->io_hdr.status;
697		msg.scsi.scsi_status = io->scsiio.scsi_status;
698		msg.scsi.tag_num = io->scsiio.tag_num;
699		msg.scsi.tag_type = io->scsiio.tag_type;
700		msg.scsi.sense_len = io->scsiio.sense_len;
701		msg.scsi.sense_residual = io->scsiio.sense_residual;
702		msg.scsi.residual = io->scsiio.residual;
703		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
704		    io->scsiio.sense_len);
705		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
706		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
707		    msg.scsi.sense_len, M_WAITOK);
708	}
709	ctl_free_io(io);
710}
711
712static void
713ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
714			    union ctl_ha_msg *msg_info)
715{
716	struct ctl_scsiio *ctsio;
717
718	if (msg_info->hdr.original_sc == NULL) {
719		printf("%s: original_sc == NULL!\n", __func__);
720		/* XXX KDM now what? */
721		return;
722	}
723
724	ctsio = &msg_info->hdr.original_sc->scsiio;
725	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
726	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
727	ctsio->io_hdr.status = msg_info->hdr.status;
728	ctsio->scsi_status = msg_info->scsi.scsi_status;
729	ctsio->sense_len = msg_info->scsi.sense_len;
730	ctsio->sense_residual = msg_info->scsi.sense_residual;
731	ctsio->residual = msg_info->scsi.residual;
732	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
733	       msg_info->scsi.sense_len);
734	ctl_enqueue_isc((union ctl_io *)ctsio);
735}
736
737static void
738ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
739				union ctl_ha_msg *msg_info)
740{
741	struct ctl_scsiio *ctsio;
742
743	if (msg_info->hdr.serializing_sc == NULL) {
744		printf("%s: serializing_sc == NULL!\n", __func__);
745		/* XXX KDM now what? */
746		return;
747	}
748
749	ctsio = &msg_info->hdr.serializing_sc->scsiio;
750	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
751	ctl_enqueue_isc((union ctl_io *)ctsio);
752}
753
754void
755ctl_isc_announce_lun(struct ctl_lun *lun)
756{
757	struct ctl_softc *softc = lun->ctl_softc;
758	union ctl_ha_msg *msg;
759	struct ctl_ha_msg_lun_pr_key pr_key;
760	int i, k;
761
762	if (softc->ha_link != CTL_HA_LINK_ONLINE)
763		return;
764	mtx_lock(&lun->lun_lock);
765	i = sizeof(msg->lun);
766	if (lun->lun_devid)
767		i += lun->lun_devid->len;
768	i += sizeof(pr_key) * lun->pr_key_count;
769alloc:
770	mtx_unlock(&lun->lun_lock);
771	msg = malloc(i, M_CTL, M_WAITOK);
772	mtx_lock(&lun->lun_lock);
773	k = sizeof(msg->lun);
774	if (lun->lun_devid)
775		k += lun->lun_devid->len;
776	k += sizeof(pr_key) * lun->pr_key_count;
777	if (i < k) {
778		free(msg, M_CTL);
779		i = k;
780		goto alloc;
781	}
782	bzero(&msg->lun, sizeof(msg->lun));
783	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
784	msg->hdr.nexus.targ_lun = lun->lun;
785	msg->hdr.nexus.targ_mapped_lun = lun->lun;
786	msg->lun.flags = lun->flags;
787	msg->lun.pr_generation = lun->pr_generation;
788	msg->lun.pr_res_idx = lun->pr_res_idx;
789	msg->lun.pr_res_type = lun->pr_res_type;
790	msg->lun.pr_key_count = lun->pr_key_count;
791	i = 0;
792	if (lun->lun_devid) {
793		msg->lun.lun_devid_len = lun->lun_devid->len;
794		memcpy(&msg->lun.data[i], lun->lun_devid->data,
795		    msg->lun.lun_devid_len);
796		i += msg->lun.lun_devid_len;
797	}
798	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
799		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
800			continue;
801		pr_key.pr_iid = k;
802		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
803		i += sizeof(pr_key);
804	}
805	mtx_unlock(&lun->lun_lock);
806	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
807	    M_WAITOK);
808	free(msg, M_CTL);
809
810	if (lun->flags & CTL_LUN_PRIMARY_SC) {
811		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
812			ctl_isc_announce_mode(lun, -1,
813			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
814			    lun->mode_pages.index[i].subpage);
815		}
816	}
817}
818
819void
820ctl_isc_announce_port(struct ctl_port *port)
821{
822	struct ctl_softc *softc = port->ctl_softc;
823	union ctl_ha_msg *msg;
824	int i;
825
826	if (port->targ_port < softc->port_min ||
827	    port->targ_port >= softc->port_max ||
828	    softc->ha_link != CTL_HA_LINK_ONLINE)
829		return;
830	i = sizeof(msg->port) + strlen(port->port_name) + 1;
831	if (port->lun_map)
832		i += port->lun_map_size * sizeof(uint32_t);
833	if (port->port_devid)
834		i += port->port_devid->len;
835	if (port->target_devid)
836		i += port->target_devid->len;
837	if (port->init_devid)
838		i += port->init_devid->len;
839	msg = malloc(i, M_CTL, M_WAITOK);
840	bzero(&msg->port, sizeof(msg->port));
841	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
842	msg->hdr.nexus.targ_port = port->targ_port;
843	msg->port.port_type = port->port_type;
844	msg->port.physical_port = port->physical_port;
845	msg->port.virtual_port = port->virtual_port;
846	msg->port.status = port->status;
847	i = 0;
848	msg->port.name_len = sprintf(&msg->port.data[i],
849	    "%d:%s", softc->ha_id, port->port_name) + 1;
850	i += msg->port.name_len;
851	if (port->lun_map) {
852		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
853		memcpy(&msg->port.data[i], port->lun_map,
854		    msg->port.lun_map_len);
855		i += msg->port.lun_map_len;
856	}
857	if (port->port_devid) {
858		msg->port.port_devid_len = port->port_devid->len;
859		memcpy(&msg->port.data[i], port->port_devid->data,
860		    msg->port.port_devid_len);
861		i += msg->port.port_devid_len;
862	}
863	if (port->target_devid) {
864		msg->port.target_devid_len = port->target_devid->len;
865		memcpy(&msg->port.data[i], port->target_devid->data,
866		    msg->port.target_devid_len);
867		i += msg->port.target_devid_len;
868	}
869	if (port->init_devid) {
870		msg->port.init_devid_len = port->init_devid->len;
871		memcpy(&msg->port.data[i], port->init_devid->data,
872		    msg->port.init_devid_len);
873		i += msg->port.init_devid_len;
874	}
875	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
876	    M_WAITOK);
877	free(msg, M_CTL);
878}
879
880void
881ctl_isc_announce_iid(struct ctl_port *port, int iid)
882{
883	struct ctl_softc *softc = port->ctl_softc;
884	union ctl_ha_msg *msg;
885	int i, l;
886
887	if (port->targ_port < softc->port_min ||
888	    port->targ_port >= softc->port_max ||
889	    softc->ha_link != CTL_HA_LINK_ONLINE)
890		return;
891	mtx_lock(&softc->ctl_lock);
892	i = sizeof(msg->iid);
893	l = 0;
894	if (port->wwpn_iid[iid].name)
895		l = strlen(port->wwpn_iid[iid].name) + 1;
896	i += l;
897	msg = malloc(i, M_CTL, M_NOWAIT);
898	if (msg == NULL) {
899		mtx_unlock(&softc->ctl_lock);
900		return;
901	}
902	bzero(&msg->iid, sizeof(msg->iid));
903	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
904	msg->hdr.nexus.targ_port = port->targ_port;
905	msg->hdr.nexus.initid = iid;
906	msg->iid.in_use = port->wwpn_iid[iid].in_use;
907	msg->iid.name_len = l;
908	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
909	if (port->wwpn_iid[iid].name)
910		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
911	mtx_unlock(&softc->ctl_lock);
912	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
913	free(msg, M_CTL);
914}
915
916void
917ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
918    uint8_t page, uint8_t subpage)
919{
920	struct ctl_softc *softc = lun->ctl_softc;
921	union ctl_ha_msg msg;
922	u_int i;
923
924	if (softc->ha_link != CTL_HA_LINK_ONLINE)
925		return;
926	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
927		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
928		    page && lun->mode_pages.index[i].subpage == subpage)
929			break;
930	}
931	if (i == CTL_NUM_MODE_PAGES)
932		return;
933
934	/* Don't try to replicate pages not present on this device. */
935	if (lun->mode_pages.index[i].page_data == NULL)
936		return;
937
938	bzero(&msg.mode, sizeof(msg.mode));
939	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
940	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
941	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
942	msg.hdr.nexus.targ_lun = lun->lun;
943	msg.hdr.nexus.targ_mapped_lun = lun->lun;
944	msg.mode.page_code = page;
945	msg.mode.subpage = subpage;
946	msg.mode.page_len = lun->mode_pages.index[i].page_len;
947	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
948	    msg.mode.page_len);
949	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
950	    M_WAITOK);
951}
952
953static void
954ctl_isc_ha_link_up(struct ctl_softc *softc)
955{
956	struct ctl_port *port;
957	struct ctl_lun *lun;
958	union ctl_ha_msg msg;
959	int i;
960
961	/* Announce this node parameters to peer for validation. */
962	msg.login.msg_type = CTL_MSG_LOGIN;
963	msg.login.version = CTL_HA_VERSION;
964	msg.login.ha_mode = softc->ha_mode;
965	msg.login.ha_id = softc->ha_id;
966	msg.login.max_luns = CTL_MAX_LUNS;
967	msg.login.max_ports = CTL_MAX_PORTS;
968	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
969	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
970	    M_WAITOK);
971
972	STAILQ_FOREACH(port, &softc->port_list, links) {
973		ctl_isc_announce_port(port);
974		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
975			if (port->wwpn_iid[i].in_use)
976				ctl_isc_announce_iid(port, i);
977		}
978	}
979	STAILQ_FOREACH(lun, &softc->lun_list, links)
980		ctl_isc_announce_lun(lun);
981}
982
983static void
984ctl_isc_ha_link_down(struct ctl_softc *softc)
985{
986	struct ctl_port *port;
987	struct ctl_lun *lun;
988	union ctl_io *io;
989	int i;
990
991	mtx_lock(&softc->ctl_lock);
992	STAILQ_FOREACH(lun, &softc->lun_list, links) {
993		mtx_lock(&lun->lun_lock);
994		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
995			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
996			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
997		}
998		mtx_unlock(&lun->lun_lock);
999
1000		mtx_unlock(&softc->ctl_lock);
1001		io = ctl_alloc_io(softc->othersc_pool);
1002		mtx_lock(&softc->ctl_lock);
1003		ctl_zero_io(io);
1004		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1005		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1006		ctl_enqueue_isc(io);
1007	}
1008
1009	STAILQ_FOREACH(port, &softc->port_list, links) {
1010		if (port->targ_port >= softc->port_min &&
1011		    port->targ_port < softc->port_max)
1012			continue;
1013		port->status &= ~CTL_PORT_STATUS_ONLINE;
1014		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1015			port->wwpn_iid[i].in_use = 0;
1016			free(port->wwpn_iid[i].name, M_CTL);
1017			port->wwpn_iid[i].name = NULL;
1018		}
1019	}
1020	mtx_unlock(&softc->ctl_lock);
1021}
1022
1023static void
1024ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1025{
1026	struct ctl_lun *lun;
1027	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1028
1029	mtx_lock(&softc->ctl_lock);
1030	if (msg->hdr.nexus.targ_mapped_lun >= CTL_MAX_LUNS ||
1031	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1032		mtx_unlock(&softc->ctl_lock);
1033		return;
1034	}
1035	mtx_lock(&lun->lun_lock);
1036	mtx_unlock(&softc->ctl_lock);
1037	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1038		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1039	if (msg->ua.ua_all) {
1040		if (msg->ua.ua_set)
1041			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1042		else
1043			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1044	} else {
1045		if (msg->ua.ua_set)
1046			ctl_est_ua(lun, iid, msg->ua.ua_type);
1047		else
1048			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1049	}
1050	mtx_unlock(&lun->lun_lock);
1051}
1052
1053static void
1054ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1055{
1056	struct ctl_lun *lun;
1057	struct ctl_ha_msg_lun_pr_key pr_key;
1058	int i, k;
1059	ctl_lun_flags oflags;
1060	uint32_t targ_lun;
1061
1062	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1063	mtx_lock(&softc->ctl_lock);
1064	if (targ_lun >= CTL_MAX_LUNS ||
1065	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1066		mtx_unlock(&softc->ctl_lock);
1067		return;
1068	}
1069	mtx_lock(&lun->lun_lock);
1070	mtx_unlock(&softc->ctl_lock);
1071	if (lun->flags & CTL_LUN_DISABLED) {
1072		mtx_unlock(&lun->lun_lock);
1073		return;
1074	}
1075	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1076	if (msg->lun.lun_devid_len != i || (i > 0 &&
1077	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1078		mtx_unlock(&lun->lun_lock);
1079		printf("%s: Received conflicting HA LUN %d\n",
1080		    __func__, targ_lun);
1081		return;
1082	} else {
1083		/* Record whether peer is primary. */
1084		oflags = lun->flags;
1085		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1086		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1087			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1088		else
1089			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1090		if (oflags != lun->flags)
1091			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1092
1093		/* If peer is primary and we are not -- use data */
1094		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1095		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1096			lun->pr_generation = msg->lun.pr_generation;
1097			lun->pr_res_idx = msg->lun.pr_res_idx;
1098			lun->pr_res_type = msg->lun.pr_res_type;
1099			lun->pr_key_count = msg->lun.pr_key_count;
1100			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1101				ctl_clr_prkey(lun, k);
1102			for (k = 0; k < msg->lun.pr_key_count; k++) {
1103				memcpy(&pr_key, &msg->lun.data[i],
1104				    sizeof(pr_key));
1105				ctl_alloc_prkey(lun, pr_key.pr_iid);
1106				ctl_set_prkey(lun, pr_key.pr_iid,
1107				    pr_key.pr_key);
1108				i += sizeof(pr_key);
1109			}
1110		}
1111
1112		mtx_unlock(&lun->lun_lock);
1113		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1114		    __func__, targ_lun,
1115		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1116		    "primary" : "secondary"));
1117
1118		/* If we are primary but peer doesn't know -- notify */
1119		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1120		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1121			ctl_isc_announce_lun(lun);
1122	}
1123}
1124
1125static void
1126ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1127{
1128	struct ctl_port *port;
1129	struct ctl_lun *lun;
1130	int i, new;
1131
1132	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1133	if (port == NULL) {
1134		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1135		    msg->hdr.nexus.targ_port));
1136		new = 1;
1137		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1138		port->frontend = &ha_frontend;
1139		port->targ_port = msg->hdr.nexus.targ_port;
1140		port->fe_datamove = ctl_ha_datamove;
1141		port->fe_done = ctl_ha_done;
1142	} else if (port->frontend == &ha_frontend) {
1143		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1144		    msg->hdr.nexus.targ_port));
1145		new = 0;
1146	} else {
1147		printf("%s: Received conflicting HA port %d\n",
1148		    __func__, msg->hdr.nexus.targ_port);
1149		return;
1150	}
1151	port->port_type = msg->port.port_type;
1152	port->physical_port = msg->port.physical_port;
1153	port->virtual_port = msg->port.virtual_port;
1154	port->status = msg->port.status;
1155	i = 0;
1156	free(port->port_name, M_CTL);
1157	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1158	    M_CTL);
1159	i += msg->port.name_len;
1160	if (msg->port.lun_map_len != 0) {
1161		if (port->lun_map == NULL ||
1162		    port->lun_map_size * sizeof(uint32_t) <
1163		    msg->port.lun_map_len) {
1164			port->lun_map_size = 0;
1165			free(port->lun_map, M_CTL);
1166			port->lun_map = malloc(msg->port.lun_map_len,
1167			    M_CTL, M_WAITOK);
1168		}
1169		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1170		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1171		i += msg->port.lun_map_len;
1172	} else {
1173		port->lun_map_size = 0;
1174		free(port->lun_map, M_CTL);
1175		port->lun_map = NULL;
1176	}
1177	if (msg->port.port_devid_len != 0) {
1178		if (port->port_devid == NULL ||
1179		    port->port_devid->len < msg->port.port_devid_len) {
1180			free(port->port_devid, M_CTL);
1181			port->port_devid = malloc(sizeof(struct ctl_devid) +
1182			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1183		}
1184		memcpy(port->port_devid->data, &msg->port.data[i],
1185		    msg->port.port_devid_len);
1186		port->port_devid->len = msg->port.port_devid_len;
1187		i += msg->port.port_devid_len;
1188	} else {
1189		free(port->port_devid, M_CTL);
1190		port->port_devid = NULL;
1191	}
1192	if (msg->port.target_devid_len != 0) {
1193		if (port->target_devid == NULL ||
1194		    port->target_devid->len < msg->port.target_devid_len) {
1195			free(port->target_devid, M_CTL);
1196			port->target_devid = malloc(sizeof(struct ctl_devid) +
1197			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1198		}
1199		memcpy(port->target_devid->data, &msg->port.data[i],
1200		    msg->port.target_devid_len);
1201		port->target_devid->len = msg->port.target_devid_len;
1202		i += msg->port.target_devid_len;
1203	} else {
1204		free(port->target_devid, M_CTL);
1205		port->target_devid = NULL;
1206	}
1207	if (msg->port.init_devid_len != 0) {
1208		if (port->init_devid == NULL ||
1209		    port->init_devid->len < msg->port.init_devid_len) {
1210			free(port->init_devid, M_CTL);
1211			port->init_devid = malloc(sizeof(struct ctl_devid) +
1212			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1213		}
1214		memcpy(port->init_devid->data, &msg->port.data[i],
1215		    msg->port.init_devid_len);
1216		port->init_devid->len = msg->port.init_devid_len;
1217		i += msg->port.init_devid_len;
1218	} else {
1219		free(port->init_devid, M_CTL);
1220		port->init_devid = NULL;
1221	}
1222	if (new) {
1223		if (ctl_port_register(port) != 0) {
1224			printf("%s: ctl_port_register() failed with error\n",
1225			    __func__);
1226		}
1227	}
1228	mtx_lock(&softc->ctl_lock);
1229	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1230		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1231			continue;
1232		mtx_lock(&lun->lun_lock);
1233		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1234		mtx_unlock(&lun->lun_lock);
1235	}
1236	mtx_unlock(&softc->ctl_lock);
1237}
1238
1239static void
1240ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1241{
1242	struct ctl_port *port;
1243	int iid;
1244
1245	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1246	if (port == NULL) {
1247		printf("%s: Received IID for unknown port %d\n",
1248		    __func__, msg->hdr.nexus.targ_port);
1249		return;
1250	}
1251	iid = msg->hdr.nexus.initid;
1252	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1253	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1254	free(port->wwpn_iid[iid].name, M_CTL);
1255	if (msg->iid.name_len) {
1256		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1257		    msg->iid.name_len, M_CTL);
1258	} else
1259		port->wwpn_iid[iid].name = NULL;
1260}
1261
1262static void
1263ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1264{
1265
1266	if (msg->login.version != CTL_HA_VERSION) {
1267		printf("CTL HA peers have different versions %d != %d\n",
1268		    msg->login.version, CTL_HA_VERSION);
1269		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1270		return;
1271	}
1272	if (msg->login.ha_mode != softc->ha_mode) {
1273		printf("CTL HA peers have different ha_mode %d != %d\n",
1274		    msg->login.ha_mode, softc->ha_mode);
1275		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1276		return;
1277	}
1278	if (msg->login.ha_id == softc->ha_id) {
1279		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1280		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1281		return;
1282	}
1283	if (msg->login.max_luns != CTL_MAX_LUNS ||
1284	    msg->login.max_ports != CTL_MAX_PORTS ||
1285	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1286		printf("CTL HA peers have different limits\n");
1287		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1288		return;
1289	}
1290}
1291
1292static void
1293ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1294{
1295	struct ctl_lun *lun;
1296	u_int i;
1297	uint32_t initidx, targ_lun;
1298
1299	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1300	mtx_lock(&softc->ctl_lock);
1301	if (targ_lun >= CTL_MAX_LUNS ||
1302	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1303		mtx_unlock(&softc->ctl_lock);
1304		return;
1305	}
1306	mtx_lock(&lun->lun_lock);
1307	mtx_unlock(&softc->ctl_lock);
1308	if (lun->flags & CTL_LUN_DISABLED) {
1309		mtx_unlock(&lun->lun_lock);
1310		return;
1311	}
1312	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1313		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1314		    msg->mode.page_code &&
1315		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1316			break;
1317	}
1318	if (i == CTL_NUM_MODE_PAGES) {
1319		mtx_unlock(&lun->lun_lock);
1320		return;
1321	}
1322	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1323	    lun->mode_pages.index[i].page_len);
1324	initidx = ctl_get_initindex(&msg->hdr.nexus);
1325	if (initidx != -1)
1326		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1327	mtx_unlock(&lun->lun_lock);
1328}
1329
1330/*
1331 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1332 * subsystem come in here.
1333 */
1334static void
1335ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1336{
1337	struct ctl_softc *softc = control_softc;
1338	union ctl_io *io;
1339	struct ctl_prio *presio;
1340	ctl_ha_status isc_status;
1341
1342	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1343	if (event == CTL_HA_EVT_MSG_RECV) {
1344		union ctl_ha_msg *msg, msgbuf;
1345
1346		if (param > sizeof(msgbuf))
1347			msg = malloc(param, M_CTL, M_WAITOK);
1348		else
1349			msg = &msgbuf;
1350		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1351		    M_WAITOK);
1352		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1353			printf("%s: Error receiving message: %d\n",
1354			    __func__, isc_status);
1355			if (msg != &msgbuf)
1356				free(msg, M_CTL);
1357			return;
1358		}
1359
1360		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1361		switch (msg->hdr.msg_type) {
1362		case CTL_MSG_SERIALIZE:
1363			io = ctl_alloc_io(softc->othersc_pool);
1364			ctl_zero_io(io);
1365			// populate ctsio from msg
1366			io->io_hdr.io_type = CTL_IO_SCSI;
1367			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1368			io->io_hdr.original_sc = msg->hdr.original_sc;
1369			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1370					    CTL_FLAG_IO_ACTIVE;
1371			/*
1372			 * If we're in serialization-only mode, we don't
1373			 * want to go through full done processing.  Thus
1374			 * the COPY flag.
1375			 *
1376			 * XXX KDM add another flag that is more specific.
1377			 */
1378			if (softc->ha_mode != CTL_HA_MODE_XFER)
1379				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1380			io->io_hdr.nexus = msg->hdr.nexus;
1381#if 0
1382			printf("port %u, iid %u, lun %u\n",
1383			       io->io_hdr.nexus.targ_port,
1384			       io->io_hdr.nexus.initid,
1385			       io->io_hdr.nexus.targ_lun);
1386#endif
1387			io->scsiio.tag_num = msg->scsi.tag_num;
1388			io->scsiio.tag_type = msg->scsi.tag_type;
1389#ifdef CTL_TIME_IO
1390			io->io_hdr.start_time = time_uptime;
1391			getbinuptime(&io->io_hdr.start_bt);
1392#endif /* CTL_TIME_IO */
1393			io->scsiio.cdb_len = msg->scsi.cdb_len;
1394			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1395			       CTL_MAX_CDBLEN);
1396			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1397				const struct ctl_cmd_entry *entry;
1398
1399				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1400				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1401				io->io_hdr.flags |=
1402					entry->flags & CTL_FLAG_DATA_MASK;
1403			}
1404			ctl_enqueue_isc(io);
1405			break;
1406
1407		/* Performed on the Originating SC, XFER mode only */
1408		case CTL_MSG_DATAMOVE: {
1409			struct ctl_sg_entry *sgl;
1410			int i, j;
1411
1412			io = msg->hdr.original_sc;
1413			if (io == NULL) {
1414				printf("%s: original_sc == NULL!\n", __func__);
1415				/* XXX KDM do something here */
1416				break;
1417			}
1418			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1419			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1420			/*
1421			 * Keep track of this, we need to send it back over
1422			 * when the datamove is complete.
1423			 */
1424			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1425			if (msg->hdr.status == CTL_SUCCESS)
1426				io->io_hdr.status = msg->hdr.status;
1427
1428			if (msg->dt.sg_sequence == 0) {
1429#ifdef CTL_TIME_IO
1430				getbinuptime(&io->io_hdr.dma_start_bt);
1431#endif
1432				i = msg->dt.kern_sg_entries +
1433				    msg->dt.kern_data_len /
1434				    CTL_HA_DATAMOVE_SEGMENT + 1;
1435				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1436				    M_WAITOK | M_ZERO);
1437				io->io_hdr.remote_sglist = sgl;
1438				io->io_hdr.local_sglist =
1439				    &sgl[msg->dt.kern_sg_entries];
1440
1441				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1442
1443				io->scsiio.kern_sg_entries =
1444					msg->dt.kern_sg_entries;
1445				io->scsiio.rem_sg_entries =
1446					msg->dt.kern_sg_entries;
1447				io->scsiio.kern_data_len =
1448					msg->dt.kern_data_len;
1449				io->scsiio.kern_total_len =
1450					msg->dt.kern_total_len;
1451				io->scsiio.kern_data_resid =
1452					msg->dt.kern_data_resid;
1453				io->scsiio.kern_rel_offset =
1454					msg->dt.kern_rel_offset;
1455				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1456				io->io_hdr.flags |= msg->dt.flags &
1457				    CTL_FLAG_BUS_ADDR;
1458			} else
1459				sgl = (struct ctl_sg_entry *)
1460					io->scsiio.kern_data_ptr;
1461
1462			for (i = msg->dt.sent_sg_entries, j = 0;
1463			     i < (msg->dt.sent_sg_entries +
1464			     msg->dt.cur_sg_entries); i++, j++) {
1465				sgl[i].addr = msg->dt.sg_list[j].addr;
1466				sgl[i].len = msg->dt.sg_list[j].len;
1467
1468#if 0
1469				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1470				    __func__, sgl[i].addr, sgl[i].len, j, i);
1471#endif
1472			}
1473
1474			/*
1475			 * If this is the last piece of the I/O, we've got
1476			 * the full S/G list.  Queue processing in the thread.
1477			 * Otherwise wait for the next piece.
1478			 */
1479			if (msg->dt.sg_last != 0)
1480				ctl_enqueue_isc(io);
1481			break;
1482		}
1483		/* Performed on the Serializing (primary) SC, XFER mode only */
1484		case CTL_MSG_DATAMOVE_DONE: {
1485			if (msg->hdr.serializing_sc == NULL) {
1486				printf("%s: serializing_sc == NULL!\n",
1487				       __func__);
1488				/* XXX KDM now what? */
1489				break;
1490			}
1491			/*
1492			 * We grab the sense information here in case
1493			 * there was a failure, so we can return status
1494			 * back to the initiator.
1495			 */
1496			io = msg->hdr.serializing_sc;
1497			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1498			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1499			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1500			io->io_hdr.port_status = msg->scsi.fetd_status;
1501			io->scsiio.residual = msg->scsi.residual;
1502			if (msg->hdr.status != CTL_STATUS_NONE) {
1503				io->io_hdr.status = msg->hdr.status;
1504				io->scsiio.scsi_status = msg->scsi.scsi_status;
1505				io->scsiio.sense_len = msg->scsi.sense_len;
1506				io->scsiio.sense_residual =msg->scsi.sense_residual;
1507				memcpy(&io->scsiio.sense_data,
1508				    &msg->scsi.sense_data,
1509				    msg->scsi.sense_len);
1510				if (msg->hdr.status == CTL_SUCCESS)
1511					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1512			}
1513			ctl_enqueue_isc(io);
1514			break;
1515		}
1516
1517		/* Preformed on Originating SC, SER_ONLY mode */
1518		case CTL_MSG_R2R:
1519			io = msg->hdr.original_sc;
1520			if (io == NULL) {
1521				printf("%s: original_sc == NULL!\n",
1522				    __func__);
1523				break;
1524			}
1525			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1526			io->io_hdr.msg_type = CTL_MSG_R2R;
1527			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1528			ctl_enqueue_isc(io);
1529			break;
1530
1531		/*
1532		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1533		 * mode.
1534		 * Performed on the Originating (i.e. secondary) SC in XFER
1535		 * mode
1536		 */
1537		case CTL_MSG_FINISH_IO:
1538			if (softc->ha_mode == CTL_HA_MODE_XFER)
1539				ctl_isc_handler_finish_xfer(softc, msg);
1540			else
1541				ctl_isc_handler_finish_ser_only(softc, msg);
1542			break;
1543
1544		/* Preformed on Originating SC */
1545		case CTL_MSG_BAD_JUJU:
1546			io = msg->hdr.original_sc;
1547			if (io == NULL) {
1548				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1549				       __func__);
1550				break;
1551			}
1552			ctl_copy_sense_data(msg, io);
1553			/*
1554			 * IO should have already been cleaned up on other
1555			 * SC so clear this flag so we won't send a message
1556			 * back to finish the IO there.
1557			 */
1558			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1559			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1560
1561			/* io = msg->hdr.serializing_sc; */
1562			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1563			ctl_enqueue_isc(io);
1564			break;
1565
1566		/* Handle resets sent from the other side */
1567		case CTL_MSG_MANAGE_TASKS: {
1568			struct ctl_taskio *taskio;
1569			taskio = (struct ctl_taskio *)ctl_alloc_io(
1570			    softc->othersc_pool);
1571			ctl_zero_io((union ctl_io *)taskio);
1572			taskio->io_hdr.io_type = CTL_IO_TASK;
1573			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1574			taskio->io_hdr.nexus = msg->hdr.nexus;
1575			taskio->task_action = msg->task.task_action;
1576			taskio->tag_num = msg->task.tag_num;
1577			taskio->tag_type = msg->task.tag_type;
1578#ifdef CTL_TIME_IO
1579			taskio->io_hdr.start_time = time_uptime;
1580			getbinuptime(&taskio->io_hdr.start_bt);
1581#endif /* CTL_TIME_IO */
1582			ctl_run_task((union ctl_io *)taskio);
1583			break;
1584		}
1585		/* Persistent Reserve action which needs attention */
1586		case CTL_MSG_PERS_ACTION:
1587			presio = (struct ctl_prio *)ctl_alloc_io(
1588			    softc->othersc_pool);
1589			ctl_zero_io((union ctl_io *)presio);
1590			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1591			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1592			presio->io_hdr.nexus = msg->hdr.nexus;
1593			presio->pr_msg = msg->pr;
1594			ctl_enqueue_isc((union ctl_io *)presio);
1595			break;
1596		case CTL_MSG_UA:
1597			ctl_isc_ua(softc, msg, param);
1598			break;
1599		case CTL_MSG_PORT_SYNC:
1600			ctl_isc_port_sync(softc, msg, param);
1601			break;
1602		case CTL_MSG_LUN_SYNC:
1603			ctl_isc_lun_sync(softc, msg, param);
1604			break;
1605		case CTL_MSG_IID_SYNC:
1606			ctl_isc_iid_sync(softc, msg, param);
1607			break;
1608		case CTL_MSG_LOGIN:
1609			ctl_isc_login(softc, msg, param);
1610			break;
1611		case CTL_MSG_MODE_SYNC:
1612			ctl_isc_mode_sync(softc, msg, param);
1613			break;
1614		default:
1615			printf("Received HA message of unknown type %d\n",
1616			    msg->hdr.msg_type);
1617			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1618			break;
1619		}
1620		if (msg != &msgbuf)
1621			free(msg, M_CTL);
1622	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1623		printf("CTL: HA link status changed from %d to %d\n",
1624		    softc->ha_link, param);
1625		if (param == softc->ha_link)
1626			return;
1627		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1628			softc->ha_link = param;
1629			ctl_isc_ha_link_down(softc);
1630		} else {
1631			softc->ha_link = param;
1632			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1633				ctl_isc_ha_link_up(softc);
1634		}
1635		return;
1636	} else {
1637		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1638		return;
1639	}
1640}
1641
1642static void
1643ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1644{
1645
1646	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1647	    src->scsi.sense_len);
1648	dest->scsiio.scsi_status = src->scsi.scsi_status;
1649	dest->scsiio.sense_len = src->scsi.sense_len;
1650	dest->io_hdr.status = src->hdr.status;
1651}
1652
1653static void
1654ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1655{
1656
1657	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1658	    src->scsiio.sense_len);
1659	dest->scsi.scsi_status = src->scsiio.scsi_status;
1660	dest->scsi.sense_len = src->scsiio.sense_len;
1661	dest->hdr.status = src->io_hdr.status;
1662}
1663
1664void
1665ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1666{
1667	struct ctl_softc *softc = lun->ctl_softc;
1668	ctl_ua_type *pu;
1669
1670	if (initidx < softc->init_min || initidx >= softc->init_max)
1671		return;
1672	mtx_assert(&lun->lun_lock, MA_OWNED);
1673	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1674	if (pu == NULL)
1675		return;
1676	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1677}
1678
1679void
1680ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1681{
1682	int i;
1683
1684	mtx_assert(&lun->lun_lock, MA_OWNED);
1685	if (lun->pending_ua[port] == NULL)
1686		return;
1687	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1688		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1689			continue;
1690		lun->pending_ua[port][i] |= ua;
1691	}
1692}
1693
1694void
1695ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1696{
1697	struct ctl_softc *softc = lun->ctl_softc;
1698	int i;
1699
1700	mtx_assert(&lun->lun_lock, MA_OWNED);
1701	for (i = softc->port_min; i < softc->port_max; i++)
1702		ctl_est_ua_port(lun, i, except, ua);
1703}
1704
1705void
1706ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1707{
1708	struct ctl_softc *softc = lun->ctl_softc;
1709	ctl_ua_type *pu;
1710
1711	if (initidx < softc->init_min || initidx >= softc->init_max)
1712		return;
1713	mtx_assert(&lun->lun_lock, MA_OWNED);
1714	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1715	if (pu == NULL)
1716		return;
1717	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1718}
1719
1720void
1721ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1722{
1723	struct ctl_softc *softc = lun->ctl_softc;
1724	int i, j;
1725
1726	mtx_assert(&lun->lun_lock, MA_OWNED);
1727	for (i = softc->port_min; i < softc->port_max; i++) {
1728		if (lun->pending_ua[i] == NULL)
1729			continue;
1730		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1731			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1732				continue;
1733			lun->pending_ua[i][j] &= ~ua;
1734		}
1735	}
1736}
1737
1738void
1739ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1740    ctl_ua_type ua_type)
1741{
1742	struct ctl_lun *lun;
1743
1744	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1745	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1746		mtx_lock(&lun->lun_lock);
1747		ctl_clr_ua(lun, initidx, ua_type);
1748		mtx_unlock(&lun->lun_lock);
1749	}
1750}
1751
1752static int
1753ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1754{
1755	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1756	struct ctl_lun *lun;
1757	struct ctl_lun_req ireq;
1758	int error, value;
1759
1760	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1761	error = sysctl_handle_int(oidp, &value, 0, req);
1762	if ((error != 0) || (req->newptr == NULL))
1763		return (error);
1764
1765	mtx_lock(&softc->ctl_lock);
1766	if (value == 0)
1767		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1768	else
1769		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1770	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1771		mtx_unlock(&softc->ctl_lock);
1772		bzero(&ireq, sizeof(ireq));
1773		ireq.reqtype = CTL_LUNREQ_MODIFY;
1774		ireq.reqdata.modify.lun_id = lun->lun;
1775		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1776		    curthread);
1777		if (ireq.status != CTL_LUN_OK) {
1778			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1779			    __func__, ireq.status, ireq.error_str);
1780		}
1781		mtx_lock(&softc->ctl_lock);
1782	}
1783	mtx_unlock(&softc->ctl_lock);
1784	return (0);
1785}
1786
1787static int
1788ctl_init(void)
1789{
1790	struct make_dev_args args;
1791	struct ctl_softc *softc;
1792	void *other_pool;
1793	int i, error;
1794
1795	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1796			       M_WAITOK | M_ZERO);
1797
1798	make_dev_args_init(&args);
1799	args.mda_devsw = &ctl_cdevsw;
1800	args.mda_uid = UID_ROOT;
1801	args.mda_gid = GID_OPERATOR;
1802	args.mda_mode = 0600;
1803	args.mda_si_drv1 = softc;
1804	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1805	if (error != 0) {
1806		free(softc, M_DEVBUF);
1807		control_softc = NULL;
1808		return (error);
1809	}
1810
1811	sysctl_ctx_init(&softc->sysctl_ctx);
1812	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1813		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1814		CTLFLAG_RD, 0, "CAM Target Layer");
1815
1816	if (softc->sysctl_tree == NULL) {
1817		printf("%s: unable to allocate sysctl tree\n", __func__);
1818		destroy_dev(softc->dev);
1819		free(softc, M_DEVBUF);
1820		control_softc = NULL;
1821		return (ENOMEM);
1822	}
1823
1824	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1825	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1826	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1827	softc->flags = 0;
1828
1829	TUNABLE_INT_FETCH("kern.cam.ctl.ha_mode", (int *)&softc->ha_mode);
1830	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1831	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1832	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1833
1834	/*
1835	 * In Copan's HA scheme, the "master" and "slave" roles are
1836	 * figured out through the slot the controller is in.  Although it
1837	 * is an active/active system, someone has to be in charge.
1838	 */
1839	TUNABLE_INT_FETCH("kern.cam.ctl.ha_id", &softc->ha_id);
1840	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1841	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1842	    "HA head ID (0 - no HA)");
1843	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1844		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1845		softc->is_single = 1;
1846		softc->port_cnt = CTL_MAX_PORTS;
1847		softc->port_min = 0;
1848	} else {
1849		softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1850		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1851	}
1852	softc->port_max = softc->port_min + softc->port_cnt;
1853	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1854	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1855
1856	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1857	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1858	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1859
1860	STAILQ_INIT(&softc->lun_list);
1861	STAILQ_INIT(&softc->pending_lun_queue);
1862	STAILQ_INIT(&softc->fe_list);
1863	STAILQ_INIT(&softc->port_list);
1864	STAILQ_INIT(&softc->be_list);
1865	ctl_tpc_init(softc);
1866
1867	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1868	                    &other_pool) != 0)
1869	{
1870		printf("ctl: can't allocate %d entry other SC pool, "
1871		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1872		return (ENOMEM);
1873	}
1874	softc->othersc_pool = other_pool;
1875
1876	if (worker_threads <= 0)
1877		worker_threads = max(1, mp_ncpus / 4);
1878	if (worker_threads > CTL_MAX_THREADS)
1879		worker_threads = CTL_MAX_THREADS;
1880
1881	for (i = 0; i < worker_threads; i++) {
1882		struct ctl_thread *thr = &softc->threads[i];
1883
1884		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1885		thr->ctl_softc = softc;
1886		STAILQ_INIT(&thr->incoming_queue);
1887		STAILQ_INIT(&thr->rtr_queue);
1888		STAILQ_INIT(&thr->done_queue);
1889		STAILQ_INIT(&thr->isc_queue);
1890
1891		error = kproc_kthread_add(ctl_work_thread, thr,
1892		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1893		if (error != 0) {
1894			printf("error creating CTL work thread!\n");
1895			ctl_pool_free(other_pool);
1896			return (error);
1897		}
1898	}
1899	error = kproc_kthread_add(ctl_lun_thread, softc,
1900	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1901	if (error != 0) {
1902		printf("error creating CTL lun thread!\n");
1903		ctl_pool_free(other_pool);
1904		return (error);
1905	}
1906	error = kproc_kthread_add(ctl_thresh_thread, softc,
1907	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1908	if (error != 0) {
1909		printf("error creating CTL threshold thread!\n");
1910		ctl_pool_free(other_pool);
1911		return (error);
1912	}
1913
1914	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1915	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1916	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1917
1918	if (softc->is_single == 0) {
1919		ctl_frontend_register(&ha_frontend);
1920		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1921			printf("ctl_init: ctl_ha_msg_init failed.\n");
1922			softc->is_single = 1;
1923		} else
1924		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1925		    != CTL_HA_STATUS_SUCCESS) {
1926			printf("ctl_init: ctl_ha_msg_register failed.\n");
1927			softc->is_single = 1;
1928		}
1929	}
1930	return (0);
1931}
1932
1933void
1934ctl_shutdown(void)
1935{
1936	struct ctl_softc *softc = control_softc;
1937	struct ctl_lun *lun, *next_lun;
1938
1939	if (softc->is_single == 0) {
1940		ctl_ha_msg_shutdown(softc);
1941		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1942		    != CTL_HA_STATUS_SUCCESS)
1943			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1944		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1945			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1946		ctl_frontend_deregister(&ha_frontend);
1947	}
1948
1949	mtx_lock(&softc->ctl_lock);
1950
1951	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1952		ctl_free_lun(lun);
1953
1954	mtx_unlock(&softc->ctl_lock);
1955
1956#if 0
1957	ctl_shutdown_thread(softc->work_thread);
1958	mtx_destroy(&softc->queue_lock);
1959#endif
1960
1961	ctl_tpc_shutdown(softc);
1962	uma_zdestroy(softc->io_zone);
1963	mtx_destroy(&softc->ctl_lock);
1964
1965	destroy_dev(softc->dev);
1966
1967	sysctl_ctx_free(&softc->sysctl_ctx);
1968
1969	free(softc, M_DEVBUF);
1970	control_softc = NULL;
1971}
1972
1973static int
1974ctl_module_event_handler(module_t mod, int what, void *arg)
1975{
1976
1977	switch (what) {
1978	case MOD_LOAD:
1979		return (ctl_init());
1980	case MOD_UNLOAD:
1981		return (EBUSY);
1982	default:
1983		return (EOPNOTSUPP);
1984	}
1985}
1986
1987/*
1988 * XXX KDM should we do some access checks here?  Bump a reference count to
1989 * prevent a CTL module from being unloaded while someone has it open?
1990 */
1991static int
1992ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1993{
1994	return (0);
1995}
1996
1997static int
1998ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1999{
2000	return (0);
2001}
2002
2003/*
2004 * Remove an initiator by port number and initiator ID.
2005 * Returns 0 for success, -1 for failure.
2006 */
2007int
2008ctl_remove_initiator(struct ctl_port *port, int iid)
2009{
2010	struct ctl_softc *softc = port->ctl_softc;
2011
2012	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2013
2014	if (iid > CTL_MAX_INIT_PER_PORT) {
2015		printf("%s: initiator ID %u > maximun %u!\n",
2016		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2017		return (-1);
2018	}
2019
2020	mtx_lock(&softc->ctl_lock);
2021	port->wwpn_iid[iid].in_use--;
2022	port->wwpn_iid[iid].last_use = time_uptime;
2023	mtx_unlock(&softc->ctl_lock);
2024	ctl_isc_announce_iid(port, iid);
2025
2026	return (0);
2027}
2028
2029/*
2030 * Add an initiator to the initiator map.
2031 * Returns iid for success, < 0 for failure.
2032 */
2033int
2034ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2035{
2036	struct ctl_softc *softc = port->ctl_softc;
2037	time_t best_time;
2038	int i, best;
2039
2040	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2041
2042	if (iid >= CTL_MAX_INIT_PER_PORT) {
2043		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2044		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2045		free(name, M_CTL);
2046		return (-1);
2047	}
2048
2049	mtx_lock(&softc->ctl_lock);
2050
2051	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2052		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2053			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2054				iid = i;
2055				break;
2056			}
2057			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2058			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2059				iid = i;
2060				break;
2061			}
2062		}
2063	}
2064
2065	if (iid < 0) {
2066		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2067			if (port->wwpn_iid[i].in_use == 0 &&
2068			    port->wwpn_iid[i].wwpn == 0 &&
2069			    port->wwpn_iid[i].name == NULL) {
2070				iid = i;
2071				break;
2072			}
2073		}
2074	}
2075
2076	if (iid < 0) {
2077		best = -1;
2078		best_time = INT32_MAX;
2079		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2080			if (port->wwpn_iid[i].in_use == 0) {
2081				if (port->wwpn_iid[i].last_use < best_time) {
2082					best = i;
2083					best_time = port->wwpn_iid[i].last_use;
2084				}
2085			}
2086		}
2087		iid = best;
2088	}
2089
2090	if (iid < 0) {
2091		mtx_unlock(&softc->ctl_lock);
2092		free(name, M_CTL);
2093		return (-2);
2094	}
2095
2096	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2097		/*
2098		 * This is not an error yet.
2099		 */
2100		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2101#if 0
2102			printf("%s: port %d iid %u WWPN %#jx arrived"
2103			    " again\n", __func__, port->targ_port,
2104			    iid, (uintmax_t)wwpn);
2105#endif
2106			goto take;
2107		}
2108		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2109		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2110#if 0
2111			printf("%s: port %d iid %u name '%s' arrived"
2112			    " again\n", __func__, port->targ_port,
2113			    iid, name);
2114#endif
2115			goto take;
2116		}
2117
2118		/*
2119		 * This is an error, but what do we do about it?  The
2120		 * driver is telling us we have a new WWPN for this
2121		 * initiator ID, so we pretty much need to use it.
2122		 */
2123		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2124		    " but WWPN %#jx '%s' is still at that address\n",
2125		    __func__, port->targ_port, iid, wwpn, name,
2126		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2127		    port->wwpn_iid[iid].name);
2128
2129		/*
2130		 * XXX KDM clear have_ca and ua_pending on each LUN for
2131		 * this initiator.
2132		 */
2133	}
2134take:
2135	free(port->wwpn_iid[iid].name, M_CTL);
2136	port->wwpn_iid[iid].name = name;
2137	port->wwpn_iid[iid].wwpn = wwpn;
2138	port->wwpn_iid[iid].in_use++;
2139	mtx_unlock(&softc->ctl_lock);
2140	ctl_isc_announce_iid(port, iid);
2141
2142	return (iid);
2143}
2144
2145static int
2146ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2147{
2148	int len;
2149
2150	switch (port->port_type) {
2151	case CTL_PORT_FC:
2152	{
2153		struct scsi_transportid_fcp *id =
2154		    (struct scsi_transportid_fcp *)buf;
2155		if (port->wwpn_iid[iid].wwpn == 0)
2156			return (0);
2157		memset(id, 0, sizeof(*id));
2158		id->format_protocol = SCSI_PROTO_FC;
2159		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2160		return (sizeof(*id));
2161	}
2162	case CTL_PORT_ISCSI:
2163	{
2164		struct scsi_transportid_iscsi_port *id =
2165		    (struct scsi_transportid_iscsi_port *)buf;
2166		if (port->wwpn_iid[iid].name == NULL)
2167			return (0);
2168		memset(id, 0, 256);
2169		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2170		    SCSI_PROTO_ISCSI;
2171		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2172		len = roundup2(min(len, 252), 4);
2173		scsi_ulto2b(len, id->additional_length);
2174		return (sizeof(*id) + len);
2175	}
2176	case CTL_PORT_SAS:
2177	{
2178		struct scsi_transportid_sas *id =
2179		    (struct scsi_transportid_sas *)buf;
2180		if (port->wwpn_iid[iid].wwpn == 0)
2181			return (0);
2182		memset(id, 0, sizeof(*id));
2183		id->format_protocol = SCSI_PROTO_SAS;
2184		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2185		return (sizeof(*id));
2186	}
2187	default:
2188	{
2189		struct scsi_transportid_spi *id =
2190		    (struct scsi_transportid_spi *)buf;
2191		memset(id, 0, sizeof(*id));
2192		id->format_protocol = SCSI_PROTO_SPI;
2193		scsi_ulto2b(iid, id->scsi_addr);
2194		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2195		return (sizeof(*id));
2196	}
2197	}
2198}
2199
2200/*
2201 * Serialize a command that went down the "wrong" side, and so was sent to
2202 * this controller for execution.  The logic is a little different than the
2203 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2204 * sent back to the other side, but in the success case, we execute the
2205 * command on this side (XFER mode) or tell the other side to execute it
2206 * (SER_ONLY mode).
2207 */
2208static void
2209ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2210{
2211	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2212	struct ctl_port *port = CTL_PORT(ctsio);
2213	union ctl_ha_msg msg_info;
2214	struct ctl_lun *lun;
2215	const struct ctl_cmd_entry *entry;
2216	uint32_t targ_lun;
2217
2218	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2219
2220	/* Make sure that we know about this port. */
2221	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2222		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2223					 /*retry_count*/ 1);
2224		goto badjuju;
2225	}
2226
2227	/* Make sure that we know about this LUN. */
2228	mtx_lock(&softc->ctl_lock);
2229	if (targ_lun >= CTL_MAX_LUNS ||
2230	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2231		mtx_unlock(&softc->ctl_lock);
2232
2233		/*
2234		 * The other node would not send this request to us unless
2235		 * received announce that we are primary node for this LUN.
2236		 * If this LUN does not exist now, it is probably result of
2237		 * a race, so respond to initiator in the most opaque way.
2238		 */
2239		ctl_set_busy(ctsio);
2240		goto badjuju;
2241	}
2242	mtx_lock(&lun->lun_lock);
2243	mtx_unlock(&softc->ctl_lock);
2244
2245	/*
2246	 * If the LUN is invalid, pretend that it doesn't exist.
2247	 * It will go away as soon as all pending I/Os completed.
2248	 */
2249	if (lun->flags & CTL_LUN_DISABLED) {
2250		mtx_unlock(&lun->lun_lock);
2251		ctl_set_busy(ctsio);
2252		goto badjuju;
2253	}
2254
2255	entry = ctl_get_cmd_entry(ctsio, NULL);
2256	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2257		mtx_unlock(&lun->lun_lock);
2258		goto badjuju;
2259	}
2260
2261	CTL_LUN(ctsio) = lun;
2262	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2263
2264	/*
2265	 * Every I/O goes into the OOA queue for a
2266	 * particular LUN, and stays there until completion.
2267	 */
2268#ifdef CTL_TIME_IO
2269	if (TAILQ_EMPTY(&lun->ooa_queue))
2270		lun->idle_time += getsbinuptime() - lun->last_busy;
2271#endif
2272	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2273
2274	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2275		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2276		 ooa_links))) {
2277	case CTL_ACTION_BLOCK:
2278		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2279		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2280				  blocked_links);
2281		mtx_unlock(&lun->lun_lock);
2282		break;
2283	case CTL_ACTION_PASS:
2284	case CTL_ACTION_SKIP:
2285		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2286			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2287			ctl_enqueue_rtr((union ctl_io *)ctsio);
2288			mtx_unlock(&lun->lun_lock);
2289		} else {
2290			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2291			mtx_unlock(&lun->lun_lock);
2292
2293			/* send msg back to other side */
2294			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2295			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2296			msg_info.hdr.msg_type = CTL_MSG_R2R;
2297			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2298			    sizeof(msg_info.hdr), M_WAITOK);
2299		}
2300		break;
2301	case CTL_ACTION_OVERLAP:
2302		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2303		mtx_unlock(&lun->lun_lock);
2304		ctl_set_overlapped_cmd(ctsio);
2305		goto badjuju;
2306	case CTL_ACTION_OVERLAP_TAG:
2307		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2308		mtx_unlock(&lun->lun_lock);
2309		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2310		goto badjuju;
2311	case CTL_ACTION_ERROR:
2312	default:
2313		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2314		mtx_unlock(&lun->lun_lock);
2315
2316		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2317					 /*retry_count*/ 0);
2318badjuju:
2319		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2320		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2321		msg_info.hdr.serializing_sc = NULL;
2322		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2323		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2324		    sizeof(msg_info.scsi), M_WAITOK);
2325		ctl_free_io((union ctl_io *)ctsio);
2326		break;
2327	}
2328}
2329
2330/*
2331 * Returns 0 for success, errno for failure.
2332 */
2333static void
2334ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2335		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2336{
2337	union ctl_io *io;
2338
2339	mtx_lock(&lun->lun_lock);
2340	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2341	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2342	     ooa_links)) {
2343		struct ctl_ooa_entry *entry;
2344
2345		/*
2346		 * If we've got more than we can fit, just count the
2347		 * remaining entries.
2348		 */
2349		if (*cur_fill_num >= ooa_hdr->alloc_num)
2350			continue;
2351
2352		entry = &kern_entries[*cur_fill_num];
2353
2354		entry->tag_num = io->scsiio.tag_num;
2355		entry->lun_num = lun->lun;
2356#ifdef CTL_TIME_IO
2357		entry->start_bt = io->io_hdr.start_bt;
2358#endif
2359		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2360		entry->cdb_len = io->scsiio.cdb_len;
2361		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2362			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2363
2364		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2365			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2366
2367		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2368			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2369
2370		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2371			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2372
2373		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2374			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2375	}
2376	mtx_unlock(&lun->lun_lock);
2377}
2378
2379static void *
2380ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2381		 size_t error_str_len)
2382{
2383	void *kptr;
2384
2385	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2386
2387	if (copyin(user_addr, kptr, len) != 0) {
2388		snprintf(error_str, error_str_len, "Error copying %d bytes "
2389			 "from user address %p to kernel address %p", len,
2390			 user_addr, kptr);
2391		free(kptr, M_CTL);
2392		return (NULL);
2393	}
2394
2395	return (kptr);
2396}
2397
2398static void
2399ctl_free_args(int num_args, struct ctl_be_arg *args)
2400{
2401	int i;
2402
2403	if (args == NULL)
2404		return;
2405
2406	for (i = 0; i < num_args; i++) {
2407		free(args[i].kname, M_CTL);
2408		free(args[i].kvalue, M_CTL);
2409	}
2410
2411	free(args, M_CTL);
2412}
2413
2414static struct ctl_be_arg *
2415ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2416		char *error_str, size_t error_str_len)
2417{
2418	struct ctl_be_arg *args;
2419	int i;
2420
2421	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2422				error_str, error_str_len);
2423
2424	if (args == NULL)
2425		goto bailout;
2426
2427	for (i = 0; i < num_args; i++) {
2428		args[i].kname = NULL;
2429		args[i].kvalue = NULL;
2430	}
2431
2432	for (i = 0; i < num_args; i++) {
2433		uint8_t *tmpptr;
2434
2435		args[i].kname = ctl_copyin_alloc(args[i].name,
2436			args[i].namelen, error_str, error_str_len);
2437		if (args[i].kname == NULL)
2438			goto bailout;
2439
2440		if (args[i].kname[args[i].namelen - 1] != '\0') {
2441			snprintf(error_str, error_str_len, "Argument %d "
2442				 "name is not NUL-terminated", i);
2443			goto bailout;
2444		}
2445
2446		if (args[i].flags & CTL_BEARG_RD) {
2447			tmpptr = ctl_copyin_alloc(args[i].value,
2448				args[i].vallen, error_str, error_str_len);
2449			if (tmpptr == NULL)
2450				goto bailout;
2451			if ((args[i].flags & CTL_BEARG_ASCII)
2452			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2453				snprintf(error_str, error_str_len, "Argument "
2454				    "%d value is not NUL-terminated", i);
2455				free(tmpptr, M_CTL);
2456				goto bailout;
2457			}
2458			args[i].kvalue = tmpptr;
2459		} else {
2460			args[i].kvalue = malloc(args[i].vallen,
2461			    M_CTL, M_WAITOK | M_ZERO);
2462		}
2463	}
2464
2465	return (args);
2466bailout:
2467
2468	ctl_free_args(num_args, args);
2469
2470	return (NULL);
2471}
2472
2473static void
2474ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2475{
2476	int i;
2477
2478	for (i = 0; i < num_args; i++) {
2479		if (args[i].flags & CTL_BEARG_WR)
2480			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2481	}
2482}
2483
2484/*
2485 * Escape characters that are illegal or not recommended in XML.
2486 */
2487int
2488ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2489{
2490	char *end = str + size;
2491	int retval;
2492
2493	retval = 0;
2494
2495	for (; *str && str < end; str++) {
2496		switch (*str) {
2497		case '&':
2498			retval = sbuf_printf(sb, "&amp;");
2499			break;
2500		case '>':
2501			retval = sbuf_printf(sb, "&gt;");
2502			break;
2503		case '<':
2504			retval = sbuf_printf(sb, "&lt;");
2505			break;
2506		default:
2507			retval = sbuf_putc(sb, *str);
2508			break;
2509		}
2510
2511		if (retval != 0)
2512			break;
2513
2514	}
2515
2516	return (retval);
2517}
2518
2519static void
2520ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2521{
2522	struct scsi_vpd_id_descriptor *desc;
2523	int i;
2524
2525	if (id == NULL || id->len < 4)
2526		return;
2527	desc = (struct scsi_vpd_id_descriptor *)id->data;
2528	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2529	case SVPD_ID_TYPE_T10:
2530		sbuf_printf(sb, "t10.");
2531		break;
2532	case SVPD_ID_TYPE_EUI64:
2533		sbuf_printf(sb, "eui.");
2534		break;
2535	case SVPD_ID_TYPE_NAA:
2536		sbuf_printf(sb, "naa.");
2537		break;
2538	case SVPD_ID_TYPE_SCSI_NAME:
2539		break;
2540	}
2541	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2542	case SVPD_ID_CODESET_BINARY:
2543		for (i = 0; i < desc->length; i++)
2544			sbuf_printf(sb, "%02x", desc->identifier[i]);
2545		break;
2546	case SVPD_ID_CODESET_ASCII:
2547		sbuf_printf(sb, "%.*s", (int)desc->length,
2548		    (char *)desc->identifier);
2549		break;
2550	case SVPD_ID_CODESET_UTF8:
2551		sbuf_printf(sb, "%s", (char *)desc->identifier);
2552		break;
2553	}
2554}
2555
2556static int
2557ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2558	  struct thread *td)
2559{
2560	struct ctl_softc *softc = dev->si_drv1;
2561	struct ctl_lun *lun;
2562	int retval;
2563
2564	retval = 0;
2565
2566	switch (cmd) {
2567	case CTL_IO:
2568		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2569		break;
2570	case CTL_ENABLE_PORT:
2571	case CTL_DISABLE_PORT:
2572	case CTL_SET_PORT_WWNS: {
2573		struct ctl_port *port;
2574		struct ctl_port_entry *entry;
2575
2576		entry = (struct ctl_port_entry *)addr;
2577
2578		mtx_lock(&softc->ctl_lock);
2579		STAILQ_FOREACH(port, &softc->port_list, links) {
2580			int action, done;
2581
2582			if (port->targ_port < softc->port_min ||
2583			    port->targ_port >= softc->port_max)
2584				continue;
2585
2586			action = 0;
2587			done = 0;
2588			if ((entry->port_type == CTL_PORT_NONE)
2589			 && (entry->targ_port == port->targ_port)) {
2590				/*
2591				 * If the user only wants to enable or
2592				 * disable or set WWNs on a specific port,
2593				 * do the operation and we're done.
2594				 */
2595				action = 1;
2596				done = 1;
2597			} else if (entry->port_type & port->port_type) {
2598				/*
2599				 * Compare the user's type mask with the
2600				 * particular frontend type to see if we
2601				 * have a match.
2602				 */
2603				action = 1;
2604				done = 0;
2605
2606				/*
2607				 * Make sure the user isn't trying to set
2608				 * WWNs on multiple ports at the same time.
2609				 */
2610				if (cmd == CTL_SET_PORT_WWNS) {
2611					printf("%s: Can't set WWNs on "
2612					       "multiple ports\n", __func__);
2613					retval = EINVAL;
2614					break;
2615				}
2616			}
2617			if (action == 0)
2618				continue;
2619
2620			/*
2621			 * XXX KDM we have to drop the lock here, because
2622			 * the online/offline operations can potentially
2623			 * block.  We need to reference count the frontends
2624			 * so they can't go away,
2625			 */
2626			if (cmd == CTL_ENABLE_PORT) {
2627				mtx_unlock(&softc->ctl_lock);
2628				ctl_port_online(port);
2629				mtx_lock(&softc->ctl_lock);
2630			} else if (cmd == CTL_DISABLE_PORT) {
2631				mtx_unlock(&softc->ctl_lock);
2632				ctl_port_offline(port);
2633				mtx_lock(&softc->ctl_lock);
2634			} else if (cmd == CTL_SET_PORT_WWNS) {
2635				ctl_port_set_wwns(port,
2636				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2637				    1 : 0, entry->wwnn,
2638				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2639				    1 : 0, entry->wwpn);
2640			}
2641			if (done != 0)
2642				break;
2643		}
2644		mtx_unlock(&softc->ctl_lock);
2645		break;
2646	}
2647	case CTL_GET_OOA: {
2648		struct ctl_ooa *ooa_hdr;
2649		struct ctl_ooa_entry *entries;
2650		uint32_t cur_fill_num;
2651
2652		ooa_hdr = (struct ctl_ooa *)addr;
2653
2654		if ((ooa_hdr->alloc_len == 0)
2655		 || (ooa_hdr->alloc_num == 0)) {
2656			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2657			       "must be non-zero\n", __func__,
2658			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2659			retval = EINVAL;
2660			break;
2661		}
2662
2663		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2664		    sizeof(struct ctl_ooa_entry))) {
2665			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2666			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2667			       __func__, ooa_hdr->alloc_len,
2668			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2669			retval = EINVAL;
2670			break;
2671		}
2672
2673		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2674		if (entries == NULL) {
2675			printf("%s: could not allocate %d bytes for OOA "
2676			       "dump\n", __func__, ooa_hdr->alloc_len);
2677			retval = ENOMEM;
2678			break;
2679		}
2680
2681		mtx_lock(&softc->ctl_lock);
2682		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2683		    (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2684		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2685			mtx_unlock(&softc->ctl_lock);
2686			free(entries, M_CTL);
2687			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2688			       __func__, (uintmax_t)ooa_hdr->lun_num);
2689			retval = EINVAL;
2690			break;
2691		}
2692
2693		cur_fill_num = 0;
2694
2695		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2696			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2697				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2698				    ooa_hdr, entries);
2699			}
2700		} else {
2701			lun = softc->ctl_luns[ooa_hdr->lun_num];
2702			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2703			    entries);
2704		}
2705		mtx_unlock(&softc->ctl_lock);
2706
2707		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2708		ooa_hdr->fill_len = ooa_hdr->fill_num *
2709			sizeof(struct ctl_ooa_entry);
2710		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2711		if (retval != 0) {
2712			printf("%s: error copying out %d bytes for OOA dump\n",
2713			       __func__, ooa_hdr->fill_len);
2714		}
2715
2716		getbinuptime(&ooa_hdr->cur_bt);
2717
2718		if (cur_fill_num > ooa_hdr->alloc_num) {
2719			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2720			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2721		} else {
2722			ooa_hdr->dropped_num = 0;
2723			ooa_hdr->status = CTL_OOA_OK;
2724		}
2725
2726		free(entries, M_CTL);
2727		break;
2728	}
2729	case CTL_DELAY_IO: {
2730		struct ctl_io_delay_info *delay_info;
2731
2732		delay_info = (struct ctl_io_delay_info *)addr;
2733
2734#ifdef CTL_IO_DELAY
2735		mtx_lock(&softc->ctl_lock);
2736		if (delay_info->lun_id >= CTL_MAX_LUNS ||
2737		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2738			mtx_unlock(&softc->ctl_lock);
2739			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2740			break;
2741		}
2742		mtx_lock(&lun->lun_lock);
2743		mtx_unlock(&softc->ctl_lock);
2744		delay_info->status = CTL_DELAY_STATUS_OK;
2745		switch (delay_info->delay_type) {
2746		case CTL_DELAY_TYPE_CONT:
2747		case CTL_DELAY_TYPE_ONESHOT:
2748			break;
2749		default:
2750			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2751			break;
2752		}
2753		switch (delay_info->delay_loc) {
2754		case CTL_DELAY_LOC_DATAMOVE:
2755			lun->delay_info.datamove_type = delay_info->delay_type;
2756			lun->delay_info.datamove_delay = delay_info->delay_secs;
2757			break;
2758		case CTL_DELAY_LOC_DONE:
2759			lun->delay_info.done_type = delay_info->delay_type;
2760			lun->delay_info.done_delay = delay_info->delay_secs;
2761			break;
2762		default:
2763			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2764			break;
2765		}
2766		mtx_unlock(&lun->lun_lock);
2767#else
2768		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2769#endif /* CTL_IO_DELAY */
2770		break;
2771	}
2772	case CTL_GETSTATS: {
2773		struct ctl_stats *stats = (struct ctl_stats *)addr;
2774		int i;
2775
2776		/*
2777		 * XXX KDM no locking here.  If the LUN list changes,
2778		 * things can blow up.
2779		 */
2780		i = 0;
2781		stats->status = CTL_SS_OK;
2782		stats->fill_len = 0;
2783		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2784			if (stats->fill_len + sizeof(lun->stats) >
2785			    stats->alloc_len) {
2786				stats->status = CTL_SS_NEED_MORE_SPACE;
2787				break;
2788			}
2789			retval = copyout(&lun->stats, &stats->lun_stats[i++],
2790					 sizeof(lun->stats));
2791			if (retval != 0)
2792				break;
2793			stats->fill_len += sizeof(lun->stats);
2794		}
2795		stats->num_luns = softc->num_luns;
2796#ifdef CTL_TIME_IO
2797		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2798#else
2799		stats->flags = CTL_STATS_FLAG_NONE;
2800#endif
2801		getnanouptime(&stats->timestamp);
2802		break;
2803	}
2804	case CTL_ERROR_INJECT: {
2805		struct ctl_error_desc *err_desc, *new_err_desc;
2806
2807		err_desc = (struct ctl_error_desc *)addr;
2808
2809		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2810				      M_WAITOK | M_ZERO);
2811		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2812
2813		mtx_lock(&softc->ctl_lock);
2814		if (err_desc->lun_id >= CTL_MAX_LUNS ||
2815		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2816			mtx_unlock(&softc->ctl_lock);
2817			free(new_err_desc, M_CTL);
2818			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2819			       __func__, (uintmax_t)err_desc->lun_id);
2820			retval = EINVAL;
2821			break;
2822		}
2823		mtx_lock(&lun->lun_lock);
2824		mtx_unlock(&softc->ctl_lock);
2825
2826		/*
2827		 * We could do some checking here to verify the validity
2828		 * of the request, but given the complexity of error
2829		 * injection requests, the checking logic would be fairly
2830		 * complex.
2831		 *
2832		 * For now, if the request is invalid, it just won't get
2833		 * executed and might get deleted.
2834		 */
2835		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2836
2837		/*
2838		 * XXX KDM check to make sure the serial number is unique,
2839		 * in case we somehow manage to wrap.  That shouldn't
2840		 * happen for a very long time, but it's the right thing to
2841		 * do.
2842		 */
2843		new_err_desc->serial = lun->error_serial;
2844		err_desc->serial = lun->error_serial;
2845		lun->error_serial++;
2846
2847		mtx_unlock(&lun->lun_lock);
2848		break;
2849	}
2850	case CTL_ERROR_INJECT_DELETE: {
2851		struct ctl_error_desc *delete_desc, *desc, *desc2;
2852		int delete_done;
2853
2854		delete_desc = (struct ctl_error_desc *)addr;
2855		delete_done = 0;
2856
2857		mtx_lock(&softc->ctl_lock);
2858		if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2859		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2860			mtx_unlock(&softc->ctl_lock);
2861			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2862			       __func__, (uintmax_t)delete_desc->lun_id);
2863			retval = EINVAL;
2864			break;
2865		}
2866		mtx_lock(&lun->lun_lock);
2867		mtx_unlock(&softc->ctl_lock);
2868		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2869			if (desc->serial != delete_desc->serial)
2870				continue;
2871
2872			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2873				      links);
2874			free(desc, M_CTL);
2875			delete_done = 1;
2876		}
2877		mtx_unlock(&lun->lun_lock);
2878		if (delete_done == 0) {
2879			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2880			       "error serial %ju on LUN %u\n", __func__,
2881			       delete_desc->serial, delete_desc->lun_id);
2882			retval = EINVAL;
2883			break;
2884		}
2885		break;
2886	}
2887	case CTL_DUMP_STRUCTS: {
2888		int j, k;
2889		struct ctl_port *port;
2890		struct ctl_frontend *fe;
2891
2892		mtx_lock(&softc->ctl_lock);
2893		printf("CTL Persistent Reservation information start:\n");
2894		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2895			mtx_lock(&lun->lun_lock);
2896			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2897				mtx_unlock(&lun->lun_lock);
2898				continue;
2899			}
2900
2901			for (j = 0; j < CTL_MAX_PORTS; j++) {
2902				if (lun->pr_keys[j] == NULL)
2903					continue;
2904				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2905					if (lun->pr_keys[j][k] == 0)
2906						continue;
2907					printf("  LUN %ju port %d iid %d key "
2908					       "%#jx\n", lun->lun, j, k,
2909					       (uintmax_t)lun->pr_keys[j][k]);
2910				}
2911			}
2912			mtx_unlock(&lun->lun_lock);
2913		}
2914		printf("CTL Persistent Reservation information end\n");
2915		printf("CTL Ports:\n");
2916		STAILQ_FOREACH(port, &softc->port_list, links) {
2917			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2918			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2919			       port->frontend->name, port->port_type,
2920			       port->physical_port, port->virtual_port,
2921			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2922			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2923				if (port->wwpn_iid[j].in_use == 0 &&
2924				    port->wwpn_iid[j].wwpn == 0 &&
2925				    port->wwpn_iid[j].name == NULL)
2926					continue;
2927
2928				printf("    iid %u use %d WWPN %#jx '%s'\n",
2929				    j, port->wwpn_iid[j].in_use,
2930				    (uintmax_t)port->wwpn_iid[j].wwpn,
2931				    port->wwpn_iid[j].name);
2932			}
2933		}
2934		printf("CTL Port information end\n");
2935		mtx_unlock(&softc->ctl_lock);
2936		/*
2937		 * XXX KDM calling this without a lock.  We'd likely want
2938		 * to drop the lock before calling the frontend's dump
2939		 * routine anyway.
2940		 */
2941		printf("CTL Frontends:\n");
2942		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2943			printf("  Frontend '%s'\n", fe->name);
2944			if (fe->fe_dump != NULL)
2945				fe->fe_dump();
2946		}
2947		printf("CTL Frontend information end\n");
2948		break;
2949	}
2950	case CTL_LUN_REQ: {
2951		struct ctl_lun_req *lun_req;
2952		struct ctl_backend_driver *backend;
2953
2954		lun_req = (struct ctl_lun_req *)addr;
2955
2956		backend = ctl_backend_find(lun_req->backend);
2957		if (backend == NULL) {
2958			lun_req->status = CTL_LUN_ERROR;
2959			snprintf(lun_req->error_str,
2960				 sizeof(lun_req->error_str),
2961				 "Backend \"%s\" not found.",
2962				 lun_req->backend);
2963			break;
2964		}
2965		if (lun_req->num_be_args > 0) {
2966			lun_req->kern_be_args = ctl_copyin_args(
2967				lun_req->num_be_args,
2968				lun_req->be_args,
2969				lun_req->error_str,
2970				sizeof(lun_req->error_str));
2971			if (lun_req->kern_be_args == NULL) {
2972				lun_req->status = CTL_LUN_ERROR;
2973				break;
2974			}
2975		}
2976
2977		retval = backend->ioctl(dev, cmd, addr, flag, td);
2978
2979		if (lun_req->num_be_args > 0) {
2980			ctl_copyout_args(lun_req->num_be_args,
2981				      lun_req->kern_be_args);
2982			ctl_free_args(lun_req->num_be_args,
2983				      lun_req->kern_be_args);
2984		}
2985		break;
2986	}
2987	case CTL_LUN_LIST: {
2988		struct sbuf *sb;
2989		struct ctl_lun_list *list;
2990		struct ctl_option *opt;
2991
2992		list = (struct ctl_lun_list *)addr;
2993
2994		/*
2995		 * Allocate a fixed length sbuf here, based on the length
2996		 * of the user's buffer.  We could allocate an auto-extending
2997		 * buffer, and then tell the user how much larger our
2998		 * amount of data is than his buffer, but that presents
2999		 * some problems:
3000		 *
3001		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3002		 *     we can't hold a lock while calling them with an
3003		 *     auto-extending buffer.
3004 		 *
3005		 * 2.  There is not currently a LUN reference counting
3006		 *     mechanism, outside of outstanding transactions on
3007		 *     the LUN's OOA queue.  So a LUN could go away on us
3008		 *     while we're getting the LUN number, backend-specific
3009		 *     information, etc.  Thus, given the way things
3010		 *     currently work, we need to hold the CTL lock while
3011		 *     grabbing LUN information.
3012		 *
3013		 * So, from the user's standpoint, the best thing to do is
3014		 * allocate what he thinks is a reasonable buffer length,
3015		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3016		 * double the buffer length and try again.  (And repeat
3017		 * that until he succeeds.)
3018		 */
3019		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3020		if (sb == NULL) {
3021			list->status = CTL_LUN_LIST_ERROR;
3022			snprintf(list->error_str, sizeof(list->error_str),
3023				 "Unable to allocate %d bytes for LUN list",
3024				 list->alloc_len);
3025			break;
3026		}
3027
3028		sbuf_printf(sb, "<ctllunlist>\n");
3029
3030		mtx_lock(&softc->ctl_lock);
3031		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3032			mtx_lock(&lun->lun_lock);
3033			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3034					     (uintmax_t)lun->lun);
3035
3036			/*
3037			 * Bail out as soon as we see that we've overfilled
3038			 * the buffer.
3039			 */
3040			if (retval != 0)
3041				break;
3042
3043			retval = sbuf_printf(sb, "\t<backend_type>%s"
3044					     "</backend_type>\n",
3045					     (lun->backend == NULL) ?  "none" :
3046					     lun->backend->name);
3047
3048			if (retval != 0)
3049				break;
3050
3051			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3052					     lun->be_lun->lun_type);
3053
3054			if (retval != 0)
3055				break;
3056
3057			if (lun->backend == NULL) {
3058				retval = sbuf_printf(sb, "</lun>\n");
3059				if (retval != 0)
3060					break;
3061				continue;
3062			}
3063
3064			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3065					     (lun->be_lun->maxlba > 0) ?
3066					     lun->be_lun->maxlba + 1 : 0);
3067
3068			if (retval != 0)
3069				break;
3070
3071			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3072					     lun->be_lun->blocksize);
3073
3074			if (retval != 0)
3075				break;
3076
3077			retval = sbuf_printf(sb, "\t<serial_number>");
3078
3079			if (retval != 0)
3080				break;
3081
3082			retval = ctl_sbuf_printf_esc(sb,
3083			    lun->be_lun->serial_num,
3084			    sizeof(lun->be_lun->serial_num));
3085
3086			if (retval != 0)
3087				break;
3088
3089			retval = sbuf_printf(sb, "</serial_number>\n");
3090
3091			if (retval != 0)
3092				break;
3093
3094			retval = sbuf_printf(sb, "\t<device_id>");
3095
3096			if (retval != 0)
3097				break;
3098
3099			retval = ctl_sbuf_printf_esc(sb,
3100			    lun->be_lun->device_id,
3101			    sizeof(lun->be_lun->device_id));
3102
3103			if (retval != 0)
3104				break;
3105
3106			retval = sbuf_printf(sb, "</device_id>\n");
3107
3108			if (retval != 0)
3109				break;
3110
3111			if (lun->backend->lun_info != NULL) {
3112				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3113				if (retval != 0)
3114					break;
3115			}
3116			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3117				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3118				    opt->name, opt->value, opt->name);
3119				if (retval != 0)
3120					break;
3121			}
3122
3123			retval = sbuf_printf(sb, "</lun>\n");
3124
3125			if (retval != 0)
3126				break;
3127			mtx_unlock(&lun->lun_lock);
3128		}
3129		if (lun != NULL)
3130			mtx_unlock(&lun->lun_lock);
3131		mtx_unlock(&softc->ctl_lock);
3132
3133		if ((retval != 0)
3134		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3135			retval = 0;
3136			sbuf_delete(sb);
3137			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3138			snprintf(list->error_str, sizeof(list->error_str),
3139				 "Out of space, %d bytes is too small",
3140				 list->alloc_len);
3141			break;
3142		}
3143
3144		sbuf_finish(sb);
3145
3146		retval = copyout(sbuf_data(sb), list->lun_xml,
3147				 sbuf_len(sb) + 1);
3148
3149		list->fill_len = sbuf_len(sb) + 1;
3150		list->status = CTL_LUN_LIST_OK;
3151		sbuf_delete(sb);
3152		break;
3153	}
3154	case CTL_ISCSI: {
3155		struct ctl_iscsi *ci;
3156		struct ctl_frontend *fe;
3157
3158		ci = (struct ctl_iscsi *)addr;
3159
3160		fe = ctl_frontend_find("iscsi");
3161		if (fe == NULL) {
3162			ci->status = CTL_ISCSI_ERROR;
3163			snprintf(ci->error_str, sizeof(ci->error_str),
3164			    "Frontend \"iscsi\" not found.");
3165			break;
3166		}
3167
3168		retval = fe->ioctl(dev, cmd, addr, flag, td);
3169		break;
3170	}
3171	case CTL_PORT_REQ: {
3172		struct ctl_req *req;
3173		struct ctl_frontend *fe;
3174
3175		req = (struct ctl_req *)addr;
3176
3177		fe = ctl_frontend_find(req->driver);
3178		if (fe == NULL) {
3179			req->status = CTL_LUN_ERROR;
3180			snprintf(req->error_str, sizeof(req->error_str),
3181			    "Frontend \"%s\" not found.", req->driver);
3182			break;
3183		}
3184		if (req->num_args > 0) {
3185			req->kern_args = ctl_copyin_args(req->num_args,
3186			    req->args, req->error_str, sizeof(req->error_str));
3187			if (req->kern_args == NULL) {
3188				req->status = CTL_LUN_ERROR;
3189				break;
3190			}
3191		}
3192
3193		if (fe->ioctl)
3194			retval = fe->ioctl(dev, cmd, addr, flag, td);
3195		else
3196			retval = ENODEV;
3197
3198		if (req->num_args > 0) {
3199			ctl_copyout_args(req->num_args, req->kern_args);
3200			ctl_free_args(req->num_args, req->kern_args);
3201		}
3202		break;
3203	}
3204	case CTL_PORT_LIST: {
3205		struct sbuf *sb;
3206		struct ctl_port *port;
3207		struct ctl_lun_list *list;
3208		struct ctl_option *opt;
3209		int j;
3210		uint32_t plun;
3211
3212		list = (struct ctl_lun_list *)addr;
3213
3214		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3215		if (sb == NULL) {
3216			list->status = CTL_LUN_LIST_ERROR;
3217			snprintf(list->error_str, sizeof(list->error_str),
3218				 "Unable to allocate %d bytes for LUN list",
3219				 list->alloc_len);
3220			break;
3221		}
3222
3223		sbuf_printf(sb, "<ctlportlist>\n");
3224
3225		mtx_lock(&softc->ctl_lock);
3226		STAILQ_FOREACH(port, &softc->port_list, links) {
3227			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3228					     (uintmax_t)port->targ_port);
3229
3230			/*
3231			 * Bail out as soon as we see that we've overfilled
3232			 * the buffer.
3233			 */
3234			if (retval != 0)
3235				break;
3236
3237			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3238			    "</frontend_type>\n", port->frontend->name);
3239			if (retval != 0)
3240				break;
3241
3242			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3243					     port->port_type);
3244			if (retval != 0)
3245				break;
3246
3247			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3248			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3249			if (retval != 0)
3250				break;
3251
3252			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3253			    port->port_name);
3254			if (retval != 0)
3255				break;
3256
3257			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3258			    port->physical_port);
3259			if (retval != 0)
3260				break;
3261
3262			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3263			    port->virtual_port);
3264			if (retval != 0)
3265				break;
3266
3267			if (port->target_devid != NULL) {
3268				sbuf_printf(sb, "\t<target>");
3269				ctl_id_sbuf(port->target_devid, sb);
3270				sbuf_printf(sb, "</target>\n");
3271			}
3272
3273			if (port->port_devid != NULL) {
3274				sbuf_printf(sb, "\t<port>");
3275				ctl_id_sbuf(port->port_devid, sb);
3276				sbuf_printf(sb, "</port>\n");
3277			}
3278
3279			if (port->port_info != NULL) {
3280				retval = port->port_info(port->onoff_arg, sb);
3281				if (retval != 0)
3282					break;
3283			}
3284			STAILQ_FOREACH(opt, &port->options, links) {
3285				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3286				    opt->name, opt->value, opt->name);
3287				if (retval != 0)
3288					break;
3289			}
3290
3291			if (port->lun_map != NULL) {
3292				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3293				for (j = 0; j < port->lun_map_size; j++) {
3294					plun = ctl_lun_map_from_port(port, j);
3295					if (plun == UINT32_MAX)
3296						continue;
3297					sbuf_printf(sb,
3298					    "\t<lun id=\"%u\">%u</lun>\n",
3299					    j, plun);
3300				}
3301			}
3302
3303			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3304				if (port->wwpn_iid[j].in_use == 0 ||
3305				    (port->wwpn_iid[j].wwpn == 0 &&
3306				     port->wwpn_iid[j].name == NULL))
3307					continue;
3308
3309				if (port->wwpn_iid[j].name != NULL)
3310					retval = sbuf_printf(sb,
3311					    "\t<initiator id=\"%u\">%s</initiator>\n",
3312					    j, port->wwpn_iid[j].name);
3313				else
3314					retval = sbuf_printf(sb,
3315					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3316					    j, port->wwpn_iid[j].wwpn);
3317				if (retval != 0)
3318					break;
3319			}
3320			if (retval != 0)
3321				break;
3322
3323			retval = sbuf_printf(sb, "</targ_port>\n");
3324			if (retval != 0)
3325				break;
3326		}
3327		mtx_unlock(&softc->ctl_lock);
3328
3329		if ((retval != 0)
3330		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3331			retval = 0;
3332			sbuf_delete(sb);
3333			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3334			snprintf(list->error_str, sizeof(list->error_str),
3335				 "Out of space, %d bytes is too small",
3336				 list->alloc_len);
3337			break;
3338		}
3339
3340		sbuf_finish(sb);
3341
3342		retval = copyout(sbuf_data(sb), list->lun_xml,
3343				 sbuf_len(sb) + 1);
3344
3345		list->fill_len = sbuf_len(sb) + 1;
3346		list->status = CTL_LUN_LIST_OK;
3347		sbuf_delete(sb);
3348		break;
3349	}
3350	case CTL_LUN_MAP: {
3351		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3352		struct ctl_port *port;
3353
3354		mtx_lock(&softc->ctl_lock);
3355		if (lm->port < softc->port_min ||
3356		    lm->port >= softc->port_max ||
3357		    (port = softc->ctl_ports[lm->port]) == NULL) {
3358			mtx_unlock(&softc->ctl_lock);
3359			return (ENXIO);
3360		}
3361		if (port->status & CTL_PORT_STATUS_ONLINE) {
3362			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3363				if (ctl_lun_map_to_port(port, lun->lun) ==
3364				    UINT32_MAX)
3365					continue;
3366				mtx_lock(&lun->lun_lock);
3367				ctl_est_ua_port(lun, lm->port, -1,
3368				    CTL_UA_LUN_CHANGE);
3369				mtx_unlock(&lun->lun_lock);
3370			}
3371		}
3372		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3373		if (lm->plun != UINT32_MAX) {
3374			if (lm->lun == UINT32_MAX)
3375				retval = ctl_lun_map_unset(port, lm->plun);
3376			else if (lm->lun < CTL_MAX_LUNS &&
3377			    softc->ctl_luns[lm->lun] != NULL)
3378				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3379			else
3380				return (ENXIO);
3381		} else {
3382			if (lm->lun == UINT32_MAX)
3383				retval = ctl_lun_map_deinit(port);
3384			else
3385				retval = ctl_lun_map_init(port);
3386		}
3387		if (port->status & CTL_PORT_STATUS_ONLINE)
3388			ctl_isc_announce_port(port);
3389		break;
3390	}
3391	default: {
3392		/* XXX KDM should we fix this? */
3393#if 0
3394		struct ctl_backend_driver *backend;
3395		unsigned int type;
3396		int found;
3397
3398		found = 0;
3399
3400		/*
3401		 * We encode the backend type as the ioctl type for backend
3402		 * ioctls.  So parse it out here, and then search for a
3403		 * backend of this type.
3404		 */
3405		type = _IOC_TYPE(cmd);
3406
3407		STAILQ_FOREACH(backend, &softc->be_list, links) {
3408			if (backend->type == type) {
3409				found = 1;
3410				break;
3411			}
3412		}
3413		if (found == 0) {
3414			printf("ctl: unknown ioctl command %#lx or backend "
3415			       "%d\n", cmd, type);
3416			retval = EINVAL;
3417			break;
3418		}
3419		retval = backend->ioctl(dev, cmd, addr, flag, td);
3420#endif
3421		retval = ENOTTY;
3422		break;
3423	}
3424	}
3425	return (retval);
3426}
3427
3428uint32_t
3429ctl_get_initindex(struct ctl_nexus *nexus)
3430{
3431	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3432}
3433
3434int
3435ctl_lun_map_init(struct ctl_port *port)
3436{
3437	struct ctl_softc *softc = port->ctl_softc;
3438	struct ctl_lun *lun;
3439	int size = ctl_lun_map_size;
3440	uint32_t i;
3441
3442	if (port->lun_map == NULL || port->lun_map_size < size) {
3443		port->lun_map_size = 0;
3444		free(port->lun_map, M_CTL);
3445		port->lun_map = malloc(size * sizeof(uint32_t),
3446		    M_CTL, M_NOWAIT);
3447	}
3448	if (port->lun_map == NULL)
3449		return (ENOMEM);
3450	for (i = 0; i < size; i++)
3451		port->lun_map[i] = UINT32_MAX;
3452	port->lun_map_size = size;
3453	if (port->status & CTL_PORT_STATUS_ONLINE) {
3454		if (port->lun_disable != NULL) {
3455			STAILQ_FOREACH(lun, &softc->lun_list, links)
3456				port->lun_disable(port->targ_lun_arg, lun->lun);
3457		}
3458		ctl_isc_announce_port(port);
3459	}
3460	return (0);
3461}
3462
3463int
3464ctl_lun_map_deinit(struct ctl_port *port)
3465{
3466	struct ctl_softc *softc = port->ctl_softc;
3467	struct ctl_lun *lun;
3468
3469	if (port->lun_map == NULL)
3470		return (0);
3471	port->lun_map_size = 0;
3472	free(port->lun_map, M_CTL);
3473	port->lun_map = NULL;
3474	if (port->status & CTL_PORT_STATUS_ONLINE) {
3475		if (port->lun_enable != NULL) {
3476			STAILQ_FOREACH(lun, &softc->lun_list, links)
3477				port->lun_enable(port->targ_lun_arg, lun->lun);
3478		}
3479		ctl_isc_announce_port(port);
3480	}
3481	return (0);
3482}
3483
3484int
3485ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3486{
3487	int status;
3488	uint32_t old;
3489
3490	if (port->lun_map == NULL) {
3491		status = ctl_lun_map_init(port);
3492		if (status != 0)
3493			return (status);
3494	}
3495	if (plun >= port->lun_map_size)
3496		return (EINVAL);
3497	old = port->lun_map[plun];
3498	port->lun_map[plun] = glun;
3499	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3500		if (port->lun_enable != NULL)
3501			port->lun_enable(port->targ_lun_arg, plun);
3502		ctl_isc_announce_port(port);
3503	}
3504	return (0);
3505}
3506
3507int
3508ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3509{
3510	uint32_t old;
3511
3512	if (port->lun_map == NULL || plun >= port->lun_map_size)
3513		return (0);
3514	old = port->lun_map[plun];
3515	port->lun_map[plun] = UINT32_MAX;
3516	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3517		if (port->lun_disable != NULL)
3518			port->lun_disable(port->targ_lun_arg, plun);
3519		ctl_isc_announce_port(port);
3520	}
3521	return (0);
3522}
3523
3524uint32_t
3525ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3526{
3527
3528	if (port == NULL)
3529		return (UINT32_MAX);
3530	if (port->lun_map == NULL)
3531		return (lun_id);
3532	if (lun_id > port->lun_map_size)
3533		return (UINT32_MAX);
3534	return (port->lun_map[lun_id]);
3535}
3536
3537uint32_t
3538ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3539{
3540	uint32_t i;
3541
3542	if (port == NULL)
3543		return (UINT32_MAX);
3544	if (port->lun_map == NULL)
3545		return (lun_id);
3546	for (i = 0; i < port->lun_map_size; i++) {
3547		if (port->lun_map[i] == lun_id)
3548			return (i);
3549	}
3550	return (UINT32_MAX);
3551}
3552
3553uint32_t
3554ctl_decode_lun(uint64_t encoded)
3555{
3556	uint8_t lun[8];
3557	uint32_t result = 0xffffffff;
3558
3559	be64enc(lun, encoded);
3560	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3561	case RPL_LUNDATA_ATYP_PERIPH:
3562		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3563		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3564			result = lun[1];
3565		break;
3566	case RPL_LUNDATA_ATYP_FLAT:
3567		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3568		    lun[6] == 0 && lun[7] == 0)
3569			result = ((lun[0] & 0x3f) << 8) + lun[1];
3570		break;
3571	case RPL_LUNDATA_ATYP_EXTLUN:
3572		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3573		case 0x02:
3574			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3575			case 0x00:
3576				result = lun[1];
3577				break;
3578			case 0x10:
3579				result = (lun[1] << 16) + (lun[2] << 8) +
3580				    lun[3];
3581				break;
3582			case 0x20:
3583				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3584					result = (lun[2] << 24) +
3585					    (lun[3] << 16) + (lun[4] << 8) +
3586					    lun[5];
3587				break;
3588			}
3589			break;
3590		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3591			result = 0xffffffff;
3592			break;
3593		}
3594		break;
3595	}
3596	return (result);
3597}
3598
3599uint64_t
3600ctl_encode_lun(uint32_t decoded)
3601{
3602	uint64_t l = decoded;
3603
3604	if (l <= 0xff)
3605		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3606	if (l <= 0x3fff)
3607		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3608	if (l <= 0xffffff)
3609		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3610		    (l << 32));
3611	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3612}
3613
3614int
3615ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3616{
3617	int i;
3618
3619	for (i = first; i < last; i++) {
3620		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3621			return (i);
3622	}
3623	return (-1);
3624}
3625
3626int
3627ctl_set_mask(uint32_t *mask, uint32_t bit)
3628{
3629	uint32_t chunk, piece;
3630
3631	chunk = bit >> 5;
3632	piece = bit % (sizeof(uint32_t) * 8);
3633
3634	if ((mask[chunk] & (1 << piece)) != 0)
3635		return (-1);
3636	else
3637		mask[chunk] |= (1 << piece);
3638
3639	return (0);
3640}
3641
3642int
3643ctl_clear_mask(uint32_t *mask, uint32_t bit)
3644{
3645	uint32_t chunk, piece;
3646
3647	chunk = bit >> 5;
3648	piece = bit % (sizeof(uint32_t) * 8);
3649
3650	if ((mask[chunk] & (1 << piece)) == 0)
3651		return (-1);
3652	else
3653		mask[chunk] &= ~(1 << piece);
3654
3655	return (0);
3656}
3657
3658int
3659ctl_is_set(uint32_t *mask, uint32_t bit)
3660{
3661	uint32_t chunk, piece;
3662
3663	chunk = bit >> 5;
3664	piece = bit % (sizeof(uint32_t) * 8);
3665
3666	if ((mask[chunk] & (1 << piece)) == 0)
3667		return (0);
3668	else
3669		return (1);
3670}
3671
3672static uint64_t
3673ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3674{
3675	uint64_t *t;
3676
3677	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3678	if (t == NULL)
3679		return (0);
3680	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3681}
3682
3683static void
3684ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3685{
3686	uint64_t *t;
3687
3688	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3689	if (t == NULL)
3690		return;
3691	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3692}
3693
3694static void
3695ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3696{
3697	uint64_t *p;
3698	u_int i;
3699
3700	i = residx/CTL_MAX_INIT_PER_PORT;
3701	if (lun->pr_keys[i] != NULL)
3702		return;
3703	mtx_unlock(&lun->lun_lock);
3704	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3705	    M_WAITOK | M_ZERO);
3706	mtx_lock(&lun->lun_lock);
3707	if (lun->pr_keys[i] == NULL)
3708		lun->pr_keys[i] = p;
3709	else
3710		free(p, M_CTL);
3711}
3712
3713static void
3714ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3715{
3716	uint64_t *t;
3717
3718	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3719	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3720	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3721}
3722
3723/*
3724 * ctl_softc, pool_name, total_ctl_io are passed in.
3725 * npool is passed out.
3726 */
3727int
3728ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3729		uint32_t total_ctl_io, void **npool)
3730{
3731	struct ctl_io_pool *pool;
3732
3733	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3734					    M_NOWAIT | M_ZERO);
3735	if (pool == NULL)
3736		return (ENOMEM);
3737
3738	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3739	pool->ctl_softc = ctl_softc;
3740#ifdef IO_POOLS
3741	pool->zone = uma_zsecond_create(pool->name, NULL,
3742	    NULL, NULL, NULL, ctl_softc->io_zone);
3743	/* uma_prealloc(pool->zone, total_ctl_io); */
3744#else
3745	pool->zone = ctl_softc->io_zone;
3746#endif
3747
3748	*npool = pool;
3749	return (0);
3750}
3751
3752void
3753ctl_pool_free(struct ctl_io_pool *pool)
3754{
3755
3756	if (pool == NULL)
3757		return;
3758
3759#ifdef IO_POOLS
3760	uma_zdestroy(pool->zone);
3761#endif
3762	free(pool, M_CTL);
3763}
3764
3765union ctl_io *
3766ctl_alloc_io(void *pool_ref)
3767{
3768	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3769	union ctl_io *io;
3770
3771	io = uma_zalloc(pool->zone, M_WAITOK);
3772	if (io != NULL) {
3773		io->io_hdr.pool = pool_ref;
3774		CTL_SOFTC(io) = pool->ctl_softc;
3775	}
3776	return (io);
3777}
3778
3779union ctl_io *
3780ctl_alloc_io_nowait(void *pool_ref)
3781{
3782	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3783	union ctl_io *io;
3784
3785	io = uma_zalloc(pool->zone, M_NOWAIT);
3786	if (io != NULL) {
3787		io->io_hdr.pool = pool_ref;
3788		CTL_SOFTC(io) = pool->ctl_softc;
3789	}
3790	return (io);
3791}
3792
3793void
3794ctl_free_io(union ctl_io *io)
3795{
3796	struct ctl_io_pool *pool;
3797
3798	if (io == NULL)
3799		return;
3800
3801	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3802	uma_zfree(pool->zone, io);
3803}
3804
3805void
3806ctl_zero_io(union ctl_io *io)
3807{
3808	struct ctl_io_pool *pool;
3809
3810	if (io == NULL)
3811		return;
3812
3813	/*
3814	 * May need to preserve linked list pointers at some point too.
3815	 */
3816	pool = io->io_hdr.pool;
3817	memset(io, 0, sizeof(*io));
3818	io->io_hdr.pool = pool;
3819	CTL_SOFTC(io) = pool->ctl_softc;
3820}
3821
3822int
3823ctl_expand_number(const char *buf, uint64_t *num)
3824{
3825	char *endptr;
3826	uint64_t number;
3827	unsigned shift;
3828
3829	number = strtoq(buf, &endptr, 0);
3830
3831	switch (tolower((unsigned char)*endptr)) {
3832	case 'e':
3833		shift = 60;
3834		break;
3835	case 'p':
3836		shift = 50;
3837		break;
3838	case 't':
3839		shift = 40;
3840		break;
3841	case 'g':
3842		shift = 30;
3843		break;
3844	case 'm':
3845		shift = 20;
3846		break;
3847	case 'k':
3848		shift = 10;
3849		break;
3850	case 'b':
3851	case '\0': /* No unit. */
3852		*num = number;
3853		return (0);
3854	default:
3855		/* Unrecognized unit. */
3856		return (-1);
3857	}
3858
3859	if ((number << shift) >> shift != number) {
3860		/* Overflow */
3861		return (-1);
3862	}
3863	*num = number << shift;
3864	return (0);
3865}
3866
3867
3868/*
3869 * This routine could be used in the future to load default and/or saved
3870 * mode page parameters for a particuar lun.
3871 */
3872static int
3873ctl_init_page_index(struct ctl_lun *lun)
3874{
3875	int i, page_code;
3876	struct ctl_page_index *page_index;
3877	const char *value;
3878	uint64_t ival;
3879
3880	memcpy(&lun->mode_pages.index, page_index_template,
3881	       sizeof(page_index_template));
3882
3883	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3884
3885		page_index = &lun->mode_pages.index[i];
3886		if (lun->be_lun->lun_type == T_DIRECT &&
3887		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3888			continue;
3889		if (lun->be_lun->lun_type == T_PROCESSOR &&
3890		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3891			continue;
3892		if (lun->be_lun->lun_type == T_CDROM &&
3893		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3894			continue;
3895
3896		page_code = page_index->page_code & SMPH_PC_MASK;
3897		switch (page_code) {
3898		case SMS_RW_ERROR_RECOVERY_PAGE: {
3899			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3900			    ("subpage %#x for page %#x is incorrect!",
3901			    page_index->subpage, page_code));
3902			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3903			       &rw_er_page_default,
3904			       sizeof(rw_er_page_default));
3905			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3906			       &rw_er_page_changeable,
3907			       sizeof(rw_er_page_changeable));
3908			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3909			       &rw_er_page_default,
3910			       sizeof(rw_er_page_default));
3911			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3912			       &rw_er_page_default,
3913			       sizeof(rw_er_page_default));
3914			page_index->page_data =
3915				(uint8_t *)lun->mode_pages.rw_er_page;
3916			break;
3917		}
3918		case SMS_FORMAT_DEVICE_PAGE: {
3919			struct scsi_format_page *format_page;
3920
3921			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3922			    ("subpage %#x for page %#x is incorrect!",
3923			    page_index->subpage, page_code));
3924
3925			/*
3926			 * Sectors per track are set above.  Bytes per
3927			 * sector need to be set here on a per-LUN basis.
3928			 */
3929			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3930			       &format_page_default,
3931			       sizeof(format_page_default));
3932			memcpy(&lun->mode_pages.format_page[
3933			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3934			       sizeof(format_page_changeable));
3935			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3936			       &format_page_default,
3937			       sizeof(format_page_default));
3938			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3939			       &format_page_default,
3940			       sizeof(format_page_default));
3941
3942			format_page = &lun->mode_pages.format_page[
3943				CTL_PAGE_CURRENT];
3944			scsi_ulto2b(lun->be_lun->blocksize,
3945				    format_page->bytes_per_sector);
3946
3947			format_page = &lun->mode_pages.format_page[
3948				CTL_PAGE_DEFAULT];
3949			scsi_ulto2b(lun->be_lun->blocksize,
3950				    format_page->bytes_per_sector);
3951
3952			format_page = &lun->mode_pages.format_page[
3953				CTL_PAGE_SAVED];
3954			scsi_ulto2b(lun->be_lun->blocksize,
3955				    format_page->bytes_per_sector);
3956
3957			page_index->page_data =
3958				(uint8_t *)lun->mode_pages.format_page;
3959			break;
3960		}
3961		case SMS_RIGID_DISK_PAGE: {
3962			struct scsi_rigid_disk_page *rigid_disk_page;
3963			uint32_t sectors_per_cylinder;
3964			uint64_t cylinders;
3965#ifndef	__XSCALE__
3966			int shift;
3967#endif /* !__XSCALE__ */
3968
3969			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3970			    ("subpage %#x for page %#x is incorrect!",
3971			    page_index->subpage, page_code));
3972
3973			/*
3974			 * Rotation rate and sectors per track are set
3975			 * above.  We calculate the cylinders here based on
3976			 * capacity.  Due to the number of heads and
3977			 * sectors per track we're using, smaller arrays
3978			 * may turn out to have 0 cylinders.  Linux and
3979			 * FreeBSD don't pay attention to these mode pages
3980			 * to figure out capacity, but Solaris does.  It
3981			 * seems to deal with 0 cylinders just fine, and
3982			 * works out a fake geometry based on the capacity.
3983			 */
3984			memcpy(&lun->mode_pages.rigid_disk_page[
3985			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3986			       sizeof(rigid_disk_page_default));
3987			memcpy(&lun->mode_pages.rigid_disk_page[
3988			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3989			       sizeof(rigid_disk_page_changeable));
3990
3991			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3992				CTL_DEFAULT_HEADS;
3993
3994			/*
3995			 * The divide method here will be more accurate,
3996			 * probably, but results in floating point being
3997			 * used in the kernel on i386 (__udivdi3()).  On the
3998			 * XScale, though, __udivdi3() is implemented in
3999			 * software.
4000			 *
4001			 * The shift method for cylinder calculation is
4002			 * accurate if sectors_per_cylinder is a power of
4003			 * 2.  Otherwise it might be slightly off -- you
4004			 * might have a bit of a truncation problem.
4005			 */
4006#ifdef	__XSCALE__
4007			cylinders = (lun->be_lun->maxlba + 1) /
4008				sectors_per_cylinder;
4009#else
4010			for (shift = 31; shift > 0; shift--) {
4011				if (sectors_per_cylinder & (1 << shift))
4012					break;
4013			}
4014			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4015#endif
4016
4017			/*
4018			 * We've basically got 3 bytes, or 24 bits for the
4019			 * cylinder size in the mode page.  If we're over,
4020			 * just round down to 2^24.
4021			 */
4022			if (cylinders > 0xffffff)
4023				cylinders = 0xffffff;
4024
4025			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4026				CTL_PAGE_DEFAULT];
4027			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4028
4029			if ((value = ctl_get_opt(&lun->be_lun->options,
4030			    "rpm")) != NULL) {
4031				scsi_ulto2b(strtol(value, NULL, 0),
4032				     rigid_disk_page->rotation_rate);
4033			}
4034
4035			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4036			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4037			       sizeof(rigid_disk_page_default));
4038			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4039			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4040			       sizeof(rigid_disk_page_default));
4041
4042			page_index->page_data =
4043				(uint8_t *)lun->mode_pages.rigid_disk_page;
4044			break;
4045		}
4046		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4047			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4048			    ("subpage %#x for page %#x is incorrect!",
4049			    page_index->subpage, page_code));
4050			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4051			       &verify_er_page_default,
4052			       sizeof(verify_er_page_default));
4053			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4054			       &verify_er_page_changeable,
4055			       sizeof(verify_er_page_changeable));
4056			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4057			       &verify_er_page_default,
4058			       sizeof(verify_er_page_default));
4059			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4060			       &verify_er_page_default,
4061			       sizeof(verify_er_page_default));
4062			page_index->page_data =
4063				(uint8_t *)lun->mode_pages.verify_er_page;
4064			break;
4065		}
4066		case SMS_CACHING_PAGE: {
4067			struct scsi_caching_page *caching_page;
4068
4069			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4070			    ("subpage %#x for page %#x is incorrect!",
4071			    page_index->subpage, page_code));
4072			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4073			       &caching_page_default,
4074			       sizeof(caching_page_default));
4075			memcpy(&lun->mode_pages.caching_page[
4076			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4077			       sizeof(caching_page_changeable));
4078			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4079			       &caching_page_default,
4080			       sizeof(caching_page_default));
4081			caching_page = &lun->mode_pages.caching_page[
4082			    CTL_PAGE_SAVED];
4083			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4084			if (value != NULL && strcmp(value, "off") == 0)
4085				caching_page->flags1 &= ~SCP_WCE;
4086			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4087			if (value != NULL && strcmp(value, "off") == 0)
4088				caching_page->flags1 |= SCP_RCD;
4089			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4090			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4091			       sizeof(caching_page_default));
4092			page_index->page_data =
4093				(uint8_t *)lun->mode_pages.caching_page;
4094			break;
4095		}
4096		case SMS_CONTROL_MODE_PAGE: {
4097			switch (page_index->subpage) {
4098			case SMS_SUBPAGE_PAGE_0: {
4099				struct scsi_control_page *control_page;
4100
4101				memcpy(&lun->mode_pages.control_page[
4102				    CTL_PAGE_DEFAULT],
4103				       &control_page_default,
4104				       sizeof(control_page_default));
4105				memcpy(&lun->mode_pages.control_page[
4106				    CTL_PAGE_CHANGEABLE],
4107				       &control_page_changeable,
4108				       sizeof(control_page_changeable));
4109				memcpy(&lun->mode_pages.control_page[
4110				    CTL_PAGE_SAVED],
4111				       &control_page_default,
4112				       sizeof(control_page_default));
4113				control_page = &lun->mode_pages.control_page[
4114				    CTL_PAGE_SAVED];
4115				value = ctl_get_opt(&lun->be_lun->options,
4116				    "reordering");
4117				if (value != NULL &&
4118				    strcmp(value, "unrestricted") == 0) {
4119					control_page->queue_flags &=
4120					    ~SCP_QUEUE_ALG_MASK;
4121					control_page->queue_flags |=
4122					    SCP_QUEUE_ALG_UNRESTRICTED;
4123				}
4124				memcpy(&lun->mode_pages.control_page[
4125				    CTL_PAGE_CURRENT],
4126				       &lun->mode_pages.control_page[
4127				    CTL_PAGE_SAVED],
4128				       sizeof(control_page_default));
4129				page_index->page_data =
4130				    (uint8_t *)lun->mode_pages.control_page;
4131				break;
4132			}
4133			case 0x01:
4134				memcpy(&lun->mode_pages.control_ext_page[
4135				    CTL_PAGE_DEFAULT],
4136				       &control_ext_page_default,
4137				       sizeof(control_ext_page_default));
4138				memcpy(&lun->mode_pages.control_ext_page[
4139				    CTL_PAGE_CHANGEABLE],
4140				       &control_ext_page_changeable,
4141				       sizeof(control_ext_page_changeable));
4142				memcpy(&lun->mode_pages.control_ext_page[
4143				    CTL_PAGE_SAVED],
4144				       &control_ext_page_default,
4145				       sizeof(control_ext_page_default));
4146				memcpy(&lun->mode_pages.control_ext_page[
4147				    CTL_PAGE_CURRENT],
4148				       &lun->mode_pages.control_ext_page[
4149				    CTL_PAGE_SAVED],
4150				       sizeof(control_ext_page_default));
4151				page_index->page_data =
4152				    (uint8_t *)lun->mode_pages.control_ext_page;
4153				break;
4154			default:
4155				panic("subpage %#x for page %#x is incorrect!",
4156				      page_index->subpage, page_code);
4157			}
4158			break;
4159		}
4160		case SMS_INFO_EXCEPTIONS_PAGE: {
4161			switch (page_index->subpage) {
4162			case SMS_SUBPAGE_PAGE_0:
4163				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4164				       &ie_page_default,
4165				       sizeof(ie_page_default));
4166				memcpy(&lun->mode_pages.ie_page[
4167				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4168				       sizeof(ie_page_changeable));
4169				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4170				       &ie_page_default,
4171				       sizeof(ie_page_default));
4172				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4173				       &ie_page_default,
4174				       sizeof(ie_page_default));
4175				page_index->page_data =
4176					(uint8_t *)lun->mode_pages.ie_page;
4177				break;
4178			case 0x02: {
4179				struct ctl_logical_block_provisioning_page *page;
4180
4181				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4182				       &lbp_page_default,
4183				       sizeof(lbp_page_default));
4184				memcpy(&lun->mode_pages.lbp_page[
4185				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4186				       sizeof(lbp_page_changeable));
4187				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4188				       &lbp_page_default,
4189				       sizeof(lbp_page_default));
4190				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4191				value = ctl_get_opt(&lun->be_lun->options,
4192				    "avail-threshold");
4193				if (value != NULL &&
4194				    ctl_expand_number(value, &ival) == 0) {
4195					page->descr[0].flags |= SLBPPD_ENABLED |
4196					    SLBPPD_ARMING_DEC;
4197					if (lun->be_lun->blocksize)
4198						ival /= lun->be_lun->blocksize;
4199					else
4200						ival /= 512;
4201					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4202					    page->descr[0].count);
4203				}
4204				value = ctl_get_opt(&lun->be_lun->options,
4205				    "used-threshold");
4206				if (value != NULL &&
4207				    ctl_expand_number(value, &ival) == 0) {
4208					page->descr[1].flags |= SLBPPD_ENABLED |
4209					    SLBPPD_ARMING_INC;
4210					if (lun->be_lun->blocksize)
4211						ival /= lun->be_lun->blocksize;
4212					else
4213						ival /= 512;
4214					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4215					    page->descr[1].count);
4216				}
4217				value = ctl_get_opt(&lun->be_lun->options,
4218				    "pool-avail-threshold");
4219				if (value != NULL &&
4220				    ctl_expand_number(value, &ival) == 0) {
4221					page->descr[2].flags |= SLBPPD_ENABLED |
4222					    SLBPPD_ARMING_DEC;
4223					if (lun->be_lun->blocksize)
4224						ival /= lun->be_lun->blocksize;
4225					else
4226						ival /= 512;
4227					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4228					    page->descr[2].count);
4229				}
4230				value = ctl_get_opt(&lun->be_lun->options,
4231				    "pool-used-threshold");
4232				if (value != NULL &&
4233				    ctl_expand_number(value, &ival) == 0) {
4234					page->descr[3].flags |= SLBPPD_ENABLED |
4235					    SLBPPD_ARMING_INC;
4236					if (lun->be_lun->blocksize)
4237						ival /= lun->be_lun->blocksize;
4238					else
4239						ival /= 512;
4240					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4241					    page->descr[3].count);
4242				}
4243				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4244				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4245				       sizeof(lbp_page_default));
4246				page_index->page_data =
4247					(uint8_t *)lun->mode_pages.lbp_page;
4248				break;
4249			}
4250			default:
4251				panic("subpage %#x for page %#x is incorrect!",
4252				      page_index->subpage, page_code);
4253			}
4254			break;
4255		}
4256		case SMS_CDDVD_CAPS_PAGE:{
4257			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4258			    ("subpage %#x for page %#x is incorrect!",
4259			    page_index->subpage, page_code));
4260			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4261			       &cddvd_page_default,
4262			       sizeof(cddvd_page_default));
4263			memcpy(&lun->mode_pages.cddvd_page[
4264			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4265			       sizeof(cddvd_page_changeable));
4266			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4267			       &cddvd_page_default,
4268			       sizeof(cddvd_page_default));
4269			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4270			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4271			       sizeof(cddvd_page_default));
4272			page_index->page_data =
4273				(uint8_t *)lun->mode_pages.cddvd_page;
4274			break;
4275		}
4276		default:
4277			panic("invalid page code value %#x", page_code);
4278		}
4279	}
4280
4281	return (CTL_RETVAL_COMPLETE);
4282}
4283
4284static int
4285ctl_init_log_page_index(struct ctl_lun *lun)
4286{
4287	struct ctl_page_index *page_index;
4288	int i, j, k, prev;
4289
4290	memcpy(&lun->log_pages.index, log_page_index_template,
4291	       sizeof(log_page_index_template));
4292
4293	prev = -1;
4294	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4295
4296		page_index = &lun->log_pages.index[i];
4297		if (lun->be_lun->lun_type == T_DIRECT &&
4298		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4299			continue;
4300		if (lun->be_lun->lun_type == T_PROCESSOR &&
4301		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4302			continue;
4303		if (lun->be_lun->lun_type == T_CDROM &&
4304		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4305			continue;
4306
4307		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4308		    lun->backend->lun_attr == NULL)
4309			continue;
4310
4311		if (page_index->page_code != prev) {
4312			lun->log_pages.pages_page[j] = page_index->page_code;
4313			prev = page_index->page_code;
4314			j++;
4315		}
4316		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4317		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4318		k++;
4319	}
4320	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4321	lun->log_pages.index[0].page_len = j;
4322	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4323	lun->log_pages.index[1].page_len = k * 2;
4324	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4325	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4326	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4327	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4328	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4329	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4330
4331	return (CTL_RETVAL_COMPLETE);
4332}
4333
4334static int
4335hex2bin(const char *str, uint8_t *buf, int buf_size)
4336{
4337	int i;
4338	u_char c;
4339
4340	memset(buf, 0, buf_size);
4341	while (isspace(str[0]))
4342		str++;
4343	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4344		str += 2;
4345	buf_size *= 2;
4346	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4347		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4348			str++;
4349		c = str[i];
4350		if (isdigit(c))
4351			c -= '0';
4352		else if (isalpha(c))
4353			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4354		else
4355			break;
4356		if (c >= 16)
4357			break;
4358		if ((i & 1) == 0)
4359			buf[i / 2] |= (c << 4);
4360		else
4361			buf[i / 2] |= c;
4362	}
4363	return ((i + 1) / 2);
4364}
4365
4366/*
4367 * LUN allocation.
4368 *
4369 * Requirements:
4370 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4371 *   wants us to allocate the LUN and he can block.
4372 * - ctl_softc is always set
4373 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4374 *
4375 * Returns 0 for success, non-zero (errno) for failure.
4376 */
4377static int
4378ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4379	      struct ctl_be_lun *const be_lun)
4380{
4381	struct ctl_lun *nlun, *lun;
4382	struct scsi_vpd_id_descriptor *desc;
4383	struct scsi_vpd_id_t10 *t10id;
4384	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4385	int lun_number, i, lun_malloced;
4386	int devidlen, idlen1, idlen2 = 0, len;
4387
4388	if (be_lun == NULL)
4389		return (EINVAL);
4390
4391	/*
4392	 * We currently only support Direct Access or Processor LUN types.
4393	 */
4394	switch (be_lun->lun_type) {
4395	case T_DIRECT:
4396	case T_PROCESSOR:
4397	case T_CDROM:
4398		break;
4399	case T_SEQUENTIAL:
4400	case T_CHANGER:
4401	default:
4402		be_lun->lun_config_status(be_lun->be_lun,
4403					  CTL_LUN_CONFIG_FAILURE);
4404		break;
4405	}
4406	if (ctl_lun == NULL) {
4407		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4408		lun_malloced = 1;
4409	} else {
4410		lun_malloced = 0;
4411		lun = ctl_lun;
4412	}
4413
4414	memset(lun, 0, sizeof(*lun));
4415	if (lun_malloced)
4416		lun->flags = CTL_LUN_MALLOCED;
4417
4418	/* Generate LUN ID. */
4419	devidlen = max(CTL_DEVID_MIN_LEN,
4420	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4421	idlen1 = sizeof(*t10id) + devidlen;
4422	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4423	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4424	if (scsiname != NULL) {
4425		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4426		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4427	}
4428	eui = ctl_get_opt(&be_lun->options, "eui");
4429	if (eui != NULL) {
4430		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4431	}
4432	naa = ctl_get_opt(&be_lun->options, "naa");
4433	if (naa != NULL) {
4434		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4435	}
4436	uuid = ctl_get_opt(&be_lun->options, "uuid");
4437	if (uuid != NULL) {
4438		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4439	}
4440	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4441	    M_CTL, M_WAITOK | M_ZERO);
4442	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4443	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4444	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4445	desc->length = idlen1;
4446	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4447	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4448	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4449		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4450	} else {
4451		strncpy(t10id->vendor, vendor,
4452		    min(sizeof(t10id->vendor), strlen(vendor)));
4453	}
4454	strncpy((char *)t10id->vendor_spec_id,
4455	    (char *)be_lun->device_id, devidlen);
4456	if (scsiname != NULL) {
4457		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4458		    desc->length);
4459		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4460		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4461		    SVPD_ID_TYPE_SCSI_NAME;
4462		desc->length = idlen2;
4463		strlcpy(desc->identifier, scsiname, idlen2);
4464	}
4465	if (eui != NULL) {
4466		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4467		    desc->length);
4468		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4469		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4470		    SVPD_ID_TYPE_EUI64;
4471		desc->length = hex2bin(eui, desc->identifier, 16);
4472		desc->length = desc->length > 12 ? 16 :
4473		    (desc->length > 8 ? 12 : 8);
4474		len -= 16 - desc->length;
4475	}
4476	if (naa != NULL) {
4477		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4478		    desc->length);
4479		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4480		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4481		    SVPD_ID_TYPE_NAA;
4482		desc->length = hex2bin(naa, desc->identifier, 16);
4483		desc->length = desc->length > 8 ? 16 : 8;
4484		len -= 16 - desc->length;
4485	}
4486	if (uuid != NULL) {
4487		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4488		    desc->length);
4489		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4490		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4491		    SVPD_ID_TYPE_UUID;
4492		desc->identifier[0] = 0x10;
4493		hex2bin(uuid, &desc->identifier[2], 16);
4494		desc->length = 18;
4495	}
4496	lun->lun_devid->len = len;
4497
4498	mtx_lock(&ctl_softc->ctl_lock);
4499	/*
4500	 * See if the caller requested a particular LUN number.  If so, see
4501	 * if it is available.  Otherwise, allocate the first available LUN.
4502	 */
4503	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4504		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4505		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4506			mtx_unlock(&ctl_softc->ctl_lock);
4507			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4508				printf("ctl: requested LUN ID %d is higher "
4509				       "than CTL_MAX_LUNS - 1 (%d)\n",
4510				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4511			} else {
4512				/*
4513				 * XXX KDM return an error, or just assign
4514				 * another LUN ID in this case??
4515				 */
4516				printf("ctl: requested LUN ID %d is already "
4517				       "in use\n", be_lun->req_lun_id);
4518			}
4519			if (lun->flags & CTL_LUN_MALLOCED)
4520				free(lun, M_CTL);
4521			be_lun->lun_config_status(be_lun->be_lun,
4522						  CTL_LUN_CONFIG_FAILURE);
4523			return (ENOSPC);
4524		}
4525		lun_number = be_lun->req_lun_id;
4526	} else {
4527		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4528		if (lun_number == -1) {
4529			mtx_unlock(&ctl_softc->ctl_lock);
4530			printf("ctl: can't allocate LUN, out of LUNs\n");
4531			if (lun->flags & CTL_LUN_MALLOCED)
4532				free(lun, M_CTL);
4533			be_lun->lun_config_status(be_lun->be_lun,
4534						  CTL_LUN_CONFIG_FAILURE);
4535			return (ENOSPC);
4536		}
4537	}
4538	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4539
4540	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4541	lun->lun = lun_number;
4542	lun->be_lun = be_lun;
4543	/*
4544	 * The processor LUN is always enabled.  Disk LUNs come on line
4545	 * disabled, and must be enabled by the backend.
4546	 */
4547	lun->flags |= CTL_LUN_DISABLED;
4548	lun->backend = be_lun->be;
4549	be_lun->ctl_lun = lun;
4550	be_lun->lun_id = lun_number;
4551	atomic_add_int(&be_lun->be->num_luns, 1);
4552	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4553		lun->flags |= CTL_LUN_EJECTED;
4554	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4555		lun->flags |= CTL_LUN_NO_MEDIA;
4556	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4557		lun->flags |= CTL_LUN_STOPPED;
4558
4559	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4560		lun->flags |= CTL_LUN_PRIMARY_SC;
4561
4562	value = ctl_get_opt(&be_lun->options, "removable");
4563	if (value != NULL) {
4564		if (strcmp(value, "on") == 0)
4565			lun->flags |= CTL_LUN_REMOVABLE;
4566	} else if (be_lun->lun_type == T_CDROM)
4567		lun->flags |= CTL_LUN_REMOVABLE;
4568
4569	lun->ctl_softc = ctl_softc;
4570#ifdef CTL_TIME_IO
4571	lun->last_busy = getsbinuptime();
4572#endif
4573	TAILQ_INIT(&lun->ooa_queue);
4574	TAILQ_INIT(&lun->blocked_queue);
4575	STAILQ_INIT(&lun->error_list);
4576	lun->ie_reported = 1;
4577	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4578	ctl_tpc_lun_init(lun);
4579
4580	/*
4581	 * Initialize the mode and log page index.
4582	 */
4583	ctl_init_page_index(lun);
4584	ctl_init_log_page_index(lun);
4585
4586	/*
4587	 * Now, before we insert this lun on the lun list, set the lun
4588	 * inventory changed UA for all other luns.
4589	 */
4590	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4591		mtx_lock(&nlun->lun_lock);
4592		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4593		mtx_unlock(&nlun->lun_lock);
4594	}
4595
4596	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4597
4598	ctl_softc->ctl_luns[lun_number] = lun;
4599
4600	ctl_softc->num_luns++;
4601
4602	/* Setup statistics gathering */
4603	lun->stats.device_type = be_lun->lun_type;
4604	lun->stats.lun_number = lun_number;
4605	lun->stats.blocksize = be_lun->blocksize;
4606	if (be_lun->blocksize == 0)
4607		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4608	for (i = 0;i < CTL_MAX_PORTS;i++)
4609		lun->stats.ports[i].targ_port = i;
4610
4611	mtx_unlock(&ctl_softc->ctl_lock);
4612
4613	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4614	return (0);
4615}
4616
4617/*
4618 * Delete a LUN.
4619 * Assumptions:
4620 * - LUN has already been marked invalid and any pending I/O has been taken
4621 *   care of.
4622 */
4623static int
4624ctl_free_lun(struct ctl_lun *lun)
4625{
4626	struct ctl_softc *softc = lun->ctl_softc;
4627	struct ctl_lun *nlun;
4628	int i;
4629
4630	mtx_assert(&softc->ctl_lock, MA_OWNED);
4631
4632	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4633
4634	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4635
4636	softc->ctl_luns[lun->lun] = NULL;
4637
4638	if (!TAILQ_EMPTY(&lun->ooa_queue))
4639		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4640
4641	softc->num_luns--;
4642
4643	/*
4644	 * Tell the backend to free resources, if this LUN has a backend.
4645	 */
4646	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4647	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4648
4649	lun->ie_reportcnt = UINT32_MAX;
4650	callout_drain(&lun->ie_callout);
4651
4652	ctl_tpc_lun_shutdown(lun);
4653	mtx_destroy(&lun->lun_lock);
4654	free(lun->lun_devid, M_CTL);
4655	for (i = 0; i < CTL_MAX_PORTS; i++)
4656		free(lun->pending_ua[i], M_CTL);
4657	for (i = 0; i < CTL_MAX_PORTS; i++)
4658		free(lun->pr_keys[i], M_CTL);
4659	free(lun->write_buffer, M_CTL);
4660	if (lun->flags & CTL_LUN_MALLOCED)
4661		free(lun, M_CTL);
4662
4663	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4664		mtx_lock(&nlun->lun_lock);
4665		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4666		mtx_unlock(&nlun->lun_lock);
4667	}
4668
4669	return (0);
4670}
4671
4672static void
4673ctl_create_lun(struct ctl_be_lun *be_lun)
4674{
4675
4676	/*
4677	 * ctl_alloc_lun() should handle all potential failure cases.
4678	 */
4679	ctl_alloc_lun(control_softc, NULL, be_lun);
4680}
4681
4682int
4683ctl_add_lun(struct ctl_be_lun *be_lun)
4684{
4685	struct ctl_softc *softc = control_softc;
4686
4687	mtx_lock(&softc->ctl_lock);
4688	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4689	mtx_unlock(&softc->ctl_lock);
4690	wakeup(&softc->pending_lun_queue);
4691
4692	return (0);
4693}
4694
4695int
4696ctl_enable_lun(struct ctl_be_lun *be_lun)
4697{
4698	struct ctl_softc *softc;
4699	struct ctl_port *port, *nport;
4700	struct ctl_lun *lun;
4701	int retval;
4702
4703	lun = (struct ctl_lun *)be_lun->ctl_lun;
4704	softc = lun->ctl_softc;
4705
4706	mtx_lock(&softc->ctl_lock);
4707	mtx_lock(&lun->lun_lock);
4708	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4709		/*
4710		 * eh?  Why did we get called if the LUN is already
4711		 * enabled?
4712		 */
4713		mtx_unlock(&lun->lun_lock);
4714		mtx_unlock(&softc->ctl_lock);
4715		return (0);
4716	}
4717	lun->flags &= ~CTL_LUN_DISABLED;
4718	mtx_unlock(&lun->lun_lock);
4719
4720	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4721		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4722		    port->lun_map != NULL || port->lun_enable == NULL)
4723			continue;
4724
4725		/*
4726		 * Drop the lock while we call the FETD's enable routine.
4727		 * This can lead to a callback into CTL (at least in the
4728		 * case of the internal initiator frontend.
4729		 */
4730		mtx_unlock(&softc->ctl_lock);
4731		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4732		mtx_lock(&softc->ctl_lock);
4733		if (retval != 0) {
4734			printf("%s: FETD %s port %d returned error "
4735			       "%d for lun_enable on lun %jd\n",
4736			       __func__, port->port_name, port->targ_port,
4737			       retval, (intmax_t)lun->lun);
4738		}
4739	}
4740
4741	mtx_unlock(&softc->ctl_lock);
4742	ctl_isc_announce_lun(lun);
4743
4744	return (0);
4745}
4746
4747int
4748ctl_disable_lun(struct ctl_be_lun *be_lun)
4749{
4750	struct ctl_softc *softc;
4751	struct ctl_port *port;
4752	struct ctl_lun *lun;
4753	int retval;
4754
4755	lun = (struct ctl_lun *)be_lun->ctl_lun;
4756	softc = lun->ctl_softc;
4757
4758	mtx_lock(&softc->ctl_lock);
4759	mtx_lock(&lun->lun_lock);
4760	if (lun->flags & CTL_LUN_DISABLED) {
4761		mtx_unlock(&lun->lun_lock);
4762		mtx_unlock(&softc->ctl_lock);
4763		return (0);
4764	}
4765	lun->flags |= CTL_LUN_DISABLED;
4766	mtx_unlock(&lun->lun_lock);
4767
4768	STAILQ_FOREACH(port, &softc->port_list, links) {
4769		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4770		    port->lun_map != NULL || port->lun_disable == NULL)
4771			continue;
4772
4773		/*
4774		 * Drop the lock before we call the frontend's disable
4775		 * routine, to avoid lock order reversals.
4776		 *
4777		 * XXX KDM what happens if the frontend list changes while
4778		 * we're traversing it?  It's unlikely, but should be handled.
4779		 */
4780		mtx_unlock(&softc->ctl_lock);
4781		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4782		mtx_lock(&softc->ctl_lock);
4783		if (retval != 0) {
4784			printf("%s: FETD %s port %d returned error "
4785			       "%d for lun_disable on lun %jd\n",
4786			       __func__, port->port_name, port->targ_port,
4787			       retval, (intmax_t)lun->lun);
4788		}
4789	}
4790
4791	mtx_unlock(&softc->ctl_lock);
4792	ctl_isc_announce_lun(lun);
4793
4794	return (0);
4795}
4796
4797int
4798ctl_start_lun(struct ctl_be_lun *be_lun)
4799{
4800	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4801
4802	mtx_lock(&lun->lun_lock);
4803	lun->flags &= ~CTL_LUN_STOPPED;
4804	mtx_unlock(&lun->lun_lock);
4805	return (0);
4806}
4807
4808int
4809ctl_stop_lun(struct ctl_be_lun *be_lun)
4810{
4811	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4812
4813	mtx_lock(&lun->lun_lock);
4814	lun->flags |= CTL_LUN_STOPPED;
4815	mtx_unlock(&lun->lun_lock);
4816	return (0);
4817}
4818
4819int
4820ctl_lun_no_media(struct ctl_be_lun *be_lun)
4821{
4822	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4823
4824	mtx_lock(&lun->lun_lock);
4825	lun->flags |= CTL_LUN_NO_MEDIA;
4826	mtx_unlock(&lun->lun_lock);
4827	return (0);
4828}
4829
4830int
4831ctl_lun_has_media(struct ctl_be_lun *be_lun)
4832{
4833	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4834	union ctl_ha_msg msg;
4835
4836	mtx_lock(&lun->lun_lock);
4837	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4838	if (lun->flags & CTL_LUN_REMOVABLE)
4839		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4840	mtx_unlock(&lun->lun_lock);
4841	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4842	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4843		bzero(&msg.ua, sizeof(msg.ua));
4844		msg.hdr.msg_type = CTL_MSG_UA;
4845		msg.hdr.nexus.initid = -1;
4846		msg.hdr.nexus.targ_port = -1;
4847		msg.hdr.nexus.targ_lun = lun->lun;
4848		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4849		msg.ua.ua_all = 1;
4850		msg.ua.ua_set = 1;
4851		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4852		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4853		    M_WAITOK);
4854	}
4855	return (0);
4856}
4857
4858int
4859ctl_lun_ejected(struct ctl_be_lun *be_lun)
4860{
4861	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4862
4863	mtx_lock(&lun->lun_lock);
4864	lun->flags |= CTL_LUN_EJECTED;
4865	mtx_unlock(&lun->lun_lock);
4866	return (0);
4867}
4868
4869int
4870ctl_lun_primary(struct ctl_be_lun *be_lun)
4871{
4872	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4873
4874	mtx_lock(&lun->lun_lock);
4875	lun->flags |= CTL_LUN_PRIMARY_SC;
4876	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4877	mtx_unlock(&lun->lun_lock);
4878	ctl_isc_announce_lun(lun);
4879	return (0);
4880}
4881
4882int
4883ctl_lun_secondary(struct ctl_be_lun *be_lun)
4884{
4885	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4886
4887	mtx_lock(&lun->lun_lock);
4888	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4889	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4890	mtx_unlock(&lun->lun_lock);
4891	ctl_isc_announce_lun(lun);
4892	return (0);
4893}
4894
4895int
4896ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4897{
4898	struct ctl_softc *softc;
4899	struct ctl_lun *lun;
4900
4901	lun = (struct ctl_lun *)be_lun->ctl_lun;
4902	softc = lun->ctl_softc;
4903
4904	mtx_lock(&lun->lun_lock);
4905
4906	/*
4907	 * The LUN needs to be disabled before it can be marked invalid.
4908	 */
4909	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4910		mtx_unlock(&lun->lun_lock);
4911		return (-1);
4912	}
4913	/*
4914	 * Mark the LUN invalid.
4915	 */
4916	lun->flags |= CTL_LUN_INVALID;
4917
4918	/*
4919	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4920	 * If we have something in the OOA queue, we'll free it when the
4921	 * last I/O completes.
4922	 */
4923	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4924		mtx_unlock(&lun->lun_lock);
4925		mtx_lock(&softc->ctl_lock);
4926		ctl_free_lun(lun);
4927		mtx_unlock(&softc->ctl_lock);
4928	} else
4929		mtx_unlock(&lun->lun_lock);
4930
4931	return (0);
4932}
4933
4934void
4935ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4936{
4937	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4938	union ctl_ha_msg msg;
4939
4940	mtx_lock(&lun->lun_lock);
4941	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4942	mtx_unlock(&lun->lun_lock);
4943	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4944		/* Send msg to other side. */
4945		bzero(&msg.ua, sizeof(msg.ua));
4946		msg.hdr.msg_type = CTL_MSG_UA;
4947		msg.hdr.nexus.initid = -1;
4948		msg.hdr.nexus.targ_port = -1;
4949		msg.hdr.nexus.targ_lun = lun->lun;
4950		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4951		msg.ua.ua_all = 1;
4952		msg.ua.ua_set = 1;
4953		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4954		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4955		    M_WAITOK);
4956	}
4957}
4958
4959/*
4960 * Backend "memory move is complete" callback for requests that never
4961 * make it down to say RAIDCore's configuration code.
4962 */
4963int
4964ctl_config_move_done(union ctl_io *io)
4965{
4966	int retval;
4967
4968	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4969	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4970	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4971
4972	if ((io->io_hdr.port_status != 0) &&
4973	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4974	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4975		/*
4976		 * For hardware error sense keys, the sense key
4977		 * specific value is defined to be a retry count,
4978		 * but we use it to pass back an internal FETD
4979		 * error code.  XXX KDM  Hopefully the FETD is only
4980		 * using 16 bits for an error code, since that's
4981		 * all the space we have in the sks field.
4982		 */
4983		ctl_set_internal_failure(&io->scsiio,
4984					 /*sks_valid*/ 1,
4985					 /*retry_count*/
4986					 io->io_hdr.port_status);
4987	}
4988
4989	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4990		ctl_data_print(io);
4991	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4992	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4993	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4994	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4995		/*
4996		 * XXX KDM just assuming a single pointer here, and not a
4997		 * S/G list.  If we start using S/G lists for config data,
4998		 * we'll need to know how to clean them up here as well.
4999		 */
5000		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5001			free(io->scsiio.kern_data_ptr, M_CTL);
5002		ctl_done(io);
5003		retval = CTL_RETVAL_COMPLETE;
5004	} else {
5005		/*
5006		 * XXX KDM now we need to continue data movement.  Some
5007		 * options:
5008		 * - call ctl_scsiio() again?  We don't do this for data
5009		 *   writes, because for those at least we know ahead of
5010		 *   time where the write will go and how long it is.  For
5011		 *   config writes, though, that information is largely
5012		 *   contained within the write itself, thus we need to
5013		 *   parse out the data again.
5014		 *
5015		 * - Call some other function once the data is in?
5016		 */
5017
5018		/*
5019		 * XXX KDM call ctl_scsiio() again for now, and check flag
5020		 * bits to see whether we're allocated or not.
5021		 */
5022		retval = ctl_scsiio(&io->scsiio);
5023	}
5024	return (retval);
5025}
5026
5027/*
5028 * This gets called by a backend driver when it is done with a
5029 * data_submit method.
5030 */
5031void
5032ctl_data_submit_done(union ctl_io *io)
5033{
5034	/*
5035	 * If the IO_CONT flag is set, we need to call the supplied
5036	 * function to continue processing the I/O, instead of completing
5037	 * the I/O just yet.
5038	 *
5039	 * If there is an error, though, we don't want to keep processing.
5040	 * Instead, just send status back to the initiator.
5041	 */
5042	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5043	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5044	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5045	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5046		io->scsiio.io_cont(io);
5047		return;
5048	}
5049	ctl_done(io);
5050}
5051
5052/*
5053 * This gets called by a backend driver when it is done with a
5054 * configuration write.
5055 */
5056void
5057ctl_config_write_done(union ctl_io *io)
5058{
5059	uint8_t *buf;
5060
5061	/*
5062	 * If the IO_CONT flag is set, we need to call the supplied
5063	 * function to continue processing the I/O, instead of completing
5064	 * the I/O just yet.
5065	 *
5066	 * If there is an error, though, we don't want to keep processing.
5067	 * Instead, just send status back to the initiator.
5068	 */
5069	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5070	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5071	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5072	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5073		io->scsiio.io_cont(io);
5074		return;
5075	}
5076	/*
5077	 * Since a configuration write can be done for commands that actually
5078	 * have data allocated, like write buffer, and commands that have
5079	 * no data, like start/stop unit, we need to check here.
5080	 */
5081	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5082		buf = io->scsiio.kern_data_ptr;
5083	else
5084		buf = NULL;
5085	ctl_done(io);
5086	if (buf)
5087		free(buf, M_CTL);
5088}
5089
5090void
5091ctl_config_read_done(union ctl_io *io)
5092{
5093	uint8_t *buf;
5094
5095	/*
5096	 * If there is some error -- we are done, skip data transfer.
5097	 */
5098	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5099	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5100	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5101		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5102			buf = io->scsiio.kern_data_ptr;
5103		else
5104			buf = NULL;
5105		ctl_done(io);
5106		if (buf)
5107			free(buf, M_CTL);
5108		return;
5109	}
5110
5111	/*
5112	 * If the IO_CONT flag is set, we need to call the supplied
5113	 * function to continue processing the I/O, instead of completing
5114	 * the I/O just yet.
5115	 */
5116	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5117		io->scsiio.io_cont(io);
5118		return;
5119	}
5120
5121	ctl_datamove(io);
5122}
5123
5124/*
5125 * SCSI release command.
5126 */
5127int
5128ctl_scsi_release(struct ctl_scsiio *ctsio)
5129{
5130	struct ctl_lun *lun = CTL_LUN(ctsio);
5131	uint32_t residx;
5132
5133	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5134
5135	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5136
5137	/*
5138	 * XXX KDM right now, we only support LUN reservation.  We don't
5139	 * support 3rd party reservations, or extent reservations, which
5140	 * might actually need the parameter list.  If we've gotten this
5141	 * far, we've got a LUN reservation.  Anything else got kicked out
5142	 * above.  So, according to SPC, ignore the length.
5143	 */
5144
5145	mtx_lock(&lun->lun_lock);
5146
5147	/*
5148	 * According to SPC, it is not an error for an intiator to attempt
5149	 * to release a reservation on a LUN that isn't reserved, or that
5150	 * is reserved by another initiator.  The reservation can only be
5151	 * released, though, by the initiator who made it or by one of
5152	 * several reset type events.
5153	 */
5154	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5155			lun->flags &= ~CTL_LUN_RESERVED;
5156
5157	mtx_unlock(&lun->lun_lock);
5158
5159	ctl_set_success(ctsio);
5160	ctl_done((union ctl_io *)ctsio);
5161	return (CTL_RETVAL_COMPLETE);
5162}
5163
5164int
5165ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5166{
5167	struct ctl_lun *lun = CTL_LUN(ctsio);
5168	uint32_t residx;
5169
5170	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5171
5172	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5173
5174	/*
5175	 * XXX KDM right now, we only support LUN reservation.  We don't
5176	 * support 3rd party reservations, or extent reservations, which
5177	 * might actually need the parameter list.  If we've gotten this
5178	 * far, we've got a LUN reservation.  Anything else got kicked out
5179	 * above.  So, according to SPC, ignore the length.
5180	 */
5181
5182	mtx_lock(&lun->lun_lock);
5183	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5184		ctl_set_reservation_conflict(ctsio);
5185		goto bailout;
5186	}
5187
5188	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5189	if (lun->flags & CTL_LUN_PR_RESERVED) {
5190		ctl_set_success(ctsio);
5191		goto bailout;
5192	}
5193
5194	lun->flags |= CTL_LUN_RESERVED;
5195	lun->res_idx = residx;
5196	ctl_set_success(ctsio);
5197
5198bailout:
5199	mtx_unlock(&lun->lun_lock);
5200	ctl_done((union ctl_io *)ctsio);
5201	return (CTL_RETVAL_COMPLETE);
5202}
5203
5204int
5205ctl_start_stop(struct ctl_scsiio *ctsio)
5206{
5207	struct ctl_lun *lun = CTL_LUN(ctsio);
5208	struct scsi_start_stop_unit *cdb;
5209	int retval;
5210
5211	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5212
5213	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5214
5215	if ((cdb->how & SSS_PC_MASK) == 0) {
5216		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5217		    (cdb->how & SSS_START) == 0) {
5218			uint32_t residx;
5219
5220			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5221			if (ctl_get_prkey(lun, residx) == 0 ||
5222			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5223
5224				ctl_set_reservation_conflict(ctsio);
5225				ctl_done((union ctl_io *)ctsio);
5226				return (CTL_RETVAL_COMPLETE);
5227			}
5228		}
5229
5230		if ((cdb->how & SSS_LOEJ) &&
5231		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5232			ctl_set_invalid_field(ctsio,
5233					      /*sks_valid*/ 1,
5234					      /*command*/ 1,
5235					      /*field*/ 4,
5236					      /*bit_valid*/ 1,
5237					      /*bit*/ 1);
5238			ctl_done((union ctl_io *)ctsio);
5239			return (CTL_RETVAL_COMPLETE);
5240		}
5241
5242		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5243		    lun->prevent_count > 0) {
5244			/* "Medium removal prevented" */
5245			ctl_set_sense(ctsio, /*current_error*/ 1,
5246			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5247			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5248			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5249			ctl_done((union ctl_io *)ctsio);
5250			return (CTL_RETVAL_COMPLETE);
5251		}
5252	}
5253
5254	retval = lun->backend->config_write((union ctl_io *)ctsio);
5255	return (retval);
5256}
5257
5258int
5259ctl_prevent_allow(struct ctl_scsiio *ctsio)
5260{
5261	struct ctl_lun *lun = CTL_LUN(ctsio);
5262	struct scsi_prevent *cdb;
5263	int retval;
5264	uint32_t initidx;
5265
5266	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5267
5268	cdb = (struct scsi_prevent *)ctsio->cdb;
5269
5270	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5271		ctl_set_invalid_opcode(ctsio);
5272		ctl_done((union ctl_io *)ctsio);
5273		return (CTL_RETVAL_COMPLETE);
5274	}
5275
5276	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5277	mtx_lock(&lun->lun_lock);
5278	if ((cdb->how & PR_PREVENT) &&
5279	    ctl_is_set(lun->prevent, initidx) == 0) {
5280		ctl_set_mask(lun->prevent, initidx);
5281		lun->prevent_count++;
5282	} else if ((cdb->how & PR_PREVENT) == 0 &&
5283	    ctl_is_set(lun->prevent, initidx)) {
5284		ctl_clear_mask(lun->prevent, initidx);
5285		lun->prevent_count--;
5286	}
5287	mtx_unlock(&lun->lun_lock);
5288	retval = lun->backend->config_write((union ctl_io *)ctsio);
5289	return (retval);
5290}
5291
5292/*
5293 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5294 * we don't really do anything with the LBA and length fields if the user
5295 * passes them in.  Instead we'll just flush out the cache for the entire
5296 * LUN.
5297 */
5298int
5299ctl_sync_cache(struct ctl_scsiio *ctsio)
5300{
5301	struct ctl_lun *lun = CTL_LUN(ctsio);
5302	struct ctl_lba_len_flags *lbalen;
5303	uint64_t starting_lba;
5304	uint32_t block_count;
5305	int retval;
5306	uint8_t byte2;
5307
5308	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5309
5310	retval = 0;
5311
5312	switch (ctsio->cdb[0]) {
5313	case SYNCHRONIZE_CACHE: {
5314		struct scsi_sync_cache *cdb;
5315		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5316
5317		starting_lba = scsi_4btoul(cdb->begin_lba);
5318		block_count = scsi_2btoul(cdb->lb_count);
5319		byte2 = cdb->byte2;
5320		break;
5321	}
5322	case SYNCHRONIZE_CACHE_16: {
5323		struct scsi_sync_cache_16 *cdb;
5324		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5325
5326		starting_lba = scsi_8btou64(cdb->begin_lba);
5327		block_count = scsi_4btoul(cdb->lb_count);
5328		byte2 = cdb->byte2;
5329		break;
5330	}
5331	default:
5332		ctl_set_invalid_opcode(ctsio);
5333		ctl_done((union ctl_io *)ctsio);
5334		goto bailout;
5335		break; /* NOTREACHED */
5336	}
5337
5338	/*
5339	 * We check the LBA and length, but don't do anything with them.
5340	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5341	 * get flushed.  This check will just help satisfy anyone who wants
5342	 * to see an error for an out of range LBA.
5343	 */
5344	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5345		ctl_set_lba_out_of_range(ctsio,
5346		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5347		ctl_done((union ctl_io *)ctsio);
5348		goto bailout;
5349	}
5350
5351	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5352	lbalen->lba = starting_lba;
5353	lbalen->len = block_count;
5354	lbalen->flags = byte2;
5355	retval = lun->backend->config_write((union ctl_io *)ctsio);
5356
5357bailout:
5358	return (retval);
5359}
5360
5361int
5362ctl_format(struct ctl_scsiio *ctsio)
5363{
5364	struct scsi_format *cdb;
5365	int length, defect_list_len;
5366
5367	CTL_DEBUG_PRINT(("ctl_format\n"));
5368
5369	cdb = (struct scsi_format *)ctsio->cdb;
5370
5371	length = 0;
5372	if (cdb->byte2 & SF_FMTDATA) {
5373		if (cdb->byte2 & SF_LONGLIST)
5374			length = sizeof(struct scsi_format_header_long);
5375		else
5376			length = sizeof(struct scsi_format_header_short);
5377	}
5378
5379	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5380	 && (length > 0)) {
5381		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5382		ctsio->kern_data_len = length;
5383		ctsio->kern_total_len = length;
5384		ctsio->kern_data_resid = 0;
5385		ctsio->kern_rel_offset = 0;
5386		ctsio->kern_sg_entries = 0;
5387		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5388		ctsio->be_move_done = ctl_config_move_done;
5389		ctl_datamove((union ctl_io *)ctsio);
5390
5391		return (CTL_RETVAL_COMPLETE);
5392	}
5393
5394	defect_list_len = 0;
5395
5396	if (cdb->byte2 & SF_FMTDATA) {
5397		if (cdb->byte2 & SF_LONGLIST) {
5398			struct scsi_format_header_long *header;
5399
5400			header = (struct scsi_format_header_long *)
5401				ctsio->kern_data_ptr;
5402
5403			defect_list_len = scsi_4btoul(header->defect_list_len);
5404			if (defect_list_len != 0) {
5405				ctl_set_invalid_field(ctsio,
5406						      /*sks_valid*/ 1,
5407						      /*command*/ 0,
5408						      /*field*/ 2,
5409						      /*bit_valid*/ 0,
5410						      /*bit*/ 0);
5411				goto bailout;
5412			}
5413		} else {
5414			struct scsi_format_header_short *header;
5415
5416			header = (struct scsi_format_header_short *)
5417				ctsio->kern_data_ptr;
5418
5419			defect_list_len = scsi_2btoul(header->defect_list_len);
5420			if (defect_list_len != 0) {
5421				ctl_set_invalid_field(ctsio,
5422						      /*sks_valid*/ 1,
5423						      /*command*/ 0,
5424						      /*field*/ 2,
5425						      /*bit_valid*/ 0,
5426						      /*bit*/ 0);
5427				goto bailout;
5428			}
5429		}
5430	}
5431
5432	ctl_set_success(ctsio);
5433bailout:
5434
5435	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5436		free(ctsio->kern_data_ptr, M_CTL);
5437		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5438	}
5439
5440	ctl_done((union ctl_io *)ctsio);
5441	return (CTL_RETVAL_COMPLETE);
5442}
5443
5444int
5445ctl_read_buffer(struct ctl_scsiio *ctsio)
5446{
5447	struct ctl_lun *lun = CTL_LUN(ctsio);
5448	uint64_t buffer_offset;
5449	uint32_t len;
5450	uint8_t byte2;
5451	static uint8_t descr[4];
5452	static uint8_t echo_descr[4] = { 0 };
5453
5454	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5455
5456	switch (ctsio->cdb[0]) {
5457	case READ_BUFFER: {
5458		struct scsi_read_buffer *cdb;
5459
5460		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5461		buffer_offset = scsi_3btoul(cdb->offset);
5462		len = scsi_3btoul(cdb->length);
5463		byte2 = cdb->byte2;
5464		break;
5465	}
5466	case READ_BUFFER_16: {
5467		struct scsi_read_buffer_16 *cdb;
5468
5469		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5470		buffer_offset = scsi_8btou64(cdb->offset);
5471		len = scsi_4btoul(cdb->length);
5472		byte2 = cdb->byte2;
5473		break;
5474	}
5475	default: /* This shouldn't happen. */
5476		ctl_set_invalid_opcode(ctsio);
5477		ctl_done((union ctl_io *)ctsio);
5478		return (CTL_RETVAL_COMPLETE);
5479	}
5480
5481	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5482	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5483		ctl_set_invalid_field(ctsio,
5484				      /*sks_valid*/ 1,
5485				      /*command*/ 1,
5486				      /*field*/ 6,
5487				      /*bit_valid*/ 0,
5488				      /*bit*/ 0);
5489		ctl_done((union ctl_io *)ctsio);
5490		return (CTL_RETVAL_COMPLETE);
5491	}
5492
5493	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5494		descr[0] = 0;
5495		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5496		ctsio->kern_data_ptr = descr;
5497		len = min(len, sizeof(descr));
5498	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5499		ctsio->kern_data_ptr = echo_descr;
5500		len = min(len, sizeof(echo_descr));
5501	} else {
5502		if (lun->write_buffer == NULL) {
5503			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5504			    M_CTL, M_WAITOK);
5505		}
5506		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5507	}
5508	ctsio->kern_data_len = len;
5509	ctsio->kern_total_len = len;
5510	ctsio->kern_data_resid = 0;
5511	ctsio->kern_rel_offset = 0;
5512	ctsio->kern_sg_entries = 0;
5513	ctl_set_success(ctsio);
5514	ctsio->be_move_done = ctl_config_move_done;
5515	ctl_datamove((union ctl_io *)ctsio);
5516	return (CTL_RETVAL_COMPLETE);
5517}
5518
5519int
5520ctl_write_buffer(struct ctl_scsiio *ctsio)
5521{
5522	struct ctl_lun *lun = CTL_LUN(ctsio);
5523	struct scsi_write_buffer *cdb;
5524	int buffer_offset, len;
5525
5526	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5527
5528	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5529
5530	len = scsi_3btoul(cdb->length);
5531	buffer_offset = scsi_3btoul(cdb->offset);
5532
5533	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5534		ctl_set_invalid_field(ctsio,
5535				      /*sks_valid*/ 1,
5536				      /*command*/ 1,
5537				      /*field*/ 6,
5538				      /*bit_valid*/ 0,
5539				      /*bit*/ 0);
5540		ctl_done((union ctl_io *)ctsio);
5541		return (CTL_RETVAL_COMPLETE);
5542	}
5543
5544	/*
5545	 * If we've got a kernel request that hasn't been malloced yet,
5546	 * malloc it and tell the caller the data buffer is here.
5547	 */
5548	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5549		if (lun->write_buffer == NULL) {
5550			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5551			    M_CTL, M_WAITOK);
5552		}
5553		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5554		ctsio->kern_data_len = len;
5555		ctsio->kern_total_len = len;
5556		ctsio->kern_data_resid = 0;
5557		ctsio->kern_rel_offset = 0;
5558		ctsio->kern_sg_entries = 0;
5559		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5560		ctsio->be_move_done = ctl_config_move_done;
5561		ctl_datamove((union ctl_io *)ctsio);
5562
5563		return (CTL_RETVAL_COMPLETE);
5564	}
5565
5566	ctl_set_success(ctsio);
5567	ctl_done((union ctl_io *)ctsio);
5568	return (CTL_RETVAL_COMPLETE);
5569}
5570
5571int
5572ctl_write_same(struct ctl_scsiio *ctsio)
5573{
5574	struct ctl_lun *lun = CTL_LUN(ctsio);
5575	struct ctl_lba_len_flags *lbalen;
5576	uint64_t lba;
5577	uint32_t num_blocks;
5578	int len, retval;
5579	uint8_t byte2;
5580
5581	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5582
5583	switch (ctsio->cdb[0]) {
5584	case WRITE_SAME_10: {
5585		struct scsi_write_same_10 *cdb;
5586
5587		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5588
5589		lba = scsi_4btoul(cdb->addr);
5590		num_blocks = scsi_2btoul(cdb->length);
5591		byte2 = cdb->byte2;
5592		break;
5593	}
5594	case WRITE_SAME_16: {
5595		struct scsi_write_same_16 *cdb;
5596
5597		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5598
5599		lba = scsi_8btou64(cdb->addr);
5600		num_blocks = scsi_4btoul(cdb->length);
5601		byte2 = cdb->byte2;
5602		break;
5603	}
5604	default:
5605		/*
5606		 * We got a command we don't support.  This shouldn't
5607		 * happen, commands should be filtered out above us.
5608		 */
5609		ctl_set_invalid_opcode(ctsio);
5610		ctl_done((union ctl_io *)ctsio);
5611
5612		return (CTL_RETVAL_COMPLETE);
5613		break; /* NOTREACHED */
5614	}
5615
5616	/* ANCHOR flag can be used only together with UNMAP */
5617	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5618		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5619		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5620		ctl_done((union ctl_io *)ctsio);
5621		return (CTL_RETVAL_COMPLETE);
5622	}
5623
5624	/*
5625	 * The first check is to make sure we're in bounds, the second
5626	 * check is to catch wrap-around problems.  If the lba + num blocks
5627	 * is less than the lba, then we've wrapped around and the block
5628	 * range is invalid anyway.
5629	 */
5630	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5631	 || ((lba + num_blocks) < lba)) {
5632		ctl_set_lba_out_of_range(ctsio,
5633		    MAX(lba, lun->be_lun->maxlba + 1));
5634		ctl_done((union ctl_io *)ctsio);
5635		return (CTL_RETVAL_COMPLETE);
5636	}
5637
5638	/* Zero number of blocks means "to the last logical block" */
5639	if (num_blocks == 0) {
5640		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5641			ctl_set_invalid_field(ctsio,
5642					      /*sks_valid*/ 0,
5643					      /*command*/ 1,
5644					      /*field*/ 0,
5645					      /*bit_valid*/ 0,
5646					      /*bit*/ 0);
5647			ctl_done((union ctl_io *)ctsio);
5648			return (CTL_RETVAL_COMPLETE);
5649		}
5650		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5651	}
5652
5653	len = lun->be_lun->blocksize;
5654
5655	/*
5656	 * If we've got a kernel request that hasn't been malloced yet,
5657	 * malloc it and tell the caller the data buffer is here.
5658	 */
5659	if ((byte2 & SWS_NDOB) == 0 &&
5660	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5661		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5662		ctsio->kern_data_len = len;
5663		ctsio->kern_total_len = len;
5664		ctsio->kern_data_resid = 0;
5665		ctsio->kern_rel_offset = 0;
5666		ctsio->kern_sg_entries = 0;
5667		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5668		ctsio->be_move_done = ctl_config_move_done;
5669		ctl_datamove((union ctl_io *)ctsio);
5670
5671		return (CTL_RETVAL_COMPLETE);
5672	}
5673
5674	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5675	lbalen->lba = lba;
5676	lbalen->len = num_blocks;
5677	lbalen->flags = byte2;
5678	retval = lun->backend->config_write((union ctl_io *)ctsio);
5679
5680	return (retval);
5681}
5682
5683int
5684ctl_unmap(struct ctl_scsiio *ctsio)
5685{
5686	struct ctl_lun *lun = CTL_LUN(ctsio);
5687	struct scsi_unmap *cdb;
5688	struct ctl_ptr_len_flags *ptrlen;
5689	struct scsi_unmap_header *hdr;
5690	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5691	uint64_t lba;
5692	uint32_t num_blocks;
5693	int len, retval;
5694	uint8_t byte2;
5695
5696	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5697
5698	cdb = (struct scsi_unmap *)ctsio->cdb;
5699	len = scsi_2btoul(cdb->length);
5700	byte2 = cdb->byte2;
5701
5702	/*
5703	 * If we've got a kernel request that hasn't been malloced yet,
5704	 * malloc it and tell the caller the data buffer is here.
5705	 */
5706	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5707		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5708		ctsio->kern_data_len = len;
5709		ctsio->kern_total_len = len;
5710		ctsio->kern_data_resid = 0;
5711		ctsio->kern_rel_offset = 0;
5712		ctsio->kern_sg_entries = 0;
5713		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5714		ctsio->be_move_done = ctl_config_move_done;
5715		ctl_datamove((union ctl_io *)ctsio);
5716
5717		return (CTL_RETVAL_COMPLETE);
5718	}
5719
5720	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5721	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5722	if (len < sizeof (*hdr) ||
5723	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5724	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5725	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5726		ctl_set_invalid_field(ctsio,
5727				      /*sks_valid*/ 0,
5728				      /*command*/ 0,
5729				      /*field*/ 0,
5730				      /*bit_valid*/ 0,
5731				      /*bit*/ 0);
5732		goto done;
5733	}
5734	len = scsi_2btoul(hdr->desc_length);
5735	buf = (struct scsi_unmap_desc *)(hdr + 1);
5736	end = buf + len / sizeof(*buf);
5737
5738	endnz = buf;
5739	for (range = buf; range < end; range++) {
5740		lba = scsi_8btou64(range->lba);
5741		num_blocks = scsi_4btoul(range->length);
5742		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5743		 || ((lba + num_blocks) < lba)) {
5744			ctl_set_lba_out_of_range(ctsio,
5745			    MAX(lba, lun->be_lun->maxlba + 1));
5746			ctl_done((union ctl_io *)ctsio);
5747			return (CTL_RETVAL_COMPLETE);
5748		}
5749		if (num_blocks != 0)
5750			endnz = range + 1;
5751	}
5752
5753	/*
5754	 * Block backend can not handle zero last range.
5755	 * Filter it out and return if there is nothing left.
5756	 */
5757	len = (uint8_t *)endnz - (uint8_t *)buf;
5758	if (len == 0) {
5759		ctl_set_success(ctsio);
5760		goto done;
5761	}
5762
5763	mtx_lock(&lun->lun_lock);
5764	ptrlen = (struct ctl_ptr_len_flags *)
5765	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5766	ptrlen->ptr = (void *)buf;
5767	ptrlen->len = len;
5768	ptrlen->flags = byte2;
5769	ctl_check_blocked(lun);
5770	mtx_unlock(&lun->lun_lock);
5771
5772	retval = lun->backend->config_write((union ctl_io *)ctsio);
5773	return (retval);
5774
5775done:
5776	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5777		free(ctsio->kern_data_ptr, M_CTL);
5778		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5779	}
5780	ctl_done((union ctl_io *)ctsio);
5781	return (CTL_RETVAL_COMPLETE);
5782}
5783
5784int
5785ctl_default_page_handler(struct ctl_scsiio *ctsio,
5786			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5787{
5788	struct ctl_lun *lun = CTL_LUN(ctsio);
5789	uint8_t *current_cp;
5790	int set_ua;
5791	uint32_t initidx;
5792
5793	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5794	set_ua = 0;
5795
5796	current_cp = (page_index->page_data + (page_index->page_len *
5797	    CTL_PAGE_CURRENT));
5798
5799	mtx_lock(&lun->lun_lock);
5800	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5801		memcpy(current_cp, page_ptr, page_index->page_len);
5802		set_ua = 1;
5803	}
5804	if (set_ua != 0)
5805		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5806	mtx_unlock(&lun->lun_lock);
5807	if (set_ua) {
5808		ctl_isc_announce_mode(lun,
5809		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5810		    page_index->page_code, page_index->subpage);
5811	}
5812	return (CTL_RETVAL_COMPLETE);
5813}
5814
5815static void
5816ctl_ie_timer(void *arg)
5817{
5818	struct ctl_lun *lun = arg;
5819	uint64_t t;
5820
5821	if (lun->ie_asc == 0)
5822		return;
5823
5824	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5825		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5826	else
5827		lun->ie_reported = 0;
5828
5829	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5830		lun->ie_reportcnt++;
5831		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5832		if (t == 0 || t == UINT32_MAX)
5833			t = 3000;  /* 5 min */
5834		callout_schedule(&lun->ie_callout, t * hz / 10);
5835	}
5836}
5837
5838int
5839ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5840			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5841{
5842	struct ctl_lun *lun = CTL_LUN(ctsio);
5843	struct scsi_info_exceptions_page *pg;
5844	uint64_t t;
5845
5846	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5847
5848	pg = (struct scsi_info_exceptions_page *)page_ptr;
5849	mtx_lock(&lun->lun_lock);
5850	if (pg->info_flags & SIEP_FLAGS_TEST) {
5851		lun->ie_asc = 0x5d;
5852		lun->ie_ascq = 0xff;
5853		if (pg->mrie == SIEP_MRIE_UA) {
5854			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5855			lun->ie_reported = 1;
5856		} else {
5857			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5858			lun->ie_reported = -1;
5859		}
5860		lun->ie_reportcnt = 1;
5861		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5862			lun->ie_reportcnt++;
5863			t = scsi_4btoul(pg->interval_timer);
5864			if (t == 0 || t == UINT32_MAX)
5865				t = 3000;  /* 5 min */
5866			callout_reset(&lun->ie_callout, t * hz / 10,
5867			    ctl_ie_timer, lun);
5868		}
5869	} else {
5870		lun->ie_asc = 0;
5871		lun->ie_ascq = 0;
5872		lun->ie_reported = 1;
5873		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5874		lun->ie_reportcnt = UINT32_MAX;
5875		callout_stop(&lun->ie_callout);
5876	}
5877	mtx_unlock(&lun->lun_lock);
5878	return (CTL_RETVAL_COMPLETE);
5879}
5880
5881static int
5882ctl_do_mode_select(union ctl_io *io)
5883{
5884	struct ctl_lun *lun = CTL_LUN(io);
5885	struct scsi_mode_page_header *page_header;
5886	struct ctl_page_index *page_index;
5887	struct ctl_scsiio *ctsio;
5888	int page_len, page_len_offset, page_len_size;
5889	union ctl_modepage_info *modepage_info;
5890	uint16_t *len_left, *len_used;
5891	int retval, i;
5892
5893	ctsio = &io->scsiio;
5894	page_index = NULL;
5895	page_len = 0;
5896
5897	modepage_info = (union ctl_modepage_info *)
5898		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5899	len_left = &modepage_info->header.len_left;
5900	len_used = &modepage_info->header.len_used;
5901
5902do_next_page:
5903
5904	page_header = (struct scsi_mode_page_header *)
5905		(ctsio->kern_data_ptr + *len_used);
5906
5907	if (*len_left == 0) {
5908		free(ctsio->kern_data_ptr, M_CTL);
5909		ctl_set_success(ctsio);
5910		ctl_done((union ctl_io *)ctsio);
5911		return (CTL_RETVAL_COMPLETE);
5912	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5913
5914		free(ctsio->kern_data_ptr, M_CTL);
5915		ctl_set_param_len_error(ctsio);
5916		ctl_done((union ctl_io *)ctsio);
5917		return (CTL_RETVAL_COMPLETE);
5918
5919	} else if ((page_header->page_code & SMPH_SPF)
5920		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5921
5922		free(ctsio->kern_data_ptr, M_CTL);
5923		ctl_set_param_len_error(ctsio);
5924		ctl_done((union ctl_io *)ctsio);
5925		return (CTL_RETVAL_COMPLETE);
5926	}
5927
5928
5929	/*
5930	 * XXX KDM should we do something with the block descriptor?
5931	 */
5932	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5933		page_index = &lun->mode_pages.index[i];
5934		if (lun->be_lun->lun_type == T_DIRECT &&
5935		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5936			continue;
5937		if (lun->be_lun->lun_type == T_PROCESSOR &&
5938		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5939			continue;
5940		if (lun->be_lun->lun_type == T_CDROM &&
5941		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5942			continue;
5943
5944		if ((page_index->page_code & SMPH_PC_MASK) !=
5945		    (page_header->page_code & SMPH_PC_MASK))
5946			continue;
5947
5948		/*
5949		 * If neither page has a subpage code, then we've got a
5950		 * match.
5951		 */
5952		if (((page_index->page_code & SMPH_SPF) == 0)
5953		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5954			page_len = page_header->page_length;
5955			break;
5956		}
5957
5958		/*
5959		 * If both pages have subpages, then the subpage numbers
5960		 * have to match.
5961		 */
5962		if ((page_index->page_code & SMPH_SPF)
5963		  && (page_header->page_code & SMPH_SPF)) {
5964			struct scsi_mode_page_header_sp *sph;
5965
5966			sph = (struct scsi_mode_page_header_sp *)page_header;
5967			if (page_index->subpage == sph->subpage) {
5968				page_len = scsi_2btoul(sph->page_length);
5969				break;
5970			}
5971		}
5972	}
5973
5974	/*
5975	 * If we couldn't find the page, or if we don't have a mode select
5976	 * handler for it, send back an error to the user.
5977	 */
5978	if ((i >= CTL_NUM_MODE_PAGES)
5979	 || (page_index->select_handler == NULL)) {
5980		ctl_set_invalid_field(ctsio,
5981				      /*sks_valid*/ 1,
5982				      /*command*/ 0,
5983				      /*field*/ *len_used,
5984				      /*bit_valid*/ 0,
5985				      /*bit*/ 0);
5986		free(ctsio->kern_data_ptr, M_CTL);
5987		ctl_done((union ctl_io *)ctsio);
5988		return (CTL_RETVAL_COMPLETE);
5989	}
5990
5991	if (page_index->page_code & SMPH_SPF) {
5992		page_len_offset = 2;
5993		page_len_size = 2;
5994	} else {
5995		page_len_size = 1;
5996		page_len_offset = 1;
5997	}
5998
5999	/*
6000	 * If the length the initiator gives us isn't the one we specify in
6001	 * the mode page header, or if they didn't specify enough data in
6002	 * the CDB to avoid truncating this page, kick out the request.
6003	 */
6004	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6005		ctl_set_invalid_field(ctsio,
6006				      /*sks_valid*/ 1,
6007				      /*command*/ 0,
6008				      /*field*/ *len_used + page_len_offset,
6009				      /*bit_valid*/ 0,
6010				      /*bit*/ 0);
6011		free(ctsio->kern_data_ptr, M_CTL);
6012		ctl_done((union ctl_io *)ctsio);
6013		return (CTL_RETVAL_COMPLETE);
6014	}
6015	if (*len_left < page_index->page_len) {
6016		free(ctsio->kern_data_ptr, M_CTL);
6017		ctl_set_param_len_error(ctsio);
6018		ctl_done((union ctl_io *)ctsio);
6019		return (CTL_RETVAL_COMPLETE);
6020	}
6021
6022	/*
6023	 * Run through the mode page, checking to make sure that the bits
6024	 * the user changed are actually legal for him to change.
6025	 */
6026	for (i = 0; i < page_index->page_len; i++) {
6027		uint8_t *user_byte, *change_mask, *current_byte;
6028		int bad_bit;
6029		int j;
6030
6031		user_byte = (uint8_t *)page_header + i;
6032		change_mask = page_index->page_data +
6033			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6034		current_byte = page_index->page_data +
6035			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6036
6037		/*
6038		 * Check to see whether the user set any bits in this byte
6039		 * that he is not allowed to set.
6040		 */
6041		if ((*user_byte & ~(*change_mask)) ==
6042		    (*current_byte & ~(*change_mask)))
6043			continue;
6044
6045		/*
6046		 * Go through bit by bit to determine which one is illegal.
6047		 */
6048		bad_bit = 0;
6049		for (j = 7; j >= 0; j--) {
6050			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6051			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6052				bad_bit = i;
6053				break;
6054			}
6055		}
6056		ctl_set_invalid_field(ctsio,
6057				      /*sks_valid*/ 1,
6058				      /*command*/ 0,
6059				      /*field*/ *len_used + i,
6060				      /*bit_valid*/ 1,
6061				      /*bit*/ bad_bit);
6062		free(ctsio->kern_data_ptr, M_CTL);
6063		ctl_done((union ctl_io *)ctsio);
6064		return (CTL_RETVAL_COMPLETE);
6065	}
6066
6067	/*
6068	 * Decrement these before we call the page handler, since we may
6069	 * end up getting called back one way or another before the handler
6070	 * returns to this context.
6071	 */
6072	*len_left -= page_index->page_len;
6073	*len_used += page_index->page_len;
6074
6075	retval = page_index->select_handler(ctsio, page_index,
6076					    (uint8_t *)page_header);
6077
6078	/*
6079	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6080	 * wait until this queued command completes to finish processing
6081	 * the mode page.  If it returns anything other than
6082	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6083	 * already set the sense information, freed the data pointer, and
6084	 * completed the io for us.
6085	 */
6086	if (retval != CTL_RETVAL_COMPLETE)
6087		goto bailout_no_done;
6088
6089	/*
6090	 * If the initiator sent us more than one page, parse the next one.
6091	 */
6092	if (*len_left > 0)
6093		goto do_next_page;
6094
6095	ctl_set_success(ctsio);
6096	free(ctsio->kern_data_ptr, M_CTL);
6097	ctl_done((union ctl_io *)ctsio);
6098
6099bailout_no_done:
6100
6101	return (CTL_RETVAL_COMPLETE);
6102
6103}
6104
6105int
6106ctl_mode_select(struct ctl_scsiio *ctsio)
6107{
6108	struct ctl_lun *lun = CTL_LUN(ctsio);
6109	union ctl_modepage_info *modepage_info;
6110	int bd_len, i, header_size, param_len, pf, rtd, sp;
6111	uint32_t initidx;
6112
6113	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6114	switch (ctsio->cdb[0]) {
6115	case MODE_SELECT_6: {
6116		struct scsi_mode_select_6 *cdb;
6117
6118		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6119
6120		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6121		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6122		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6123		param_len = cdb->length;
6124		header_size = sizeof(struct scsi_mode_header_6);
6125		break;
6126	}
6127	case MODE_SELECT_10: {
6128		struct scsi_mode_select_10 *cdb;
6129
6130		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6131
6132		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6133		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6134		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6135		param_len = scsi_2btoul(cdb->length);
6136		header_size = sizeof(struct scsi_mode_header_10);
6137		break;
6138	}
6139	default:
6140		ctl_set_invalid_opcode(ctsio);
6141		ctl_done((union ctl_io *)ctsio);
6142		return (CTL_RETVAL_COMPLETE);
6143	}
6144
6145	if (rtd) {
6146		if (param_len != 0) {
6147			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6148			    /*command*/ 1, /*field*/ 0,
6149			    /*bit_valid*/ 0, /*bit*/ 0);
6150			ctl_done((union ctl_io *)ctsio);
6151			return (CTL_RETVAL_COMPLETE);
6152		}
6153
6154		/* Revert to defaults. */
6155		ctl_init_page_index(lun);
6156		mtx_lock(&lun->lun_lock);
6157		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6158		mtx_unlock(&lun->lun_lock);
6159		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6160			ctl_isc_announce_mode(lun, -1,
6161			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6162			    lun->mode_pages.index[i].subpage);
6163		}
6164		ctl_set_success(ctsio);
6165		ctl_done((union ctl_io *)ctsio);
6166		return (CTL_RETVAL_COMPLETE);
6167	}
6168
6169	/*
6170	 * From SPC-3:
6171	 * "A parameter list length of zero indicates that the Data-Out Buffer
6172	 * shall be empty. This condition shall not be considered as an error."
6173	 */
6174	if (param_len == 0) {
6175		ctl_set_success(ctsio);
6176		ctl_done((union ctl_io *)ctsio);
6177		return (CTL_RETVAL_COMPLETE);
6178	}
6179
6180	/*
6181	 * Since we'll hit this the first time through, prior to
6182	 * allocation, we don't need to free a data buffer here.
6183	 */
6184	if (param_len < header_size) {
6185		ctl_set_param_len_error(ctsio);
6186		ctl_done((union ctl_io *)ctsio);
6187		return (CTL_RETVAL_COMPLETE);
6188	}
6189
6190	/*
6191	 * Allocate the data buffer and grab the user's data.  In theory,
6192	 * we shouldn't have to sanity check the parameter list length here
6193	 * because the maximum size is 64K.  We should be able to malloc
6194	 * that much without too many problems.
6195	 */
6196	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6197		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6198		ctsio->kern_data_len = param_len;
6199		ctsio->kern_total_len = param_len;
6200		ctsio->kern_data_resid = 0;
6201		ctsio->kern_rel_offset = 0;
6202		ctsio->kern_sg_entries = 0;
6203		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6204		ctsio->be_move_done = ctl_config_move_done;
6205		ctl_datamove((union ctl_io *)ctsio);
6206
6207		return (CTL_RETVAL_COMPLETE);
6208	}
6209
6210	switch (ctsio->cdb[0]) {
6211	case MODE_SELECT_6: {
6212		struct scsi_mode_header_6 *mh6;
6213
6214		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6215		bd_len = mh6->blk_desc_len;
6216		break;
6217	}
6218	case MODE_SELECT_10: {
6219		struct scsi_mode_header_10 *mh10;
6220
6221		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6222		bd_len = scsi_2btoul(mh10->blk_desc_len);
6223		break;
6224	}
6225	default:
6226		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6227	}
6228
6229	if (param_len < (header_size + bd_len)) {
6230		free(ctsio->kern_data_ptr, M_CTL);
6231		ctl_set_param_len_error(ctsio);
6232		ctl_done((union ctl_io *)ctsio);
6233		return (CTL_RETVAL_COMPLETE);
6234	}
6235
6236	/*
6237	 * Set the IO_CONT flag, so that if this I/O gets passed to
6238	 * ctl_config_write_done(), it'll get passed back to
6239	 * ctl_do_mode_select() for further processing, or completion if
6240	 * we're all done.
6241	 */
6242	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6243	ctsio->io_cont = ctl_do_mode_select;
6244
6245	modepage_info = (union ctl_modepage_info *)
6246		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6247	memset(modepage_info, 0, sizeof(*modepage_info));
6248	modepage_info->header.len_left = param_len - header_size - bd_len;
6249	modepage_info->header.len_used = header_size + bd_len;
6250
6251	return (ctl_do_mode_select((union ctl_io *)ctsio));
6252}
6253
6254int
6255ctl_mode_sense(struct ctl_scsiio *ctsio)
6256{
6257	struct ctl_lun *lun = CTL_LUN(ctsio);
6258	int pc, page_code, dbd, llba, subpage;
6259	int alloc_len, page_len, header_len, total_len;
6260	struct scsi_mode_block_descr *block_desc;
6261	struct ctl_page_index *page_index;
6262
6263	dbd = 0;
6264	llba = 0;
6265	block_desc = NULL;
6266
6267	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6268
6269	switch (ctsio->cdb[0]) {
6270	case MODE_SENSE_6: {
6271		struct scsi_mode_sense_6 *cdb;
6272
6273		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6274
6275		header_len = sizeof(struct scsi_mode_hdr_6);
6276		if (cdb->byte2 & SMS_DBD)
6277			dbd = 1;
6278		else
6279			header_len += sizeof(struct scsi_mode_block_descr);
6280
6281		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6282		page_code = cdb->page & SMS_PAGE_CODE;
6283		subpage = cdb->subpage;
6284		alloc_len = cdb->length;
6285		break;
6286	}
6287	case MODE_SENSE_10: {
6288		struct scsi_mode_sense_10 *cdb;
6289
6290		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6291
6292		header_len = sizeof(struct scsi_mode_hdr_10);
6293
6294		if (cdb->byte2 & SMS_DBD)
6295			dbd = 1;
6296		else
6297			header_len += sizeof(struct scsi_mode_block_descr);
6298		if (cdb->byte2 & SMS10_LLBAA)
6299			llba = 1;
6300		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6301		page_code = cdb->page & SMS_PAGE_CODE;
6302		subpage = cdb->subpage;
6303		alloc_len = scsi_2btoul(cdb->length);
6304		break;
6305	}
6306	default:
6307		ctl_set_invalid_opcode(ctsio);
6308		ctl_done((union ctl_io *)ctsio);
6309		return (CTL_RETVAL_COMPLETE);
6310		break; /* NOTREACHED */
6311	}
6312
6313	/*
6314	 * We have to make a first pass through to calculate the size of
6315	 * the pages that match the user's query.  Then we allocate enough
6316	 * memory to hold it, and actually copy the data into the buffer.
6317	 */
6318	switch (page_code) {
6319	case SMS_ALL_PAGES_PAGE: {
6320		u_int i;
6321
6322		page_len = 0;
6323
6324		/*
6325		 * At the moment, values other than 0 and 0xff here are
6326		 * reserved according to SPC-3.
6327		 */
6328		if ((subpage != SMS_SUBPAGE_PAGE_0)
6329		 && (subpage != SMS_SUBPAGE_ALL)) {
6330			ctl_set_invalid_field(ctsio,
6331					      /*sks_valid*/ 1,
6332					      /*command*/ 1,
6333					      /*field*/ 3,
6334					      /*bit_valid*/ 0,
6335					      /*bit*/ 0);
6336			ctl_done((union ctl_io *)ctsio);
6337			return (CTL_RETVAL_COMPLETE);
6338		}
6339
6340		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6341			page_index = &lun->mode_pages.index[i];
6342
6343			/* Make sure the page is supported for this dev type */
6344			if (lun->be_lun->lun_type == T_DIRECT &&
6345			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6346				continue;
6347			if (lun->be_lun->lun_type == T_PROCESSOR &&
6348			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6349				continue;
6350			if (lun->be_lun->lun_type == T_CDROM &&
6351			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6352				continue;
6353
6354			/*
6355			 * We don't use this subpage if the user didn't
6356			 * request all subpages.
6357			 */
6358			if ((page_index->subpage != 0)
6359			 && (subpage == SMS_SUBPAGE_PAGE_0))
6360				continue;
6361
6362#if 0
6363			printf("found page %#x len %d\n",
6364			       page_index->page_code & SMPH_PC_MASK,
6365			       page_index->page_len);
6366#endif
6367			page_len += page_index->page_len;
6368		}
6369		break;
6370	}
6371	default: {
6372		u_int i;
6373
6374		page_len = 0;
6375
6376		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6377			page_index = &lun->mode_pages.index[i];
6378
6379			/* Make sure the page is supported for this dev type */
6380			if (lun->be_lun->lun_type == T_DIRECT &&
6381			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6382				continue;
6383			if (lun->be_lun->lun_type == T_PROCESSOR &&
6384			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6385				continue;
6386			if (lun->be_lun->lun_type == T_CDROM &&
6387			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6388				continue;
6389
6390			/* Look for the right page code */
6391			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6392				continue;
6393
6394			/* Look for the right subpage or the subpage wildcard*/
6395			if ((page_index->subpage != subpage)
6396			 && (subpage != SMS_SUBPAGE_ALL))
6397				continue;
6398
6399#if 0
6400			printf("found page %#x len %d\n",
6401			       page_index->page_code & SMPH_PC_MASK,
6402			       page_index->page_len);
6403#endif
6404
6405			page_len += page_index->page_len;
6406		}
6407
6408		if (page_len == 0) {
6409			ctl_set_invalid_field(ctsio,
6410					      /*sks_valid*/ 1,
6411					      /*command*/ 1,
6412					      /*field*/ 2,
6413					      /*bit_valid*/ 1,
6414					      /*bit*/ 5);
6415			ctl_done((union ctl_io *)ctsio);
6416			return (CTL_RETVAL_COMPLETE);
6417		}
6418		break;
6419	}
6420	}
6421
6422	total_len = header_len + page_len;
6423#if 0
6424	printf("header_len = %d, page_len = %d, total_len = %d\n",
6425	       header_len, page_len, total_len);
6426#endif
6427
6428	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6429	ctsio->kern_sg_entries = 0;
6430	ctsio->kern_data_resid = 0;
6431	ctsio->kern_rel_offset = 0;
6432	if (total_len < alloc_len) {
6433		ctsio->residual = alloc_len - total_len;
6434		ctsio->kern_data_len = total_len;
6435		ctsio->kern_total_len = total_len;
6436	} else {
6437		ctsio->residual = 0;
6438		ctsio->kern_data_len = alloc_len;
6439		ctsio->kern_total_len = alloc_len;
6440	}
6441
6442	switch (ctsio->cdb[0]) {
6443	case MODE_SENSE_6: {
6444		struct scsi_mode_hdr_6 *header;
6445
6446		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6447
6448		header->datalen = MIN(total_len - 1, 254);
6449		if (lun->be_lun->lun_type == T_DIRECT) {
6450			header->dev_specific = 0x10; /* DPOFUA */
6451			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6452			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6453				header->dev_specific |= 0x80; /* WP */
6454		}
6455		if (dbd)
6456			header->block_descr_len = 0;
6457		else
6458			header->block_descr_len =
6459				sizeof(struct scsi_mode_block_descr);
6460		block_desc = (struct scsi_mode_block_descr *)&header[1];
6461		break;
6462	}
6463	case MODE_SENSE_10: {
6464		struct scsi_mode_hdr_10 *header;
6465		int datalen;
6466
6467		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6468
6469		datalen = MIN(total_len - 2, 65533);
6470		scsi_ulto2b(datalen, header->datalen);
6471		if (lun->be_lun->lun_type == T_DIRECT) {
6472			header->dev_specific = 0x10; /* DPOFUA */
6473			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6474			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6475				header->dev_specific |= 0x80; /* WP */
6476		}
6477		if (dbd)
6478			scsi_ulto2b(0, header->block_descr_len);
6479		else
6480			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6481				    header->block_descr_len);
6482		block_desc = (struct scsi_mode_block_descr *)&header[1];
6483		break;
6484	}
6485	default:
6486		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6487	}
6488
6489	/*
6490	 * If we've got a disk, use its blocksize in the block
6491	 * descriptor.  Otherwise, just set it to 0.
6492	 */
6493	if (dbd == 0) {
6494		if (lun->be_lun->lun_type == T_DIRECT)
6495			scsi_ulto3b(lun->be_lun->blocksize,
6496				    block_desc->block_len);
6497		else
6498			scsi_ulto3b(0, block_desc->block_len);
6499	}
6500
6501	switch (page_code) {
6502	case SMS_ALL_PAGES_PAGE: {
6503		int i, data_used;
6504
6505		data_used = header_len;
6506		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6507			struct ctl_page_index *page_index;
6508
6509			page_index = &lun->mode_pages.index[i];
6510			if (lun->be_lun->lun_type == T_DIRECT &&
6511			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6512				continue;
6513			if (lun->be_lun->lun_type == T_PROCESSOR &&
6514			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6515				continue;
6516			if (lun->be_lun->lun_type == T_CDROM &&
6517			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6518				continue;
6519
6520			/*
6521			 * We don't use this subpage if the user didn't
6522			 * request all subpages.  We already checked (above)
6523			 * to make sure the user only specified a subpage
6524			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6525			 */
6526			if ((page_index->subpage != 0)
6527			 && (subpage == SMS_SUBPAGE_PAGE_0))
6528				continue;
6529
6530			/*
6531			 * Call the handler, if it exists, to update the
6532			 * page to the latest values.
6533			 */
6534			if (page_index->sense_handler != NULL)
6535				page_index->sense_handler(ctsio, page_index,pc);
6536
6537			memcpy(ctsio->kern_data_ptr + data_used,
6538			       page_index->page_data +
6539			       (page_index->page_len * pc),
6540			       page_index->page_len);
6541			data_used += page_index->page_len;
6542		}
6543		break;
6544	}
6545	default: {
6546		int i, data_used;
6547
6548		data_used = header_len;
6549
6550		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6551			struct ctl_page_index *page_index;
6552
6553			page_index = &lun->mode_pages.index[i];
6554
6555			/* Look for the right page code */
6556			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6557				continue;
6558
6559			/* Look for the right subpage or the subpage wildcard*/
6560			if ((page_index->subpage != subpage)
6561			 && (subpage != SMS_SUBPAGE_ALL))
6562				continue;
6563
6564			/* Make sure the page is supported for this dev type */
6565			if (lun->be_lun->lun_type == T_DIRECT &&
6566			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6567				continue;
6568			if (lun->be_lun->lun_type == T_PROCESSOR &&
6569			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6570				continue;
6571			if (lun->be_lun->lun_type == T_CDROM &&
6572			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6573				continue;
6574
6575			/*
6576			 * Call the handler, if it exists, to update the
6577			 * page to the latest values.
6578			 */
6579			if (page_index->sense_handler != NULL)
6580				page_index->sense_handler(ctsio, page_index,pc);
6581
6582			memcpy(ctsio->kern_data_ptr + data_used,
6583			       page_index->page_data +
6584			       (page_index->page_len * pc),
6585			       page_index->page_len);
6586			data_used += page_index->page_len;
6587		}
6588		break;
6589	}
6590	}
6591
6592	ctl_set_success(ctsio);
6593	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6594	ctsio->be_move_done = ctl_config_move_done;
6595	ctl_datamove((union ctl_io *)ctsio);
6596	return (CTL_RETVAL_COMPLETE);
6597}
6598
6599int
6600ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6601			       struct ctl_page_index *page_index,
6602			       int pc)
6603{
6604	struct ctl_lun *lun = CTL_LUN(ctsio);
6605	struct scsi_log_param_header *phdr;
6606	uint8_t *data;
6607	uint64_t val;
6608
6609	data = page_index->page_data;
6610
6611	if (lun->backend->lun_attr != NULL &&
6612	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6613	     != UINT64_MAX) {
6614		phdr = (struct scsi_log_param_header *)data;
6615		scsi_ulto2b(0x0001, phdr->param_code);
6616		phdr->param_control = SLP_LBIN | SLP_LP;
6617		phdr->param_len = 8;
6618		data = (uint8_t *)(phdr + 1);
6619		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6620		data[4] = 0x02; /* per-pool */
6621		data += phdr->param_len;
6622	}
6623
6624	if (lun->backend->lun_attr != NULL &&
6625	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6626	     != UINT64_MAX) {
6627		phdr = (struct scsi_log_param_header *)data;
6628		scsi_ulto2b(0x0002, phdr->param_code);
6629		phdr->param_control = SLP_LBIN | SLP_LP;
6630		phdr->param_len = 8;
6631		data = (uint8_t *)(phdr + 1);
6632		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6633		data[4] = 0x01; /* per-LUN */
6634		data += phdr->param_len;
6635	}
6636
6637	if (lun->backend->lun_attr != NULL &&
6638	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6639	     != UINT64_MAX) {
6640		phdr = (struct scsi_log_param_header *)data;
6641		scsi_ulto2b(0x00f1, phdr->param_code);
6642		phdr->param_control = SLP_LBIN | SLP_LP;
6643		phdr->param_len = 8;
6644		data = (uint8_t *)(phdr + 1);
6645		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6646		data[4] = 0x02; /* per-pool */
6647		data += phdr->param_len;
6648	}
6649
6650	if (lun->backend->lun_attr != NULL &&
6651	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6652	     != UINT64_MAX) {
6653		phdr = (struct scsi_log_param_header *)data;
6654		scsi_ulto2b(0x00f2, phdr->param_code);
6655		phdr->param_control = SLP_LBIN | SLP_LP;
6656		phdr->param_len = 8;
6657		data = (uint8_t *)(phdr + 1);
6658		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6659		data[4] = 0x02; /* per-pool */
6660		data += phdr->param_len;
6661	}
6662
6663	page_index->page_len = data - page_index->page_data;
6664	return (0);
6665}
6666
6667int
6668ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6669			       struct ctl_page_index *page_index,
6670			       int pc)
6671{
6672	struct ctl_lun *lun = CTL_LUN(ctsio);
6673	struct stat_page *data;
6674	uint64_t rn, wn, rb, wb;
6675	struct bintime rt, wt;
6676	int i;
6677
6678	data = (struct stat_page *)page_index->page_data;
6679
6680	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6681	data->sap.hdr.param_control = SLP_LBIN;
6682	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6683	    sizeof(struct scsi_log_param_header);
6684	rn = wn = rb = wb = 0;
6685	bintime_clear(&rt);
6686	bintime_clear(&wt);
6687	for (i = 0; i < CTL_MAX_PORTS; i++) {
6688		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6689		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6690		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6691		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6692		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6693		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6694	}
6695	scsi_u64to8b(rn, data->sap.read_num);
6696	scsi_u64to8b(wn, data->sap.write_num);
6697	if (lun->stats.blocksize > 0) {
6698		scsi_u64to8b(wb / lun->stats.blocksize,
6699		    data->sap.recvieved_lba);
6700		scsi_u64to8b(rb / lun->stats.blocksize,
6701		    data->sap.transmitted_lba);
6702	}
6703	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6704	    data->sap.read_int);
6705	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6706	    data->sap.write_int);
6707	scsi_u64to8b(0, data->sap.weighted_num);
6708	scsi_u64to8b(0, data->sap.weighted_int);
6709	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6710	data->it.hdr.param_control = SLP_LBIN;
6711	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6712	    sizeof(struct scsi_log_param_header);
6713#ifdef CTL_TIME_IO
6714	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6715#endif
6716	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6717	data->it.hdr.param_control = SLP_LBIN;
6718	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6719	    sizeof(struct scsi_log_param_header);
6720	scsi_ulto4b(3, data->ti.exponent);
6721	scsi_ulto4b(1, data->ti.integer);
6722	return (0);
6723}
6724
6725int
6726ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6727			       struct ctl_page_index *page_index,
6728			       int pc)
6729{
6730	struct ctl_lun *lun = CTL_LUN(ctsio);
6731	struct scsi_log_informational_exceptions *data;
6732
6733	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6734
6735	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6736	data->hdr.param_control = SLP_LBIN;
6737	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6738	    sizeof(struct scsi_log_param_header);
6739	data->ie_asc = lun->ie_asc;
6740	data->ie_ascq = lun->ie_ascq;
6741	data->temperature = 0xff;
6742	return (0);
6743}
6744
6745int
6746ctl_log_sense(struct ctl_scsiio *ctsio)
6747{
6748	struct ctl_lun *lun = CTL_LUN(ctsio);
6749	int i, pc, page_code, subpage;
6750	int alloc_len, total_len;
6751	struct ctl_page_index *page_index;
6752	struct scsi_log_sense *cdb;
6753	struct scsi_log_header *header;
6754
6755	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6756
6757	cdb = (struct scsi_log_sense *)ctsio->cdb;
6758	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6759	page_code = cdb->page & SLS_PAGE_CODE;
6760	subpage = cdb->subpage;
6761	alloc_len = scsi_2btoul(cdb->length);
6762
6763	page_index = NULL;
6764	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6765		page_index = &lun->log_pages.index[i];
6766
6767		/* Look for the right page code */
6768		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6769			continue;
6770
6771		/* Look for the right subpage or the subpage wildcard*/
6772		if (page_index->subpage != subpage)
6773			continue;
6774
6775		break;
6776	}
6777	if (i >= CTL_NUM_LOG_PAGES) {
6778		ctl_set_invalid_field(ctsio,
6779				      /*sks_valid*/ 1,
6780				      /*command*/ 1,
6781				      /*field*/ 2,
6782				      /*bit_valid*/ 0,
6783				      /*bit*/ 0);
6784		ctl_done((union ctl_io *)ctsio);
6785		return (CTL_RETVAL_COMPLETE);
6786	}
6787
6788	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6789
6790	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6791	ctsio->kern_sg_entries = 0;
6792	ctsio->kern_data_resid = 0;
6793	ctsio->kern_rel_offset = 0;
6794	if (total_len < alloc_len) {
6795		ctsio->residual = alloc_len - total_len;
6796		ctsio->kern_data_len = total_len;
6797		ctsio->kern_total_len = total_len;
6798	} else {
6799		ctsio->residual = 0;
6800		ctsio->kern_data_len = alloc_len;
6801		ctsio->kern_total_len = alloc_len;
6802	}
6803
6804	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6805	header->page = page_index->page_code;
6806	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6807		header->page |= SL_DS;
6808	if (page_index->subpage) {
6809		header->page |= SL_SPF;
6810		header->subpage = page_index->subpage;
6811	}
6812	scsi_ulto2b(page_index->page_len, header->datalen);
6813
6814	/*
6815	 * Call the handler, if it exists, to update the
6816	 * page to the latest values.
6817	 */
6818	if (page_index->sense_handler != NULL)
6819		page_index->sense_handler(ctsio, page_index, pc);
6820
6821	memcpy(header + 1, page_index->page_data, page_index->page_len);
6822
6823	ctl_set_success(ctsio);
6824	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6825	ctsio->be_move_done = ctl_config_move_done;
6826	ctl_datamove((union ctl_io *)ctsio);
6827	return (CTL_RETVAL_COMPLETE);
6828}
6829
6830int
6831ctl_read_capacity(struct ctl_scsiio *ctsio)
6832{
6833	struct ctl_lun *lun = CTL_LUN(ctsio);
6834	struct scsi_read_capacity *cdb;
6835	struct scsi_read_capacity_data *data;
6836	uint32_t lba;
6837
6838	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6839
6840	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6841
6842	lba = scsi_4btoul(cdb->addr);
6843	if (((cdb->pmi & SRC_PMI) == 0)
6844	 && (lba != 0)) {
6845		ctl_set_invalid_field(/*ctsio*/ ctsio,
6846				      /*sks_valid*/ 1,
6847				      /*command*/ 1,
6848				      /*field*/ 2,
6849				      /*bit_valid*/ 0,
6850				      /*bit*/ 0);
6851		ctl_done((union ctl_io *)ctsio);
6852		return (CTL_RETVAL_COMPLETE);
6853	}
6854
6855	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6856	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6857	ctsio->residual = 0;
6858	ctsio->kern_data_len = sizeof(*data);
6859	ctsio->kern_total_len = sizeof(*data);
6860	ctsio->kern_data_resid = 0;
6861	ctsio->kern_rel_offset = 0;
6862	ctsio->kern_sg_entries = 0;
6863
6864	/*
6865	 * If the maximum LBA is greater than 0xfffffffe, the user must
6866	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6867	 * serivce action set.
6868	 */
6869	if (lun->be_lun->maxlba > 0xfffffffe)
6870		scsi_ulto4b(0xffffffff, data->addr);
6871	else
6872		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6873
6874	/*
6875	 * XXX KDM this may not be 512 bytes...
6876	 */
6877	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6878
6879	ctl_set_success(ctsio);
6880	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6881	ctsio->be_move_done = ctl_config_move_done;
6882	ctl_datamove((union ctl_io *)ctsio);
6883	return (CTL_RETVAL_COMPLETE);
6884}
6885
6886int
6887ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6888{
6889	struct ctl_lun *lun = CTL_LUN(ctsio);
6890	struct scsi_read_capacity_16 *cdb;
6891	struct scsi_read_capacity_data_long *data;
6892	uint64_t lba;
6893	uint32_t alloc_len;
6894
6895	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6896
6897	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6898
6899	alloc_len = scsi_4btoul(cdb->alloc_len);
6900	lba = scsi_8btou64(cdb->addr);
6901
6902	if ((cdb->reladr & SRC16_PMI)
6903	 && (lba != 0)) {
6904		ctl_set_invalid_field(/*ctsio*/ ctsio,
6905				      /*sks_valid*/ 1,
6906				      /*command*/ 1,
6907				      /*field*/ 2,
6908				      /*bit_valid*/ 0,
6909				      /*bit*/ 0);
6910		ctl_done((union ctl_io *)ctsio);
6911		return (CTL_RETVAL_COMPLETE);
6912	}
6913
6914	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6915	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6916
6917	if (sizeof(*data) < alloc_len) {
6918		ctsio->residual = alloc_len - sizeof(*data);
6919		ctsio->kern_data_len = sizeof(*data);
6920		ctsio->kern_total_len = sizeof(*data);
6921	} else {
6922		ctsio->residual = 0;
6923		ctsio->kern_data_len = alloc_len;
6924		ctsio->kern_total_len = alloc_len;
6925	}
6926	ctsio->kern_data_resid = 0;
6927	ctsio->kern_rel_offset = 0;
6928	ctsio->kern_sg_entries = 0;
6929
6930	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6931	/* XXX KDM this may not be 512 bytes... */
6932	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6933	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6934	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6935	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6936		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6937
6938	ctl_set_success(ctsio);
6939	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6940	ctsio->be_move_done = ctl_config_move_done;
6941	ctl_datamove((union ctl_io *)ctsio);
6942	return (CTL_RETVAL_COMPLETE);
6943}
6944
6945int
6946ctl_get_lba_status(struct ctl_scsiio *ctsio)
6947{
6948	struct ctl_lun *lun = CTL_LUN(ctsio);
6949	struct scsi_get_lba_status *cdb;
6950	struct scsi_get_lba_status_data *data;
6951	struct ctl_lba_len_flags *lbalen;
6952	uint64_t lba;
6953	uint32_t alloc_len, total_len;
6954	int retval;
6955
6956	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6957
6958	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6959	lba = scsi_8btou64(cdb->addr);
6960	alloc_len = scsi_4btoul(cdb->alloc_len);
6961
6962	if (lba > lun->be_lun->maxlba) {
6963		ctl_set_lba_out_of_range(ctsio, lba);
6964		ctl_done((union ctl_io *)ctsio);
6965		return (CTL_RETVAL_COMPLETE);
6966	}
6967
6968	total_len = sizeof(*data) + sizeof(data->descr[0]);
6969	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6970	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6971
6972	if (total_len < alloc_len) {
6973		ctsio->residual = alloc_len - total_len;
6974		ctsio->kern_data_len = total_len;
6975		ctsio->kern_total_len = total_len;
6976	} else {
6977		ctsio->residual = 0;
6978		ctsio->kern_data_len = alloc_len;
6979		ctsio->kern_total_len = alloc_len;
6980	}
6981	ctsio->kern_data_resid = 0;
6982	ctsio->kern_rel_offset = 0;
6983	ctsio->kern_sg_entries = 0;
6984
6985	/* Fill dummy data in case backend can't tell anything. */
6986	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6987	scsi_u64to8b(lba, data->descr[0].addr);
6988	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6989	    data->descr[0].length);
6990	data->descr[0].status = 0; /* Mapped or unknown. */
6991
6992	ctl_set_success(ctsio);
6993	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6994	ctsio->be_move_done = ctl_config_move_done;
6995
6996	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6997	lbalen->lba = lba;
6998	lbalen->len = total_len;
6999	lbalen->flags = 0;
7000	retval = lun->backend->config_read((union ctl_io *)ctsio);
7001	return (CTL_RETVAL_COMPLETE);
7002}
7003
7004int
7005ctl_read_defect(struct ctl_scsiio *ctsio)
7006{
7007	struct scsi_read_defect_data_10 *ccb10;
7008	struct scsi_read_defect_data_12 *ccb12;
7009	struct scsi_read_defect_data_hdr_10 *data10;
7010	struct scsi_read_defect_data_hdr_12 *data12;
7011	uint32_t alloc_len, data_len;
7012	uint8_t format;
7013
7014	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7015
7016	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7017		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7018		format = ccb10->format;
7019		alloc_len = scsi_2btoul(ccb10->alloc_length);
7020		data_len = sizeof(*data10);
7021	} else {
7022		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7023		format = ccb12->format;
7024		alloc_len = scsi_4btoul(ccb12->alloc_length);
7025		data_len = sizeof(*data12);
7026	}
7027	if (alloc_len == 0) {
7028		ctl_set_success(ctsio);
7029		ctl_done((union ctl_io *)ctsio);
7030		return (CTL_RETVAL_COMPLETE);
7031	}
7032
7033	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7034	if (data_len < alloc_len) {
7035		ctsio->residual = alloc_len - data_len;
7036		ctsio->kern_data_len = data_len;
7037		ctsio->kern_total_len = data_len;
7038	} else {
7039		ctsio->residual = 0;
7040		ctsio->kern_data_len = alloc_len;
7041		ctsio->kern_total_len = alloc_len;
7042	}
7043	ctsio->kern_data_resid = 0;
7044	ctsio->kern_rel_offset = 0;
7045	ctsio->kern_sg_entries = 0;
7046
7047	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7048		data10 = (struct scsi_read_defect_data_hdr_10 *)
7049		    ctsio->kern_data_ptr;
7050		data10->format = format;
7051		scsi_ulto2b(0, data10->length);
7052	} else {
7053		data12 = (struct scsi_read_defect_data_hdr_12 *)
7054		    ctsio->kern_data_ptr;
7055		data12->format = format;
7056		scsi_ulto2b(0, data12->generation);
7057		scsi_ulto4b(0, data12->length);
7058	}
7059
7060	ctl_set_success(ctsio);
7061	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7062	ctsio->be_move_done = ctl_config_move_done;
7063	ctl_datamove((union ctl_io *)ctsio);
7064	return (CTL_RETVAL_COMPLETE);
7065}
7066
7067int
7068ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7069{
7070	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7071	struct ctl_lun *lun = CTL_LUN(ctsio);
7072	struct scsi_maintenance_in *cdb;
7073	int retval;
7074	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7075	int num_ha_groups, num_target_ports, shared_group;
7076	struct ctl_port *port;
7077	struct scsi_target_group_data *rtg_ptr;
7078	struct scsi_target_group_data_extended *rtg_ext_ptr;
7079	struct scsi_target_port_group_descriptor *tpg_desc;
7080
7081	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7082
7083	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7084	retval = CTL_RETVAL_COMPLETE;
7085
7086	switch (cdb->byte2 & STG_PDF_MASK) {
7087	case STG_PDF_LENGTH:
7088		ext = 0;
7089		break;
7090	case STG_PDF_EXTENDED:
7091		ext = 1;
7092		break;
7093	default:
7094		ctl_set_invalid_field(/*ctsio*/ ctsio,
7095				      /*sks_valid*/ 1,
7096				      /*command*/ 1,
7097				      /*field*/ 2,
7098				      /*bit_valid*/ 1,
7099				      /*bit*/ 5);
7100		ctl_done((union ctl_io *)ctsio);
7101		return(retval);
7102	}
7103
7104	num_target_ports = 0;
7105	shared_group = (softc->is_single != 0);
7106	mtx_lock(&softc->ctl_lock);
7107	STAILQ_FOREACH(port, &softc->port_list, links) {
7108		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7109			continue;
7110		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7111			continue;
7112		num_target_ports++;
7113		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7114			shared_group = 1;
7115	}
7116	mtx_unlock(&softc->ctl_lock);
7117	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7118
7119	if (ext)
7120		total_len = sizeof(struct scsi_target_group_data_extended);
7121	else
7122		total_len = sizeof(struct scsi_target_group_data);
7123	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7124		(shared_group + num_ha_groups) +
7125	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7126
7127	alloc_len = scsi_4btoul(cdb->length);
7128
7129	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7130
7131	ctsio->kern_sg_entries = 0;
7132
7133	if (total_len < alloc_len) {
7134		ctsio->residual = alloc_len - total_len;
7135		ctsio->kern_data_len = total_len;
7136		ctsio->kern_total_len = total_len;
7137	} else {
7138		ctsio->residual = 0;
7139		ctsio->kern_data_len = alloc_len;
7140		ctsio->kern_total_len = alloc_len;
7141	}
7142	ctsio->kern_data_resid = 0;
7143	ctsio->kern_rel_offset = 0;
7144
7145	if (ext) {
7146		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7147		    ctsio->kern_data_ptr;
7148		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7149		rtg_ext_ptr->format_type = 0x10;
7150		rtg_ext_ptr->implicit_transition_time = 0;
7151		tpg_desc = &rtg_ext_ptr->groups[0];
7152	} else {
7153		rtg_ptr = (struct scsi_target_group_data *)
7154		    ctsio->kern_data_ptr;
7155		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7156		tpg_desc = &rtg_ptr->groups[0];
7157	}
7158
7159	mtx_lock(&softc->ctl_lock);
7160	pg = softc->port_min / softc->port_cnt;
7161	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7162		/* Some shelf is known to be primary. */
7163		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7164			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7165		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7166			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7167		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7168			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7169		else
7170			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7171		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7172			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7173		} else {
7174			ts = os;
7175			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7176		}
7177	} else {
7178		/* No known primary shelf. */
7179		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7180			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7181			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7182		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7183			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7184			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7185		} else {
7186			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7187		}
7188	}
7189	if (shared_group) {
7190		tpg_desc->pref_state = ts;
7191		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7192		    TPG_U_SUP | TPG_T_SUP;
7193		scsi_ulto2b(1, tpg_desc->target_port_group);
7194		tpg_desc->status = TPG_IMPLICIT;
7195		pc = 0;
7196		STAILQ_FOREACH(port, &softc->port_list, links) {
7197			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7198				continue;
7199			if (!softc->is_single &&
7200			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7201				continue;
7202			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7203				continue;
7204			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7205			    relative_target_port_identifier);
7206			pc++;
7207		}
7208		tpg_desc->target_port_count = pc;
7209		tpg_desc = (struct scsi_target_port_group_descriptor *)
7210		    &tpg_desc->descriptors[pc];
7211	}
7212	for (g = 0; g < num_ha_groups; g++) {
7213		tpg_desc->pref_state = (g == pg) ? ts : os;
7214		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7215		    TPG_U_SUP | TPG_T_SUP;
7216		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7217		tpg_desc->status = TPG_IMPLICIT;
7218		pc = 0;
7219		STAILQ_FOREACH(port, &softc->port_list, links) {
7220			if (port->targ_port < g * softc->port_cnt ||
7221			    port->targ_port >= (g + 1) * softc->port_cnt)
7222				continue;
7223			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7224				continue;
7225			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7226				continue;
7227			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7228				continue;
7229			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7230			    relative_target_port_identifier);
7231			pc++;
7232		}
7233		tpg_desc->target_port_count = pc;
7234		tpg_desc = (struct scsi_target_port_group_descriptor *)
7235		    &tpg_desc->descriptors[pc];
7236	}
7237	mtx_unlock(&softc->ctl_lock);
7238
7239	ctl_set_success(ctsio);
7240	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7241	ctsio->be_move_done = ctl_config_move_done;
7242	ctl_datamove((union ctl_io *)ctsio);
7243	return(retval);
7244}
7245
7246int
7247ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7248{
7249	struct ctl_lun *lun = CTL_LUN(ctsio);
7250	struct scsi_report_supported_opcodes *cdb;
7251	const struct ctl_cmd_entry *entry, *sentry;
7252	struct scsi_report_supported_opcodes_all *all;
7253	struct scsi_report_supported_opcodes_descr *descr;
7254	struct scsi_report_supported_opcodes_one *one;
7255	int retval;
7256	int alloc_len, total_len;
7257	int opcode, service_action, i, j, num;
7258
7259	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7260
7261	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7262	retval = CTL_RETVAL_COMPLETE;
7263
7264	opcode = cdb->requested_opcode;
7265	service_action = scsi_2btoul(cdb->requested_service_action);
7266	switch (cdb->options & RSO_OPTIONS_MASK) {
7267	case RSO_OPTIONS_ALL:
7268		num = 0;
7269		for (i = 0; i < 256; i++) {
7270			entry = &ctl_cmd_table[i];
7271			if (entry->flags & CTL_CMD_FLAG_SA5) {
7272				for (j = 0; j < 32; j++) {
7273					sentry = &((const struct ctl_cmd_entry *)
7274					    entry->execute)[j];
7275					if (ctl_cmd_applicable(
7276					    lun->be_lun->lun_type, sentry))
7277						num++;
7278				}
7279			} else {
7280				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7281				    entry))
7282					num++;
7283			}
7284		}
7285		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7286		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7287		break;
7288	case RSO_OPTIONS_OC:
7289		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7290			ctl_set_invalid_field(/*ctsio*/ ctsio,
7291					      /*sks_valid*/ 1,
7292					      /*command*/ 1,
7293					      /*field*/ 2,
7294					      /*bit_valid*/ 1,
7295					      /*bit*/ 2);
7296			ctl_done((union ctl_io *)ctsio);
7297			return (CTL_RETVAL_COMPLETE);
7298		}
7299		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7300		break;
7301	case RSO_OPTIONS_OC_SA:
7302		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7303		    service_action >= 32) {
7304			ctl_set_invalid_field(/*ctsio*/ ctsio,
7305					      /*sks_valid*/ 1,
7306					      /*command*/ 1,
7307					      /*field*/ 2,
7308					      /*bit_valid*/ 1,
7309					      /*bit*/ 2);
7310			ctl_done((union ctl_io *)ctsio);
7311			return (CTL_RETVAL_COMPLETE);
7312		}
7313		/* FALLTHROUGH */
7314	case RSO_OPTIONS_OC_ASA:
7315		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7316		break;
7317	default:
7318		ctl_set_invalid_field(/*ctsio*/ ctsio,
7319				      /*sks_valid*/ 1,
7320				      /*command*/ 1,
7321				      /*field*/ 2,
7322				      /*bit_valid*/ 1,
7323				      /*bit*/ 2);
7324		ctl_done((union ctl_io *)ctsio);
7325		return (CTL_RETVAL_COMPLETE);
7326	}
7327
7328	alloc_len = scsi_4btoul(cdb->length);
7329
7330	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7331
7332	ctsio->kern_sg_entries = 0;
7333
7334	if (total_len < alloc_len) {
7335		ctsio->residual = alloc_len - total_len;
7336		ctsio->kern_data_len = total_len;
7337		ctsio->kern_total_len = total_len;
7338	} else {
7339		ctsio->residual = 0;
7340		ctsio->kern_data_len = alloc_len;
7341		ctsio->kern_total_len = alloc_len;
7342	}
7343	ctsio->kern_data_resid = 0;
7344	ctsio->kern_rel_offset = 0;
7345
7346	switch (cdb->options & RSO_OPTIONS_MASK) {
7347	case RSO_OPTIONS_ALL:
7348		all = (struct scsi_report_supported_opcodes_all *)
7349		    ctsio->kern_data_ptr;
7350		num = 0;
7351		for (i = 0; i < 256; i++) {
7352			entry = &ctl_cmd_table[i];
7353			if (entry->flags & CTL_CMD_FLAG_SA5) {
7354				for (j = 0; j < 32; j++) {
7355					sentry = &((const struct ctl_cmd_entry *)
7356					    entry->execute)[j];
7357					if (!ctl_cmd_applicable(
7358					    lun->be_lun->lun_type, sentry))
7359						continue;
7360					descr = &all->descr[num++];
7361					descr->opcode = i;
7362					scsi_ulto2b(j, descr->service_action);
7363					descr->flags = RSO_SERVACTV;
7364					scsi_ulto2b(sentry->length,
7365					    descr->cdb_length);
7366				}
7367			} else {
7368				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7369				    entry))
7370					continue;
7371				descr = &all->descr[num++];
7372				descr->opcode = i;
7373				scsi_ulto2b(0, descr->service_action);
7374				descr->flags = 0;
7375				scsi_ulto2b(entry->length, descr->cdb_length);
7376			}
7377		}
7378		scsi_ulto4b(
7379		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7380		    all->length);
7381		break;
7382	case RSO_OPTIONS_OC:
7383		one = (struct scsi_report_supported_opcodes_one *)
7384		    ctsio->kern_data_ptr;
7385		entry = &ctl_cmd_table[opcode];
7386		goto fill_one;
7387	case RSO_OPTIONS_OC_SA:
7388		one = (struct scsi_report_supported_opcodes_one *)
7389		    ctsio->kern_data_ptr;
7390		entry = &ctl_cmd_table[opcode];
7391		entry = &((const struct ctl_cmd_entry *)
7392		    entry->execute)[service_action];
7393fill_one:
7394		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7395			one->support = 3;
7396			scsi_ulto2b(entry->length, one->cdb_length);
7397			one->cdb_usage[0] = opcode;
7398			memcpy(&one->cdb_usage[1], entry->usage,
7399			    entry->length - 1);
7400		} else
7401			one->support = 1;
7402		break;
7403	case RSO_OPTIONS_OC_ASA:
7404		one = (struct scsi_report_supported_opcodes_one *)
7405		    ctsio->kern_data_ptr;
7406		entry = &ctl_cmd_table[opcode];
7407		if (entry->flags & CTL_CMD_FLAG_SA5) {
7408			entry = &((const struct ctl_cmd_entry *)
7409			    entry->execute)[service_action];
7410		} else if (service_action != 0) {
7411			one->support = 1;
7412			break;
7413		}
7414		goto fill_one;
7415	}
7416
7417	ctl_set_success(ctsio);
7418	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7419	ctsio->be_move_done = ctl_config_move_done;
7420	ctl_datamove((union ctl_io *)ctsio);
7421	return(retval);
7422}
7423
7424int
7425ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7426{
7427	struct scsi_report_supported_tmf *cdb;
7428	struct scsi_report_supported_tmf_ext_data *data;
7429	int retval;
7430	int alloc_len, total_len;
7431
7432	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7433
7434	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7435
7436	retval = CTL_RETVAL_COMPLETE;
7437
7438	if (cdb->options & RST_REPD)
7439		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7440	else
7441		total_len = sizeof(struct scsi_report_supported_tmf_data);
7442	alloc_len = scsi_4btoul(cdb->length);
7443
7444	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7445
7446	ctsio->kern_sg_entries = 0;
7447
7448	if (total_len < alloc_len) {
7449		ctsio->residual = alloc_len - total_len;
7450		ctsio->kern_data_len = total_len;
7451		ctsio->kern_total_len = total_len;
7452	} else {
7453		ctsio->residual = 0;
7454		ctsio->kern_data_len = alloc_len;
7455		ctsio->kern_total_len = alloc_len;
7456	}
7457	ctsio->kern_data_resid = 0;
7458	ctsio->kern_rel_offset = 0;
7459
7460	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7461	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7462	    RST_TRS;
7463	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7464	data->length = total_len - 4;
7465
7466	ctl_set_success(ctsio);
7467	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7468	ctsio->be_move_done = ctl_config_move_done;
7469	ctl_datamove((union ctl_io *)ctsio);
7470	return (retval);
7471}
7472
7473int
7474ctl_report_timestamp(struct ctl_scsiio *ctsio)
7475{
7476	struct scsi_report_timestamp *cdb;
7477	struct scsi_report_timestamp_data *data;
7478	struct timeval tv;
7479	int64_t timestamp;
7480	int retval;
7481	int alloc_len, total_len;
7482
7483	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7484
7485	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7486
7487	retval = CTL_RETVAL_COMPLETE;
7488
7489	total_len = sizeof(struct scsi_report_timestamp_data);
7490	alloc_len = scsi_4btoul(cdb->length);
7491
7492	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7493
7494	ctsio->kern_sg_entries = 0;
7495
7496	if (total_len < alloc_len) {
7497		ctsio->residual = alloc_len - total_len;
7498		ctsio->kern_data_len = total_len;
7499		ctsio->kern_total_len = total_len;
7500	} else {
7501		ctsio->residual = 0;
7502		ctsio->kern_data_len = alloc_len;
7503		ctsio->kern_total_len = alloc_len;
7504	}
7505	ctsio->kern_data_resid = 0;
7506	ctsio->kern_rel_offset = 0;
7507
7508	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7509	scsi_ulto2b(sizeof(*data) - 2, data->length);
7510	data->origin = RTS_ORIG_OUTSIDE;
7511	getmicrotime(&tv);
7512	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7513	scsi_ulto4b(timestamp >> 16, data->timestamp);
7514	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7515
7516	ctl_set_success(ctsio);
7517	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7518	ctsio->be_move_done = ctl_config_move_done;
7519	ctl_datamove((union ctl_io *)ctsio);
7520	return (retval);
7521}
7522
7523int
7524ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7525{
7526	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7527	struct ctl_lun *lun = CTL_LUN(ctsio);
7528	struct scsi_per_res_in *cdb;
7529	int alloc_len, total_len = 0;
7530	/* struct scsi_per_res_in_rsrv in_data; */
7531	uint64_t key;
7532
7533	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7534
7535	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7536
7537	alloc_len = scsi_2btoul(cdb->length);
7538
7539retry:
7540	mtx_lock(&lun->lun_lock);
7541	switch (cdb->action) {
7542	case SPRI_RK: /* read keys */
7543		total_len = sizeof(struct scsi_per_res_in_keys) +
7544			lun->pr_key_count *
7545			sizeof(struct scsi_per_res_key);
7546		break;
7547	case SPRI_RR: /* read reservation */
7548		if (lun->flags & CTL_LUN_PR_RESERVED)
7549			total_len = sizeof(struct scsi_per_res_in_rsrv);
7550		else
7551			total_len = sizeof(struct scsi_per_res_in_header);
7552		break;
7553	case SPRI_RC: /* report capabilities */
7554		total_len = sizeof(struct scsi_per_res_cap);
7555		break;
7556	case SPRI_RS: /* read full status */
7557		total_len = sizeof(struct scsi_per_res_in_header) +
7558		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7559		    lun->pr_key_count;
7560		break;
7561	default:
7562		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7563	}
7564	mtx_unlock(&lun->lun_lock);
7565
7566	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7567
7568	if (total_len < alloc_len) {
7569		ctsio->residual = alloc_len - total_len;
7570		ctsio->kern_data_len = total_len;
7571		ctsio->kern_total_len = total_len;
7572	} else {
7573		ctsio->residual = 0;
7574		ctsio->kern_data_len = alloc_len;
7575		ctsio->kern_total_len = alloc_len;
7576	}
7577
7578	ctsio->kern_data_resid = 0;
7579	ctsio->kern_rel_offset = 0;
7580	ctsio->kern_sg_entries = 0;
7581
7582	mtx_lock(&lun->lun_lock);
7583	switch (cdb->action) {
7584	case SPRI_RK: { // read keys
7585        struct scsi_per_res_in_keys *res_keys;
7586		int i, key_count;
7587
7588		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7589
7590		/*
7591		 * We had to drop the lock to allocate our buffer, which
7592		 * leaves time for someone to come in with another
7593		 * persistent reservation.  (That is unlikely, though,
7594		 * since this should be the only persistent reservation
7595		 * command active right now.)
7596		 */
7597		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7598		    (lun->pr_key_count *
7599		     sizeof(struct scsi_per_res_key)))){
7600			mtx_unlock(&lun->lun_lock);
7601			free(ctsio->kern_data_ptr, M_CTL);
7602			printf("%s: reservation length changed, retrying\n",
7603			       __func__);
7604			goto retry;
7605		}
7606
7607		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7608
7609		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7610			     lun->pr_key_count, res_keys->header.length);
7611
7612		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7613			if ((key = ctl_get_prkey(lun, i)) == 0)
7614				continue;
7615
7616			/*
7617			 * We used lun->pr_key_count to calculate the
7618			 * size to allocate.  If it turns out the number of
7619			 * initiators with the registered flag set is
7620			 * larger than that (i.e. they haven't been kept in
7621			 * sync), we've got a problem.
7622			 */
7623			if (key_count >= lun->pr_key_count) {
7624				key_count++;
7625				continue;
7626			}
7627			scsi_u64to8b(key, res_keys->keys[key_count].key);
7628			key_count++;
7629		}
7630		break;
7631	}
7632	case SPRI_RR: { // read reservation
7633		struct scsi_per_res_in_rsrv *res;
7634		int tmp_len, header_only;
7635
7636		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7637
7638		scsi_ulto4b(lun->pr_generation, res->header.generation);
7639
7640		if (lun->flags & CTL_LUN_PR_RESERVED)
7641		{
7642			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7643			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7644				    res->header.length);
7645			header_only = 0;
7646		} else {
7647			tmp_len = sizeof(struct scsi_per_res_in_header);
7648			scsi_ulto4b(0, res->header.length);
7649			header_only = 1;
7650		}
7651
7652		/*
7653		 * We had to drop the lock to allocate our buffer, which
7654		 * leaves time for someone to come in with another
7655		 * persistent reservation.  (That is unlikely, though,
7656		 * since this should be the only persistent reservation
7657		 * command active right now.)
7658		 */
7659		if (tmp_len != total_len) {
7660			mtx_unlock(&lun->lun_lock);
7661			free(ctsio->kern_data_ptr, M_CTL);
7662			printf("%s: reservation status changed, retrying\n",
7663			       __func__);
7664			goto retry;
7665		}
7666
7667		/*
7668		 * No reservation held, so we're done.
7669		 */
7670		if (header_only != 0)
7671			break;
7672
7673		/*
7674		 * If the registration is an All Registrants type, the key
7675		 * is 0, since it doesn't really matter.
7676		 */
7677		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7678			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7679			    res->data.reservation);
7680		}
7681		res->data.scopetype = lun->pr_res_type;
7682		break;
7683	}
7684	case SPRI_RC:     //report capabilities
7685	{
7686		struct scsi_per_res_cap *res_cap;
7687		uint16_t type_mask;
7688
7689		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7690		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7691		res_cap->flags1 = SPRI_CRH;
7692		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7693		type_mask = SPRI_TM_WR_EX_AR |
7694			    SPRI_TM_EX_AC_RO |
7695			    SPRI_TM_WR_EX_RO |
7696			    SPRI_TM_EX_AC |
7697			    SPRI_TM_WR_EX |
7698			    SPRI_TM_EX_AC_AR;
7699		scsi_ulto2b(type_mask, res_cap->type_mask);
7700		break;
7701	}
7702	case SPRI_RS: { // read full status
7703		struct scsi_per_res_in_full *res_status;
7704		struct scsi_per_res_in_full_desc *res_desc;
7705		struct ctl_port *port;
7706		int i, len;
7707
7708		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7709
7710		/*
7711		 * We had to drop the lock to allocate our buffer, which
7712		 * leaves time for someone to come in with another
7713		 * persistent reservation.  (That is unlikely, though,
7714		 * since this should be the only persistent reservation
7715		 * command active right now.)
7716		 */
7717		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7718		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7719		     lun->pr_key_count)){
7720			mtx_unlock(&lun->lun_lock);
7721			free(ctsio->kern_data_ptr, M_CTL);
7722			printf("%s: reservation length changed, retrying\n",
7723			       __func__);
7724			goto retry;
7725		}
7726
7727		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7728
7729		res_desc = &res_status->desc[0];
7730		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7731			if ((key = ctl_get_prkey(lun, i)) == 0)
7732				continue;
7733
7734			scsi_u64to8b(key, res_desc->res_key.key);
7735			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7736			    (lun->pr_res_idx == i ||
7737			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7738				res_desc->flags = SPRI_FULL_R_HOLDER;
7739				res_desc->scopetype = lun->pr_res_type;
7740			}
7741			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7742			    res_desc->rel_trgt_port_id);
7743			len = 0;
7744			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7745			if (port != NULL)
7746				len = ctl_create_iid(port,
7747				    i % CTL_MAX_INIT_PER_PORT,
7748				    res_desc->transport_id);
7749			scsi_ulto4b(len, res_desc->additional_length);
7750			res_desc = (struct scsi_per_res_in_full_desc *)
7751			    &res_desc->transport_id[len];
7752		}
7753		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7754		    res_status->header.length);
7755		break;
7756	}
7757	default:
7758		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7759	}
7760	mtx_unlock(&lun->lun_lock);
7761
7762	ctl_set_success(ctsio);
7763	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7764	ctsio->be_move_done = ctl_config_move_done;
7765	ctl_datamove((union ctl_io *)ctsio);
7766	return (CTL_RETVAL_COMPLETE);
7767}
7768
7769/*
7770 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7771 * it should return.
7772 */
7773static int
7774ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7775		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7776		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7777		struct scsi_per_res_out_parms* param)
7778{
7779	union ctl_ha_msg persis_io;
7780	int i;
7781
7782	mtx_lock(&lun->lun_lock);
7783	if (sa_res_key == 0) {
7784		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7785			/* validate scope and type */
7786			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7787			     SPR_LU_SCOPE) {
7788				mtx_unlock(&lun->lun_lock);
7789				ctl_set_invalid_field(/*ctsio*/ ctsio,
7790						      /*sks_valid*/ 1,
7791						      /*command*/ 1,
7792						      /*field*/ 2,
7793						      /*bit_valid*/ 1,
7794						      /*bit*/ 4);
7795				ctl_done((union ctl_io *)ctsio);
7796				return (1);
7797			}
7798
7799		        if (type>8 || type==2 || type==4 || type==0) {
7800				mtx_unlock(&lun->lun_lock);
7801				ctl_set_invalid_field(/*ctsio*/ ctsio,
7802       	           				      /*sks_valid*/ 1,
7803						      /*command*/ 1,
7804						      /*field*/ 2,
7805						      /*bit_valid*/ 1,
7806						      /*bit*/ 0);
7807				ctl_done((union ctl_io *)ctsio);
7808				return (1);
7809		        }
7810
7811			/*
7812			 * Unregister everybody else and build UA for
7813			 * them
7814			 */
7815			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7816				if (i == residx || ctl_get_prkey(lun, i) == 0)
7817					continue;
7818
7819				ctl_clr_prkey(lun, i);
7820				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7821			}
7822			lun->pr_key_count = 1;
7823			lun->pr_res_type = type;
7824			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7825			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7826				lun->pr_res_idx = residx;
7827			lun->pr_generation++;
7828			mtx_unlock(&lun->lun_lock);
7829
7830			/* send msg to other side */
7831			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7832			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7833			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7834			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7835			persis_io.pr.pr_info.res_type = type;
7836			memcpy(persis_io.pr.pr_info.sa_res_key,
7837			       param->serv_act_res_key,
7838			       sizeof(param->serv_act_res_key));
7839			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7840			    sizeof(persis_io.pr), M_WAITOK);
7841		} else {
7842			/* not all registrants */
7843			mtx_unlock(&lun->lun_lock);
7844			free(ctsio->kern_data_ptr, M_CTL);
7845			ctl_set_invalid_field(ctsio,
7846					      /*sks_valid*/ 1,
7847					      /*command*/ 0,
7848					      /*field*/ 8,
7849					      /*bit_valid*/ 0,
7850					      /*bit*/ 0);
7851			ctl_done((union ctl_io *)ctsio);
7852			return (1);
7853		}
7854	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7855		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7856		int found = 0;
7857
7858		if (res_key == sa_res_key) {
7859			/* special case */
7860			/*
7861			 * The spec implies this is not good but doesn't
7862			 * say what to do. There are two choices either
7863			 * generate a res conflict or check condition
7864			 * with illegal field in parameter data. Since
7865			 * that is what is done when the sa_res_key is
7866			 * zero I'll take that approach since this has
7867			 * to do with the sa_res_key.
7868			 */
7869			mtx_unlock(&lun->lun_lock);
7870			free(ctsio->kern_data_ptr, M_CTL);
7871			ctl_set_invalid_field(ctsio,
7872					      /*sks_valid*/ 1,
7873					      /*command*/ 0,
7874					      /*field*/ 8,
7875					      /*bit_valid*/ 0,
7876					      /*bit*/ 0);
7877			ctl_done((union ctl_io *)ctsio);
7878			return (1);
7879		}
7880
7881		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7882			if (ctl_get_prkey(lun, i) != sa_res_key)
7883				continue;
7884
7885			found = 1;
7886			ctl_clr_prkey(lun, i);
7887			lun->pr_key_count--;
7888			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7889		}
7890		if (!found) {
7891			mtx_unlock(&lun->lun_lock);
7892			free(ctsio->kern_data_ptr, M_CTL);
7893			ctl_set_reservation_conflict(ctsio);
7894			ctl_done((union ctl_io *)ctsio);
7895			return (CTL_RETVAL_COMPLETE);
7896		}
7897		lun->pr_generation++;
7898		mtx_unlock(&lun->lun_lock);
7899
7900		/* send msg to other side */
7901		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7902		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7903		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7904		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7905		persis_io.pr.pr_info.res_type = type;
7906		memcpy(persis_io.pr.pr_info.sa_res_key,
7907		       param->serv_act_res_key,
7908		       sizeof(param->serv_act_res_key));
7909		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7910		    sizeof(persis_io.pr), M_WAITOK);
7911	} else {
7912		/* Reserved but not all registrants */
7913		/* sa_res_key is res holder */
7914		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7915			/* validate scope and type */
7916			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7917			     SPR_LU_SCOPE) {
7918				mtx_unlock(&lun->lun_lock);
7919				ctl_set_invalid_field(/*ctsio*/ ctsio,
7920						      /*sks_valid*/ 1,
7921						      /*command*/ 1,
7922						      /*field*/ 2,
7923						      /*bit_valid*/ 1,
7924						      /*bit*/ 4);
7925				ctl_done((union ctl_io *)ctsio);
7926				return (1);
7927			}
7928
7929			if (type>8 || type==2 || type==4 || type==0) {
7930				mtx_unlock(&lun->lun_lock);
7931				ctl_set_invalid_field(/*ctsio*/ ctsio,
7932						      /*sks_valid*/ 1,
7933						      /*command*/ 1,
7934						      /*field*/ 2,
7935						      /*bit_valid*/ 1,
7936						      /*bit*/ 0);
7937				ctl_done((union ctl_io *)ctsio);
7938				return (1);
7939			}
7940
7941			/*
7942			 * Do the following:
7943			 * if sa_res_key != res_key remove all
7944			 * registrants w/sa_res_key and generate UA
7945			 * for these registrants(Registrations
7946			 * Preempted) if it wasn't an exclusive
7947			 * reservation generate UA(Reservations
7948			 * Preempted) for all other registered nexuses
7949			 * if the type has changed. Establish the new
7950			 * reservation and holder. If res_key and
7951			 * sa_res_key are the same do the above
7952			 * except don't unregister the res holder.
7953			 */
7954
7955			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7956				if (i == residx || ctl_get_prkey(lun, i) == 0)
7957					continue;
7958
7959				if (sa_res_key == ctl_get_prkey(lun, i)) {
7960					ctl_clr_prkey(lun, i);
7961					lun->pr_key_count--;
7962					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7963				} else if (type != lun->pr_res_type &&
7964				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7965				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7966					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7967				}
7968			}
7969			lun->pr_res_type = type;
7970			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7971			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7972				lun->pr_res_idx = residx;
7973			else
7974				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7975			lun->pr_generation++;
7976			mtx_unlock(&lun->lun_lock);
7977
7978			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7979			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7980			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7981			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7982			persis_io.pr.pr_info.res_type = type;
7983			memcpy(persis_io.pr.pr_info.sa_res_key,
7984			       param->serv_act_res_key,
7985			       sizeof(param->serv_act_res_key));
7986			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7987			    sizeof(persis_io.pr), M_WAITOK);
7988		} else {
7989			/*
7990			 * sa_res_key is not the res holder just
7991			 * remove registrants
7992			 */
7993			int found=0;
7994
7995			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7996				if (sa_res_key != ctl_get_prkey(lun, i))
7997					continue;
7998
7999				found = 1;
8000				ctl_clr_prkey(lun, i);
8001				lun->pr_key_count--;
8002				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8003			}
8004
8005			if (!found) {
8006				mtx_unlock(&lun->lun_lock);
8007				free(ctsio->kern_data_ptr, M_CTL);
8008				ctl_set_reservation_conflict(ctsio);
8009				ctl_done((union ctl_io *)ctsio);
8010		        	return (1);
8011			}
8012			lun->pr_generation++;
8013			mtx_unlock(&lun->lun_lock);
8014
8015			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8016			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8017			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8018			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8019			persis_io.pr.pr_info.res_type = type;
8020			memcpy(persis_io.pr.pr_info.sa_res_key,
8021			       param->serv_act_res_key,
8022			       sizeof(param->serv_act_res_key));
8023			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8024			    sizeof(persis_io.pr), M_WAITOK);
8025		}
8026	}
8027	return (0);
8028}
8029
8030static void
8031ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8032{
8033	uint64_t sa_res_key;
8034	int i;
8035
8036	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8037
8038	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8039	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8040	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8041		if (sa_res_key == 0) {
8042			/*
8043			 * Unregister everybody else and build UA for
8044			 * them
8045			 */
8046			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8047				if (i == msg->pr.pr_info.residx ||
8048				    ctl_get_prkey(lun, i) == 0)
8049					continue;
8050
8051				ctl_clr_prkey(lun, i);
8052				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8053			}
8054
8055			lun->pr_key_count = 1;
8056			lun->pr_res_type = msg->pr.pr_info.res_type;
8057			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8058			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8059				lun->pr_res_idx = msg->pr.pr_info.residx;
8060		} else {
8061		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8062				if (sa_res_key == ctl_get_prkey(lun, i))
8063					continue;
8064
8065				ctl_clr_prkey(lun, i);
8066				lun->pr_key_count--;
8067				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8068			}
8069		}
8070	} else {
8071		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8072			if (i == msg->pr.pr_info.residx ||
8073			    ctl_get_prkey(lun, i) == 0)
8074				continue;
8075
8076			if (sa_res_key == ctl_get_prkey(lun, i)) {
8077				ctl_clr_prkey(lun, i);
8078				lun->pr_key_count--;
8079				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8080			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8081			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8082			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8083				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8084			}
8085		}
8086		lun->pr_res_type = msg->pr.pr_info.res_type;
8087		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8088		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8089			lun->pr_res_idx = msg->pr.pr_info.residx;
8090		else
8091			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8092	}
8093	lun->pr_generation++;
8094
8095}
8096
8097
8098int
8099ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8100{
8101	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8102	struct ctl_lun *lun = CTL_LUN(ctsio);
8103	int retval;
8104	u_int32_t param_len;
8105	struct scsi_per_res_out *cdb;
8106	struct scsi_per_res_out_parms* param;
8107	uint32_t residx;
8108	uint64_t res_key, sa_res_key, key;
8109	uint8_t type;
8110	union ctl_ha_msg persis_io;
8111	int    i;
8112
8113	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8114
8115	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8116	retval = CTL_RETVAL_COMPLETE;
8117
8118	/*
8119	 * We only support whole-LUN scope.  The scope & type are ignored for
8120	 * register, register and ignore existing key and clear.
8121	 * We sometimes ignore scope and type on preempts too!!
8122	 * Verify reservation type here as well.
8123	 */
8124	type = cdb->scope_type & SPR_TYPE_MASK;
8125	if ((cdb->action == SPRO_RESERVE)
8126	 || (cdb->action == SPRO_RELEASE)) {
8127		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8128			ctl_set_invalid_field(/*ctsio*/ ctsio,
8129					      /*sks_valid*/ 1,
8130					      /*command*/ 1,
8131					      /*field*/ 2,
8132					      /*bit_valid*/ 1,
8133					      /*bit*/ 4);
8134			ctl_done((union ctl_io *)ctsio);
8135			return (CTL_RETVAL_COMPLETE);
8136		}
8137
8138		if (type>8 || type==2 || type==4 || type==0) {
8139			ctl_set_invalid_field(/*ctsio*/ ctsio,
8140					      /*sks_valid*/ 1,
8141					      /*command*/ 1,
8142					      /*field*/ 2,
8143					      /*bit_valid*/ 1,
8144					      /*bit*/ 0);
8145			ctl_done((union ctl_io *)ctsio);
8146			return (CTL_RETVAL_COMPLETE);
8147		}
8148	}
8149
8150	param_len = scsi_4btoul(cdb->length);
8151
8152	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8153		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8154		ctsio->kern_data_len = param_len;
8155		ctsio->kern_total_len = param_len;
8156		ctsio->kern_data_resid = 0;
8157		ctsio->kern_rel_offset = 0;
8158		ctsio->kern_sg_entries = 0;
8159		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8160		ctsio->be_move_done = ctl_config_move_done;
8161		ctl_datamove((union ctl_io *)ctsio);
8162
8163		return (CTL_RETVAL_COMPLETE);
8164	}
8165
8166	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8167
8168	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8169	res_key = scsi_8btou64(param->res_key.key);
8170	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8171
8172	/*
8173	 * Validate the reservation key here except for SPRO_REG_IGNO
8174	 * This must be done for all other service actions
8175	 */
8176	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8177		mtx_lock(&lun->lun_lock);
8178		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8179			if (res_key != key) {
8180				/*
8181				 * The current key passed in doesn't match
8182				 * the one the initiator previously
8183				 * registered.
8184				 */
8185				mtx_unlock(&lun->lun_lock);
8186				free(ctsio->kern_data_ptr, M_CTL);
8187				ctl_set_reservation_conflict(ctsio);
8188				ctl_done((union ctl_io *)ctsio);
8189				return (CTL_RETVAL_COMPLETE);
8190			}
8191		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8192			/*
8193			 * We are not registered
8194			 */
8195			mtx_unlock(&lun->lun_lock);
8196			free(ctsio->kern_data_ptr, M_CTL);
8197			ctl_set_reservation_conflict(ctsio);
8198			ctl_done((union ctl_io *)ctsio);
8199			return (CTL_RETVAL_COMPLETE);
8200		} else if (res_key != 0) {
8201			/*
8202			 * We are not registered and trying to register but
8203			 * the register key isn't zero.
8204			 */
8205			mtx_unlock(&lun->lun_lock);
8206			free(ctsio->kern_data_ptr, M_CTL);
8207			ctl_set_reservation_conflict(ctsio);
8208			ctl_done((union ctl_io *)ctsio);
8209			return (CTL_RETVAL_COMPLETE);
8210		}
8211		mtx_unlock(&lun->lun_lock);
8212	}
8213
8214	switch (cdb->action & SPRO_ACTION_MASK) {
8215	case SPRO_REGISTER:
8216	case SPRO_REG_IGNO: {
8217
8218#if 0
8219		printf("Registration received\n");
8220#endif
8221
8222		/*
8223		 * We don't support any of these options, as we report in
8224		 * the read capabilities request (see
8225		 * ctl_persistent_reserve_in(), above).
8226		 */
8227		if ((param->flags & SPR_SPEC_I_PT)
8228		 || (param->flags & SPR_ALL_TG_PT)
8229		 || (param->flags & SPR_APTPL)) {
8230			int bit_ptr;
8231
8232			if (param->flags & SPR_APTPL)
8233				bit_ptr = 0;
8234			else if (param->flags & SPR_ALL_TG_PT)
8235				bit_ptr = 2;
8236			else /* SPR_SPEC_I_PT */
8237				bit_ptr = 3;
8238
8239			free(ctsio->kern_data_ptr, M_CTL);
8240			ctl_set_invalid_field(ctsio,
8241					      /*sks_valid*/ 1,
8242					      /*command*/ 0,
8243					      /*field*/ 20,
8244					      /*bit_valid*/ 1,
8245					      /*bit*/ bit_ptr);
8246			ctl_done((union ctl_io *)ctsio);
8247			return (CTL_RETVAL_COMPLETE);
8248		}
8249
8250		mtx_lock(&lun->lun_lock);
8251
8252		/*
8253		 * The initiator wants to clear the
8254		 * key/unregister.
8255		 */
8256		if (sa_res_key == 0) {
8257			if ((res_key == 0
8258			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8259			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8260			  && ctl_get_prkey(lun, residx) == 0)) {
8261				mtx_unlock(&lun->lun_lock);
8262				goto done;
8263			}
8264
8265			ctl_clr_prkey(lun, residx);
8266			lun->pr_key_count--;
8267
8268			if (residx == lun->pr_res_idx) {
8269				lun->flags &= ~CTL_LUN_PR_RESERVED;
8270				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8271
8272				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8273				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8274				    lun->pr_key_count) {
8275					/*
8276					 * If the reservation is a registrants
8277					 * only type we need to generate a UA
8278					 * for other registered inits.  The
8279					 * sense code should be RESERVATIONS
8280					 * RELEASED
8281					 */
8282
8283					for (i = softc->init_min; i < softc->init_max; i++){
8284						if (ctl_get_prkey(lun, i) == 0)
8285							continue;
8286						ctl_est_ua(lun, i,
8287						    CTL_UA_RES_RELEASE);
8288					}
8289				}
8290				lun->pr_res_type = 0;
8291			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8292				if (lun->pr_key_count==0) {
8293					lun->flags &= ~CTL_LUN_PR_RESERVED;
8294					lun->pr_res_type = 0;
8295					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8296				}
8297			}
8298			lun->pr_generation++;
8299			mtx_unlock(&lun->lun_lock);
8300
8301			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8302			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8303			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8304			persis_io.pr.pr_info.residx = residx;
8305			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8306			    sizeof(persis_io.pr), M_WAITOK);
8307		} else /* sa_res_key != 0 */ {
8308
8309			/*
8310			 * If we aren't registered currently then increment
8311			 * the key count and set the registered flag.
8312			 */
8313			ctl_alloc_prkey(lun, residx);
8314			if (ctl_get_prkey(lun, residx) == 0)
8315				lun->pr_key_count++;
8316			ctl_set_prkey(lun, residx, sa_res_key);
8317			lun->pr_generation++;
8318			mtx_unlock(&lun->lun_lock);
8319
8320			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8321			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8322			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8323			persis_io.pr.pr_info.residx = residx;
8324			memcpy(persis_io.pr.pr_info.sa_res_key,
8325			       param->serv_act_res_key,
8326			       sizeof(param->serv_act_res_key));
8327			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8328			    sizeof(persis_io.pr), M_WAITOK);
8329		}
8330
8331		break;
8332	}
8333	case SPRO_RESERVE:
8334#if 0
8335                printf("Reserve executed type %d\n", type);
8336#endif
8337		mtx_lock(&lun->lun_lock);
8338		if (lun->flags & CTL_LUN_PR_RESERVED) {
8339			/*
8340			 * if this isn't the reservation holder and it's
8341			 * not a "all registrants" type or if the type is
8342			 * different then we have a conflict
8343			 */
8344			if ((lun->pr_res_idx != residx
8345			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8346			 || lun->pr_res_type != type) {
8347				mtx_unlock(&lun->lun_lock);
8348				free(ctsio->kern_data_ptr, M_CTL);
8349				ctl_set_reservation_conflict(ctsio);
8350				ctl_done((union ctl_io *)ctsio);
8351				return (CTL_RETVAL_COMPLETE);
8352			}
8353			mtx_unlock(&lun->lun_lock);
8354		} else /* create a reservation */ {
8355			/*
8356			 * If it's not an "all registrants" type record
8357			 * reservation holder
8358			 */
8359			if (type != SPR_TYPE_WR_EX_AR
8360			 && type != SPR_TYPE_EX_AC_AR)
8361				lun->pr_res_idx = residx; /* Res holder */
8362			else
8363				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8364
8365			lun->flags |= CTL_LUN_PR_RESERVED;
8366			lun->pr_res_type = type;
8367
8368			mtx_unlock(&lun->lun_lock);
8369
8370			/* send msg to other side */
8371			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8372			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8373			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8374			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8375			persis_io.pr.pr_info.res_type = type;
8376			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8377			    sizeof(persis_io.pr), M_WAITOK);
8378		}
8379		break;
8380
8381	case SPRO_RELEASE:
8382		mtx_lock(&lun->lun_lock);
8383		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8384			/* No reservation exists return good status */
8385			mtx_unlock(&lun->lun_lock);
8386			goto done;
8387		}
8388		/*
8389		 * Is this nexus a reservation holder?
8390		 */
8391		if (lun->pr_res_idx != residx
8392		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8393			/*
8394			 * not a res holder return good status but
8395			 * do nothing
8396			 */
8397			mtx_unlock(&lun->lun_lock);
8398			goto done;
8399		}
8400
8401		if (lun->pr_res_type != type) {
8402			mtx_unlock(&lun->lun_lock);
8403			free(ctsio->kern_data_ptr, M_CTL);
8404			ctl_set_illegal_pr_release(ctsio);
8405			ctl_done((union ctl_io *)ctsio);
8406			return (CTL_RETVAL_COMPLETE);
8407		}
8408
8409		/* okay to release */
8410		lun->flags &= ~CTL_LUN_PR_RESERVED;
8411		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8412		lun->pr_res_type = 0;
8413
8414		/*
8415		 * If this isn't an exclusive access reservation and NUAR
8416		 * is not set, generate UA for all other registrants.
8417		 */
8418		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8419		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8420			for (i = softc->init_min; i < softc->init_max; i++) {
8421				if (i == residx || ctl_get_prkey(lun, i) == 0)
8422					continue;
8423				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8424			}
8425		}
8426		mtx_unlock(&lun->lun_lock);
8427
8428		/* Send msg to other side */
8429		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8430		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8431		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8432		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8433		     sizeof(persis_io.pr), M_WAITOK);
8434		break;
8435
8436	case SPRO_CLEAR:
8437		/* send msg to other side */
8438
8439		mtx_lock(&lun->lun_lock);
8440		lun->flags &= ~CTL_LUN_PR_RESERVED;
8441		lun->pr_res_type = 0;
8442		lun->pr_key_count = 0;
8443		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8444
8445		ctl_clr_prkey(lun, residx);
8446		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8447			if (ctl_get_prkey(lun, i) != 0) {
8448				ctl_clr_prkey(lun, i);
8449				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8450			}
8451		lun->pr_generation++;
8452		mtx_unlock(&lun->lun_lock);
8453
8454		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8455		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8456		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8457		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8458		     sizeof(persis_io.pr), M_WAITOK);
8459		break;
8460
8461	case SPRO_PREEMPT:
8462	case SPRO_PRE_ABO: {
8463		int nretval;
8464
8465		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8466					  residx, ctsio, cdb, param);
8467		if (nretval != 0)
8468			return (CTL_RETVAL_COMPLETE);
8469		break;
8470	}
8471	default:
8472		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8473	}
8474
8475done:
8476	free(ctsio->kern_data_ptr, M_CTL);
8477	ctl_set_success(ctsio);
8478	ctl_done((union ctl_io *)ctsio);
8479
8480	return (retval);
8481}
8482
8483/*
8484 * This routine is for handling a message from the other SC pertaining to
8485 * persistent reserve out. All the error checking will have been done
8486 * so only perorming the action need be done here to keep the two
8487 * in sync.
8488 */
8489static void
8490ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8491{
8492	struct ctl_softc *softc = CTL_SOFTC(io);
8493	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8494	struct ctl_lun *lun;
8495	int i;
8496	uint32_t residx, targ_lun;
8497
8498	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8499	mtx_lock(&softc->ctl_lock);
8500	if (targ_lun >= CTL_MAX_LUNS ||
8501	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8502		mtx_unlock(&softc->ctl_lock);
8503		return;
8504	}
8505	mtx_lock(&lun->lun_lock);
8506	mtx_unlock(&softc->ctl_lock);
8507	if (lun->flags & CTL_LUN_DISABLED) {
8508		mtx_unlock(&lun->lun_lock);
8509		return;
8510	}
8511	residx = ctl_get_initindex(&msg->hdr.nexus);
8512	switch(msg->pr.pr_info.action) {
8513	case CTL_PR_REG_KEY:
8514		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8515		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8516			lun->pr_key_count++;
8517		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8518		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8519		lun->pr_generation++;
8520		break;
8521
8522	case CTL_PR_UNREG_KEY:
8523		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8524		lun->pr_key_count--;
8525
8526		/* XXX Need to see if the reservation has been released */
8527		/* if so do we need to generate UA? */
8528		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8529			lun->flags &= ~CTL_LUN_PR_RESERVED;
8530			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8531
8532			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8533			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8534			    lun->pr_key_count) {
8535				/*
8536				 * If the reservation is a registrants
8537				 * only type we need to generate a UA
8538				 * for other registered inits.  The
8539				 * sense code should be RESERVATIONS
8540				 * RELEASED
8541				 */
8542
8543				for (i = softc->init_min; i < softc->init_max; i++) {
8544					if (ctl_get_prkey(lun, i) == 0)
8545						continue;
8546
8547					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8548				}
8549			}
8550			lun->pr_res_type = 0;
8551		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8552			if (lun->pr_key_count==0) {
8553				lun->flags &= ~CTL_LUN_PR_RESERVED;
8554				lun->pr_res_type = 0;
8555				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8556			}
8557		}
8558		lun->pr_generation++;
8559		break;
8560
8561	case CTL_PR_RESERVE:
8562		lun->flags |= CTL_LUN_PR_RESERVED;
8563		lun->pr_res_type = msg->pr.pr_info.res_type;
8564		lun->pr_res_idx = msg->pr.pr_info.residx;
8565
8566		break;
8567
8568	case CTL_PR_RELEASE:
8569		/*
8570		 * If this isn't an exclusive access reservation and NUAR
8571		 * is not set, generate UA for all other registrants.
8572		 */
8573		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8574		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8575		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8576			for (i = softc->init_min; i < softc->init_max; i++)
8577				if (i == residx || ctl_get_prkey(lun, i) == 0)
8578					continue;
8579				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8580		}
8581
8582		lun->flags &= ~CTL_LUN_PR_RESERVED;
8583		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8584		lun->pr_res_type = 0;
8585		break;
8586
8587	case CTL_PR_PREEMPT:
8588		ctl_pro_preempt_other(lun, msg);
8589		break;
8590	case CTL_PR_CLEAR:
8591		lun->flags &= ~CTL_LUN_PR_RESERVED;
8592		lun->pr_res_type = 0;
8593		lun->pr_key_count = 0;
8594		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8595
8596		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8597			if (ctl_get_prkey(lun, i) == 0)
8598				continue;
8599			ctl_clr_prkey(lun, i);
8600			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8601		}
8602		lun->pr_generation++;
8603		break;
8604	}
8605
8606	mtx_unlock(&lun->lun_lock);
8607}
8608
8609int
8610ctl_read_write(struct ctl_scsiio *ctsio)
8611{
8612	struct ctl_lun *lun = CTL_LUN(ctsio);
8613	struct ctl_lba_len_flags *lbalen;
8614	uint64_t lba;
8615	uint32_t num_blocks;
8616	int flags, retval;
8617	int isread;
8618
8619	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8620
8621	flags = 0;
8622	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8623	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8624	switch (ctsio->cdb[0]) {
8625	case READ_6:
8626	case WRITE_6: {
8627		struct scsi_rw_6 *cdb;
8628
8629		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8630
8631		lba = scsi_3btoul(cdb->addr);
8632		/* only 5 bits are valid in the most significant address byte */
8633		lba &= 0x1fffff;
8634		num_blocks = cdb->length;
8635		/*
8636		 * This is correct according to SBC-2.
8637		 */
8638		if (num_blocks == 0)
8639			num_blocks = 256;
8640		break;
8641	}
8642	case READ_10:
8643	case WRITE_10: {
8644		struct scsi_rw_10 *cdb;
8645
8646		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8647		if (cdb->byte2 & SRW10_FUA)
8648			flags |= CTL_LLF_FUA;
8649		if (cdb->byte2 & SRW10_DPO)
8650			flags |= CTL_LLF_DPO;
8651		lba = scsi_4btoul(cdb->addr);
8652		num_blocks = scsi_2btoul(cdb->length);
8653		break;
8654	}
8655	case WRITE_VERIFY_10: {
8656		struct scsi_write_verify_10 *cdb;
8657
8658		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8659		flags |= CTL_LLF_FUA;
8660		if (cdb->byte2 & SWV_DPO)
8661			flags |= CTL_LLF_DPO;
8662		lba = scsi_4btoul(cdb->addr);
8663		num_blocks = scsi_2btoul(cdb->length);
8664		break;
8665	}
8666	case READ_12:
8667	case WRITE_12: {
8668		struct scsi_rw_12 *cdb;
8669
8670		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8671		if (cdb->byte2 & SRW12_FUA)
8672			flags |= CTL_LLF_FUA;
8673		if (cdb->byte2 & SRW12_DPO)
8674			flags |= CTL_LLF_DPO;
8675		lba = scsi_4btoul(cdb->addr);
8676		num_blocks = scsi_4btoul(cdb->length);
8677		break;
8678	}
8679	case WRITE_VERIFY_12: {
8680		struct scsi_write_verify_12 *cdb;
8681
8682		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8683		flags |= CTL_LLF_FUA;
8684		if (cdb->byte2 & SWV_DPO)
8685			flags |= CTL_LLF_DPO;
8686		lba = scsi_4btoul(cdb->addr);
8687		num_blocks = scsi_4btoul(cdb->length);
8688		break;
8689	}
8690	case READ_16:
8691	case WRITE_16: {
8692		struct scsi_rw_16 *cdb;
8693
8694		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8695		if (cdb->byte2 & SRW12_FUA)
8696			flags |= CTL_LLF_FUA;
8697		if (cdb->byte2 & SRW12_DPO)
8698			flags |= CTL_LLF_DPO;
8699		lba = scsi_8btou64(cdb->addr);
8700		num_blocks = scsi_4btoul(cdb->length);
8701		break;
8702	}
8703	case WRITE_ATOMIC_16: {
8704		struct scsi_write_atomic_16 *cdb;
8705
8706		if (lun->be_lun->atomicblock == 0) {
8707			ctl_set_invalid_opcode(ctsio);
8708			ctl_done((union ctl_io *)ctsio);
8709			return (CTL_RETVAL_COMPLETE);
8710		}
8711
8712		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8713		if (cdb->byte2 & SRW12_FUA)
8714			flags |= CTL_LLF_FUA;
8715		if (cdb->byte2 & SRW12_DPO)
8716			flags |= CTL_LLF_DPO;
8717		lba = scsi_8btou64(cdb->addr);
8718		num_blocks = scsi_2btoul(cdb->length);
8719		if (num_blocks > lun->be_lun->atomicblock) {
8720			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8721			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8722			    /*bit*/ 0);
8723			ctl_done((union ctl_io *)ctsio);
8724			return (CTL_RETVAL_COMPLETE);
8725		}
8726		break;
8727	}
8728	case WRITE_VERIFY_16: {
8729		struct scsi_write_verify_16 *cdb;
8730
8731		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8732		flags |= CTL_LLF_FUA;
8733		if (cdb->byte2 & SWV_DPO)
8734			flags |= CTL_LLF_DPO;
8735		lba = scsi_8btou64(cdb->addr);
8736		num_blocks = scsi_4btoul(cdb->length);
8737		break;
8738	}
8739	default:
8740		/*
8741		 * We got a command we don't support.  This shouldn't
8742		 * happen, commands should be filtered out above us.
8743		 */
8744		ctl_set_invalid_opcode(ctsio);
8745		ctl_done((union ctl_io *)ctsio);
8746
8747		return (CTL_RETVAL_COMPLETE);
8748		break; /* NOTREACHED */
8749	}
8750
8751	/*
8752	 * The first check is to make sure we're in bounds, the second
8753	 * check is to catch wrap-around problems.  If the lba + num blocks
8754	 * is less than the lba, then we've wrapped around and the block
8755	 * range is invalid anyway.
8756	 */
8757	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8758	 || ((lba + num_blocks) < lba)) {
8759		ctl_set_lba_out_of_range(ctsio,
8760		    MAX(lba, lun->be_lun->maxlba + 1));
8761		ctl_done((union ctl_io *)ctsio);
8762		return (CTL_RETVAL_COMPLETE);
8763	}
8764
8765	/*
8766	 * According to SBC-3, a transfer length of 0 is not an error.
8767	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8768	 * translates to 256 blocks for those commands.
8769	 */
8770	if (num_blocks == 0) {
8771		ctl_set_success(ctsio);
8772		ctl_done((union ctl_io *)ctsio);
8773		return (CTL_RETVAL_COMPLETE);
8774	}
8775
8776	/* Set FUA and/or DPO if caches are disabled. */
8777	if (isread) {
8778		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8779			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8780	} else {
8781		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8782			flags |= CTL_LLF_FUA;
8783	}
8784
8785	lbalen = (struct ctl_lba_len_flags *)
8786	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8787	lbalen->lba = lba;
8788	lbalen->len = num_blocks;
8789	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8790
8791	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8792	ctsio->kern_rel_offset = 0;
8793
8794	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8795
8796	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8797	return (retval);
8798}
8799
8800static int
8801ctl_cnw_cont(union ctl_io *io)
8802{
8803	struct ctl_lun *lun = CTL_LUN(io);
8804	struct ctl_scsiio *ctsio;
8805	struct ctl_lba_len_flags *lbalen;
8806	int retval;
8807
8808	ctsio = &io->scsiio;
8809	ctsio->io_hdr.status = CTL_STATUS_NONE;
8810	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8811	lbalen = (struct ctl_lba_len_flags *)
8812	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8813	lbalen->flags &= ~CTL_LLF_COMPARE;
8814	lbalen->flags |= CTL_LLF_WRITE;
8815
8816	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8817	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8818	return (retval);
8819}
8820
8821int
8822ctl_cnw(struct ctl_scsiio *ctsio)
8823{
8824	struct ctl_lun *lun = CTL_LUN(ctsio);
8825	struct ctl_lba_len_flags *lbalen;
8826	uint64_t lba;
8827	uint32_t num_blocks;
8828	int flags, retval;
8829
8830	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8831
8832	flags = 0;
8833	switch (ctsio->cdb[0]) {
8834	case COMPARE_AND_WRITE: {
8835		struct scsi_compare_and_write *cdb;
8836
8837		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8838		if (cdb->byte2 & SRW10_FUA)
8839			flags |= CTL_LLF_FUA;
8840		if (cdb->byte2 & SRW10_DPO)
8841			flags |= CTL_LLF_DPO;
8842		lba = scsi_8btou64(cdb->addr);
8843		num_blocks = cdb->length;
8844		break;
8845	}
8846	default:
8847		/*
8848		 * We got a command we don't support.  This shouldn't
8849		 * happen, commands should be filtered out above us.
8850		 */
8851		ctl_set_invalid_opcode(ctsio);
8852		ctl_done((union ctl_io *)ctsio);
8853
8854		return (CTL_RETVAL_COMPLETE);
8855		break; /* NOTREACHED */
8856	}
8857
8858	/*
8859	 * The first check is to make sure we're in bounds, the second
8860	 * check is to catch wrap-around problems.  If the lba + num blocks
8861	 * is less than the lba, then we've wrapped around and the block
8862	 * range is invalid anyway.
8863	 */
8864	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8865	 || ((lba + num_blocks) < lba)) {
8866		ctl_set_lba_out_of_range(ctsio,
8867		    MAX(lba, lun->be_lun->maxlba + 1));
8868		ctl_done((union ctl_io *)ctsio);
8869		return (CTL_RETVAL_COMPLETE);
8870	}
8871
8872	/*
8873	 * According to SBC-3, a transfer length of 0 is not an error.
8874	 */
8875	if (num_blocks == 0) {
8876		ctl_set_success(ctsio);
8877		ctl_done((union ctl_io *)ctsio);
8878		return (CTL_RETVAL_COMPLETE);
8879	}
8880
8881	/* Set FUA if write cache is disabled. */
8882	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8883		flags |= CTL_LLF_FUA;
8884
8885	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8886	ctsio->kern_rel_offset = 0;
8887
8888	/*
8889	 * Set the IO_CONT flag, so that if this I/O gets passed to
8890	 * ctl_data_submit_done(), it'll get passed back to
8891	 * ctl_ctl_cnw_cont() for further processing.
8892	 */
8893	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8894	ctsio->io_cont = ctl_cnw_cont;
8895
8896	lbalen = (struct ctl_lba_len_flags *)
8897	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8898	lbalen->lba = lba;
8899	lbalen->len = num_blocks;
8900	lbalen->flags = CTL_LLF_COMPARE | flags;
8901
8902	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8903	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8904	return (retval);
8905}
8906
8907int
8908ctl_verify(struct ctl_scsiio *ctsio)
8909{
8910	struct ctl_lun *lun = CTL_LUN(ctsio);
8911	struct ctl_lba_len_flags *lbalen;
8912	uint64_t lba;
8913	uint32_t num_blocks;
8914	int bytchk, flags;
8915	int retval;
8916
8917	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8918
8919	bytchk = 0;
8920	flags = CTL_LLF_FUA;
8921	switch (ctsio->cdb[0]) {
8922	case VERIFY_10: {
8923		struct scsi_verify_10 *cdb;
8924
8925		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8926		if (cdb->byte2 & SVFY_BYTCHK)
8927			bytchk = 1;
8928		if (cdb->byte2 & SVFY_DPO)
8929			flags |= CTL_LLF_DPO;
8930		lba = scsi_4btoul(cdb->addr);
8931		num_blocks = scsi_2btoul(cdb->length);
8932		break;
8933	}
8934	case VERIFY_12: {
8935		struct scsi_verify_12 *cdb;
8936
8937		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8938		if (cdb->byte2 & SVFY_BYTCHK)
8939			bytchk = 1;
8940		if (cdb->byte2 & SVFY_DPO)
8941			flags |= CTL_LLF_DPO;
8942		lba = scsi_4btoul(cdb->addr);
8943		num_blocks = scsi_4btoul(cdb->length);
8944		break;
8945	}
8946	case VERIFY_16: {
8947		struct scsi_rw_16 *cdb;
8948
8949		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8950		if (cdb->byte2 & SVFY_BYTCHK)
8951			bytchk = 1;
8952		if (cdb->byte2 & SVFY_DPO)
8953			flags |= CTL_LLF_DPO;
8954		lba = scsi_8btou64(cdb->addr);
8955		num_blocks = scsi_4btoul(cdb->length);
8956		break;
8957	}
8958	default:
8959		/*
8960		 * We got a command we don't support.  This shouldn't
8961		 * happen, commands should be filtered out above us.
8962		 */
8963		ctl_set_invalid_opcode(ctsio);
8964		ctl_done((union ctl_io *)ctsio);
8965		return (CTL_RETVAL_COMPLETE);
8966	}
8967
8968	/*
8969	 * The first check is to make sure we're in bounds, the second
8970	 * check is to catch wrap-around problems.  If the lba + num blocks
8971	 * is less than the lba, then we've wrapped around and the block
8972	 * range is invalid anyway.
8973	 */
8974	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8975	 || ((lba + num_blocks) < lba)) {
8976		ctl_set_lba_out_of_range(ctsio,
8977		    MAX(lba, lun->be_lun->maxlba + 1));
8978		ctl_done((union ctl_io *)ctsio);
8979		return (CTL_RETVAL_COMPLETE);
8980	}
8981
8982	/*
8983	 * According to SBC-3, a transfer length of 0 is not an error.
8984	 */
8985	if (num_blocks == 0) {
8986		ctl_set_success(ctsio);
8987		ctl_done((union ctl_io *)ctsio);
8988		return (CTL_RETVAL_COMPLETE);
8989	}
8990
8991	lbalen = (struct ctl_lba_len_flags *)
8992	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8993	lbalen->lba = lba;
8994	lbalen->len = num_blocks;
8995	if (bytchk) {
8996		lbalen->flags = CTL_LLF_COMPARE | flags;
8997		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8998	} else {
8999		lbalen->flags = CTL_LLF_VERIFY | flags;
9000		ctsio->kern_total_len = 0;
9001	}
9002	ctsio->kern_rel_offset = 0;
9003
9004	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9005	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9006	return (retval);
9007}
9008
9009int
9010ctl_report_luns(struct ctl_scsiio *ctsio)
9011{
9012	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9013	struct ctl_port *port = CTL_PORT(ctsio);
9014	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9015	struct scsi_report_luns *cdb;
9016	struct scsi_report_luns_data *lun_data;
9017	int num_filled, num_luns, num_port_luns, retval;
9018	uint32_t alloc_len, lun_datalen;
9019	uint32_t initidx, targ_lun_id, lun_id;
9020
9021	retval = CTL_RETVAL_COMPLETE;
9022	cdb = (struct scsi_report_luns *)ctsio->cdb;
9023
9024	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9025
9026	num_luns = 0;
9027	num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9028	mtx_lock(&softc->ctl_lock);
9029	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9030		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9031			num_luns++;
9032	}
9033	mtx_unlock(&softc->ctl_lock);
9034
9035	switch (cdb->select_report) {
9036	case RPL_REPORT_DEFAULT:
9037	case RPL_REPORT_ALL:
9038	case RPL_REPORT_NONSUBSID:
9039		break;
9040	case RPL_REPORT_WELLKNOWN:
9041	case RPL_REPORT_ADMIN:
9042	case RPL_REPORT_CONGLOM:
9043		num_luns = 0;
9044		break;
9045	default:
9046		ctl_set_invalid_field(ctsio,
9047				      /*sks_valid*/ 1,
9048				      /*command*/ 1,
9049				      /*field*/ 2,
9050				      /*bit_valid*/ 0,
9051				      /*bit*/ 0);
9052		ctl_done((union ctl_io *)ctsio);
9053		return (retval);
9054		break; /* NOTREACHED */
9055	}
9056
9057	alloc_len = scsi_4btoul(cdb->length);
9058	/*
9059	 * The initiator has to allocate at least 16 bytes for this request,
9060	 * so he can at least get the header and the first LUN.  Otherwise
9061	 * we reject the request (per SPC-3 rev 14, section 6.21).
9062	 */
9063	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9064	    sizeof(struct scsi_report_luns_lundata))) {
9065		ctl_set_invalid_field(ctsio,
9066				      /*sks_valid*/ 1,
9067				      /*command*/ 1,
9068				      /*field*/ 6,
9069				      /*bit_valid*/ 0,
9070				      /*bit*/ 0);
9071		ctl_done((union ctl_io *)ctsio);
9072		return (retval);
9073	}
9074
9075	lun_datalen = sizeof(*lun_data) +
9076		(num_luns * sizeof(struct scsi_report_luns_lundata));
9077
9078	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9079	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9080	ctsio->kern_sg_entries = 0;
9081
9082	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9083
9084	mtx_lock(&softc->ctl_lock);
9085	for (targ_lun_id = 0, num_filled = 0;
9086	    targ_lun_id < num_port_luns && num_filled < num_luns;
9087	    targ_lun_id++) {
9088		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9089		if (lun_id == UINT32_MAX)
9090			continue;
9091		lun = softc->ctl_luns[lun_id];
9092		if (lun == NULL)
9093			continue;
9094
9095		be64enc(lun_data->luns[num_filled++].lundata,
9096		    ctl_encode_lun(targ_lun_id));
9097
9098		/*
9099		 * According to SPC-3, rev 14 section 6.21:
9100		 *
9101		 * "The execution of a REPORT LUNS command to any valid and
9102		 * installed logical unit shall clear the REPORTED LUNS DATA
9103		 * HAS CHANGED unit attention condition for all logical
9104		 * units of that target with respect to the requesting
9105		 * initiator. A valid and installed logical unit is one
9106		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9107		 * INQUIRY data (see 6.4.2)."
9108		 *
9109		 * If request_lun is NULL, the LUN this report luns command
9110		 * was issued to is either disabled or doesn't exist. In that
9111		 * case, we shouldn't clear any pending lun change unit
9112		 * attention.
9113		 */
9114		if (request_lun != NULL) {
9115			mtx_lock(&lun->lun_lock);
9116			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9117			mtx_unlock(&lun->lun_lock);
9118		}
9119	}
9120	mtx_unlock(&softc->ctl_lock);
9121
9122	/*
9123	 * It's quite possible that we've returned fewer LUNs than we allocated
9124	 * space for.  Trim it.
9125	 */
9126	lun_datalen = sizeof(*lun_data) +
9127		(num_filled * sizeof(struct scsi_report_luns_lundata));
9128
9129	if (lun_datalen < alloc_len) {
9130		ctsio->residual = alloc_len - lun_datalen;
9131		ctsio->kern_data_len = lun_datalen;
9132		ctsio->kern_total_len = lun_datalen;
9133	} else {
9134		ctsio->residual = 0;
9135		ctsio->kern_data_len = alloc_len;
9136		ctsio->kern_total_len = alloc_len;
9137	}
9138	ctsio->kern_data_resid = 0;
9139	ctsio->kern_rel_offset = 0;
9140	ctsio->kern_sg_entries = 0;
9141
9142	/*
9143	 * We set this to the actual data length, regardless of how much
9144	 * space we actually have to return results.  If the user looks at
9145	 * this value, he'll know whether or not he allocated enough space
9146	 * and reissue the command if necessary.  We don't support well
9147	 * known logical units, so if the user asks for that, return none.
9148	 */
9149	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9150
9151	/*
9152	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9153	 * this request.
9154	 */
9155	ctl_set_success(ctsio);
9156	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9157	ctsio->be_move_done = ctl_config_move_done;
9158	ctl_datamove((union ctl_io *)ctsio);
9159	return (retval);
9160}
9161
9162int
9163ctl_request_sense(struct ctl_scsiio *ctsio)
9164{
9165	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9166	struct ctl_lun *lun = CTL_LUN(ctsio);
9167	struct scsi_request_sense *cdb;
9168	struct scsi_sense_data *sense_ptr;
9169	uint32_t initidx;
9170	int have_error;
9171	u_int sense_len = SSD_FULL_SIZE;
9172	scsi_sense_data_type sense_format;
9173	ctl_ua_type ua_type;
9174	uint8_t asc = 0, ascq = 0;
9175
9176	cdb = (struct scsi_request_sense *)ctsio->cdb;
9177
9178	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9179
9180	/*
9181	 * Determine which sense format the user wants.
9182	 */
9183	if (cdb->byte2 & SRS_DESC)
9184		sense_format = SSD_TYPE_DESC;
9185	else
9186		sense_format = SSD_TYPE_FIXED;
9187
9188	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9189	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9190	ctsio->kern_sg_entries = 0;
9191
9192	/*
9193	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9194	 * larger than the largest allowed value for the length field in the
9195	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9196	 */
9197	ctsio->residual = 0;
9198	ctsio->kern_data_len = cdb->length;
9199	ctsio->kern_total_len = cdb->length;
9200
9201	ctsio->kern_data_resid = 0;
9202	ctsio->kern_rel_offset = 0;
9203	ctsio->kern_sg_entries = 0;
9204
9205	/*
9206	 * If we don't have a LUN, we don't have any pending sense.
9207	 */
9208	if (lun == NULL ||
9209	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9210	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9211		/* "Logical unit not supported" */
9212		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9213		    /*current_error*/ 1,
9214		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9215		    /*asc*/ 0x25,
9216		    /*ascq*/ 0x00,
9217		    SSD_ELEM_NONE);
9218		goto send;
9219	}
9220
9221	have_error = 0;
9222	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9223	/*
9224	 * Check for pending sense, and then for pending unit attentions.
9225	 * Pending sense gets returned first, then pending unit attentions.
9226	 */
9227	mtx_lock(&lun->lun_lock);
9228#ifdef CTL_WITH_CA
9229	if (ctl_is_set(lun->have_ca, initidx)) {
9230		scsi_sense_data_type stored_format;
9231
9232		/*
9233		 * Check to see which sense format was used for the stored
9234		 * sense data.
9235		 */
9236		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9237
9238		/*
9239		 * If the user requested a different sense format than the
9240		 * one we stored, then we need to convert it to the other
9241		 * format.  If we're going from descriptor to fixed format
9242		 * sense data, we may lose things in translation, depending
9243		 * on what options were used.
9244		 *
9245		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9246		 * for some reason we'll just copy it out as-is.
9247		 */
9248		if ((stored_format == SSD_TYPE_FIXED)
9249		 && (sense_format == SSD_TYPE_DESC))
9250			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9251			    &lun->pending_sense[initidx],
9252			    (struct scsi_sense_data_desc *)sense_ptr);
9253		else if ((stored_format == SSD_TYPE_DESC)
9254		      && (sense_format == SSD_TYPE_FIXED))
9255			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9256			    &lun->pending_sense[initidx],
9257			    (struct scsi_sense_data_fixed *)sense_ptr);
9258		else
9259			memcpy(sense_ptr, &lun->pending_sense[initidx],
9260			       MIN(sizeof(*sense_ptr),
9261			       sizeof(lun->pending_sense[initidx])));
9262
9263		ctl_clear_mask(lun->have_ca, initidx);
9264		have_error = 1;
9265	} else
9266#endif
9267	if (have_error == 0) {
9268		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9269		    sense_format);
9270		if (ua_type != CTL_UA_NONE)
9271			have_error = 1;
9272	}
9273	if (have_error == 0) {
9274		/*
9275		 * Report informational exception if have one and allowed.
9276		 */
9277		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9278			asc = lun->ie_asc;
9279			ascq = lun->ie_ascq;
9280		}
9281		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9282		    /*current_error*/ 1,
9283		    /*sense_key*/ SSD_KEY_NO_SENSE,
9284		    /*asc*/ asc,
9285		    /*ascq*/ ascq,
9286		    SSD_ELEM_NONE);
9287	}
9288	mtx_unlock(&lun->lun_lock);
9289
9290send:
9291	/*
9292	 * We report the SCSI status as OK, since the status of the command
9293	 * itself is OK.  We're reporting sense as parameter data.
9294	 */
9295	ctl_set_success(ctsio);
9296	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9297	ctsio->be_move_done = ctl_config_move_done;
9298	ctl_datamove((union ctl_io *)ctsio);
9299	return (CTL_RETVAL_COMPLETE);
9300}
9301
9302int
9303ctl_tur(struct ctl_scsiio *ctsio)
9304{
9305
9306	CTL_DEBUG_PRINT(("ctl_tur\n"));
9307
9308	ctl_set_success(ctsio);
9309	ctl_done((union ctl_io *)ctsio);
9310
9311	return (CTL_RETVAL_COMPLETE);
9312}
9313
9314/*
9315 * SCSI VPD page 0x00, the Supported VPD Pages page.
9316 */
9317static int
9318ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9319{
9320	struct ctl_lun *lun = CTL_LUN(ctsio);
9321	struct scsi_vpd_supported_pages *pages;
9322	int sup_page_size;
9323	int p;
9324
9325	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9326	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9327	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9328	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9329	ctsio->kern_sg_entries = 0;
9330
9331	if (sup_page_size < alloc_len) {
9332		ctsio->residual = alloc_len - sup_page_size;
9333		ctsio->kern_data_len = sup_page_size;
9334		ctsio->kern_total_len = sup_page_size;
9335	} else {
9336		ctsio->residual = 0;
9337		ctsio->kern_data_len = alloc_len;
9338		ctsio->kern_total_len = alloc_len;
9339	}
9340	ctsio->kern_data_resid = 0;
9341	ctsio->kern_rel_offset = 0;
9342	ctsio->kern_sg_entries = 0;
9343
9344	/*
9345	 * The control device is always connected.  The disk device, on the
9346	 * other hand, may not be online all the time.  Need to change this
9347	 * to figure out whether the disk device is actually online or not.
9348	 */
9349	if (lun != NULL)
9350		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9351				lun->be_lun->lun_type;
9352	else
9353		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9354
9355	p = 0;
9356	/* Supported VPD pages */
9357	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9358	/* Serial Number */
9359	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9360	/* Device Identification */
9361	pages->page_list[p++] = SVPD_DEVICE_ID;
9362	/* Extended INQUIRY Data */
9363	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9364	/* Mode Page Policy */
9365	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9366	/* SCSI Ports */
9367	pages->page_list[p++] = SVPD_SCSI_PORTS;
9368	/* Third-party Copy */
9369	pages->page_list[p++] = SVPD_SCSI_TPC;
9370	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9371		/* Block limits */
9372		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9373		/* Block Device Characteristics */
9374		pages->page_list[p++] = SVPD_BDC;
9375		/* Logical Block Provisioning */
9376		pages->page_list[p++] = SVPD_LBP;
9377	}
9378	pages->length = p;
9379
9380	ctl_set_success(ctsio);
9381	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9382	ctsio->be_move_done = ctl_config_move_done;
9383	ctl_datamove((union ctl_io *)ctsio);
9384	return (CTL_RETVAL_COMPLETE);
9385}
9386
9387/*
9388 * SCSI VPD page 0x80, the Unit Serial Number page.
9389 */
9390static int
9391ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9392{
9393	struct ctl_lun *lun = CTL_LUN(ctsio);
9394	struct scsi_vpd_unit_serial_number *sn_ptr;
9395	int data_len;
9396
9397	data_len = 4 + CTL_SN_LEN;
9398	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9399	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9400	if (data_len < alloc_len) {
9401		ctsio->residual = alloc_len - data_len;
9402		ctsio->kern_data_len = data_len;
9403		ctsio->kern_total_len = data_len;
9404	} else {
9405		ctsio->residual = 0;
9406		ctsio->kern_data_len = alloc_len;
9407		ctsio->kern_total_len = alloc_len;
9408	}
9409	ctsio->kern_data_resid = 0;
9410	ctsio->kern_rel_offset = 0;
9411	ctsio->kern_sg_entries = 0;
9412
9413	/*
9414	 * The control device is always connected.  The disk device, on the
9415	 * other hand, may not be online all the time.  Need to change this
9416	 * to figure out whether the disk device is actually online or not.
9417	 */
9418	if (lun != NULL)
9419		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9420				  lun->be_lun->lun_type;
9421	else
9422		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9423
9424	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9425	sn_ptr->length = CTL_SN_LEN;
9426	/*
9427	 * If we don't have a LUN, we just leave the serial number as
9428	 * all spaces.
9429	 */
9430	if (lun != NULL) {
9431		strncpy((char *)sn_ptr->serial_num,
9432			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9433	} else
9434		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9435
9436	ctl_set_success(ctsio);
9437	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9438	ctsio->be_move_done = ctl_config_move_done;
9439	ctl_datamove((union ctl_io *)ctsio);
9440	return (CTL_RETVAL_COMPLETE);
9441}
9442
9443
9444/*
9445 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9446 */
9447static int
9448ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9449{
9450	struct ctl_lun *lun = CTL_LUN(ctsio);
9451	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9452	int data_len;
9453
9454	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9455	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9456	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9457	ctsio->kern_sg_entries = 0;
9458
9459	if (data_len < alloc_len) {
9460		ctsio->residual = alloc_len - data_len;
9461		ctsio->kern_data_len = data_len;
9462		ctsio->kern_total_len = data_len;
9463	} else {
9464		ctsio->residual = 0;
9465		ctsio->kern_data_len = alloc_len;
9466		ctsio->kern_total_len = alloc_len;
9467	}
9468	ctsio->kern_data_resid = 0;
9469	ctsio->kern_rel_offset = 0;
9470	ctsio->kern_sg_entries = 0;
9471
9472	/*
9473	 * The control device is always connected.  The disk device, on the
9474	 * other hand, may not be online all the time.
9475	 */
9476	if (lun != NULL)
9477		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9478				     lun->be_lun->lun_type;
9479	else
9480		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9481	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9482	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9483	/*
9484	 * We support head of queue, ordered and simple tags.
9485	 */
9486	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9487	/*
9488	 * Volatile cache supported.
9489	 */
9490	eid_ptr->flags3 = SVPD_EID_V_SUP;
9491
9492	/*
9493	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9494	 * attention for a particular IT nexus on all LUNs once we report
9495	 * it to that nexus once.  This bit is required as of SPC-4.
9496	 */
9497	eid_ptr->flags4 = SVPD_EID_LUICLR;
9498
9499	/*
9500	 * We support revert to defaults (RTD) bit in MODE SELECT.
9501	 */
9502	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9503
9504	/*
9505	 * XXX KDM in order to correctly answer this, we would need
9506	 * information from the SIM to determine how much sense data it
9507	 * can send.  So this would really be a path inquiry field, most
9508	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9509	 * but the hardware may or may not be able to support that much.
9510	 * 0 just means that the maximum sense data length is not reported.
9511	 */
9512	eid_ptr->max_sense_length = 0;
9513
9514	ctl_set_success(ctsio);
9515	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9516	ctsio->be_move_done = ctl_config_move_done;
9517	ctl_datamove((union ctl_io *)ctsio);
9518	return (CTL_RETVAL_COMPLETE);
9519}
9520
9521static int
9522ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9523{
9524	struct ctl_lun *lun = CTL_LUN(ctsio);
9525	struct scsi_vpd_mode_page_policy *mpp_ptr;
9526	int data_len;
9527
9528	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9529	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9530
9531	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9532	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9533	ctsio->kern_sg_entries = 0;
9534
9535	if (data_len < alloc_len) {
9536		ctsio->residual = alloc_len - data_len;
9537		ctsio->kern_data_len = data_len;
9538		ctsio->kern_total_len = data_len;
9539	} else {
9540		ctsio->residual = 0;
9541		ctsio->kern_data_len = alloc_len;
9542		ctsio->kern_total_len = alloc_len;
9543	}
9544	ctsio->kern_data_resid = 0;
9545	ctsio->kern_rel_offset = 0;
9546	ctsio->kern_sg_entries = 0;
9547
9548	/*
9549	 * The control device is always connected.  The disk device, on the
9550	 * other hand, may not be online all the time.
9551	 */
9552	if (lun != NULL)
9553		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9554				     lun->be_lun->lun_type;
9555	else
9556		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9557	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9558	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9559	mpp_ptr->descr[0].page_code = 0x3f;
9560	mpp_ptr->descr[0].subpage_code = 0xff;
9561	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9562
9563	ctl_set_success(ctsio);
9564	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9565	ctsio->be_move_done = ctl_config_move_done;
9566	ctl_datamove((union ctl_io *)ctsio);
9567	return (CTL_RETVAL_COMPLETE);
9568}
9569
9570/*
9571 * SCSI VPD page 0x83, the Device Identification page.
9572 */
9573static int
9574ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9575{
9576	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9577	struct ctl_port *port = CTL_PORT(ctsio);
9578	struct ctl_lun *lun = CTL_LUN(ctsio);
9579	struct scsi_vpd_device_id *devid_ptr;
9580	struct scsi_vpd_id_descriptor *desc;
9581	int data_len, g;
9582	uint8_t proto;
9583
9584	data_len = sizeof(struct scsi_vpd_device_id) +
9585	    sizeof(struct scsi_vpd_id_descriptor) +
9586		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9587	    sizeof(struct scsi_vpd_id_descriptor) +
9588		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9589	if (lun && lun->lun_devid)
9590		data_len += lun->lun_devid->len;
9591	if (port && port->port_devid)
9592		data_len += port->port_devid->len;
9593	if (port && port->target_devid)
9594		data_len += port->target_devid->len;
9595
9596	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9597	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9598	ctsio->kern_sg_entries = 0;
9599
9600	if (data_len < alloc_len) {
9601		ctsio->residual = alloc_len - data_len;
9602		ctsio->kern_data_len = data_len;
9603		ctsio->kern_total_len = data_len;
9604	} else {
9605		ctsio->residual = 0;
9606		ctsio->kern_data_len = alloc_len;
9607		ctsio->kern_total_len = alloc_len;
9608	}
9609	ctsio->kern_data_resid = 0;
9610	ctsio->kern_rel_offset = 0;
9611	ctsio->kern_sg_entries = 0;
9612
9613	/*
9614	 * The control device is always connected.  The disk device, on the
9615	 * other hand, may not be online all the time.
9616	 */
9617	if (lun != NULL)
9618		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9619				     lun->be_lun->lun_type;
9620	else
9621		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9622	devid_ptr->page_code = SVPD_DEVICE_ID;
9623	scsi_ulto2b(data_len - 4, devid_ptr->length);
9624
9625	if (port && port->port_type == CTL_PORT_FC)
9626		proto = SCSI_PROTO_FC << 4;
9627	else if (port && port->port_type == CTL_PORT_ISCSI)
9628		proto = SCSI_PROTO_ISCSI << 4;
9629	else
9630		proto = SCSI_PROTO_SPI << 4;
9631	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9632
9633	/*
9634	 * We're using a LUN association here.  i.e., this device ID is a
9635	 * per-LUN identifier.
9636	 */
9637	if (lun && lun->lun_devid) {
9638		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9639		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9640		    lun->lun_devid->len);
9641	}
9642
9643	/*
9644	 * This is for the WWPN which is a port association.
9645	 */
9646	if (port && port->port_devid) {
9647		memcpy(desc, port->port_devid->data, port->port_devid->len);
9648		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9649		    port->port_devid->len);
9650	}
9651
9652	/*
9653	 * This is for the Relative Target Port(type 4h) identifier
9654	 */
9655	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9656	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9657	    SVPD_ID_TYPE_RELTARG;
9658	desc->length = 4;
9659	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9660	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9661	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9662
9663	/*
9664	 * This is for the Target Port Group(type 5h) identifier
9665	 */
9666	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9667	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9668	    SVPD_ID_TYPE_TPORTGRP;
9669	desc->length = 4;
9670	if (softc->is_single ||
9671	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9672		g = 1;
9673	else
9674		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9675	scsi_ulto2b(g, &desc->identifier[2]);
9676	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9677	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9678
9679	/*
9680	 * This is for the Target identifier
9681	 */
9682	if (port && port->target_devid) {
9683		memcpy(desc, port->target_devid->data, port->target_devid->len);
9684	}
9685
9686	ctl_set_success(ctsio);
9687	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9688	ctsio->be_move_done = ctl_config_move_done;
9689	ctl_datamove((union ctl_io *)ctsio);
9690	return (CTL_RETVAL_COMPLETE);
9691}
9692
9693static int
9694ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9695{
9696	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9697	struct ctl_lun *lun = CTL_LUN(ctsio);
9698	struct scsi_vpd_scsi_ports *sp;
9699	struct scsi_vpd_port_designation *pd;
9700	struct scsi_vpd_port_designation_cont *pdc;
9701	struct ctl_port *port;
9702	int data_len, num_target_ports, iid_len, id_len;
9703
9704	num_target_ports = 0;
9705	iid_len = 0;
9706	id_len = 0;
9707	mtx_lock(&softc->ctl_lock);
9708	STAILQ_FOREACH(port, &softc->port_list, links) {
9709		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9710			continue;
9711		if (lun != NULL &&
9712		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9713			continue;
9714		num_target_ports++;
9715		if (port->init_devid)
9716			iid_len += port->init_devid->len;
9717		if (port->port_devid)
9718			id_len += port->port_devid->len;
9719	}
9720	mtx_unlock(&softc->ctl_lock);
9721
9722	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9723	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9724	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9725	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9726	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9727	ctsio->kern_sg_entries = 0;
9728
9729	if (data_len < alloc_len) {
9730		ctsio->residual = alloc_len - data_len;
9731		ctsio->kern_data_len = data_len;
9732		ctsio->kern_total_len = data_len;
9733	} else {
9734		ctsio->residual = 0;
9735		ctsio->kern_data_len = alloc_len;
9736		ctsio->kern_total_len = alloc_len;
9737	}
9738	ctsio->kern_data_resid = 0;
9739	ctsio->kern_rel_offset = 0;
9740	ctsio->kern_sg_entries = 0;
9741
9742	/*
9743	 * The control device is always connected.  The disk device, on the
9744	 * other hand, may not be online all the time.  Need to change this
9745	 * to figure out whether the disk device is actually online or not.
9746	 */
9747	if (lun != NULL)
9748		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9749				  lun->be_lun->lun_type;
9750	else
9751		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9752
9753	sp->page_code = SVPD_SCSI_PORTS;
9754	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9755	    sp->page_length);
9756	pd = &sp->design[0];
9757
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) == UINT32_MAX)
9764			continue;
9765		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9766		if (port->init_devid) {
9767			iid_len = port->init_devid->len;
9768			memcpy(pd->initiator_transportid,
9769			    port->init_devid->data, port->init_devid->len);
9770		} else
9771			iid_len = 0;
9772		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9773		pdc = (struct scsi_vpd_port_designation_cont *)
9774		    (&pd->initiator_transportid[iid_len]);
9775		if (port->port_devid) {
9776			id_len = port->port_devid->len;
9777			memcpy(pdc->target_port_descriptors,
9778			    port->port_devid->data, port->port_devid->len);
9779		} else
9780			id_len = 0;
9781		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9782		pd = (struct scsi_vpd_port_designation *)
9783		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9784	}
9785	mtx_unlock(&softc->ctl_lock);
9786
9787	ctl_set_success(ctsio);
9788	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9789	ctsio->be_move_done = ctl_config_move_done;
9790	ctl_datamove((union ctl_io *)ctsio);
9791	return (CTL_RETVAL_COMPLETE);
9792}
9793
9794static int
9795ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9796{
9797	struct ctl_lun *lun = CTL_LUN(ctsio);
9798	struct scsi_vpd_block_limits *bl_ptr;
9799	uint64_t ival;
9800
9801	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9802	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9803	ctsio->kern_sg_entries = 0;
9804
9805	if (sizeof(*bl_ptr) < alloc_len) {
9806		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9807		ctsio->kern_data_len = sizeof(*bl_ptr);
9808		ctsio->kern_total_len = sizeof(*bl_ptr);
9809	} else {
9810		ctsio->residual = 0;
9811		ctsio->kern_data_len = alloc_len;
9812		ctsio->kern_total_len = alloc_len;
9813	}
9814	ctsio->kern_data_resid = 0;
9815	ctsio->kern_rel_offset = 0;
9816	ctsio->kern_sg_entries = 0;
9817
9818	/*
9819	 * The control device is always connected.  The disk device, on the
9820	 * other hand, may not be online all the time.  Need to change this
9821	 * to figure out whether the disk device is actually online or not.
9822	 */
9823	if (lun != NULL)
9824		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9825				  lun->be_lun->lun_type;
9826	else
9827		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9828
9829	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9830	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9831	bl_ptr->max_cmp_write_len = 0xff;
9832	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9833	if (lun != NULL) {
9834		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9835		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9836			ival = 0xffffffff;
9837			ctl_get_opt_number(&lun->be_lun->options,
9838			    "unmap_max_lba", &ival);
9839			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9840			ival = 0xffffffff;
9841			ctl_get_opt_number(&lun->be_lun->options,
9842			    "unmap_max_descr", &ival);
9843			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9844			if (lun->be_lun->ublockexp != 0) {
9845				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9846				    bl_ptr->opt_unmap_grain);
9847				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9848				    bl_ptr->unmap_grain_align);
9849			}
9850		}
9851		scsi_ulto4b(lun->be_lun->atomicblock,
9852		    bl_ptr->max_atomic_transfer_length);
9853		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9854		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9855		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9856		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9857		ival = UINT64_MAX;
9858		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9859		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9860	}
9861
9862	ctl_set_success(ctsio);
9863	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9864	ctsio->be_move_done = ctl_config_move_done;
9865	ctl_datamove((union ctl_io *)ctsio);
9866	return (CTL_RETVAL_COMPLETE);
9867}
9868
9869static int
9870ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9871{
9872	struct ctl_lun *lun = CTL_LUN(ctsio);
9873	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9874	const char *value;
9875	u_int i;
9876
9877	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9878	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9879	ctsio->kern_sg_entries = 0;
9880
9881	if (sizeof(*bdc_ptr) < alloc_len) {
9882		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9883		ctsio->kern_data_len = sizeof(*bdc_ptr);
9884		ctsio->kern_total_len = sizeof(*bdc_ptr);
9885	} else {
9886		ctsio->residual = 0;
9887		ctsio->kern_data_len = alloc_len;
9888		ctsio->kern_total_len = alloc_len;
9889	}
9890	ctsio->kern_data_resid = 0;
9891	ctsio->kern_rel_offset = 0;
9892	ctsio->kern_sg_entries = 0;
9893
9894	/*
9895	 * The control device is always connected.  The disk device, on the
9896	 * other hand, may not be online all the time.  Need to change this
9897	 * to figure out whether the disk device is actually online or not.
9898	 */
9899	if (lun != NULL)
9900		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9901				  lun->be_lun->lun_type;
9902	else
9903		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9904	bdc_ptr->page_code = SVPD_BDC;
9905	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9906	if (lun != NULL &&
9907	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9908		i = strtol(value, NULL, 0);
9909	else
9910		i = CTL_DEFAULT_ROTATION_RATE;
9911	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9912	if (lun != NULL &&
9913	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9914		i = strtol(value, NULL, 0);
9915	else
9916		i = 0;
9917	bdc_ptr->wab_wac_ff = (i & 0x0f);
9918	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9919
9920	ctl_set_success(ctsio);
9921	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9922	ctsio->be_move_done = ctl_config_move_done;
9923	ctl_datamove((union ctl_io *)ctsio);
9924	return (CTL_RETVAL_COMPLETE);
9925}
9926
9927static int
9928ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9929{
9930	struct ctl_lun *lun = CTL_LUN(ctsio);
9931	struct scsi_vpd_logical_block_prov *lbp_ptr;
9932	const char *value;
9933
9934	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9935	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9936	ctsio->kern_sg_entries = 0;
9937
9938	if (sizeof(*lbp_ptr) < alloc_len) {
9939		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9940		ctsio->kern_data_len = sizeof(*lbp_ptr);
9941		ctsio->kern_total_len = sizeof(*lbp_ptr);
9942	} else {
9943		ctsio->residual = 0;
9944		ctsio->kern_data_len = alloc_len;
9945		ctsio->kern_total_len = alloc_len;
9946	}
9947	ctsio->kern_data_resid = 0;
9948	ctsio->kern_rel_offset = 0;
9949	ctsio->kern_sg_entries = 0;
9950
9951	/*
9952	 * The control device is always connected.  The disk device, on the
9953	 * other hand, may not be online all the time.  Need to change this
9954	 * to figure out whether the disk device is actually online or not.
9955	 */
9956	if (lun != NULL)
9957		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9958				  lun->be_lun->lun_type;
9959	else
9960		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9961
9962	lbp_ptr->page_code = SVPD_LBP;
9963	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9964	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9965	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9966		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9967		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9968		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
9969		if (value != NULL) {
9970			if (strcmp(value, "resource") == 0)
9971				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9972			else if (strcmp(value, "thin") == 0)
9973				lbp_ptr->prov_type = SVPD_LBP_THIN;
9974		} else
9975			lbp_ptr->prov_type = SVPD_LBP_THIN;
9976	}
9977
9978	ctl_set_success(ctsio);
9979	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9980	ctsio->be_move_done = ctl_config_move_done;
9981	ctl_datamove((union ctl_io *)ctsio);
9982	return (CTL_RETVAL_COMPLETE);
9983}
9984
9985/*
9986 * INQUIRY with the EVPD bit set.
9987 */
9988static int
9989ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9990{
9991	struct ctl_lun *lun = CTL_LUN(ctsio);
9992	struct scsi_inquiry *cdb;
9993	int alloc_len, retval;
9994
9995	cdb = (struct scsi_inquiry *)ctsio->cdb;
9996	alloc_len = scsi_2btoul(cdb->length);
9997
9998	switch (cdb->page_code) {
9999	case SVPD_SUPPORTED_PAGES:
10000		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10001		break;
10002	case SVPD_UNIT_SERIAL_NUMBER:
10003		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10004		break;
10005	case SVPD_DEVICE_ID:
10006		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10007		break;
10008	case SVPD_EXTENDED_INQUIRY_DATA:
10009		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10010		break;
10011	case SVPD_MODE_PAGE_POLICY:
10012		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10013		break;
10014	case SVPD_SCSI_PORTS:
10015		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10016		break;
10017	case SVPD_SCSI_TPC:
10018		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10019		break;
10020	case SVPD_BLOCK_LIMITS:
10021		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10022			goto err;
10023		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10024		break;
10025	case SVPD_BDC:
10026		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10027			goto err;
10028		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10029		break;
10030	case SVPD_LBP:
10031		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10032			goto err;
10033		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10034		break;
10035	default:
10036err:
10037		ctl_set_invalid_field(ctsio,
10038				      /*sks_valid*/ 1,
10039				      /*command*/ 1,
10040				      /*field*/ 2,
10041				      /*bit_valid*/ 0,
10042				      /*bit*/ 0);
10043		ctl_done((union ctl_io *)ctsio);
10044		retval = CTL_RETVAL_COMPLETE;
10045		break;
10046	}
10047
10048	return (retval);
10049}
10050
10051/*
10052 * Standard INQUIRY data.
10053 */
10054static int
10055ctl_inquiry_std(struct ctl_scsiio *ctsio)
10056{
10057	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10058	struct ctl_port *port = CTL_PORT(ctsio);
10059	struct ctl_lun *lun = CTL_LUN(ctsio);
10060	struct scsi_inquiry_data *inq_ptr;
10061	struct scsi_inquiry *cdb;
10062	char *val;
10063	uint32_t alloc_len, data_len;
10064	ctl_port_type port_type;
10065
10066	port_type = port->port_type;
10067	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10068		port_type = CTL_PORT_SCSI;
10069
10070	cdb = (struct scsi_inquiry *)ctsio->cdb;
10071	alloc_len = scsi_2btoul(cdb->length);
10072
10073	/*
10074	 * We malloc the full inquiry data size here and fill it
10075	 * in.  If the user only asks for less, we'll give him
10076	 * that much.
10077	 */
10078	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10079	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10080	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10081	ctsio->kern_sg_entries = 0;
10082	ctsio->kern_data_resid = 0;
10083	ctsio->kern_rel_offset = 0;
10084
10085	if (data_len < alloc_len) {
10086		ctsio->residual = alloc_len - data_len;
10087		ctsio->kern_data_len = data_len;
10088		ctsio->kern_total_len = data_len;
10089	} else {
10090		ctsio->residual = 0;
10091		ctsio->kern_data_len = alloc_len;
10092		ctsio->kern_total_len = alloc_len;
10093	}
10094
10095	if (lun != NULL) {
10096		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10097		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10098			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10099			    lun->be_lun->lun_type;
10100		} else {
10101			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10102			    lun->be_lun->lun_type;
10103		}
10104		if (lun->flags & CTL_LUN_REMOVABLE)
10105			inq_ptr->dev_qual2 |= SID_RMB;
10106	} else
10107		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10108
10109	/* RMB in byte 2 is 0 */
10110	inq_ptr->version = SCSI_REV_SPC5;
10111
10112	/*
10113	 * According to SAM-3, even if a device only supports a single
10114	 * level of LUN addressing, it should still set the HISUP bit:
10115	 *
10116	 * 4.9.1 Logical unit numbers overview
10117	 *
10118	 * All logical unit number formats described in this standard are
10119	 * hierarchical in structure even when only a single level in that
10120	 * hierarchy is used. The HISUP bit shall be set to one in the
10121	 * standard INQUIRY data (see SPC-2) when any logical unit number
10122	 * format described in this standard is used.  Non-hierarchical
10123	 * formats are outside the scope of this standard.
10124	 *
10125	 * Therefore we set the HiSup bit here.
10126	 *
10127	 * The response format is 2, per SPC-3.
10128	 */
10129	inq_ptr->response_format = SID_HiSup | 2;
10130
10131	inq_ptr->additional_length = data_len -
10132	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10133	CTL_DEBUG_PRINT(("additional_length = %d\n",
10134			 inq_ptr->additional_length));
10135
10136	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10137	if (port_type == CTL_PORT_SCSI)
10138		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10139	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10140	inq_ptr->flags = SID_CmdQue;
10141	if (port_type == CTL_PORT_SCSI)
10142		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10143
10144	/*
10145	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10146	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10147	 * name and 4 bytes for the revision.
10148	 */
10149	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10150	    "vendor")) == NULL) {
10151		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10152	} else {
10153		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10154		strncpy(inq_ptr->vendor, val,
10155		    min(sizeof(inq_ptr->vendor), strlen(val)));
10156	}
10157	if (lun == NULL) {
10158		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10159		    sizeof(inq_ptr->product));
10160	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10161		switch (lun->be_lun->lun_type) {
10162		case T_DIRECT:
10163			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10164			    sizeof(inq_ptr->product));
10165			break;
10166		case T_PROCESSOR:
10167			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10168			    sizeof(inq_ptr->product));
10169			break;
10170		case T_CDROM:
10171			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10172			    sizeof(inq_ptr->product));
10173			break;
10174		default:
10175			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10176			    sizeof(inq_ptr->product));
10177			break;
10178		}
10179	} else {
10180		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10181		strncpy(inq_ptr->product, val,
10182		    min(sizeof(inq_ptr->product), strlen(val)));
10183	}
10184
10185	/*
10186	 * XXX make this a macro somewhere so it automatically gets
10187	 * incremented when we make changes.
10188	 */
10189	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10190	    "revision")) == NULL) {
10191		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10192	} else {
10193		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10194		strncpy(inq_ptr->revision, val,
10195		    min(sizeof(inq_ptr->revision), strlen(val)));
10196	}
10197
10198	/*
10199	 * For parallel SCSI, we support double transition and single
10200	 * transition clocking.  We also support QAS (Quick Arbitration
10201	 * and Selection) and Information Unit transfers on both the
10202	 * control and array devices.
10203	 */
10204	if (port_type == CTL_PORT_SCSI)
10205		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10206				    SID_SPI_IUS;
10207
10208	/* SAM-6 (no version claimed) */
10209	scsi_ulto2b(0x00C0, inq_ptr->version1);
10210	/* SPC-5 (no version claimed) */
10211	scsi_ulto2b(0x05C0, inq_ptr->version2);
10212	if (port_type == CTL_PORT_FC) {
10213		/* FCP-2 ANSI INCITS.350:2003 */
10214		scsi_ulto2b(0x0917, inq_ptr->version3);
10215	} else if (port_type == CTL_PORT_SCSI) {
10216		/* SPI-4 ANSI INCITS.362:200x */
10217		scsi_ulto2b(0x0B56, inq_ptr->version3);
10218	} else if (port_type == CTL_PORT_ISCSI) {
10219		/* iSCSI (no version claimed) */
10220		scsi_ulto2b(0x0960, inq_ptr->version3);
10221	} else if (port_type == CTL_PORT_SAS) {
10222		/* SAS (no version claimed) */
10223		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10224	}
10225
10226	if (lun == NULL) {
10227		/* SBC-4 (no version claimed) */
10228		scsi_ulto2b(0x0600, inq_ptr->version4);
10229	} else {
10230		switch (lun->be_lun->lun_type) {
10231		case T_DIRECT:
10232			/* SBC-4 (no version claimed) */
10233			scsi_ulto2b(0x0600, inq_ptr->version4);
10234			break;
10235		case T_PROCESSOR:
10236			break;
10237		case T_CDROM:
10238			/* MMC-6 (no version claimed) */
10239			scsi_ulto2b(0x04E0, inq_ptr->version4);
10240			break;
10241		default:
10242			break;
10243		}
10244	}
10245
10246	ctl_set_success(ctsio);
10247	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10248	ctsio->be_move_done = ctl_config_move_done;
10249	ctl_datamove((union ctl_io *)ctsio);
10250	return (CTL_RETVAL_COMPLETE);
10251}
10252
10253int
10254ctl_inquiry(struct ctl_scsiio *ctsio)
10255{
10256	struct scsi_inquiry *cdb;
10257	int retval;
10258
10259	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10260
10261	cdb = (struct scsi_inquiry *)ctsio->cdb;
10262	if (cdb->byte2 & SI_EVPD)
10263		retval = ctl_inquiry_evpd(ctsio);
10264	else if (cdb->page_code == 0)
10265		retval = ctl_inquiry_std(ctsio);
10266	else {
10267		ctl_set_invalid_field(ctsio,
10268				      /*sks_valid*/ 1,
10269				      /*command*/ 1,
10270				      /*field*/ 2,
10271				      /*bit_valid*/ 0,
10272				      /*bit*/ 0);
10273		ctl_done((union ctl_io *)ctsio);
10274		return (CTL_RETVAL_COMPLETE);
10275	}
10276
10277	return (retval);
10278}
10279
10280int
10281ctl_get_config(struct ctl_scsiio *ctsio)
10282{
10283	struct ctl_lun *lun = CTL_LUN(ctsio);
10284	struct scsi_get_config_header *hdr;
10285	struct scsi_get_config_feature *feature;
10286	struct scsi_get_config *cdb;
10287	uint32_t alloc_len, data_len;
10288	int rt, starting;
10289
10290	cdb = (struct scsi_get_config *)ctsio->cdb;
10291	rt = (cdb->rt & SGC_RT_MASK);
10292	starting = scsi_2btoul(cdb->starting_feature);
10293	alloc_len = scsi_2btoul(cdb->length);
10294
10295	data_len = sizeof(struct scsi_get_config_header) +
10296	    sizeof(struct scsi_get_config_feature) + 8 +
10297	    sizeof(struct scsi_get_config_feature) + 8 +
10298	    sizeof(struct scsi_get_config_feature) + 4 +
10299	    sizeof(struct scsi_get_config_feature) + 4 +
10300	    sizeof(struct scsi_get_config_feature) + 8 +
10301	    sizeof(struct scsi_get_config_feature) +
10302	    sizeof(struct scsi_get_config_feature) + 4 +
10303	    sizeof(struct scsi_get_config_feature) + 4 +
10304	    sizeof(struct scsi_get_config_feature) + 4 +
10305	    sizeof(struct scsi_get_config_feature) + 4 +
10306	    sizeof(struct scsi_get_config_feature) + 4 +
10307	    sizeof(struct scsi_get_config_feature) + 4;
10308	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10309	ctsio->kern_sg_entries = 0;
10310	ctsio->kern_data_resid = 0;
10311	ctsio->kern_rel_offset = 0;
10312
10313	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10314	if (lun->flags & CTL_LUN_NO_MEDIA)
10315		scsi_ulto2b(0x0000, hdr->current_profile);
10316	else
10317		scsi_ulto2b(0x0010, hdr->current_profile);
10318	feature = (struct scsi_get_config_feature *)(hdr + 1);
10319
10320	if (starting > 0x003b)
10321		goto done;
10322	if (starting > 0x003a)
10323		goto f3b;
10324	if (starting > 0x002b)
10325		goto f3a;
10326	if (starting > 0x002a)
10327		goto f2b;
10328	if (starting > 0x001f)
10329		goto f2a;
10330	if (starting > 0x001e)
10331		goto f1f;
10332	if (starting > 0x001d)
10333		goto f1e;
10334	if (starting > 0x0010)
10335		goto f1d;
10336	if (starting > 0x0003)
10337		goto f10;
10338	if (starting > 0x0002)
10339		goto f3;
10340	if (starting > 0x0001)
10341		goto f2;
10342	if (starting > 0x0000)
10343		goto f1;
10344
10345	/* Profile List */
10346	scsi_ulto2b(0x0000, feature->feature_code);
10347	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10348	feature->add_length = 8;
10349	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10350	feature->feature_data[2] = 0x00;
10351	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10352	feature->feature_data[6] = 0x01;
10353	feature = (struct scsi_get_config_feature *)
10354	    &feature->feature_data[feature->add_length];
10355
10356f1:	/* Core */
10357	scsi_ulto2b(0x0001, feature->feature_code);
10358	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10359	feature->add_length = 8;
10360	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10361	feature->feature_data[4] = 0x03;
10362	feature = (struct scsi_get_config_feature *)
10363	    &feature->feature_data[feature->add_length];
10364
10365f2:	/* Morphing */
10366	scsi_ulto2b(0x0002, feature->feature_code);
10367	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10368	feature->add_length = 4;
10369	feature->feature_data[0] = 0x02;
10370	feature = (struct scsi_get_config_feature *)
10371	    &feature->feature_data[feature->add_length];
10372
10373f3:	/* Removable Medium */
10374	scsi_ulto2b(0x0003, feature->feature_code);
10375	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10376	feature->add_length = 4;
10377	feature->feature_data[0] = 0x39;
10378	feature = (struct scsi_get_config_feature *)
10379	    &feature->feature_data[feature->add_length];
10380
10381	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10382		goto done;
10383
10384f10:	/* Random Read */
10385	scsi_ulto2b(0x0010, feature->feature_code);
10386	feature->flags = 0x00;
10387	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10388		feature->flags |= SGC_F_CURRENT;
10389	feature->add_length = 8;
10390	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10391	scsi_ulto2b(1, &feature->feature_data[4]);
10392	feature->feature_data[6] = 0x00;
10393	feature = (struct scsi_get_config_feature *)
10394	    &feature->feature_data[feature->add_length];
10395
10396f1d:	/* Multi-Read */
10397	scsi_ulto2b(0x001D, feature->feature_code);
10398	feature->flags = 0x00;
10399	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10400		feature->flags |= SGC_F_CURRENT;
10401	feature->add_length = 0;
10402	feature = (struct scsi_get_config_feature *)
10403	    &feature->feature_data[feature->add_length];
10404
10405f1e:	/* CD Read */
10406	scsi_ulto2b(0x001E, feature->feature_code);
10407	feature->flags = 0x00;
10408	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10409		feature->flags |= SGC_F_CURRENT;
10410	feature->add_length = 4;
10411	feature->feature_data[0] = 0x00;
10412	feature = (struct scsi_get_config_feature *)
10413	    &feature->feature_data[feature->add_length];
10414
10415f1f:	/* DVD Read */
10416	scsi_ulto2b(0x001F, feature->feature_code);
10417	feature->flags = 0x08;
10418	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10419		feature->flags |= SGC_F_CURRENT;
10420	feature->add_length = 4;
10421	feature->feature_data[0] = 0x01;
10422	feature->feature_data[2] = 0x03;
10423	feature = (struct scsi_get_config_feature *)
10424	    &feature->feature_data[feature->add_length];
10425
10426f2a:	/* DVD+RW */
10427	scsi_ulto2b(0x002A, feature->feature_code);
10428	feature->flags = 0x04;
10429	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10430		feature->flags |= SGC_F_CURRENT;
10431	feature->add_length = 4;
10432	feature->feature_data[0] = 0x00;
10433	feature->feature_data[1] = 0x00;
10434	feature = (struct scsi_get_config_feature *)
10435	    &feature->feature_data[feature->add_length];
10436
10437f2b:	/* DVD+R */
10438	scsi_ulto2b(0x002B, feature->feature_code);
10439	feature->flags = 0x00;
10440	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10441		feature->flags |= SGC_F_CURRENT;
10442	feature->add_length = 4;
10443	feature->feature_data[0] = 0x00;
10444	feature = (struct scsi_get_config_feature *)
10445	    &feature->feature_data[feature->add_length];
10446
10447f3a:	/* DVD+RW Dual Layer */
10448	scsi_ulto2b(0x003A, feature->feature_code);
10449	feature->flags = 0x00;
10450	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10451		feature->flags |= SGC_F_CURRENT;
10452	feature->add_length = 4;
10453	feature->feature_data[0] = 0x00;
10454	feature->feature_data[1] = 0x00;
10455	feature = (struct scsi_get_config_feature *)
10456	    &feature->feature_data[feature->add_length];
10457
10458f3b:	/* DVD+R Dual Layer */
10459	scsi_ulto2b(0x003B, feature->feature_code);
10460	feature->flags = 0x00;
10461	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10462		feature->flags |= SGC_F_CURRENT;
10463	feature->add_length = 4;
10464	feature->feature_data[0] = 0x00;
10465	feature = (struct scsi_get_config_feature *)
10466	    &feature->feature_data[feature->add_length];
10467
10468done:
10469	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10470	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10471		feature = (struct scsi_get_config_feature *)(hdr + 1);
10472		if (scsi_2btoul(feature->feature_code) == starting)
10473			feature = (struct scsi_get_config_feature *)
10474			    &feature->feature_data[feature->add_length];
10475		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10476	}
10477	scsi_ulto4b(data_len - 4, hdr->data_length);
10478	if (data_len < alloc_len) {
10479		ctsio->residual = alloc_len - data_len;
10480		ctsio->kern_data_len = data_len;
10481		ctsio->kern_total_len = data_len;
10482	} else {
10483		ctsio->residual = 0;
10484		ctsio->kern_data_len = alloc_len;
10485		ctsio->kern_total_len = alloc_len;
10486	}
10487
10488	ctl_set_success(ctsio);
10489	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10490	ctsio->be_move_done = ctl_config_move_done;
10491	ctl_datamove((union ctl_io *)ctsio);
10492	return (CTL_RETVAL_COMPLETE);
10493}
10494
10495int
10496ctl_get_event_status(struct ctl_scsiio *ctsio)
10497{
10498	struct scsi_get_event_status_header *hdr;
10499	struct scsi_get_event_status *cdb;
10500	uint32_t alloc_len, data_len;
10501	int notif_class;
10502
10503	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10504	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10505		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10506		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10507		ctl_done((union ctl_io *)ctsio);
10508		return (CTL_RETVAL_COMPLETE);
10509	}
10510	notif_class = cdb->notif_class;
10511	alloc_len = scsi_2btoul(cdb->length);
10512
10513	data_len = sizeof(struct scsi_get_event_status_header);
10514	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10515	ctsio->kern_sg_entries = 0;
10516	ctsio->kern_data_resid = 0;
10517	ctsio->kern_rel_offset = 0;
10518
10519	if (data_len < alloc_len) {
10520		ctsio->residual = alloc_len - data_len;
10521		ctsio->kern_data_len = data_len;
10522		ctsio->kern_total_len = data_len;
10523	} else {
10524		ctsio->residual = 0;
10525		ctsio->kern_data_len = alloc_len;
10526		ctsio->kern_total_len = alloc_len;
10527	}
10528
10529	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10530	scsi_ulto2b(0, hdr->descr_length);
10531	hdr->nea_class = SGESN_NEA;
10532	hdr->supported_class = 0;
10533
10534	ctl_set_success(ctsio);
10535	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10536	ctsio->be_move_done = ctl_config_move_done;
10537	ctl_datamove((union ctl_io *)ctsio);
10538	return (CTL_RETVAL_COMPLETE);
10539}
10540
10541int
10542ctl_mechanism_status(struct ctl_scsiio *ctsio)
10543{
10544	struct scsi_mechanism_status_header *hdr;
10545	struct scsi_mechanism_status *cdb;
10546	uint32_t alloc_len, data_len;
10547
10548	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10549	alloc_len = scsi_2btoul(cdb->length);
10550
10551	data_len = sizeof(struct scsi_mechanism_status_header);
10552	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10553	ctsio->kern_sg_entries = 0;
10554	ctsio->kern_data_resid = 0;
10555	ctsio->kern_rel_offset = 0;
10556
10557	if (data_len < alloc_len) {
10558		ctsio->residual = alloc_len - data_len;
10559		ctsio->kern_data_len = data_len;
10560		ctsio->kern_total_len = data_len;
10561	} else {
10562		ctsio->residual = 0;
10563		ctsio->kern_data_len = alloc_len;
10564		ctsio->kern_total_len = alloc_len;
10565	}
10566
10567	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10568	hdr->state1 = 0x00;
10569	hdr->state2 = 0xe0;
10570	scsi_ulto3b(0, hdr->lba);
10571	hdr->slots_num = 0;
10572	scsi_ulto2b(0, hdr->slots_length);
10573
10574	ctl_set_success(ctsio);
10575	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10576	ctsio->be_move_done = ctl_config_move_done;
10577	ctl_datamove((union ctl_io *)ctsio);
10578	return (CTL_RETVAL_COMPLETE);
10579}
10580
10581static void
10582ctl_ultomsf(uint32_t lba, uint8_t *buf)
10583{
10584
10585	lba += 150;
10586	buf[0] = 0;
10587	buf[1] = bin2bcd((lba / 75) / 60);
10588	buf[2] = bin2bcd((lba / 75) % 60);
10589	buf[3] = bin2bcd(lba % 75);
10590}
10591
10592int
10593ctl_read_toc(struct ctl_scsiio *ctsio)
10594{
10595	struct ctl_lun *lun = CTL_LUN(ctsio);
10596	struct scsi_read_toc_hdr *hdr;
10597	struct scsi_read_toc_type01_descr *descr;
10598	struct scsi_read_toc *cdb;
10599	uint32_t alloc_len, data_len;
10600	int format, msf;
10601
10602	cdb = (struct scsi_read_toc *)ctsio->cdb;
10603	msf = (cdb->byte2 & CD_MSF) != 0;
10604	format = cdb->format;
10605	alloc_len = scsi_2btoul(cdb->data_len);
10606
10607	data_len = sizeof(struct scsi_read_toc_hdr);
10608	if (format == 0)
10609		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10610	else
10611		data_len += sizeof(struct scsi_read_toc_type01_descr);
10612	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10613	ctsio->kern_sg_entries = 0;
10614	ctsio->kern_data_resid = 0;
10615	ctsio->kern_rel_offset = 0;
10616
10617	if (data_len < alloc_len) {
10618		ctsio->residual = alloc_len - data_len;
10619		ctsio->kern_data_len = data_len;
10620		ctsio->kern_total_len = data_len;
10621	} else {
10622		ctsio->residual = 0;
10623		ctsio->kern_data_len = alloc_len;
10624		ctsio->kern_total_len = alloc_len;
10625	}
10626
10627	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10628	if (format == 0) {
10629		scsi_ulto2b(0x12, hdr->data_length);
10630		hdr->first = 1;
10631		hdr->last = 1;
10632		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10633		descr->addr_ctl = 0x14;
10634		descr->track_number = 1;
10635		if (msf)
10636			ctl_ultomsf(0, descr->track_start);
10637		else
10638			scsi_ulto4b(0, descr->track_start);
10639		descr++;
10640		descr->addr_ctl = 0x14;
10641		descr->track_number = 0xaa;
10642		if (msf)
10643			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10644		else
10645			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10646	} else {
10647		scsi_ulto2b(0x0a, hdr->data_length);
10648		hdr->first = 1;
10649		hdr->last = 1;
10650		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10651		descr->addr_ctl = 0x14;
10652		descr->track_number = 1;
10653		if (msf)
10654			ctl_ultomsf(0, descr->track_start);
10655		else
10656			scsi_ulto4b(0, descr->track_start);
10657	}
10658
10659	ctl_set_success(ctsio);
10660	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10661	ctsio->be_move_done = ctl_config_move_done;
10662	ctl_datamove((union ctl_io *)ctsio);
10663	return (CTL_RETVAL_COMPLETE);
10664}
10665
10666/*
10667 * For known CDB types, parse the LBA and length.
10668 */
10669static int
10670ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10671{
10672	if (io->io_hdr.io_type != CTL_IO_SCSI)
10673		return (1);
10674
10675	switch (io->scsiio.cdb[0]) {
10676	case COMPARE_AND_WRITE: {
10677		struct scsi_compare_and_write *cdb;
10678
10679		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10680
10681		*lba = scsi_8btou64(cdb->addr);
10682		*len = cdb->length;
10683		break;
10684	}
10685	case READ_6:
10686	case WRITE_6: {
10687		struct scsi_rw_6 *cdb;
10688
10689		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10690
10691		*lba = scsi_3btoul(cdb->addr);
10692		/* only 5 bits are valid in the most significant address byte */
10693		*lba &= 0x1fffff;
10694		*len = cdb->length;
10695		break;
10696	}
10697	case READ_10:
10698	case WRITE_10: {
10699		struct scsi_rw_10 *cdb;
10700
10701		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10702
10703		*lba = scsi_4btoul(cdb->addr);
10704		*len = scsi_2btoul(cdb->length);
10705		break;
10706	}
10707	case WRITE_VERIFY_10: {
10708		struct scsi_write_verify_10 *cdb;
10709
10710		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10711
10712		*lba = scsi_4btoul(cdb->addr);
10713		*len = scsi_2btoul(cdb->length);
10714		break;
10715	}
10716	case READ_12:
10717	case WRITE_12: {
10718		struct scsi_rw_12 *cdb;
10719
10720		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10721
10722		*lba = scsi_4btoul(cdb->addr);
10723		*len = scsi_4btoul(cdb->length);
10724		break;
10725	}
10726	case WRITE_VERIFY_12: {
10727		struct scsi_write_verify_12 *cdb;
10728
10729		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10730
10731		*lba = scsi_4btoul(cdb->addr);
10732		*len = scsi_4btoul(cdb->length);
10733		break;
10734	}
10735	case READ_16:
10736	case WRITE_16: {
10737		struct scsi_rw_16 *cdb;
10738
10739		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10740
10741		*lba = scsi_8btou64(cdb->addr);
10742		*len = scsi_4btoul(cdb->length);
10743		break;
10744	}
10745	case WRITE_ATOMIC_16: {
10746		struct scsi_write_atomic_16 *cdb;
10747
10748		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10749
10750		*lba = scsi_8btou64(cdb->addr);
10751		*len = scsi_2btoul(cdb->length);
10752		break;
10753	}
10754	case WRITE_VERIFY_16: {
10755		struct scsi_write_verify_16 *cdb;
10756
10757		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10758
10759		*lba = scsi_8btou64(cdb->addr);
10760		*len = scsi_4btoul(cdb->length);
10761		break;
10762	}
10763	case WRITE_SAME_10: {
10764		struct scsi_write_same_10 *cdb;
10765
10766		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10767
10768		*lba = scsi_4btoul(cdb->addr);
10769		*len = scsi_2btoul(cdb->length);
10770		break;
10771	}
10772	case WRITE_SAME_16: {
10773		struct scsi_write_same_16 *cdb;
10774
10775		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10776
10777		*lba = scsi_8btou64(cdb->addr);
10778		*len = scsi_4btoul(cdb->length);
10779		break;
10780	}
10781	case VERIFY_10: {
10782		struct scsi_verify_10 *cdb;
10783
10784		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10785
10786		*lba = scsi_4btoul(cdb->addr);
10787		*len = scsi_2btoul(cdb->length);
10788		break;
10789	}
10790	case VERIFY_12: {
10791		struct scsi_verify_12 *cdb;
10792
10793		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10794
10795		*lba = scsi_4btoul(cdb->addr);
10796		*len = scsi_4btoul(cdb->length);
10797		break;
10798	}
10799	case VERIFY_16: {
10800		struct scsi_verify_16 *cdb;
10801
10802		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10803
10804		*lba = scsi_8btou64(cdb->addr);
10805		*len = scsi_4btoul(cdb->length);
10806		break;
10807	}
10808	case UNMAP: {
10809		*lba = 0;
10810		*len = UINT64_MAX;
10811		break;
10812	}
10813	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10814		struct scsi_get_lba_status *cdb;
10815
10816		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10817		*lba = scsi_8btou64(cdb->addr);
10818		*len = UINT32_MAX;
10819		break;
10820	}
10821	default:
10822		return (1);
10823		break; /* NOTREACHED */
10824	}
10825
10826	return (0);
10827}
10828
10829static ctl_action
10830ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10831    bool seq)
10832{
10833	uint64_t endlba1, endlba2;
10834
10835	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10836	endlba2 = lba2 + len2 - 1;
10837
10838	if ((endlba1 < lba2) || (endlba2 < lba1))
10839		return (CTL_ACTION_PASS);
10840	else
10841		return (CTL_ACTION_BLOCK);
10842}
10843
10844static int
10845ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10846{
10847	struct ctl_ptr_len_flags *ptrlen;
10848	struct scsi_unmap_desc *buf, *end, *range;
10849	uint64_t lba;
10850	uint32_t len;
10851
10852	/* If not UNMAP -- go other way. */
10853	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10854	    io->scsiio.cdb[0] != UNMAP)
10855		return (CTL_ACTION_ERROR);
10856
10857	/* If UNMAP without data -- block and wait for data. */
10858	ptrlen = (struct ctl_ptr_len_flags *)
10859	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10860	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10861	    ptrlen->ptr == NULL)
10862		return (CTL_ACTION_BLOCK);
10863
10864	/* UNMAP with data -- check for collision. */
10865	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10866	end = buf + ptrlen->len / sizeof(*buf);
10867	for (range = buf; range < end; range++) {
10868		lba = scsi_8btou64(range->lba);
10869		len = scsi_4btoul(range->length);
10870		if ((lba < lba2 + len2) && (lba + len > lba2))
10871			return (CTL_ACTION_BLOCK);
10872	}
10873	return (CTL_ACTION_PASS);
10874}
10875
10876static ctl_action
10877ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10878{
10879	uint64_t lba1, lba2;
10880	uint64_t len1, len2;
10881	int retval;
10882
10883	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10884		return (CTL_ACTION_ERROR);
10885
10886	retval = ctl_extent_check_unmap(io1, lba2, len2);
10887	if (retval != CTL_ACTION_ERROR)
10888		return (retval);
10889
10890	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10891		return (CTL_ACTION_ERROR);
10892
10893	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10894		seq = FALSE;
10895	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10896}
10897
10898static ctl_action
10899ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10900{
10901	uint64_t lba1, lba2;
10902	uint64_t len1, len2;
10903
10904	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10905		return (CTL_ACTION_PASS);
10906	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10907		return (CTL_ACTION_ERROR);
10908	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10909		return (CTL_ACTION_ERROR);
10910
10911	if (lba1 + len1 == lba2)
10912		return (CTL_ACTION_BLOCK);
10913	return (CTL_ACTION_PASS);
10914}
10915
10916static ctl_action
10917ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10918    union ctl_io *ooa_io)
10919{
10920	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10921	const ctl_serialize_action *serialize_row;
10922
10923	/*
10924	 * The initiator attempted multiple untagged commands at the same
10925	 * time.  Can't do that.
10926	 */
10927	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10928	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10929	 && ((pending_io->io_hdr.nexus.targ_port ==
10930	      ooa_io->io_hdr.nexus.targ_port)
10931	  && (pending_io->io_hdr.nexus.initid ==
10932	      ooa_io->io_hdr.nexus.initid))
10933	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10934	      CTL_FLAG_STATUS_SENT)) == 0))
10935		return (CTL_ACTION_OVERLAP);
10936
10937	/*
10938	 * The initiator attempted to send multiple tagged commands with
10939	 * the same ID.  (It's fine if different initiators have the same
10940	 * tag ID.)
10941	 *
10942	 * Even if all of those conditions are true, we don't kill the I/O
10943	 * if the command ahead of us has been aborted.  We won't end up
10944	 * sending it to the FETD, and it's perfectly legal to resend a
10945	 * command with the same tag number as long as the previous
10946	 * instance of this tag number has been aborted somehow.
10947	 */
10948	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10949	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10950	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10951	 && ((pending_io->io_hdr.nexus.targ_port ==
10952	      ooa_io->io_hdr.nexus.targ_port)
10953	  && (pending_io->io_hdr.nexus.initid ==
10954	      ooa_io->io_hdr.nexus.initid))
10955	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10956	      CTL_FLAG_STATUS_SENT)) == 0))
10957		return (CTL_ACTION_OVERLAP_TAG);
10958
10959	/*
10960	 * If we get a head of queue tag, SAM-3 says that we should
10961	 * immediately execute it.
10962	 *
10963	 * What happens if this command would normally block for some other
10964	 * reason?  e.g. a request sense with a head of queue tag
10965	 * immediately after a write.  Normally that would block, but this
10966	 * will result in its getting executed immediately...
10967	 *
10968	 * We currently return "pass" instead of "skip", so we'll end up
10969	 * going through the rest of the queue to check for overlapped tags.
10970	 *
10971	 * XXX KDM check for other types of blockage first??
10972	 */
10973	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10974		return (CTL_ACTION_PASS);
10975
10976	/*
10977	 * Ordered tags have to block until all items ahead of them
10978	 * have completed.  If we get called with an ordered tag, we always
10979	 * block, if something else is ahead of us in the queue.
10980	 */
10981	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10982		return (CTL_ACTION_BLOCK);
10983
10984	/*
10985	 * Simple tags get blocked until all head of queue and ordered tags
10986	 * ahead of them have completed.  I'm lumping untagged commands in
10987	 * with simple tags here.  XXX KDM is that the right thing to do?
10988	 */
10989	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10990	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10991	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10992	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10993		return (CTL_ACTION_BLOCK);
10994
10995	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10996	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
10997	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
10998	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
10999	     pending_io->scsiio.cdb[1], pending_io));
11000	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11001	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11002		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11003	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11004	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11005	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11006	     ooa_io->scsiio.cdb[1], ooa_io));
11007
11008	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11009
11010	switch (serialize_row[pending_entry->seridx]) {
11011	case CTL_SER_BLOCK:
11012		return (CTL_ACTION_BLOCK);
11013	case CTL_SER_EXTENT:
11014		return (ctl_extent_check(ooa_io, pending_io,
11015		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11016	case CTL_SER_EXTENTOPT:
11017		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11018		    SCP_QUEUE_ALG_UNRESTRICTED)
11019			return (ctl_extent_check(ooa_io, pending_io,
11020			    (lun->be_lun &&
11021			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11022		return (CTL_ACTION_PASS);
11023	case CTL_SER_EXTENTSEQ:
11024		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11025			return (ctl_extent_check_seq(ooa_io, pending_io));
11026		return (CTL_ACTION_PASS);
11027	case CTL_SER_PASS:
11028		return (CTL_ACTION_PASS);
11029	case CTL_SER_BLOCKOPT:
11030		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11031		    SCP_QUEUE_ALG_UNRESTRICTED)
11032			return (CTL_ACTION_BLOCK);
11033		return (CTL_ACTION_PASS);
11034	case CTL_SER_SKIP:
11035		return (CTL_ACTION_SKIP);
11036	default:
11037		panic("%s: Invalid serialization value %d for %d => %d",
11038		    __func__, serialize_row[pending_entry->seridx],
11039		    pending_entry->seridx, ooa_entry->seridx);
11040	}
11041
11042	return (CTL_ACTION_ERROR);
11043}
11044
11045/*
11046 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11047 * Assumptions:
11048 * - pending_io is generally either incoming, or on the blocked queue
11049 * - starting I/O is the I/O we want to start the check with.
11050 */
11051static ctl_action
11052ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11053	      union ctl_io *starting_io)
11054{
11055	union ctl_io *ooa_io;
11056	ctl_action action;
11057
11058	mtx_assert(&lun->lun_lock, MA_OWNED);
11059
11060	/*
11061	 * Run back along the OOA queue, starting with the current
11062	 * blocked I/O and going through every I/O before it on the
11063	 * queue.  If starting_io is NULL, we'll just end up returning
11064	 * CTL_ACTION_PASS.
11065	 */
11066	for (ooa_io = starting_io; ooa_io != NULL;
11067	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11068	     ooa_links)){
11069
11070		/*
11071		 * This routine just checks to see whether
11072		 * cur_blocked is blocked by ooa_io, which is ahead
11073		 * of it in the queue.  It doesn't queue/dequeue
11074		 * cur_blocked.
11075		 */
11076		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11077		switch (action) {
11078		case CTL_ACTION_BLOCK:
11079		case CTL_ACTION_OVERLAP:
11080		case CTL_ACTION_OVERLAP_TAG:
11081		case CTL_ACTION_SKIP:
11082		case CTL_ACTION_ERROR:
11083			return (action);
11084			break; /* NOTREACHED */
11085		case CTL_ACTION_PASS:
11086			break;
11087		default:
11088			panic("%s: Invalid action %d\n", __func__, action);
11089		}
11090	}
11091
11092	return (CTL_ACTION_PASS);
11093}
11094
11095/*
11096 * Assumptions:
11097 * - An I/O has just completed, and has been removed from the per-LUN OOA
11098 *   queue, so some items on the blocked queue may now be unblocked.
11099 */
11100static int
11101ctl_check_blocked(struct ctl_lun *lun)
11102{
11103	struct ctl_softc *softc = lun->ctl_softc;
11104	union ctl_io *cur_blocked, *next_blocked;
11105
11106	mtx_assert(&lun->lun_lock, MA_OWNED);
11107
11108	/*
11109	 * Run forward from the head of the blocked queue, checking each
11110	 * entry against the I/Os prior to it on the OOA queue to see if
11111	 * there is still any blockage.
11112	 *
11113	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11114	 * with our removing a variable on it while it is traversing the
11115	 * list.
11116	 */
11117	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11118	     cur_blocked != NULL; cur_blocked = next_blocked) {
11119		union ctl_io *prev_ooa;
11120		ctl_action action;
11121
11122		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11123							  blocked_links);
11124
11125		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11126						      ctl_ooaq, ooa_links);
11127
11128		/*
11129		 * If cur_blocked happens to be the first item in the OOA
11130		 * queue now, prev_ooa will be NULL, and the action
11131		 * returned will just be CTL_ACTION_PASS.
11132		 */
11133		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11134
11135		switch (action) {
11136		case CTL_ACTION_BLOCK:
11137			/* Nothing to do here, still blocked */
11138			break;
11139		case CTL_ACTION_OVERLAP:
11140		case CTL_ACTION_OVERLAP_TAG:
11141			/*
11142			 * This shouldn't happen!  In theory we've already
11143			 * checked this command for overlap...
11144			 */
11145			break;
11146		case CTL_ACTION_PASS:
11147		case CTL_ACTION_SKIP: {
11148			const struct ctl_cmd_entry *entry;
11149
11150			/*
11151			 * The skip case shouldn't happen, this transaction
11152			 * should have never made it onto the blocked queue.
11153			 */
11154			/*
11155			 * This I/O is no longer blocked, we can remove it
11156			 * from the blocked queue.  Since this is a TAILQ
11157			 * (doubly linked list), we can do O(1) removals
11158			 * from any place on the list.
11159			 */
11160			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11161				     blocked_links);
11162			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11163
11164			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11165			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11166				/*
11167				 * Need to send IO back to original side to
11168				 * run
11169				 */
11170				union ctl_ha_msg msg_info;
11171
11172				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11173				msg_info.hdr.original_sc =
11174					cur_blocked->io_hdr.original_sc;
11175				msg_info.hdr.serializing_sc = cur_blocked;
11176				msg_info.hdr.msg_type = CTL_MSG_R2R;
11177				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11178				    sizeof(msg_info.hdr), M_NOWAIT);
11179				break;
11180			}
11181			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11182
11183			/*
11184			 * Check this I/O for LUN state changes that may
11185			 * have happened while this command was blocked.
11186			 * The LUN state may have been changed by a command
11187			 * ahead of us in the queue, so we need to re-check
11188			 * for any states that can be caused by SCSI
11189			 * commands.
11190			 */
11191			if (ctl_scsiio_lun_check(lun, entry,
11192						 &cur_blocked->scsiio) == 0) {
11193				cur_blocked->io_hdr.flags |=
11194				                      CTL_FLAG_IS_WAS_ON_RTR;
11195				ctl_enqueue_rtr(cur_blocked);
11196			} else
11197				ctl_done(cur_blocked);
11198			break;
11199		}
11200		default:
11201			/*
11202			 * This probably shouldn't happen -- we shouldn't
11203			 * get CTL_ACTION_ERROR, or anything else.
11204			 */
11205			break;
11206		}
11207	}
11208
11209	return (CTL_RETVAL_COMPLETE);
11210}
11211
11212/*
11213 * This routine (with one exception) checks LUN flags that can be set by
11214 * commands ahead of us in the OOA queue.  These flags have to be checked
11215 * when a command initially comes in, and when we pull a command off the
11216 * blocked queue and are preparing to execute it.  The reason we have to
11217 * check these flags for commands on the blocked queue is that the LUN
11218 * state may have been changed by a command ahead of us while we're on the
11219 * blocked queue.
11220 *
11221 * Ordering is somewhat important with these checks, so please pay
11222 * careful attention to the placement of any new checks.
11223 */
11224static int
11225ctl_scsiio_lun_check(struct ctl_lun *lun,
11226    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11227{
11228	struct ctl_softc *softc = lun->ctl_softc;
11229	int retval;
11230	uint32_t residx;
11231
11232	retval = 0;
11233
11234	mtx_assert(&lun->lun_lock, MA_OWNED);
11235
11236	/*
11237	 * If this shelf is a secondary shelf controller, we may have to
11238	 * reject some commands disallowed by HA mode and link state.
11239	 */
11240	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11241		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11242		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11243			ctl_set_lun_unavail(ctsio);
11244			retval = 1;
11245			goto bailout;
11246		}
11247		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11248		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11249			ctl_set_lun_transit(ctsio);
11250			retval = 1;
11251			goto bailout;
11252		}
11253		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11254		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11255			ctl_set_lun_standby(ctsio);
11256			retval = 1;
11257			goto bailout;
11258		}
11259
11260		/* The rest of checks are only done on executing side */
11261		if (softc->ha_mode == CTL_HA_MODE_XFER)
11262			goto bailout;
11263	}
11264
11265	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11266		if (lun->be_lun &&
11267		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11268			ctl_set_hw_write_protected(ctsio);
11269			retval = 1;
11270			goto bailout;
11271		}
11272		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11273			ctl_set_sense(ctsio, /*current_error*/ 1,
11274			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11275			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11276			retval = 1;
11277			goto bailout;
11278		}
11279	}
11280
11281	/*
11282	 * Check for a reservation conflict.  If this command isn't allowed
11283	 * even on reserved LUNs, and if this initiator isn't the one who
11284	 * reserved us, reject the command with a reservation conflict.
11285	 */
11286	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11287	if ((lun->flags & CTL_LUN_RESERVED)
11288	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11289		if (lun->res_idx != residx) {
11290			ctl_set_reservation_conflict(ctsio);
11291			retval = 1;
11292			goto bailout;
11293		}
11294	}
11295
11296	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11297	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11298		/* No reservation or command is allowed. */;
11299	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11300	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11301	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11302	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11303		/* The command is allowed for Write Exclusive resv. */;
11304	} else {
11305		/*
11306		 * if we aren't registered or it's a res holder type
11307		 * reservation and this isn't the res holder then set a
11308		 * conflict.
11309		 */
11310		if (ctl_get_prkey(lun, residx) == 0 ||
11311		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11312			ctl_set_reservation_conflict(ctsio);
11313			retval = 1;
11314			goto bailout;
11315		}
11316	}
11317
11318	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11319		if (lun->flags & CTL_LUN_EJECTED)
11320			ctl_set_lun_ejected(ctsio);
11321		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11322			if (lun->flags & CTL_LUN_REMOVABLE)
11323				ctl_set_lun_no_media(ctsio);
11324			else
11325				ctl_set_lun_int_reqd(ctsio);
11326		} else if (lun->flags & CTL_LUN_STOPPED)
11327			ctl_set_lun_stopped(ctsio);
11328		else
11329			goto bailout;
11330		retval = 1;
11331		goto bailout;
11332	}
11333
11334bailout:
11335	return (retval);
11336}
11337
11338static void
11339ctl_failover_io(union ctl_io *io, int have_lock)
11340{
11341	ctl_set_busy(&io->scsiio);
11342	ctl_done(io);
11343}
11344
11345static void
11346ctl_failover_lun(union ctl_io *rio)
11347{
11348	struct ctl_softc *softc = CTL_SOFTC(rio);
11349	struct ctl_lun *lun;
11350	struct ctl_io_hdr *io, *next_io;
11351	uint32_t targ_lun;
11352
11353	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11354	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11355
11356	/* Find and lock the LUN. */
11357	mtx_lock(&softc->ctl_lock);
11358	if (targ_lun > CTL_MAX_LUNS ||
11359	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11360		mtx_unlock(&softc->ctl_lock);
11361		return;
11362	}
11363	mtx_lock(&lun->lun_lock);
11364	mtx_unlock(&softc->ctl_lock);
11365	if (lun->flags & CTL_LUN_DISABLED) {
11366		mtx_unlock(&lun->lun_lock);
11367		return;
11368	}
11369
11370	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11371		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11372			/* We are master */
11373			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11374				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11375					io->flags |= CTL_FLAG_ABORT;
11376					io->flags |= CTL_FLAG_FAILOVER;
11377				} else { /* This can be only due to DATAMOVE */
11378					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11379					io->flags &= ~CTL_FLAG_DMA_INPROG;
11380					io->flags |= CTL_FLAG_IO_ACTIVE;
11381					io->port_status = 31340;
11382					ctl_enqueue_isc((union ctl_io *)io);
11383				}
11384			}
11385			/* We are slave */
11386			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11387				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11388				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11389					io->flags |= CTL_FLAG_FAILOVER;
11390				} else {
11391					ctl_set_busy(&((union ctl_io *)io)->
11392					    scsiio);
11393					ctl_done((union ctl_io *)io);
11394				}
11395			}
11396		}
11397	} else { /* SERIALIZE modes */
11398		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11399		    next_io) {
11400			/* We are master */
11401			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11402				TAILQ_REMOVE(&lun->blocked_queue, io,
11403				    blocked_links);
11404				io->flags &= ~CTL_FLAG_BLOCKED;
11405				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11406				ctl_free_io((union ctl_io *)io);
11407			}
11408		}
11409		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11410			/* We are master */
11411			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11412				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11413				ctl_free_io((union ctl_io *)io);
11414			}
11415			/* We are slave */
11416			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11417				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11418				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11419					ctl_set_busy(&((union ctl_io *)io)->
11420					    scsiio);
11421					ctl_done((union ctl_io *)io);
11422				}
11423			}
11424		}
11425		ctl_check_blocked(lun);
11426	}
11427	mtx_unlock(&lun->lun_lock);
11428}
11429
11430static int
11431ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11432{
11433	struct ctl_lun *lun;
11434	const struct ctl_cmd_entry *entry;
11435	uint32_t initidx, targ_lun;
11436	int retval = 0;
11437
11438	lun = NULL;
11439	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11440	if (targ_lun < CTL_MAX_LUNS)
11441		lun = softc->ctl_luns[targ_lun];
11442	if (lun) {
11443		/*
11444		 * If the LUN is invalid, pretend that it doesn't exist.
11445		 * It will go away as soon as all pending I/O has been
11446		 * completed.
11447		 */
11448		mtx_lock(&lun->lun_lock);
11449		if (lun->flags & CTL_LUN_DISABLED) {
11450			mtx_unlock(&lun->lun_lock);
11451			lun = NULL;
11452		}
11453	}
11454	CTL_LUN(ctsio) = lun;
11455	if (lun) {
11456		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11457
11458		/*
11459		 * Every I/O goes into the OOA queue for a particular LUN,
11460		 * and stays there until completion.
11461		 */
11462#ifdef CTL_TIME_IO
11463		if (TAILQ_EMPTY(&lun->ooa_queue))
11464			lun->idle_time += getsbinuptime() - lun->last_busy;
11465#endif
11466		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11467	}
11468
11469	/* Get command entry and return error if it is unsuppotyed. */
11470	entry = ctl_validate_command(ctsio);
11471	if (entry == NULL) {
11472		if (lun)
11473			mtx_unlock(&lun->lun_lock);
11474		return (retval);
11475	}
11476
11477	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11478	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11479
11480	/*
11481	 * Check to see whether we can send this command to LUNs that don't
11482	 * exist.  This should pretty much only be the case for inquiry
11483	 * and request sense.  Further checks, below, really require having
11484	 * a LUN, so we can't really check the command anymore.  Just put
11485	 * it on the rtr queue.
11486	 */
11487	if (lun == NULL) {
11488		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11489			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11490			ctl_enqueue_rtr((union ctl_io *)ctsio);
11491			return (retval);
11492		}
11493
11494		ctl_set_unsupported_lun(ctsio);
11495		ctl_done((union ctl_io *)ctsio);
11496		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11497		return (retval);
11498	} else {
11499		/*
11500		 * Make sure we support this particular command on this LUN.
11501		 * e.g., we don't support writes to the control LUN.
11502		 */
11503		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11504			mtx_unlock(&lun->lun_lock);
11505			ctl_set_invalid_opcode(ctsio);
11506			ctl_done((union ctl_io *)ctsio);
11507			return (retval);
11508		}
11509	}
11510
11511	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11512
11513#ifdef CTL_WITH_CA
11514	/*
11515	 * If we've got a request sense, it'll clear the contingent
11516	 * allegiance condition.  Otherwise, if we have a CA condition for
11517	 * this initiator, clear it, because it sent down a command other
11518	 * than request sense.
11519	 */
11520	if ((ctsio->cdb[0] != REQUEST_SENSE)
11521	 && (ctl_is_set(lun->have_ca, initidx)))
11522		ctl_clear_mask(lun->have_ca, initidx);
11523#endif
11524
11525	/*
11526	 * If the command has this flag set, it handles its own unit
11527	 * attention reporting, we shouldn't do anything.  Otherwise we
11528	 * check for any pending unit attentions, and send them back to the
11529	 * initiator.  We only do this when a command initially comes in,
11530	 * not when we pull it off the blocked queue.
11531	 *
11532	 * According to SAM-3, section 5.3.2, the order that things get
11533	 * presented back to the host is basically unit attentions caused
11534	 * by some sort of reset event, busy status, reservation conflicts
11535	 * or task set full, and finally any other status.
11536	 *
11537	 * One issue here is that some of the unit attentions we report
11538	 * don't fall into the "reset" category (e.g. "reported luns data
11539	 * has changed").  So reporting it here, before the reservation
11540	 * check, may be technically wrong.  I guess the only thing to do
11541	 * would be to check for and report the reset events here, and then
11542	 * check for the other unit attention types after we check for a
11543	 * reservation conflict.
11544	 *
11545	 * XXX KDM need to fix this
11546	 */
11547	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11548		ctl_ua_type ua_type;
11549		u_int sense_len = 0;
11550
11551		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11552		    &sense_len, SSD_TYPE_NONE);
11553		if (ua_type != CTL_UA_NONE) {
11554			mtx_unlock(&lun->lun_lock);
11555			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11556			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11557			ctsio->sense_len = sense_len;
11558			ctl_done((union ctl_io *)ctsio);
11559			return (retval);
11560		}
11561	}
11562
11563
11564	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11565		mtx_unlock(&lun->lun_lock);
11566		ctl_done((union ctl_io *)ctsio);
11567		return (retval);
11568	}
11569
11570	/*
11571	 * XXX CHD this is where we want to send IO to other side if
11572	 * this LUN is secondary on this SC. We will need to make a copy
11573	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11574	 * the copy we send as FROM_OTHER.
11575	 * We also need to stuff the address of the original IO so we can
11576	 * find it easily. Something similar will need be done on the other
11577	 * side so when we are done we can find the copy.
11578	 */
11579	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11580	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11581	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11582		union ctl_ha_msg msg_info;
11583		int isc_retval;
11584
11585		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11586		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11587		mtx_unlock(&lun->lun_lock);
11588
11589		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11590		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11591		msg_info.hdr.serializing_sc = NULL;
11592		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11593		msg_info.scsi.tag_num = ctsio->tag_num;
11594		msg_info.scsi.tag_type = ctsio->tag_type;
11595		msg_info.scsi.cdb_len = ctsio->cdb_len;
11596		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11597
11598		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11599		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11600		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11601			ctl_set_busy(ctsio);
11602			ctl_done((union ctl_io *)ctsio);
11603			return (retval);
11604		}
11605		return (retval);
11606	}
11607
11608	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11609			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11610			      ctl_ooaq, ooa_links))) {
11611	case CTL_ACTION_BLOCK:
11612		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11613		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11614				  blocked_links);
11615		mtx_unlock(&lun->lun_lock);
11616		return (retval);
11617	case CTL_ACTION_PASS:
11618	case CTL_ACTION_SKIP:
11619		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11620		mtx_unlock(&lun->lun_lock);
11621		ctl_enqueue_rtr((union ctl_io *)ctsio);
11622		break;
11623	case CTL_ACTION_OVERLAP:
11624		mtx_unlock(&lun->lun_lock);
11625		ctl_set_overlapped_cmd(ctsio);
11626		ctl_done((union ctl_io *)ctsio);
11627		break;
11628	case CTL_ACTION_OVERLAP_TAG:
11629		mtx_unlock(&lun->lun_lock);
11630		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11631		ctl_done((union ctl_io *)ctsio);
11632		break;
11633	case CTL_ACTION_ERROR:
11634	default:
11635		mtx_unlock(&lun->lun_lock);
11636		ctl_set_internal_failure(ctsio,
11637					 /*sks_valid*/ 0,
11638					 /*retry_count*/ 0);
11639		ctl_done((union ctl_io *)ctsio);
11640		break;
11641	}
11642	return (retval);
11643}
11644
11645const struct ctl_cmd_entry *
11646ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11647{
11648	const struct ctl_cmd_entry *entry;
11649	int service_action;
11650
11651	entry = &ctl_cmd_table[ctsio->cdb[0]];
11652	if (sa)
11653		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11654	if (entry->flags & CTL_CMD_FLAG_SA5) {
11655		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11656		entry = &((const struct ctl_cmd_entry *)
11657		    entry->execute)[service_action];
11658	}
11659	return (entry);
11660}
11661
11662const struct ctl_cmd_entry *
11663ctl_validate_command(struct ctl_scsiio *ctsio)
11664{
11665	const struct ctl_cmd_entry *entry;
11666	int i, sa;
11667	uint8_t diff;
11668
11669	entry = ctl_get_cmd_entry(ctsio, &sa);
11670	if (entry->execute == NULL) {
11671		if (sa)
11672			ctl_set_invalid_field(ctsio,
11673					      /*sks_valid*/ 1,
11674					      /*command*/ 1,
11675					      /*field*/ 1,
11676					      /*bit_valid*/ 1,
11677					      /*bit*/ 4);
11678		else
11679			ctl_set_invalid_opcode(ctsio);
11680		ctl_done((union ctl_io *)ctsio);
11681		return (NULL);
11682	}
11683	KASSERT(entry->length > 0,
11684	    ("Not defined length for command 0x%02x/0x%02x",
11685	     ctsio->cdb[0], ctsio->cdb[1]));
11686	for (i = 1; i < entry->length; i++) {
11687		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11688		if (diff == 0)
11689			continue;
11690		ctl_set_invalid_field(ctsio,
11691				      /*sks_valid*/ 1,
11692				      /*command*/ 1,
11693				      /*field*/ i,
11694				      /*bit_valid*/ 1,
11695				      /*bit*/ fls(diff) - 1);
11696		ctl_done((union ctl_io *)ctsio);
11697		return (NULL);
11698	}
11699	return (entry);
11700}
11701
11702static int
11703ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11704{
11705
11706	switch (lun_type) {
11707	case T_DIRECT:
11708		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11709			return (0);
11710		break;
11711	case T_PROCESSOR:
11712		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11713			return (0);
11714		break;
11715	case T_CDROM:
11716		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11717			return (0);
11718		break;
11719	default:
11720		return (0);
11721	}
11722	return (1);
11723}
11724
11725static int
11726ctl_scsiio(struct ctl_scsiio *ctsio)
11727{
11728	int retval;
11729	const struct ctl_cmd_entry *entry;
11730
11731	retval = CTL_RETVAL_COMPLETE;
11732
11733	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11734
11735	entry = ctl_get_cmd_entry(ctsio, NULL);
11736
11737	/*
11738	 * If this I/O has been aborted, just send it straight to
11739	 * ctl_done() without executing it.
11740	 */
11741	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11742		ctl_done((union ctl_io *)ctsio);
11743		goto bailout;
11744	}
11745
11746	/*
11747	 * All the checks should have been handled by ctl_scsiio_precheck().
11748	 * We should be clear now to just execute the I/O.
11749	 */
11750	retval = entry->execute(ctsio);
11751
11752bailout:
11753	return (retval);
11754}
11755
11756/*
11757 * Since we only implement one target right now, a bus reset simply resets
11758 * our single target.
11759 */
11760static int
11761ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11762{
11763	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11764}
11765
11766static int
11767ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11768		 ctl_ua_type ua_type)
11769{
11770	struct ctl_port *port = CTL_PORT(io);
11771	struct ctl_lun *lun;
11772	int retval;
11773
11774	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11775		union ctl_ha_msg msg_info;
11776
11777		msg_info.hdr.nexus = io->io_hdr.nexus;
11778		if (ua_type==CTL_UA_TARG_RESET)
11779			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11780		else
11781			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11782		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11783		msg_info.hdr.original_sc = NULL;
11784		msg_info.hdr.serializing_sc = NULL;
11785		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11786		    sizeof(msg_info.task), M_WAITOK);
11787	}
11788	retval = 0;
11789
11790	mtx_lock(&softc->ctl_lock);
11791	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11792		if (port != NULL &&
11793		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11794			continue;
11795		retval += ctl_do_lun_reset(lun, io, ua_type);
11796	}
11797	mtx_unlock(&softc->ctl_lock);
11798	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11799	return (retval);
11800}
11801
11802/*
11803 * The LUN should always be set.  The I/O is optional, and is used to
11804 * distinguish between I/Os sent by this initiator, and by other
11805 * initiators.  We set unit attention for initiators other than this one.
11806 * SAM-3 is vague on this point.  It does say that a unit attention should
11807 * be established for other initiators when a LUN is reset (see section
11808 * 5.7.3), but it doesn't specifically say that the unit attention should
11809 * be established for this particular initiator when a LUN is reset.  Here
11810 * is the relevant text, from SAM-3 rev 8:
11811 *
11812 * 5.7.2 When a SCSI initiator port aborts its own tasks
11813 *
11814 * When a SCSI initiator port causes its own task(s) to be aborted, no
11815 * notification that the task(s) have been aborted shall be returned to
11816 * the SCSI initiator port other than the completion response for the
11817 * command or task management function action that caused the task(s) to
11818 * be aborted and notification(s) associated with related effects of the
11819 * action (e.g., a reset unit attention condition).
11820 *
11821 * XXX KDM for now, we're setting unit attention for all initiators.
11822 */
11823static int
11824ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11825{
11826	union ctl_io *xio;
11827#if 0
11828	uint32_t initidx;
11829#endif
11830	int i;
11831
11832	mtx_lock(&lun->lun_lock);
11833	/*
11834	 * Run through the OOA queue and abort each I/O.
11835	 */
11836	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11837	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11838		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11839	}
11840
11841	/*
11842	 * This version sets unit attention for every
11843	 */
11844#if 0
11845	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11846	ctl_est_ua_all(lun, initidx, ua_type);
11847#else
11848	ctl_est_ua_all(lun, -1, ua_type);
11849#endif
11850
11851	/*
11852	 * A reset (any kind, really) clears reservations established with
11853	 * RESERVE/RELEASE.  It does not clear reservations established
11854	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11855	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11856	 * reservations made with the RESERVE/RELEASE commands, because
11857	 * those commands are obsolete in SPC-3.
11858	 */
11859	lun->flags &= ~CTL_LUN_RESERVED;
11860
11861#ifdef CTL_WITH_CA
11862	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11863		ctl_clear_mask(lun->have_ca, i);
11864#endif
11865	lun->prevent_count = 0;
11866	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11867		ctl_clear_mask(lun->prevent, i);
11868	mtx_unlock(&lun->lun_lock);
11869
11870	return (0);
11871}
11872
11873static int
11874ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11875{
11876	struct ctl_lun *lun;
11877	uint32_t targ_lun;
11878	int retval;
11879
11880	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11881	mtx_lock(&softc->ctl_lock);
11882	if (targ_lun >= CTL_MAX_LUNS ||
11883	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11884		mtx_unlock(&softc->ctl_lock);
11885		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11886		return (1);
11887	}
11888	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11889	mtx_unlock(&softc->ctl_lock);
11890	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11891
11892	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11893		union ctl_ha_msg msg_info;
11894
11895		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11896		msg_info.hdr.nexus = io->io_hdr.nexus;
11897		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11898		msg_info.hdr.original_sc = NULL;
11899		msg_info.hdr.serializing_sc = NULL;
11900		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11901		    sizeof(msg_info.task), M_WAITOK);
11902	}
11903	return (retval);
11904}
11905
11906static void
11907ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11908    int other_sc)
11909{
11910	union ctl_io *xio;
11911
11912	mtx_assert(&lun->lun_lock, MA_OWNED);
11913
11914	/*
11915	 * Run through the OOA queue and attempt to find the given I/O.
11916	 * The target port, initiator ID, tag type and tag number have to
11917	 * match the values that we got from the initiator.  If we have an
11918	 * untagged command to abort, simply abort the first untagged command
11919	 * we come to.  We only allow one untagged command at a time of course.
11920	 */
11921	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11922	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11923
11924		if ((targ_port == UINT32_MAX ||
11925		     targ_port == xio->io_hdr.nexus.targ_port) &&
11926		    (init_id == UINT32_MAX ||
11927		     init_id == xio->io_hdr.nexus.initid)) {
11928			if (targ_port != xio->io_hdr.nexus.targ_port ||
11929			    init_id != xio->io_hdr.nexus.initid)
11930				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11931			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11932			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11933				union ctl_ha_msg msg_info;
11934
11935				msg_info.hdr.nexus = xio->io_hdr.nexus;
11936				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11937				msg_info.task.tag_num = xio->scsiio.tag_num;
11938				msg_info.task.tag_type = xio->scsiio.tag_type;
11939				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11940				msg_info.hdr.original_sc = NULL;
11941				msg_info.hdr.serializing_sc = NULL;
11942				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11943				    sizeof(msg_info.task), M_NOWAIT);
11944			}
11945		}
11946	}
11947}
11948
11949static int
11950ctl_abort_task_set(union ctl_io *io)
11951{
11952	struct ctl_softc *softc = CTL_SOFTC(io);
11953	struct ctl_lun *lun;
11954	uint32_t targ_lun;
11955
11956	/*
11957	 * Look up the LUN.
11958	 */
11959	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11960	mtx_lock(&softc->ctl_lock);
11961	if (targ_lun >= CTL_MAX_LUNS ||
11962	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11963		mtx_unlock(&softc->ctl_lock);
11964		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11965		return (1);
11966	}
11967
11968	mtx_lock(&lun->lun_lock);
11969	mtx_unlock(&softc->ctl_lock);
11970	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11971		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11972		    io->io_hdr.nexus.initid,
11973		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11974	} else { /* CTL_TASK_CLEAR_TASK_SET */
11975		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11976		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11977	}
11978	mtx_unlock(&lun->lun_lock);
11979	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11980	return (0);
11981}
11982
11983static int
11984ctl_i_t_nexus_reset(union ctl_io *io)
11985{
11986	struct ctl_softc *softc = CTL_SOFTC(io);
11987	struct ctl_lun *lun;
11988	uint32_t initidx;
11989
11990	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11991		union ctl_ha_msg msg_info;
11992
11993		msg_info.hdr.nexus = io->io_hdr.nexus;
11994		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11995		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11996		msg_info.hdr.original_sc = NULL;
11997		msg_info.hdr.serializing_sc = NULL;
11998		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11999		    sizeof(msg_info.task), M_WAITOK);
12000	}
12001
12002	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12003	mtx_lock(&softc->ctl_lock);
12004	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12005		mtx_lock(&lun->lun_lock);
12006		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12007		    io->io_hdr.nexus.initid, 1);
12008#ifdef CTL_WITH_CA
12009		ctl_clear_mask(lun->have_ca, initidx);
12010#endif
12011		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12012			lun->flags &= ~CTL_LUN_RESERVED;
12013		if (ctl_is_set(lun->prevent, initidx)) {
12014			ctl_clear_mask(lun->prevent, initidx);
12015			lun->prevent_count--;
12016		}
12017		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12018		mtx_unlock(&lun->lun_lock);
12019	}
12020	mtx_unlock(&softc->ctl_lock);
12021	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12022	return (0);
12023}
12024
12025static int
12026ctl_abort_task(union ctl_io *io)
12027{
12028	struct ctl_softc *softc = CTL_SOFTC(io);
12029	union ctl_io *xio;
12030	struct ctl_lun *lun;
12031#if 0
12032	struct sbuf sb;
12033	char printbuf[128];
12034#endif
12035	int found;
12036	uint32_t targ_lun;
12037
12038	found = 0;
12039
12040	/*
12041	 * Look up the LUN.
12042	 */
12043	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12044	mtx_lock(&softc->ctl_lock);
12045	if (targ_lun >= CTL_MAX_LUNS ||
12046	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12047		mtx_unlock(&softc->ctl_lock);
12048		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12049		return (1);
12050	}
12051
12052#if 0
12053	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12054	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12055#endif
12056
12057	mtx_lock(&lun->lun_lock);
12058	mtx_unlock(&softc->ctl_lock);
12059	/*
12060	 * Run through the OOA queue and attempt to find the given I/O.
12061	 * The target port, initiator ID, tag type and tag number have to
12062	 * match the values that we got from the initiator.  If we have an
12063	 * untagged command to abort, simply abort the first untagged command
12064	 * we come to.  We only allow one untagged command at a time of course.
12065	 */
12066	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12067	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12068#if 0
12069		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12070
12071		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12072			    lun->lun, xio->scsiio.tag_num,
12073			    xio->scsiio.tag_type,
12074			    (xio->io_hdr.blocked_links.tqe_prev
12075			    == NULL) ? "" : " BLOCKED",
12076			    (xio->io_hdr.flags &
12077			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12078			    (xio->io_hdr.flags &
12079			    CTL_FLAG_ABORT) ? " ABORT" : "",
12080			    (xio->io_hdr.flags &
12081			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12082		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12083		sbuf_finish(&sb);
12084		printf("%s\n", sbuf_data(&sb));
12085#endif
12086
12087		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12088		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12089		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12090			continue;
12091
12092		/*
12093		 * If the abort says that the task is untagged, the
12094		 * task in the queue must be untagged.  Otherwise,
12095		 * we just check to see whether the tag numbers
12096		 * match.  This is because the QLogic firmware
12097		 * doesn't pass back the tag type in an abort
12098		 * request.
12099		 */
12100#if 0
12101		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12102		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12103		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12104#endif
12105		/*
12106		 * XXX KDM we've got problems with FC, because it
12107		 * doesn't send down a tag type with aborts.  So we
12108		 * can only really go by the tag number...
12109		 * This may cause problems with parallel SCSI.
12110		 * Need to figure that out!!
12111		 */
12112		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12113			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12114			found = 1;
12115			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12116			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12117				union ctl_ha_msg msg_info;
12118
12119				msg_info.hdr.nexus = io->io_hdr.nexus;
12120				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12121				msg_info.task.tag_num = io->taskio.tag_num;
12122				msg_info.task.tag_type = io->taskio.tag_type;
12123				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12124				msg_info.hdr.original_sc = NULL;
12125				msg_info.hdr.serializing_sc = NULL;
12126#if 0
12127				printf("Sent Abort to other side\n");
12128#endif
12129				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12130				    sizeof(msg_info.task), M_NOWAIT);
12131			}
12132#if 0
12133			printf("ctl_abort_task: found I/O to abort\n");
12134#endif
12135		}
12136	}
12137	mtx_unlock(&lun->lun_lock);
12138
12139	if (found == 0) {
12140		/*
12141		 * This isn't really an error.  It's entirely possible for
12142		 * the abort and command completion to cross on the wire.
12143		 * This is more of an informative/diagnostic error.
12144		 */
12145#if 0
12146		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12147		       "%u:%u:%u tag %d type %d\n",
12148		       io->io_hdr.nexus.initid,
12149		       io->io_hdr.nexus.targ_port,
12150		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12151		       io->taskio.tag_type);
12152#endif
12153	}
12154	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12155	return (0);
12156}
12157
12158static int
12159ctl_query_task(union ctl_io *io, int task_set)
12160{
12161	struct ctl_softc *softc = CTL_SOFTC(io);
12162	union ctl_io *xio;
12163	struct ctl_lun *lun;
12164	int found = 0;
12165	uint32_t targ_lun;
12166
12167	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12168	mtx_lock(&softc->ctl_lock);
12169	if (targ_lun >= CTL_MAX_LUNS ||
12170	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12171		mtx_unlock(&softc->ctl_lock);
12172		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12173		return (1);
12174	}
12175	mtx_lock(&lun->lun_lock);
12176	mtx_unlock(&softc->ctl_lock);
12177	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12178	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12179
12180		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12181		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12182		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12183			continue;
12184
12185		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12186			found = 1;
12187			break;
12188		}
12189	}
12190	mtx_unlock(&lun->lun_lock);
12191	if (found)
12192		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12193	else
12194		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12195	return (0);
12196}
12197
12198static int
12199ctl_query_async_event(union ctl_io *io)
12200{
12201	struct ctl_softc *softc = CTL_SOFTC(io);
12202	struct ctl_lun *lun;
12203	ctl_ua_type ua;
12204	uint32_t targ_lun, initidx;
12205
12206	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12207	mtx_lock(&softc->ctl_lock);
12208	if (targ_lun >= CTL_MAX_LUNS ||
12209	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12210		mtx_unlock(&softc->ctl_lock);
12211		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12212		return (1);
12213	}
12214	mtx_lock(&lun->lun_lock);
12215	mtx_unlock(&softc->ctl_lock);
12216	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12217	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12218	mtx_unlock(&lun->lun_lock);
12219	if (ua != CTL_UA_NONE)
12220		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12221	else
12222		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12223	return (0);
12224}
12225
12226static void
12227ctl_run_task(union ctl_io *io)
12228{
12229	struct ctl_softc *softc = CTL_SOFTC(io);
12230	int retval = 1;
12231
12232	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12233	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12234	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12235	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12236	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12237	switch (io->taskio.task_action) {
12238	case CTL_TASK_ABORT_TASK:
12239		retval = ctl_abort_task(io);
12240		break;
12241	case CTL_TASK_ABORT_TASK_SET:
12242	case CTL_TASK_CLEAR_TASK_SET:
12243		retval = ctl_abort_task_set(io);
12244		break;
12245	case CTL_TASK_CLEAR_ACA:
12246		break;
12247	case CTL_TASK_I_T_NEXUS_RESET:
12248		retval = ctl_i_t_nexus_reset(io);
12249		break;
12250	case CTL_TASK_LUN_RESET:
12251		retval = ctl_lun_reset(softc, io);
12252		break;
12253	case CTL_TASK_TARGET_RESET:
12254		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12255		break;
12256	case CTL_TASK_BUS_RESET:
12257		retval = ctl_bus_reset(softc, io);
12258		break;
12259	case CTL_TASK_PORT_LOGIN:
12260		break;
12261	case CTL_TASK_PORT_LOGOUT:
12262		break;
12263	case CTL_TASK_QUERY_TASK:
12264		retval = ctl_query_task(io, 0);
12265		break;
12266	case CTL_TASK_QUERY_TASK_SET:
12267		retval = ctl_query_task(io, 1);
12268		break;
12269	case CTL_TASK_QUERY_ASYNC_EVENT:
12270		retval = ctl_query_async_event(io);
12271		break;
12272	default:
12273		printf("%s: got unknown task management event %d\n",
12274		       __func__, io->taskio.task_action);
12275		break;
12276	}
12277	if (retval == 0)
12278		io->io_hdr.status = CTL_SUCCESS;
12279	else
12280		io->io_hdr.status = CTL_ERROR;
12281	ctl_done(io);
12282}
12283
12284/*
12285 * For HA operation.  Handle commands that come in from the other
12286 * controller.
12287 */
12288static void
12289ctl_handle_isc(union ctl_io *io)
12290{
12291	struct ctl_softc *softc = CTL_SOFTC(io);
12292	struct ctl_lun *lun;
12293	const struct ctl_cmd_entry *entry;
12294	uint32_t targ_lun;
12295
12296	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12297	switch (io->io_hdr.msg_type) {
12298	case CTL_MSG_SERIALIZE:
12299		ctl_serialize_other_sc_cmd(&io->scsiio);
12300		break;
12301	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12302		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12303		if (targ_lun >= CTL_MAX_LUNS ||
12304		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12305			ctl_done(io);
12306			break;
12307		}
12308		mtx_lock(&lun->lun_lock);
12309		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12310			mtx_unlock(&lun->lun_lock);
12311			ctl_done(io);
12312			break;
12313		}
12314		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12315		mtx_unlock(&lun->lun_lock);
12316		ctl_enqueue_rtr(io);
12317		break;
12318	case CTL_MSG_FINISH_IO:
12319		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12320			ctl_done(io);
12321			break;
12322		}
12323		if (targ_lun >= CTL_MAX_LUNS ||
12324		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12325			ctl_free_io(io);
12326			break;
12327		}
12328		mtx_lock(&lun->lun_lock);
12329		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12330		ctl_check_blocked(lun);
12331		mtx_unlock(&lun->lun_lock);
12332		ctl_free_io(io);
12333		break;
12334	case CTL_MSG_PERS_ACTION:
12335		ctl_hndl_per_res_out_on_other_sc(io);
12336		ctl_free_io(io);
12337		break;
12338	case CTL_MSG_BAD_JUJU:
12339		ctl_done(io);
12340		break;
12341	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12342		ctl_datamove_remote(io);
12343		break;
12344	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12345		io->scsiio.be_move_done(io);
12346		break;
12347	case CTL_MSG_FAILOVER:
12348		ctl_failover_lun(io);
12349		ctl_free_io(io);
12350		break;
12351	default:
12352		printf("%s: Invalid message type %d\n",
12353		       __func__, io->io_hdr.msg_type);
12354		ctl_free_io(io);
12355		break;
12356	}
12357
12358}
12359
12360
12361/*
12362 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12363 * there is no match.
12364 */
12365static ctl_lun_error_pattern
12366ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12367{
12368	const struct ctl_cmd_entry *entry;
12369	ctl_lun_error_pattern filtered_pattern, pattern;
12370
12371	pattern = desc->error_pattern;
12372
12373	/*
12374	 * XXX KDM we need more data passed into this function to match a
12375	 * custom pattern, and we actually need to implement custom pattern
12376	 * matching.
12377	 */
12378	if (pattern & CTL_LUN_PAT_CMD)
12379		return (CTL_LUN_PAT_CMD);
12380
12381	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12382		return (CTL_LUN_PAT_ANY);
12383
12384	entry = ctl_get_cmd_entry(ctsio, NULL);
12385
12386	filtered_pattern = entry->pattern & pattern;
12387
12388	/*
12389	 * If the user requested specific flags in the pattern (e.g.
12390	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12391	 * flags.
12392	 *
12393	 * If the user did not specify any flags, it doesn't matter whether
12394	 * or not the command supports the flags.
12395	 */
12396	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12397	     (pattern & ~CTL_LUN_PAT_MASK))
12398		return (CTL_LUN_PAT_NONE);
12399
12400	/*
12401	 * If the user asked for a range check, see if the requested LBA
12402	 * range overlaps with this command's LBA range.
12403	 */
12404	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12405		uint64_t lba1;
12406		uint64_t len1;
12407		ctl_action action;
12408		int retval;
12409
12410		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12411		if (retval != 0)
12412			return (CTL_LUN_PAT_NONE);
12413
12414		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12415					      desc->lba_range.len, FALSE);
12416		/*
12417		 * A "pass" means that the LBA ranges don't overlap, so
12418		 * this doesn't match the user's range criteria.
12419		 */
12420		if (action == CTL_ACTION_PASS)
12421			return (CTL_LUN_PAT_NONE);
12422	}
12423
12424	return (filtered_pattern);
12425}
12426
12427static void
12428ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12429{
12430	struct ctl_error_desc *desc, *desc2;
12431
12432	mtx_assert(&lun->lun_lock, MA_OWNED);
12433
12434	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12435		ctl_lun_error_pattern pattern;
12436		/*
12437		 * Check to see whether this particular command matches
12438		 * the pattern in the descriptor.
12439		 */
12440		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12441		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12442			continue;
12443
12444		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12445		case CTL_LUN_INJ_ABORTED:
12446			ctl_set_aborted(&io->scsiio);
12447			break;
12448		case CTL_LUN_INJ_MEDIUM_ERR:
12449			ctl_set_medium_error(&io->scsiio,
12450			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12451			     CTL_FLAG_DATA_OUT);
12452			break;
12453		case CTL_LUN_INJ_UA:
12454			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12455			 * OCCURRED */
12456			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12457			break;
12458		case CTL_LUN_INJ_CUSTOM:
12459			/*
12460			 * We're assuming the user knows what he is doing.
12461			 * Just copy the sense information without doing
12462			 * checks.
12463			 */
12464			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12465			      MIN(sizeof(desc->custom_sense),
12466				  sizeof(io->scsiio.sense_data)));
12467			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12468			io->scsiio.sense_len = SSD_FULL_SIZE;
12469			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12470			break;
12471		case CTL_LUN_INJ_NONE:
12472		default:
12473			/*
12474			 * If this is an error injection type we don't know
12475			 * about, clear the continuous flag (if it is set)
12476			 * so it will get deleted below.
12477			 */
12478			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12479			break;
12480		}
12481		/*
12482		 * By default, each error injection action is a one-shot
12483		 */
12484		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12485			continue;
12486
12487		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12488
12489		free(desc, M_CTL);
12490	}
12491}
12492
12493#ifdef CTL_IO_DELAY
12494static void
12495ctl_datamove_timer_wakeup(void *arg)
12496{
12497	union ctl_io *io;
12498
12499	io = (union ctl_io *)arg;
12500
12501	ctl_datamove(io);
12502}
12503#endif /* CTL_IO_DELAY */
12504
12505void
12506ctl_datamove(union ctl_io *io)
12507{
12508	void (*fe_datamove)(union ctl_io *io);
12509
12510	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12511
12512	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12513
12514#ifdef CTL_TIME_IO
12515	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12516		char str[256];
12517		char path_str[64];
12518		struct sbuf sb;
12519
12520		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12521		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12522
12523		sbuf_cat(&sb, path_str);
12524		switch (io->io_hdr.io_type) {
12525		case CTL_IO_SCSI:
12526			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12527			sbuf_printf(&sb, "\n");
12528			sbuf_cat(&sb, path_str);
12529			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12530				    io->scsiio.tag_num, io->scsiio.tag_type);
12531			break;
12532		case CTL_IO_TASK:
12533			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12534				    "Tag Type: %d\n", io->taskio.task_action,
12535				    io->taskio.tag_num, io->taskio.tag_type);
12536			break;
12537		default:
12538			panic("%s: Invalid CTL I/O type %d\n",
12539			    __func__, io->io_hdr.io_type);
12540		}
12541		sbuf_cat(&sb, path_str);
12542		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12543			    (intmax_t)time_uptime - io->io_hdr.start_time);
12544		sbuf_finish(&sb);
12545		printf("%s", sbuf_data(&sb));
12546	}
12547#endif /* CTL_TIME_IO */
12548
12549#ifdef CTL_IO_DELAY
12550	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12551		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12552	} else {
12553		if ((lun != NULL)
12554		 && (lun->delay_info.datamove_delay > 0)) {
12555
12556			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12557			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12558			callout_reset(&io->io_hdr.delay_callout,
12559				      lun->delay_info.datamove_delay * hz,
12560				      ctl_datamove_timer_wakeup, io);
12561			if (lun->delay_info.datamove_type ==
12562			    CTL_DELAY_TYPE_ONESHOT)
12563				lun->delay_info.datamove_delay = 0;
12564			return;
12565		}
12566	}
12567#endif
12568
12569	/*
12570	 * This command has been aborted.  Set the port status, so we fail
12571	 * the data move.
12572	 */
12573	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12574		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12575		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12576		       io->io_hdr.nexus.targ_port,
12577		       io->io_hdr.nexus.targ_lun);
12578		io->io_hdr.port_status = 31337;
12579		/*
12580		 * Note that the backend, in this case, will get the
12581		 * callback in its context.  In other cases it may get
12582		 * called in the frontend's interrupt thread context.
12583		 */
12584		io->scsiio.be_move_done(io);
12585		return;
12586	}
12587
12588	/* Don't confuse frontend with zero length data move. */
12589	if (io->scsiio.kern_data_len == 0) {
12590		io->scsiio.be_move_done(io);
12591		return;
12592	}
12593
12594	fe_datamove = CTL_PORT(io)->fe_datamove;
12595	fe_datamove(io);
12596}
12597
12598static void
12599ctl_send_datamove_done(union ctl_io *io, int have_lock)
12600{
12601	union ctl_ha_msg msg;
12602#ifdef CTL_TIME_IO
12603	struct bintime cur_bt;
12604#endif
12605
12606	memset(&msg, 0, sizeof(msg));
12607	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12608	msg.hdr.original_sc = io;
12609	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12610	msg.hdr.nexus = io->io_hdr.nexus;
12611	msg.hdr.status = io->io_hdr.status;
12612	msg.scsi.tag_num = io->scsiio.tag_num;
12613	msg.scsi.tag_type = io->scsiio.tag_type;
12614	msg.scsi.scsi_status = io->scsiio.scsi_status;
12615	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12616	       io->scsiio.sense_len);
12617	msg.scsi.sense_len = io->scsiio.sense_len;
12618	msg.scsi.sense_residual = io->scsiio.sense_residual;
12619	msg.scsi.fetd_status = io->io_hdr.port_status;
12620	msg.scsi.residual = io->scsiio.residual;
12621	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12622	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12623		ctl_failover_io(io, /*have_lock*/ have_lock);
12624		return;
12625	}
12626	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12627	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12628	    msg.scsi.sense_len, M_WAITOK);
12629
12630#ifdef CTL_TIME_IO
12631	getbinuptime(&cur_bt);
12632	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12633	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12634#endif
12635	io->io_hdr.num_dmas++;
12636}
12637
12638/*
12639 * The DMA to the remote side is done, now we need to tell the other side
12640 * we're done so it can continue with its data movement.
12641 */
12642static void
12643ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12644{
12645	union ctl_io *io;
12646	uint32_t i;
12647
12648	io = rq->context;
12649
12650	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12651		printf("%s: ISC DMA write failed with error %d", __func__,
12652		       rq->ret);
12653		ctl_set_internal_failure(&io->scsiio,
12654					 /*sks_valid*/ 1,
12655					 /*retry_count*/ rq->ret);
12656	}
12657
12658	ctl_dt_req_free(rq);
12659
12660	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12661		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12662	free(io->io_hdr.remote_sglist, M_CTL);
12663	io->io_hdr.remote_sglist = NULL;
12664	io->io_hdr.local_sglist = NULL;
12665
12666	/*
12667	 * The data is in local and remote memory, so now we need to send
12668	 * status (good or back) back to the other side.
12669	 */
12670	ctl_send_datamove_done(io, /*have_lock*/ 0);
12671}
12672
12673/*
12674 * We've moved the data from the host/controller into local memory.  Now we
12675 * need to push it over to the remote controller's memory.
12676 */
12677static int
12678ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12679{
12680	int retval;
12681
12682	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12683					  ctl_datamove_remote_write_cb);
12684	return (retval);
12685}
12686
12687static void
12688ctl_datamove_remote_write(union ctl_io *io)
12689{
12690	int retval;
12691	void (*fe_datamove)(union ctl_io *io);
12692
12693	/*
12694	 * - Get the data from the host/HBA into local memory.
12695	 * - DMA memory from the local controller to the remote controller.
12696	 * - Send status back to the remote controller.
12697	 */
12698
12699	retval = ctl_datamove_remote_sgl_setup(io);
12700	if (retval != 0)
12701		return;
12702
12703	/* Switch the pointer over so the FETD knows what to do */
12704	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12705
12706	/*
12707	 * Use a custom move done callback, since we need to send completion
12708	 * back to the other controller, not to the backend on this side.
12709	 */
12710	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12711
12712	fe_datamove = CTL_PORT(io)->fe_datamove;
12713	fe_datamove(io);
12714}
12715
12716static int
12717ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12718{
12719#if 0
12720	char str[256];
12721	char path_str[64];
12722	struct sbuf sb;
12723#endif
12724	uint32_t i;
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#if 0
12733	scsi_path_string(io, path_str, sizeof(path_str));
12734	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12735	sbuf_cat(&sb, path_str);
12736	scsi_command_string(&io->scsiio, NULL, &sb);
12737	sbuf_printf(&sb, "\n");
12738	sbuf_cat(&sb, path_str);
12739	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12740		    io->scsiio.tag_num, io->scsiio.tag_type);
12741	sbuf_cat(&sb, path_str);
12742	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12743		    io->io_hdr.flags, io->io_hdr.status);
12744	sbuf_finish(&sb);
12745	printk("%s", sbuf_data(&sb));
12746#endif
12747
12748
12749	/*
12750	 * The read is done, now we need to send status (good or bad) back
12751	 * to the other side.
12752	 */
12753	ctl_send_datamove_done(io, /*have_lock*/ 0);
12754
12755	return (0);
12756}
12757
12758static void
12759ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12760{
12761	union ctl_io *io;
12762	void (*fe_datamove)(union ctl_io *io);
12763
12764	io = rq->context;
12765
12766	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12767		printf("%s: ISC DMA read failed with error %d\n", __func__,
12768		       rq->ret);
12769		ctl_set_internal_failure(&io->scsiio,
12770					 /*sks_valid*/ 1,
12771					 /*retry_count*/ rq->ret);
12772	}
12773
12774	ctl_dt_req_free(rq);
12775
12776	/* Switch the pointer over so the FETD knows what to do */
12777	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12778
12779	/*
12780	 * Use a custom move done callback, since we need to send completion
12781	 * back to the other controller, not to the backend on this side.
12782	 */
12783	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12784
12785	/* XXX KDM add checks like the ones in ctl_datamove? */
12786
12787	fe_datamove = CTL_PORT(io)->fe_datamove;
12788	fe_datamove(io);
12789}
12790
12791static int
12792ctl_datamove_remote_sgl_setup(union ctl_io *io)
12793{
12794	struct ctl_sg_entry *local_sglist;
12795	uint32_t len_to_go;
12796	int retval;
12797	int i;
12798
12799	retval = 0;
12800	local_sglist = io->io_hdr.local_sglist;
12801	len_to_go = io->scsiio.kern_data_len;
12802
12803	/*
12804	 * The difficult thing here is that the size of the various
12805	 * S/G segments may be different than the size from the
12806	 * remote controller.  That'll make it harder when DMAing
12807	 * the data back to the other side.
12808	 */
12809	for (i = 0; len_to_go > 0; i++) {
12810		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12811		local_sglist[i].addr =
12812		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12813
12814		len_to_go -= local_sglist[i].len;
12815	}
12816	/*
12817	 * Reset the number of S/G entries accordingly.  The original
12818	 * number of S/G entries is available in rem_sg_entries.
12819	 */
12820	io->scsiio.kern_sg_entries = i;
12821
12822#if 0
12823	printf("%s: kern_sg_entries = %d\n", __func__,
12824	       io->scsiio.kern_sg_entries);
12825	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12826		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12827		       local_sglist[i].addr, local_sglist[i].len);
12828#endif
12829
12830	return (retval);
12831}
12832
12833static int
12834ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12835			 ctl_ha_dt_cb callback)
12836{
12837	struct ctl_ha_dt_req *rq;
12838	struct ctl_sg_entry *remote_sglist, *local_sglist;
12839	uint32_t local_used, remote_used, total_used;
12840	int i, j, isc_ret;
12841
12842	rq = ctl_dt_req_alloc();
12843
12844	/*
12845	 * If we failed to allocate the request, and if the DMA didn't fail
12846	 * anyway, set busy status.  This is just a resource allocation
12847	 * failure.
12848	 */
12849	if ((rq == NULL)
12850	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12851	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12852		ctl_set_busy(&io->scsiio);
12853
12854	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12855	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12856
12857		if (rq != NULL)
12858			ctl_dt_req_free(rq);
12859
12860		/*
12861		 * The data move failed.  We need to return status back
12862		 * to the other controller.  No point in trying to DMA
12863		 * data to the remote controller.
12864		 */
12865
12866		ctl_send_datamove_done(io, /*have_lock*/ 0);
12867
12868		return (1);
12869	}
12870
12871	local_sglist = io->io_hdr.local_sglist;
12872	remote_sglist = io->io_hdr.remote_sglist;
12873	local_used = 0;
12874	remote_used = 0;
12875	total_used = 0;
12876
12877	/*
12878	 * Pull/push the data over the wire from/to the other controller.
12879	 * This takes into account the possibility that the local and
12880	 * remote sglists may not be identical in terms of the size of
12881	 * the elements and the number of elements.
12882	 *
12883	 * One fundamental assumption here is that the length allocated for
12884	 * both the local and remote sglists is identical.  Otherwise, we've
12885	 * essentially got a coding error of some sort.
12886	 */
12887	isc_ret = CTL_HA_STATUS_SUCCESS;
12888	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12889		uint32_t cur_len;
12890		uint8_t *tmp_ptr;
12891
12892		rq->command = command;
12893		rq->context = io;
12894
12895		/*
12896		 * Both pointers should be aligned.  But it is possible
12897		 * that the allocation length is not.  They should both
12898		 * also have enough slack left over at the end, though,
12899		 * to round up to the next 8 byte boundary.
12900		 */
12901		cur_len = MIN(local_sglist[i].len - local_used,
12902			      remote_sglist[j].len - remote_used);
12903		rq->size = cur_len;
12904
12905		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12906		tmp_ptr += local_used;
12907
12908#if 0
12909		/* Use physical addresses when talking to ISC hardware */
12910		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12911			/* XXX KDM use busdma */
12912			rq->local = vtophys(tmp_ptr);
12913		} else
12914			rq->local = tmp_ptr;
12915#else
12916		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12917		    ("HA does not support BUS_ADDR"));
12918		rq->local = tmp_ptr;
12919#endif
12920
12921		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12922		tmp_ptr += remote_used;
12923		rq->remote = tmp_ptr;
12924
12925		rq->callback = NULL;
12926
12927		local_used += cur_len;
12928		if (local_used >= local_sglist[i].len) {
12929			i++;
12930			local_used = 0;
12931		}
12932
12933		remote_used += cur_len;
12934		if (remote_used >= remote_sglist[j].len) {
12935			j++;
12936			remote_used = 0;
12937		}
12938		total_used += cur_len;
12939
12940		if (total_used >= io->scsiio.kern_data_len)
12941			rq->callback = callback;
12942
12943#if 0
12944		printf("%s: %s: local %p remote %p size %d\n", __func__,
12945		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12946		       rq->local, rq->remote, rq->size);
12947#endif
12948
12949		isc_ret = ctl_dt_single(rq);
12950		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12951			break;
12952	}
12953	if (isc_ret != CTL_HA_STATUS_WAIT) {
12954		rq->ret = isc_ret;
12955		callback(rq);
12956	}
12957
12958	return (0);
12959}
12960
12961static void
12962ctl_datamove_remote_read(union ctl_io *io)
12963{
12964	int retval;
12965	uint32_t i;
12966
12967	/*
12968	 * This will send an error to the other controller in the case of a
12969	 * failure.
12970	 */
12971	retval = ctl_datamove_remote_sgl_setup(io);
12972	if (retval != 0)
12973		return;
12974
12975	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12976					  ctl_datamove_remote_read_cb);
12977	if (retval != 0) {
12978		/*
12979		 * Make sure we free memory if there was an error..  The
12980		 * ctl_datamove_remote_xfer() function will send the
12981		 * datamove done message, or call the callback with an
12982		 * error if there is a problem.
12983		 */
12984		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12985			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12986		free(io->io_hdr.remote_sglist, M_CTL);
12987		io->io_hdr.remote_sglist = NULL;
12988		io->io_hdr.local_sglist = NULL;
12989	}
12990}
12991
12992/*
12993 * Process a datamove request from the other controller.  This is used for
12994 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12995 * first.  Once that is complete, the data gets DMAed into the remote
12996 * controller's memory.  For reads, we DMA from the remote controller's
12997 * memory into our memory first, and then move it out to the FETD.
12998 */
12999static void
13000ctl_datamove_remote(union ctl_io *io)
13001{
13002
13003	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
13004
13005	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13006		ctl_failover_io(io, /*have_lock*/ 0);
13007		return;
13008	}
13009
13010	/*
13011	 * Note that we look for an aborted I/O here, but don't do some of
13012	 * the other checks that ctl_datamove() normally does.
13013	 * We don't need to run the datamove delay code, since that should
13014	 * have been done if need be on the other controller.
13015	 */
13016	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13017		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13018		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13019		       io->io_hdr.nexus.targ_port,
13020		       io->io_hdr.nexus.targ_lun);
13021		io->io_hdr.port_status = 31338;
13022		ctl_send_datamove_done(io, /*have_lock*/ 0);
13023		return;
13024	}
13025
13026	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13027		ctl_datamove_remote_write(io);
13028	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13029		ctl_datamove_remote_read(io);
13030	else {
13031		io->io_hdr.port_status = 31339;
13032		ctl_send_datamove_done(io, /*have_lock*/ 0);
13033	}
13034}
13035
13036static void
13037ctl_process_done(union ctl_io *io)
13038{
13039	struct ctl_softc *softc = CTL_SOFTC(io);
13040	struct ctl_lun *lun = CTL_LUN(io);
13041	void (*fe_done)(union ctl_io *io);
13042	union ctl_ha_msg msg;
13043	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13044
13045	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13046	fe_done = softc->ctl_ports[targ_port]->fe_done;
13047
13048#ifdef CTL_TIME_IO
13049	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13050		char str[256];
13051		char path_str[64];
13052		struct sbuf sb;
13053
13054		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13055		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13056
13057		sbuf_cat(&sb, path_str);
13058		switch (io->io_hdr.io_type) {
13059		case CTL_IO_SCSI:
13060			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13061			sbuf_printf(&sb, "\n");
13062			sbuf_cat(&sb, path_str);
13063			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13064				    io->scsiio.tag_num, io->scsiio.tag_type);
13065			break;
13066		case CTL_IO_TASK:
13067			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13068				    "Tag Type: %d\n", io->taskio.task_action,
13069				    io->taskio.tag_num, io->taskio.tag_type);
13070			break;
13071		default:
13072			panic("%s: Invalid CTL I/O type %d\n",
13073			    __func__, io->io_hdr.io_type);
13074		}
13075		sbuf_cat(&sb, path_str);
13076		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13077			    (intmax_t)time_uptime - io->io_hdr.start_time);
13078		sbuf_finish(&sb);
13079		printf("%s", sbuf_data(&sb));
13080	}
13081#endif /* CTL_TIME_IO */
13082
13083	switch (io->io_hdr.io_type) {
13084	case CTL_IO_SCSI:
13085		break;
13086	case CTL_IO_TASK:
13087		if (ctl_debug & CTL_DEBUG_INFO)
13088			ctl_io_error_print(io, NULL);
13089		fe_done(io);
13090		return;
13091	default:
13092		panic("%s: Invalid CTL I/O type %d\n",
13093		    __func__, io->io_hdr.io_type);
13094	}
13095
13096	if (lun == NULL) {
13097		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13098				 io->io_hdr.nexus.targ_mapped_lun));
13099		goto bailout;
13100	}
13101
13102	mtx_lock(&lun->lun_lock);
13103
13104	/*
13105	 * Check to see if we have any informational exception and status
13106	 * of this command can be modified to report it in form of either
13107	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13108	 */
13109	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13110	    io->io_hdr.status == CTL_SUCCESS &&
13111	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13112		uint8_t mrie = lun->MODE_IE.mrie;
13113		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13114		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13115		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13116		     mrie == SIEP_MRIE_REC_UNCOND ||
13117		     mrie == SIEP_MRIE_NO_SENSE) &&
13118		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13119		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13120			ctl_set_sense(&io->scsiio,
13121			      /*current_error*/ 1,
13122			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13123			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13124			      /*asc*/ lun->ie_asc,
13125			      /*ascq*/ lun->ie_ascq,
13126			      SSD_ELEM_NONE);
13127			lun->ie_reported = 1;
13128		}
13129	} else if (lun->ie_reported < 0)
13130		lun->ie_reported = 0;
13131
13132	/*
13133	 * Check to see if we have any errors to inject here.  We only
13134	 * inject errors for commands that don't already have errors set.
13135	 */
13136	if (!STAILQ_EMPTY(&lun->error_list) &&
13137	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13138	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13139		ctl_inject_error(lun, io);
13140
13141	/*
13142	 * XXX KDM how do we treat commands that aren't completed
13143	 * successfully?
13144	 *
13145	 * XXX KDM should we also track I/O latency?
13146	 */
13147	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13148	    io->io_hdr.io_type == CTL_IO_SCSI) {
13149#ifdef CTL_TIME_IO
13150		struct bintime cur_bt;
13151#endif
13152		int type;
13153
13154		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13155		    CTL_FLAG_DATA_IN)
13156			type = CTL_STATS_READ;
13157		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13158		    CTL_FLAG_DATA_OUT)
13159			type = CTL_STATS_WRITE;
13160		else
13161			type = CTL_STATS_NO_IO;
13162
13163		lun->stats.ports[targ_port].bytes[type] +=
13164		    io->scsiio.kern_total_len;
13165		lun->stats.ports[targ_port].operations[type]++;
13166#ifdef CTL_TIME_IO
13167		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13168		   &io->io_hdr.dma_bt);
13169		getbinuptime(&cur_bt);
13170		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13171		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13172#endif
13173		lun->stats.ports[targ_port].num_dmas[type] +=
13174		    io->io_hdr.num_dmas;
13175	}
13176
13177	/*
13178	 * Remove this from the OOA queue.
13179	 */
13180	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13181#ifdef CTL_TIME_IO
13182	if (TAILQ_EMPTY(&lun->ooa_queue))
13183		lun->last_busy = getsbinuptime();
13184#endif
13185
13186	/*
13187	 * Run through the blocked queue on this LUN and see if anything
13188	 * has become unblocked, now that this transaction is done.
13189	 */
13190	ctl_check_blocked(lun);
13191
13192	/*
13193	 * If the LUN has been invalidated, free it if there is nothing
13194	 * left on its OOA queue.
13195	 */
13196	if ((lun->flags & CTL_LUN_INVALID)
13197	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13198		mtx_unlock(&lun->lun_lock);
13199		mtx_lock(&softc->ctl_lock);
13200		ctl_free_lun(lun);
13201		mtx_unlock(&softc->ctl_lock);
13202	} else
13203		mtx_unlock(&lun->lun_lock);
13204
13205bailout:
13206
13207	/*
13208	 * If this command has been aborted, make sure we set the status
13209	 * properly.  The FETD is responsible for freeing the I/O and doing
13210	 * whatever it needs to do to clean up its state.
13211	 */
13212	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13213		ctl_set_task_aborted(&io->scsiio);
13214
13215	/*
13216	 * If enabled, print command error status.
13217	 */
13218	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13219	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13220		ctl_io_error_print(io, NULL);
13221
13222	/*
13223	 * Tell the FETD or the other shelf controller we're done with this
13224	 * command.  Note that only SCSI commands get to this point.  Task
13225	 * management commands are completed above.
13226	 */
13227	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13228	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13229		memset(&msg, 0, sizeof(msg));
13230		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13231		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13232		msg.hdr.nexus = io->io_hdr.nexus;
13233		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13234		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13235		    M_WAITOK);
13236	}
13237
13238	fe_done(io);
13239}
13240
13241#ifdef CTL_WITH_CA
13242/*
13243 * Front end should call this if it doesn't do autosense.  When the request
13244 * sense comes back in from the initiator, we'll dequeue this and send it.
13245 */
13246int
13247ctl_queue_sense(union ctl_io *io)
13248{
13249	struct ctl_softc *softc = CTL_SOFTC(io);
13250	struct ctl_port *port = CTL_PORT(io);
13251	struct ctl_lun *lun;
13252	uint32_t initidx, targ_lun;
13253
13254	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13255
13256	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13257
13258	/*
13259	 * LUN lookup will likely move to the ctl_work_thread() once we
13260	 * have our new queueing infrastructure (that doesn't put things on
13261	 * a per-LUN queue initially).  That is so that we can handle
13262	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13263	 * can't deal with that right now.
13264	 * If we don't have a LUN for this, just toss the sense information.
13265	 */
13266	mtx_lock(&softc->ctl_lock);
13267	if (targ_lun >= CTL_MAX_LUNS ||
13268	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13269		mtx_unlock(&softc->ctl_lock);
13270		goto bailout;
13271	}
13272	mtx_lock(&lun->lun_lock);
13273	mtx_unlock(&softc->ctl_lock);
13274
13275	/*
13276	 * Already have CA set for this LUN...toss the sense information.
13277	 */
13278	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13279	if (ctl_is_set(lun->have_ca, initidx)) {
13280		mtx_unlock(&lun->lun_lock);
13281		goto bailout;
13282	}
13283
13284	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13285	       MIN(sizeof(lun->pending_sense[initidx]),
13286	       sizeof(io->scsiio.sense_data)));
13287	ctl_set_mask(lun->have_ca, initidx);
13288	mtx_unlock(&lun->lun_lock);
13289
13290bailout:
13291	ctl_free_io(io);
13292	return (CTL_RETVAL_COMPLETE);
13293}
13294#endif
13295
13296/*
13297 * Primary command inlet from frontend ports.  All SCSI and task I/O
13298 * requests must go through this function.
13299 */
13300int
13301ctl_queue(union ctl_io *io)
13302{
13303	struct ctl_port *port = CTL_PORT(io);
13304
13305	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13306
13307#ifdef CTL_TIME_IO
13308	io->io_hdr.start_time = time_uptime;
13309	getbinuptime(&io->io_hdr.start_bt);
13310#endif /* CTL_TIME_IO */
13311
13312	/* Map FE-specific LUN ID into global one. */
13313	io->io_hdr.nexus.targ_mapped_lun =
13314	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13315
13316	switch (io->io_hdr.io_type) {
13317	case CTL_IO_SCSI:
13318	case CTL_IO_TASK:
13319		if (ctl_debug & CTL_DEBUG_CDB)
13320			ctl_io_print(io);
13321		ctl_enqueue_incoming(io);
13322		break;
13323	default:
13324		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13325		return (EINVAL);
13326	}
13327
13328	return (CTL_RETVAL_COMPLETE);
13329}
13330
13331#ifdef CTL_IO_DELAY
13332static void
13333ctl_done_timer_wakeup(void *arg)
13334{
13335	union ctl_io *io;
13336
13337	io = (union ctl_io *)arg;
13338	ctl_done(io);
13339}
13340#endif /* CTL_IO_DELAY */
13341
13342void
13343ctl_serseq_done(union ctl_io *io)
13344{
13345	struct ctl_lun *lun = CTL_LUN(io);;
13346
13347	if (lun->be_lun == NULL ||
13348	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13349		return;
13350	mtx_lock(&lun->lun_lock);
13351	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13352	ctl_check_blocked(lun);
13353	mtx_unlock(&lun->lun_lock);
13354}
13355
13356void
13357ctl_done(union ctl_io *io)
13358{
13359
13360	/*
13361	 * Enable this to catch duplicate completion issues.
13362	 */
13363#if 0
13364	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13365		printf("%s: type %d msg %d cdb %x iptl: "
13366		       "%u:%u:%u tag 0x%04x "
13367		       "flag %#x status %x\n",
13368			__func__,
13369			io->io_hdr.io_type,
13370			io->io_hdr.msg_type,
13371			io->scsiio.cdb[0],
13372			io->io_hdr.nexus.initid,
13373			io->io_hdr.nexus.targ_port,
13374			io->io_hdr.nexus.targ_lun,
13375			(io->io_hdr.io_type ==
13376			CTL_IO_TASK) ?
13377			io->taskio.tag_num :
13378			io->scsiio.tag_num,
13379		        io->io_hdr.flags,
13380			io->io_hdr.status);
13381	} else
13382		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13383#endif
13384
13385	/*
13386	 * This is an internal copy of an I/O, and should not go through
13387	 * the normal done processing logic.
13388	 */
13389	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13390		return;
13391
13392#ifdef CTL_IO_DELAY
13393	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13394		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13395	} else {
13396		struct ctl_lun *lun = CTL_LUN(io);
13397
13398		if ((lun != NULL)
13399		 && (lun->delay_info.done_delay > 0)) {
13400
13401			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13402			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13403			callout_reset(&io->io_hdr.delay_callout,
13404				      lun->delay_info.done_delay * hz,
13405				      ctl_done_timer_wakeup, io);
13406			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13407				lun->delay_info.done_delay = 0;
13408			return;
13409		}
13410	}
13411#endif /* CTL_IO_DELAY */
13412
13413	ctl_enqueue_done(io);
13414}
13415
13416static void
13417ctl_work_thread(void *arg)
13418{
13419	struct ctl_thread *thr = (struct ctl_thread *)arg;
13420	struct ctl_softc *softc = thr->ctl_softc;
13421	union ctl_io *io;
13422	int retval;
13423
13424	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13425
13426	for (;;) {
13427		/*
13428		 * We handle the queues in this order:
13429		 * - ISC
13430		 * - done queue (to free up resources, unblock other commands)
13431		 * - RtR queue
13432		 * - incoming queue
13433		 *
13434		 * If those queues are empty, we break out of the loop and
13435		 * go to sleep.
13436		 */
13437		mtx_lock(&thr->queue_lock);
13438		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13439		if (io != NULL) {
13440			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13441			mtx_unlock(&thr->queue_lock);
13442			ctl_handle_isc(io);
13443			continue;
13444		}
13445		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13446		if (io != NULL) {
13447			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13448			/* clear any blocked commands, call fe_done */
13449			mtx_unlock(&thr->queue_lock);
13450			ctl_process_done(io);
13451			continue;
13452		}
13453		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13454		if (io != NULL) {
13455			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13456			mtx_unlock(&thr->queue_lock);
13457			if (io->io_hdr.io_type == CTL_IO_TASK)
13458				ctl_run_task(io);
13459			else
13460				ctl_scsiio_precheck(softc, &io->scsiio);
13461			continue;
13462		}
13463		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13464		if (io != NULL) {
13465			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13466			mtx_unlock(&thr->queue_lock);
13467			retval = ctl_scsiio(&io->scsiio);
13468			if (retval != CTL_RETVAL_COMPLETE)
13469				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13470			continue;
13471		}
13472
13473		/* Sleep until we have something to do. */
13474		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13475	}
13476}
13477
13478static void
13479ctl_lun_thread(void *arg)
13480{
13481	struct ctl_softc *softc = (struct ctl_softc *)arg;
13482	struct ctl_be_lun *be_lun;
13483
13484	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13485
13486	for (;;) {
13487		mtx_lock(&softc->ctl_lock);
13488		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13489		if (be_lun != NULL) {
13490			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13491			mtx_unlock(&softc->ctl_lock);
13492			ctl_create_lun(be_lun);
13493			continue;
13494		}
13495
13496		/* Sleep until we have something to do. */
13497		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13498		    PDROP | PRIBIO, "-", 0);
13499	}
13500}
13501
13502static void
13503ctl_thresh_thread(void *arg)
13504{
13505	struct ctl_softc *softc = (struct ctl_softc *)arg;
13506	struct ctl_lun *lun;
13507	struct ctl_logical_block_provisioning_page *page;
13508	const char *attr;
13509	union ctl_ha_msg msg;
13510	uint64_t thres, val;
13511	int i, e, set;
13512
13513	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13514
13515	for (;;) {
13516		mtx_lock(&softc->ctl_lock);
13517		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13518			if ((lun->flags & CTL_LUN_DISABLED) ||
13519			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13520			    lun->backend->lun_attr == NULL)
13521				continue;
13522			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13523			    softc->ha_mode == CTL_HA_MODE_XFER)
13524				continue;
13525			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13526				continue;
13527			e = 0;
13528			page = &lun->MODE_LBP;
13529			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13530				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13531					continue;
13532				thres = scsi_4btoul(page->descr[i].count);
13533				thres <<= CTL_LBP_EXPONENT;
13534				switch (page->descr[i].resource) {
13535				case 0x01:
13536					attr = "blocksavail";
13537					break;
13538				case 0x02:
13539					attr = "blocksused";
13540					break;
13541				case 0xf1:
13542					attr = "poolblocksavail";
13543					break;
13544				case 0xf2:
13545					attr = "poolblocksused";
13546					break;
13547				default:
13548					continue;
13549				}
13550				mtx_unlock(&softc->ctl_lock); // XXX
13551				val = lun->backend->lun_attr(
13552				    lun->be_lun->be_lun, attr);
13553				mtx_lock(&softc->ctl_lock);
13554				if (val == UINT64_MAX)
13555					continue;
13556				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13557				    == SLBPPD_ARMING_INC)
13558					e = (val >= thres);
13559				else
13560					e = (val <= thres);
13561				if (e)
13562					break;
13563			}
13564			mtx_lock(&lun->lun_lock);
13565			if (e) {
13566				scsi_u64to8b((uint8_t *)&page->descr[i] -
13567				    (uint8_t *)page, lun->ua_tpt_info);
13568				if (lun->lasttpt == 0 ||
13569				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13570					lun->lasttpt = time_uptime;
13571					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13572					set = 1;
13573				} else
13574					set = 0;
13575			} else {
13576				lun->lasttpt = 0;
13577				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13578				set = -1;
13579			}
13580			mtx_unlock(&lun->lun_lock);
13581			if (set != 0 &&
13582			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13583				/* Send msg to other side. */
13584				bzero(&msg.ua, sizeof(msg.ua));
13585				msg.hdr.msg_type = CTL_MSG_UA;
13586				msg.hdr.nexus.initid = -1;
13587				msg.hdr.nexus.targ_port = -1;
13588				msg.hdr.nexus.targ_lun = lun->lun;
13589				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13590				msg.ua.ua_all = 1;
13591				msg.ua.ua_set = (set > 0);
13592				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13593				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13594				mtx_unlock(&softc->ctl_lock); // XXX
13595				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13596				    sizeof(msg.ua), M_WAITOK);
13597				mtx_lock(&softc->ctl_lock);
13598			}
13599		}
13600		mtx_unlock(&softc->ctl_lock);
13601		pause("-", CTL_LBP_PERIOD * hz);
13602	}
13603}
13604
13605static void
13606ctl_enqueue_incoming(union ctl_io *io)
13607{
13608	struct ctl_softc *softc = CTL_SOFTC(io);
13609	struct ctl_thread *thr;
13610	u_int idx;
13611
13612	idx = (io->io_hdr.nexus.targ_port * 127 +
13613	       io->io_hdr.nexus.initid) % worker_threads;
13614	thr = &softc->threads[idx];
13615	mtx_lock(&thr->queue_lock);
13616	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13617	mtx_unlock(&thr->queue_lock);
13618	wakeup(thr);
13619}
13620
13621static void
13622ctl_enqueue_rtr(union ctl_io *io)
13623{
13624	struct ctl_softc *softc = CTL_SOFTC(io);
13625	struct ctl_thread *thr;
13626
13627	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13628	mtx_lock(&thr->queue_lock);
13629	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13630	mtx_unlock(&thr->queue_lock);
13631	wakeup(thr);
13632}
13633
13634static void
13635ctl_enqueue_done(union ctl_io *io)
13636{
13637	struct ctl_softc *softc = CTL_SOFTC(io);
13638	struct ctl_thread *thr;
13639
13640	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13641	mtx_lock(&thr->queue_lock);
13642	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13643	mtx_unlock(&thr->queue_lock);
13644	wakeup(thr);
13645}
13646
13647static void
13648ctl_enqueue_isc(union ctl_io *io)
13649{
13650	struct ctl_softc *softc = CTL_SOFTC(io);
13651	struct ctl_thread *thr;
13652
13653	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13654	mtx_lock(&thr->queue_lock);
13655	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13656	mtx_unlock(&thr->queue_lock);
13657	wakeup(thr);
13658}
13659
13660/*
13661 *  vim: ts=8
13662 */
13663