ctl.c revision 312572
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/11/sys/cam/ctl/ctl.c 312572 2017-01-21 08:31:20Z 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;
405SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
406    &worker_threads, 1, "Number of worker threads");
407static int ctl_debug = CTL_DEBUG_NONE;
408SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
409    &ctl_debug, 0, "Enabled debug flags");
410
411/*
412 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
413 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
414 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
415 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
416 */
417#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
418
419static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
420				  int param);
421static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
422static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
423static int ctl_init(void);
424void ctl_shutdown(void);
425static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
426static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
427static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
428static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
429			      struct ctl_ooa *ooa_hdr,
430			      struct ctl_ooa_entry *kern_entries);
431static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
432		     struct thread *td);
433static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
434			 struct ctl_be_lun *be_lun);
435static int ctl_free_lun(struct ctl_lun *lun);
436static void ctl_create_lun(struct ctl_be_lun *be_lun);
437static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
438
439static int ctl_do_mode_select(union ctl_io *io);
440static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
441			   uint64_t res_key, uint64_t sa_res_key,
442			   uint8_t type, uint32_t residx,
443			   struct ctl_scsiio *ctsio,
444			   struct scsi_per_res_out *cdb,
445			   struct scsi_per_res_out_parms* param);
446static void ctl_pro_preempt_other(struct ctl_lun *lun,
447				  union ctl_ha_msg *msg);
448static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
449static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
450static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
451static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
452static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
453static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
455					 int alloc_len);
456static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
457					 int alloc_len);
458static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
459static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
460static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
461static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
462static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
463static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
464    bool seq);
465static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
466static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
467    union ctl_io *pending_io, union ctl_io *ooa_io);
468static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
469				union ctl_io *starting_io);
470static int ctl_check_blocked(struct ctl_lun *lun);
471static int ctl_scsiio_lun_check(struct ctl_lun *lun,
472				const struct ctl_cmd_entry *entry,
473				struct ctl_scsiio *ctsio);
474static void ctl_failover_lun(union ctl_io *io);
475static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
476			       struct ctl_scsiio *ctsio);
477static int ctl_scsiio(struct ctl_scsiio *ctsio);
478
479static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
480static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
481			    ctl_ua_type ua_type);
482static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
483			 ctl_ua_type ua_type);
484static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
485static int ctl_abort_task(union ctl_io *io);
486static int ctl_abort_task_set(union ctl_io *io);
487static int ctl_query_task(union ctl_io *io, int task_set);
488static int ctl_i_t_nexus_reset(union ctl_io *io);
489static int ctl_query_async_event(union ctl_io *io);
490static void ctl_run_task(union ctl_io *io);
491#ifdef CTL_IO_DELAY
492static void ctl_datamove_timer_wakeup(void *arg);
493static void ctl_done_timer_wakeup(void *arg);
494#endif /* CTL_IO_DELAY */
495
496static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
497static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
498static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
499static void ctl_datamove_remote_write(union ctl_io *io);
500static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
501static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
502static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
503static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
504				    ctl_ha_dt_cb callback);
505static void ctl_datamove_remote_read(union ctl_io *io);
506static void ctl_datamove_remote(union ctl_io *io);
507static void ctl_process_done(union ctl_io *io);
508static void ctl_lun_thread(void *arg);
509static void ctl_thresh_thread(void *arg);
510static void ctl_work_thread(void *arg);
511static void ctl_enqueue_incoming(union ctl_io *io);
512static void ctl_enqueue_rtr(union ctl_io *io);
513static void ctl_enqueue_done(union ctl_io *io);
514static void ctl_enqueue_isc(union ctl_io *io);
515static const struct ctl_cmd_entry *
516    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
517static const struct ctl_cmd_entry *
518    ctl_validate_command(struct ctl_scsiio *ctsio);
519static int ctl_cmd_applicable(uint8_t lun_type,
520    const struct ctl_cmd_entry *entry);
521
522static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
523static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
524static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
525static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
526
527/*
528 * Load the serialization table.  This isn't very pretty, but is probably
529 * the easiest way to do it.
530 */
531#include "ctl_ser_table.c"
532
533/*
534 * We only need to define open, close and ioctl routines for this driver.
535 */
536static struct cdevsw ctl_cdevsw = {
537	.d_version =	D_VERSION,
538	.d_flags =	0,
539	.d_open =	ctl_open,
540	.d_close =	ctl_close,
541	.d_ioctl =	ctl_ioctl,
542	.d_name =	"ctl",
543};
544
545
546MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
547
548static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
549
550static moduledata_t ctl_moduledata = {
551	"ctl",
552	ctl_module_event_handler,
553	NULL
554};
555
556DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
557MODULE_VERSION(ctl, 1);
558
559static struct ctl_frontend ha_frontend =
560{
561	.name = "ha",
562};
563
564static void
565ctl_ha_datamove(union ctl_io *io)
566{
567	struct ctl_lun *lun;
568	struct ctl_sg_entry *sgl;
569	union ctl_ha_msg msg;
570	uint32_t sg_entries_sent;
571	int do_sg_copy, i, j;
572
573	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
574	memset(&msg.dt, 0, sizeof(msg.dt));
575	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
576	msg.hdr.original_sc = io->io_hdr.original_sc;
577	msg.hdr.serializing_sc = io;
578	msg.hdr.nexus = io->io_hdr.nexus;
579	msg.hdr.status = io->io_hdr.status;
580	msg.dt.flags = io->io_hdr.flags;
581
582	/*
583	 * We convert everything into a S/G list here.  We can't
584	 * pass by reference, only by value between controllers.
585	 * So we can't pass a pointer to the S/G list, only as many
586	 * S/G entries as we can fit in here.  If it's possible for
587	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
588	 * then we need to break this up into multiple transfers.
589	 */
590	if (io->scsiio.kern_sg_entries == 0) {
591		msg.dt.kern_sg_entries = 1;
592#if 0
593		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
594			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
595		} else {
596			/* XXX KDM use busdma here! */
597			msg.dt.sg_list[0].addr =
598			    (void *)vtophys(io->scsiio.kern_data_ptr);
599		}
600#else
601		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
602		    ("HA does not support BUS_ADDR"));
603		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
604#endif
605		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
606		do_sg_copy = 0;
607	} else {
608		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
609		do_sg_copy = 1;
610	}
611
612	msg.dt.kern_data_len = io->scsiio.kern_data_len;
613	msg.dt.kern_total_len = io->scsiio.kern_total_len;
614	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
615	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
616	msg.dt.sg_sequence = 0;
617
618	/*
619	 * Loop until we've sent all of the S/G entries.  On the
620	 * other end, we'll recompose these S/G entries into one
621	 * contiguous list before processing.
622	 */
623	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
624	    msg.dt.sg_sequence++) {
625		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
626		    sizeof(msg.dt.sg_list[0])),
627		    msg.dt.kern_sg_entries - sg_entries_sent);
628		if (do_sg_copy != 0) {
629			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
630			for (i = sg_entries_sent, j = 0;
631			     i < msg.dt.cur_sg_entries; i++, j++) {
632#if 0
633				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
634					msg.dt.sg_list[j].addr = sgl[i].addr;
635				} else {
636					/* XXX KDM use busdma here! */
637					msg.dt.sg_list[j].addr =
638					    (void *)vtophys(sgl[i].addr);
639				}
640#else
641				KASSERT((io->io_hdr.flags &
642				    CTL_FLAG_BUS_ADDR) == 0,
643				    ("HA does not support BUS_ADDR"));
644				msg.dt.sg_list[j].addr = sgl[i].addr;
645#endif
646				msg.dt.sg_list[j].len = sgl[i].len;
647			}
648		}
649
650		sg_entries_sent += msg.dt.cur_sg_entries;
651		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
652		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
653		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
654		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
655		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
656			io->io_hdr.port_status = 31341;
657			io->scsiio.be_move_done(io);
658			return;
659		}
660		msg.dt.sent_sg_entries = sg_entries_sent;
661	}
662
663	/*
664	 * Officially handover the request from us to peer.
665	 * If failover has just happened, then we must return error.
666	 * If failover happen just after, then it is not our problem.
667	 */
668	if (lun)
669		mtx_lock(&lun->lun_lock);
670	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
671		if (lun)
672			mtx_unlock(&lun->lun_lock);
673		io->io_hdr.port_status = 31342;
674		io->scsiio.be_move_done(io);
675		return;
676	}
677	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
678	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
679	if (lun)
680		mtx_unlock(&lun->lun_lock);
681}
682
683static void
684ctl_ha_done(union ctl_io *io)
685{
686	union ctl_ha_msg msg;
687
688	if (io->io_hdr.io_type == CTL_IO_SCSI) {
689		memset(&msg, 0, sizeof(msg));
690		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
691		msg.hdr.original_sc = io->io_hdr.original_sc;
692		msg.hdr.nexus = io->io_hdr.nexus;
693		msg.hdr.status = io->io_hdr.status;
694		msg.scsi.scsi_status = io->scsiio.scsi_status;
695		msg.scsi.tag_num = io->scsiio.tag_num;
696		msg.scsi.tag_type = io->scsiio.tag_type;
697		msg.scsi.sense_len = io->scsiio.sense_len;
698		msg.scsi.sense_residual = io->scsiio.sense_residual;
699		msg.scsi.residual = io->scsiio.residual;
700		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
701		    io->scsiio.sense_len);
702		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
703		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
704		    msg.scsi.sense_len, M_WAITOK);
705	}
706	ctl_free_io(io);
707}
708
709static void
710ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
711			    union ctl_ha_msg *msg_info)
712{
713	struct ctl_scsiio *ctsio;
714
715	if (msg_info->hdr.original_sc == NULL) {
716		printf("%s: original_sc == NULL!\n", __func__);
717		/* XXX KDM now what? */
718		return;
719	}
720
721	ctsio = &msg_info->hdr.original_sc->scsiio;
722	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
723	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
724	ctsio->io_hdr.status = msg_info->hdr.status;
725	ctsio->scsi_status = msg_info->scsi.scsi_status;
726	ctsio->sense_len = msg_info->scsi.sense_len;
727	ctsio->sense_residual = msg_info->scsi.sense_residual;
728	ctsio->residual = msg_info->scsi.residual;
729	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
730	       msg_info->scsi.sense_len);
731	ctl_enqueue_isc((union ctl_io *)ctsio);
732}
733
734static void
735ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
736				union ctl_ha_msg *msg_info)
737{
738	struct ctl_scsiio *ctsio;
739
740	if (msg_info->hdr.serializing_sc == NULL) {
741		printf("%s: serializing_sc == NULL!\n", __func__);
742		/* XXX KDM now what? */
743		return;
744	}
745
746	ctsio = &msg_info->hdr.serializing_sc->scsiio;
747	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
748	ctl_enqueue_isc((union ctl_io *)ctsio);
749}
750
751void
752ctl_isc_announce_lun(struct ctl_lun *lun)
753{
754	struct ctl_softc *softc = lun->ctl_softc;
755	union ctl_ha_msg *msg;
756	struct ctl_ha_msg_lun_pr_key pr_key;
757	int i, k;
758
759	if (softc->ha_link != CTL_HA_LINK_ONLINE)
760		return;
761	mtx_lock(&lun->lun_lock);
762	i = sizeof(msg->lun);
763	if (lun->lun_devid)
764		i += lun->lun_devid->len;
765	i += sizeof(pr_key) * lun->pr_key_count;
766alloc:
767	mtx_unlock(&lun->lun_lock);
768	msg = malloc(i, M_CTL, M_WAITOK);
769	mtx_lock(&lun->lun_lock);
770	k = sizeof(msg->lun);
771	if (lun->lun_devid)
772		k += lun->lun_devid->len;
773	k += sizeof(pr_key) * lun->pr_key_count;
774	if (i < k) {
775		free(msg, M_CTL);
776		i = k;
777		goto alloc;
778	}
779	bzero(&msg->lun, sizeof(msg->lun));
780	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
781	msg->hdr.nexus.targ_lun = lun->lun;
782	msg->hdr.nexus.targ_mapped_lun = lun->lun;
783	msg->lun.flags = lun->flags;
784	msg->lun.pr_generation = lun->pr_generation;
785	msg->lun.pr_res_idx = lun->pr_res_idx;
786	msg->lun.pr_res_type = lun->pr_res_type;
787	msg->lun.pr_key_count = lun->pr_key_count;
788	i = 0;
789	if (lun->lun_devid) {
790		msg->lun.lun_devid_len = lun->lun_devid->len;
791		memcpy(&msg->lun.data[i], lun->lun_devid->data,
792		    msg->lun.lun_devid_len);
793		i += msg->lun.lun_devid_len;
794	}
795	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
796		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
797			continue;
798		pr_key.pr_iid = k;
799		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
800		i += sizeof(pr_key);
801	}
802	mtx_unlock(&lun->lun_lock);
803	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
804	    M_WAITOK);
805	free(msg, M_CTL);
806
807	if (lun->flags & CTL_LUN_PRIMARY_SC) {
808		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
809			ctl_isc_announce_mode(lun, -1,
810			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
811			    lun->mode_pages.index[i].subpage);
812		}
813	}
814}
815
816void
817ctl_isc_announce_port(struct ctl_port *port)
818{
819	struct ctl_softc *softc = port->ctl_softc;
820	union ctl_ha_msg *msg;
821	int i;
822
823	if (port->targ_port < softc->port_min ||
824	    port->targ_port >= softc->port_max ||
825	    softc->ha_link != CTL_HA_LINK_ONLINE)
826		return;
827	i = sizeof(msg->port) + strlen(port->port_name) + 1;
828	if (port->lun_map)
829		i += sizeof(uint32_t) * CTL_MAX_LUNS;
830	if (port->port_devid)
831		i += port->port_devid->len;
832	if (port->target_devid)
833		i += port->target_devid->len;
834	if (port->init_devid)
835		i += port->init_devid->len;
836	msg = malloc(i, M_CTL, M_WAITOK);
837	bzero(&msg->port, sizeof(msg->port));
838	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
839	msg->hdr.nexus.targ_port = port->targ_port;
840	msg->port.port_type = port->port_type;
841	msg->port.physical_port = port->physical_port;
842	msg->port.virtual_port = port->virtual_port;
843	msg->port.status = port->status;
844	i = 0;
845	msg->port.name_len = sprintf(&msg->port.data[i],
846	    "%d:%s", softc->ha_id, port->port_name) + 1;
847	i += msg->port.name_len;
848	if (port->lun_map) {
849		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
850		memcpy(&msg->port.data[i], port->lun_map,
851		    msg->port.lun_map_len);
852		i += msg->port.lun_map_len;
853	}
854	if (port->port_devid) {
855		msg->port.port_devid_len = port->port_devid->len;
856		memcpy(&msg->port.data[i], port->port_devid->data,
857		    msg->port.port_devid_len);
858		i += msg->port.port_devid_len;
859	}
860	if (port->target_devid) {
861		msg->port.target_devid_len = port->target_devid->len;
862		memcpy(&msg->port.data[i], port->target_devid->data,
863		    msg->port.target_devid_len);
864		i += msg->port.target_devid_len;
865	}
866	if (port->init_devid) {
867		msg->port.init_devid_len = port->init_devid->len;
868		memcpy(&msg->port.data[i], port->init_devid->data,
869		    msg->port.init_devid_len);
870		i += msg->port.init_devid_len;
871	}
872	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
873	    M_WAITOK);
874	free(msg, M_CTL);
875}
876
877void
878ctl_isc_announce_iid(struct ctl_port *port, int iid)
879{
880	struct ctl_softc *softc = port->ctl_softc;
881	union ctl_ha_msg *msg;
882	int i, l;
883
884	if (port->targ_port < softc->port_min ||
885	    port->targ_port >= softc->port_max ||
886	    softc->ha_link != CTL_HA_LINK_ONLINE)
887		return;
888	mtx_lock(&softc->ctl_lock);
889	i = sizeof(msg->iid);
890	l = 0;
891	if (port->wwpn_iid[iid].name)
892		l = strlen(port->wwpn_iid[iid].name) + 1;
893	i += l;
894	msg = malloc(i, M_CTL, M_NOWAIT);
895	if (msg == NULL) {
896		mtx_unlock(&softc->ctl_lock);
897		return;
898	}
899	bzero(&msg->iid, sizeof(msg->iid));
900	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
901	msg->hdr.nexus.targ_port = port->targ_port;
902	msg->hdr.nexus.initid = iid;
903	msg->iid.in_use = port->wwpn_iid[iid].in_use;
904	msg->iid.name_len = l;
905	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
906	if (port->wwpn_iid[iid].name)
907		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
908	mtx_unlock(&softc->ctl_lock);
909	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
910	free(msg, M_CTL);
911}
912
913void
914ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
915    uint8_t page, uint8_t subpage)
916{
917	struct ctl_softc *softc = lun->ctl_softc;
918	union ctl_ha_msg msg;
919	u_int i;
920
921	if (softc->ha_link != CTL_HA_LINK_ONLINE)
922		return;
923	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
924		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
925		    page && lun->mode_pages.index[i].subpage == subpage)
926			break;
927	}
928	if (i == CTL_NUM_MODE_PAGES)
929		return;
930
931	/* Don't try to replicate pages not present on this device. */
932	if (lun->mode_pages.index[i].page_data == NULL)
933		return;
934
935	bzero(&msg.mode, sizeof(msg.mode));
936	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
937	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
938	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
939	msg.hdr.nexus.targ_lun = lun->lun;
940	msg.hdr.nexus.targ_mapped_lun = lun->lun;
941	msg.mode.page_code = page;
942	msg.mode.subpage = subpage;
943	msg.mode.page_len = lun->mode_pages.index[i].page_len;
944	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
945	    msg.mode.page_len);
946	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
947	    M_WAITOK);
948}
949
950static void
951ctl_isc_ha_link_up(struct ctl_softc *softc)
952{
953	struct ctl_port *port;
954	struct ctl_lun *lun;
955	union ctl_ha_msg msg;
956	int i;
957
958	/* Announce this node parameters to peer for validation. */
959	msg.login.msg_type = CTL_MSG_LOGIN;
960	msg.login.version = CTL_HA_VERSION;
961	msg.login.ha_mode = softc->ha_mode;
962	msg.login.ha_id = softc->ha_id;
963	msg.login.max_luns = CTL_MAX_LUNS;
964	msg.login.max_ports = CTL_MAX_PORTS;
965	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
966	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
967	    M_WAITOK);
968
969	STAILQ_FOREACH(port, &softc->port_list, links) {
970		ctl_isc_announce_port(port);
971		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
972			if (port->wwpn_iid[i].in_use)
973				ctl_isc_announce_iid(port, i);
974		}
975	}
976	STAILQ_FOREACH(lun, &softc->lun_list, links)
977		ctl_isc_announce_lun(lun);
978}
979
980static void
981ctl_isc_ha_link_down(struct ctl_softc *softc)
982{
983	struct ctl_port *port;
984	struct ctl_lun *lun;
985	union ctl_io *io;
986	int i;
987
988	mtx_lock(&softc->ctl_lock);
989	STAILQ_FOREACH(lun, &softc->lun_list, links) {
990		mtx_lock(&lun->lun_lock);
991		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
992			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
993			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
994		}
995		mtx_unlock(&lun->lun_lock);
996
997		mtx_unlock(&softc->ctl_lock);
998		io = ctl_alloc_io(softc->othersc_pool);
999		mtx_lock(&softc->ctl_lock);
1000		ctl_zero_io(io);
1001		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1002		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1003		ctl_enqueue_isc(io);
1004	}
1005
1006	STAILQ_FOREACH(port, &softc->port_list, links) {
1007		if (port->targ_port >= softc->port_min &&
1008		    port->targ_port < softc->port_max)
1009			continue;
1010		port->status &= ~CTL_PORT_STATUS_ONLINE;
1011		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1012			port->wwpn_iid[i].in_use = 0;
1013			free(port->wwpn_iid[i].name, M_CTL);
1014			port->wwpn_iid[i].name = NULL;
1015		}
1016	}
1017	mtx_unlock(&softc->ctl_lock);
1018}
1019
1020static void
1021ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1022{
1023	struct ctl_lun *lun;
1024	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1025
1026	mtx_lock(&softc->ctl_lock);
1027	if (msg->hdr.nexus.targ_lun >= CTL_MAX_LUNS ||
1028	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1029		mtx_unlock(&softc->ctl_lock);
1030		return;
1031	}
1032	mtx_lock(&lun->lun_lock);
1033	mtx_unlock(&softc->ctl_lock);
1034	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1035		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1036	if (msg->ua.ua_all) {
1037		if (msg->ua.ua_set)
1038			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1039		else
1040			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1041	} else {
1042		if (msg->ua.ua_set)
1043			ctl_est_ua(lun, iid, msg->ua.ua_type);
1044		else
1045			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1046	}
1047	mtx_unlock(&lun->lun_lock);
1048}
1049
1050static void
1051ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1052{
1053	struct ctl_lun *lun;
1054	struct ctl_ha_msg_lun_pr_key pr_key;
1055	int i, k;
1056	ctl_lun_flags oflags;
1057	uint32_t targ_lun;
1058
1059	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1060	mtx_lock(&softc->ctl_lock);
1061	if (targ_lun >= CTL_MAX_LUNS ||
1062	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1063		mtx_unlock(&softc->ctl_lock);
1064		return;
1065	}
1066	mtx_lock(&lun->lun_lock);
1067	mtx_unlock(&softc->ctl_lock);
1068	if (lun->flags & CTL_LUN_DISABLED) {
1069		mtx_unlock(&lun->lun_lock);
1070		return;
1071	}
1072	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1073	if (msg->lun.lun_devid_len != i || (i > 0 &&
1074	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1075		mtx_unlock(&lun->lun_lock);
1076		printf("%s: Received conflicting HA LUN %d\n",
1077		    __func__, msg->hdr.nexus.targ_lun);
1078		return;
1079	} else {
1080		/* Record whether peer is primary. */
1081		oflags = lun->flags;
1082		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1083		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1084			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1085		else
1086			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1087		if (oflags != lun->flags)
1088			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1089
1090		/* If peer is primary and we are not -- use data */
1091		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1092		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1093			lun->pr_generation = msg->lun.pr_generation;
1094			lun->pr_res_idx = msg->lun.pr_res_idx;
1095			lun->pr_res_type = msg->lun.pr_res_type;
1096			lun->pr_key_count = msg->lun.pr_key_count;
1097			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1098				ctl_clr_prkey(lun, k);
1099			for (k = 0; k < msg->lun.pr_key_count; k++) {
1100				memcpy(&pr_key, &msg->lun.data[i],
1101				    sizeof(pr_key));
1102				ctl_alloc_prkey(lun, pr_key.pr_iid);
1103				ctl_set_prkey(lun, pr_key.pr_iid,
1104				    pr_key.pr_key);
1105				i += sizeof(pr_key);
1106			}
1107		}
1108
1109		mtx_unlock(&lun->lun_lock);
1110		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1111		    __func__, msg->hdr.nexus.targ_lun,
1112		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1113		    "primary" : "secondary"));
1114
1115		/* If we are primary but peer doesn't know -- notify */
1116		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1117		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1118			ctl_isc_announce_lun(lun);
1119	}
1120}
1121
1122static void
1123ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1124{
1125	struct ctl_port *port;
1126	struct ctl_lun *lun;
1127	int i, new;
1128
1129	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1130	if (port == NULL) {
1131		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1132		    msg->hdr.nexus.targ_port));
1133		new = 1;
1134		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1135		port->frontend = &ha_frontend;
1136		port->targ_port = msg->hdr.nexus.targ_port;
1137		port->fe_datamove = ctl_ha_datamove;
1138		port->fe_done = ctl_ha_done;
1139	} else if (port->frontend == &ha_frontend) {
1140		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1141		    msg->hdr.nexus.targ_port));
1142		new = 0;
1143	} else {
1144		printf("%s: Received conflicting HA port %d\n",
1145		    __func__, msg->hdr.nexus.targ_port);
1146		return;
1147	}
1148	port->port_type = msg->port.port_type;
1149	port->physical_port = msg->port.physical_port;
1150	port->virtual_port = msg->port.virtual_port;
1151	port->status = msg->port.status;
1152	i = 0;
1153	free(port->port_name, M_CTL);
1154	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1155	    M_CTL);
1156	i += msg->port.name_len;
1157	if (msg->port.lun_map_len != 0) {
1158		if (port->lun_map == NULL)
1159			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1160			    M_CTL, M_WAITOK);
1161		memcpy(port->lun_map, &msg->port.data[i],
1162		    sizeof(uint32_t) * CTL_MAX_LUNS);
1163		i += msg->port.lun_map_len;
1164	} else {
1165		free(port->lun_map, M_CTL);
1166		port->lun_map = NULL;
1167	}
1168	if (msg->port.port_devid_len != 0) {
1169		if (port->port_devid == NULL ||
1170		    port->port_devid->len != msg->port.port_devid_len) {
1171			free(port->port_devid, M_CTL);
1172			port->port_devid = malloc(sizeof(struct ctl_devid) +
1173			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1174		}
1175		memcpy(port->port_devid->data, &msg->port.data[i],
1176		    msg->port.port_devid_len);
1177		port->port_devid->len = msg->port.port_devid_len;
1178		i += msg->port.port_devid_len;
1179	} else {
1180		free(port->port_devid, M_CTL);
1181		port->port_devid = NULL;
1182	}
1183	if (msg->port.target_devid_len != 0) {
1184		if (port->target_devid == NULL ||
1185		    port->target_devid->len != msg->port.target_devid_len) {
1186			free(port->target_devid, M_CTL);
1187			port->target_devid = malloc(sizeof(struct ctl_devid) +
1188			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1189		}
1190		memcpy(port->target_devid->data, &msg->port.data[i],
1191		    msg->port.target_devid_len);
1192		port->target_devid->len = msg->port.target_devid_len;
1193		i += msg->port.target_devid_len;
1194	} else {
1195		free(port->target_devid, M_CTL);
1196		port->target_devid = NULL;
1197	}
1198	if (msg->port.init_devid_len != 0) {
1199		if (port->init_devid == NULL ||
1200		    port->init_devid->len != msg->port.init_devid_len) {
1201			free(port->init_devid, M_CTL);
1202			port->init_devid = malloc(sizeof(struct ctl_devid) +
1203			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1204		}
1205		memcpy(port->init_devid->data, &msg->port.data[i],
1206		    msg->port.init_devid_len);
1207		port->init_devid->len = msg->port.init_devid_len;
1208		i += msg->port.init_devid_len;
1209	} else {
1210		free(port->init_devid, M_CTL);
1211		port->init_devid = NULL;
1212	}
1213	if (new) {
1214		if (ctl_port_register(port) != 0) {
1215			printf("%s: ctl_port_register() failed with error\n",
1216			    __func__);
1217		}
1218	}
1219	mtx_lock(&softc->ctl_lock);
1220	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1221		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1222			continue;
1223		mtx_lock(&lun->lun_lock);
1224		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1225		mtx_unlock(&lun->lun_lock);
1226	}
1227	mtx_unlock(&softc->ctl_lock);
1228}
1229
1230static void
1231ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1232{
1233	struct ctl_port *port;
1234	int iid;
1235
1236	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1237	if (port == NULL) {
1238		printf("%s: Received IID for unknown port %d\n",
1239		    __func__, msg->hdr.nexus.targ_port);
1240		return;
1241	}
1242	iid = msg->hdr.nexus.initid;
1243	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1244	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1245	free(port->wwpn_iid[iid].name, M_CTL);
1246	if (msg->iid.name_len) {
1247		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1248		    msg->iid.name_len, M_CTL);
1249	} else
1250		port->wwpn_iid[iid].name = NULL;
1251}
1252
1253static void
1254ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1255{
1256
1257	if (msg->login.version != CTL_HA_VERSION) {
1258		printf("CTL HA peers have different versions %d != %d\n",
1259		    msg->login.version, CTL_HA_VERSION);
1260		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1261		return;
1262	}
1263	if (msg->login.ha_mode != softc->ha_mode) {
1264		printf("CTL HA peers have different ha_mode %d != %d\n",
1265		    msg->login.ha_mode, softc->ha_mode);
1266		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1267		return;
1268	}
1269	if (msg->login.ha_id == softc->ha_id) {
1270		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1271		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1272		return;
1273	}
1274	if (msg->login.max_luns != CTL_MAX_LUNS ||
1275	    msg->login.max_ports != CTL_MAX_PORTS ||
1276	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1277		printf("CTL HA peers have different limits\n");
1278		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1279		return;
1280	}
1281}
1282
1283static void
1284ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1285{
1286	struct ctl_lun *lun;
1287	u_int i;
1288	uint32_t initidx, targ_lun;
1289
1290	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1291	mtx_lock(&softc->ctl_lock);
1292	if (targ_lun >= CTL_MAX_LUNS ||
1293	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1294		mtx_unlock(&softc->ctl_lock);
1295		return;
1296	}
1297	mtx_lock(&lun->lun_lock);
1298	mtx_unlock(&softc->ctl_lock);
1299	if (lun->flags & CTL_LUN_DISABLED) {
1300		mtx_unlock(&lun->lun_lock);
1301		return;
1302	}
1303	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1304		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1305		    msg->mode.page_code &&
1306		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1307			break;
1308	}
1309	if (i == CTL_NUM_MODE_PAGES) {
1310		mtx_unlock(&lun->lun_lock);
1311		return;
1312	}
1313	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1314	    lun->mode_pages.index[i].page_len);
1315	initidx = ctl_get_initindex(&msg->hdr.nexus);
1316	if (initidx != -1)
1317		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1318	mtx_unlock(&lun->lun_lock);
1319}
1320
1321/*
1322 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1323 * subsystem come in here.
1324 */
1325static void
1326ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1327{
1328	struct ctl_softc *softc = control_softc;
1329	union ctl_io *io;
1330	struct ctl_prio *presio;
1331	ctl_ha_status isc_status;
1332
1333	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1334	if (event == CTL_HA_EVT_MSG_RECV) {
1335		union ctl_ha_msg *msg, msgbuf;
1336
1337		if (param > sizeof(msgbuf))
1338			msg = malloc(param, M_CTL, M_WAITOK);
1339		else
1340			msg = &msgbuf;
1341		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1342		    M_WAITOK);
1343		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1344			printf("%s: Error receiving message: %d\n",
1345			    __func__, isc_status);
1346			if (msg != &msgbuf)
1347				free(msg, M_CTL);
1348			return;
1349		}
1350
1351		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1352		switch (msg->hdr.msg_type) {
1353		case CTL_MSG_SERIALIZE:
1354			io = ctl_alloc_io(softc->othersc_pool);
1355			ctl_zero_io(io);
1356			// populate ctsio from msg
1357			io->io_hdr.io_type = CTL_IO_SCSI;
1358			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1359			io->io_hdr.original_sc = msg->hdr.original_sc;
1360			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1361					    CTL_FLAG_IO_ACTIVE;
1362			/*
1363			 * If we're in serialization-only mode, we don't
1364			 * want to go through full done processing.  Thus
1365			 * the COPY flag.
1366			 *
1367			 * XXX KDM add another flag that is more specific.
1368			 */
1369			if (softc->ha_mode != CTL_HA_MODE_XFER)
1370				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1371			io->io_hdr.nexus = msg->hdr.nexus;
1372#if 0
1373			printf("port %u, iid %u, lun %u\n",
1374			       io->io_hdr.nexus.targ_port,
1375			       io->io_hdr.nexus.initid,
1376			       io->io_hdr.nexus.targ_lun);
1377#endif
1378			io->scsiio.tag_num = msg->scsi.tag_num;
1379			io->scsiio.tag_type = msg->scsi.tag_type;
1380#ifdef CTL_TIME_IO
1381			io->io_hdr.start_time = time_uptime;
1382			getbinuptime(&io->io_hdr.start_bt);
1383#endif /* CTL_TIME_IO */
1384			io->scsiio.cdb_len = msg->scsi.cdb_len;
1385			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1386			       CTL_MAX_CDBLEN);
1387			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1388				const struct ctl_cmd_entry *entry;
1389
1390				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1391				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1392				io->io_hdr.flags |=
1393					entry->flags & CTL_FLAG_DATA_MASK;
1394			}
1395			ctl_enqueue_isc(io);
1396			break;
1397
1398		/* Performed on the Originating SC, XFER mode only */
1399		case CTL_MSG_DATAMOVE: {
1400			struct ctl_sg_entry *sgl;
1401			int i, j;
1402
1403			io = msg->hdr.original_sc;
1404			if (io == NULL) {
1405				printf("%s: original_sc == NULL!\n", __func__);
1406				/* XXX KDM do something here */
1407				break;
1408			}
1409			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1410			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1411			/*
1412			 * Keep track of this, we need to send it back over
1413			 * when the datamove is complete.
1414			 */
1415			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1416			if (msg->hdr.status == CTL_SUCCESS)
1417				io->io_hdr.status = msg->hdr.status;
1418
1419			if (msg->dt.sg_sequence == 0) {
1420#ifdef CTL_TIME_IO
1421				getbinuptime(&io->io_hdr.dma_start_bt);
1422#endif
1423				i = msg->dt.kern_sg_entries +
1424				    msg->dt.kern_data_len /
1425				    CTL_HA_DATAMOVE_SEGMENT + 1;
1426				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1427				    M_WAITOK | M_ZERO);
1428				io->io_hdr.remote_sglist = sgl;
1429				io->io_hdr.local_sglist =
1430				    &sgl[msg->dt.kern_sg_entries];
1431
1432				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1433
1434				io->scsiio.kern_sg_entries =
1435					msg->dt.kern_sg_entries;
1436				io->scsiio.rem_sg_entries =
1437					msg->dt.kern_sg_entries;
1438				io->scsiio.kern_data_len =
1439					msg->dt.kern_data_len;
1440				io->scsiio.kern_total_len =
1441					msg->dt.kern_total_len;
1442				io->scsiio.kern_data_resid =
1443					msg->dt.kern_data_resid;
1444				io->scsiio.kern_rel_offset =
1445					msg->dt.kern_rel_offset;
1446				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1447				io->io_hdr.flags |= msg->dt.flags &
1448				    CTL_FLAG_BUS_ADDR;
1449			} else
1450				sgl = (struct ctl_sg_entry *)
1451					io->scsiio.kern_data_ptr;
1452
1453			for (i = msg->dt.sent_sg_entries, j = 0;
1454			     i < (msg->dt.sent_sg_entries +
1455			     msg->dt.cur_sg_entries); i++, j++) {
1456				sgl[i].addr = msg->dt.sg_list[j].addr;
1457				sgl[i].len = msg->dt.sg_list[j].len;
1458
1459#if 0
1460				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1461				    __func__, sgl[i].addr, sgl[i].len, j, i);
1462#endif
1463			}
1464
1465			/*
1466			 * If this is the last piece of the I/O, we've got
1467			 * the full S/G list.  Queue processing in the thread.
1468			 * Otherwise wait for the next piece.
1469			 */
1470			if (msg->dt.sg_last != 0)
1471				ctl_enqueue_isc(io);
1472			break;
1473		}
1474		/* Performed on the Serializing (primary) SC, XFER mode only */
1475		case CTL_MSG_DATAMOVE_DONE: {
1476			if (msg->hdr.serializing_sc == NULL) {
1477				printf("%s: serializing_sc == NULL!\n",
1478				       __func__);
1479				/* XXX KDM now what? */
1480				break;
1481			}
1482			/*
1483			 * We grab the sense information here in case
1484			 * there was a failure, so we can return status
1485			 * back to the initiator.
1486			 */
1487			io = msg->hdr.serializing_sc;
1488			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1489			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1490			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1491			io->io_hdr.port_status = msg->scsi.fetd_status;
1492			io->scsiio.residual = msg->scsi.residual;
1493			if (msg->hdr.status != CTL_STATUS_NONE) {
1494				io->io_hdr.status = msg->hdr.status;
1495				io->scsiio.scsi_status = msg->scsi.scsi_status;
1496				io->scsiio.sense_len = msg->scsi.sense_len;
1497				io->scsiio.sense_residual =msg->scsi.sense_residual;
1498				memcpy(&io->scsiio.sense_data,
1499				    &msg->scsi.sense_data,
1500				    msg->scsi.sense_len);
1501				if (msg->hdr.status == CTL_SUCCESS)
1502					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1503			}
1504			ctl_enqueue_isc(io);
1505			break;
1506		}
1507
1508		/* Preformed on Originating SC, SER_ONLY mode */
1509		case CTL_MSG_R2R:
1510			io = msg->hdr.original_sc;
1511			if (io == NULL) {
1512				printf("%s: original_sc == NULL!\n",
1513				    __func__);
1514				break;
1515			}
1516			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1517			io->io_hdr.msg_type = CTL_MSG_R2R;
1518			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1519			ctl_enqueue_isc(io);
1520			break;
1521
1522		/*
1523		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1524		 * mode.
1525		 * Performed on the Originating (i.e. secondary) SC in XFER
1526		 * mode
1527		 */
1528		case CTL_MSG_FINISH_IO:
1529			if (softc->ha_mode == CTL_HA_MODE_XFER)
1530				ctl_isc_handler_finish_xfer(softc, msg);
1531			else
1532				ctl_isc_handler_finish_ser_only(softc, msg);
1533			break;
1534
1535		/* Preformed on Originating SC */
1536		case CTL_MSG_BAD_JUJU:
1537			io = msg->hdr.original_sc;
1538			if (io == NULL) {
1539				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1540				       __func__);
1541				break;
1542			}
1543			ctl_copy_sense_data(msg, io);
1544			/*
1545			 * IO should have already been cleaned up on other
1546			 * SC so clear this flag so we won't send a message
1547			 * back to finish the IO there.
1548			 */
1549			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1550			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1551
1552			/* io = msg->hdr.serializing_sc; */
1553			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1554			ctl_enqueue_isc(io);
1555			break;
1556
1557		/* Handle resets sent from the other side */
1558		case CTL_MSG_MANAGE_TASKS: {
1559			struct ctl_taskio *taskio;
1560			taskio = (struct ctl_taskio *)ctl_alloc_io(
1561			    softc->othersc_pool);
1562			ctl_zero_io((union ctl_io *)taskio);
1563			taskio->io_hdr.io_type = CTL_IO_TASK;
1564			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1565			taskio->io_hdr.nexus = msg->hdr.nexus;
1566			taskio->task_action = msg->task.task_action;
1567			taskio->tag_num = msg->task.tag_num;
1568			taskio->tag_type = msg->task.tag_type;
1569#ifdef CTL_TIME_IO
1570			taskio->io_hdr.start_time = time_uptime;
1571			getbinuptime(&taskio->io_hdr.start_bt);
1572#endif /* CTL_TIME_IO */
1573			ctl_run_task((union ctl_io *)taskio);
1574			break;
1575		}
1576		/* Persistent Reserve action which needs attention */
1577		case CTL_MSG_PERS_ACTION:
1578			presio = (struct ctl_prio *)ctl_alloc_io(
1579			    softc->othersc_pool);
1580			ctl_zero_io((union ctl_io *)presio);
1581			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1582			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1583			presio->io_hdr.nexus = msg->hdr.nexus;
1584			presio->pr_msg = msg->pr;
1585			ctl_enqueue_isc((union ctl_io *)presio);
1586			break;
1587		case CTL_MSG_UA:
1588			ctl_isc_ua(softc, msg, param);
1589			break;
1590		case CTL_MSG_PORT_SYNC:
1591			ctl_isc_port_sync(softc, msg, param);
1592			break;
1593		case CTL_MSG_LUN_SYNC:
1594			ctl_isc_lun_sync(softc, msg, param);
1595			break;
1596		case CTL_MSG_IID_SYNC:
1597			ctl_isc_iid_sync(softc, msg, param);
1598			break;
1599		case CTL_MSG_LOGIN:
1600			ctl_isc_login(softc, msg, param);
1601			break;
1602		case CTL_MSG_MODE_SYNC:
1603			ctl_isc_mode_sync(softc, msg, param);
1604			break;
1605		default:
1606			printf("Received HA message of unknown type %d\n",
1607			    msg->hdr.msg_type);
1608			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1609			break;
1610		}
1611		if (msg != &msgbuf)
1612			free(msg, M_CTL);
1613	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1614		printf("CTL: HA link status changed from %d to %d\n",
1615		    softc->ha_link, param);
1616		if (param == softc->ha_link)
1617			return;
1618		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1619			softc->ha_link = param;
1620			ctl_isc_ha_link_down(softc);
1621		} else {
1622			softc->ha_link = param;
1623			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1624				ctl_isc_ha_link_up(softc);
1625		}
1626		return;
1627	} else {
1628		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1629		return;
1630	}
1631}
1632
1633static void
1634ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1635{
1636
1637	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1638	    src->scsi.sense_len);
1639	dest->scsiio.scsi_status = src->scsi.scsi_status;
1640	dest->scsiio.sense_len = src->scsi.sense_len;
1641	dest->io_hdr.status = src->hdr.status;
1642}
1643
1644static void
1645ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1646{
1647
1648	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1649	    src->scsiio.sense_len);
1650	dest->scsi.scsi_status = src->scsiio.scsi_status;
1651	dest->scsi.sense_len = src->scsiio.sense_len;
1652	dest->hdr.status = src->io_hdr.status;
1653}
1654
1655void
1656ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1657{
1658	struct ctl_softc *softc = lun->ctl_softc;
1659	ctl_ua_type *pu;
1660
1661	if (initidx < softc->init_min || initidx >= softc->init_max)
1662		return;
1663	mtx_assert(&lun->lun_lock, MA_OWNED);
1664	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1665	if (pu == NULL)
1666		return;
1667	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1668}
1669
1670void
1671ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1672{
1673	int i;
1674
1675	mtx_assert(&lun->lun_lock, MA_OWNED);
1676	if (lun->pending_ua[port] == NULL)
1677		return;
1678	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1679		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1680			continue;
1681		lun->pending_ua[port][i] |= ua;
1682	}
1683}
1684
1685void
1686ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1687{
1688	struct ctl_softc *softc = lun->ctl_softc;
1689	int i;
1690
1691	mtx_assert(&lun->lun_lock, MA_OWNED);
1692	for (i = softc->port_min; i < softc->port_max; i++)
1693		ctl_est_ua_port(lun, i, except, ua);
1694}
1695
1696void
1697ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1698{
1699	struct ctl_softc *softc = lun->ctl_softc;
1700	ctl_ua_type *pu;
1701
1702	if (initidx < softc->init_min || initidx >= softc->init_max)
1703		return;
1704	mtx_assert(&lun->lun_lock, MA_OWNED);
1705	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1706	if (pu == NULL)
1707		return;
1708	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1709}
1710
1711void
1712ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1713{
1714	struct ctl_softc *softc = lun->ctl_softc;
1715	int i, j;
1716
1717	mtx_assert(&lun->lun_lock, MA_OWNED);
1718	for (i = softc->port_min; i < softc->port_max; i++) {
1719		if (lun->pending_ua[i] == NULL)
1720			continue;
1721		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1722			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1723				continue;
1724			lun->pending_ua[i][j] &= ~ua;
1725		}
1726	}
1727}
1728
1729void
1730ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1731    ctl_ua_type ua_type)
1732{
1733	struct ctl_lun *lun;
1734
1735	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1736	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1737		mtx_lock(&lun->lun_lock);
1738		ctl_clr_ua(lun, initidx, ua_type);
1739		mtx_unlock(&lun->lun_lock);
1740	}
1741}
1742
1743static int
1744ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1745{
1746	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1747	struct ctl_lun *lun;
1748	struct ctl_lun_req ireq;
1749	int error, value;
1750
1751	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1752	error = sysctl_handle_int(oidp, &value, 0, req);
1753	if ((error != 0) || (req->newptr == NULL))
1754		return (error);
1755
1756	mtx_lock(&softc->ctl_lock);
1757	if (value == 0)
1758		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1759	else
1760		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1761	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1762		mtx_unlock(&softc->ctl_lock);
1763		bzero(&ireq, sizeof(ireq));
1764		ireq.reqtype = CTL_LUNREQ_MODIFY;
1765		ireq.reqdata.modify.lun_id = lun->lun;
1766		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1767		    curthread);
1768		if (ireq.status != CTL_LUN_OK) {
1769			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1770			    __func__, ireq.status, ireq.error_str);
1771		}
1772		mtx_lock(&softc->ctl_lock);
1773	}
1774	mtx_unlock(&softc->ctl_lock);
1775	return (0);
1776}
1777
1778static int
1779ctl_init(void)
1780{
1781	struct make_dev_args args;
1782	struct ctl_softc *softc;
1783	void *other_pool;
1784	int i, error;
1785
1786	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1787			       M_WAITOK | M_ZERO);
1788
1789	make_dev_args_init(&args);
1790	args.mda_devsw = &ctl_cdevsw;
1791	args.mda_uid = UID_ROOT;
1792	args.mda_gid = GID_OPERATOR;
1793	args.mda_mode = 0600;
1794	args.mda_si_drv1 = softc;
1795	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1796	if (error != 0) {
1797		free(control_softc, M_DEVBUF);
1798		return (error);
1799	}
1800
1801	sysctl_ctx_init(&softc->sysctl_ctx);
1802	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1803		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1804		CTLFLAG_RD, 0, "CAM Target Layer");
1805
1806	if (softc->sysctl_tree == NULL) {
1807		printf("%s: unable to allocate sysctl tree\n", __func__);
1808		destroy_dev(softc->dev);
1809		free(control_softc, M_DEVBUF);
1810		control_softc = NULL;
1811		return (ENOMEM);
1812	}
1813
1814	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1815	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1816	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1817	softc->flags = 0;
1818
1819	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1820	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1821	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1822
1823	/*
1824	 * In Copan's HA scheme, the "master" and "slave" roles are
1825	 * figured out through the slot the controller is in.  Although it
1826	 * is an active/active system, someone has to be in charge.
1827	 */
1828	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1829	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1830	    "HA head ID (0 - no HA)");
1831	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1832		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1833		softc->is_single = 1;
1834		softc->port_cnt = CTL_MAX_PORTS;
1835		softc->port_min = 0;
1836	} else {
1837		softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1838		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1839	}
1840	softc->port_max = softc->port_min + softc->port_cnt;
1841	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1842	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1843
1844	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1845	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1846	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1847
1848	STAILQ_INIT(&softc->lun_list);
1849	STAILQ_INIT(&softc->pending_lun_queue);
1850	STAILQ_INIT(&softc->fe_list);
1851	STAILQ_INIT(&softc->port_list);
1852	STAILQ_INIT(&softc->be_list);
1853	ctl_tpc_init(softc);
1854
1855	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1856	                    &other_pool) != 0)
1857	{
1858		printf("ctl: can't allocate %d entry other SC pool, "
1859		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1860		return (ENOMEM);
1861	}
1862	softc->othersc_pool = other_pool;
1863
1864	if (worker_threads <= 0)
1865		worker_threads = max(1, mp_ncpus / 4);
1866	if (worker_threads > CTL_MAX_THREADS)
1867		worker_threads = CTL_MAX_THREADS;
1868
1869	for (i = 0; i < worker_threads; i++) {
1870		struct ctl_thread *thr = &softc->threads[i];
1871
1872		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1873		thr->ctl_softc = softc;
1874		STAILQ_INIT(&thr->incoming_queue);
1875		STAILQ_INIT(&thr->rtr_queue);
1876		STAILQ_INIT(&thr->done_queue);
1877		STAILQ_INIT(&thr->isc_queue);
1878
1879		error = kproc_kthread_add(ctl_work_thread, thr,
1880		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1881		if (error != 0) {
1882			printf("error creating CTL work thread!\n");
1883			ctl_pool_free(other_pool);
1884			return (error);
1885		}
1886	}
1887	error = kproc_kthread_add(ctl_lun_thread, softc,
1888	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1889	if (error != 0) {
1890		printf("error creating CTL lun thread!\n");
1891		ctl_pool_free(other_pool);
1892		return (error);
1893	}
1894	error = kproc_kthread_add(ctl_thresh_thread, softc,
1895	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1896	if (error != 0) {
1897		printf("error creating CTL threshold thread!\n");
1898		ctl_pool_free(other_pool);
1899		return (error);
1900	}
1901
1902	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1903	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1904	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1905
1906	if (softc->is_single == 0) {
1907		ctl_frontend_register(&ha_frontend);
1908		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1909			printf("ctl_init: ctl_ha_msg_init failed.\n");
1910			softc->is_single = 1;
1911		} else
1912		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1913		    != CTL_HA_STATUS_SUCCESS) {
1914			printf("ctl_init: ctl_ha_msg_register failed.\n");
1915			softc->is_single = 1;
1916		}
1917	}
1918	return (0);
1919}
1920
1921void
1922ctl_shutdown(void)
1923{
1924	struct ctl_softc *softc = control_softc;
1925	struct ctl_lun *lun, *next_lun;
1926
1927	if (softc->is_single == 0) {
1928		ctl_ha_msg_shutdown(softc);
1929		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1930		    != CTL_HA_STATUS_SUCCESS)
1931			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1932		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1933			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1934		ctl_frontend_deregister(&ha_frontend);
1935	}
1936
1937	mtx_lock(&softc->ctl_lock);
1938
1939	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1940		ctl_free_lun(lun);
1941
1942	mtx_unlock(&softc->ctl_lock);
1943
1944#if 0
1945	ctl_shutdown_thread(softc->work_thread);
1946	mtx_destroy(&softc->queue_lock);
1947#endif
1948
1949	ctl_tpc_shutdown(softc);
1950	uma_zdestroy(softc->io_zone);
1951	mtx_destroy(&softc->ctl_lock);
1952
1953	destroy_dev(softc->dev);
1954
1955	sysctl_ctx_free(&softc->sysctl_ctx);
1956
1957	free(control_softc, M_DEVBUF);
1958	control_softc = NULL;
1959}
1960
1961static int
1962ctl_module_event_handler(module_t mod, int what, void *arg)
1963{
1964
1965	switch (what) {
1966	case MOD_LOAD:
1967		return (ctl_init());
1968	case MOD_UNLOAD:
1969		return (EBUSY);
1970	default:
1971		return (EOPNOTSUPP);
1972	}
1973}
1974
1975/*
1976 * XXX KDM should we do some access checks here?  Bump a reference count to
1977 * prevent a CTL module from being unloaded while someone has it open?
1978 */
1979static int
1980ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1981{
1982	return (0);
1983}
1984
1985static int
1986ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1987{
1988	return (0);
1989}
1990
1991/*
1992 * Remove an initiator by port number and initiator ID.
1993 * Returns 0 for success, -1 for failure.
1994 */
1995int
1996ctl_remove_initiator(struct ctl_port *port, int iid)
1997{
1998	struct ctl_softc *softc = port->ctl_softc;
1999
2000	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2001
2002	if (iid > CTL_MAX_INIT_PER_PORT) {
2003		printf("%s: initiator ID %u > maximun %u!\n",
2004		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2005		return (-1);
2006	}
2007
2008	mtx_lock(&softc->ctl_lock);
2009	port->wwpn_iid[iid].in_use--;
2010	port->wwpn_iid[iid].last_use = time_uptime;
2011	mtx_unlock(&softc->ctl_lock);
2012	ctl_isc_announce_iid(port, iid);
2013
2014	return (0);
2015}
2016
2017/*
2018 * Add an initiator to the initiator map.
2019 * Returns iid for success, < 0 for failure.
2020 */
2021int
2022ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2023{
2024	struct ctl_softc *softc = port->ctl_softc;
2025	time_t best_time;
2026	int i, best;
2027
2028	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2029
2030	if (iid >= CTL_MAX_INIT_PER_PORT) {
2031		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2032		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2033		free(name, M_CTL);
2034		return (-1);
2035	}
2036
2037	mtx_lock(&softc->ctl_lock);
2038
2039	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2040		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2041			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2042				iid = i;
2043				break;
2044			}
2045			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2046			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2047				iid = i;
2048				break;
2049			}
2050		}
2051	}
2052
2053	if (iid < 0) {
2054		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2055			if (port->wwpn_iid[i].in_use == 0 &&
2056			    port->wwpn_iid[i].wwpn == 0 &&
2057			    port->wwpn_iid[i].name == NULL) {
2058				iid = i;
2059				break;
2060			}
2061		}
2062	}
2063
2064	if (iid < 0) {
2065		best = -1;
2066		best_time = INT32_MAX;
2067		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2068			if (port->wwpn_iid[i].in_use == 0) {
2069				if (port->wwpn_iid[i].last_use < best_time) {
2070					best = i;
2071					best_time = port->wwpn_iid[i].last_use;
2072				}
2073			}
2074		}
2075		iid = best;
2076	}
2077
2078	if (iid < 0) {
2079		mtx_unlock(&softc->ctl_lock);
2080		free(name, M_CTL);
2081		return (-2);
2082	}
2083
2084	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2085		/*
2086		 * This is not an error yet.
2087		 */
2088		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2089#if 0
2090			printf("%s: port %d iid %u WWPN %#jx arrived"
2091			    " again\n", __func__, port->targ_port,
2092			    iid, (uintmax_t)wwpn);
2093#endif
2094			goto take;
2095		}
2096		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2097		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2098#if 0
2099			printf("%s: port %d iid %u name '%s' arrived"
2100			    " again\n", __func__, port->targ_port,
2101			    iid, name);
2102#endif
2103			goto take;
2104		}
2105
2106		/*
2107		 * This is an error, but what do we do about it?  The
2108		 * driver is telling us we have a new WWPN for this
2109		 * initiator ID, so we pretty much need to use it.
2110		 */
2111		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2112		    " but WWPN %#jx '%s' is still at that address\n",
2113		    __func__, port->targ_port, iid, wwpn, name,
2114		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2115		    port->wwpn_iid[iid].name);
2116
2117		/*
2118		 * XXX KDM clear have_ca and ua_pending on each LUN for
2119		 * this initiator.
2120		 */
2121	}
2122take:
2123	free(port->wwpn_iid[iid].name, M_CTL);
2124	port->wwpn_iid[iid].name = name;
2125	port->wwpn_iid[iid].wwpn = wwpn;
2126	port->wwpn_iid[iid].in_use++;
2127	mtx_unlock(&softc->ctl_lock);
2128	ctl_isc_announce_iid(port, iid);
2129
2130	return (iid);
2131}
2132
2133static int
2134ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2135{
2136	int len;
2137
2138	switch (port->port_type) {
2139	case CTL_PORT_FC:
2140	{
2141		struct scsi_transportid_fcp *id =
2142		    (struct scsi_transportid_fcp *)buf;
2143		if (port->wwpn_iid[iid].wwpn == 0)
2144			return (0);
2145		memset(id, 0, sizeof(*id));
2146		id->format_protocol = SCSI_PROTO_FC;
2147		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2148		return (sizeof(*id));
2149	}
2150	case CTL_PORT_ISCSI:
2151	{
2152		struct scsi_transportid_iscsi_port *id =
2153		    (struct scsi_transportid_iscsi_port *)buf;
2154		if (port->wwpn_iid[iid].name == NULL)
2155			return (0);
2156		memset(id, 0, 256);
2157		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2158		    SCSI_PROTO_ISCSI;
2159		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2160		len = roundup2(min(len, 252), 4);
2161		scsi_ulto2b(len, id->additional_length);
2162		return (sizeof(*id) + len);
2163	}
2164	case CTL_PORT_SAS:
2165	{
2166		struct scsi_transportid_sas *id =
2167		    (struct scsi_transportid_sas *)buf;
2168		if (port->wwpn_iid[iid].wwpn == 0)
2169			return (0);
2170		memset(id, 0, sizeof(*id));
2171		id->format_protocol = SCSI_PROTO_SAS;
2172		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2173		return (sizeof(*id));
2174	}
2175	default:
2176	{
2177		struct scsi_transportid_spi *id =
2178		    (struct scsi_transportid_spi *)buf;
2179		memset(id, 0, sizeof(*id));
2180		id->format_protocol = SCSI_PROTO_SPI;
2181		scsi_ulto2b(iid, id->scsi_addr);
2182		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2183		return (sizeof(*id));
2184	}
2185	}
2186}
2187
2188/*
2189 * Serialize a command that went down the "wrong" side, and so was sent to
2190 * this controller for execution.  The logic is a little different than the
2191 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2192 * sent back to the other side, but in the success case, we execute the
2193 * command on this side (XFER mode) or tell the other side to execute it
2194 * (SER_ONLY mode).
2195 */
2196static void
2197ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2198{
2199	struct ctl_softc *softc = control_softc;
2200	union ctl_ha_msg msg_info;
2201	struct ctl_port *port;
2202	struct ctl_lun *lun;
2203	const struct ctl_cmd_entry *entry;
2204	uint32_t targ_lun;
2205
2206	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2207	mtx_lock(&softc->ctl_lock);
2208
2209	/* Make sure that we know about this port. */
2210	port = ctl_io_port(&ctsio->io_hdr);
2211	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2212		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2213					 /*retry_count*/ 1);
2214		goto badjuju;
2215	}
2216
2217	/* Make sure that we know about this LUN. */
2218	if (targ_lun >= CTL_MAX_LUNS ||
2219	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2220		mtx_unlock(&softc->ctl_lock);
2221
2222		/*
2223		 * The other node would not send this request to us unless
2224		 * received announce that we are primary node for this LUN.
2225		 * If this LUN does not exist now, it is probably result of
2226		 * a race, so respond to initiator in the most opaque way.
2227		 */
2228		ctl_set_busy(ctsio);
2229		goto badjuju;
2230	}
2231	mtx_lock(&lun->lun_lock);
2232	mtx_unlock(&softc->ctl_lock);
2233
2234	/*
2235	 * If the LUN is invalid, pretend that it doesn't exist.
2236	 * It will go away as soon as all pending I/Os completed.
2237	 */
2238	if (lun->flags & CTL_LUN_DISABLED) {
2239		mtx_unlock(&lun->lun_lock);
2240		ctl_set_busy(ctsio);
2241		goto badjuju;
2242	}
2243
2244	entry = ctl_get_cmd_entry(ctsio, NULL);
2245	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2246		mtx_unlock(&lun->lun_lock);
2247		goto badjuju;
2248	}
2249
2250	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2251	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2252
2253	/*
2254	 * Every I/O goes into the OOA queue for a
2255	 * particular LUN, and stays there until completion.
2256	 */
2257#ifdef CTL_TIME_IO
2258	if (TAILQ_EMPTY(&lun->ooa_queue))
2259		lun->idle_time += getsbinuptime() - lun->last_busy;
2260#endif
2261	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2262
2263	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2264		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2265		 ooa_links))) {
2266	case CTL_ACTION_BLOCK:
2267		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2268		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2269				  blocked_links);
2270		mtx_unlock(&lun->lun_lock);
2271		break;
2272	case CTL_ACTION_PASS:
2273	case CTL_ACTION_SKIP:
2274		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2275			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2276			ctl_enqueue_rtr((union ctl_io *)ctsio);
2277			mtx_unlock(&lun->lun_lock);
2278		} else {
2279			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2280			mtx_unlock(&lun->lun_lock);
2281
2282			/* send msg back to other side */
2283			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2284			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2285			msg_info.hdr.msg_type = CTL_MSG_R2R;
2286			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2287			    sizeof(msg_info.hdr), M_WAITOK);
2288		}
2289		break;
2290	case CTL_ACTION_OVERLAP:
2291		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2292		mtx_unlock(&lun->lun_lock);
2293		ctl_set_overlapped_cmd(ctsio);
2294		goto badjuju;
2295	case CTL_ACTION_OVERLAP_TAG:
2296		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2297		mtx_unlock(&lun->lun_lock);
2298		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2299		goto badjuju;
2300	case CTL_ACTION_ERROR:
2301	default:
2302		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2303		mtx_unlock(&lun->lun_lock);
2304
2305		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2306					 /*retry_count*/ 0);
2307badjuju:
2308		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2309		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2310		msg_info.hdr.serializing_sc = NULL;
2311		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2312		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2313		    sizeof(msg_info.scsi), M_WAITOK);
2314		ctl_free_io((union ctl_io *)ctsio);
2315		break;
2316	}
2317}
2318
2319/*
2320 * Returns 0 for success, errno for failure.
2321 */
2322static void
2323ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2324		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2325{
2326	union ctl_io *io;
2327
2328	mtx_lock(&lun->lun_lock);
2329	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2330	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2331	     ooa_links)) {
2332		struct ctl_ooa_entry *entry;
2333
2334		/*
2335		 * If we've got more than we can fit, just count the
2336		 * remaining entries.
2337		 */
2338		if (*cur_fill_num >= ooa_hdr->alloc_num)
2339			continue;
2340
2341		entry = &kern_entries[*cur_fill_num];
2342
2343		entry->tag_num = io->scsiio.tag_num;
2344		entry->lun_num = lun->lun;
2345#ifdef CTL_TIME_IO
2346		entry->start_bt = io->io_hdr.start_bt;
2347#endif
2348		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2349		entry->cdb_len = io->scsiio.cdb_len;
2350		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2351			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2352
2353		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2354			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2355
2356		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2357			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2358
2359		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2360			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2361
2362		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2363			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2364	}
2365	mtx_unlock(&lun->lun_lock);
2366}
2367
2368static void *
2369ctl_copyin_alloc(void *user_addr, unsigned int len, char *error_str,
2370		 size_t error_str_len)
2371{
2372	void *kptr;
2373
2374	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2375
2376	if (copyin(user_addr, kptr, len) != 0) {
2377		snprintf(error_str, error_str_len, "Error copying %d bytes "
2378			 "from user address %p to kernel address %p", len,
2379			 user_addr, kptr);
2380		free(kptr, M_CTL);
2381		return (NULL);
2382	}
2383
2384	return (kptr);
2385}
2386
2387static void
2388ctl_free_args(int num_args, struct ctl_be_arg *args)
2389{
2390	int i;
2391
2392	if (args == NULL)
2393		return;
2394
2395	for (i = 0; i < num_args; i++) {
2396		free(args[i].kname, M_CTL);
2397		free(args[i].kvalue, M_CTL);
2398	}
2399
2400	free(args, M_CTL);
2401}
2402
2403static struct ctl_be_arg *
2404ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2405		char *error_str, size_t error_str_len)
2406{
2407	struct ctl_be_arg *args;
2408	int i;
2409
2410	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2411				error_str, error_str_len);
2412
2413	if (args == NULL)
2414		goto bailout;
2415
2416	for (i = 0; i < num_args; i++) {
2417		args[i].kname = NULL;
2418		args[i].kvalue = NULL;
2419	}
2420
2421	for (i = 0; i < num_args; i++) {
2422		uint8_t *tmpptr;
2423
2424		if (args[i].namelen == 0) {
2425			snprintf(error_str, error_str_len, "Argument %d "
2426				 "name length is zero", i);
2427			goto bailout;
2428		}
2429
2430		args[i].kname = ctl_copyin_alloc(args[i].name,
2431			args[i].namelen, error_str, error_str_len);
2432		if (args[i].kname == NULL)
2433			goto bailout;
2434
2435		if (args[i].kname[args[i].namelen - 1] != '\0') {
2436			snprintf(error_str, error_str_len, "Argument %d "
2437				 "name is not NUL-terminated", i);
2438			goto bailout;
2439		}
2440
2441		if (args[i].flags & CTL_BEARG_RD) {
2442			if (args[i].vallen == 0) {
2443				snprintf(error_str, error_str_len, "Argument %d "
2444					 "value length is zero", i);
2445				goto bailout;
2446			}
2447
2448			tmpptr = ctl_copyin_alloc(args[i].value,
2449				args[i].vallen, error_str, error_str_len);
2450			if (tmpptr == NULL)
2451				goto bailout;
2452
2453			if ((args[i].flags & CTL_BEARG_ASCII)
2454			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2455				snprintf(error_str, error_str_len, "Argument "
2456				    "%d value is not NUL-terminated", i);
2457				free(tmpptr, M_CTL);
2458				goto bailout;
2459			}
2460			args[i].kvalue = tmpptr;
2461		} else {
2462			args[i].kvalue = malloc(args[i].vallen,
2463			    M_CTL, M_WAITOK | M_ZERO);
2464		}
2465	}
2466
2467	return (args);
2468bailout:
2469
2470	ctl_free_args(num_args, args);
2471
2472	return (NULL);
2473}
2474
2475static void
2476ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2477{
2478	int i;
2479
2480	for (i = 0; i < num_args; i++) {
2481		if (args[i].flags & CTL_BEARG_WR)
2482			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2483	}
2484}
2485
2486/*
2487 * Escape characters that are illegal or not recommended in XML.
2488 */
2489int
2490ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2491{
2492	char *end = str + size;
2493	int retval;
2494
2495	retval = 0;
2496
2497	for (; *str && str < end; str++) {
2498		switch (*str) {
2499		case '&':
2500			retval = sbuf_printf(sb, "&amp;");
2501			break;
2502		case '>':
2503			retval = sbuf_printf(sb, "&gt;");
2504			break;
2505		case '<':
2506			retval = sbuf_printf(sb, "&lt;");
2507			break;
2508		default:
2509			retval = sbuf_putc(sb, *str);
2510			break;
2511		}
2512
2513		if (retval != 0)
2514			break;
2515
2516	}
2517
2518	return (retval);
2519}
2520
2521static void
2522ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2523{
2524	struct scsi_vpd_id_descriptor *desc;
2525	int i;
2526
2527	if (id == NULL || id->len < 4)
2528		return;
2529	desc = (struct scsi_vpd_id_descriptor *)id->data;
2530	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2531	case SVPD_ID_TYPE_T10:
2532		sbuf_printf(sb, "t10.");
2533		break;
2534	case SVPD_ID_TYPE_EUI64:
2535		sbuf_printf(sb, "eui.");
2536		break;
2537	case SVPD_ID_TYPE_NAA:
2538		sbuf_printf(sb, "naa.");
2539		break;
2540	case SVPD_ID_TYPE_SCSI_NAME:
2541		break;
2542	}
2543	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2544	case SVPD_ID_CODESET_BINARY:
2545		for (i = 0; i < desc->length; i++)
2546			sbuf_printf(sb, "%02x", desc->identifier[i]);
2547		break;
2548	case SVPD_ID_CODESET_ASCII:
2549		sbuf_printf(sb, "%.*s", (int)desc->length,
2550		    (char *)desc->identifier);
2551		break;
2552	case SVPD_ID_CODESET_UTF8:
2553		sbuf_printf(sb, "%s", (char *)desc->identifier);
2554		break;
2555	}
2556}
2557
2558static int
2559ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2560	  struct thread *td)
2561{
2562	struct ctl_softc *softc = dev->si_drv1;
2563	struct ctl_lun *lun;
2564	int retval;
2565
2566	retval = 0;
2567
2568	switch (cmd) {
2569	case CTL_IO:
2570		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2571		break;
2572	case CTL_ENABLE_PORT:
2573	case CTL_DISABLE_PORT:
2574	case CTL_SET_PORT_WWNS: {
2575		struct ctl_port *port;
2576		struct ctl_port_entry *entry;
2577
2578		entry = (struct ctl_port_entry *)addr;
2579
2580		mtx_lock(&softc->ctl_lock);
2581		STAILQ_FOREACH(port, &softc->port_list, links) {
2582			int action, done;
2583
2584			if (port->targ_port < softc->port_min ||
2585			    port->targ_port >= softc->port_max)
2586				continue;
2587
2588			action = 0;
2589			done = 0;
2590			if ((entry->port_type == CTL_PORT_NONE)
2591			 && (entry->targ_port == port->targ_port)) {
2592				/*
2593				 * If the user only wants to enable or
2594				 * disable or set WWNs on a specific port,
2595				 * do the operation and we're done.
2596				 */
2597				action = 1;
2598				done = 1;
2599			} else if (entry->port_type & port->port_type) {
2600				/*
2601				 * Compare the user's type mask with the
2602				 * particular frontend type to see if we
2603				 * have a match.
2604				 */
2605				action = 1;
2606				done = 0;
2607
2608				/*
2609				 * Make sure the user isn't trying to set
2610				 * WWNs on multiple ports at the same time.
2611				 */
2612				if (cmd == CTL_SET_PORT_WWNS) {
2613					printf("%s: Can't set WWNs on "
2614					       "multiple ports\n", __func__);
2615					retval = EINVAL;
2616					break;
2617				}
2618			}
2619			if (action == 0)
2620				continue;
2621
2622			/*
2623			 * XXX KDM we have to drop the lock here, because
2624			 * the online/offline operations can potentially
2625			 * block.  We need to reference count the frontends
2626			 * so they can't go away,
2627			 */
2628			if (cmd == CTL_ENABLE_PORT) {
2629				mtx_unlock(&softc->ctl_lock);
2630				ctl_port_online(port);
2631				mtx_lock(&softc->ctl_lock);
2632			} else if (cmd == CTL_DISABLE_PORT) {
2633				mtx_unlock(&softc->ctl_lock);
2634				ctl_port_offline(port);
2635				mtx_lock(&softc->ctl_lock);
2636			} else if (cmd == CTL_SET_PORT_WWNS) {
2637				ctl_port_set_wwns(port,
2638				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2639				    1 : 0, entry->wwnn,
2640				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2641				    1 : 0, entry->wwpn);
2642			}
2643			if (done != 0)
2644				break;
2645		}
2646		mtx_unlock(&softc->ctl_lock);
2647		break;
2648	}
2649	case CTL_GET_OOA: {
2650		struct ctl_ooa *ooa_hdr;
2651		struct ctl_ooa_entry *entries;
2652		uint32_t cur_fill_num;
2653
2654		ooa_hdr = (struct ctl_ooa *)addr;
2655
2656		if ((ooa_hdr->alloc_len == 0)
2657		 || (ooa_hdr->alloc_num == 0)) {
2658			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2659			       "must be non-zero\n", __func__,
2660			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2661			retval = EINVAL;
2662			break;
2663		}
2664
2665		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2666		    sizeof(struct ctl_ooa_entry))) {
2667			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2668			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2669			       __func__, ooa_hdr->alloc_len,
2670			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2671			retval = EINVAL;
2672			break;
2673		}
2674
2675		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2676		if (entries == NULL) {
2677			printf("%s: could not allocate %d bytes for OOA "
2678			       "dump\n", __func__, ooa_hdr->alloc_len);
2679			retval = ENOMEM;
2680			break;
2681		}
2682
2683		mtx_lock(&softc->ctl_lock);
2684		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2685		    (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2686		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2687			mtx_unlock(&softc->ctl_lock);
2688			free(entries, M_CTL);
2689			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2690			       __func__, (uintmax_t)ooa_hdr->lun_num);
2691			retval = EINVAL;
2692			break;
2693		}
2694
2695		cur_fill_num = 0;
2696
2697		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2698			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2699				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2700				    ooa_hdr, entries);
2701			}
2702		} else {
2703			lun = softc->ctl_luns[ooa_hdr->lun_num];
2704			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2705			    entries);
2706		}
2707		mtx_unlock(&softc->ctl_lock);
2708
2709		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2710		ooa_hdr->fill_len = ooa_hdr->fill_num *
2711			sizeof(struct ctl_ooa_entry);
2712		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2713		if (retval != 0) {
2714			printf("%s: error copying out %d bytes for OOA dump\n",
2715			       __func__, ooa_hdr->fill_len);
2716		}
2717
2718		getbinuptime(&ooa_hdr->cur_bt);
2719
2720		if (cur_fill_num > ooa_hdr->alloc_num) {
2721			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2722			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2723		} else {
2724			ooa_hdr->dropped_num = 0;
2725			ooa_hdr->status = CTL_OOA_OK;
2726		}
2727
2728		free(entries, M_CTL);
2729		break;
2730	}
2731	case CTL_DELAY_IO: {
2732		struct ctl_io_delay_info *delay_info;
2733
2734		delay_info = (struct ctl_io_delay_info *)addr;
2735
2736#ifdef CTL_IO_DELAY
2737		mtx_lock(&softc->ctl_lock);
2738		if (delay_info->lun_id >= CTL_MAX_LUNS ||
2739		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2740			mtx_unlock(&softc->ctl_lock);
2741			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2742			break;
2743		}
2744		mtx_lock(&lun->lun_lock);
2745		mtx_unlock(&softc->ctl_lock);
2746		delay_info->status = CTL_DELAY_STATUS_OK;
2747		switch (delay_info->delay_type) {
2748		case CTL_DELAY_TYPE_CONT:
2749		case CTL_DELAY_TYPE_ONESHOT:
2750			break;
2751		default:
2752			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2753			break;
2754		}
2755		switch (delay_info->delay_loc) {
2756		case CTL_DELAY_LOC_DATAMOVE:
2757			lun->delay_info.datamove_type = delay_info->delay_type;
2758			lun->delay_info.datamove_delay = delay_info->delay_secs;
2759			break;
2760		case CTL_DELAY_LOC_DONE:
2761			lun->delay_info.done_type = delay_info->delay_type;
2762			lun->delay_info.done_delay = delay_info->delay_secs;
2763			break;
2764		default:
2765			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2766			break;
2767		}
2768		mtx_unlock(&lun->lun_lock);
2769#else
2770		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2771#endif /* CTL_IO_DELAY */
2772		break;
2773	}
2774	case CTL_GETSTATS: {
2775		struct ctl_stats *stats;
2776		int i;
2777
2778		stats = (struct ctl_stats *)addr;
2779
2780		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2781		     stats->alloc_len) {
2782			stats->status = CTL_SS_NEED_MORE_SPACE;
2783			stats->num_luns = softc->num_luns;
2784			break;
2785		}
2786		/*
2787		 * XXX KDM no locking here.  If the LUN list changes,
2788		 * things can blow up.
2789		 */
2790		i = 0;
2791		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2792			retval = copyout(&lun->stats, &stats->lun_stats[i++],
2793					 sizeof(lun->stats));
2794			if (retval != 0)
2795				break;
2796		}
2797		stats->num_luns = softc->num_luns;
2798		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2799				 softc->num_luns;
2800		stats->status = CTL_SS_OK;
2801#ifdef CTL_TIME_IO
2802		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2803#else
2804		stats->flags = CTL_STATS_FLAG_NONE;
2805#endif
2806		getnanouptime(&stats->timestamp);
2807		break;
2808	}
2809	case CTL_ERROR_INJECT: {
2810		struct ctl_error_desc *err_desc, *new_err_desc;
2811
2812		err_desc = (struct ctl_error_desc *)addr;
2813
2814		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2815				      M_WAITOK | M_ZERO);
2816		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2817
2818		mtx_lock(&softc->ctl_lock);
2819		if (err_desc->lun_id >= CTL_MAX_LUNS ||
2820		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2821			mtx_unlock(&softc->ctl_lock);
2822			free(new_err_desc, M_CTL);
2823			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2824			       __func__, (uintmax_t)err_desc->lun_id);
2825			retval = EINVAL;
2826			break;
2827		}
2828		mtx_lock(&lun->lun_lock);
2829		mtx_unlock(&softc->ctl_lock);
2830
2831		/*
2832		 * We could do some checking here to verify the validity
2833		 * of the request, but given the complexity of error
2834		 * injection requests, the checking logic would be fairly
2835		 * complex.
2836		 *
2837		 * For now, if the request is invalid, it just won't get
2838		 * executed and might get deleted.
2839		 */
2840		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2841
2842		/*
2843		 * XXX KDM check to make sure the serial number is unique,
2844		 * in case we somehow manage to wrap.  That shouldn't
2845		 * happen for a very long time, but it's the right thing to
2846		 * do.
2847		 */
2848		new_err_desc->serial = lun->error_serial;
2849		err_desc->serial = lun->error_serial;
2850		lun->error_serial++;
2851
2852		mtx_unlock(&lun->lun_lock);
2853		break;
2854	}
2855	case CTL_ERROR_INJECT_DELETE: {
2856		struct ctl_error_desc *delete_desc, *desc, *desc2;
2857		int delete_done;
2858
2859		delete_desc = (struct ctl_error_desc *)addr;
2860		delete_done = 0;
2861
2862		mtx_lock(&softc->ctl_lock);
2863		if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2864		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2865			mtx_unlock(&softc->ctl_lock);
2866			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2867			       __func__, (uintmax_t)delete_desc->lun_id);
2868			retval = EINVAL;
2869			break;
2870		}
2871		mtx_lock(&lun->lun_lock);
2872		mtx_unlock(&softc->ctl_lock);
2873		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2874			if (desc->serial != delete_desc->serial)
2875				continue;
2876
2877			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2878				      links);
2879			free(desc, M_CTL);
2880			delete_done = 1;
2881		}
2882		mtx_unlock(&lun->lun_lock);
2883		if (delete_done == 0) {
2884			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2885			       "error serial %ju on LUN %u\n", __func__,
2886			       delete_desc->serial, delete_desc->lun_id);
2887			retval = EINVAL;
2888			break;
2889		}
2890		break;
2891	}
2892	case CTL_DUMP_STRUCTS: {
2893		int j, k;
2894		struct ctl_port *port;
2895		struct ctl_frontend *fe;
2896
2897		mtx_lock(&softc->ctl_lock);
2898		printf("CTL Persistent Reservation information start:\n");
2899		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2900			mtx_lock(&lun->lun_lock);
2901			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2902				mtx_unlock(&lun->lun_lock);
2903				continue;
2904			}
2905
2906			for (j = 0; j < CTL_MAX_PORTS; j++) {
2907				if (lun->pr_keys[j] == NULL)
2908					continue;
2909				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2910					if (lun->pr_keys[j][k] == 0)
2911						continue;
2912					printf("  LUN %ju port %d iid %d key "
2913					       "%#jx\n", lun->lun, j, k,
2914					       (uintmax_t)lun->pr_keys[j][k]);
2915				}
2916			}
2917			mtx_unlock(&lun->lun_lock);
2918		}
2919		printf("CTL Persistent Reservation information end\n");
2920		printf("CTL Ports:\n");
2921		STAILQ_FOREACH(port, &softc->port_list, links) {
2922			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2923			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2924			       port->frontend->name, port->port_type,
2925			       port->physical_port, port->virtual_port,
2926			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2927			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2928				if (port->wwpn_iid[j].in_use == 0 &&
2929				    port->wwpn_iid[j].wwpn == 0 &&
2930				    port->wwpn_iid[j].name == NULL)
2931					continue;
2932
2933				printf("    iid %u use %d WWPN %#jx '%s'\n",
2934				    j, port->wwpn_iid[j].in_use,
2935				    (uintmax_t)port->wwpn_iid[j].wwpn,
2936				    port->wwpn_iid[j].name);
2937			}
2938		}
2939		printf("CTL Port information end\n");
2940		mtx_unlock(&softc->ctl_lock);
2941		/*
2942		 * XXX KDM calling this without a lock.  We'd likely want
2943		 * to drop the lock before calling the frontend's dump
2944		 * routine anyway.
2945		 */
2946		printf("CTL Frontends:\n");
2947		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2948			printf("  Frontend '%s'\n", fe->name);
2949			if (fe->fe_dump != NULL)
2950				fe->fe_dump();
2951		}
2952		printf("CTL Frontend information end\n");
2953		break;
2954	}
2955	case CTL_LUN_REQ: {
2956		struct ctl_lun_req *lun_req;
2957		struct ctl_backend_driver *backend;
2958
2959		lun_req = (struct ctl_lun_req *)addr;
2960
2961		backend = ctl_backend_find(lun_req->backend);
2962		if (backend == NULL) {
2963			lun_req->status = CTL_LUN_ERROR;
2964			snprintf(lun_req->error_str,
2965				 sizeof(lun_req->error_str),
2966				 "Backend \"%s\" not found.",
2967				 lun_req->backend);
2968			break;
2969		}
2970		if (lun_req->num_be_args > 0) {
2971			lun_req->kern_be_args = ctl_copyin_args(
2972				lun_req->num_be_args,
2973				lun_req->be_args,
2974				lun_req->error_str,
2975				sizeof(lun_req->error_str));
2976			if (lun_req->kern_be_args == NULL) {
2977				lun_req->status = CTL_LUN_ERROR;
2978				break;
2979			}
2980		}
2981
2982		retval = backend->ioctl(dev, cmd, addr, flag, td);
2983
2984		if (lun_req->num_be_args > 0) {
2985			ctl_copyout_args(lun_req->num_be_args,
2986				      lun_req->kern_be_args);
2987			ctl_free_args(lun_req->num_be_args,
2988				      lun_req->kern_be_args);
2989		}
2990		break;
2991	}
2992	case CTL_LUN_LIST: {
2993		struct sbuf *sb;
2994		struct ctl_lun_list *list;
2995		struct ctl_option *opt;
2996
2997		list = (struct ctl_lun_list *)addr;
2998
2999		/*
3000		 * Allocate a fixed length sbuf here, based on the length
3001		 * of the user's buffer.  We could allocate an auto-extending
3002		 * buffer, and then tell the user how much larger our
3003		 * amount of data is than his buffer, but that presents
3004		 * some problems:
3005		 *
3006		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3007		 *     we can't hold a lock while calling them with an
3008		 *     auto-extending buffer.
3009 		 *
3010		 * 2.  There is not currently a LUN reference counting
3011		 *     mechanism, outside of outstanding transactions on
3012		 *     the LUN's OOA queue.  So a LUN could go away on us
3013		 *     while we're getting the LUN number, backend-specific
3014		 *     information, etc.  Thus, given the way things
3015		 *     currently work, we need to hold the CTL lock while
3016		 *     grabbing LUN information.
3017		 *
3018		 * So, from the user's standpoint, the best thing to do is
3019		 * allocate what he thinks is a reasonable buffer length,
3020		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3021		 * double the buffer length and try again.  (And repeat
3022		 * that until he succeeds.)
3023		 */
3024		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3025		if (sb == NULL) {
3026			list->status = CTL_LUN_LIST_ERROR;
3027			snprintf(list->error_str, sizeof(list->error_str),
3028				 "Unable to allocate %d bytes for LUN list",
3029				 list->alloc_len);
3030			break;
3031		}
3032
3033		sbuf_printf(sb, "<ctllunlist>\n");
3034
3035		mtx_lock(&softc->ctl_lock);
3036		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3037			mtx_lock(&lun->lun_lock);
3038			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3039					     (uintmax_t)lun->lun);
3040
3041			/*
3042			 * Bail out as soon as we see that we've overfilled
3043			 * the buffer.
3044			 */
3045			if (retval != 0)
3046				break;
3047
3048			retval = sbuf_printf(sb, "\t<backend_type>%s"
3049					     "</backend_type>\n",
3050					     (lun->backend == NULL) ?  "none" :
3051					     lun->backend->name);
3052
3053			if (retval != 0)
3054				break;
3055
3056			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3057					     lun->be_lun->lun_type);
3058
3059			if (retval != 0)
3060				break;
3061
3062			if (lun->backend == NULL) {
3063				retval = sbuf_printf(sb, "</lun>\n");
3064				if (retval != 0)
3065					break;
3066				continue;
3067			}
3068
3069			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3070					     (lun->be_lun->maxlba > 0) ?
3071					     lun->be_lun->maxlba + 1 : 0);
3072
3073			if (retval != 0)
3074				break;
3075
3076			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3077					     lun->be_lun->blocksize);
3078
3079			if (retval != 0)
3080				break;
3081
3082			retval = sbuf_printf(sb, "\t<serial_number>");
3083
3084			if (retval != 0)
3085				break;
3086
3087			retval = ctl_sbuf_printf_esc(sb,
3088			    lun->be_lun->serial_num,
3089			    sizeof(lun->be_lun->serial_num));
3090
3091			if (retval != 0)
3092				break;
3093
3094			retval = sbuf_printf(sb, "</serial_number>\n");
3095
3096			if (retval != 0)
3097				break;
3098
3099			retval = sbuf_printf(sb, "\t<device_id>");
3100
3101			if (retval != 0)
3102				break;
3103
3104			retval = ctl_sbuf_printf_esc(sb,
3105			    lun->be_lun->device_id,
3106			    sizeof(lun->be_lun->device_id));
3107
3108			if (retval != 0)
3109				break;
3110
3111			retval = sbuf_printf(sb, "</device_id>\n");
3112
3113			if (retval != 0)
3114				break;
3115
3116			if (lun->backend->lun_info != NULL) {
3117				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3118				if (retval != 0)
3119					break;
3120			}
3121			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3122				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3123				    opt->name, opt->value, opt->name);
3124				if (retval != 0)
3125					break;
3126			}
3127
3128			retval = sbuf_printf(sb, "</lun>\n");
3129
3130			if (retval != 0)
3131				break;
3132			mtx_unlock(&lun->lun_lock);
3133		}
3134		if (lun != NULL)
3135			mtx_unlock(&lun->lun_lock);
3136		mtx_unlock(&softc->ctl_lock);
3137
3138		if ((retval != 0)
3139		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3140			retval = 0;
3141			sbuf_delete(sb);
3142			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3143			snprintf(list->error_str, sizeof(list->error_str),
3144				 "Out of space, %d bytes is too small",
3145				 list->alloc_len);
3146			break;
3147		}
3148
3149		sbuf_finish(sb);
3150
3151		retval = copyout(sbuf_data(sb), list->lun_xml,
3152				 sbuf_len(sb) + 1);
3153
3154		list->fill_len = sbuf_len(sb) + 1;
3155		list->status = CTL_LUN_LIST_OK;
3156		sbuf_delete(sb);
3157		break;
3158	}
3159	case CTL_ISCSI: {
3160		struct ctl_iscsi *ci;
3161		struct ctl_frontend *fe;
3162
3163		ci = (struct ctl_iscsi *)addr;
3164
3165		fe = ctl_frontend_find("iscsi");
3166		if (fe == NULL) {
3167			ci->status = CTL_ISCSI_ERROR;
3168			snprintf(ci->error_str, sizeof(ci->error_str),
3169			    "Frontend \"iscsi\" not found.");
3170			break;
3171		}
3172
3173		retval = fe->ioctl(dev, cmd, addr, flag, td);
3174		break;
3175	}
3176	case CTL_PORT_REQ: {
3177		struct ctl_req *req;
3178		struct ctl_frontend *fe;
3179
3180		req = (struct ctl_req *)addr;
3181
3182		fe = ctl_frontend_find(req->driver);
3183		if (fe == NULL) {
3184			req->status = CTL_LUN_ERROR;
3185			snprintf(req->error_str, sizeof(req->error_str),
3186			    "Frontend \"%s\" not found.", req->driver);
3187			break;
3188		}
3189		if (req->num_args > 0) {
3190			req->kern_args = ctl_copyin_args(req->num_args,
3191			    req->args, req->error_str, sizeof(req->error_str));
3192			if (req->kern_args == NULL) {
3193				req->status = CTL_LUN_ERROR;
3194				break;
3195			}
3196		}
3197
3198		if (fe->ioctl)
3199			retval = fe->ioctl(dev, cmd, addr, flag, td);
3200		else
3201			retval = ENODEV;
3202
3203		if (req->num_args > 0) {
3204			ctl_copyout_args(req->num_args, req->kern_args);
3205			ctl_free_args(req->num_args, req->kern_args);
3206		}
3207		break;
3208	}
3209	case CTL_PORT_LIST: {
3210		struct sbuf *sb;
3211		struct ctl_port *port;
3212		struct ctl_lun_list *list;
3213		struct ctl_option *opt;
3214		int j;
3215		uint32_t plun;
3216
3217		list = (struct ctl_lun_list *)addr;
3218
3219		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3220		if (sb == NULL) {
3221			list->status = CTL_LUN_LIST_ERROR;
3222			snprintf(list->error_str, sizeof(list->error_str),
3223				 "Unable to allocate %d bytes for LUN list",
3224				 list->alloc_len);
3225			break;
3226		}
3227
3228		sbuf_printf(sb, "<ctlportlist>\n");
3229
3230		mtx_lock(&softc->ctl_lock);
3231		STAILQ_FOREACH(port, &softc->port_list, links) {
3232			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3233					     (uintmax_t)port->targ_port);
3234
3235			/*
3236			 * Bail out as soon as we see that we've overfilled
3237			 * the buffer.
3238			 */
3239			if (retval != 0)
3240				break;
3241
3242			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3243			    "</frontend_type>\n", port->frontend->name);
3244			if (retval != 0)
3245				break;
3246
3247			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3248					     port->port_type);
3249			if (retval != 0)
3250				break;
3251
3252			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3253			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3254			if (retval != 0)
3255				break;
3256
3257			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3258			    port->port_name);
3259			if (retval != 0)
3260				break;
3261
3262			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3263			    port->physical_port);
3264			if (retval != 0)
3265				break;
3266
3267			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3268			    port->virtual_port);
3269			if (retval != 0)
3270				break;
3271
3272			if (port->target_devid != NULL) {
3273				sbuf_printf(sb, "\t<target>");
3274				ctl_id_sbuf(port->target_devid, sb);
3275				sbuf_printf(sb, "</target>\n");
3276			}
3277
3278			if (port->port_devid != NULL) {
3279				sbuf_printf(sb, "\t<port>");
3280				ctl_id_sbuf(port->port_devid, sb);
3281				sbuf_printf(sb, "</port>\n");
3282			}
3283
3284			if (port->port_info != NULL) {
3285				retval = port->port_info(port->onoff_arg, sb);
3286				if (retval != 0)
3287					break;
3288			}
3289			STAILQ_FOREACH(opt, &port->options, links) {
3290				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3291				    opt->name, opt->value, opt->name);
3292				if (retval != 0)
3293					break;
3294			}
3295
3296			if (port->lun_map != NULL) {
3297				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3298				for (j = 0; j < CTL_MAX_LUNS; j++) {
3299					plun = ctl_lun_map_from_port(port, j);
3300					if (plun == UINT32_MAX)
3301						continue;
3302					sbuf_printf(sb,
3303					    "\t<lun id=\"%u\">%u</lun>\n",
3304					    j, plun);
3305				}
3306			}
3307
3308			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3309				if (port->wwpn_iid[j].in_use == 0 ||
3310				    (port->wwpn_iid[j].wwpn == 0 &&
3311				     port->wwpn_iid[j].name == NULL))
3312					continue;
3313
3314				if (port->wwpn_iid[j].name != NULL)
3315					retval = sbuf_printf(sb,
3316					    "\t<initiator id=\"%u\">%s</initiator>\n",
3317					    j, port->wwpn_iid[j].name);
3318				else
3319					retval = sbuf_printf(sb,
3320					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3321					    j, port->wwpn_iid[j].wwpn);
3322				if (retval != 0)
3323					break;
3324			}
3325			if (retval != 0)
3326				break;
3327
3328			retval = sbuf_printf(sb, "</targ_port>\n");
3329			if (retval != 0)
3330				break;
3331		}
3332		mtx_unlock(&softc->ctl_lock);
3333
3334		if ((retval != 0)
3335		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3336			retval = 0;
3337			sbuf_delete(sb);
3338			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3339			snprintf(list->error_str, sizeof(list->error_str),
3340				 "Out of space, %d bytes is too small",
3341				 list->alloc_len);
3342			break;
3343		}
3344
3345		sbuf_finish(sb);
3346
3347		retval = copyout(sbuf_data(sb), list->lun_xml,
3348				 sbuf_len(sb) + 1);
3349
3350		list->fill_len = sbuf_len(sb) + 1;
3351		list->status = CTL_LUN_LIST_OK;
3352		sbuf_delete(sb);
3353		break;
3354	}
3355	case CTL_LUN_MAP: {
3356		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3357		struct ctl_port *port;
3358
3359		mtx_lock(&softc->ctl_lock);
3360		if (lm->port < softc->port_min ||
3361		    lm->port >= softc->port_max ||
3362		    (port = softc->ctl_ports[lm->port]) == NULL) {
3363			mtx_unlock(&softc->ctl_lock);
3364			return (ENXIO);
3365		}
3366		if (port->status & CTL_PORT_STATUS_ONLINE) {
3367			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3368				if (ctl_lun_map_to_port(port, lun->lun) ==
3369				    UINT32_MAX)
3370					continue;
3371				mtx_lock(&lun->lun_lock);
3372				ctl_est_ua_port(lun, lm->port, -1,
3373				    CTL_UA_LUN_CHANGE);
3374				mtx_unlock(&lun->lun_lock);
3375			}
3376		}
3377		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3378		if (lm->plun < CTL_MAX_LUNS) {
3379			if (lm->lun == UINT32_MAX)
3380				retval = ctl_lun_map_unset(port, lm->plun);
3381			else if (lm->lun < CTL_MAX_LUNS &&
3382			    softc->ctl_luns[lm->lun] != NULL)
3383				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3384			else
3385				return (ENXIO);
3386		} else if (lm->plun == UINT32_MAX) {
3387			if (lm->lun == UINT32_MAX)
3388				retval = ctl_lun_map_deinit(port);
3389			else
3390				retval = ctl_lun_map_init(port);
3391		} else
3392			return (ENXIO);
3393		if (port->status & CTL_PORT_STATUS_ONLINE)
3394			ctl_isc_announce_port(port);
3395		break;
3396	}
3397	default: {
3398		/* XXX KDM should we fix this? */
3399#if 0
3400		struct ctl_backend_driver *backend;
3401		unsigned int type;
3402		int found;
3403
3404		found = 0;
3405
3406		/*
3407		 * We encode the backend type as the ioctl type for backend
3408		 * ioctls.  So parse it out here, and then search for a
3409		 * backend of this type.
3410		 */
3411		type = _IOC_TYPE(cmd);
3412
3413		STAILQ_FOREACH(backend, &softc->be_list, links) {
3414			if (backend->type == type) {
3415				found = 1;
3416				break;
3417			}
3418		}
3419		if (found == 0) {
3420			printf("ctl: unknown ioctl command %#lx or backend "
3421			       "%d\n", cmd, type);
3422			retval = EINVAL;
3423			break;
3424		}
3425		retval = backend->ioctl(dev, cmd, addr, flag, td);
3426#endif
3427		retval = ENOTTY;
3428		break;
3429	}
3430	}
3431	return (retval);
3432}
3433
3434uint32_t
3435ctl_get_initindex(struct ctl_nexus *nexus)
3436{
3437	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3438}
3439
3440int
3441ctl_lun_map_init(struct ctl_port *port)
3442{
3443	struct ctl_softc *softc = port->ctl_softc;
3444	struct ctl_lun *lun;
3445	uint32_t i;
3446
3447	if (port->lun_map == NULL)
3448		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3449		    M_CTL, M_NOWAIT);
3450	if (port->lun_map == NULL)
3451		return (ENOMEM);
3452	for (i = 0; i < CTL_MAX_LUNS; i++)
3453		port->lun_map[i] = UINT32_MAX;
3454	if (port->status & CTL_PORT_STATUS_ONLINE) {
3455		if (port->lun_disable != NULL) {
3456			STAILQ_FOREACH(lun, &softc->lun_list, links)
3457				port->lun_disable(port->targ_lun_arg, lun->lun);
3458		}
3459		ctl_isc_announce_port(port);
3460	}
3461	return (0);
3462}
3463
3464int
3465ctl_lun_map_deinit(struct ctl_port *port)
3466{
3467	struct ctl_softc *softc = port->ctl_softc;
3468	struct ctl_lun *lun;
3469
3470	if (port->lun_map == NULL)
3471		return (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	old = port->lun_map[plun];
3496	port->lun_map[plun] = glun;
3497	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3498		if (port->lun_enable != NULL)
3499			port->lun_enable(port->targ_lun_arg, plun);
3500		ctl_isc_announce_port(port);
3501	}
3502	return (0);
3503}
3504
3505int
3506ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3507{
3508	uint32_t old;
3509
3510	if (port->lun_map == NULL)
3511		return (0);
3512	old = port->lun_map[plun];
3513	port->lun_map[plun] = UINT32_MAX;
3514	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3515		if (port->lun_disable != NULL)
3516			port->lun_disable(port->targ_lun_arg, plun);
3517		ctl_isc_announce_port(port);
3518	}
3519	return (0);
3520}
3521
3522uint32_t
3523ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3524{
3525
3526	if (port == NULL)
3527		return (UINT32_MAX);
3528	if (port->lun_map == NULL || lun_id == UINT32_MAX)
3529		return (lun_id);
3530	return (port->lun_map[lun_id]);
3531}
3532
3533uint32_t
3534ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3535{
3536	uint32_t i;
3537
3538	if (port == NULL)
3539		return (UINT32_MAX);
3540	if (port->lun_map == NULL)
3541		return (lun_id);
3542	for (i = 0; i < CTL_MAX_LUNS; i++) {
3543		if (port->lun_map[i] == lun_id)
3544			return (i);
3545	}
3546	return (UINT32_MAX);
3547}
3548
3549uint32_t
3550ctl_decode_lun(uint64_t encoded)
3551{
3552	uint8_t lun[8];
3553	uint32_t result = 0xffffffff;
3554
3555	be64enc(lun, encoded);
3556	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3557	case RPL_LUNDATA_ATYP_PERIPH:
3558		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3559		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3560			result = lun[1];
3561		break;
3562	case RPL_LUNDATA_ATYP_FLAT:
3563		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3564		    lun[6] == 0 && lun[7] == 0)
3565			result = ((lun[0] & 0x3f) << 8) + lun[1];
3566		break;
3567	case RPL_LUNDATA_ATYP_EXTLUN:
3568		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3569		case 0x02:
3570			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3571			case 0x00:
3572				result = lun[1];
3573				break;
3574			case 0x10:
3575				result = (lun[1] << 16) + (lun[2] << 8) +
3576				    lun[3];
3577				break;
3578			case 0x20:
3579				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3580					result = (lun[2] << 24) +
3581					    (lun[3] << 16) + (lun[4] << 8) +
3582					    lun[5];
3583				break;
3584			}
3585			break;
3586		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3587			result = 0xffffffff;
3588			break;
3589		}
3590		break;
3591	}
3592	return (result);
3593}
3594
3595uint64_t
3596ctl_encode_lun(uint32_t decoded)
3597{
3598	uint64_t l = decoded;
3599
3600	if (l <= 0xff)
3601		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3602	if (l <= 0x3fff)
3603		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3604	if (l <= 0xffffff)
3605		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3606		    (l << 32));
3607	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3608}
3609
3610static struct ctl_port *
3611ctl_io_port(struct ctl_io_hdr *io_hdr)
3612{
3613
3614	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3615}
3616
3617int
3618ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3619{
3620	int i;
3621
3622	for (i = first; i < last; i++) {
3623		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3624			return (i);
3625	}
3626	return (-1);
3627}
3628
3629int
3630ctl_set_mask(uint32_t *mask, uint32_t bit)
3631{
3632	uint32_t chunk, piece;
3633
3634	chunk = bit >> 5;
3635	piece = bit % (sizeof(uint32_t) * 8);
3636
3637	if ((mask[chunk] & (1 << piece)) != 0)
3638		return (-1);
3639	else
3640		mask[chunk] |= (1 << piece);
3641
3642	return (0);
3643}
3644
3645int
3646ctl_clear_mask(uint32_t *mask, uint32_t bit)
3647{
3648	uint32_t chunk, piece;
3649
3650	chunk = bit >> 5;
3651	piece = bit % (sizeof(uint32_t) * 8);
3652
3653	if ((mask[chunk] & (1 << piece)) == 0)
3654		return (-1);
3655	else
3656		mask[chunk] &= ~(1 << piece);
3657
3658	return (0);
3659}
3660
3661int
3662ctl_is_set(uint32_t *mask, uint32_t bit)
3663{
3664	uint32_t chunk, piece;
3665
3666	chunk = bit >> 5;
3667	piece = bit % (sizeof(uint32_t) * 8);
3668
3669	if ((mask[chunk] & (1 << piece)) == 0)
3670		return (0);
3671	else
3672		return (1);
3673}
3674
3675static uint64_t
3676ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3677{
3678	uint64_t *t;
3679
3680	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3681	if (t == NULL)
3682		return (0);
3683	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3684}
3685
3686static void
3687ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3688{
3689	uint64_t *t;
3690
3691	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3692	if (t == NULL)
3693		return;
3694	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3695}
3696
3697static void
3698ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3699{
3700	uint64_t *p;
3701	u_int i;
3702
3703	i = residx/CTL_MAX_INIT_PER_PORT;
3704	if (lun->pr_keys[i] != NULL)
3705		return;
3706	mtx_unlock(&lun->lun_lock);
3707	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3708	    M_WAITOK | M_ZERO);
3709	mtx_lock(&lun->lun_lock);
3710	if (lun->pr_keys[i] == NULL)
3711		lun->pr_keys[i] = p;
3712	else
3713		free(p, M_CTL);
3714}
3715
3716static void
3717ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3718{
3719	uint64_t *t;
3720
3721	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3722	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3723	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3724}
3725
3726/*
3727 * ctl_softc, pool_name, total_ctl_io are passed in.
3728 * npool is passed out.
3729 */
3730int
3731ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3732		uint32_t total_ctl_io, void **npool)
3733{
3734#ifdef IO_POOLS
3735	struct ctl_io_pool *pool;
3736
3737	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3738					    M_NOWAIT | M_ZERO);
3739	if (pool == NULL)
3740		return (ENOMEM);
3741
3742	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3743	pool->ctl_softc = ctl_softc;
3744	pool->zone = uma_zsecond_create(pool->name, NULL,
3745	    NULL, NULL, NULL, ctl_softc->io_zone);
3746	/* uma_prealloc(pool->zone, total_ctl_io); */
3747
3748	*npool = pool;
3749#else
3750	*npool = ctl_softc->io_zone;
3751#endif
3752	return (0);
3753}
3754
3755void
3756ctl_pool_free(struct ctl_io_pool *pool)
3757{
3758
3759	if (pool == NULL)
3760		return;
3761
3762#ifdef IO_POOLS
3763	uma_zdestroy(pool->zone);
3764	free(pool, M_CTL);
3765#endif
3766}
3767
3768union ctl_io *
3769ctl_alloc_io(void *pool_ref)
3770{
3771	union ctl_io *io;
3772#ifdef IO_POOLS
3773	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3774
3775	io = uma_zalloc(pool->zone, M_WAITOK);
3776#else
3777	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3778#endif
3779	if (io != NULL)
3780		io->io_hdr.pool = pool_ref;
3781	return (io);
3782}
3783
3784union ctl_io *
3785ctl_alloc_io_nowait(void *pool_ref)
3786{
3787	union ctl_io *io;
3788#ifdef IO_POOLS
3789	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3790
3791	io = uma_zalloc(pool->zone, M_NOWAIT);
3792#else
3793	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3794#endif
3795	if (io != NULL)
3796		io->io_hdr.pool = pool_ref;
3797	return (io);
3798}
3799
3800void
3801ctl_free_io(union ctl_io *io)
3802{
3803#ifdef IO_POOLS
3804	struct ctl_io_pool *pool;
3805#endif
3806
3807	if (io == NULL)
3808		return;
3809
3810#ifdef IO_POOLS
3811	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3812	uma_zfree(pool->zone, io);
3813#else
3814	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3815#endif
3816}
3817
3818void
3819ctl_zero_io(union ctl_io *io)
3820{
3821	void *pool_ref;
3822
3823	if (io == NULL)
3824		return;
3825
3826	/*
3827	 * May need to preserve linked list pointers at some point too.
3828	 */
3829	pool_ref = io->io_hdr.pool;
3830	memset(io, 0, sizeof(*io));
3831	io->io_hdr.pool = pool_ref;
3832}
3833
3834int
3835ctl_expand_number(const char *buf, uint64_t *num)
3836{
3837	char *endptr;
3838	uint64_t number;
3839	unsigned shift;
3840
3841	number = strtoq(buf, &endptr, 0);
3842
3843	switch (tolower((unsigned char)*endptr)) {
3844	case 'e':
3845		shift = 60;
3846		break;
3847	case 'p':
3848		shift = 50;
3849		break;
3850	case 't':
3851		shift = 40;
3852		break;
3853	case 'g':
3854		shift = 30;
3855		break;
3856	case 'm':
3857		shift = 20;
3858		break;
3859	case 'k':
3860		shift = 10;
3861		break;
3862	case 'b':
3863	case '\0': /* No unit. */
3864		*num = number;
3865		return (0);
3866	default:
3867		/* Unrecognized unit. */
3868		return (-1);
3869	}
3870
3871	if ((number << shift) >> shift != number) {
3872		/* Overflow */
3873		return (-1);
3874	}
3875	*num = number << shift;
3876	return (0);
3877}
3878
3879
3880/*
3881 * This routine could be used in the future to load default and/or saved
3882 * mode page parameters for a particuar lun.
3883 */
3884static int
3885ctl_init_page_index(struct ctl_lun *lun)
3886{
3887	int i, page_code;
3888	struct ctl_page_index *page_index;
3889	const char *value;
3890	uint64_t ival;
3891
3892	memcpy(&lun->mode_pages.index, page_index_template,
3893	       sizeof(page_index_template));
3894
3895	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3896
3897		page_index = &lun->mode_pages.index[i];
3898		if (lun->be_lun->lun_type == T_DIRECT &&
3899		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3900			continue;
3901		if (lun->be_lun->lun_type == T_PROCESSOR &&
3902		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3903			continue;
3904		if (lun->be_lun->lun_type == T_CDROM &&
3905		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3906			continue;
3907
3908		page_code = page_index->page_code & SMPH_PC_MASK;
3909		switch (page_code) {
3910		case SMS_RW_ERROR_RECOVERY_PAGE: {
3911			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3912			    ("subpage %#x for page %#x is incorrect!",
3913			    page_index->subpage, page_code));
3914			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3915			       &rw_er_page_default,
3916			       sizeof(rw_er_page_default));
3917			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3918			       &rw_er_page_changeable,
3919			       sizeof(rw_er_page_changeable));
3920			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3921			       &rw_er_page_default,
3922			       sizeof(rw_er_page_default));
3923			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3924			       &rw_er_page_default,
3925			       sizeof(rw_er_page_default));
3926			page_index->page_data =
3927				(uint8_t *)lun->mode_pages.rw_er_page;
3928			break;
3929		}
3930		case SMS_FORMAT_DEVICE_PAGE: {
3931			struct scsi_format_page *format_page;
3932
3933			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3934			    ("subpage %#x for page %#x is incorrect!",
3935			    page_index->subpage, page_code));
3936
3937			/*
3938			 * Sectors per track are set above.  Bytes per
3939			 * sector need to be set here on a per-LUN basis.
3940			 */
3941			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3942			       &format_page_default,
3943			       sizeof(format_page_default));
3944			memcpy(&lun->mode_pages.format_page[
3945			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3946			       sizeof(format_page_changeable));
3947			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3948			       &format_page_default,
3949			       sizeof(format_page_default));
3950			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3951			       &format_page_default,
3952			       sizeof(format_page_default));
3953
3954			format_page = &lun->mode_pages.format_page[
3955				CTL_PAGE_CURRENT];
3956			scsi_ulto2b(lun->be_lun->blocksize,
3957				    format_page->bytes_per_sector);
3958
3959			format_page = &lun->mode_pages.format_page[
3960				CTL_PAGE_DEFAULT];
3961			scsi_ulto2b(lun->be_lun->blocksize,
3962				    format_page->bytes_per_sector);
3963
3964			format_page = &lun->mode_pages.format_page[
3965				CTL_PAGE_SAVED];
3966			scsi_ulto2b(lun->be_lun->blocksize,
3967				    format_page->bytes_per_sector);
3968
3969			page_index->page_data =
3970				(uint8_t *)lun->mode_pages.format_page;
3971			break;
3972		}
3973		case SMS_RIGID_DISK_PAGE: {
3974			struct scsi_rigid_disk_page *rigid_disk_page;
3975			uint32_t sectors_per_cylinder;
3976			uint64_t cylinders;
3977#ifndef	__XSCALE__
3978			int shift;
3979#endif /* !__XSCALE__ */
3980
3981			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3982			    ("subpage %#x for page %#x is incorrect!",
3983			    page_index->subpage, page_code));
3984
3985			/*
3986			 * Rotation rate and sectors per track are set
3987			 * above.  We calculate the cylinders here based on
3988			 * capacity.  Due to the number of heads and
3989			 * sectors per track we're using, smaller arrays
3990			 * may turn out to have 0 cylinders.  Linux and
3991			 * FreeBSD don't pay attention to these mode pages
3992			 * to figure out capacity, but Solaris does.  It
3993			 * seems to deal with 0 cylinders just fine, and
3994			 * works out a fake geometry based on the capacity.
3995			 */
3996			memcpy(&lun->mode_pages.rigid_disk_page[
3997			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3998			       sizeof(rigid_disk_page_default));
3999			memcpy(&lun->mode_pages.rigid_disk_page[
4000			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4001			       sizeof(rigid_disk_page_changeable));
4002
4003			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4004				CTL_DEFAULT_HEADS;
4005
4006			/*
4007			 * The divide method here will be more accurate,
4008			 * probably, but results in floating point being
4009			 * used in the kernel on i386 (__udivdi3()).  On the
4010			 * XScale, though, __udivdi3() is implemented in
4011			 * software.
4012			 *
4013			 * The shift method for cylinder calculation is
4014			 * accurate if sectors_per_cylinder is a power of
4015			 * 2.  Otherwise it might be slightly off -- you
4016			 * might have a bit of a truncation problem.
4017			 */
4018#ifdef	__XSCALE__
4019			cylinders = (lun->be_lun->maxlba + 1) /
4020				sectors_per_cylinder;
4021#else
4022			for (shift = 31; shift > 0; shift--) {
4023				if (sectors_per_cylinder & (1 << shift))
4024					break;
4025			}
4026			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4027#endif
4028
4029			/*
4030			 * We've basically got 3 bytes, or 24 bits for the
4031			 * cylinder size in the mode page.  If we're over,
4032			 * just round down to 2^24.
4033			 */
4034			if (cylinders > 0xffffff)
4035				cylinders = 0xffffff;
4036
4037			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4038				CTL_PAGE_DEFAULT];
4039			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4040
4041			if ((value = ctl_get_opt(&lun->be_lun->options,
4042			    "rpm")) != NULL) {
4043				scsi_ulto2b(strtol(value, NULL, 0),
4044				     rigid_disk_page->rotation_rate);
4045			}
4046
4047			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4048			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4049			       sizeof(rigid_disk_page_default));
4050			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4051			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4052			       sizeof(rigid_disk_page_default));
4053
4054			page_index->page_data =
4055				(uint8_t *)lun->mode_pages.rigid_disk_page;
4056			break;
4057		}
4058		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4059			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4060			    ("subpage %#x for page %#x is incorrect!",
4061			    page_index->subpage, page_code));
4062			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4063			       &verify_er_page_default,
4064			       sizeof(verify_er_page_default));
4065			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4066			       &verify_er_page_changeable,
4067			       sizeof(verify_er_page_changeable));
4068			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4069			       &verify_er_page_default,
4070			       sizeof(verify_er_page_default));
4071			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4072			       &verify_er_page_default,
4073			       sizeof(verify_er_page_default));
4074			page_index->page_data =
4075				(uint8_t *)lun->mode_pages.verify_er_page;
4076			break;
4077		}
4078		case SMS_CACHING_PAGE: {
4079			struct scsi_caching_page *caching_page;
4080
4081			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4082			    ("subpage %#x for page %#x is incorrect!",
4083			    page_index->subpage, page_code));
4084			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4085			       &caching_page_default,
4086			       sizeof(caching_page_default));
4087			memcpy(&lun->mode_pages.caching_page[
4088			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4089			       sizeof(caching_page_changeable));
4090			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4091			       &caching_page_default,
4092			       sizeof(caching_page_default));
4093			caching_page = &lun->mode_pages.caching_page[
4094			    CTL_PAGE_SAVED];
4095			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4096			if (value != NULL && strcmp(value, "off") == 0)
4097				caching_page->flags1 &= ~SCP_WCE;
4098			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4099			if (value != NULL && strcmp(value, "off") == 0)
4100				caching_page->flags1 |= SCP_RCD;
4101			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4102			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4103			       sizeof(caching_page_default));
4104			page_index->page_data =
4105				(uint8_t *)lun->mode_pages.caching_page;
4106			break;
4107		}
4108		case SMS_CONTROL_MODE_PAGE: {
4109			switch (page_index->subpage) {
4110			case SMS_SUBPAGE_PAGE_0: {
4111				struct scsi_control_page *control_page;
4112
4113				memcpy(&lun->mode_pages.control_page[
4114				    CTL_PAGE_DEFAULT],
4115				       &control_page_default,
4116				       sizeof(control_page_default));
4117				memcpy(&lun->mode_pages.control_page[
4118				    CTL_PAGE_CHANGEABLE],
4119				       &control_page_changeable,
4120				       sizeof(control_page_changeable));
4121				memcpy(&lun->mode_pages.control_page[
4122				    CTL_PAGE_SAVED],
4123				       &control_page_default,
4124				       sizeof(control_page_default));
4125				control_page = &lun->mode_pages.control_page[
4126				    CTL_PAGE_SAVED];
4127				value = ctl_get_opt(&lun->be_lun->options,
4128				    "reordering");
4129				if (value != NULL &&
4130				    strcmp(value, "unrestricted") == 0) {
4131					control_page->queue_flags &=
4132					    ~SCP_QUEUE_ALG_MASK;
4133					control_page->queue_flags |=
4134					    SCP_QUEUE_ALG_UNRESTRICTED;
4135				}
4136				memcpy(&lun->mode_pages.control_page[
4137				    CTL_PAGE_CURRENT],
4138				       &lun->mode_pages.control_page[
4139				    CTL_PAGE_SAVED],
4140				       sizeof(control_page_default));
4141				page_index->page_data =
4142				    (uint8_t *)lun->mode_pages.control_page;
4143				break;
4144			}
4145			case 0x01:
4146				memcpy(&lun->mode_pages.control_ext_page[
4147				    CTL_PAGE_DEFAULT],
4148				       &control_ext_page_default,
4149				       sizeof(control_ext_page_default));
4150				memcpy(&lun->mode_pages.control_ext_page[
4151				    CTL_PAGE_CHANGEABLE],
4152				       &control_ext_page_changeable,
4153				       sizeof(control_ext_page_changeable));
4154				memcpy(&lun->mode_pages.control_ext_page[
4155				    CTL_PAGE_SAVED],
4156				       &control_ext_page_default,
4157				       sizeof(control_ext_page_default));
4158				memcpy(&lun->mode_pages.control_ext_page[
4159				    CTL_PAGE_CURRENT],
4160				       &lun->mode_pages.control_ext_page[
4161				    CTL_PAGE_SAVED],
4162				       sizeof(control_ext_page_default));
4163				page_index->page_data =
4164				    (uint8_t *)lun->mode_pages.control_ext_page;
4165				break;
4166			default:
4167				panic("subpage %#x for page %#x is incorrect!",
4168				      page_index->subpage, page_code);
4169			}
4170			break;
4171		}
4172		case SMS_INFO_EXCEPTIONS_PAGE: {
4173			switch (page_index->subpage) {
4174			case SMS_SUBPAGE_PAGE_0:
4175				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4176				       &ie_page_default,
4177				       sizeof(ie_page_default));
4178				memcpy(&lun->mode_pages.ie_page[
4179				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4180				       sizeof(ie_page_changeable));
4181				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4182				       &ie_page_default,
4183				       sizeof(ie_page_default));
4184				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4185				       &ie_page_default,
4186				       sizeof(ie_page_default));
4187				page_index->page_data =
4188					(uint8_t *)lun->mode_pages.ie_page;
4189				break;
4190			case 0x02: {
4191				struct ctl_logical_block_provisioning_page *page;
4192
4193				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4194				       &lbp_page_default,
4195				       sizeof(lbp_page_default));
4196				memcpy(&lun->mode_pages.lbp_page[
4197				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4198				       sizeof(lbp_page_changeable));
4199				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4200				       &lbp_page_default,
4201				       sizeof(lbp_page_default));
4202				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4203				value = ctl_get_opt(&lun->be_lun->options,
4204				    "avail-threshold");
4205				if (value != NULL &&
4206				    ctl_expand_number(value, &ival) == 0) {
4207					page->descr[0].flags |= SLBPPD_ENABLED |
4208					    SLBPPD_ARMING_DEC;
4209					if (lun->be_lun->blocksize)
4210						ival /= lun->be_lun->blocksize;
4211					else
4212						ival /= 512;
4213					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4214					    page->descr[0].count);
4215				}
4216				value = ctl_get_opt(&lun->be_lun->options,
4217				    "used-threshold");
4218				if (value != NULL &&
4219				    ctl_expand_number(value, &ival) == 0) {
4220					page->descr[1].flags |= SLBPPD_ENABLED |
4221					    SLBPPD_ARMING_INC;
4222					if (lun->be_lun->blocksize)
4223						ival /= lun->be_lun->blocksize;
4224					else
4225						ival /= 512;
4226					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4227					    page->descr[1].count);
4228				}
4229				value = ctl_get_opt(&lun->be_lun->options,
4230				    "pool-avail-threshold");
4231				if (value != NULL &&
4232				    ctl_expand_number(value, &ival) == 0) {
4233					page->descr[2].flags |= SLBPPD_ENABLED |
4234					    SLBPPD_ARMING_DEC;
4235					if (lun->be_lun->blocksize)
4236						ival /= lun->be_lun->blocksize;
4237					else
4238						ival /= 512;
4239					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4240					    page->descr[2].count);
4241				}
4242				value = ctl_get_opt(&lun->be_lun->options,
4243				    "pool-used-threshold");
4244				if (value != NULL &&
4245				    ctl_expand_number(value, &ival) == 0) {
4246					page->descr[3].flags |= SLBPPD_ENABLED |
4247					    SLBPPD_ARMING_INC;
4248					if (lun->be_lun->blocksize)
4249						ival /= lun->be_lun->blocksize;
4250					else
4251						ival /= 512;
4252					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4253					    page->descr[3].count);
4254				}
4255				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4256				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4257				       sizeof(lbp_page_default));
4258				page_index->page_data =
4259					(uint8_t *)lun->mode_pages.lbp_page;
4260				break;
4261			}
4262			default:
4263				panic("subpage %#x for page %#x is incorrect!",
4264				      page_index->subpage, page_code);
4265			}
4266			break;
4267		}
4268		case SMS_CDDVD_CAPS_PAGE:{
4269			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4270			    ("subpage %#x for page %#x is incorrect!",
4271			    page_index->subpage, page_code));
4272			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4273			       &cddvd_page_default,
4274			       sizeof(cddvd_page_default));
4275			memcpy(&lun->mode_pages.cddvd_page[
4276			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4277			       sizeof(cddvd_page_changeable));
4278			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4279			       &cddvd_page_default,
4280			       sizeof(cddvd_page_default));
4281			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4282			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4283			       sizeof(cddvd_page_default));
4284			page_index->page_data =
4285				(uint8_t *)lun->mode_pages.cddvd_page;
4286			break;
4287		}
4288		default:
4289			panic("invalid page code value %#x", page_code);
4290		}
4291	}
4292
4293	return (CTL_RETVAL_COMPLETE);
4294}
4295
4296static int
4297ctl_init_log_page_index(struct ctl_lun *lun)
4298{
4299	struct ctl_page_index *page_index;
4300	int i, j, k, prev;
4301
4302	memcpy(&lun->log_pages.index, log_page_index_template,
4303	       sizeof(log_page_index_template));
4304
4305	prev = -1;
4306	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4307
4308		page_index = &lun->log_pages.index[i];
4309		if (lun->be_lun->lun_type == T_DIRECT &&
4310		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4311			continue;
4312		if (lun->be_lun->lun_type == T_PROCESSOR &&
4313		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4314			continue;
4315		if (lun->be_lun->lun_type == T_CDROM &&
4316		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4317			continue;
4318
4319		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4320		    lun->backend->lun_attr == NULL)
4321			continue;
4322
4323		if (page_index->page_code != prev) {
4324			lun->log_pages.pages_page[j] = page_index->page_code;
4325			prev = page_index->page_code;
4326			j++;
4327		}
4328		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4329		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4330		k++;
4331	}
4332	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4333	lun->log_pages.index[0].page_len = j;
4334	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4335	lun->log_pages.index[1].page_len = k * 2;
4336	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4337	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4338	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4339	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4340	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4341	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4342
4343	return (CTL_RETVAL_COMPLETE);
4344}
4345
4346static int
4347hex2bin(const char *str, uint8_t *buf, int buf_size)
4348{
4349	int i;
4350	u_char c;
4351
4352	memset(buf, 0, buf_size);
4353	while (isspace(str[0]))
4354		str++;
4355	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4356		str += 2;
4357	buf_size *= 2;
4358	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4359		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4360			str++;
4361		c = str[i];
4362		if (isdigit(c))
4363			c -= '0';
4364		else if (isalpha(c))
4365			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4366		else
4367			break;
4368		if (c >= 16)
4369			break;
4370		if ((i & 1) == 0)
4371			buf[i / 2] |= (c << 4);
4372		else
4373			buf[i / 2] |= c;
4374	}
4375	return ((i + 1) / 2);
4376}
4377
4378/*
4379 * LUN allocation.
4380 *
4381 * Requirements:
4382 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4383 *   wants us to allocate the LUN and he can block.
4384 * - ctl_softc is always set
4385 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4386 *
4387 * Returns 0 for success, non-zero (errno) for failure.
4388 */
4389static int
4390ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4391	      struct ctl_be_lun *const be_lun)
4392{
4393	struct ctl_lun *nlun, *lun;
4394	struct scsi_vpd_id_descriptor *desc;
4395	struct scsi_vpd_id_t10 *t10id;
4396	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4397	int lun_number, i, lun_malloced;
4398	int devidlen, idlen1, idlen2 = 0, len;
4399
4400	if (be_lun == NULL)
4401		return (EINVAL);
4402
4403	/*
4404	 * We currently only support Direct Access or Processor LUN types.
4405	 */
4406	switch (be_lun->lun_type) {
4407	case T_DIRECT:
4408	case T_PROCESSOR:
4409	case T_CDROM:
4410		break;
4411	case T_SEQUENTIAL:
4412	case T_CHANGER:
4413	default:
4414		be_lun->lun_config_status(be_lun->be_lun,
4415					  CTL_LUN_CONFIG_FAILURE);
4416		break;
4417	}
4418	if (ctl_lun == NULL) {
4419		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4420		lun_malloced = 1;
4421	} else {
4422		lun_malloced = 0;
4423		lun = ctl_lun;
4424	}
4425
4426	memset(lun, 0, sizeof(*lun));
4427	if (lun_malloced)
4428		lun->flags = CTL_LUN_MALLOCED;
4429
4430	/* Generate LUN ID. */
4431	devidlen = max(CTL_DEVID_MIN_LEN,
4432	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4433	idlen1 = sizeof(*t10id) + devidlen;
4434	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4435	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4436	if (scsiname != NULL) {
4437		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4438		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4439	}
4440	eui = ctl_get_opt(&be_lun->options, "eui");
4441	if (eui != NULL) {
4442		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4443	}
4444	naa = ctl_get_opt(&be_lun->options, "naa");
4445	if (naa != NULL) {
4446		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4447	}
4448	uuid = ctl_get_opt(&be_lun->options, "uuid");
4449	if (uuid != NULL) {
4450		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4451	}
4452	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4453	    M_CTL, M_WAITOK | M_ZERO);
4454	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4455	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4456	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4457	desc->length = idlen1;
4458	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4459	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4460	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4461		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4462	} else {
4463		strncpy(t10id->vendor, vendor,
4464		    min(sizeof(t10id->vendor), strlen(vendor)));
4465	}
4466	strncpy((char *)t10id->vendor_spec_id,
4467	    (char *)be_lun->device_id, devidlen);
4468	if (scsiname != NULL) {
4469		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4470		    desc->length);
4471		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4472		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4473		    SVPD_ID_TYPE_SCSI_NAME;
4474		desc->length = idlen2;
4475		strlcpy(desc->identifier, scsiname, idlen2);
4476	}
4477	if (eui != NULL) {
4478		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4479		    desc->length);
4480		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4481		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4482		    SVPD_ID_TYPE_EUI64;
4483		desc->length = hex2bin(eui, desc->identifier, 16);
4484		desc->length = desc->length > 12 ? 16 :
4485		    (desc->length > 8 ? 12 : 8);
4486		len -= 16 - desc->length;
4487	}
4488	if (naa != NULL) {
4489		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4490		    desc->length);
4491		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4492		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4493		    SVPD_ID_TYPE_NAA;
4494		desc->length = hex2bin(naa, desc->identifier, 16);
4495		desc->length = desc->length > 8 ? 16 : 8;
4496		len -= 16 - desc->length;
4497	}
4498	if (uuid != NULL) {
4499		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4500		    desc->length);
4501		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4502		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4503		    SVPD_ID_TYPE_UUID;
4504		desc->identifier[0] = 0x10;
4505		hex2bin(uuid, &desc->identifier[2], 16);
4506		desc->length = 18;
4507	}
4508	lun->lun_devid->len = len;
4509
4510	mtx_lock(&ctl_softc->ctl_lock);
4511	/*
4512	 * See if the caller requested a particular LUN number.  If so, see
4513	 * if it is available.  Otherwise, allocate the first available LUN.
4514	 */
4515	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4516		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4517		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4518			mtx_unlock(&ctl_softc->ctl_lock);
4519			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4520				printf("ctl: requested LUN ID %d is higher "
4521				       "than CTL_MAX_LUNS - 1 (%d)\n",
4522				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4523			} else {
4524				/*
4525				 * XXX KDM return an error, or just assign
4526				 * another LUN ID in this case??
4527				 */
4528				printf("ctl: requested LUN ID %d is already "
4529				       "in use\n", be_lun->req_lun_id);
4530			}
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		lun_number = be_lun->req_lun_id;
4538	} else {
4539		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4540		if (lun_number == -1) {
4541			mtx_unlock(&ctl_softc->ctl_lock);
4542			printf("ctl: can't allocate LUN, out of LUNs\n");
4543			if (lun->flags & CTL_LUN_MALLOCED)
4544				free(lun, M_CTL);
4545			be_lun->lun_config_status(be_lun->be_lun,
4546						  CTL_LUN_CONFIG_FAILURE);
4547			return (ENOSPC);
4548		}
4549	}
4550	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4551
4552	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4553	lun->lun = lun_number;
4554	lun->be_lun = be_lun;
4555	/*
4556	 * The processor LUN is always enabled.  Disk LUNs come on line
4557	 * disabled, and must be enabled by the backend.
4558	 */
4559	lun->flags |= CTL_LUN_DISABLED;
4560	lun->backend = be_lun->be;
4561	be_lun->ctl_lun = lun;
4562	be_lun->lun_id = lun_number;
4563	atomic_add_int(&be_lun->be->num_luns, 1);
4564	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4565		lun->flags |= CTL_LUN_EJECTED;
4566	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4567		lun->flags |= CTL_LUN_NO_MEDIA;
4568	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4569		lun->flags |= CTL_LUN_STOPPED;
4570
4571	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4572		lun->flags |= CTL_LUN_PRIMARY_SC;
4573
4574	value = ctl_get_opt(&be_lun->options, "removable");
4575	if (value != NULL) {
4576		if (strcmp(value, "on") == 0)
4577			lun->flags |= CTL_LUN_REMOVABLE;
4578	} else if (be_lun->lun_type == T_CDROM)
4579		lun->flags |= CTL_LUN_REMOVABLE;
4580
4581	lun->ctl_softc = ctl_softc;
4582#ifdef CTL_TIME_IO
4583	lun->last_busy = getsbinuptime();
4584#endif
4585	TAILQ_INIT(&lun->ooa_queue);
4586	TAILQ_INIT(&lun->blocked_queue);
4587	STAILQ_INIT(&lun->error_list);
4588	lun->ie_reported = 1;
4589	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4590	ctl_tpc_lun_init(lun);
4591
4592	/*
4593	 * Initialize the mode and log page index.
4594	 */
4595	ctl_init_page_index(lun);
4596	ctl_init_log_page_index(lun);
4597
4598	/*
4599	 * Now, before we insert this lun on the lun list, set the lun
4600	 * inventory changed UA for all other luns.
4601	 */
4602	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4603		mtx_lock(&nlun->lun_lock);
4604		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4605		mtx_unlock(&nlun->lun_lock);
4606	}
4607
4608	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4609
4610	ctl_softc->ctl_luns[lun_number] = lun;
4611
4612	ctl_softc->num_luns++;
4613
4614	/* Setup statistics gathering */
4615	lun->stats.device_type = be_lun->lun_type;
4616	lun->stats.lun_number = lun_number;
4617	lun->stats.blocksize = be_lun->blocksize;
4618	if (be_lun->blocksize == 0)
4619		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4620	for (i = 0;i < CTL_MAX_PORTS;i++)
4621		lun->stats.ports[i].targ_port = i;
4622
4623	mtx_unlock(&ctl_softc->ctl_lock);
4624
4625	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4626	return (0);
4627}
4628
4629/*
4630 * Delete a LUN.
4631 * Assumptions:
4632 * - LUN has already been marked invalid and any pending I/O has been taken
4633 *   care of.
4634 */
4635static int
4636ctl_free_lun(struct ctl_lun *lun)
4637{
4638	struct ctl_softc *softc;
4639	struct ctl_lun *nlun;
4640	int i;
4641
4642	softc = lun->ctl_softc;
4643
4644	mtx_assert(&softc->ctl_lock, MA_OWNED);
4645
4646	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4647
4648	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4649
4650	softc->ctl_luns[lun->lun] = NULL;
4651
4652	if (!TAILQ_EMPTY(&lun->ooa_queue))
4653		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4654
4655	softc->num_luns--;
4656
4657	/*
4658	 * Tell the backend to free resources, if this LUN has a backend.
4659	 */
4660	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4661	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4662
4663	lun->ie_reportcnt = UINT32_MAX;
4664	callout_drain(&lun->ie_callout);
4665
4666	ctl_tpc_lun_shutdown(lun);
4667	mtx_destroy(&lun->lun_lock);
4668	free(lun->lun_devid, M_CTL);
4669	for (i = 0; i < CTL_MAX_PORTS; i++)
4670		free(lun->pending_ua[i], M_CTL);
4671	for (i = 0; i < CTL_MAX_PORTS; i++)
4672		free(lun->pr_keys[i], M_CTL);
4673	free(lun->write_buffer, M_CTL);
4674	if (lun->flags & CTL_LUN_MALLOCED)
4675		free(lun, M_CTL);
4676
4677	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4678		mtx_lock(&nlun->lun_lock);
4679		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4680		mtx_unlock(&nlun->lun_lock);
4681	}
4682
4683	return (0);
4684}
4685
4686static void
4687ctl_create_lun(struct ctl_be_lun *be_lun)
4688{
4689
4690	/*
4691	 * ctl_alloc_lun() should handle all potential failure cases.
4692	 */
4693	ctl_alloc_lun(control_softc, NULL, be_lun);
4694}
4695
4696int
4697ctl_add_lun(struct ctl_be_lun *be_lun)
4698{
4699	struct ctl_softc *softc = control_softc;
4700
4701	mtx_lock(&softc->ctl_lock);
4702	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4703	mtx_unlock(&softc->ctl_lock);
4704	wakeup(&softc->pending_lun_queue);
4705
4706	return (0);
4707}
4708
4709int
4710ctl_enable_lun(struct ctl_be_lun *be_lun)
4711{
4712	struct ctl_softc *softc;
4713	struct ctl_port *port, *nport;
4714	struct ctl_lun *lun;
4715	int retval;
4716
4717	lun = (struct ctl_lun *)be_lun->ctl_lun;
4718	softc = lun->ctl_softc;
4719
4720	mtx_lock(&softc->ctl_lock);
4721	mtx_lock(&lun->lun_lock);
4722	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4723		/*
4724		 * eh?  Why did we get called if the LUN is already
4725		 * enabled?
4726		 */
4727		mtx_unlock(&lun->lun_lock);
4728		mtx_unlock(&softc->ctl_lock);
4729		return (0);
4730	}
4731	lun->flags &= ~CTL_LUN_DISABLED;
4732	mtx_unlock(&lun->lun_lock);
4733
4734	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4735		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4736		    port->lun_map != NULL || port->lun_enable == NULL)
4737			continue;
4738
4739		/*
4740		 * Drop the lock while we call the FETD's enable routine.
4741		 * This can lead to a callback into CTL (at least in the
4742		 * case of the internal initiator frontend.
4743		 */
4744		mtx_unlock(&softc->ctl_lock);
4745		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4746		mtx_lock(&softc->ctl_lock);
4747		if (retval != 0) {
4748			printf("%s: FETD %s port %d returned error "
4749			       "%d for lun_enable on lun %jd\n",
4750			       __func__, port->port_name, port->targ_port,
4751			       retval, (intmax_t)lun->lun);
4752		}
4753	}
4754
4755	mtx_unlock(&softc->ctl_lock);
4756	ctl_isc_announce_lun(lun);
4757
4758	return (0);
4759}
4760
4761int
4762ctl_disable_lun(struct ctl_be_lun *be_lun)
4763{
4764	struct ctl_softc *softc;
4765	struct ctl_port *port;
4766	struct ctl_lun *lun;
4767	int retval;
4768
4769	lun = (struct ctl_lun *)be_lun->ctl_lun;
4770	softc = lun->ctl_softc;
4771
4772	mtx_lock(&softc->ctl_lock);
4773	mtx_lock(&lun->lun_lock);
4774	if (lun->flags & CTL_LUN_DISABLED) {
4775		mtx_unlock(&lun->lun_lock);
4776		mtx_unlock(&softc->ctl_lock);
4777		return (0);
4778	}
4779	lun->flags |= CTL_LUN_DISABLED;
4780	mtx_unlock(&lun->lun_lock);
4781
4782	STAILQ_FOREACH(port, &softc->port_list, links) {
4783		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4784		    port->lun_map != NULL || port->lun_disable == NULL)
4785			continue;
4786
4787		/*
4788		 * Drop the lock before we call the frontend's disable
4789		 * routine, to avoid lock order reversals.
4790		 *
4791		 * XXX KDM what happens if the frontend list changes while
4792		 * we're traversing it?  It's unlikely, but should be handled.
4793		 */
4794		mtx_unlock(&softc->ctl_lock);
4795		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4796		mtx_lock(&softc->ctl_lock);
4797		if (retval != 0) {
4798			printf("%s: FETD %s port %d returned error "
4799			       "%d for lun_disable on lun %jd\n",
4800			       __func__, port->port_name, port->targ_port,
4801			       retval, (intmax_t)lun->lun);
4802		}
4803	}
4804
4805	mtx_unlock(&softc->ctl_lock);
4806	ctl_isc_announce_lun(lun);
4807
4808	return (0);
4809}
4810
4811int
4812ctl_start_lun(struct ctl_be_lun *be_lun)
4813{
4814	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4815
4816	mtx_lock(&lun->lun_lock);
4817	lun->flags &= ~CTL_LUN_STOPPED;
4818	mtx_unlock(&lun->lun_lock);
4819	return (0);
4820}
4821
4822int
4823ctl_stop_lun(struct ctl_be_lun *be_lun)
4824{
4825	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4826
4827	mtx_lock(&lun->lun_lock);
4828	lun->flags |= CTL_LUN_STOPPED;
4829	mtx_unlock(&lun->lun_lock);
4830	return (0);
4831}
4832
4833int
4834ctl_lun_no_media(struct ctl_be_lun *be_lun)
4835{
4836	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4837
4838	mtx_lock(&lun->lun_lock);
4839	lun->flags |= CTL_LUN_NO_MEDIA;
4840	mtx_unlock(&lun->lun_lock);
4841	return (0);
4842}
4843
4844int
4845ctl_lun_has_media(struct ctl_be_lun *be_lun)
4846{
4847	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4848	union ctl_ha_msg msg;
4849
4850	mtx_lock(&lun->lun_lock);
4851	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4852	if (lun->flags & CTL_LUN_REMOVABLE)
4853		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4854	mtx_unlock(&lun->lun_lock);
4855	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4856	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4857		bzero(&msg.ua, sizeof(msg.ua));
4858		msg.hdr.msg_type = CTL_MSG_UA;
4859		msg.hdr.nexus.initid = -1;
4860		msg.hdr.nexus.targ_port = -1;
4861		msg.hdr.nexus.targ_lun = lun->lun;
4862		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4863		msg.ua.ua_all = 1;
4864		msg.ua.ua_set = 1;
4865		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4866		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4867		    M_WAITOK);
4868	}
4869	return (0);
4870}
4871
4872int
4873ctl_lun_ejected(struct ctl_be_lun *be_lun)
4874{
4875	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4876
4877	mtx_lock(&lun->lun_lock);
4878	lun->flags |= CTL_LUN_EJECTED;
4879	mtx_unlock(&lun->lun_lock);
4880	return (0);
4881}
4882
4883int
4884ctl_lun_primary(struct ctl_be_lun *be_lun)
4885{
4886	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4887
4888	mtx_lock(&lun->lun_lock);
4889	lun->flags |= CTL_LUN_PRIMARY_SC;
4890	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4891	mtx_unlock(&lun->lun_lock);
4892	ctl_isc_announce_lun(lun);
4893	return (0);
4894}
4895
4896int
4897ctl_lun_secondary(struct ctl_be_lun *be_lun)
4898{
4899	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4900
4901	mtx_lock(&lun->lun_lock);
4902	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4903	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4904	mtx_unlock(&lun->lun_lock);
4905	ctl_isc_announce_lun(lun);
4906	return (0);
4907}
4908
4909int
4910ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4911{
4912	struct ctl_softc *softc;
4913	struct ctl_lun *lun;
4914
4915	lun = (struct ctl_lun *)be_lun->ctl_lun;
4916	softc = lun->ctl_softc;
4917
4918	mtx_lock(&lun->lun_lock);
4919
4920	/*
4921	 * The LUN needs to be disabled before it can be marked invalid.
4922	 */
4923	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4924		mtx_unlock(&lun->lun_lock);
4925		return (-1);
4926	}
4927	/*
4928	 * Mark the LUN invalid.
4929	 */
4930	lun->flags |= CTL_LUN_INVALID;
4931
4932	/*
4933	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4934	 * If we have something in the OOA queue, we'll free it when the
4935	 * last I/O completes.
4936	 */
4937	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4938		mtx_unlock(&lun->lun_lock);
4939		mtx_lock(&softc->ctl_lock);
4940		ctl_free_lun(lun);
4941		mtx_unlock(&softc->ctl_lock);
4942	} else
4943		mtx_unlock(&lun->lun_lock);
4944
4945	return (0);
4946}
4947
4948void
4949ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4950{
4951	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4952	union ctl_ha_msg msg;
4953
4954	mtx_lock(&lun->lun_lock);
4955	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4956	mtx_unlock(&lun->lun_lock);
4957	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4958		/* Send msg to other side. */
4959		bzero(&msg.ua, sizeof(msg.ua));
4960		msg.hdr.msg_type = CTL_MSG_UA;
4961		msg.hdr.nexus.initid = -1;
4962		msg.hdr.nexus.targ_port = -1;
4963		msg.hdr.nexus.targ_lun = lun->lun;
4964		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4965		msg.ua.ua_all = 1;
4966		msg.ua.ua_set = 1;
4967		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4968		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4969		    M_WAITOK);
4970	}
4971}
4972
4973/*
4974 * Backend "memory move is complete" callback for requests that never
4975 * make it down to say RAIDCore's configuration code.
4976 */
4977int
4978ctl_config_move_done(union ctl_io *io)
4979{
4980	int retval;
4981
4982	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4983	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4984	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4985
4986	if ((io->io_hdr.port_status != 0) &&
4987	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4988	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4989		/*
4990		 * For hardware error sense keys, the sense key
4991		 * specific value is defined to be a retry count,
4992		 * but we use it to pass back an internal FETD
4993		 * error code.  XXX KDM  Hopefully the FETD is only
4994		 * using 16 bits for an error code, since that's
4995		 * all the space we have in the sks field.
4996		 */
4997		ctl_set_internal_failure(&io->scsiio,
4998					 /*sks_valid*/ 1,
4999					 /*retry_count*/
5000					 io->io_hdr.port_status);
5001	}
5002
5003	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5004		ctl_data_print(io);
5005	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5006	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5007	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5008	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5009		/*
5010		 * XXX KDM just assuming a single pointer here, and not a
5011		 * S/G list.  If we start using S/G lists for config data,
5012		 * we'll need to know how to clean them up here as well.
5013		 */
5014		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5015			free(io->scsiio.kern_data_ptr, M_CTL);
5016		ctl_done(io);
5017		retval = CTL_RETVAL_COMPLETE;
5018	} else {
5019		/*
5020		 * XXX KDM now we need to continue data movement.  Some
5021		 * options:
5022		 * - call ctl_scsiio() again?  We don't do this for data
5023		 *   writes, because for those at least we know ahead of
5024		 *   time where the write will go and how long it is.  For
5025		 *   config writes, though, that information is largely
5026		 *   contained within the write itself, thus we need to
5027		 *   parse out the data again.
5028		 *
5029		 * - Call some other function once the data is in?
5030		 */
5031
5032		/*
5033		 * XXX KDM call ctl_scsiio() again for now, and check flag
5034		 * bits to see whether we're allocated or not.
5035		 */
5036		retval = ctl_scsiio(&io->scsiio);
5037	}
5038	return (retval);
5039}
5040
5041/*
5042 * This gets called by a backend driver when it is done with a
5043 * data_submit method.
5044 */
5045void
5046ctl_data_submit_done(union ctl_io *io)
5047{
5048	/*
5049	 * If the IO_CONT flag is set, we need to call the supplied
5050	 * function to continue processing the I/O, instead of completing
5051	 * the I/O just yet.
5052	 *
5053	 * If there is an error, though, we don't want to keep processing.
5054	 * Instead, just send status back to the initiator.
5055	 */
5056	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5057	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5058	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5059	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5060		io->scsiio.io_cont(io);
5061		return;
5062	}
5063	ctl_done(io);
5064}
5065
5066/*
5067 * This gets called by a backend driver when it is done with a
5068 * configuration write.
5069 */
5070void
5071ctl_config_write_done(union ctl_io *io)
5072{
5073	uint8_t *buf;
5074
5075	/*
5076	 * If the IO_CONT flag is set, we need to call the supplied
5077	 * function to continue processing the I/O, instead of completing
5078	 * the I/O just yet.
5079	 *
5080	 * If there is an error, though, we don't want to keep processing.
5081	 * Instead, just send status back to the initiator.
5082	 */
5083	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5084	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5085	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5086	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5087		io->scsiio.io_cont(io);
5088		return;
5089	}
5090	/*
5091	 * Since a configuration write can be done for commands that actually
5092	 * have data allocated, like write buffer, and commands that have
5093	 * no data, like start/stop unit, we need to check here.
5094	 */
5095	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5096		buf = io->scsiio.kern_data_ptr;
5097	else
5098		buf = NULL;
5099	ctl_done(io);
5100	if (buf)
5101		free(buf, M_CTL);
5102}
5103
5104void
5105ctl_config_read_done(union ctl_io *io)
5106{
5107	uint8_t *buf;
5108
5109	/*
5110	 * If there is some error -- we are done, skip data transfer.
5111	 */
5112	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5113	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5114	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5115		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5116			buf = io->scsiio.kern_data_ptr;
5117		else
5118			buf = NULL;
5119		ctl_done(io);
5120		if (buf)
5121			free(buf, M_CTL);
5122		return;
5123	}
5124
5125	/*
5126	 * If the IO_CONT flag is set, we need to call the supplied
5127	 * function to continue processing the I/O, instead of completing
5128	 * the I/O just yet.
5129	 */
5130	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5131		io->scsiio.io_cont(io);
5132		return;
5133	}
5134
5135	ctl_datamove(io);
5136}
5137
5138/*
5139 * SCSI release command.
5140 */
5141int
5142ctl_scsi_release(struct ctl_scsiio *ctsio)
5143{
5144	struct ctl_lun *lun;
5145	uint32_t residx;
5146
5147	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5148
5149	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5150	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5151
5152	/*
5153	 * XXX KDM right now, we only support LUN reservation.  We don't
5154	 * support 3rd party reservations, or extent reservations, which
5155	 * might actually need the parameter list.  If we've gotten this
5156	 * far, we've got a LUN reservation.  Anything else got kicked out
5157	 * above.  So, according to SPC, ignore the length.
5158	 */
5159
5160	mtx_lock(&lun->lun_lock);
5161
5162	/*
5163	 * According to SPC, it is not an error for an intiator to attempt
5164	 * to release a reservation on a LUN that isn't reserved, or that
5165	 * is reserved by another initiator.  The reservation can only be
5166	 * released, though, by the initiator who made it or by one of
5167	 * several reset type events.
5168	 */
5169	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5170			lun->flags &= ~CTL_LUN_RESERVED;
5171
5172	mtx_unlock(&lun->lun_lock);
5173
5174	ctl_set_success(ctsio);
5175	ctl_done((union ctl_io *)ctsio);
5176	return (CTL_RETVAL_COMPLETE);
5177}
5178
5179int
5180ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5181{
5182	struct ctl_lun *lun;
5183	uint32_t residx;
5184
5185	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5186
5187	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5188	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5189
5190	/*
5191	 * XXX KDM right now, we only support LUN reservation.  We don't
5192	 * support 3rd party reservations, or extent reservations, which
5193	 * might actually need the parameter list.  If we've gotten this
5194	 * far, we've got a LUN reservation.  Anything else got kicked out
5195	 * above.  So, according to SPC, ignore the length.
5196	 */
5197
5198	mtx_lock(&lun->lun_lock);
5199	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5200		ctl_set_reservation_conflict(ctsio);
5201		goto bailout;
5202	}
5203
5204	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5205	if (lun->flags & CTL_LUN_PR_RESERVED) {
5206		ctl_set_success(ctsio);
5207		goto bailout;
5208	}
5209
5210	lun->flags |= CTL_LUN_RESERVED;
5211	lun->res_idx = residx;
5212	ctl_set_success(ctsio);
5213
5214bailout:
5215	mtx_unlock(&lun->lun_lock);
5216	ctl_done((union ctl_io *)ctsio);
5217	return (CTL_RETVAL_COMPLETE);
5218}
5219
5220int
5221ctl_start_stop(struct ctl_scsiio *ctsio)
5222{
5223	struct scsi_start_stop_unit *cdb;
5224	struct ctl_lun *lun;
5225	int retval;
5226
5227	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5228
5229	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5230	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5231
5232	if ((cdb->how & SSS_PC_MASK) == 0) {
5233		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5234		    (cdb->how & SSS_START) == 0) {
5235			uint32_t residx;
5236
5237			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5238			if (ctl_get_prkey(lun, residx) == 0 ||
5239			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5240
5241				ctl_set_reservation_conflict(ctsio);
5242				ctl_done((union ctl_io *)ctsio);
5243				return (CTL_RETVAL_COMPLETE);
5244			}
5245		}
5246
5247		if ((cdb->how & SSS_LOEJ) &&
5248		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5249			ctl_set_invalid_field(ctsio,
5250					      /*sks_valid*/ 1,
5251					      /*command*/ 1,
5252					      /*field*/ 4,
5253					      /*bit_valid*/ 1,
5254					      /*bit*/ 1);
5255			ctl_done((union ctl_io *)ctsio);
5256			return (CTL_RETVAL_COMPLETE);
5257		}
5258
5259		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5260		    lun->prevent_count > 0) {
5261			/* "Medium removal prevented" */
5262			ctl_set_sense(ctsio, /*current_error*/ 1,
5263			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5264			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5265			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5266			ctl_done((union ctl_io *)ctsio);
5267			return (CTL_RETVAL_COMPLETE);
5268		}
5269	}
5270
5271	retval = lun->backend->config_write((union ctl_io *)ctsio);
5272	return (retval);
5273}
5274
5275int
5276ctl_prevent_allow(struct ctl_scsiio *ctsio)
5277{
5278	struct ctl_lun *lun;
5279	struct scsi_prevent *cdb;
5280	int retval;
5281	uint32_t initidx;
5282
5283	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5284
5285	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5286	cdb = (struct scsi_prevent *)ctsio->cdb;
5287
5288	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5289		ctl_set_invalid_opcode(ctsio);
5290		ctl_done((union ctl_io *)ctsio);
5291		return (CTL_RETVAL_COMPLETE);
5292	}
5293
5294	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5295	mtx_lock(&lun->lun_lock);
5296	if ((cdb->how & PR_PREVENT) &&
5297	    ctl_is_set(lun->prevent, initidx) == 0) {
5298		ctl_set_mask(lun->prevent, initidx);
5299		lun->prevent_count++;
5300	} else if ((cdb->how & PR_PREVENT) == 0 &&
5301	    ctl_is_set(lun->prevent, initidx)) {
5302		ctl_clear_mask(lun->prevent, initidx);
5303		lun->prevent_count--;
5304	}
5305	mtx_unlock(&lun->lun_lock);
5306	retval = lun->backend->config_write((union ctl_io *)ctsio);
5307	return (retval);
5308}
5309
5310/*
5311 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5312 * we don't really do anything with the LBA and length fields if the user
5313 * passes them in.  Instead we'll just flush out the cache for the entire
5314 * LUN.
5315 */
5316int
5317ctl_sync_cache(struct ctl_scsiio *ctsio)
5318{
5319	struct ctl_lun *lun;
5320	struct ctl_softc *softc;
5321	struct ctl_lba_len_flags *lbalen;
5322	uint64_t starting_lba;
5323	uint32_t block_count;
5324	int retval;
5325	uint8_t byte2;
5326
5327	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5328
5329	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5330	softc = lun->ctl_softc;
5331	retval = 0;
5332
5333	switch (ctsio->cdb[0]) {
5334	case SYNCHRONIZE_CACHE: {
5335		struct scsi_sync_cache *cdb;
5336		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5337
5338		starting_lba = scsi_4btoul(cdb->begin_lba);
5339		block_count = scsi_2btoul(cdb->lb_count);
5340		byte2 = cdb->byte2;
5341		break;
5342	}
5343	case SYNCHRONIZE_CACHE_16: {
5344		struct scsi_sync_cache_16 *cdb;
5345		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5346
5347		starting_lba = scsi_8btou64(cdb->begin_lba);
5348		block_count = scsi_4btoul(cdb->lb_count);
5349		byte2 = cdb->byte2;
5350		break;
5351	}
5352	default:
5353		ctl_set_invalid_opcode(ctsio);
5354		ctl_done((union ctl_io *)ctsio);
5355		goto bailout;
5356		break; /* NOTREACHED */
5357	}
5358
5359	/*
5360	 * We check the LBA and length, but don't do anything with them.
5361	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5362	 * get flushed.  This check will just help satisfy anyone who wants
5363	 * to see an error for an out of range LBA.
5364	 */
5365	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5366		ctl_set_lba_out_of_range(ctsio,
5367		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5368		ctl_done((union ctl_io *)ctsio);
5369		goto bailout;
5370	}
5371
5372	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5373	lbalen->lba = starting_lba;
5374	lbalen->len = block_count;
5375	lbalen->flags = byte2;
5376	retval = lun->backend->config_write((union ctl_io *)ctsio);
5377
5378bailout:
5379	return (retval);
5380}
5381
5382int
5383ctl_format(struct ctl_scsiio *ctsio)
5384{
5385	struct scsi_format *cdb;
5386	struct ctl_lun *lun;
5387	int length, defect_list_len;
5388
5389	CTL_DEBUG_PRINT(("ctl_format\n"));
5390
5391	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5392
5393	cdb = (struct scsi_format *)ctsio->cdb;
5394
5395	length = 0;
5396	if (cdb->byte2 & SF_FMTDATA) {
5397		if (cdb->byte2 & SF_LONGLIST)
5398			length = sizeof(struct scsi_format_header_long);
5399		else
5400			length = sizeof(struct scsi_format_header_short);
5401	}
5402
5403	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5404	 && (length > 0)) {
5405		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5406		ctsio->kern_data_len = length;
5407		ctsio->kern_total_len = length;
5408		ctsio->kern_data_resid = 0;
5409		ctsio->kern_rel_offset = 0;
5410		ctsio->kern_sg_entries = 0;
5411		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5412		ctsio->be_move_done = ctl_config_move_done;
5413		ctl_datamove((union ctl_io *)ctsio);
5414
5415		return (CTL_RETVAL_COMPLETE);
5416	}
5417
5418	defect_list_len = 0;
5419
5420	if (cdb->byte2 & SF_FMTDATA) {
5421		if (cdb->byte2 & SF_LONGLIST) {
5422			struct scsi_format_header_long *header;
5423
5424			header = (struct scsi_format_header_long *)
5425				ctsio->kern_data_ptr;
5426
5427			defect_list_len = scsi_4btoul(header->defect_list_len);
5428			if (defect_list_len != 0) {
5429				ctl_set_invalid_field(ctsio,
5430						      /*sks_valid*/ 1,
5431						      /*command*/ 0,
5432						      /*field*/ 2,
5433						      /*bit_valid*/ 0,
5434						      /*bit*/ 0);
5435				goto bailout;
5436			}
5437		} else {
5438			struct scsi_format_header_short *header;
5439
5440			header = (struct scsi_format_header_short *)
5441				ctsio->kern_data_ptr;
5442
5443			defect_list_len = scsi_2btoul(header->defect_list_len);
5444			if (defect_list_len != 0) {
5445				ctl_set_invalid_field(ctsio,
5446						      /*sks_valid*/ 1,
5447						      /*command*/ 0,
5448						      /*field*/ 2,
5449						      /*bit_valid*/ 0,
5450						      /*bit*/ 0);
5451				goto bailout;
5452			}
5453		}
5454	}
5455
5456	ctl_set_success(ctsio);
5457bailout:
5458
5459	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5460		free(ctsio->kern_data_ptr, M_CTL);
5461		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5462	}
5463
5464	ctl_done((union ctl_io *)ctsio);
5465	return (CTL_RETVAL_COMPLETE);
5466}
5467
5468int
5469ctl_read_buffer(struct ctl_scsiio *ctsio)
5470{
5471	struct ctl_lun *lun;
5472	uint64_t buffer_offset;
5473	uint32_t len;
5474	uint8_t byte2;
5475	static uint8_t descr[4];
5476	static uint8_t echo_descr[4] = { 0 };
5477
5478	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5479	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5480	switch (ctsio->cdb[0]) {
5481	case READ_BUFFER: {
5482		struct scsi_read_buffer *cdb;
5483
5484		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5485		buffer_offset = scsi_3btoul(cdb->offset);
5486		len = scsi_3btoul(cdb->length);
5487		byte2 = cdb->byte2;
5488		break;
5489	}
5490	case READ_BUFFER_16: {
5491		struct scsi_read_buffer_16 *cdb;
5492
5493		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5494		buffer_offset = scsi_8btou64(cdb->offset);
5495		len = scsi_4btoul(cdb->length);
5496		byte2 = cdb->byte2;
5497		break;
5498	}
5499	default: /* This shouldn't happen. */
5500		ctl_set_invalid_opcode(ctsio);
5501		ctl_done((union ctl_io *)ctsio);
5502		return (CTL_RETVAL_COMPLETE);
5503	}
5504
5505	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5506	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5507		ctl_set_invalid_field(ctsio,
5508				      /*sks_valid*/ 1,
5509				      /*command*/ 1,
5510				      /*field*/ 6,
5511				      /*bit_valid*/ 0,
5512				      /*bit*/ 0);
5513		ctl_done((union ctl_io *)ctsio);
5514		return (CTL_RETVAL_COMPLETE);
5515	}
5516
5517	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5518		descr[0] = 0;
5519		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5520		ctsio->kern_data_ptr = descr;
5521		len = min(len, sizeof(descr));
5522	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5523		ctsio->kern_data_ptr = echo_descr;
5524		len = min(len, sizeof(echo_descr));
5525	} else {
5526		if (lun->write_buffer == NULL) {
5527			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5528			    M_CTL, M_WAITOK);
5529		}
5530		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5531	}
5532	ctsio->kern_data_len = len;
5533	ctsio->kern_total_len = len;
5534	ctsio->kern_data_resid = 0;
5535	ctsio->kern_rel_offset = 0;
5536	ctsio->kern_sg_entries = 0;
5537	ctl_set_success(ctsio);
5538	ctsio->be_move_done = ctl_config_move_done;
5539	ctl_datamove((union ctl_io *)ctsio);
5540	return (CTL_RETVAL_COMPLETE);
5541}
5542
5543int
5544ctl_write_buffer(struct ctl_scsiio *ctsio)
5545{
5546	struct scsi_write_buffer *cdb;
5547	struct ctl_lun *lun;
5548	int buffer_offset, len;
5549
5550	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5551
5552	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5553	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5554
5555	len = scsi_3btoul(cdb->length);
5556	buffer_offset = scsi_3btoul(cdb->offset);
5557
5558	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5559		ctl_set_invalid_field(ctsio,
5560				      /*sks_valid*/ 1,
5561				      /*command*/ 1,
5562				      /*field*/ 6,
5563				      /*bit_valid*/ 0,
5564				      /*bit*/ 0);
5565		ctl_done((union ctl_io *)ctsio);
5566		return (CTL_RETVAL_COMPLETE);
5567	}
5568
5569	/*
5570	 * If we've got a kernel request that hasn't been malloced yet,
5571	 * malloc it and tell the caller the data buffer is here.
5572	 */
5573	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5574		if (lun->write_buffer == NULL) {
5575			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5576			    M_CTL, M_WAITOK);
5577		}
5578		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5579		ctsio->kern_data_len = len;
5580		ctsio->kern_total_len = len;
5581		ctsio->kern_data_resid = 0;
5582		ctsio->kern_rel_offset = 0;
5583		ctsio->kern_sg_entries = 0;
5584		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5585		ctsio->be_move_done = ctl_config_move_done;
5586		ctl_datamove((union ctl_io *)ctsio);
5587
5588		return (CTL_RETVAL_COMPLETE);
5589	}
5590
5591	ctl_set_success(ctsio);
5592	ctl_done((union ctl_io *)ctsio);
5593	return (CTL_RETVAL_COMPLETE);
5594}
5595
5596int
5597ctl_write_same(struct ctl_scsiio *ctsio)
5598{
5599	struct ctl_lun *lun;
5600	struct ctl_lba_len_flags *lbalen;
5601	uint64_t lba;
5602	uint32_t num_blocks;
5603	int len, retval;
5604	uint8_t byte2;
5605
5606	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5607
5608	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5609
5610	switch (ctsio->cdb[0]) {
5611	case WRITE_SAME_10: {
5612		struct scsi_write_same_10 *cdb;
5613
5614		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5615
5616		lba = scsi_4btoul(cdb->addr);
5617		num_blocks = scsi_2btoul(cdb->length);
5618		byte2 = cdb->byte2;
5619		break;
5620	}
5621	case WRITE_SAME_16: {
5622		struct scsi_write_same_16 *cdb;
5623
5624		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5625
5626		lba = scsi_8btou64(cdb->addr);
5627		num_blocks = scsi_4btoul(cdb->length);
5628		byte2 = cdb->byte2;
5629		break;
5630	}
5631	default:
5632		/*
5633		 * We got a command we don't support.  This shouldn't
5634		 * happen, commands should be filtered out above us.
5635		 */
5636		ctl_set_invalid_opcode(ctsio);
5637		ctl_done((union ctl_io *)ctsio);
5638
5639		return (CTL_RETVAL_COMPLETE);
5640		break; /* NOTREACHED */
5641	}
5642
5643	/* ANCHOR flag can be used only together with UNMAP */
5644	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5645		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5646		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5647		ctl_done((union ctl_io *)ctsio);
5648		return (CTL_RETVAL_COMPLETE);
5649	}
5650
5651	/*
5652	 * The first check is to make sure we're in bounds, the second
5653	 * check is to catch wrap-around problems.  If the lba + num blocks
5654	 * is less than the lba, then we've wrapped around and the block
5655	 * range is invalid anyway.
5656	 */
5657	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5658	 || ((lba + num_blocks) < lba)) {
5659		ctl_set_lba_out_of_range(ctsio,
5660		    MAX(lba, lun->be_lun->maxlba + 1));
5661		ctl_done((union ctl_io *)ctsio);
5662		return (CTL_RETVAL_COMPLETE);
5663	}
5664
5665	/* Zero number of blocks means "to the last logical block" */
5666	if (num_blocks == 0) {
5667		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5668			ctl_set_invalid_field(ctsio,
5669					      /*sks_valid*/ 0,
5670					      /*command*/ 1,
5671					      /*field*/ 0,
5672					      /*bit_valid*/ 0,
5673					      /*bit*/ 0);
5674			ctl_done((union ctl_io *)ctsio);
5675			return (CTL_RETVAL_COMPLETE);
5676		}
5677		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5678	}
5679
5680	len = lun->be_lun->blocksize;
5681
5682	/*
5683	 * If we've got a kernel request that hasn't been malloced yet,
5684	 * malloc it and tell the caller the data buffer is here.
5685	 */
5686	if ((byte2 & SWS_NDOB) == 0 &&
5687	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5688		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5689		ctsio->kern_data_len = len;
5690		ctsio->kern_total_len = len;
5691		ctsio->kern_data_resid = 0;
5692		ctsio->kern_rel_offset = 0;
5693		ctsio->kern_sg_entries = 0;
5694		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5695		ctsio->be_move_done = ctl_config_move_done;
5696		ctl_datamove((union ctl_io *)ctsio);
5697
5698		return (CTL_RETVAL_COMPLETE);
5699	}
5700
5701	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5702	lbalen->lba = lba;
5703	lbalen->len = num_blocks;
5704	lbalen->flags = byte2;
5705	retval = lun->backend->config_write((union ctl_io *)ctsio);
5706
5707	return (retval);
5708}
5709
5710int
5711ctl_unmap(struct ctl_scsiio *ctsio)
5712{
5713	struct ctl_lun *lun;
5714	struct scsi_unmap *cdb;
5715	struct ctl_ptr_len_flags *ptrlen;
5716	struct scsi_unmap_header *hdr;
5717	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5718	uint64_t lba;
5719	uint32_t num_blocks;
5720	int len, retval;
5721	uint8_t byte2;
5722
5723	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5724
5725	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5726	cdb = (struct scsi_unmap *)ctsio->cdb;
5727
5728	len = scsi_2btoul(cdb->length);
5729	byte2 = cdb->byte2;
5730
5731	/*
5732	 * If we've got a kernel request that hasn't been malloced yet,
5733	 * malloc it and tell the caller the data buffer is here.
5734	 */
5735	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5736		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5737		ctsio->kern_data_len = len;
5738		ctsio->kern_total_len = len;
5739		ctsio->kern_data_resid = 0;
5740		ctsio->kern_rel_offset = 0;
5741		ctsio->kern_sg_entries = 0;
5742		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5743		ctsio->be_move_done = ctl_config_move_done;
5744		ctl_datamove((union ctl_io *)ctsio);
5745
5746		return (CTL_RETVAL_COMPLETE);
5747	}
5748
5749	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5750	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5751	if (len < sizeof (*hdr) ||
5752	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5753	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5754	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5755		ctl_set_invalid_field(ctsio,
5756				      /*sks_valid*/ 0,
5757				      /*command*/ 0,
5758				      /*field*/ 0,
5759				      /*bit_valid*/ 0,
5760				      /*bit*/ 0);
5761		goto done;
5762	}
5763	len = scsi_2btoul(hdr->desc_length);
5764	buf = (struct scsi_unmap_desc *)(hdr + 1);
5765	end = buf + len / sizeof(*buf);
5766
5767	endnz = buf;
5768	for (range = buf; range < end; range++) {
5769		lba = scsi_8btou64(range->lba);
5770		num_blocks = scsi_4btoul(range->length);
5771		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5772		 || ((lba + num_blocks) < lba)) {
5773			ctl_set_lba_out_of_range(ctsio,
5774			    MAX(lba, lun->be_lun->maxlba + 1));
5775			ctl_done((union ctl_io *)ctsio);
5776			return (CTL_RETVAL_COMPLETE);
5777		}
5778		if (num_blocks != 0)
5779			endnz = range + 1;
5780	}
5781
5782	/*
5783	 * Block backend can not handle zero last range.
5784	 * Filter it out and return if there is nothing left.
5785	 */
5786	len = (uint8_t *)endnz - (uint8_t *)buf;
5787	if (len == 0) {
5788		ctl_set_success(ctsio);
5789		goto done;
5790	}
5791
5792	mtx_lock(&lun->lun_lock);
5793	ptrlen = (struct ctl_ptr_len_flags *)
5794	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5795	ptrlen->ptr = (void *)buf;
5796	ptrlen->len = len;
5797	ptrlen->flags = byte2;
5798	ctl_check_blocked(lun);
5799	mtx_unlock(&lun->lun_lock);
5800
5801	retval = lun->backend->config_write((union ctl_io *)ctsio);
5802	return (retval);
5803
5804done:
5805	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5806		free(ctsio->kern_data_ptr, M_CTL);
5807		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5808	}
5809	ctl_done((union ctl_io *)ctsio);
5810	return (CTL_RETVAL_COMPLETE);
5811}
5812
5813int
5814ctl_default_page_handler(struct ctl_scsiio *ctsio,
5815			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5816{
5817	struct ctl_lun *lun;
5818	uint8_t *current_cp, *saved_cp;
5819	int set_ua;
5820	uint32_t initidx;
5821
5822	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5823	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5824	set_ua = 0;
5825
5826	current_cp = (page_index->page_data + (page_index->page_len *
5827	    CTL_PAGE_CURRENT));
5828	saved_cp = (page_index->page_data + (page_index->page_len *
5829	    CTL_PAGE_SAVED));
5830
5831	mtx_lock(&lun->lun_lock);
5832	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5833		memcpy(current_cp, page_ptr, page_index->page_len);
5834		memcpy(saved_cp, page_ptr, page_index->page_len);
5835		set_ua = 1;
5836	}
5837	if (set_ua != 0)
5838		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5839	mtx_unlock(&lun->lun_lock);
5840	if (set_ua) {
5841		ctl_isc_announce_mode(lun,
5842		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5843		    page_index->page_code, page_index->subpage);
5844	}
5845	return (CTL_RETVAL_COMPLETE);
5846}
5847
5848static void
5849ctl_ie_timer(void *arg)
5850{
5851	struct ctl_lun *lun = arg;
5852	uint64_t t;
5853
5854	if (lun->ie_asc == 0)
5855		return;
5856
5857	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5858		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5859	else
5860		lun->ie_reported = 0;
5861
5862	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5863		lun->ie_reportcnt++;
5864		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5865		if (t == 0 || t == UINT32_MAX)
5866			t = 3000;  /* 5 min */
5867		callout_schedule(&lun->ie_callout, t * hz / 10);
5868	}
5869}
5870
5871int
5872ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5873			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5874{
5875	struct scsi_info_exceptions_page *pg;
5876	struct ctl_lun *lun;
5877	uint64_t t;
5878
5879	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5880
5881	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5882	pg = (struct scsi_info_exceptions_page *)page_ptr;
5883	mtx_lock(&lun->lun_lock);
5884	if (pg->info_flags & SIEP_FLAGS_TEST) {
5885		lun->ie_asc = 0x5d;
5886		lun->ie_ascq = 0xff;
5887		if (pg->mrie == SIEP_MRIE_UA) {
5888			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5889			lun->ie_reported = 1;
5890		} else {
5891			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5892			lun->ie_reported = -1;
5893		}
5894		lun->ie_reportcnt = 1;
5895		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5896			lun->ie_reportcnt++;
5897			t = scsi_4btoul(pg->interval_timer);
5898			if (t == 0 || t == UINT32_MAX)
5899				t = 3000;  /* 5 min */
5900			callout_reset(&lun->ie_callout, t * hz / 10,
5901			    ctl_ie_timer, lun);
5902		}
5903	} else {
5904		lun->ie_asc = 0;
5905		lun->ie_ascq = 0;
5906		lun->ie_reported = 1;
5907		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5908		lun->ie_reportcnt = UINT32_MAX;
5909		callout_stop(&lun->ie_callout);
5910	}
5911	mtx_unlock(&lun->lun_lock);
5912	return (CTL_RETVAL_COMPLETE);
5913}
5914
5915static int
5916ctl_do_mode_select(union ctl_io *io)
5917{
5918	struct scsi_mode_page_header *page_header;
5919	struct ctl_page_index *page_index;
5920	struct ctl_scsiio *ctsio;
5921	int page_len, page_len_offset, page_len_size;
5922	union ctl_modepage_info *modepage_info;
5923	struct ctl_lun *lun;
5924	int *len_left, *len_used;
5925	int retval, i;
5926
5927	ctsio = &io->scsiio;
5928	page_index = NULL;
5929	page_len = 0;
5930	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5931
5932	modepage_info = (union ctl_modepage_info *)
5933		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5934	len_left = &modepage_info->header.len_left;
5935	len_used = &modepage_info->header.len_used;
5936
5937do_next_page:
5938
5939	page_header = (struct scsi_mode_page_header *)
5940		(ctsio->kern_data_ptr + *len_used);
5941
5942	if (*len_left == 0) {
5943		free(ctsio->kern_data_ptr, M_CTL);
5944		ctl_set_success(ctsio);
5945		ctl_done((union ctl_io *)ctsio);
5946		return (CTL_RETVAL_COMPLETE);
5947	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5948
5949		free(ctsio->kern_data_ptr, M_CTL);
5950		ctl_set_param_len_error(ctsio);
5951		ctl_done((union ctl_io *)ctsio);
5952		return (CTL_RETVAL_COMPLETE);
5953
5954	} else if ((page_header->page_code & SMPH_SPF)
5955		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5956
5957		free(ctsio->kern_data_ptr, M_CTL);
5958		ctl_set_param_len_error(ctsio);
5959		ctl_done((union ctl_io *)ctsio);
5960		return (CTL_RETVAL_COMPLETE);
5961	}
5962
5963
5964	/*
5965	 * XXX KDM should we do something with the block descriptor?
5966	 */
5967	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5968		page_index = &lun->mode_pages.index[i];
5969		if (lun->be_lun->lun_type == T_DIRECT &&
5970		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5971			continue;
5972		if (lun->be_lun->lun_type == T_PROCESSOR &&
5973		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5974			continue;
5975		if (lun->be_lun->lun_type == T_CDROM &&
5976		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5977			continue;
5978
5979		if ((page_index->page_code & SMPH_PC_MASK) !=
5980		    (page_header->page_code & SMPH_PC_MASK))
5981			continue;
5982
5983		/*
5984		 * If neither page has a subpage code, then we've got a
5985		 * match.
5986		 */
5987		if (((page_index->page_code & SMPH_SPF) == 0)
5988		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5989			page_len = page_header->page_length;
5990			break;
5991		}
5992
5993		/*
5994		 * If both pages have subpages, then the subpage numbers
5995		 * have to match.
5996		 */
5997		if ((page_index->page_code & SMPH_SPF)
5998		  && (page_header->page_code & SMPH_SPF)) {
5999			struct scsi_mode_page_header_sp *sph;
6000
6001			sph = (struct scsi_mode_page_header_sp *)page_header;
6002			if (page_index->subpage == sph->subpage) {
6003				page_len = scsi_2btoul(sph->page_length);
6004				break;
6005			}
6006		}
6007	}
6008
6009	/*
6010	 * If we couldn't find the page, or if we don't have a mode select
6011	 * handler for it, send back an error to the user.
6012	 */
6013	if ((i >= CTL_NUM_MODE_PAGES)
6014	 || (page_index->select_handler == NULL)) {
6015		ctl_set_invalid_field(ctsio,
6016				      /*sks_valid*/ 1,
6017				      /*command*/ 0,
6018				      /*field*/ *len_used,
6019				      /*bit_valid*/ 0,
6020				      /*bit*/ 0);
6021		free(ctsio->kern_data_ptr, M_CTL);
6022		ctl_done((union ctl_io *)ctsio);
6023		return (CTL_RETVAL_COMPLETE);
6024	}
6025
6026	if (page_index->page_code & SMPH_SPF) {
6027		page_len_offset = 2;
6028		page_len_size = 2;
6029	} else {
6030		page_len_size = 1;
6031		page_len_offset = 1;
6032	}
6033
6034	/*
6035	 * If the length the initiator gives us isn't the one we specify in
6036	 * the mode page header, or if they didn't specify enough data in
6037	 * the CDB to avoid truncating this page, kick out the request.
6038	 */
6039	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6040		ctl_set_invalid_field(ctsio,
6041				      /*sks_valid*/ 1,
6042				      /*command*/ 0,
6043				      /*field*/ *len_used + page_len_offset,
6044				      /*bit_valid*/ 0,
6045				      /*bit*/ 0);
6046		free(ctsio->kern_data_ptr, M_CTL);
6047		ctl_done((union ctl_io *)ctsio);
6048		return (CTL_RETVAL_COMPLETE);
6049	}
6050	if (*len_left < page_index->page_len) {
6051		free(ctsio->kern_data_ptr, M_CTL);
6052		ctl_set_param_len_error(ctsio);
6053		ctl_done((union ctl_io *)ctsio);
6054		return (CTL_RETVAL_COMPLETE);
6055	}
6056
6057	/*
6058	 * Run through the mode page, checking to make sure that the bits
6059	 * the user changed are actually legal for him to change.
6060	 */
6061	for (i = 0; i < page_index->page_len; i++) {
6062		uint8_t *user_byte, *change_mask, *current_byte;
6063		int bad_bit;
6064		int j;
6065
6066		user_byte = (uint8_t *)page_header + i;
6067		change_mask = page_index->page_data +
6068			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6069		current_byte = page_index->page_data +
6070			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6071
6072		/*
6073		 * Check to see whether the user set any bits in this byte
6074		 * that he is not allowed to set.
6075		 */
6076		if ((*user_byte & ~(*change_mask)) ==
6077		    (*current_byte & ~(*change_mask)))
6078			continue;
6079
6080		/*
6081		 * Go through bit by bit to determine which one is illegal.
6082		 */
6083		bad_bit = 0;
6084		for (j = 7; j >= 0; j--) {
6085			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6086			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6087				bad_bit = i;
6088				break;
6089			}
6090		}
6091		ctl_set_invalid_field(ctsio,
6092				      /*sks_valid*/ 1,
6093				      /*command*/ 0,
6094				      /*field*/ *len_used + i,
6095				      /*bit_valid*/ 1,
6096				      /*bit*/ bad_bit);
6097		free(ctsio->kern_data_ptr, M_CTL);
6098		ctl_done((union ctl_io *)ctsio);
6099		return (CTL_RETVAL_COMPLETE);
6100	}
6101
6102	/*
6103	 * Decrement these before we call the page handler, since we may
6104	 * end up getting called back one way or another before the handler
6105	 * returns to this context.
6106	 */
6107	*len_left -= page_index->page_len;
6108	*len_used += page_index->page_len;
6109
6110	retval = page_index->select_handler(ctsio, page_index,
6111					    (uint8_t *)page_header);
6112
6113	/*
6114	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6115	 * wait until this queued command completes to finish processing
6116	 * the mode page.  If it returns anything other than
6117	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6118	 * already set the sense information, freed the data pointer, and
6119	 * completed the io for us.
6120	 */
6121	if (retval != CTL_RETVAL_COMPLETE)
6122		goto bailout_no_done;
6123
6124	/*
6125	 * If the initiator sent us more than one page, parse the next one.
6126	 */
6127	if (*len_left > 0)
6128		goto do_next_page;
6129
6130	ctl_set_success(ctsio);
6131	free(ctsio->kern_data_ptr, M_CTL);
6132	ctl_done((union ctl_io *)ctsio);
6133
6134bailout_no_done:
6135
6136	return (CTL_RETVAL_COMPLETE);
6137
6138}
6139
6140int
6141ctl_mode_select(struct ctl_scsiio *ctsio)
6142{
6143	int param_len, pf, sp;
6144	int header_size, bd_len;
6145	union ctl_modepage_info *modepage_info;
6146
6147	switch (ctsio->cdb[0]) {
6148	case MODE_SELECT_6: {
6149		struct scsi_mode_select_6 *cdb;
6150
6151		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6152
6153		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6154		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6155		param_len = cdb->length;
6156		header_size = sizeof(struct scsi_mode_header_6);
6157		break;
6158	}
6159	case MODE_SELECT_10: {
6160		struct scsi_mode_select_10 *cdb;
6161
6162		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6163
6164		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6165		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6166		param_len = scsi_2btoul(cdb->length);
6167		header_size = sizeof(struct scsi_mode_header_10);
6168		break;
6169	}
6170	default:
6171		ctl_set_invalid_opcode(ctsio);
6172		ctl_done((union ctl_io *)ctsio);
6173		return (CTL_RETVAL_COMPLETE);
6174	}
6175
6176	/*
6177	 * From SPC-3:
6178	 * "A parameter list length of zero indicates that the Data-Out Buffer
6179	 * shall be empty. This condition shall not be considered as an error."
6180	 */
6181	if (param_len == 0) {
6182		ctl_set_success(ctsio);
6183		ctl_done((union ctl_io *)ctsio);
6184		return (CTL_RETVAL_COMPLETE);
6185	}
6186
6187	/*
6188	 * Since we'll hit this the first time through, prior to
6189	 * allocation, we don't need to free a data buffer here.
6190	 */
6191	if (param_len < header_size) {
6192		ctl_set_param_len_error(ctsio);
6193		ctl_done((union ctl_io *)ctsio);
6194		return (CTL_RETVAL_COMPLETE);
6195	}
6196
6197	/*
6198	 * Allocate the data buffer and grab the user's data.  In theory,
6199	 * we shouldn't have to sanity check the parameter list length here
6200	 * because the maximum size is 64K.  We should be able to malloc
6201	 * that much without too many problems.
6202	 */
6203	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6204		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6205		ctsio->kern_data_len = param_len;
6206		ctsio->kern_total_len = param_len;
6207		ctsio->kern_data_resid = 0;
6208		ctsio->kern_rel_offset = 0;
6209		ctsio->kern_sg_entries = 0;
6210		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6211		ctsio->be_move_done = ctl_config_move_done;
6212		ctl_datamove((union ctl_io *)ctsio);
6213
6214		return (CTL_RETVAL_COMPLETE);
6215	}
6216
6217	switch (ctsio->cdb[0]) {
6218	case MODE_SELECT_6: {
6219		struct scsi_mode_header_6 *mh6;
6220
6221		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6222		bd_len = mh6->blk_desc_len;
6223		break;
6224	}
6225	case MODE_SELECT_10: {
6226		struct scsi_mode_header_10 *mh10;
6227
6228		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6229		bd_len = scsi_2btoul(mh10->blk_desc_len);
6230		break;
6231	}
6232	default:
6233		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6234	}
6235
6236	if (param_len < (header_size + bd_len)) {
6237		free(ctsio->kern_data_ptr, M_CTL);
6238		ctl_set_param_len_error(ctsio);
6239		ctl_done((union ctl_io *)ctsio);
6240		return (CTL_RETVAL_COMPLETE);
6241	}
6242
6243	/*
6244	 * Set the IO_CONT flag, so that if this I/O gets passed to
6245	 * ctl_config_write_done(), it'll get passed back to
6246	 * ctl_do_mode_select() for further processing, or completion if
6247	 * we're all done.
6248	 */
6249	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6250	ctsio->io_cont = ctl_do_mode_select;
6251
6252	modepage_info = (union ctl_modepage_info *)
6253		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6254	memset(modepage_info, 0, sizeof(*modepage_info));
6255	modepage_info->header.len_left = param_len - header_size - bd_len;
6256	modepage_info->header.len_used = header_size + bd_len;
6257
6258	return (ctl_do_mode_select((union ctl_io *)ctsio));
6259}
6260
6261int
6262ctl_mode_sense(struct ctl_scsiio *ctsio)
6263{
6264	struct ctl_lun *lun;
6265	int pc, page_code, dbd, llba, subpage;
6266	int alloc_len, page_len, header_len, total_len;
6267	struct scsi_mode_block_descr *block_desc;
6268	struct ctl_page_index *page_index;
6269
6270	dbd = 0;
6271	llba = 0;
6272	block_desc = NULL;
6273
6274	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6275
6276	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6277	switch (ctsio->cdb[0]) {
6278	case MODE_SENSE_6: {
6279		struct scsi_mode_sense_6 *cdb;
6280
6281		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6282
6283		header_len = sizeof(struct scsi_mode_hdr_6);
6284		if (cdb->byte2 & SMS_DBD)
6285			dbd = 1;
6286		else
6287			header_len += sizeof(struct scsi_mode_block_descr);
6288
6289		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6290		page_code = cdb->page & SMS_PAGE_CODE;
6291		subpage = cdb->subpage;
6292		alloc_len = cdb->length;
6293		break;
6294	}
6295	case MODE_SENSE_10: {
6296		struct scsi_mode_sense_10 *cdb;
6297
6298		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6299
6300		header_len = sizeof(struct scsi_mode_hdr_10);
6301
6302		if (cdb->byte2 & SMS_DBD)
6303			dbd = 1;
6304		else
6305			header_len += sizeof(struct scsi_mode_block_descr);
6306		if (cdb->byte2 & SMS10_LLBAA)
6307			llba = 1;
6308		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6309		page_code = cdb->page & SMS_PAGE_CODE;
6310		subpage = cdb->subpage;
6311		alloc_len = scsi_2btoul(cdb->length);
6312		break;
6313	}
6314	default:
6315		ctl_set_invalid_opcode(ctsio);
6316		ctl_done((union ctl_io *)ctsio);
6317		return (CTL_RETVAL_COMPLETE);
6318		break; /* NOTREACHED */
6319	}
6320
6321	/*
6322	 * We have to make a first pass through to calculate the size of
6323	 * the pages that match the user's query.  Then we allocate enough
6324	 * memory to hold it, and actually copy the data into the buffer.
6325	 */
6326	switch (page_code) {
6327	case SMS_ALL_PAGES_PAGE: {
6328		u_int i;
6329
6330		page_len = 0;
6331
6332		/*
6333		 * At the moment, values other than 0 and 0xff here are
6334		 * reserved according to SPC-3.
6335		 */
6336		if ((subpage != SMS_SUBPAGE_PAGE_0)
6337		 && (subpage != SMS_SUBPAGE_ALL)) {
6338			ctl_set_invalid_field(ctsio,
6339					      /*sks_valid*/ 1,
6340					      /*command*/ 1,
6341					      /*field*/ 3,
6342					      /*bit_valid*/ 0,
6343					      /*bit*/ 0);
6344			ctl_done((union ctl_io *)ctsio);
6345			return (CTL_RETVAL_COMPLETE);
6346		}
6347
6348		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6349			page_index = &lun->mode_pages.index[i];
6350
6351			/* Make sure the page is supported for this dev type */
6352			if (lun->be_lun->lun_type == T_DIRECT &&
6353			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6354				continue;
6355			if (lun->be_lun->lun_type == T_PROCESSOR &&
6356			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6357				continue;
6358			if (lun->be_lun->lun_type == T_CDROM &&
6359			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6360				continue;
6361
6362			/*
6363			 * We don't use this subpage if the user didn't
6364			 * request all subpages.
6365			 */
6366			if ((page_index->subpage != 0)
6367			 && (subpage == SMS_SUBPAGE_PAGE_0))
6368				continue;
6369
6370#if 0
6371			printf("found page %#x len %d\n",
6372			       page_index->page_code & SMPH_PC_MASK,
6373			       page_index->page_len);
6374#endif
6375			page_len += page_index->page_len;
6376		}
6377		break;
6378	}
6379	default: {
6380		u_int i;
6381
6382		page_len = 0;
6383
6384		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6385			page_index = &lun->mode_pages.index[i];
6386
6387			/* Make sure the page is supported for this dev type */
6388			if (lun->be_lun->lun_type == T_DIRECT &&
6389			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6390				continue;
6391			if (lun->be_lun->lun_type == T_PROCESSOR &&
6392			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6393				continue;
6394			if (lun->be_lun->lun_type == T_CDROM &&
6395			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6396				continue;
6397
6398			/* Look for the right page code */
6399			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6400				continue;
6401
6402			/* Look for the right subpage or the subpage wildcard*/
6403			if ((page_index->subpage != subpage)
6404			 && (subpage != SMS_SUBPAGE_ALL))
6405				continue;
6406
6407#if 0
6408			printf("found page %#x len %d\n",
6409			       page_index->page_code & SMPH_PC_MASK,
6410			       page_index->page_len);
6411#endif
6412
6413			page_len += page_index->page_len;
6414		}
6415
6416		if (page_len == 0) {
6417			ctl_set_invalid_field(ctsio,
6418					      /*sks_valid*/ 1,
6419					      /*command*/ 1,
6420					      /*field*/ 2,
6421					      /*bit_valid*/ 1,
6422					      /*bit*/ 5);
6423			ctl_done((union ctl_io *)ctsio);
6424			return (CTL_RETVAL_COMPLETE);
6425		}
6426		break;
6427	}
6428	}
6429
6430	total_len = header_len + page_len;
6431#if 0
6432	printf("header_len = %d, page_len = %d, total_len = %d\n",
6433	       header_len, page_len, total_len);
6434#endif
6435
6436	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6437	ctsio->kern_sg_entries = 0;
6438	ctsio->kern_data_resid = 0;
6439	ctsio->kern_rel_offset = 0;
6440	if (total_len < alloc_len) {
6441		ctsio->residual = alloc_len - total_len;
6442		ctsio->kern_data_len = total_len;
6443		ctsio->kern_total_len = total_len;
6444	} else {
6445		ctsio->residual = 0;
6446		ctsio->kern_data_len = alloc_len;
6447		ctsio->kern_total_len = alloc_len;
6448	}
6449
6450	switch (ctsio->cdb[0]) {
6451	case MODE_SENSE_6: {
6452		struct scsi_mode_hdr_6 *header;
6453
6454		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6455
6456		header->datalen = MIN(total_len - 1, 254);
6457		if (lun->be_lun->lun_type == T_DIRECT) {
6458			header->dev_specific = 0x10; /* DPOFUA */
6459			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6460			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6461				header->dev_specific |= 0x80; /* WP */
6462		}
6463		if (dbd)
6464			header->block_descr_len = 0;
6465		else
6466			header->block_descr_len =
6467				sizeof(struct scsi_mode_block_descr);
6468		block_desc = (struct scsi_mode_block_descr *)&header[1];
6469		break;
6470	}
6471	case MODE_SENSE_10: {
6472		struct scsi_mode_hdr_10 *header;
6473		int datalen;
6474
6475		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6476
6477		datalen = MIN(total_len - 2, 65533);
6478		scsi_ulto2b(datalen, header->datalen);
6479		if (lun->be_lun->lun_type == T_DIRECT) {
6480			header->dev_specific = 0x10; /* DPOFUA */
6481			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6482			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6483				header->dev_specific |= 0x80; /* WP */
6484		}
6485		if (dbd)
6486			scsi_ulto2b(0, header->block_descr_len);
6487		else
6488			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6489				    header->block_descr_len);
6490		block_desc = (struct scsi_mode_block_descr *)&header[1];
6491		break;
6492	}
6493	default:
6494		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6495	}
6496
6497	/*
6498	 * If we've got a disk, use its blocksize in the block
6499	 * descriptor.  Otherwise, just set it to 0.
6500	 */
6501	if (dbd == 0) {
6502		if (lun->be_lun->lun_type == T_DIRECT)
6503			scsi_ulto3b(lun->be_lun->blocksize,
6504				    block_desc->block_len);
6505		else
6506			scsi_ulto3b(0, block_desc->block_len);
6507	}
6508
6509	switch (page_code) {
6510	case SMS_ALL_PAGES_PAGE: {
6511		int i, data_used;
6512
6513		data_used = header_len;
6514		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6515			struct ctl_page_index *page_index;
6516
6517			page_index = &lun->mode_pages.index[i];
6518			if (lun->be_lun->lun_type == T_DIRECT &&
6519			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6520				continue;
6521			if (lun->be_lun->lun_type == T_PROCESSOR &&
6522			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6523				continue;
6524			if (lun->be_lun->lun_type == T_CDROM &&
6525			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6526				continue;
6527
6528			/*
6529			 * We don't use this subpage if the user didn't
6530			 * request all subpages.  We already checked (above)
6531			 * to make sure the user only specified a subpage
6532			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6533			 */
6534			if ((page_index->subpage != 0)
6535			 && (subpage == SMS_SUBPAGE_PAGE_0))
6536				continue;
6537
6538			/*
6539			 * Call the handler, if it exists, to update the
6540			 * page to the latest values.
6541			 */
6542			if (page_index->sense_handler != NULL)
6543				page_index->sense_handler(ctsio, page_index,pc);
6544
6545			memcpy(ctsio->kern_data_ptr + data_used,
6546			       page_index->page_data +
6547			       (page_index->page_len * pc),
6548			       page_index->page_len);
6549			data_used += page_index->page_len;
6550		}
6551		break;
6552	}
6553	default: {
6554		int i, data_used;
6555
6556		data_used = header_len;
6557
6558		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6559			struct ctl_page_index *page_index;
6560
6561			page_index = &lun->mode_pages.index[i];
6562
6563			/* Look for the right page code */
6564			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6565				continue;
6566
6567			/* Look for the right subpage or the subpage wildcard*/
6568			if ((page_index->subpage != subpage)
6569			 && (subpage != SMS_SUBPAGE_ALL))
6570				continue;
6571
6572			/* Make sure the page is supported for this dev type */
6573			if (lun->be_lun->lun_type == T_DIRECT &&
6574			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6575				continue;
6576			if (lun->be_lun->lun_type == T_PROCESSOR &&
6577			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6578				continue;
6579			if (lun->be_lun->lun_type == T_CDROM &&
6580			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6581				continue;
6582
6583			/*
6584			 * Call the handler, if it exists, to update the
6585			 * page to the latest values.
6586			 */
6587			if (page_index->sense_handler != NULL)
6588				page_index->sense_handler(ctsio, page_index,pc);
6589
6590			memcpy(ctsio->kern_data_ptr + data_used,
6591			       page_index->page_data +
6592			       (page_index->page_len * pc),
6593			       page_index->page_len);
6594			data_used += page_index->page_len;
6595		}
6596		break;
6597	}
6598	}
6599
6600	ctl_set_success(ctsio);
6601	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6602	ctsio->be_move_done = ctl_config_move_done;
6603	ctl_datamove((union ctl_io *)ctsio);
6604	return (CTL_RETVAL_COMPLETE);
6605}
6606
6607int
6608ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6609			       struct ctl_page_index *page_index,
6610			       int pc)
6611{
6612	struct ctl_lun *lun;
6613	struct scsi_log_param_header *phdr;
6614	uint8_t *data;
6615	uint64_t val;
6616
6617	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6618	data = page_index->page_data;
6619
6620	if (lun->backend->lun_attr != NULL &&
6621	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6622	     != UINT64_MAX) {
6623		phdr = (struct scsi_log_param_header *)data;
6624		scsi_ulto2b(0x0001, phdr->param_code);
6625		phdr->param_control = SLP_LBIN | SLP_LP;
6626		phdr->param_len = 8;
6627		data = (uint8_t *)(phdr + 1);
6628		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6629		data[4] = 0x02; /* per-pool */
6630		data += phdr->param_len;
6631	}
6632
6633	if (lun->backend->lun_attr != NULL &&
6634	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6635	     != UINT64_MAX) {
6636		phdr = (struct scsi_log_param_header *)data;
6637		scsi_ulto2b(0x0002, phdr->param_code);
6638		phdr->param_control = SLP_LBIN | SLP_LP;
6639		phdr->param_len = 8;
6640		data = (uint8_t *)(phdr + 1);
6641		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6642		data[4] = 0x01; /* per-LUN */
6643		data += phdr->param_len;
6644	}
6645
6646	if (lun->backend->lun_attr != NULL &&
6647	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6648	     != UINT64_MAX) {
6649		phdr = (struct scsi_log_param_header *)data;
6650		scsi_ulto2b(0x00f1, phdr->param_code);
6651		phdr->param_control = SLP_LBIN | SLP_LP;
6652		phdr->param_len = 8;
6653		data = (uint8_t *)(phdr + 1);
6654		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6655		data[4] = 0x02; /* per-pool */
6656		data += phdr->param_len;
6657	}
6658
6659	if (lun->backend->lun_attr != NULL &&
6660	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6661	     != UINT64_MAX) {
6662		phdr = (struct scsi_log_param_header *)data;
6663		scsi_ulto2b(0x00f2, phdr->param_code);
6664		phdr->param_control = SLP_LBIN | SLP_LP;
6665		phdr->param_len = 8;
6666		data = (uint8_t *)(phdr + 1);
6667		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6668		data[4] = 0x02; /* per-pool */
6669		data += phdr->param_len;
6670	}
6671
6672	page_index->page_len = data - page_index->page_data;
6673	return (0);
6674}
6675
6676int
6677ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6678			       struct ctl_page_index *page_index,
6679			       int pc)
6680{
6681	struct ctl_lun *lun;
6682	struct stat_page *data;
6683	uint64_t rn, wn, rb, wb;
6684	struct bintime rt, wt;
6685	int i;
6686
6687	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6688	data = (struct stat_page *)page_index->page_data;
6689
6690	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6691	data->sap.hdr.param_control = SLP_LBIN;
6692	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6693	    sizeof(struct scsi_log_param_header);
6694	rn = wn = rb = wb = 0;
6695	bintime_clear(&rt);
6696	bintime_clear(&wt);
6697	for (i = 0; i < CTL_MAX_PORTS; i++) {
6698		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6699		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6700		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6701		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6702		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6703		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6704	}
6705	scsi_u64to8b(rn, data->sap.read_num);
6706	scsi_u64to8b(wn, data->sap.write_num);
6707	if (lun->stats.blocksize > 0) {
6708		scsi_u64to8b(wb / lun->stats.blocksize,
6709		    data->sap.recvieved_lba);
6710		scsi_u64to8b(rb / lun->stats.blocksize,
6711		    data->sap.transmitted_lba);
6712	}
6713	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6714	    data->sap.read_int);
6715	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6716	    data->sap.write_int);
6717	scsi_u64to8b(0, data->sap.weighted_num);
6718	scsi_u64to8b(0, data->sap.weighted_int);
6719	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6720	data->it.hdr.param_control = SLP_LBIN;
6721	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6722	    sizeof(struct scsi_log_param_header);
6723#ifdef CTL_TIME_IO
6724	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6725#endif
6726	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6727	data->it.hdr.param_control = SLP_LBIN;
6728	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6729	    sizeof(struct scsi_log_param_header);
6730	scsi_ulto4b(3, data->ti.exponent);
6731	scsi_ulto4b(1, data->ti.integer);
6732	return (0);
6733}
6734
6735int
6736ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6737			       struct ctl_page_index *page_index,
6738			       int pc)
6739{
6740	struct ctl_lun *lun;
6741	struct scsi_log_informational_exceptions *data;
6742
6743	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6744	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6745
6746	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6747	data->hdr.param_control = SLP_LBIN;
6748	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6749	    sizeof(struct scsi_log_param_header);
6750	data->ie_asc = lun->ie_asc;
6751	data->ie_ascq = lun->ie_ascq;
6752	data->temperature = 0xff;
6753	return (0);
6754}
6755
6756int
6757ctl_log_sense(struct ctl_scsiio *ctsio)
6758{
6759	struct ctl_lun *lun;
6760	int i, pc, page_code, subpage;
6761	int alloc_len, total_len;
6762	struct ctl_page_index *page_index;
6763	struct scsi_log_sense *cdb;
6764	struct scsi_log_header *header;
6765
6766	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6767
6768	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6769	cdb = (struct scsi_log_sense *)ctsio->cdb;
6770	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6771	page_code = cdb->page & SLS_PAGE_CODE;
6772	subpage = cdb->subpage;
6773	alloc_len = scsi_2btoul(cdb->length);
6774
6775	page_index = NULL;
6776	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6777		page_index = &lun->log_pages.index[i];
6778
6779		/* Look for the right page code */
6780		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6781			continue;
6782
6783		/* Look for the right subpage or the subpage wildcard*/
6784		if (page_index->subpage != subpage)
6785			continue;
6786
6787		break;
6788	}
6789	if (i >= CTL_NUM_LOG_PAGES) {
6790		ctl_set_invalid_field(ctsio,
6791				      /*sks_valid*/ 1,
6792				      /*command*/ 1,
6793				      /*field*/ 2,
6794				      /*bit_valid*/ 0,
6795				      /*bit*/ 0);
6796		ctl_done((union ctl_io *)ctsio);
6797		return (CTL_RETVAL_COMPLETE);
6798	}
6799
6800	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6801
6802	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6803	ctsio->kern_sg_entries = 0;
6804	ctsio->kern_data_resid = 0;
6805	ctsio->kern_rel_offset = 0;
6806	if (total_len < alloc_len) {
6807		ctsio->residual = alloc_len - total_len;
6808		ctsio->kern_data_len = total_len;
6809		ctsio->kern_total_len = total_len;
6810	} else {
6811		ctsio->residual = 0;
6812		ctsio->kern_data_len = alloc_len;
6813		ctsio->kern_total_len = alloc_len;
6814	}
6815
6816	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6817	header->page = page_index->page_code;
6818	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6819		header->page |= SL_DS;
6820	if (page_index->subpage) {
6821		header->page |= SL_SPF;
6822		header->subpage = page_index->subpage;
6823	}
6824	scsi_ulto2b(page_index->page_len, header->datalen);
6825
6826	/*
6827	 * Call the handler, if it exists, to update the
6828	 * page to the latest values.
6829	 */
6830	if (page_index->sense_handler != NULL)
6831		page_index->sense_handler(ctsio, page_index, pc);
6832
6833	memcpy(header + 1, page_index->page_data, page_index->page_len);
6834
6835	ctl_set_success(ctsio);
6836	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6837	ctsio->be_move_done = ctl_config_move_done;
6838	ctl_datamove((union ctl_io *)ctsio);
6839	return (CTL_RETVAL_COMPLETE);
6840}
6841
6842int
6843ctl_read_capacity(struct ctl_scsiio *ctsio)
6844{
6845	struct scsi_read_capacity *cdb;
6846	struct scsi_read_capacity_data *data;
6847	struct ctl_lun *lun;
6848	uint32_t lba;
6849
6850	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6851
6852	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6853
6854	lba = scsi_4btoul(cdb->addr);
6855	if (((cdb->pmi & SRC_PMI) == 0)
6856	 && (lba != 0)) {
6857		ctl_set_invalid_field(/*ctsio*/ ctsio,
6858				      /*sks_valid*/ 1,
6859				      /*command*/ 1,
6860				      /*field*/ 2,
6861				      /*bit_valid*/ 0,
6862				      /*bit*/ 0);
6863		ctl_done((union ctl_io *)ctsio);
6864		return (CTL_RETVAL_COMPLETE);
6865	}
6866
6867	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6868
6869	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6870	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6871	ctsio->residual = 0;
6872	ctsio->kern_data_len = sizeof(*data);
6873	ctsio->kern_total_len = sizeof(*data);
6874	ctsio->kern_data_resid = 0;
6875	ctsio->kern_rel_offset = 0;
6876	ctsio->kern_sg_entries = 0;
6877
6878	/*
6879	 * If the maximum LBA is greater than 0xfffffffe, the user must
6880	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6881	 * serivce action set.
6882	 */
6883	if (lun->be_lun->maxlba > 0xfffffffe)
6884		scsi_ulto4b(0xffffffff, data->addr);
6885	else
6886		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6887
6888	/*
6889	 * XXX KDM this may not be 512 bytes...
6890	 */
6891	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6892
6893	ctl_set_success(ctsio);
6894	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6895	ctsio->be_move_done = ctl_config_move_done;
6896	ctl_datamove((union ctl_io *)ctsio);
6897	return (CTL_RETVAL_COMPLETE);
6898}
6899
6900int
6901ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6902{
6903	struct scsi_read_capacity_16 *cdb;
6904	struct scsi_read_capacity_data_long *data;
6905	struct ctl_lun *lun;
6906	uint64_t lba;
6907	uint32_t alloc_len;
6908
6909	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6910
6911	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6912
6913	alloc_len = scsi_4btoul(cdb->alloc_len);
6914	lba = scsi_8btou64(cdb->addr);
6915
6916	if ((cdb->reladr & SRC16_PMI)
6917	 && (lba != 0)) {
6918		ctl_set_invalid_field(/*ctsio*/ ctsio,
6919				      /*sks_valid*/ 1,
6920				      /*command*/ 1,
6921				      /*field*/ 2,
6922				      /*bit_valid*/ 0,
6923				      /*bit*/ 0);
6924		ctl_done((union ctl_io *)ctsio);
6925		return (CTL_RETVAL_COMPLETE);
6926	}
6927
6928	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6929
6930	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6931	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6932
6933	if (sizeof(*data) < alloc_len) {
6934		ctsio->residual = alloc_len - sizeof(*data);
6935		ctsio->kern_data_len = sizeof(*data);
6936		ctsio->kern_total_len = sizeof(*data);
6937	} else {
6938		ctsio->residual = 0;
6939		ctsio->kern_data_len = alloc_len;
6940		ctsio->kern_total_len = alloc_len;
6941	}
6942	ctsio->kern_data_resid = 0;
6943	ctsio->kern_rel_offset = 0;
6944	ctsio->kern_sg_entries = 0;
6945
6946	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6947	/* XXX KDM this may not be 512 bytes... */
6948	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6949	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6950	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6951	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6952		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6953
6954	ctl_set_success(ctsio);
6955	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6956	ctsio->be_move_done = ctl_config_move_done;
6957	ctl_datamove((union ctl_io *)ctsio);
6958	return (CTL_RETVAL_COMPLETE);
6959}
6960
6961int
6962ctl_get_lba_status(struct ctl_scsiio *ctsio)
6963{
6964	struct scsi_get_lba_status *cdb;
6965	struct scsi_get_lba_status_data *data;
6966	struct ctl_lun *lun;
6967	struct ctl_lba_len_flags *lbalen;
6968	uint64_t lba;
6969	uint32_t alloc_len, total_len;
6970	int retval;
6971
6972	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6973
6974	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6975	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6976	lba = scsi_8btou64(cdb->addr);
6977	alloc_len = scsi_4btoul(cdb->alloc_len);
6978
6979	if (lba > lun->be_lun->maxlba) {
6980		ctl_set_lba_out_of_range(ctsio, lba);
6981		ctl_done((union ctl_io *)ctsio);
6982		return (CTL_RETVAL_COMPLETE);
6983	}
6984
6985	total_len = sizeof(*data) + sizeof(data->descr[0]);
6986	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6987	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6988
6989	if (total_len < alloc_len) {
6990		ctsio->residual = alloc_len - total_len;
6991		ctsio->kern_data_len = total_len;
6992		ctsio->kern_total_len = total_len;
6993	} else {
6994		ctsio->residual = 0;
6995		ctsio->kern_data_len = alloc_len;
6996		ctsio->kern_total_len = alloc_len;
6997	}
6998	ctsio->kern_data_resid = 0;
6999	ctsio->kern_rel_offset = 0;
7000	ctsio->kern_sg_entries = 0;
7001
7002	/* Fill dummy data in case backend can't tell anything. */
7003	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7004	scsi_u64to8b(lba, data->descr[0].addr);
7005	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7006	    data->descr[0].length);
7007	data->descr[0].status = 0; /* Mapped or unknown. */
7008
7009	ctl_set_success(ctsio);
7010	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7011	ctsio->be_move_done = ctl_config_move_done;
7012
7013	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7014	lbalen->lba = lba;
7015	lbalen->len = total_len;
7016	lbalen->flags = 0;
7017	retval = lun->backend->config_read((union ctl_io *)ctsio);
7018	return (CTL_RETVAL_COMPLETE);
7019}
7020
7021int
7022ctl_read_defect(struct ctl_scsiio *ctsio)
7023{
7024	struct scsi_read_defect_data_10 *ccb10;
7025	struct scsi_read_defect_data_12 *ccb12;
7026	struct scsi_read_defect_data_hdr_10 *data10;
7027	struct scsi_read_defect_data_hdr_12 *data12;
7028	uint32_t alloc_len, data_len;
7029	uint8_t format;
7030
7031	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7032
7033	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7034		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7035		format = ccb10->format;
7036		alloc_len = scsi_2btoul(ccb10->alloc_length);
7037		data_len = sizeof(*data10);
7038	} else {
7039		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7040		format = ccb12->format;
7041		alloc_len = scsi_4btoul(ccb12->alloc_length);
7042		data_len = sizeof(*data12);
7043	}
7044	if (alloc_len == 0) {
7045		ctl_set_success(ctsio);
7046		ctl_done((union ctl_io *)ctsio);
7047		return (CTL_RETVAL_COMPLETE);
7048	}
7049
7050	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7051	if (data_len < alloc_len) {
7052		ctsio->residual = alloc_len - data_len;
7053		ctsio->kern_data_len = data_len;
7054		ctsio->kern_total_len = data_len;
7055	} else {
7056		ctsio->residual = 0;
7057		ctsio->kern_data_len = alloc_len;
7058		ctsio->kern_total_len = alloc_len;
7059	}
7060	ctsio->kern_data_resid = 0;
7061	ctsio->kern_rel_offset = 0;
7062	ctsio->kern_sg_entries = 0;
7063
7064	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7065		data10 = (struct scsi_read_defect_data_hdr_10 *)
7066		    ctsio->kern_data_ptr;
7067		data10->format = format;
7068		scsi_ulto2b(0, data10->length);
7069	} else {
7070		data12 = (struct scsi_read_defect_data_hdr_12 *)
7071		    ctsio->kern_data_ptr;
7072		data12->format = format;
7073		scsi_ulto2b(0, data12->generation);
7074		scsi_ulto4b(0, data12->length);
7075	}
7076
7077	ctl_set_success(ctsio);
7078	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7079	ctsio->be_move_done = ctl_config_move_done;
7080	ctl_datamove((union ctl_io *)ctsio);
7081	return (CTL_RETVAL_COMPLETE);
7082}
7083
7084int
7085ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7086{
7087	struct scsi_maintenance_in *cdb;
7088	int retval;
7089	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7090	int num_ha_groups, num_target_ports, shared_group;
7091	struct ctl_lun *lun;
7092	struct ctl_softc *softc;
7093	struct ctl_port *port;
7094	struct scsi_target_group_data *rtg_ptr;
7095	struct scsi_target_group_data_extended *rtg_ext_ptr;
7096	struct scsi_target_port_group_descriptor *tpg_desc;
7097
7098	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7099
7100	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7101	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7102	softc = lun->ctl_softc;
7103
7104	retval = CTL_RETVAL_COMPLETE;
7105
7106	switch (cdb->byte2 & STG_PDF_MASK) {
7107	case STG_PDF_LENGTH:
7108		ext = 0;
7109		break;
7110	case STG_PDF_EXTENDED:
7111		ext = 1;
7112		break;
7113	default:
7114		ctl_set_invalid_field(/*ctsio*/ ctsio,
7115				      /*sks_valid*/ 1,
7116				      /*command*/ 1,
7117				      /*field*/ 2,
7118				      /*bit_valid*/ 1,
7119				      /*bit*/ 5);
7120		ctl_done((union ctl_io *)ctsio);
7121		return(retval);
7122	}
7123
7124	num_target_ports = 0;
7125	shared_group = (softc->is_single != 0);
7126	mtx_lock(&softc->ctl_lock);
7127	STAILQ_FOREACH(port, &softc->port_list, links) {
7128		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7129			continue;
7130		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7131			continue;
7132		num_target_ports++;
7133		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7134			shared_group = 1;
7135	}
7136	mtx_unlock(&softc->ctl_lock);
7137	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7138
7139	if (ext)
7140		total_len = sizeof(struct scsi_target_group_data_extended);
7141	else
7142		total_len = sizeof(struct scsi_target_group_data);
7143	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7144		(shared_group + num_ha_groups) +
7145	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7146
7147	alloc_len = scsi_4btoul(cdb->length);
7148
7149	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7150
7151	ctsio->kern_sg_entries = 0;
7152
7153	if (total_len < alloc_len) {
7154		ctsio->residual = alloc_len - total_len;
7155		ctsio->kern_data_len = total_len;
7156		ctsio->kern_total_len = total_len;
7157	} else {
7158		ctsio->residual = 0;
7159		ctsio->kern_data_len = alloc_len;
7160		ctsio->kern_total_len = alloc_len;
7161	}
7162	ctsio->kern_data_resid = 0;
7163	ctsio->kern_rel_offset = 0;
7164
7165	if (ext) {
7166		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7167		    ctsio->kern_data_ptr;
7168		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7169		rtg_ext_ptr->format_type = 0x10;
7170		rtg_ext_ptr->implicit_transition_time = 0;
7171		tpg_desc = &rtg_ext_ptr->groups[0];
7172	} else {
7173		rtg_ptr = (struct scsi_target_group_data *)
7174		    ctsio->kern_data_ptr;
7175		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7176		tpg_desc = &rtg_ptr->groups[0];
7177	}
7178
7179	mtx_lock(&softc->ctl_lock);
7180	pg = softc->port_min / softc->port_cnt;
7181	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7182		/* Some shelf is known to be primary. */
7183		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7184			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7185		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7186			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7187		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7188			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7189		else
7190			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7191		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7192			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7193		} else {
7194			ts = os;
7195			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7196		}
7197	} else {
7198		/* No known primary shelf. */
7199		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7200			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7201			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7202		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7203			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7204			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7205		} else {
7206			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7207		}
7208	}
7209	if (shared_group) {
7210		tpg_desc->pref_state = ts;
7211		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7212		    TPG_U_SUP | TPG_T_SUP;
7213		scsi_ulto2b(1, tpg_desc->target_port_group);
7214		tpg_desc->status = TPG_IMPLICIT;
7215		pc = 0;
7216		STAILQ_FOREACH(port, &softc->port_list, links) {
7217			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7218				continue;
7219			if (!softc->is_single &&
7220			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7221				continue;
7222			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7223				continue;
7224			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7225			    relative_target_port_identifier);
7226			pc++;
7227		}
7228		tpg_desc->target_port_count = pc;
7229		tpg_desc = (struct scsi_target_port_group_descriptor *)
7230		    &tpg_desc->descriptors[pc];
7231	}
7232	for (g = 0; g < num_ha_groups; g++) {
7233		tpg_desc->pref_state = (g == pg) ? ts : os;
7234		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7235		    TPG_U_SUP | TPG_T_SUP;
7236		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7237		tpg_desc->status = TPG_IMPLICIT;
7238		pc = 0;
7239		STAILQ_FOREACH(port, &softc->port_list, links) {
7240			if (port->targ_port < g * softc->port_cnt ||
7241			    port->targ_port >= (g + 1) * softc->port_cnt)
7242				continue;
7243			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7244				continue;
7245			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7246				continue;
7247			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7248				continue;
7249			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7250			    relative_target_port_identifier);
7251			pc++;
7252		}
7253		tpg_desc->target_port_count = pc;
7254		tpg_desc = (struct scsi_target_port_group_descriptor *)
7255		    &tpg_desc->descriptors[pc];
7256	}
7257	mtx_unlock(&softc->ctl_lock);
7258
7259	ctl_set_success(ctsio);
7260	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7261	ctsio->be_move_done = ctl_config_move_done;
7262	ctl_datamove((union ctl_io *)ctsio);
7263	return(retval);
7264}
7265
7266int
7267ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7268{
7269	struct ctl_lun *lun;
7270	struct scsi_report_supported_opcodes *cdb;
7271	const struct ctl_cmd_entry *entry, *sentry;
7272	struct scsi_report_supported_opcodes_all *all;
7273	struct scsi_report_supported_opcodes_descr *descr;
7274	struct scsi_report_supported_opcodes_one *one;
7275	int retval;
7276	int alloc_len, total_len;
7277	int opcode, service_action, i, j, num;
7278
7279	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7280
7281	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7282	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7283
7284	retval = CTL_RETVAL_COMPLETE;
7285
7286	opcode = cdb->requested_opcode;
7287	service_action = scsi_2btoul(cdb->requested_service_action);
7288	switch (cdb->options & RSO_OPTIONS_MASK) {
7289	case RSO_OPTIONS_ALL:
7290		num = 0;
7291		for (i = 0; i < 256; i++) {
7292			entry = &ctl_cmd_table[i];
7293			if (entry->flags & CTL_CMD_FLAG_SA5) {
7294				for (j = 0; j < 32; j++) {
7295					sentry = &((const struct ctl_cmd_entry *)
7296					    entry->execute)[j];
7297					if (ctl_cmd_applicable(
7298					    lun->be_lun->lun_type, sentry))
7299						num++;
7300				}
7301			} else {
7302				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7303				    entry))
7304					num++;
7305			}
7306		}
7307		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7308		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7309		break;
7310	case RSO_OPTIONS_OC:
7311		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7312			ctl_set_invalid_field(/*ctsio*/ ctsio,
7313					      /*sks_valid*/ 1,
7314					      /*command*/ 1,
7315					      /*field*/ 2,
7316					      /*bit_valid*/ 1,
7317					      /*bit*/ 2);
7318			ctl_done((union ctl_io *)ctsio);
7319			return (CTL_RETVAL_COMPLETE);
7320		}
7321		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7322		break;
7323	case RSO_OPTIONS_OC_SA:
7324		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7325		    service_action >= 32) {
7326			ctl_set_invalid_field(/*ctsio*/ ctsio,
7327					      /*sks_valid*/ 1,
7328					      /*command*/ 1,
7329					      /*field*/ 2,
7330					      /*bit_valid*/ 1,
7331					      /*bit*/ 2);
7332			ctl_done((union ctl_io *)ctsio);
7333			return (CTL_RETVAL_COMPLETE);
7334		}
7335		/* FALLTHROUGH */
7336	case RSO_OPTIONS_OC_ASA:
7337		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7338		break;
7339	default:
7340		ctl_set_invalid_field(/*ctsio*/ ctsio,
7341				      /*sks_valid*/ 1,
7342				      /*command*/ 1,
7343				      /*field*/ 2,
7344				      /*bit_valid*/ 1,
7345				      /*bit*/ 2);
7346		ctl_done((union ctl_io *)ctsio);
7347		return (CTL_RETVAL_COMPLETE);
7348	}
7349
7350	alloc_len = scsi_4btoul(cdb->length);
7351
7352	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7353
7354	ctsio->kern_sg_entries = 0;
7355
7356	if (total_len < alloc_len) {
7357		ctsio->residual = alloc_len - total_len;
7358		ctsio->kern_data_len = total_len;
7359		ctsio->kern_total_len = total_len;
7360	} else {
7361		ctsio->residual = 0;
7362		ctsio->kern_data_len = alloc_len;
7363		ctsio->kern_total_len = alloc_len;
7364	}
7365	ctsio->kern_data_resid = 0;
7366	ctsio->kern_rel_offset = 0;
7367
7368	switch (cdb->options & RSO_OPTIONS_MASK) {
7369	case RSO_OPTIONS_ALL:
7370		all = (struct scsi_report_supported_opcodes_all *)
7371		    ctsio->kern_data_ptr;
7372		num = 0;
7373		for (i = 0; i < 256; i++) {
7374			entry = &ctl_cmd_table[i];
7375			if (entry->flags & CTL_CMD_FLAG_SA5) {
7376				for (j = 0; j < 32; j++) {
7377					sentry = &((const struct ctl_cmd_entry *)
7378					    entry->execute)[j];
7379					if (!ctl_cmd_applicable(
7380					    lun->be_lun->lun_type, sentry))
7381						continue;
7382					descr = &all->descr[num++];
7383					descr->opcode = i;
7384					scsi_ulto2b(j, descr->service_action);
7385					descr->flags = RSO_SERVACTV;
7386					scsi_ulto2b(sentry->length,
7387					    descr->cdb_length);
7388				}
7389			} else {
7390				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7391				    entry))
7392					continue;
7393				descr = &all->descr[num++];
7394				descr->opcode = i;
7395				scsi_ulto2b(0, descr->service_action);
7396				descr->flags = 0;
7397				scsi_ulto2b(entry->length, descr->cdb_length);
7398			}
7399		}
7400		scsi_ulto4b(
7401		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7402		    all->length);
7403		break;
7404	case RSO_OPTIONS_OC:
7405		one = (struct scsi_report_supported_opcodes_one *)
7406		    ctsio->kern_data_ptr;
7407		entry = &ctl_cmd_table[opcode];
7408		goto fill_one;
7409	case RSO_OPTIONS_OC_SA:
7410		one = (struct scsi_report_supported_opcodes_one *)
7411		    ctsio->kern_data_ptr;
7412		entry = &ctl_cmd_table[opcode];
7413		entry = &((const struct ctl_cmd_entry *)
7414		    entry->execute)[service_action];
7415fill_one:
7416		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7417			one->support = 3;
7418			scsi_ulto2b(entry->length, one->cdb_length);
7419			one->cdb_usage[0] = opcode;
7420			memcpy(&one->cdb_usage[1], entry->usage,
7421			    entry->length - 1);
7422		} else
7423			one->support = 1;
7424		break;
7425	case RSO_OPTIONS_OC_ASA:
7426		one = (struct scsi_report_supported_opcodes_one *)
7427		    ctsio->kern_data_ptr;
7428		entry = &ctl_cmd_table[opcode];
7429		if (entry->flags & CTL_CMD_FLAG_SA5) {
7430			entry = &((const struct ctl_cmd_entry *)
7431			    entry->execute)[service_action];
7432		} else if (service_action != 0) {
7433			one->support = 1;
7434			break;
7435		}
7436		goto fill_one;
7437	}
7438
7439	ctl_set_success(ctsio);
7440	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7441	ctsio->be_move_done = ctl_config_move_done;
7442	ctl_datamove((union ctl_io *)ctsio);
7443	return(retval);
7444}
7445
7446int
7447ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7448{
7449	struct scsi_report_supported_tmf *cdb;
7450	struct scsi_report_supported_tmf_ext_data *data;
7451	int retval;
7452	int alloc_len, total_len;
7453
7454	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7455
7456	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7457
7458	retval = CTL_RETVAL_COMPLETE;
7459
7460	if (cdb->options & RST_REPD)
7461		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7462	else
7463		total_len = sizeof(struct scsi_report_supported_tmf_data);
7464	alloc_len = scsi_4btoul(cdb->length);
7465
7466	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7467
7468	ctsio->kern_sg_entries = 0;
7469
7470	if (total_len < alloc_len) {
7471		ctsio->residual = alloc_len - total_len;
7472		ctsio->kern_data_len = total_len;
7473		ctsio->kern_total_len = total_len;
7474	} else {
7475		ctsio->residual = 0;
7476		ctsio->kern_data_len = alloc_len;
7477		ctsio->kern_total_len = alloc_len;
7478	}
7479	ctsio->kern_data_resid = 0;
7480	ctsio->kern_rel_offset = 0;
7481
7482	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7483	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7484	    RST_TRS;
7485	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7486	data->length = total_len - 4;
7487
7488	ctl_set_success(ctsio);
7489	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7490	ctsio->be_move_done = ctl_config_move_done;
7491	ctl_datamove((union ctl_io *)ctsio);
7492	return (retval);
7493}
7494
7495int
7496ctl_report_timestamp(struct ctl_scsiio *ctsio)
7497{
7498	struct scsi_report_timestamp *cdb;
7499	struct scsi_report_timestamp_data *data;
7500	struct timeval tv;
7501	int64_t timestamp;
7502	int retval;
7503	int alloc_len, total_len;
7504
7505	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7506
7507	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7508
7509	retval = CTL_RETVAL_COMPLETE;
7510
7511	total_len = sizeof(struct scsi_report_timestamp_data);
7512	alloc_len = scsi_4btoul(cdb->length);
7513
7514	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7515
7516	ctsio->kern_sg_entries = 0;
7517
7518	if (total_len < alloc_len) {
7519		ctsio->residual = alloc_len - total_len;
7520		ctsio->kern_data_len = total_len;
7521		ctsio->kern_total_len = total_len;
7522	} else {
7523		ctsio->residual = 0;
7524		ctsio->kern_data_len = alloc_len;
7525		ctsio->kern_total_len = alloc_len;
7526	}
7527	ctsio->kern_data_resid = 0;
7528	ctsio->kern_rel_offset = 0;
7529
7530	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7531	scsi_ulto2b(sizeof(*data) - 2, data->length);
7532	data->origin = RTS_ORIG_OUTSIDE;
7533	getmicrotime(&tv);
7534	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7535	scsi_ulto4b(timestamp >> 16, data->timestamp);
7536	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7537
7538	ctl_set_success(ctsio);
7539	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7540	ctsio->be_move_done = ctl_config_move_done;
7541	ctl_datamove((union ctl_io *)ctsio);
7542	return (retval);
7543}
7544
7545int
7546ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7547{
7548	struct scsi_per_res_in *cdb;
7549	int alloc_len, total_len = 0;
7550	/* struct scsi_per_res_in_rsrv in_data; */
7551	struct ctl_lun *lun;
7552	struct ctl_softc *softc;
7553	uint64_t key;
7554
7555	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7556
7557	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7558
7559	alloc_len = scsi_2btoul(cdb->length);
7560
7561	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7562	softc = lun->ctl_softc;
7563
7564retry:
7565	mtx_lock(&lun->lun_lock);
7566	switch (cdb->action) {
7567	case SPRI_RK: /* read keys */
7568		total_len = sizeof(struct scsi_per_res_in_keys) +
7569			lun->pr_key_count *
7570			sizeof(struct scsi_per_res_key);
7571		break;
7572	case SPRI_RR: /* read reservation */
7573		if (lun->flags & CTL_LUN_PR_RESERVED)
7574			total_len = sizeof(struct scsi_per_res_in_rsrv);
7575		else
7576			total_len = sizeof(struct scsi_per_res_in_header);
7577		break;
7578	case SPRI_RC: /* report capabilities */
7579		total_len = sizeof(struct scsi_per_res_cap);
7580		break;
7581	case SPRI_RS: /* read full status */
7582		total_len = sizeof(struct scsi_per_res_in_header) +
7583		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7584		    lun->pr_key_count;
7585		break;
7586	default:
7587		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7588	}
7589	mtx_unlock(&lun->lun_lock);
7590
7591	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7592
7593	if (total_len < alloc_len) {
7594		ctsio->residual = alloc_len - total_len;
7595		ctsio->kern_data_len = total_len;
7596		ctsio->kern_total_len = total_len;
7597	} else {
7598		ctsio->residual = 0;
7599		ctsio->kern_data_len = alloc_len;
7600		ctsio->kern_total_len = alloc_len;
7601	}
7602
7603	ctsio->kern_data_resid = 0;
7604	ctsio->kern_rel_offset = 0;
7605	ctsio->kern_sg_entries = 0;
7606
7607	mtx_lock(&lun->lun_lock);
7608	switch (cdb->action) {
7609	case SPRI_RK: { // read keys
7610        struct scsi_per_res_in_keys *res_keys;
7611		int i, key_count;
7612
7613		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7614
7615		/*
7616		 * We had to drop the lock to allocate our buffer, which
7617		 * leaves time for someone to come in with another
7618		 * persistent reservation.  (That is unlikely, though,
7619		 * since this should be the only persistent reservation
7620		 * command active right now.)
7621		 */
7622		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7623		    (lun->pr_key_count *
7624		     sizeof(struct scsi_per_res_key)))){
7625			mtx_unlock(&lun->lun_lock);
7626			free(ctsio->kern_data_ptr, M_CTL);
7627			printf("%s: reservation length changed, retrying\n",
7628			       __func__);
7629			goto retry;
7630		}
7631
7632		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7633
7634		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7635			     lun->pr_key_count, res_keys->header.length);
7636
7637		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7638			if ((key = ctl_get_prkey(lun, i)) == 0)
7639				continue;
7640
7641			/*
7642			 * We used lun->pr_key_count to calculate the
7643			 * size to allocate.  If it turns out the number of
7644			 * initiators with the registered flag set is
7645			 * larger than that (i.e. they haven't been kept in
7646			 * sync), we've got a problem.
7647			 */
7648			if (key_count >= lun->pr_key_count) {
7649				key_count++;
7650				continue;
7651			}
7652			scsi_u64to8b(key, res_keys->keys[key_count].key);
7653			key_count++;
7654		}
7655		break;
7656	}
7657	case SPRI_RR: { // read reservation
7658		struct scsi_per_res_in_rsrv *res;
7659		int tmp_len, header_only;
7660
7661		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7662
7663		scsi_ulto4b(lun->pr_generation, res->header.generation);
7664
7665		if (lun->flags & CTL_LUN_PR_RESERVED)
7666		{
7667			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7668			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7669				    res->header.length);
7670			header_only = 0;
7671		} else {
7672			tmp_len = sizeof(struct scsi_per_res_in_header);
7673			scsi_ulto4b(0, res->header.length);
7674			header_only = 1;
7675		}
7676
7677		/*
7678		 * We had to drop the lock to allocate our buffer, which
7679		 * leaves time for someone to come in with another
7680		 * persistent reservation.  (That is unlikely, though,
7681		 * since this should be the only persistent reservation
7682		 * command active right now.)
7683		 */
7684		if (tmp_len != total_len) {
7685			mtx_unlock(&lun->lun_lock);
7686			free(ctsio->kern_data_ptr, M_CTL);
7687			printf("%s: reservation status changed, retrying\n",
7688			       __func__);
7689			goto retry;
7690		}
7691
7692		/*
7693		 * No reservation held, so we're done.
7694		 */
7695		if (header_only != 0)
7696			break;
7697
7698		/*
7699		 * If the registration is an All Registrants type, the key
7700		 * is 0, since it doesn't really matter.
7701		 */
7702		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7703			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7704			    res->data.reservation);
7705		}
7706		res->data.scopetype = lun->pr_res_type;
7707		break;
7708	}
7709	case SPRI_RC:     //report capabilities
7710	{
7711		struct scsi_per_res_cap *res_cap;
7712		uint16_t type_mask;
7713
7714		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7715		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7716		res_cap->flags1 = SPRI_CRH;
7717		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7718		type_mask = SPRI_TM_WR_EX_AR |
7719			    SPRI_TM_EX_AC_RO |
7720			    SPRI_TM_WR_EX_RO |
7721			    SPRI_TM_EX_AC |
7722			    SPRI_TM_WR_EX |
7723			    SPRI_TM_EX_AC_AR;
7724		scsi_ulto2b(type_mask, res_cap->type_mask);
7725		break;
7726	}
7727	case SPRI_RS: { // read full status
7728		struct scsi_per_res_in_full *res_status;
7729		struct scsi_per_res_in_full_desc *res_desc;
7730		struct ctl_port *port;
7731		int i, len;
7732
7733		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7734
7735		/*
7736		 * We had to drop the lock to allocate our buffer, which
7737		 * leaves time for someone to come in with another
7738		 * persistent reservation.  (That is unlikely, though,
7739		 * since this should be the only persistent reservation
7740		 * command active right now.)
7741		 */
7742		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7743		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7744		     lun->pr_key_count)){
7745			mtx_unlock(&lun->lun_lock);
7746			free(ctsio->kern_data_ptr, M_CTL);
7747			printf("%s: reservation length changed, retrying\n",
7748			       __func__);
7749			goto retry;
7750		}
7751
7752		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7753
7754		res_desc = &res_status->desc[0];
7755		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7756			if ((key = ctl_get_prkey(lun, i)) == 0)
7757				continue;
7758
7759			scsi_u64to8b(key, res_desc->res_key.key);
7760			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7761			    (lun->pr_res_idx == i ||
7762			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7763				res_desc->flags = SPRI_FULL_R_HOLDER;
7764				res_desc->scopetype = lun->pr_res_type;
7765			}
7766			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7767			    res_desc->rel_trgt_port_id);
7768			len = 0;
7769			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7770			if (port != NULL)
7771				len = ctl_create_iid(port,
7772				    i % CTL_MAX_INIT_PER_PORT,
7773				    res_desc->transport_id);
7774			scsi_ulto4b(len, res_desc->additional_length);
7775			res_desc = (struct scsi_per_res_in_full_desc *)
7776			    &res_desc->transport_id[len];
7777		}
7778		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7779		    res_status->header.length);
7780		break;
7781	}
7782	default:
7783		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7784	}
7785	mtx_unlock(&lun->lun_lock);
7786
7787	ctl_set_success(ctsio);
7788	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7789	ctsio->be_move_done = ctl_config_move_done;
7790	ctl_datamove((union ctl_io *)ctsio);
7791	return (CTL_RETVAL_COMPLETE);
7792}
7793
7794/*
7795 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7796 * it should return.
7797 */
7798static int
7799ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7800		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7801		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7802		struct scsi_per_res_out_parms* param)
7803{
7804	union ctl_ha_msg persis_io;
7805	int i;
7806
7807	mtx_lock(&lun->lun_lock);
7808	if (sa_res_key == 0) {
7809		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7810			/* validate scope and type */
7811			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7812			     SPR_LU_SCOPE) {
7813				mtx_unlock(&lun->lun_lock);
7814				ctl_set_invalid_field(/*ctsio*/ ctsio,
7815						      /*sks_valid*/ 1,
7816						      /*command*/ 1,
7817						      /*field*/ 2,
7818						      /*bit_valid*/ 1,
7819						      /*bit*/ 4);
7820				ctl_done((union ctl_io *)ctsio);
7821				return (1);
7822			}
7823
7824		        if (type>8 || type==2 || type==4 || type==0) {
7825				mtx_unlock(&lun->lun_lock);
7826				ctl_set_invalid_field(/*ctsio*/ ctsio,
7827       	           				      /*sks_valid*/ 1,
7828						      /*command*/ 1,
7829						      /*field*/ 2,
7830						      /*bit_valid*/ 1,
7831						      /*bit*/ 0);
7832				ctl_done((union ctl_io *)ctsio);
7833				return (1);
7834		        }
7835
7836			/*
7837			 * Unregister everybody else and build UA for
7838			 * them
7839			 */
7840			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7841				if (i == residx || ctl_get_prkey(lun, i) == 0)
7842					continue;
7843
7844				ctl_clr_prkey(lun, i);
7845				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7846			}
7847			lun->pr_key_count = 1;
7848			lun->pr_res_type = type;
7849			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7850			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7851				lun->pr_res_idx = residx;
7852			lun->pr_generation++;
7853			mtx_unlock(&lun->lun_lock);
7854
7855			/* send msg to other side */
7856			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7857			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7858			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7859			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7860			persis_io.pr.pr_info.res_type = type;
7861			memcpy(persis_io.pr.pr_info.sa_res_key,
7862			       param->serv_act_res_key,
7863			       sizeof(param->serv_act_res_key));
7864			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7865			    sizeof(persis_io.pr), M_WAITOK);
7866		} else {
7867			/* not all registrants */
7868			mtx_unlock(&lun->lun_lock);
7869			free(ctsio->kern_data_ptr, M_CTL);
7870			ctl_set_invalid_field(ctsio,
7871					      /*sks_valid*/ 1,
7872					      /*command*/ 0,
7873					      /*field*/ 8,
7874					      /*bit_valid*/ 0,
7875					      /*bit*/ 0);
7876			ctl_done((union ctl_io *)ctsio);
7877			return (1);
7878		}
7879	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7880		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7881		int found = 0;
7882
7883		if (res_key == sa_res_key) {
7884			/* special case */
7885			/*
7886			 * The spec implies this is not good but doesn't
7887			 * say what to do. There are two choices either
7888			 * generate a res conflict or check condition
7889			 * with illegal field in parameter data. Since
7890			 * that is what is done when the sa_res_key is
7891			 * zero I'll take that approach since this has
7892			 * to do with the sa_res_key.
7893			 */
7894			mtx_unlock(&lun->lun_lock);
7895			free(ctsio->kern_data_ptr, M_CTL);
7896			ctl_set_invalid_field(ctsio,
7897					      /*sks_valid*/ 1,
7898					      /*command*/ 0,
7899					      /*field*/ 8,
7900					      /*bit_valid*/ 0,
7901					      /*bit*/ 0);
7902			ctl_done((union ctl_io *)ctsio);
7903			return (1);
7904		}
7905
7906		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7907			if (ctl_get_prkey(lun, i) != sa_res_key)
7908				continue;
7909
7910			found = 1;
7911			ctl_clr_prkey(lun, i);
7912			lun->pr_key_count--;
7913			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7914		}
7915		if (!found) {
7916			mtx_unlock(&lun->lun_lock);
7917			free(ctsio->kern_data_ptr, M_CTL);
7918			ctl_set_reservation_conflict(ctsio);
7919			ctl_done((union ctl_io *)ctsio);
7920			return (CTL_RETVAL_COMPLETE);
7921		}
7922		lun->pr_generation++;
7923		mtx_unlock(&lun->lun_lock);
7924
7925		/* send msg to other side */
7926		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7927		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7928		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7929		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7930		persis_io.pr.pr_info.res_type = type;
7931		memcpy(persis_io.pr.pr_info.sa_res_key,
7932		       param->serv_act_res_key,
7933		       sizeof(param->serv_act_res_key));
7934		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7935		    sizeof(persis_io.pr), M_WAITOK);
7936	} else {
7937		/* Reserved but not all registrants */
7938		/* sa_res_key is res holder */
7939		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7940			/* validate scope and type */
7941			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7942			     SPR_LU_SCOPE) {
7943				mtx_unlock(&lun->lun_lock);
7944				ctl_set_invalid_field(/*ctsio*/ ctsio,
7945						      /*sks_valid*/ 1,
7946						      /*command*/ 1,
7947						      /*field*/ 2,
7948						      /*bit_valid*/ 1,
7949						      /*bit*/ 4);
7950				ctl_done((union ctl_io *)ctsio);
7951				return (1);
7952			}
7953
7954			if (type>8 || type==2 || type==4 || type==0) {
7955				mtx_unlock(&lun->lun_lock);
7956				ctl_set_invalid_field(/*ctsio*/ ctsio,
7957						      /*sks_valid*/ 1,
7958						      /*command*/ 1,
7959						      /*field*/ 2,
7960						      /*bit_valid*/ 1,
7961						      /*bit*/ 0);
7962				ctl_done((union ctl_io *)ctsio);
7963				return (1);
7964			}
7965
7966			/*
7967			 * Do the following:
7968			 * if sa_res_key != res_key remove all
7969			 * registrants w/sa_res_key and generate UA
7970			 * for these registrants(Registrations
7971			 * Preempted) if it wasn't an exclusive
7972			 * reservation generate UA(Reservations
7973			 * Preempted) for all other registered nexuses
7974			 * if the type has changed. Establish the new
7975			 * reservation and holder. If res_key and
7976			 * sa_res_key are the same do the above
7977			 * except don't unregister the res holder.
7978			 */
7979
7980			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7981				if (i == residx || ctl_get_prkey(lun, i) == 0)
7982					continue;
7983
7984				if (sa_res_key == ctl_get_prkey(lun, i)) {
7985					ctl_clr_prkey(lun, i);
7986					lun->pr_key_count--;
7987					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7988				} else if (type != lun->pr_res_type &&
7989				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7990				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7991					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7992				}
7993			}
7994			lun->pr_res_type = type;
7995			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7996			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7997				lun->pr_res_idx = residx;
7998			else
7999				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8000			lun->pr_generation++;
8001			mtx_unlock(&lun->lun_lock);
8002
8003			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8004			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8005			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8006			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8007			persis_io.pr.pr_info.res_type = type;
8008			memcpy(persis_io.pr.pr_info.sa_res_key,
8009			       param->serv_act_res_key,
8010			       sizeof(param->serv_act_res_key));
8011			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8012			    sizeof(persis_io.pr), M_WAITOK);
8013		} else {
8014			/*
8015			 * sa_res_key is not the res holder just
8016			 * remove registrants
8017			 */
8018			int found=0;
8019
8020			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8021				if (sa_res_key != ctl_get_prkey(lun, i))
8022					continue;
8023
8024				found = 1;
8025				ctl_clr_prkey(lun, i);
8026				lun->pr_key_count--;
8027				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8028			}
8029
8030			if (!found) {
8031				mtx_unlock(&lun->lun_lock);
8032				free(ctsio->kern_data_ptr, M_CTL);
8033				ctl_set_reservation_conflict(ctsio);
8034				ctl_done((union ctl_io *)ctsio);
8035		        	return (1);
8036			}
8037			lun->pr_generation++;
8038			mtx_unlock(&lun->lun_lock);
8039
8040			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8041			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8042			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8043			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8044			persis_io.pr.pr_info.res_type = type;
8045			memcpy(persis_io.pr.pr_info.sa_res_key,
8046			       param->serv_act_res_key,
8047			       sizeof(param->serv_act_res_key));
8048			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8049			    sizeof(persis_io.pr), M_WAITOK);
8050		}
8051	}
8052	return (0);
8053}
8054
8055static void
8056ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8057{
8058	uint64_t sa_res_key;
8059	int i;
8060
8061	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8062
8063	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8064	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8065	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8066		if (sa_res_key == 0) {
8067			/*
8068			 * Unregister everybody else and build UA for
8069			 * them
8070			 */
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				ctl_clr_prkey(lun, i);
8077				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8078			}
8079
8080			lun->pr_key_count = 1;
8081			lun->pr_res_type = msg->pr.pr_info.res_type;
8082			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8083			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8084				lun->pr_res_idx = msg->pr.pr_info.residx;
8085		} else {
8086		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8087				if (sa_res_key == ctl_get_prkey(lun, i))
8088					continue;
8089
8090				ctl_clr_prkey(lun, i);
8091				lun->pr_key_count--;
8092				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8093			}
8094		}
8095	} else {
8096		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8097			if (i == msg->pr.pr_info.residx ||
8098			    ctl_get_prkey(lun, i) == 0)
8099				continue;
8100
8101			if (sa_res_key == ctl_get_prkey(lun, i)) {
8102				ctl_clr_prkey(lun, i);
8103				lun->pr_key_count--;
8104				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8105			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8106			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8107			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8108				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8109			}
8110		}
8111		lun->pr_res_type = msg->pr.pr_info.res_type;
8112		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8113		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8114			lun->pr_res_idx = msg->pr.pr_info.residx;
8115		else
8116			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8117	}
8118	lun->pr_generation++;
8119
8120}
8121
8122
8123int
8124ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8125{
8126	int retval;
8127	u_int32_t param_len;
8128	struct scsi_per_res_out *cdb;
8129	struct ctl_lun *lun;
8130	struct scsi_per_res_out_parms* param;
8131	struct ctl_softc *softc;
8132	uint32_t residx;
8133	uint64_t res_key, sa_res_key, key;
8134	uint8_t type;
8135	union ctl_ha_msg persis_io;
8136	int    i;
8137
8138	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8139
8140	retval = CTL_RETVAL_COMPLETE;
8141
8142	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8143	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8144	softc = lun->ctl_softc;
8145
8146	/*
8147	 * We only support whole-LUN scope.  The scope & type are ignored for
8148	 * register, register and ignore existing key and clear.
8149	 * We sometimes ignore scope and type on preempts too!!
8150	 * Verify reservation type here as well.
8151	 */
8152	type = cdb->scope_type & SPR_TYPE_MASK;
8153	if ((cdb->action == SPRO_RESERVE)
8154	 || (cdb->action == SPRO_RELEASE)) {
8155		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8156			ctl_set_invalid_field(/*ctsio*/ ctsio,
8157					      /*sks_valid*/ 1,
8158					      /*command*/ 1,
8159					      /*field*/ 2,
8160					      /*bit_valid*/ 1,
8161					      /*bit*/ 4);
8162			ctl_done((union ctl_io *)ctsio);
8163			return (CTL_RETVAL_COMPLETE);
8164		}
8165
8166		if (type>8 || type==2 || type==4 || type==0) {
8167			ctl_set_invalid_field(/*ctsio*/ ctsio,
8168					      /*sks_valid*/ 1,
8169					      /*command*/ 1,
8170					      /*field*/ 2,
8171					      /*bit_valid*/ 1,
8172					      /*bit*/ 0);
8173			ctl_done((union ctl_io *)ctsio);
8174			return (CTL_RETVAL_COMPLETE);
8175		}
8176	}
8177
8178	param_len = scsi_4btoul(cdb->length);
8179
8180	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8181		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8182		ctsio->kern_data_len = param_len;
8183		ctsio->kern_total_len = param_len;
8184		ctsio->kern_data_resid = 0;
8185		ctsio->kern_rel_offset = 0;
8186		ctsio->kern_sg_entries = 0;
8187		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8188		ctsio->be_move_done = ctl_config_move_done;
8189		ctl_datamove((union ctl_io *)ctsio);
8190
8191		return (CTL_RETVAL_COMPLETE);
8192	}
8193
8194	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8195
8196	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8197	res_key = scsi_8btou64(param->res_key.key);
8198	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8199
8200	/*
8201	 * Validate the reservation key here except for SPRO_REG_IGNO
8202	 * This must be done for all other service actions
8203	 */
8204	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8205		mtx_lock(&lun->lun_lock);
8206		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8207			if (res_key != key) {
8208				/*
8209				 * The current key passed in doesn't match
8210				 * the one the initiator previously
8211				 * registered.
8212				 */
8213				mtx_unlock(&lun->lun_lock);
8214				free(ctsio->kern_data_ptr, M_CTL);
8215				ctl_set_reservation_conflict(ctsio);
8216				ctl_done((union ctl_io *)ctsio);
8217				return (CTL_RETVAL_COMPLETE);
8218			}
8219		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8220			/*
8221			 * We are not registered
8222			 */
8223			mtx_unlock(&lun->lun_lock);
8224			free(ctsio->kern_data_ptr, M_CTL);
8225			ctl_set_reservation_conflict(ctsio);
8226			ctl_done((union ctl_io *)ctsio);
8227			return (CTL_RETVAL_COMPLETE);
8228		} else if (res_key != 0) {
8229			/*
8230			 * We are not registered and trying to register but
8231			 * the register key isn't zero.
8232			 */
8233			mtx_unlock(&lun->lun_lock);
8234			free(ctsio->kern_data_ptr, M_CTL);
8235			ctl_set_reservation_conflict(ctsio);
8236			ctl_done((union ctl_io *)ctsio);
8237			return (CTL_RETVAL_COMPLETE);
8238		}
8239		mtx_unlock(&lun->lun_lock);
8240	}
8241
8242	switch (cdb->action & SPRO_ACTION_MASK) {
8243	case SPRO_REGISTER:
8244	case SPRO_REG_IGNO: {
8245
8246#if 0
8247		printf("Registration received\n");
8248#endif
8249
8250		/*
8251		 * We don't support any of these options, as we report in
8252		 * the read capabilities request (see
8253		 * ctl_persistent_reserve_in(), above).
8254		 */
8255		if ((param->flags & SPR_SPEC_I_PT)
8256		 || (param->flags & SPR_ALL_TG_PT)
8257		 || (param->flags & SPR_APTPL)) {
8258			int bit_ptr;
8259
8260			if (param->flags & SPR_APTPL)
8261				bit_ptr = 0;
8262			else if (param->flags & SPR_ALL_TG_PT)
8263				bit_ptr = 2;
8264			else /* SPR_SPEC_I_PT */
8265				bit_ptr = 3;
8266
8267			free(ctsio->kern_data_ptr, M_CTL);
8268			ctl_set_invalid_field(ctsio,
8269					      /*sks_valid*/ 1,
8270					      /*command*/ 0,
8271					      /*field*/ 20,
8272					      /*bit_valid*/ 1,
8273					      /*bit*/ bit_ptr);
8274			ctl_done((union ctl_io *)ctsio);
8275			return (CTL_RETVAL_COMPLETE);
8276		}
8277
8278		mtx_lock(&lun->lun_lock);
8279
8280		/*
8281		 * The initiator wants to clear the
8282		 * key/unregister.
8283		 */
8284		if (sa_res_key == 0) {
8285			if ((res_key == 0
8286			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8287			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8288			  && ctl_get_prkey(lun, residx) == 0)) {
8289				mtx_unlock(&lun->lun_lock);
8290				goto done;
8291			}
8292
8293			ctl_clr_prkey(lun, residx);
8294			lun->pr_key_count--;
8295
8296			if (residx == lun->pr_res_idx) {
8297				lun->flags &= ~CTL_LUN_PR_RESERVED;
8298				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8299
8300				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8301				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8302				    lun->pr_key_count) {
8303					/*
8304					 * If the reservation is a registrants
8305					 * only type we need to generate a UA
8306					 * for other registered inits.  The
8307					 * sense code should be RESERVATIONS
8308					 * RELEASED
8309					 */
8310
8311					for (i = softc->init_min; i < softc->init_max; i++){
8312						if (ctl_get_prkey(lun, i) == 0)
8313							continue;
8314						ctl_est_ua(lun, i,
8315						    CTL_UA_RES_RELEASE);
8316					}
8317				}
8318				lun->pr_res_type = 0;
8319			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8320				if (lun->pr_key_count==0) {
8321					lun->flags &= ~CTL_LUN_PR_RESERVED;
8322					lun->pr_res_type = 0;
8323					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8324				}
8325			}
8326			lun->pr_generation++;
8327			mtx_unlock(&lun->lun_lock);
8328
8329			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8330			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8331			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8332			persis_io.pr.pr_info.residx = residx;
8333			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8334			    sizeof(persis_io.pr), M_WAITOK);
8335		} else /* sa_res_key != 0 */ {
8336
8337			/*
8338			 * If we aren't registered currently then increment
8339			 * the key count and set the registered flag.
8340			 */
8341			ctl_alloc_prkey(lun, residx);
8342			if (ctl_get_prkey(lun, residx) == 0)
8343				lun->pr_key_count++;
8344			ctl_set_prkey(lun, residx, sa_res_key);
8345			lun->pr_generation++;
8346			mtx_unlock(&lun->lun_lock);
8347
8348			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8349			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8350			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8351			persis_io.pr.pr_info.residx = residx;
8352			memcpy(persis_io.pr.pr_info.sa_res_key,
8353			       param->serv_act_res_key,
8354			       sizeof(param->serv_act_res_key));
8355			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8356			    sizeof(persis_io.pr), M_WAITOK);
8357		}
8358
8359		break;
8360	}
8361	case SPRO_RESERVE:
8362#if 0
8363                printf("Reserve executed type %d\n", type);
8364#endif
8365		mtx_lock(&lun->lun_lock);
8366		if (lun->flags & CTL_LUN_PR_RESERVED) {
8367			/*
8368			 * if this isn't the reservation holder and it's
8369			 * not a "all registrants" type or if the type is
8370			 * different then we have a conflict
8371			 */
8372			if ((lun->pr_res_idx != residx
8373			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8374			 || lun->pr_res_type != type) {
8375				mtx_unlock(&lun->lun_lock);
8376				free(ctsio->kern_data_ptr, M_CTL);
8377				ctl_set_reservation_conflict(ctsio);
8378				ctl_done((union ctl_io *)ctsio);
8379				return (CTL_RETVAL_COMPLETE);
8380			}
8381			mtx_unlock(&lun->lun_lock);
8382		} else /* create a reservation */ {
8383			/*
8384			 * If it's not an "all registrants" type record
8385			 * reservation holder
8386			 */
8387			if (type != SPR_TYPE_WR_EX_AR
8388			 && type != SPR_TYPE_EX_AC_AR)
8389				lun->pr_res_idx = residx; /* Res holder */
8390			else
8391				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8392
8393			lun->flags |= CTL_LUN_PR_RESERVED;
8394			lun->pr_res_type = type;
8395
8396			mtx_unlock(&lun->lun_lock);
8397
8398			/* send msg to other side */
8399			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8400			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8401			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8402			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8403			persis_io.pr.pr_info.res_type = type;
8404			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8405			    sizeof(persis_io.pr), M_WAITOK);
8406		}
8407		break;
8408
8409	case SPRO_RELEASE:
8410		mtx_lock(&lun->lun_lock);
8411		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8412			/* No reservation exists return good status */
8413			mtx_unlock(&lun->lun_lock);
8414			goto done;
8415		}
8416		/*
8417		 * Is this nexus a reservation holder?
8418		 */
8419		if (lun->pr_res_idx != residx
8420		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8421			/*
8422			 * not a res holder return good status but
8423			 * do nothing
8424			 */
8425			mtx_unlock(&lun->lun_lock);
8426			goto done;
8427		}
8428
8429		if (lun->pr_res_type != type) {
8430			mtx_unlock(&lun->lun_lock);
8431			free(ctsio->kern_data_ptr, M_CTL);
8432			ctl_set_illegal_pr_release(ctsio);
8433			ctl_done((union ctl_io *)ctsio);
8434			return (CTL_RETVAL_COMPLETE);
8435		}
8436
8437		/* okay to release */
8438		lun->flags &= ~CTL_LUN_PR_RESERVED;
8439		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8440		lun->pr_res_type = 0;
8441
8442		/*
8443		 * If this isn't an exclusive access reservation and NUAR
8444		 * is not set, generate UA for all other registrants.
8445		 */
8446		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8447		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8448			for (i = softc->init_min; i < softc->init_max; i++) {
8449				if (i == residx || ctl_get_prkey(lun, i) == 0)
8450					continue;
8451				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8452			}
8453		}
8454		mtx_unlock(&lun->lun_lock);
8455
8456		/* Send msg to other side */
8457		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8458		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8459		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8460		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8461		     sizeof(persis_io.pr), M_WAITOK);
8462		break;
8463
8464	case SPRO_CLEAR:
8465		/* send msg to other side */
8466
8467		mtx_lock(&lun->lun_lock);
8468		lun->flags &= ~CTL_LUN_PR_RESERVED;
8469		lun->pr_res_type = 0;
8470		lun->pr_key_count = 0;
8471		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8472
8473		ctl_clr_prkey(lun, residx);
8474		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8475			if (ctl_get_prkey(lun, i) != 0) {
8476				ctl_clr_prkey(lun, i);
8477				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8478			}
8479		lun->pr_generation++;
8480		mtx_unlock(&lun->lun_lock);
8481
8482		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8483		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8484		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8485		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8486		     sizeof(persis_io.pr), M_WAITOK);
8487		break;
8488
8489	case SPRO_PREEMPT:
8490	case SPRO_PRE_ABO: {
8491		int nretval;
8492
8493		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8494					  residx, ctsio, cdb, param);
8495		if (nretval != 0)
8496			return (CTL_RETVAL_COMPLETE);
8497		break;
8498	}
8499	default:
8500		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8501	}
8502
8503done:
8504	free(ctsio->kern_data_ptr, M_CTL);
8505	ctl_set_success(ctsio);
8506	ctl_done((union ctl_io *)ctsio);
8507
8508	return (retval);
8509}
8510
8511/*
8512 * This routine is for handling a message from the other SC pertaining to
8513 * persistent reserve out. All the error checking will have been done
8514 * so only perorming the action need be done here to keep the two
8515 * in sync.
8516 */
8517static void
8518ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8519{
8520	struct ctl_softc *softc = control_softc;
8521	struct ctl_lun *lun;
8522	int i;
8523	uint32_t residx, targ_lun;
8524
8525	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8526	mtx_lock(&softc->ctl_lock);
8527	if (targ_lun >= CTL_MAX_LUNS ||
8528	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8529		mtx_unlock(&softc->ctl_lock);
8530		return;
8531	}
8532	mtx_lock(&lun->lun_lock);
8533	mtx_unlock(&softc->ctl_lock);
8534	if (lun->flags & CTL_LUN_DISABLED) {
8535		mtx_unlock(&lun->lun_lock);
8536		return;
8537	}
8538	residx = ctl_get_initindex(&msg->hdr.nexus);
8539	switch(msg->pr.pr_info.action) {
8540	case CTL_PR_REG_KEY:
8541		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8542		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8543			lun->pr_key_count++;
8544		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8545		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8546		lun->pr_generation++;
8547		break;
8548
8549	case CTL_PR_UNREG_KEY:
8550		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8551		lun->pr_key_count--;
8552
8553		/* XXX Need to see if the reservation has been released */
8554		/* if so do we need to generate UA? */
8555		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8556			lun->flags &= ~CTL_LUN_PR_RESERVED;
8557			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8558
8559			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8560			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8561			    lun->pr_key_count) {
8562				/*
8563				 * If the reservation is a registrants
8564				 * only type we need to generate a UA
8565				 * for other registered inits.  The
8566				 * sense code should be RESERVATIONS
8567				 * RELEASED
8568				 */
8569
8570				for (i = softc->init_min; i < softc->init_max; i++) {
8571					if (ctl_get_prkey(lun, i) == 0)
8572						continue;
8573
8574					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8575				}
8576			}
8577			lun->pr_res_type = 0;
8578		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8579			if (lun->pr_key_count==0) {
8580				lun->flags &= ~CTL_LUN_PR_RESERVED;
8581				lun->pr_res_type = 0;
8582				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8583			}
8584		}
8585		lun->pr_generation++;
8586		break;
8587
8588	case CTL_PR_RESERVE:
8589		lun->flags |= CTL_LUN_PR_RESERVED;
8590		lun->pr_res_type = msg->pr.pr_info.res_type;
8591		lun->pr_res_idx = msg->pr.pr_info.residx;
8592
8593		break;
8594
8595	case CTL_PR_RELEASE:
8596		/*
8597		 * If this isn't an exclusive access reservation and NUAR
8598		 * is not set, generate UA for all other registrants.
8599		 */
8600		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8601		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8602		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8603			for (i = softc->init_min; i < softc->init_max; i++)
8604				if (i == residx || ctl_get_prkey(lun, i) == 0)
8605					continue;
8606				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8607		}
8608
8609		lun->flags &= ~CTL_LUN_PR_RESERVED;
8610		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8611		lun->pr_res_type = 0;
8612		break;
8613
8614	case CTL_PR_PREEMPT:
8615		ctl_pro_preempt_other(lun, msg);
8616		break;
8617	case CTL_PR_CLEAR:
8618		lun->flags &= ~CTL_LUN_PR_RESERVED;
8619		lun->pr_res_type = 0;
8620		lun->pr_key_count = 0;
8621		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8622
8623		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8624			if (ctl_get_prkey(lun, i) == 0)
8625				continue;
8626			ctl_clr_prkey(lun, i);
8627			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8628		}
8629		lun->pr_generation++;
8630		break;
8631	}
8632
8633	mtx_unlock(&lun->lun_lock);
8634}
8635
8636int
8637ctl_read_write(struct ctl_scsiio *ctsio)
8638{
8639	struct ctl_lun *lun;
8640	struct ctl_lba_len_flags *lbalen;
8641	uint64_t lba;
8642	uint32_t num_blocks;
8643	int flags, retval;
8644	int isread;
8645
8646	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8647
8648	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8649
8650	flags = 0;
8651	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8652	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8653	switch (ctsio->cdb[0]) {
8654	case READ_6:
8655	case WRITE_6: {
8656		struct scsi_rw_6 *cdb;
8657
8658		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8659
8660		lba = scsi_3btoul(cdb->addr);
8661		/* only 5 bits are valid in the most significant address byte */
8662		lba &= 0x1fffff;
8663		num_blocks = cdb->length;
8664		/*
8665		 * This is correct according to SBC-2.
8666		 */
8667		if (num_blocks == 0)
8668			num_blocks = 256;
8669		break;
8670	}
8671	case READ_10:
8672	case WRITE_10: {
8673		struct scsi_rw_10 *cdb;
8674
8675		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8676		if (cdb->byte2 & SRW10_FUA)
8677			flags |= CTL_LLF_FUA;
8678		if (cdb->byte2 & SRW10_DPO)
8679			flags |= CTL_LLF_DPO;
8680		lba = scsi_4btoul(cdb->addr);
8681		num_blocks = scsi_2btoul(cdb->length);
8682		break;
8683	}
8684	case WRITE_VERIFY_10: {
8685		struct scsi_write_verify_10 *cdb;
8686
8687		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8688		flags |= CTL_LLF_FUA;
8689		if (cdb->byte2 & SWV_DPO)
8690			flags |= CTL_LLF_DPO;
8691		lba = scsi_4btoul(cdb->addr);
8692		num_blocks = scsi_2btoul(cdb->length);
8693		break;
8694	}
8695	case READ_12:
8696	case WRITE_12: {
8697		struct scsi_rw_12 *cdb;
8698
8699		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8700		if (cdb->byte2 & SRW12_FUA)
8701			flags |= CTL_LLF_FUA;
8702		if (cdb->byte2 & SRW12_DPO)
8703			flags |= CTL_LLF_DPO;
8704		lba = scsi_4btoul(cdb->addr);
8705		num_blocks = scsi_4btoul(cdb->length);
8706		break;
8707	}
8708	case WRITE_VERIFY_12: {
8709		struct scsi_write_verify_12 *cdb;
8710
8711		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8712		flags |= CTL_LLF_FUA;
8713		if (cdb->byte2 & SWV_DPO)
8714			flags |= CTL_LLF_DPO;
8715		lba = scsi_4btoul(cdb->addr);
8716		num_blocks = scsi_4btoul(cdb->length);
8717		break;
8718	}
8719	case READ_16:
8720	case WRITE_16: {
8721		struct scsi_rw_16 *cdb;
8722
8723		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8724		if (cdb->byte2 & SRW12_FUA)
8725			flags |= CTL_LLF_FUA;
8726		if (cdb->byte2 & SRW12_DPO)
8727			flags |= CTL_LLF_DPO;
8728		lba = scsi_8btou64(cdb->addr);
8729		num_blocks = scsi_4btoul(cdb->length);
8730		break;
8731	}
8732	case WRITE_ATOMIC_16: {
8733		struct scsi_write_atomic_16 *cdb;
8734
8735		if (lun->be_lun->atomicblock == 0) {
8736			ctl_set_invalid_opcode(ctsio);
8737			ctl_done((union ctl_io *)ctsio);
8738			return (CTL_RETVAL_COMPLETE);
8739		}
8740
8741		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8742		if (cdb->byte2 & SRW12_FUA)
8743			flags |= CTL_LLF_FUA;
8744		if (cdb->byte2 & SRW12_DPO)
8745			flags |= CTL_LLF_DPO;
8746		lba = scsi_8btou64(cdb->addr);
8747		num_blocks = scsi_2btoul(cdb->length);
8748		if (num_blocks > lun->be_lun->atomicblock) {
8749			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8750			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8751			    /*bit*/ 0);
8752			ctl_done((union ctl_io *)ctsio);
8753			return (CTL_RETVAL_COMPLETE);
8754		}
8755		break;
8756	}
8757	case WRITE_VERIFY_16: {
8758		struct scsi_write_verify_16 *cdb;
8759
8760		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8761		flags |= CTL_LLF_FUA;
8762		if (cdb->byte2 & SWV_DPO)
8763			flags |= CTL_LLF_DPO;
8764		lba = scsi_8btou64(cdb->addr);
8765		num_blocks = scsi_4btoul(cdb->length);
8766		break;
8767	}
8768	default:
8769		/*
8770		 * We got a command we don't support.  This shouldn't
8771		 * happen, commands should be filtered out above us.
8772		 */
8773		ctl_set_invalid_opcode(ctsio);
8774		ctl_done((union ctl_io *)ctsio);
8775
8776		return (CTL_RETVAL_COMPLETE);
8777		break; /* NOTREACHED */
8778	}
8779
8780	/*
8781	 * The first check is to make sure we're in bounds, the second
8782	 * check is to catch wrap-around problems.  If the lba + num blocks
8783	 * is less than the lba, then we've wrapped around and the block
8784	 * range is invalid anyway.
8785	 */
8786	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8787	 || ((lba + num_blocks) < lba)) {
8788		ctl_set_lba_out_of_range(ctsio,
8789		    MAX(lba, lun->be_lun->maxlba + 1));
8790		ctl_done((union ctl_io *)ctsio);
8791		return (CTL_RETVAL_COMPLETE);
8792	}
8793
8794	/*
8795	 * According to SBC-3, a transfer length of 0 is not an error.
8796	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8797	 * translates to 256 blocks for those commands.
8798	 */
8799	if (num_blocks == 0) {
8800		ctl_set_success(ctsio);
8801		ctl_done((union ctl_io *)ctsio);
8802		return (CTL_RETVAL_COMPLETE);
8803	}
8804
8805	/* Set FUA and/or DPO if caches are disabled. */
8806	if (isread) {
8807		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8808			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8809	} else {
8810		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8811			flags |= CTL_LLF_FUA;
8812	}
8813
8814	lbalen = (struct ctl_lba_len_flags *)
8815	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8816	lbalen->lba = lba;
8817	lbalen->len = num_blocks;
8818	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8819
8820	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8821	ctsio->kern_rel_offset = 0;
8822
8823	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8824
8825	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8826	return (retval);
8827}
8828
8829static int
8830ctl_cnw_cont(union ctl_io *io)
8831{
8832	struct ctl_scsiio *ctsio;
8833	struct ctl_lun *lun;
8834	struct ctl_lba_len_flags *lbalen;
8835	int retval;
8836
8837	ctsio = &io->scsiio;
8838	ctsio->io_hdr.status = CTL_STATUS_NONE;
8839	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8840	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8841	lbalen = (struct ctl_lba_len_flags *)
8842	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8843	lbalen->flags &= ~CTL_LLF_COMPARE;
8844	lbalen->flags |= CTL_LLF_WRITE;
8845
8846	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8847	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8848	return (retval);
8849}
8850
8851int
8852ctl_cnw(struct ctl_scsiio *ctsio)
8853{
8854	struct ctl_lun *lun;
8855	struct ctl_lba_len_flags *lbalen;
8856	uint64_t lba;
8857	uint32_t num_blocks;
8858	int flags, retval;
8859
8860	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8861
8862	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8863
8864	flags = 0;
8865	switch (ctsio->cdb[0]) {
8866	case COMPARE_AND_WRITE: {
8867		struct scsi_compare_and_write *cdb;
8868
8869		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8870		if (cdb->byte2 & SRW10_FUA)
8871			flags |= CTL_LLF_FUA;
8872		if (cdb->byte2 & SRW10_DPO)
8873			flags |= CTL_LLF_DPO;
8874		lba = scsi_8btou64(cdb->addr);
8875		num_blocks = cdb->length;
8876		break;
8877	}
8878	default:
8879		/*
8880		 * We got a command we don't support.  This shouldn't
8881		 * happen, commands should be filtered out above us.
8882		 */
8883		ctl_set_invalid_opcode(ctsio);
8884		ctl_done((union ctl_io *)ctsio);
8885
8886		return (CTL_RETVAL_COMPLETE);
8887		break; /* NOTREACHED */
8888	}
8889
8890	/*
8891	 * The first check is to make sure we're in bounds, the second
8892	 * check is to catch wrap-around problems.  If the lba + num blocks
8893	 * is less than the lba, then we've wrapped around and the block
8894	 * range is invalid anyway.
8895	 */
8896	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8897	 || ((lba + num_blocks) < lba)) {
8898		ctl_set_lba_out_of_range(ctsio,
8899		    MAX(lba, lun->be_lun->maxlba + 1));
8900		ctl_done((union ctl_io *)ctsio);
8901		return (CTL_RETVAL_COMPLETE);
8902	}
8903
8904	/*
8905	 * According to SBC-3, a transfer length of 0 is not an error.
8906	 */
8907	if (num_blocks == 0) {
8908		ctl_set_success(ctsio);
8909		ctl_done((union ctl_io *)ctsio);
8910		return (CTL_RETVAL_COMPLETE);
8911	}
8912
8913	/* Set FUA if write cache is disabled. */
8914	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8915		flags |= CTL_LLF_FUA;
8916
8917	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8918	ctsio->kern_rel_offset = 0;
8919
8920	/*
8921	 * Set the IO_CONT flag, so that if this I/O gets passed to
8922	 * ctl_data_submit_done(), it'll get passed back to
8923	 * ctl_ctl_cnw_cont() for further processing.
8924	 */
8925	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8926	ctsio->io_cont = ctl_cnw_cont;
8927
8928	lbalen = (struct ctl_lba_len_flags *)
8929	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8930	lbalen->lba = lba;
8931	lbalen->len = num_blocks;
8932	lbalen->flags = CTL_LLF_COMPARE | flags;
8933
8934	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8935	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8936	return (retval);
8937}
8938
8939int
8940ctl_verify(struct ctl_scsiio *ctsio)
8941{
8942	struct ctl_lun *lun;
8943	struct ctl_lba_len_flags *lbalen;
8944	uint64_t lba;
8945	uint32_t num_blocks;
8946	int bytchk, flags;
8947	int retval;
8948
8949	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8950
8951	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8952
8953	bytchk = 0;
8954	flags = CTL_LLF_FUA;
8955	switch (ctsio->cdb[0]) {
8956	case VERIFY_10: {
8957		struct scsi_verify_10 *cdb;
8958
8959		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8960		if (cdb->byte2 & SVFY_BYTCHK)
8961			bytchk = 1;
8962		if (cdb->byte2 & SVFY_DPO)
8963			flags |= CTL_LLF_DPO;
8964		lba = scsi_4btoul(cdb->addr);
8965		num_blocks = scsi_2btoul(cdb->length);
8966		break;
8967	}
8968	case VERIFY_12: {
8969		struct scsi_verify_12 *cdb;
8970
8971		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8972		if (cdb->byte2 & SVFY_BYTCHK)
8973			bytchk = 1;
8974		if (cdb->byte2 & SVFY_DPO)
8975			flags |= CTL_LLF_DPO;
8976		lba = scsi_4btoul(cdb->addr);
8977		num_blocks = scsi_4btoul(cdb->length);
8978		break;
8979	}
8980	case VERIFY_16: {
8981		struct scsi_rw_16 *cdb;
8982
8983		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8984		if (cdb->byte2 & SVFY_BYTCHK)
8985			bytchk = 1;
8986		if (cdb->byte2 & SVFY_DPO)
8987			flags |= CTL_LLF_DPO;
8988		lba = scsi_8btou64(cdb->addr);
8989		num_blocks = scsi_4btoul(cdb->length);
8990		break;
8991	}
8992	default:
8993		/*
8994		 * We got a command we don't support.  This shouldn't
8995		 * happen, commands should be filtered out above us.
8996		 */
8997		ctl_set_invalid_opcode(ctsio);
8998		ctl_done((union ctl_io *)ctsio);
8999		return (CTL_RETVAL_COMPLETE);
9000	}
9001
9002	/*
9003	 * The first check is to make sure we're in bounds, the second
9004	 * check is to catch wrap-around problems.  If the lba + num blocks
9005	 * is less than the lba, then we've wrapped around and the block
9006	 * range is invalid anyway.
9007	 */
9008	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9009	 || ((lba + num_blocks) < lba)) {
9010		ctl_set_lba_out_of_range(ctsio,
9011		    MAX(lba, lun->be_lun->maxlba + 1));
9012		ctl_done((union ctl_io *)ctsio);
9013		return (CTL_RETVAL_COMPLETE);
9014	}
9015
9016	/*
9017	 * According to SBC-3, a transfer length of 0 is not an error.
9018	 */
9019	if (num_blocks == 0) {
9020		ctl_set_success(ctsio);
9021		ctl_done((union ctl_io *)ctsio);
9022		return (CTL_RETVAL_COMPLETE);
9023	}
9024
9025	lbalen = (struct ctl_lba_len_flags *)
9026	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9027	lbalen->lba = lba;
9028	lbalen->len = num_blocks;
9029	if (bytchk) {
9030		lbalen->flags = CTL_LLF_COMPARE | flags;
9031		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9032	} else {
9033		lbalen->flags = CTL_LLF_VERIFY | flags;
9034		ctsio->kern_total_len = 0;
9035	}
9036	ctsio->kern_rel_offset = 0;
9037
9038	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9039	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9040	return (retval);
9041}
9042
9043int
9044ctl_report_luns(struct ctl_scsiio *ctsio)
9045{
9046	struct ctl_softc *softc;
9047	struct scsi_report_luns *cdb;
9048	struct scsi_report_luns_data *lun_data;
9049	struct ctl_lun *lun, *request_lun;
9050	struct ctl_port *port;
9051	int num_luns, retval;
9052	uint32_t alloc_len, lun_datalen;
9053	int num_filled;
9054	uint32_t initidx, targ_lun_id, lun_id;
9055
9056	retval = CTL_RETVAL_COMPLETE;
9057	cdb = (struct scsi_report_luns *)ctsio->cdb;
9058	port = ctl_io_port(&ctsio->io_hdr);
9059	softc = port->ctl_softc;
9060
9061	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9062
9063	mtx_lock(&softc->ctl_lock);
9064	num_luns = 0;
9065	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9066		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9067			num_luns++;
9068	}
9069	mtx_unlock(&softc->ctl_lock);
9070
9071	switch (cdb->select_report) {
9072	case RPL_REPORT_DEFAULT:
9073	case RPL_REPORT_ALL:
9074	case RPL_REPORT_NONSUBSID:
9075		break;
9076	case RPL_REPORT_WELLKNOWN:
9077	case RPL_REPORT_ADMIN:
9078	case RPL_REPORT_CONGLOM:
9079		num_luns = 0;
9080		break;
9081	default:
9082		ctl_set_invalid_field(ctsio,
9083				      /*sks_valid*/ 1,
9084				      /*command*/ 1,
9085				      /*field*/ 2,
9086				      /*bit_valid*/ 0,
9087				      /*bit*/ 0);
9088		ctl_done((union ctl_io *)ctsio);
9089		return (retval);
9090		break; /* NOTREACHED */
9091	}
9092
9093	alloc_len = scsi_4btoul(cdb->length);
9094	/*
9095	 * The initiator has to allocate at least 16 bytes for this request,
9096	 * so he can at least get the header and the first LUN.  Otherwise
9097	 * we reject the request (per SPC-3 rev 14, section 6.21).
9098	 */
9099	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9100	    sizeof(struct scsi_report_luns_lundata))) {
9101		ctl_set_invalid_field(ctsio,
9102				      /*sks_valid*/ 1,
9103				      /*command*/ 1,
9104				      /*field*/ 6,
9105				      /*bit_valid*/ 0,
9106				      /*bit*/ 0);
9107		ctl_done((union ctl_io *)ctsio);
9108		return (retval);
9109	}
9110
9111	request_lun = (struct ctl_lun *)
9112		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9113
9114	lun_datalen = sizeof(*lun_data) +
9115		(num_luns * sizeof(struct scsi_report_luns_lundata));
9116
9117	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9118	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9119	ctsio->kern_sg_entries = 0;
9120
9121	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9122
9123	mtx_lock(&softc->ctl_lock);
9124	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9125		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9126		if (lun_id == UINT32_MAX)
9127			continue;
9128		lun = softc->ctl_luns[lun_id];
9129		if (lun == NULL)
9130			continue;
9131
9132		be64enc(lun_data->luns[num_filled++].lundata,
9133		    ctl_encode_lun(targ_lun_id));
9134
9135		/*
9136		 * According to SPC-3, rev 14 section 6.21:
9137		 *
9138		 * "The execution of a REPORT LUNS command to any valid and
9139		 * installed logical unit shall clear the REPORTED LUNS DATA
9140		 * HAS CHANGED unit attention condition for all logical
9141		 * units of that target with respect to the requesting
9142		 * initiator. A valid and installed logical unit is one
9143		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9144		 * INQUIRY data (see 6.4.2)."
9145		 *
9146		 * If request_lun is NULL, the LUN this report luns command
9147		 * was issued to is either disabled or doesn't exist. In that
9148		 * case, we shouldn't clear any pending lun change unit
9149		 * attention.
9150		 */
9151		if (request_lun != NULL) {
9152			mtx_lock(&lun->lun_lock);
9153			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9154			mtx_unlock(&lun->lun_lock);
9155		}
9156	}
9157	mtx_unlock(&softc->ctl_lock);
9158
9159	/*
9160	 * It's quite possible that we've returned fewer LUNs than we allocated
9161	 * space for.  Trim it.
9162	 */
9163	lun_datalen = sizeof(*lun_data) +
9164		(num_filled * sizeof(struct scsi_report_luns_lundata));
9165
9166	if (lun_datalen < alloc_len) {
9167		ctsio->residual = alloc_len - lun_datalen;
9168		ctsio->kern_data_len = lun_datalen;
9169		ctsio->kern_total_len = lun_datalen;
9170	} else {
9171		ctsio->residual = 0;
9172		ctsio->kern_data_len = alloc_len;
9173		ctsio->kern_total_len = alloc_len;
9174	}
9175	ctsio->kern_data_resid = 0;
9176	ctsio->kern_rel_offset = 0;
9177	ctsio->kern_sg_entries = 0;
9178
9179	/*
9180	 * We set this to the actual data length, regardless of how much
9181	 * space we actually have to return results.  If the user looks at
9182	 * this value, he'll know whether or not he allocated enough space
9183	 * and reissue the command if necessary.  We don't support well
9184	 * known logical units, so if the user asks for that, return none.
9185	 */
9186	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9187
9188	/*
9189	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9190	 * this request.
9191	 */
9192	ctl_set_success(ctsio);
9193	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9194	ctsio->be_move_done = ctl_config_move_done;
9195	ctl_datamove((union ctl_io *)ctsio);
9196	return (retval);
9197}
9198
9199int
9200ctl_request_sense(struct ctl_scsiio *ctsio)
9201{
9202	struct scsi_request_sense *cdb;
9203	struct scsi_sense_data *sense_ptr;
9204	struct ctl_softc *softc;
9205	struct ctl_lun *lun;
9206	uint32_t initidx;
9207	int have_error;
9208	u_int sense_len = SSD_FULL_SIZE;
9209	scsi_sense_data_type sense_format;
9210	ctl_ua_type ua_type;
9211	uint8_t asc = 0, ascq = 0;
9212
9213	cdb = (struct scsi_request_sense *)ctsio->cdb;
9214
9215	softc = control_softc;
9216	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9217
9218	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9219
9220	/*
9221	 * Determine which sense format the user wants.
9222	 */
9223	if (cdb->byte2 & SRS_DESC)
9224		sense_format = SSD_TYPE_DESC;
9225	else
9226		sense_format = SSD_TYPE_FIXED;
9227
9228	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9229	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9230	ctsio->kern_sg_entries = 0;
9231
9232	/*
9233	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9234	 * larger than the largest allowed value for the length field in the
9235	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9236	 */
9237	ctsio->residual = 0;
9238	ctsio->kern_data_len = cdb->length;
9239	ctsio->kern_total_len = cdb->length;
9240
9241	ctsio->kern_data_resid = 0;
9242	ctsio->kern_rel_offset = 0;
9243	ctsio->kern_sg_entries = 0;
9244
9245	/*
9246	 * If we don't have a LUN, we don't have any pending sense.
9247	 */
9248	if (lun == NULL ||
9249	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9250	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9251		/* "Logical unit not supported" */
9252		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9253		    /*current_error*/ 1,
9254		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9255		    /*asc*/ 0x25,
9256		    /*ascq*/ 0x00,
9257		    SSD_ELEM_NONE);
9258		goto send;
9259	}
9260
9261	have_error = 0;
9262	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9263	/*
9264	 * Check for pending sense, and then for pending unit attentions.
9265	 * Pending sense gets returned first, then pending unit attentions.
9266	 */
9267	mtx_lock(&lun->lun_lock);
9268#ifdef CTL_WITH_CA
9269	if (ctl_is_set(lun->have_ca, initidx)) {
9270		scsi_sense_data_type stored_format;
9271
9272		/*
9273		 * Check to see which sense format was used for the stored
9274		 * sense data.
9275		 */
9276		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9277
9278		/*
9279		 * If the user requested a different sense format than the
9280		 * one we stored, then we need to convert it to the other
9281		 * format.  If we're going from descriptor to fixed format
9282		 * sense data, we may lose things in translation, depending
9283		 * on what options were used.
9284		 *
9285		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9286		 * for some reason we'll just copy it out as-is.
9287		 */
9288		if ((stored_format == SSD_TYPE_FIXED)
9289		 && (sense_format == SSD_TYPE_DESC))
9290			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9291			    &lun->pending_sense[initidx],
9292			    (struct scsi_sense_data_desc *)sense_ptr);
9293		else if ((stored_format == SSD_TYPE_DESC)
9294		      && (sense_format == SSD_TYPE_FIXED))
9295			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9296			    &lun->pending_sense[initidx],
9297			    (struct scsi_sense_data_fixed *)sense_ptr);
9298		else
9299			memcpy(sense_ptr, &lun->pending_sense[initidx],
9300			       MIN(sizeof(*sense_ptr),
9301			       sizeof(lun->pending_sense[initidx])));
9302
9303		ctl_clear_mask(lun->have_ca, initidx);
9304		have_error = 1;
9305	} else
9306#endif
9307	if (have_error == 0) {
9308		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9309		    sense_format);
9310		if (ua_type != CTL_UA_NONE)
9311			have_error = 1;
9312	}
9313	if (have_error == 0) {
9314		/*
9315		 * Report informational exception if have one and allowed.
9316		 */
9317		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9318			asc = lun->ie_asc;
9319			ascq = lun->ie_ascq;
9320		}
9321		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9322		    /*current_error*/ 1,
9323		    /*sense_key*/ SSD_KEY_NO_SENSE,
9324		    /*asc*/ asc,
9325		    /*ascq*/ ascq,
9326		    SSD_ELEM_NONE);
9327	}
9328	mtx_unlock(&lun->lun_lock);
9329
9330send:
9331	/*
9332	 * We report the SCSI status as OK, since the status of the command
9333	 * itself is OK.  We're reporting sense as parameter data.
9334	 */
9335	ctl_set_success(ctsio);
9336	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9337	ctsio->be_move_done = ctl_config_move_done;
9338	ctl_datamove((union ctl_io *)ctsio);
9339	return (CTL_RETVAL_COMPLETE);
9340}
9341
9342int
9343ctl_tur(struct ctl_scsiio *ctsio)
9344{
9345
9346	CTL_DEBUG_PRINT(("ctl_tur\n"));
9347
9348	ctl_set_success(ctsio);
9349	ctl_done((union ctl_io *)ctsio);
9350
9351	return (CTL_RETVAL_COMPLETE);
9352}
9353
9354/*
9355 * SCSI VPD page 0x00, the Supported VPD Pages page.
9356 */
9357static int
9358ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9359{
9360	struct scsi_vpd_supported_pages *pages;
9361	int sup_page_size;
9362	struct ctl_lun *lun;
9363	int p;
9364
9365	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9366
9367	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9368	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9369	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9370	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9371	ctsio->kern_sg_entries = 0;
9372
9373	if (sup_page_size < alloc_len) {
9374		ctsio->residual = alloc_len - sup_page_size;
9375		ctsio->kern_data_len = sup_page_size;
9376		ctsio->kern_total_len = sup_page_size;
9377	} else {
9378		ctsio->residual = 0;
9379		ctsio->kern_data_len = alloc_len;
9380		ctsio->kern_total_len = alloc_len;
9381	}
9382	ctsio->kern_data_resid = 0;
9383	ctsio->kern_rel_offset = 0;
9384	ctsio->kern_sg_entries = 0;
9385
9386	/*
9387	 * The control device is always connected.  The disk device, on the
9388	 * other hand, may not be online all the time.  Need to change this
9389	 * to figure out whether the disk device is actually online or not.
9390	 */
9391	if (lun != NULL)
9392		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9393				lun->be_lun->lun_type;
9394	else
9395		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9396
9397	p = 0;
9398	/* Supported VPD pages */
9399	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9400	/* Serial Number */
9401	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9402	/* Device Identification */
9403	pages->page_list[p++] = SVPD_DEVICE_ID;
9404	/* Extended INQUIRY Data */
9405	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9406	/* Mode Page Policy */
9407	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9408	/* SCSI Ports */
9409	pages->page_list[p++] = SVPD_SCSI_PORTS;
9410	/* Third-party Copy */
9411	pages->page_list[p++] = SVPD_SCSI_TPC;
9412	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9413		/* Block limits */
9414		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9415		/* Block Device Characteristics */
9416		pages->page_list[p++] = SVPD_BDC;
9417		/* Logical Block Provisioning */
9418		pages->page_list[p++] = SVPD_LBP;
9419	}
9420	pages->length = p;
9421
9422	ctl_set_success(ctsio);
9423	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9424	ctsio->be_move_done = ctl_config_move_done;
9425	ctl_datamove((union ctl_io *)ctsio);
9426	return (CTL_RETVAL_COMPLETE);
9427}
9428
9429/*
9430 * SCSI VPD page 0x80, the Unit Serial Number page.
9431 */
9432static int
9433ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9434{
9435	struct scsi_vpd_unit_serial_number *sn_ptr;
9436	struct ctl_lun *lun;
9437	int data_len;
9438
9439	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9440
9441	data_len = 4 + CTL_SN_LEN;
9442	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9443	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9444	if (data_len < alloc_len) {
9445		ctsio->residual = alloc_len - data_len;
9446		ctsio->kern_data_len = data_len;
9447		ctsio->kern_total_len = data_len;
9448	} else {
9449		ctsio->residual = 0;
9450		ctsio->kern_data_len = alloc_len;
9451		ctsio->kern_total_len = alloc_len;
9452	}
9453	ctsio->kern_data_resid = 0;
9454	ctsio->kern_rel_offset = 0;
9455	ctsio->kern_sg_entries = 0;
9456
9457	/*
9458	 * The control device is always connected.  The disk device, on the
9459	 * other hand, may not be online all the time.  Need to change this
9460	 * to figure out whether the disk device is actually online or not.
9461	 */
9462	if (lun != NULL)
9463		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9464				  lun->be_lun->lun_type;
9465	else
9466		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9467
9468	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9469	sn_ptr->length = CTL_SN_LEN;
9470	/*
9471	 * If we don't have a LUN, we just leave the serial number as
9472	 * all spaces.
9473	 */
9474	if (lun != NULL) {
9475		strncpy((char *)sn_ptr->serial_num,
9476			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9477	} else
9478		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9479
9480	ctl_set_success(ctsio);
9481	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9482	ctsio->be_move_done = ctl_config_move_done;
9483	ctl_datamove((union ctl_io *)ctsio);
9484	return (CTL_RETVAL_COMPLETE);
9485}
9486
9487
9488/*
9489 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9490 */
9491static int
9492ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9493{
9494	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9495	struct ctl_lun *lun;
9496	int data_len;
9497
9498	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9499
9500	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9501	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9502	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9503	ctsio->kern_sg_entries = 0;
9504
9505	if (data_len < alloc_len) {
9506		ctsio->residual = alloc_len - data_len;
9507		ctsio->kern_data_len = data_len;
9508		ctsio->kern_total_len = data_len;
9509	} else {
9510		ctsio->residual = 0;
9511		ctsio->kern_data_len = alloc_len;
9512		ctsio->kern_total_len = alloc_len;
9513	}
9514	ctsio->kern_data_resid = 0;
9515	ctsio->kern_rel_offset = 0;
9516	ctsio->kern_sg_entries = 0;
9517
9518	/*
9519	 * The control device is always connected.  The disk device, on the
9520	 * other hand, may not be online all the time.
9521	 */
9522	if (lun != NULL)
9523		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9524				     lun->be_lun->lun_type;
9525	else
9526		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9527	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9528	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9529	/*
9530	 * We support head of queue, ordered and simple tags.
9531	 */
9532	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9533	/*
9534	 * Volatile cache supported.
9535	 */
9536	eid_ptr->flags3 = SVPD_EID_V_SUP;
9537
9538	/*
9539	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9540	 * attention for a particular IT nexus on all LUNs once we report
9541	 * it to that nexus once.  This bit is required as of SPC-4.
9542	 */
9543	eid_ptr->flags4 = SVPD_EID_LUICLR;
9544
9545	/*
9546	 * XXX KDM in order to correctly answer this, we would need
9547	 * information from the SIM to determine how much sense data it
9548	 * can send.  So this would really be a path inquiry field, most
9549	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9550	 * but the hardware may or may not be able to support that much.
9551	 * 0 just means that the maximum sense data length is not reported.
9552	 */
9553	eid_ptr->max_sense_length = 0;
9554
9555	ctl_set_success(ctsio);
9556	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9557	ctsio->be_move_done = ctl_config_move_done;
9558	ctl_datamove((union ctl_io *)ctsio);
9559	return (CTL_RETVAL_COMPLETE);
9560}
9561
9562static int
9563ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9564{
9565	struct scsi_vpd_mode_page_policy *mpp_ptr;
9566	struct ctl_lun *lun;
9567	int data_len;
9568
9569	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9570
9571	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9572	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9573
9574	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9575	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9576	ctsio->kern_sg_entries = 0;
9577
9578	if (data_len < alloc_len) {
9579		ctsio->residual = alloc_len - data_len;
9580		ctsio->kern_data_len = data_len;
9581		ctsio->kern_total_len = data_len;
9582	} else {
9583		ctsio->residual = 0;
9584		ctsio->kern_data_len = alloc_len;
9585		ctsio->kern_total_len = alloc_len;
9586	}
9587	ctsio->kern_data_resid = 0;
9588	ctsio->kern_rel_offset = 0;
9589	ctsio->kern_sg_entries = 0;
9590
9591	/*
9592	 * The control device is always connected.  The disk device, on the
9593	 * other hand, may not be online all the time.
9594	 */
9595	if (lun != NULL)
9596		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9597				     lun->be_lun->lun_type;
9598	else
9599		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9600	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9601	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9602	mpp_ptr->descr[0].page_code = 0x3f;
9603	mpp_ptr->descr[0].subpage_code = 0xff;
9604	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9605
9606	ctl_set_success(ctsio);
9607	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9608	ctsio->be_move_done = ctl_config_move_done;
9609	ctl_datamove((union ctl_io *)ctsio);
9610	return (CTL_RETVAL_COMPLETE);
9611}
9612
9613/*
9614 * SCSI VPD page 0x83, the Device Identification page.
9615 */
9616static int
9617ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9618{
9619	struct scsi_vpd_device_id *devid_ptr;
9620	struct scsi_vpd_id_descriptor *desc;
9621	struct ctl_softc *softc;
9622	struct ctl_lun *lun;
9623	struct ctl_port *port;
9624	int data_len, g;
9625	uint8_t proto;
9626
9627	softc = control_softc;
9628
9629	port = ctl_io_port(&ctsio->io_hdr);
9630	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9631
9632	data_len = sizeof(struct scsi_vpd_device_id) +
9633	    sizeof(struct scsi_vpd_id_descriptor) +
9634		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9635	    sizeof(struct scsi_vpd_id_descriptor) +
9636		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9637	if (lun && lun->lun_devid)
9638		data_len += lun->lun_devid->len;
9639	if (port && port->port_devid)
9640		data_len += port->port_devid->len;
9641	if (port && port->target_devid)
9642		data_len += port->target_devid->len;
9643
9644	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9645	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9646	ctsio->kern_sg_entries = 0;
9647
9648	if (data_len < alloc_len) {
9649		ctsio->residual = alloc_len - data_len;
9650		ctsio->kern_data_len = data_len;
9651		ctsio->kern_total_len = data_len;
9652	} else {
9653		ctsio->residual = 0;
9654		ctsio->kern_data_len = alloc_len;
9655		ctsio->kern_total_len = alloc_len;
9656	}
9657	ctsio->kern_data_resid = 0;
9658	ctsio->kern_rel_offset = 0;
9659	ctsio->kern_sg_entries = 0;
9660
9661	/*
9662	 * The control device is always connected.  The disk device, on the
9663	 * other hand, may not be online all the time.
9664	 */
9665	if (lun != NULL)
9666		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9667				     lun->be_lun->lun_type;
9668	else
9669		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9670	devid_ptr->page_code = SVPD_DEVICE_ID;
9671	scsi_ulto2b(data_len - 4, devid_ptr->length);
9672
9673	if (port && port->port_type == CTL_PORT_FC)
9674		proto = SCSI_PROTO_FC << 4;
9675	else if (port && port->port_type == CTL_PORT_ISCSI)
9676		proto = SCSI_PROTO_ISCSI << 4;
9677	else
9678		proto = SCSI_PROTO_SPI << 4;
9679	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9680
9681	/*
9682	 * We're using a LUN association here.  i.e., this device ID is a
9683	 * per-LUN identifier.
9684	 */
9685	if (lun && lun->lun_devid) {
9686		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9687		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9688		    lun->lun_devid->len);
9689	}
9690
9691	/*
9692	 * This is for the WWPN which is a port association.
9693	 */
9694	if (port && port->port_devid) {
9695		memcpy(desc, port->port_devid->data, port->port_devid->len);
9696		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9697		    port->port_devid->len);
9698	}
9699
9700	/*
9701	 * This is for the Relative Target Port(type 4h) identifier
9702	 */
9703	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9704	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9705	    SVPD_ID_TYPE_RELTARG;
9706	desc->length = 4;
9707	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9708	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9709	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9710
9711	/*
9712	 * This is for the Target Port Group(type 5h) identifier
9713	 */
9714	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9715	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9716	    SVPD_ID_TYPE_TPORTGRP;
9717	desc->length = 4;
9718	if (softc->is_single ||
9719	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9720		g = 1;
9721	else
9722		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9723	scsi_ulto2b(g, &desc->identifier[2]);
9724	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9725	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9726
9727	/*
9728	 * This is for the Target identifier
9729	 */
9730	if (port && port->target_devid) {
9731		memcpy(desc, port->target_devid->data, port->target_devid->len);
9732	}
9733
9734	ctl_set_success(ctsio);
9735	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9736	ctsio->be_move_done = ctl_config_move_done;
9737	ctl_datamove((union ctl_io *)ctsio);
9738	return (CTL_RETVAL_COMPLETE);
9739}
9740
9741static int
9742ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9743{
9744	struct ctl_softc *softc = control_softc;
9745	struct scsi_vpd_scsi_ports *sp;
9746	struct scsi_vpd_port_designation *pd;
9747	struct scsi_vpd_port_designation_cont *pdc;
9748	struct ctl_lun *lun;
9749	struct ctl_port *port;
9750	int data_len, num_target_ports, iid_len, id_len;
9751
9752	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9753
9754	num_target_ports = 0;
9755	iid_len = 0;
9756	id_len = 0;
9757	mtx_lock(&softc->ctl_lock);
9758	STAILQ_FOREACH(port, &softc->port_list, links) {
9759		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9760			continue;
9761		if (lun != NULL &&
9762		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9763			continue;
9764		num_target_ports++;
9765		if (port->init_devid)
9766			iid_len += port->init_devid->len;
9767		if (port->port_devid)
9768			id_len += port->port_devid->len;
9769	}
9770	mtx_unlock(&softc->ctl_lock);
9771
9772	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9773	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9774	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9775	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9776	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9777	ctsio->kern_sg_entries = 0;
9778
9779	if (data_len < alloc_len) {
9780		ctsio->residual = alloc_len - data_len;
9781		ctsio->kern_data_len = data_len;
9782		ctsio->kern_total_len = data_len;
9783	} else {
9784		ctsio->residual = 0;
9785		ctsio->kern_data_len = alloc_len;
9786		ctsio->kern_total_len = alloc_len;
9787	}
9788	ctsio->kern_data_resid = 0;
9789	ctsio->kern_rel_offset = 0;
9790	ctsio->kern_sg_entries = 0;
9791
9792	/*
9793	 * The control device is always connected.  The disk device, on the
9794	 * other hand, may not be online all the time.  Need to change this
9795	 * to figure out whether the disk device is actually online or not.
9796	 */
9797	if (lun != NULL)
9798		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9799				  lun->be_lun->lun_type;
9800	else
9801		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9802
9803	sp->page_code = SVPD_SCSI_PORTS;
9804	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9805	    sp->page_length);
9806	pd = &sp->design[0];
9807
9808	mtx_lock(&softc->ctl_lock);
9809	STAILQ_FOREACH(port, &softc->port_list, links) {
9810		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9811			continue;
9812		if (lun != NULL &&
9813		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9814			continue;
9815		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9816		if (port->init_devid) {
9817			iid_len = port->init_devid->len;
9818			memcpy(pd->initiator_transportid,
9819			    port->init_devid->data, port->init_devid->len);
9820		} else
9821			iid_len = 0;
9822		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9823		pdc = (struct scsi_vpd_port_designation_cont *)
9824		    (&pd->initiator_transportid[iid_len]);
9825		if (port->port_devid) {
9826			id_len = port->port_devid->len;
9827			memcpy(pdc->target_port_descriptors,
9828			    port->port_devid->data, port->port_devid->len);
9829		} else
9830			id_len = 0;
9831		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9832		pd = (struct scsi_vpd_port_designation *)
9833		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9834	}
9835	mtx_unlock(&softc->ctl_lock);
9836
9837	ctl_set_success(ctsio);
9838	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9839	ctsio->be_move_done = ctl_config_move_done;
9840	ctl_datamove((union ctl_io *)ctsio);
9841	return (CTL_RETVAL_COMPLETE);
9842}
9843
9844static int
9845ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9846{
9847	struct scsi_vpd_block_limits *bl_ptr;
9848	struct ctl_lun *lun;
9849	uint64_t ival;
9850
9851	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9852
9853	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9854	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9855	ctsio->kern_sg_entries = 0;
9856
9857	if (sizeof(*bl_ptr) < alloc_len) {
9858		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9859		ctsio->kern_data_len = sizeof(*bl_ptr);
9860		ctsio->kern_total_len = sizeof(*bl_ptr);
9861	} else {
9862		ctsio->residual = 0;
9863		ctsio->kern_data_len = alloc_len;
9864		ctsio->kern_total_len = alloc_len;
9865	}
9866	ctsio->kern_data_resid = 0;
9867	ctsio->kern_rel_offset = 0;
9868	ctsio->kern_sg_entries = 0;
9869
9870	/*
9871	 * The control device is always connected.  The disk device, on the
9872	 * other hand, may not be online all the time.  Need to change this
9873	 * to figure out whether the disk device is actually online or not.
9874	 */
9875	if (lun != NULL)
9876		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9877				  lun->be_lun->lun_type;
9878	else
9879		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9880
9881	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9882	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9883	bl_ptr->max_cmp_write_len = 0xff;
9884	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9885	if (lun != NULL) {
9886		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9887		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9888			ival = 0xffffffff;
9889			ctl_get_opt_number(&lun->be_lun->options,
9890			    "unmap_max_lba", &ival);
9891			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9892			ival = 0xffffffff;
9893			ctl_get_opt_number(&lun->be_lun->options,
9894			    "unmap_max_descr", &ival);
9895			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9896			if (lun->be_lun->ublockexp != 0) {
9897				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9898				    bl_ptr->opt_unmap_grain);
9899				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9900				    bl_ptr->unmap_grain_align);
9901			}
9902		}
9903		scsi_ulto4b(lun->be_lun->atomicblock,
9904		    bl_ptr->max_atomic_transfer_length);
9905		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9906		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9907		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9908		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9909		ival = UINT64_MAX;
9910		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9911		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9912	}
9913
9914	ctl_set_success(ctsio);
9915	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9916	ctsio->be_move_done = ctl_config_move_done;
9917	ctl_datamove((union ctl_io *)ctsio);
9918	return (CTL_RETVAL_COMPLETE);
9919}
9920
9921static int
9922ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9923{
9924	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9925	struct ctl_lun *lun;
9926	const char *value;
9927	u_int i;
9928
9929	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9930
9931	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9932	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9933	ctsio->kern_sg_entries = 0;
9934
9935	if (sizeof(*bdc_ptr) < alloc_len) {
9936		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9937		ctsio->kern_data_len = sizeof(*bdc_ptr);
9938		ctsio->kern_total_len = sizeof(*bdc_ptr);
9939	} else {
9940		ctsio->residual = 0;
9941		ctsio->kern_data_len = alloc_len;
9942		ctsio->kern_total_len = alloc_len;
9943	}
9944	ctsio->kern_data_resid = 0;
9945	ctsio->kern_rel_offset = 0;
9946	ctsio->kern_sg_entries = 0;
9947
9948	/*
9949	 * The control device is always connected.  The disk device, on the
9950	 * other hand, may not be online all the time.  Need to change this
9951	 * to figure out whether the disk device is actually online or not.
9952	 */
9953	if (lun != NULL)
9954		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9955				  lun->be_lun->lun_type;
9956	else
9957		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9958	bdc_ptr->page_code = SVPD_BDC;
9959	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9960	if (lun != NULL &&
9961	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9962		i = strtol(value, NULL, 0);
9963	else
9964		i = CTL_DEFAULT_ROTATION_RATE;
9965	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9966	if (lun != NULL &&
9967	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9968		i = strtol(value, NULL, 0);
9969	else
9970		i = 0;
9971	bdc_ptr->wab_wac_ff = (i & 0x0f);
9972	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9973
9974	ctl_set_success(ctsio);
9975	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9976	ctsio->be_move_done = ctl_config_move_done;
9977	ctl_datamove((union ctl_io *)ctsio);
9978	return (CTL_RETVAL_COMPLETE);
9979}
9980
9981static int
9982ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9983{
9984	struct scsi_vpd_logical_block_prov *lbp_ptr;
9985	struct ctl_lun *lun;
9986	const char *value;
9987
9988	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9989
9990	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9991	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9992	ctsio->kern_sg_entries = 0;
9993
9994	if (sizeof(*lbp_ptr) < alloc_len) {
9995		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9996		ctsio->kern_data_len = sizeof(*lbp_ptr);
9997		ctsio->kern_total_len = sizeof(*lbp_ptr);
9998	} else {
9999		ctsio->residual = 0;
10000		ctsio->kern_data_len = alloc_len;
10001		ctsio->kern_total_len = alloc_len;
10002	}
10003	ctsio->kern_data_resid = 0;
10004	ctsio->kern_rel_offset = 0;
10005	ctsio->kern_sg_entries = 0;
10006
10007	/*
10008	 * The control device is always connected.  The disk device, on the
10009	 * other hand, may not be online all the time.  Need to change this
10010	 * to figure out whether the disk device is actually online or not.
10011	 */
10012	if (lun != NULL)
10013		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10014				  lun->be_lun->lun_type;
10015	else
10016		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10017
10018	lbp_ptr->page_code = SVPD_LBP;
10019	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10020	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10021	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10022		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10023		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10024		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10025		if (value != NULL) {
10026			if (strcmp(value, "resource") == 0)
10027				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10028			else if (strcmp(value, "thin") == 0)
10029				lbp_ptr->prov_type = SVPD_LBP_THIN;
10030		} else
10031			lbp_ptr->prov_type = SVPD_LBP_THIN;
10032	}
10033
10034	ctl_set_success(ctsio);
10035	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10036	ctsio->be_move_done = ctl_config_move_done;
10037	ctl_datamove((union ctl_io *)ctsio);
10038	return (CTL_RETVAL_COMPLETE);
10039}
10040
10041/*
10042 * INQUIRY with the EVPD bit set.
10043 */
10044static int
10045ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10046{
10047	struct ctl_lun *lun;
10048	struct scsi_inquiry *cdb;
10049	int alloc_len, retval;
10050
10051	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10052	cdb = (struct scsi_inquiry *)ctsio->cdb;
10053	alloc_len = scsi_2btoul(cdb->length);
10054
10055	switch (cdb->page_code) {
10056	case SVPD_SUPPORTED_PAGES:
10057		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10058		break;
10059	case SVPD_UNIT_SERIAL_NUMBER:
10060		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10061		break;
10062	case SVPD_DEVICE_ID:
10063		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10064		break;
10065	case SVPD_EXTENDED_INQUIRY_DATA:
10066		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10067		break;
10068	case SVPD_MODE_PAGE_POLICY:
10069		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10070		break;
10071	case SVPD_SCSI_PORTS:
10072		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10073		break;
10074	case SVPD_SCSI_TPC:
10075		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10076		break;
10077	case SVPD_BLOCK_LIMITS:
10078		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10079			goto err;
10080		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10081		break;
10082	case SVPD_BDC:
10083		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10084			goto err;
10085		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10086		break;
10087	case SVPD_LBP:
10088		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10089			goto err;
10090		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10091		break;
10092	default:
10093err:
10094		ctl_set_invalid_field(ctsio,
10095				      /*sks_valid*/ 1,
10096				      /*command*/ 1,
10097				      /*field*/ 2,
10098				      /*bit_valid*/ 0,
10099				      /*bit*/ 0);
10100		ctl_done((union ctl_io *)ctsio);
10101		retval = CTL_RETVAL_COMPLETE;
10102		break;
10103	}
10104
10105	return (retval);
10106}
10107
10108/*
10109 * Standard INQUIRY data.
10110 */
10111static int
10112ctl_inquiry_std(struct ctl_scsiio *ctsio)
10113{
10114	struct scsi_inquiry_data *inq_ptr;
10115	struct scsi_inquiry *cdb;
10116	struct ctl_softc *softc = control_softc;
10117	struct ctl_port *port;
10118	struct ctl_lun *lun;
10119	char *val;
10120	uint32_t alloc_len, data_len;
10121	ctl_port_type port_type;
10122
10123	port = ctl_io_port(&ctsio->io_hdr);
10124	port_type = port->port_type;
10125	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10126		port_type = CTL_PORT_SCSI;
10127
10128	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10129	cdb = (struct scsi_inquiry *)ctsio->cdb;
10130	alloc_len = scsi_2btoul(cdb->length);
10131
10132	/*
10133	 * We malloc the full inquiry data size here and fill it
10134	 * in.  If the user only asks for less, we'll give him
10135	 * that much.
10136	 */
10137	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10138	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10139	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10140	ctsio->kern_sg_entries = 0;
10141	ctsio->kern_data_resid = 0;
10142	ctsio->kern_rel_offset = 0;
10143
10144	if (data_len < alloc_len) {
10145		ctsio->residual = alloc_len - data_len;
10146		ctsio->kern_data_len = data_len;
10147		ctsio->kern_total_len = data_len;
10148	} else {
10149		ctsio->residual = 0;
10150		ctsio->kern_data_len = alloc_len;
10151		ctsio->kern_total_len = alloc_len;
10152	}
10153
10154	if (lun != NULL) {
10155		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10156		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10157			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10158			    lun->be_lun->lun_type;
10159		} else {
10160			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10161			    lun->be_lun->lun_type;
10162		}
10163		if (lun->flags & CTL_LUN_REMOVABLE)
10164			inq_ptr->dev_qual2 |= SID_RMB;
10165	} else
10166		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10167
10168	/* RMB in byte 2 is 0 */
10169	inq_ptr->version = SCSI_REV_SPC5;
10170
10171	/*
10172	 * According to SAM-3, even if a device only supports a single
10173	 * level of LUN addressing, it should still set the HISUP bit:
10174	 *
10175	 * 4.9.1 Logical unit numbers overview
10176	 *
10177	 * All logical unit number formats described in this standard are
10178	 * hierarchical in structure even when only a single level in that
10179	 * hierarchy is used. The HISUP bit shall be set to one in the
10180	 * standard INQUIRY data (see SPC-2) when any logical unit number
10181	 * format described in this standard is used.  Non-hierarchical
10182	 * formats are outside the scope of this standard.
10183	 *
10184	 * Therefore we set the HiSup bit here.
10185	 *
10186	 * The response format is 2, per SPC-3.
10187	 */
10188	inq_ptr->response_format = SID_HiSup | 2;
10189
10190	inq_ptr->additional_length = data_len -
10191	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10192	CTL_DEBUG_PRINT(("additional_length = %d\n",
10193			 inq_ptr->additional_length));
10194
10195	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10196	if (port_type == CTL_PORT_SCSI)
10197		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10198	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10199	inq_ptr->flags = SID_CmdQue;
10200	if (port_type == CTL_PORT_SCSI)
10201		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10202
10203	/*
10204	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10205	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10206	 * name and 4 bytes for the revision.
10207	 */
10208	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10209	    "vendor")) == NULL) {
10210		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10211	} else {
10212		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10213		strncpy(inq_ptr->vendor, val,
10214		    min(sizeof(inq_ptr->vendor), strlen(val)));
10215	}
10216	if (lun == NULL) {
10217		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10218		    sizeof(inq_ptr->product));
10219	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10220		switch (lun->be_lun->lun_type) {
10221		case T_DIRECT:
10222			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10223			    sizeof(inq_ptr->product));
10224			break;
10225		case T_PROCESSOR:
10226			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10227			    sizeof(inq_ptr->product));
10228			break;
10229		case T_CDROM:
10230			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10231			    sizeof(inq_ptr->product));
10232			break;
10233		default:
10234			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10235			    sizeof(inq_ptr->product));
10236			break;
10237		}
10238	} else {
10239		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10240		strncpy(inq_ptr->product, val,
10241		    min(sizeof(inq_ptr->product), strlen(val)));
10242	}
10243
10244	/*
10245	 * XXX make this a macro somewhere so it automatically gets
10246	 * incremented when we make changes.
10247	 */
10248	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10249	    "revision")) == NULL) {
10250		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10251	} else {
10252		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10253		strncpy(inq_ptr->revision, val,
10254		    min(sizeof(inq_ptr->revision), strlen(val)));
10255	}
10256
10257	/*
10258	 * For parallel SCSI, we support double transition and single
10259	 * transition clocking.  We also support QAS (Quick Arbitration
10260	 * and Selection) and Information Unit transfers on both the
10261	 * control and array devices.
10262	 */
10263	if (port_type == CTL_PORT_SCSI)
10264		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10265				    SID_SPI_IUS;
10266
10267	/* SAM-6 (no version claimed) */
10268	scsi_ulto2b(0x00C0, inq_ptr->version1);
10269	/* SPC-5 (no version claimed) */
10270	scsi_ulto2b(0x05C0, inq_ptr->version2);
10271	if (port_type == CTL_PORT_FC) {
10272		/* FCP-2 ANSI INCITS.350:2003 */
10273		scsi_ulto2b(0x0917, inq_ptr->version3);
10274	} else if (port_type == CTL_PORT_SCSI) {
10275		/* SPI-4 ANSI INCITS.362:200x */
10276		scsi_ulto2b(0x0B56, inq_ptr->version3);
10277	} else if (port_type == CTL_PORT_ISCSI) {
10278		/* iSCSI (no version claimed) */
10279		scsi_ulto2b(0x0960, inq_ptr->version3);
10280	} else if (port_type == CTL_PORT_SAS) {
10281		/* SAS (no version claimed) */
10282		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10283	}
10284
10285	if (lun == NULL) {
10286		/* SBC-4 (no version claimed) */
10287		scsi_ulto2b(0x0600, inq_ptr->version4);
10288	} else {
10289		switch (lun->be_lun->lun_type) {
10290		case T_DIRECT:
10291			/* SBC-4 (no version claimed) */
10292			scsi_ulto2b(0x0600, inq_ptr->version4);
10293			break;
10294		case T_PROCESSOR:
10295			break;
10296		case T_CDROM:
10297			/* MMC-6 (no version claimed) */
10298			scsi_ulto2b(0x04E0, inq_ptr->version4);
10299			break;
10300		default:
10301			break;
10302		}
10303	}
10304
10305	ctl_set_success(ctsio);
10306	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10307	ctsio->be_move_done = ctl_config_move_done;
10308	ctl_datamove((union ctl_io *)ctsio);
10309	return (CTL_RETVAL_COMPLETE);
10310}
10311
10312int
10313ctl_inquiry(struct ctl_scsiio *ctsio)
10314{
10315	struct scsi_inquiry *cdb;
10316	int retval;
10317
10318	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10319
10320	cdb = (struct scsi_inquiry *)ctsio->cdb;
10321	if (cdb->byte2 & SI_EVPD)
10322		retval = ctl_inquiry_evpd(ctsio);
10323	else if (cdb->page_code == 0)
10324		retval = ctl_inquiry_std(ctsio);
10325	else {
10326		ctl_set_invalid_field(ctsio,
10327				      /*sks_valid*/ 1,
10328				      /*command*/ 1,
10329				      /*field*/ 2,
10330				      /*bit_valid*/ 0,
10331				      /*bit*/ 0);
10332		ctl_done((union ctl_io *)ctsio);
10333		return (CTL_RETVAL_COMPLETE);
10334	}
10335
10336	return (retval);
10337}
10338
10339int
10340ctl_get_config(struct ctl_scsiio *ctsio)
10341{
10342	struct scsi_get_config_header *hdr;
10343	struct scsi_get_config_feature *feature;
10344	struct scsi_get_config *cdb;
10345	struct ctl_lun *lun;
10346	uint32_t alloc_len, data_len;
10347	int rt, starting;
10348
10349	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10350	cdb = (struct scsi_get_config *)ctsio->cdb;
10351	rt = (cdb->rt & SGC_RT_MASK);
10352	starting = scsi_2btoul(cdb->starting_feature);
10353	alloc_len = scsi_2btoul(cdb->length);
10354
10355	data_len = sizeof(struct scsi_get_config_header) +
10356	    sizeof(struct scsi_get_config_feature) + 8 +
10357	    sizeof(struct scsi_get_config_feature) + 8 +
10358	    sizeof(struct scsi_get_config_feature) + 4 +
10359	    sizeof(struct scsi_get_config_feature) + 4 +
10360	    sizeof(struct scsi_get_config_feature) + 8 +
10361	    sizeof(struct scsi_get_config_feature) +
10362	    sizeof(struct scsi_get_config_feature) + 4 +
10363	    sizeof(struct scsi_get_config_feature) + 4 +
10364	    sizeof(struct scsi_get_config_feature) + 4 +
10365	    sizeof(struct scsi_get_config_feature) + 4 +
10366	    sizeof(struct scsi_get_config_feature) + 4 +
10367	    sizeof(struct scsi_get_config_feature) + 4;
10368	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10369	ctsio->kern_sg_entries = 0;
10370	ctsio->kern_data_resid = 0;
10371	ctsio->kern_rel_offset = 0;
10372
10373	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10374	if (lun->flags & CTL_LUN_NO_MEDIA)
10375		scsi_ulto2b(0x0000, hdr->current_profile);
10376	else
10377		scsi_ulto2b(0x0010, hdr->current_profile);
10378	feature = (struct scsi_get_config_feature *)(hdr + 1);
10379
10380	if (starting > 0x003b)
10381		goto done;
10382	if (starting > 0x003a)
10383		goto f3b;
10384	if (starting > 0x002b)
10385		goto f3a;
10386	if (starting > 0x002a)
10387		goto f2b;
10388	if (starting > 0x001f)
10389		goto f2a;
10390	if (starting > 0x001e)
10391		goto f1f;
10392	if (starting > 0x001d)
10393		goto f1e;
10394	if (starting > 0x0010)
10395		goto f1d;
10396	if (starting > 0x0003)
10397		goto f10;
10398	if (starting > 0x0002)
10399		goto f3;
10400	if (starting > 0x0001)
10401		goto f2;
10402	if (starting > 0x0000)
10403		goto f1;
10404
10405	/* Profile List */
10406	scsi_ulto2b(0x0000, feature->feature_code);
10407	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10408	feature->add_length = 8;
10409	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10410	feature->feature_data[2] = 0x00;
10411	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10412	feature->feature_data[6] = 0x01;
10413	feature = (struct scsi_get_config_feature *)
10414	    &feature->feature_data[feature->add_length];
10415
10416f1:	/* Core */
10417	scsi_ulto2b(0x0001, feature->feature_code);
10418	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10419	feature->add_length = 8;
10420	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10421	feature->feature_data[4] = 0x03;
10422	feature = (struct scsi_get_config_feature *)
10423	    &feature->feature_data[feature->add_length];
10424
10425f2:	/* Morphing */
10426	scsi_ulto2b(0x0002, feature->feature_code);
10427	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10428	feature->add_length = 4;
10429	feature->feature_data[0] = 0x02;
10430	feature = (struct scsi_get_config_feature *)
10431	    &feature->feature_data[feature->add_length];
10432
10433f3:	/* Removable Medium */
10434	scsi_ulto2b(0x0003, feature->feature_code);
10435	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10436	feature->add_length = 4;
10437	feature->feature_data[0] = 0x39;
10438	feature = (struct scsi_get_config_feature *)
10439	    &feature->feature_data[feature->add_length];
10440
10441	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10442		goto done;
10443
10444f10:	/* Random Read */
10445	scsi_ulto2b(0x0010, feature->feature_code);
10446	feature->flags = 0x00;
10447	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10448		feature->flags |= SGC_F_CURRENT;
10449	feature->add_length = 8;
10450	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10451	scsi_ulto2b(1, &feature->feature_data[4]);
10452	feature->feature_data[6] = 0x00;
10453	feature = (struct scsi_get_config_feature *)
10454	    &feature->feature_data[feature->add_length];
10455
10456f1d:	/* Multi-Read */
10457	scsi_ulto2b(0x001D, feature->feature_code);
10458	feature->flags = 0x00;
10459	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10460		feature->flags |= SGC_F_CURRENT;
10461	feature->add_length = 0;
10462	feature = (struct scsi_get_config_feature *)
10463	    &feature->feature_data[feature->add_length];
10464
10465f1e:	/* CD Read */
10466	scsi_ulto2b(0x001E, feature->feature_code);
10467	feature->flags = 0x00;
10468	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10469		feature->flags |= SGC_F_CURRENT;
10470	feature->add_length = 4;
10471	feature->feature_data[0] = 0x00;
10472	feature = (struct scsi_get_config_feature *)
10473	    &feature->feature_data[feature->add_length];
10474
10475f1f:	/* DVD Read */
10476	scsi_ulto2b(0x001F, feature->feature_code);
10477	feature->flags = 0x08;
10478	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10479		feature->flags |= SGC_F_CURRENT;
10480	feature->add_length = 4;
10481	feature->feature_data[0] = 0x01;
10482	feature->feature_data[2] = 0x03;
10483	feature = (struct scsi_get_config_feature *)
10484	    &feature->feature_data[feature->add_length];
10485
10486f2a:	/* DVD+RW */
10487	scsi_ulto2b(0x002A, feature->feature_code);
10488	feature->flags = 0x04;
10489	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10490		feature->flags |= SGC_F_CURRENT;
10491	feature->add_length = 4;
10492	feature->feature_data[0] = 0x00;
10493	feature->feature_data[1] = 0x00;
10494	feature = (struct scsi_get_config_feature *)
10495	    &feature->feature_data[feature->add_length];
10496
10497f2b:	/* DVD+R */
10498	scsi_ulto2b(0x002B, feature->feature_code);
10499	feature->flags = 0x00;
10500	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10501		feature->flags |= SGC_F_CURRENT;
10502	feature->add_length = 4;
10503	feature->feature_data[0] = 0x00;
10504	feature = (struct scsi_get_config_feature *)
10505	    &feature->feature_data[feature->add_length];
10506
10507f3a:	/* DVD+RW Dual Layer */
10508	scsi_ulto2b(0x003A, feature->feature_code);
10509	feature->flags = 0x00;
10510	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10511		feature->flags |= SGC_F_CURRENT;
10512	feature->add_length = 4;
10513	feature->feature_data[0] = 0x00;
10514	feature->feature_data[1] = 0x00;
10515	feature = (struct scsi_get_config_feature *)
10516	    &feature->feature_data[feature->add_length];
10517
10518f3b:	/* DVD+R Dual Layer */
10519	scsi_ulto2b(0x003B, feature->feature_code);
10520	feature->flags = 0x00;
10521	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10522		feature->flags |= SGC_F_CURRENT;
10523	feature->add_length = 4;
10524	feature->feature_data[0] = 0x00;
10525	feature = (struct scsi_get_config_feature *)
10526	    &feature->feature_data[feature->add_length];
10527
10528done:
10529	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10530	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10531		feature = (struct scsi_get_config_feature *)(hdr + 1);
10532		if (scsi_2btoul(feature->feature_code) == starting)
10533			feature = (struct scsi_get_config_feature *)
10534			    &feature->feature_data[feature->add_length];
10535		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10536	}
10537	scsi_ulto4b(data_len - 4, hdr->data_length);
10538	if (data_len < alloc_len) {
10539		ctsio->residual = alloc_len - data_len;
10540		ctsio->kern_data_len = data_len;
10541		ctsio->kern_total_len = data_len;
10542	} else {
10543		ctsio->residual = 0;
10544		ctsio->kern_data_len = alloc_len;
10545		ctsio->kern_total_len = alloc_len;
10546	}
10547
10548	ctl_set_success(ctsio);
10549	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10550	ctsio->be_move_done = ctl_config_move_done;
10551	ctl_datamove((union ctl_io *)ctsio);
10552	return (CTL_RETVAL_COMPLETE);
10553}
10554
10555int
10556ctl_get_event_status(struct ctl_scsiio *ctsio)
10557{
10558	struct scsi_get_event_status_header *hdr;
10559	struct scsi_get_event_status *cdb;
10560	struct ctl_lun *lun;
10561	uint32_t alloc_len, data_len;
10562	int notif_class;
10563
10564	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10565	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10566	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10567		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10568		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10569		ctl_done((union ctl_io *)ctsio);
10570		return (CTL_RETVAL_COMPLETE);
10571	}
10572	notif_class = cdb->notif_class;
10573	alloc_len = scsi_2btoul(cdb->length);
10574
10575	data_len = sizeof(struct scsi_get_event_status_header);
10576	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10577	ctsio->kern_sg_entries = 0;
10578	ctsio->kern_data_resid = 0;
10579	ctsio->kern_rel_offset = 0;
10580
10581	if (data_len < alloc_len) {
10582		ctsio->residual = alloc_len - data_len;
10583		ctsio->kern_data_len = data_len;
10584		ctsio->kern_total_len = data_len;
10585	} else {
10586		ctsio->residual = 0;
10587		ctsio->kern_data_len = alloc_len;
10588		ctsio->kern_total_len = alloc_len;
10589	}
10590
10591	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10592	scsi_ulto2b(0, hdr->descr_length);
10593	hdr->nea_class = SGESN_NEA;
10594	hdr->supported_class = 0;
10595
10596	ctl_set_success(ctsio);
10597	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10598	ctsio->be_move_done = ctl_config_move_done;
10599	ctl_datamove((union ctl_io *)ctsio);
10600	return (CTL_RETVAL_COMPLETE);
10601}
10602
10603int
10604ctl_mechanism_status(struct ctl_scsiio *ctsio)
10605{
10606	struct scsi_mechanism_status_header *hdr;
10607	struct scsi_mechanism_status *cdb;
10608	struct ctl_lun *lun;
10609	uint32_t alloc_len, data_len;
10610
10611	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10612	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10613	alloc_len = scsi_2btoul(cdb->length);
10614
10615	data_len = sizeof(struct scsi_mechanism_status_header);
10616	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10617	ctsio->kern_sg_entries = 0;
10618	ctsio->kern_data_resid = 0;
10619	ctsio->kern_rel_offset = 0;
10620
10621	if (data_len < alloc_len) {
10622		ctsio->residual = alloc_len - data_len;
10623		ctsio->kern_data_len = data_len;
10624		ctsio->kern_total_len = data_len;
10625	} else {
10626		ctsio->residual = 0;
10627		ctsio->kern_data_len = alloc_len;
10628		ctsio->kern_total_len = alloc_len;
10629	}
10630
10631	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10632	hdr->state1 = 0x00;
10633	hdr->state2 = 0xe0;
10634	scsi_ulto3b(0, hdr->lba);
10635	hdr->slots_num = 0;
10636	scsi_ulto2b(0, hdr->slots_length);
10637
10638	ctl_set_success(ctsio);
10639	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10640	ctsio->be_move_done = ctl_config_move_done;
10641	ctl_datamove((union ctl_io *)ctsio);
10642	return (CTL_RETVAL_COMPLETE);
10643}
10644
10645static void
10646ctl_ultomsf(uint32_t lba, uint8_t *buf)
10647{
10648
10649	lba += 150;
10650	buf[0] = 0;
10651	buf[1] = bin2bcd((lba / 75) / 60);
10652	buf[2] = bin2bcd((lba / 75) % 60);
10653	buf[3] = bin2bcd(lba % 75);
10654}
10655
10656int
10657ctl_read_toc(struct ctl_scsiio *ctsio)
10658{
10659	struct scsi_read_toc_hdr *hdr;
10660	struct scsi_read_toc_type01_descr *descr;
10661	struct scsi_read_toc *cdb;
10662	struct ctl_lun *lun;
10663	uint32_t alloc_len, data_len;
10664	int format, msf;
10665
10666	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10667	cdb = (struct scsi_read_toc *)ctsio->cdb;
10668	msf = (cdb->byte2 & CD_MSF) != 0;
10669	format = cdb->format;
10670	alloc_len = scsi_2btoul(cdb->data_len);
10671
10672	data_len = sizeof(struct scsi_read_toc_hdr);
10673	if (format == 0)
10674		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10675	else
10676		data_len += sizeof(struct scsi_read_toc_type01_descr);
10677	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10678	ctsio->kern_sg_entries = 0;
10679	ctsio->kern_data_resid = 0;
10680	ctsio->kern_rel_offset = 0;
10681
10682	if (data_len < alloc_len) {
10683		ctsio->residual = alloc_len - data_len;
10684		ctsio->kern_data_len = data_len;
10685		ctsio->kern_total_len = data_len;
10686	} else {
10687		ctsio->residual = 0;
10688		ctsio->kern_data_len = alloc_len;
10689		ctsio->kern_total_len = alloc_len;
10690	}
10691
10692	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10693	if (format == 0) {
10694		scsi_ulto2b(0x12, hdr->data_length);
10695		hdr->first = 1;
10696		hdr->last = 1;
10697		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10698		descr->addr_ctl = 0x14;
10699		descr->track_number = 1;
10700		if (msf)
10701			ctl_ultomsf(0, descr->track_start);
10702		else
10703			scsi_ulto4b(0, descr->track_start);
10704		descr++;
10705		descr->addr_ctl = 0x14;
10706		descr->track_number = 0xaa;
10707		if (msf)
10708			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10709		else
10710			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10711	} else {
10712		scsi_ulto2b(0x0a, hdr->data_length);
10713		hdr->first = 1;
10714		hdr->last = 1;
10715		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10716		descr->addr_ctl = 0x14;
10717		descr->track_number = 1;
10718		if (msf)
10719			ctl_ultomsf(0, descr->track_start);
10720		else
10721			scsi_ulto4b(0, descr->track_start);
10722	}
10723
10724	ctl_set_success(ctsio);
10725	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10726	ctsio->be_move_done = ctl_config_move_done;
10727	ctl_datamove((union ctl_io *)ctsio);
10728	return (CTL_RETVAL_COMPLETE);
10729}
10730
10731/*
10732 * For known CDB types, parse the LBA and length.
10733 */
10734static int
10735ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10736{
10737	if (io->io_hdr.io_type != CTL_IO_SCSI)
10738		return (1);
10739
10740	switch (io->scsiio.cdb[0]) {
10741	case COMPARE_AND_WRITE: {
10742		struct scsi_compare_and_write *cdb;
10743
10744		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10745
10746		*lba = scsi_8btou64(cdb->addr);
10747		*len = cdb->length;
10748		break;
10749	}
10750	case READ_6:
10751	case WRITE_6: {
10752		struct scsi_rw_6 *cdb;
10753
10754		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10755
10756		*lba = scsi_3btoul(cdb->addr);
10757		/* only 5 bits are valid in the most significant address byte */
10758		*lba &= 0x1fffff;
10759		*len = cdb->length;
10760		break;
10761	}
10762	case READ_10:
10763	case WRITE_10: {
10764		struct scsi_rw_10 *cdb;
10765
10766		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10767
10768		*lba = scsi_4btoul(cdb->addr);
10769		*len = scsi_2btoul(cdb->length);
10770		break;
10771	}
10772	case WRITE_VERIFY_10: {
10773		struct scsi_write_verify_10 *cdb;
10774
10775		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10776
10777		*lba = scsi_4btoul(cdb->addr);
10778		*len = scsi_2btoul(cdb->length);
10779		break;
10780	}
10781	case READ_12:
10782	case WRITE_12: {
10783		struct scsi_rw_12 *cdb;
10784
10785		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10786
10787		*lba = scsi_4btoul(cdb->addr);
10788		*len = scsi_4btoul(cdb->length);
10789		break;
10790	}
10791	case WRITE_VERIFY_12: {
10792		struct scsi_write_verify_12 *cdb;
10793
10794		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10795
10796		*lba = scsi_4btoul(cdb->addr);
10797		*len = scsi_4btoul(cdb->length);
10798		break;
10799	}
10800	case READ_16:
10801	case WRITE_16: {
10802		struct scsi_rw_16 *cdb;
10803
10804		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10805
10806		*lba = scsi_8btou64(cdb->addr);
10807		*len = scsi_4btoul(cdb->length);
10808		break;
10809	}
10810	case WRITE_ATOMIC_16: {
10811		struct scsi_write_atomic_16 *cdb;
10812
10813		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10814
10815		*lba = scsi_8btou64(cdb->addr);
10816		*len = scsi_2btoul(cdb->length);
10817		break;
10818	}
10819	case WRITE_VERIFY_16: {
10820		struct scsi_write_verify_16 *cdb;
10821
10822		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10823
10824		*lba = scsi_8btou64(cdb->addr);
10825		*len = scsi_4btoul(cdb->length);
10826		break;
10827	}
10828	case WRITE_SAME_10: {
10829		struct scsi_write_same_10 *cdb;
10830
10831		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10832
10833		*lba = scsi_4btoul(cdb->addr);
10834		*len = scsi_2btoul(cdb->length);
10835		break;
10836	}
10837	case WRITE_SAME_16: {
10838		struct scsi_write_same_16 *cdb;
10839
10840		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10841
10842		*lba = scsi_8btou64(cdb->addr);
10843		*len = scsi_4btoul(cdb->length);
10844		break;
10845	}
10846	case VERIFY_10: {
10847		struct scsi_verify_10 *cdb;
10848
10849		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10850
10851		*lba = scsi_4btoul(cdb->addr);
10852		*len = scsi_2btoul(cdb->length);
10853		break;
10854	}
10855	case VERIFY_12: {
10856		struct scsi_verify_12 *cdb;
10857
10858		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10859
10860		*lba = scsi_4btoul(cdb->addr);
10861		*len = scsi_4btoul(cdb->length);
10862		break;
10863	}
10864	case VERIFY_16: {
10865		struct scsi_verify_16 *cdb;
10866
10867		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10868
10869		*lba = scsi_8btou64(cdb->addr);
10870		*len = scsi_4btoul(cdb->length);
10871		break;
10872	}
10873	case UNMAP: {
10874		*lba = 0;
10875		*len = UINT64_MAX;
10876		break;
10877	}
10878	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10879		struct scsi_get_lba_status *cdb;
10880
10881		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10882		*lba = scsi_8btou64(cdb->addr);
10883		*len = UINT32_MAX;
10884		break;
10885	}
10886	default:
10887		return (1);
10888		break; /* NOTREACHED */
10889	}
10890
10891	return (0);
10892}
10893
10894static ctl_action
10895ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10896    bool seq)
10897{
10898	uint64_t endlba1, endlba2;
10899
10900	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10901	endlba2 = lba2 + len2 - 1;
10902
10903	if ((endlba1 < lba2) || (endlba2 < lba1))
10904		return (CTL_ACTION_PASS);
10905	else
10906		return (CTL_ACTION_BLOCK);
10907}
10908
10909static int
10910ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10911{
10912	struct ctl_ptr_len_flags *ptrlen;
10913	struct scsi_unmap_desc *buf, *end, *range;
10914	uint64_t lba;
10915	uint32_t len;
10916
10917	/* If not UNMAP -- go other way. */
10918	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10919	    io->scsiio.cdb[0] != UNMAP)
10920		return (CTL_ACTION_ERROR);
10921
10922	/* If UNMAP without data -- block and wait for data. */
10923	ptrlen = (struct ctl_ptr_len_flags *)
10924	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10925	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10926	    ptrlen->ptr == NULL)
10927		return (CTL_ACTION_BLOCK);
10928
10929	/* UNMAP with data -- check for collision. */
10930	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10931	end = buf + ptrlen->len / sizeof(*buf);
10932	for (range = buf; range < end; range++) {
10933		lba = scsi_8btou64(range->lba);
10934		len = scsi_4btoul(range->length);
10935		if ((lba < lba2 + len2) && (lba + len > lba2))
10936			return (CTL_ACTION_BLOCK);
10937	}
10938	return (CTL_ACTION_PASS);
10939}
10940
10941static ctl_action
10942ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10943{
10944	uint64_t lba1, lba2;
10945	uint64_t len1, len2;
10946	int retval;
10947
10948	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10949		return (CTL_ACTION_ERROR);
10950
10951	retval = ctl_extent_check_unmap(io1, lba2, len2);
10952	if (retval != CTL_ACTION_ERROR)
10953		return (retval);
10954
10955	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10956		return (CTL_ACTION_ERROR);
10957
10958	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10959		seq = FALSE;
10960	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10961}
10962
10963static ctl_action
10964ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10965{
10966	uint64_t lba1, lba2;
10967	uint64_t len1, len2;
10968
10969	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10970		return (CTL_ACTION_PASS);
10971	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10972		return (CTL_ACTION_ERROR);
10973	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10974		return (CTL_ACTION_ERROR);
10975
10976	if (lba1 + len1 == lba2)
10977		return (CTL_ACTION_BLOCK);
10978	return (CTL_ACTION_PASS);
10979}
10980
10981static ctl_action
10982ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10983    union ctl_io *ooa_io)
10984{
10985	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10986	const ctl_serialize_action *serialize_row;
10987
10988	/*
10989	 * The initiator attempted multiple untagged commands at the same
10990	 * time.  Can't do that.
10991	 */
10992	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10993	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10994	 && ((pending_io->io_hdr.nexus.targ_port ==
10995	      ooa_io->io_hdr.nexus.targ_port)
10996	  && (pending_io->io_hdr.nexus.initid ==
10997	      ooa_io->io_hdr.nexus.initid))
10998	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10999	      CTL_FLAG_STATUS_SENT)) == 0))
11000		return (CTL_ACTION_OVERLAP);
11001
11002	/*
11003	 * The initiator attempted to send multiple tagged commands with
11004	 * the same ID.  (It's fine if different initiators have the same
11005	 * tag ID.)
11006	 *
11007	 * Even if all of those conditions are true, we don't kill the I/O
11008	 * if the command ahead of us has been aborted.  We won't end up
11009	 * sending it to the FETD, and it's perfectly legal to resend a
11010	 * command with the same tag number as long as the previous
11011	 * instance of this tag number has been aborted somehow.
11012	 */
11013	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11014	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11015	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11016	 && ((pending_io->io_hdr.nexus.targ_port ==
11017	      ooa_io->io_hdr.nexus.targ_port)
11018	  && (pending_io->io_hdr.nexus.initid ==
11019	      ooa_io->io_hdr.nexus.initid))
11020	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11021	      CTL_FLAG_STATUS_SENT)) == 0))
11022		return (CTL_ACTION_OVERLAP_TAG);
11023
11024	/*
11025	 * If we get a head of queue tag, SAM-3 says that we should
11026	 * immediately execute it.
11027	 *
11028	 * What happens if this command would normally block for some other
11029	 * reason?  e.g. a request sense with a head of queue tag
11030	 * immediately after a write.  Normally that would block, but this
11031	 * will result in its getting executed immediately...
11032	 *
11033	 * We currently return "pass" instead of "skip", so we'll end up
11034	 * going through the rest of the queue to check for overlapped tags.
11035	 *
11036	 * XXX KDM check for other types of blockage first??
11037	 */
11038	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11039		return (CTL_ACTION_PASS);
11040
11041	/*
11042	 * Ordered tags have to block until all items ahead of them
11043	 * have completed.  If we get called with an ordered tag, we always
11044	 * block, if something else is ahead of us in the queue.
11045	 */
11046	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11047		return (CTL_ACTION_BLOCK);
11048
11049	/*
11050	 * Simple tags get blocked until all head of queue and ordered tags
11051	 * ahead of them have completed.  I'm lumping untagged commands in
11052	 * with simple tags here.  XXX KDM is that the right thing to do?
11053	 */
11054	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11055	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11056	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11057	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11058		return (CTL_ACTION_BLOCK);
11059
11060	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11061	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11062	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11063	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11064	     pending_io->scsiio.cdb[1], pending_io));
11065	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11066	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11067		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11068	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11069	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11070	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11071	     ooa_io->scsiio.cdb[1], ooa_io));
11072
11073	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11074
11075	switch (serialize_row[pending_entry->seridx]) {
11076	case CTL_SER_BLOCK:
11077		return (CTL_ACTION_BLOCK);
11078	case CTL_SER_EXTENT:
11079		return (ctl_extent_check(ooa_io, pending_io,
11080		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11081	case CTL_SER_EXTENTOPT:
11082		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11083		    SCP_QUEUE_ALG_UNRESTRICTED)
11084			return (ctl_extent_check(ooa_io, pending_io,
11085			    (lun->be_lun &&
11086			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11087		return (CTL_ACTION_PASS);
11088	case CTL_SER_EXTENTSEQ:
11089		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11090			return (ctl_extent_check_seq(ooa_io, pending_io));
11091		return (CTL_ACTION_PASS);
11092	case CTL_SER_PASS:
11093		return (CTL_ACTION_PASS);
11094	case CTL_SER_BLOCKOPT:
11095		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11096		    SCP_QUEUE_ALG_UNRESTRICTED)
11097			return (CTL_ACTION_BLOCK);
11098		return (CTL_ACTION_PASS);
11099	case CTL_SER_SKIP:
11100		return (CTL_ACTION_SKIP);
11101	default:
11102		panic("%s: Invalid serialization value %d for %d => %d",
11103		    __func__, serialize_row[pending_entry->seridx],
11104		    pending_entry->seridx, ooa_entry->seridx);
11105	}
11106
11107	return (CTL_ACTION_ERROR);
11108}
11109
11110/*
11111 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11112 * Assumptions:
11113 * - pending_io is generally either incoming, or on the blocked queue
11114 * - starting I/O is the I/O we want to start the check with.
11115 */
11116static ctl_action
11117ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11118	      union ctl_io *starting_io)
11119{
11120	union ctl_io *ooa_io;
11121	ctl_action action;
11122
11123	mtx_assert(&lun->lun_lock, MA_OWNED);
11124
11125	/*
11126	 * Run back along the OOA queue, starting with the current
11127	 * blocked I/O and going through every I/O before it on the
11128	 * queue.  If starting_io is NULL, we'll just end up returning
11129	 * CTL_ACTION_PASS.
11130	 */
11131	for (ooa_io = starting_io; ooa_io != NULL;
11132	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11133	     ooa_links)){
11134
11135		/*
11136		 * This routine just checks to see whether
11137		 * cur_blocked is blocked by ooa_io, which is ahead
11138		 * of it in the queue.  It doesn't queue/dequeue
11139		 * cur_blocked.
11140		 */
11141		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11142		switch (action) {
11143		case CTL_ACTION_BLOCK:
11144		case CTL_ACTION_OVERLAP:
11145		case CTL_ACTION_OVERLAP_TAG:
11146		case CTL_ACTION_SKIP:
11147		case CTL_ACTION_ERROR:
11148			return (action);
11149			break; /* NOTREACHED */
11150		case CTL_ACTION_PASS:
11151			break;
11152		default:
11153			panic("%s: Invalid action %d\n", __func__, action);
11154		}
11155	}
11156
11157	return (CTL_ACTION_PASS);
11158}
11159
11160/*
11161 * Assumptions:
11162 * - An I/O has just completed, and has been removed from the per-LUN OOA
11163 *   queue, so some items on the blocked queue may now be unblocked.
11164 */
11165static int
11166ctl_check_blocked(struct ctl_lun *lun)
11167{
11168	struct ctl_softc *softc = lun->ctl_softc;
11169	union ctl_io *cur_blocked, *next_blocked;
11170
11171	mtx_assert(&lun->lun_lock, MA_OWNED);
11172
11173	/*
11174	 * Run forward from the head of the blocked queue, checking each
11175	 * entry against the I/Os prior to it on the OOA queue to see if
11176	 * there is still any blockage.
11177	 *
11178	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11179	 * with our removing a variable on it while it is traversing the
11180	 * list.
11181	 */
11182	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11183	     cur_blocked != NULL; cur_blocked = next_blocked) {
11184		union ctl_io *prev_ooa;
11185		ctl_action action;
11186
11187		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11188							  blocked_links);
11189
11190		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11191						      ctl_ooaq, ooa_links);
11192
11193		/*
11194		 * If cur_blocked happens to be the first item in the OOA
11195		 * queue now, prev_ooa will be NULL, and the action
11196		 * returned will just be CTL_ACTION_PASS.
11197		 */
11198		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11199
11200		switch (action) {
11201		case CTL_ACTION_BLOCK:
11202			/* Nothing to do here, still blocked */
11203			break;
11204		case CTL_ACTION_OVERLAP:
11205		case CTL_ACTION_OVERLAP_TAG:
11206			/*
11207			 * This shouldn't happen!  In theory we've already
11208			 * checked this command for overlap...
11209			 */
11210			break;
11211		case CTL_ACTION_PASS:
11212		case CTL_ACTION_SKIP: {
11213			const struct ctl_cmd_entry *entry;
11214
11215			/*
11216			 * The skip case shouldn't happen, this transaction
11217			 * should have never made it onto the blocked queue.
11218			 */
11219			/*
11220			 * This I/O is no longer blocked, we can remove it
11221			 * from the blocked queue.  Since this is a TAILQ
11222			 * (doubly linked list), we can do O(1) removals
11223			 * from any place on the list.
11224			 */
11225			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11226				     blocked_links);
11227			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11228
11229			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11230			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11231				/*
11232				 * Need to send IO back to original side to
11233				 * run
11234				 */
11235				union ctl_ha_msg msg_info;
11236
11237				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11238				msg_info.hdr.original_sc =
11239					cur_blocked->io_hdr.original_sc;
11240				msg_info.hdr.serializing_sc = cur_blocked;
11241				msg_info.hdr.msg_type = CTL_MSG_R2R;
11242				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11243				    sizeof(msg_info.hdr), M_NOWAIT);
11244				break;
11245			}
11246			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11247
11248			/*
11249			 * Check this I/O for LUN state changes that may
11250			 * have happened while this command was blocked.
11251			 * The LUN state may have been changed by a command
11252			 * ahead of us in the queue, so we need to re-check
11253			 * for any states that can be caused by SCSI
11254			 * commands.
11255			 */
11256			if (ctl_scsiio_lun_check(lun, entry,
11257						 &cur_blocked->scsiio) == 0) {
11258				cur_blocked->io_hdr.flags |=
11259				                      CTL_FLAG_IS_WAS_ON_RTR;
11260				ctl_enqueue_rtr(cur_blocked);
11261			} else
11262				ctl_done(cur_blocked);
11263			break;
11264		}
11265		default:
11266			/*
11267			 * This probably shouldn't happen -- we shouldn't
11268			 * get CTL_ACTION_ERROR, or anything else.
11269			 */
11270			break;
11271		}
11272	}
11273
11274	return (CTL_RETVAL_COMPLETE);
11275}
11276
11277/*
11278 * This routine (with one exception) checks LUN flags that can be set by
11279 * commands ahead of us in the OOA queue.  These flags have to be checked
11280 * when a command initially comes in, and when we pull a command off the
11281 * blocked queue and are preparing to execute it.  The reason we have to
11282 * check these flags for commands on the blocked queue is that the LUN
11283 * state may have been changed by a command ahead of us while we're on the
11284 * blocked queue.
11285 *
11286 * Ordering is somewhat important with these checks, so please pay
11287 * careful attention to the placement of any new checks.
11288 */
11289static int
11290ctl_scsiio_lun_check(struct ctl_lun *lun,
11291    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11292{
11293	struct ctl_softc *softc = lun->ctl_softc;
11294	int retval;
11295	uint32_t residx;
11296
11297	retval = 0;
11298
11299	mtx_assert(&lun->lun_lock, MA_OWNED);
11300
11301	/*
11302	 * If this shelf is a secondary shelf controller, we may have to
11303	 * reject some commands disallowed by HA mode and link state.
11304	 */
11305	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11306		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11307		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11308			ctl_set_lun_unavail(ctsio);
11309			retval = 1;
11310			goto bailout;
11311		}
11312		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11313		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11314			ctl_set_lun_transit(ctsio);
11315			retval = 1;
11316			goto bailout;
11317		}
11318		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11319		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11320			ctl_set_lun_standby(ctsio);
11321			retval = 1;
11322			goto bailout;
11323		}
11324
11325		/* The rest of checks are only done on executing side */
11326		if (softc->ha_mode == CTL_HA_MODE_XFER)
11327			goto bailout;
11328	}
11329
11330	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11331		if (lun->be_lun &&
11332		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11333			ctl_set_hw_write_protected(ctsio);
11334			retval = 1;
11335			goto bailout;
11336		}
11337		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11338			ctl_set_sense(ctsio, /*current_error*/ 1,
11339			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11340			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11341			retval = 1;
11342			goto bailout;
11343		}
11344	}
11345
11346	/*
11347	 * Check for a reservation conflict.  If this command isn't allowed
11348	 * even on reserved LUNs, and if this initiator isn't the one who
11349	 * reserved us, reject the command with a reservation conflict.
11350	 */
11351	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11352	if ((lun->flags & CTL_LUN_RESERVED)
11353	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11354		if (lun->res_idx != residx) {
11355			ctl_set_reservation_conflict(ctsio);
11356			retval = 1;
11357			goto bailout;
11358		}
11359	}
11360
11361	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11362	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11363		/* No reservation or command is allowed. */;
11364	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11365	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11366	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11367	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11368		/* The command is allowed for Write Exclusive resv. */;
11369	} else {
11370		/*
11371		 * if we aren't registered or it's a res holder type
11372		 * reservation and this isn't the res holder then set a
11373		 * conflict.
11374		 */
11375		if (ctl_get_prkey(lun, residx) == 0 ||
11376		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11377			ctl_set_reservation_conflict(ctsio);
11378			retval = 1;
11379			goto bailout;
11380		}
11381	}
11382
11383	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11384		if (lun->flags & CTL_LUN_EJECTED)
11385			ctl_set_lun_ejected(ctsio);
11386		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11387			if (lun->flags & CTL_LUN_REMOVABLE)
11388				ctl_set_lun_no_media(ctsio);
11389			else
11390				ctl_set_lun_int_reqd(ctsio);
11391		} else if (lun->flags & CTL_LUN_STOPPED)
11392			ctl_set_lun_stopped(ctsio);
11393		else
11394			goto bailout;
11395		retval = 1;
11396		goto bailout;
11397	}
11398
11399bailout:
11400	return (retval);
11401}
11402
11403static void
11404ctl_failover_io(union ctl_io *io, int have_lock)
11405{
11406	ctl_set_busy(&io->scsiio);
11407	ctl_done(io);
11408}
11409
11410static void
11411ctl_failover_lun(union ctl_io *rio)
11412{
11413	struct ctl_softc *softc = control_softc;
11414	struct ctl_lun *lun;
11415	struct ctl_io_hdr *io, *next_io;
11416	uint32_t targ_lun;
11417
11418	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11419	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11420
11421	/* Find and lock the LUN. */
11422	mtx_lock(&softc->ctl_lock);
11423	if (targ_lun > CTL_MAX_LUNS ||
11424	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11425		mtx_unlock(&softc->ctl_lock);
11426		return;
11427	}
11428	mtx_lock(&lun->lun_lock);
11429	mtx_unlock(&softc->ctl_lock);
11430	if (lun->flags & CTL_LUN_DISABLED) {
11431		mtx_unlock(&lun->lun_lock);
11432		return;
11433	}
11434
11435	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11436		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11437			/* We are master */
11438			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11439				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11440					io->flags |= CTL_FLAG_ABORT;
11441					io->flags |= CTL_FLAG_FAILOVER;
11442				} else { /* This can be only due to DATAMOVE */
11443					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11444					io->flags &= ~CTL_FLAG_DMA_INPROG;
11445					io->flags |= CTL_FLAG_IO_ACTIVE;
11446					io->port_status = 31340;
11447					ctl_enqueue_isc((union ctl_io *)io);
11448				}
11449			}
11450			/* We are slave */
11451			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11452				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11453				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11454					io->flags |= CTL_FLAG_FAILOVER;
11455				} else {
11456					ctl_set_busy(&((union ctl_io *)io)->
11457					    scsiio);
11458					ctl_done((union ctl_io *)io);
11459				}
11460			}
11461		}
11462	} else { /* SERIALIZE modes */
11463		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11464		    next_io) {
11465			/* We are master */
11466			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11467				TAILQ_REMOVE(&lun->blocked_queue, io,
11468				    blocked_links);
11469				io->flags &= ~CTL_FLAG_BLOCKED;
11470				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11471				ctl_free_io((union ctl_io *)io);
11472			}
11473		}
11474		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11475			/* We are master */
11476			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11477				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11478				ctl_free_io((union ctl_io *)io);
11479			}
11480			/* We are slave */
11481			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11482				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11483				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11484					ctl_set_busy(&((union ctl_io *)io)->
11485					    scsiio);
11486					ctl_done((union ctl_io *)io);
11487				}
11488			}
11489		}
11490		ctl_check_blocked(lun);
11491	}
11492	mtx_unlock(&lun->lun_lock);
11493}
11494
11495static int
11496ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11497{
11498	struct ctl_lun *lun;
11499	const struct ctl_cmd_entry *entry;
11500	uint32_t initidx, targ_lun;
11501	int retval = 0;
11502
11503	lun = NULL;
11504	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11505	if (targ_lun < CTL_MAX_LUNS)
11506		lun = softc->ctl_luns[targ_lun];
11507	if (lun) {
11508		/*
11509		 * If the LUN is invalid, pretend that it doesn't exist.
11510		 * It will go away as soon as all pending I/O has been
11511		 * completed.
11512		 */
11513		mtx_lock(&lun->lun_lock);
11514		if (lun->flags & CTL_LUN_DISABLED) {
11515			mtx_unlock(&lun->lun_lock);
11516			lun = NULL;
11517		}
11518	}
11519	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11520	if (lun) {
11521		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11522		    lun->be_lun;
11523
11524		/*
11525		 * Every I/O goes into the OOA queue for a particular LUN,
11526		 * and stays there until completion.
11527		 */
11528#ifdef CTL_TIME_IO
11529		if (TAILQ_EMPTY(&lun->ooa_queue))
11530			lun->idle_time += getsbinuptime() - lun->last_busy;
11531#endif
11532		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11533	}
11534
11535	/* Get command entry and return error if it is unsuppotyed. */
11536	entry = ctl_validate_command(ctsio);
11537	if (entry == NULL) {
11538		if (lun)
11539			mtx_unlock(&lun->lun_lock);
11540		return (retval);
11541	}
11542
11543	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11544	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11545
11546	/*
11547	 * Check to see whether we can send this command to LUNs that don't
11548	 * exist.  This should pretty much only be the case for inquiry
11549	 * and request sense.  Further checks, below, really require having
11550	 * a LUN, so we can't really check the command anymore.  Just put
11551	 * it on the rtr queue.
11552	 */
11553	if (lun == NULL) {
11554		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11555			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11556			ctl_enqueue_rtr((union ctl_io *)ctsio);
11557			return (retval);
11558		}
11559
11560		ctl_set_unsupported_lun(ctsio);
11561		ctl_done((union ctl_io *)ctsio);
11562		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11563		return (retval);
11564	} else {
11565		/*
11566		 * Make sure we support this particular command on this LUN.
11567		 * e.g., we don't support writes to the control LUN.
11568		 */
11569		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11570			mtx_unlock(&lun->lun_lock);
11571			ctl_set_invalid_opcode(ctsio);
11572			ctl_done((union ctl_io *)ctsio);
11573			return (retval);
11574		}
11575	}
11576
11577	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11578
11579#ifdef CTL_WITH_CA
11580	/*
11581	 * If we've got a request sense, it'll clear the contingent
11582	 * allegiance condition.  Otherwise, if we have a CA condition for
11583	 * this initiator, clear it, because it sent down a command other
11584	 * than request sense.
11585	 */
11586	if ((ctsio->cdb[0] != REQUEST_SENSE)
11587	 && (ctl_is_set(lun->have_ca, initidx)))
11588		ctl_clear_mask(lun->have_ca, initidx);
11589#endif
11590
11591	/*
11592	 * If the command has this flag set, it handles its own unit
11593	 * attention reporting, we shouldn't do anything.  Otherwise we
11594	 * check for any pending unit attentions, and send them back to the
11595	 * initiator.  We only do this when a command initially comes in,
11596	 * not when we pull it off the blocked queue.
11597	 *
11598	 * According to SAM-3, section 5.3.2, the order that things get
11599	 * presented back to the host is basically unit attentions caused
11600	 * by some sort of reset event, busy status, reservation conflicts
11601	 * or task set full, and finally any other status.
11602	 *
11603	 * One issue here is that some of the unit attentions we report
11604	 * don't fall into the "reset" category (e.g. "reported luns data
11605	 * has changed").  So reporting it here, before the reservation
11606	 * check, may be technically wrong.  I guess the only thing to do
11607	 * would be to check for and report the reset events here, and then
11608	 * check for the other unit attention types after we check for a
11609	 * reservation conflict.
11610	 *
11611	 * XXX KDM need to fix this
11612	 */
11613	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11614		ctl_ua_type ua_type;
11615		u_int sense_len = 0;
11616
11617		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11618		    &sense_len, SSD_TYPE_NONE);
11619		if (ua_type != CTL_UA_NONE) {
11620			mtx_unlock(&lun->lun_lock);
11621			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11622			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11623			ctsio->sense_len = sense_len;
11624			ctl_done((union ctl_io *)ctsio);
11625			return (retval);
11626		}
11627	}
11628
11629
11630	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11631		mtx_unlock(&lun->lun_lock);
11632		ctl_done((union ctl_io *)ctsio);
11633		return (retval);
11634	}
11635
11636	/*
11637	 * XXX CHD this is where we want to send IO to other side if
11638	 * this LUN is secondary on this SC. We will need to make a copy
11639	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11640	 * the copy we send as FROM_OTHER.
11641	 * We also need to stuff the address of the original IO so we can
11642	 * find it easily. Something similar will need be done on the other
11643	 * side so when we are done we can find the copy.
11644	 */
11645	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11646	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11647	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11648		union ctl_ha_msg msg_info;
11649		int isc_retval;
11650
11651		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11652		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11653		mtx_unlock(&lun->lun_lock);
11654
11655		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11656		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11657		msg_info.hdr.serializing_sc = NULL;
11658		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11659		msg_info.scsi.tag_num = ctsio->tag_num;
11660		msg_info.scsi.tag_type = ctsio->tag_type;
11661		msg_info.scsi.cdb_len = ctsio->cdb_len;
11662		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11663
11664		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11665		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11666		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11667			ctl_set_busy(ctsio);
11668			ctl_done((union ctl_io *)ctsio);
11669			return (retval);
11670		}
11671		return (retval);
11672	}
11673
11674	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11675			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11676			      ctl_ooaq, ooa_links))) {
11677	case CTL_ACTION_BLOCK:
11678		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11679		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11680				  blocked_links);
11681		mtx_unlock(&lun->lun_lock);
11682		return (retval);
11683	case CTL_ACTION_PASS:
11684	case CTL_ACTION_SKIP:
11685		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11686		mtx_unlock(&lun->lun_lock);
11687		ctl_enqueue_rtr((union ctl_io *)ctsio);
11688		break;
11689	case CTL_ACTION_OVERLAP:
11690		mtx_unlock(&lun->lun_lock);
11691		ctl_set_overlapped_cmd(ctsio);
11692		ctl_done((union ctl_io *)ctsio);
11693		break;
11694	case CTL_ACTION_OVERLAP_TAG:
11695		mtx_unlock(&lun->lun_lock);
11696		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11697		ctl_done((union ctl_io *)ctsio);
11698		break;
11699	case CTL_ACTION_ERROR:
11700	default:
11701		mtx_unlock(&lun->lun_lock);
11702		ctl_set_internal_failure(ctsio,
11703					 /*sks_valid*/ 0,
11704					 /*retry_count*/ 0);
11705		ctl_done((union ctl_io *)ctsio);
11706		break;
11707	}
11708	return (retval);
11709}
11710
11711const struct ctl_cmd_entry *
11712ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11713{
11714	const struct ctl_cmd_entry *entry;
11715	int service_action;
11716
11717	entry = &ctl_cmd_table[ctsio->cdb[0]];
11718	if (sa)
11719		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11720	if (entry->flags & CTL_CMD_FLAG_SA5) {
11721		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11722		entry = &((const struct ctl_cmd_entry *)
11723		    entry->execute)[service_action];
11724	}
11725	return (entry);
11726}
11727
11728const struct ctl_cmd_entry *
11729ctl_validate_command(struct ctl_scsiio *ctsio)
11730{
11731	const struct ctl_cmd_entry *entry;
11732	int i, sa;
11733	uint8_t diff;
11734
11735	entry = ctl_get_cmd_entry(ctsio, &sa);
11736	if (entry->execute == NULL) {
11737		if (sa)
11738			ctl_set_invalid_field(ctsio,
11739					      /*sks_valid*/ 1,
11740					      /*command*/ 1,
11741					      /*field*/ 1,
11742					      /*bit_valid*/ 1,
11743					      /*bit*/ 4);
11744		else
11745			ctl_set_invalid_opcode(ctsio);
11746		ctl_done((union ctl_io *)ctsio);
11747		return (NULL);
11748	}
11749	KASSERT(entry->length > 0,
11750	    ("Not defined length for command 0x%02x/0x%02x",
11751	     ctsio->cdb[0], ctsio->cdb[1]));
11752	for (i = 1; i < entry->length; i++) {
11753		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11754		if (diff == 0)
11755			continue;
11756		ctl_set_invalid_field(ctsio,
11757				      /*sks_valid*/ 1,
11758				      /*command*/ 1,
11759				      /*field*/ i,
11760				      /*bit_valid*/ 1,
11761				      /*bit*/ fls(diff) - 1);
11762		ctl_done((union ctl_io *)ctsio);
11763		return (NULL);
11764	}
11765	return (entry);
11766}
11767
11768static int
11769ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11770{
11771
11772	switch (lun_type) {
11773	case T_DIRECT:
11774		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11775			return (0);
11776		break;
11777	case T_PROCESSOR:
11778		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11779			return (0);
11780		break;
11781	case T_CDROM:
11782		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11783			return (0);
11784		break;
11785	default:
11786		return (0);
11787	}
11788	return (1);
11789}
11790
11791static int
11792ctl_scsiio(struct ctl_scsiio *ctsio)
11793{
11794	int retval;
11795	const struct ctl_cmd_entry *entry;
11796
11797	retval = CTL_RETVAL_COMPLETE;
11798
11799	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11800
11801	entry = ctl_get_cmd_entry(ctsio, NULL);
11802
11803	/*
11804	 * If this I/O has been aborted, just send it straight to
11805	 * ctl_done() without executing it.
11806	 */
11807	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11808		ctl_done((union ctl_io *)ctsio);
11809		goto bailout;
11810	}
11811
11812	/*
11813	 * All the checks should have been handled by ctl_scsiio_precheck().
11814	 * We should be clear now to just execute the I/O.
11815	 */
11816	retval = entry->execute(ctsio);
11817
11818bailout:
11819	return (retval);
11820}
11821
11822/*
11823 * Since we only implement one target right now, a bus reset simply resets
11824 * our single target.
11825 */
11826static int
11827ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11828{
11829	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11830}
11831
11832static int
11833ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11834		 ctl_ua_type ua_type)
11835{
11836	struct ctl_port *port;
11837	struct ctl_lun *lun;
11838	int retval;
11839
11840	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11841		union ctl_ha_msg msg_info;
11842
11843		msg_info.hdr.nexus = io->io_hdr.nexus;
11844		if (ua_type==CTL_UA_TARG_RESET)
11845			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11846		else
11847			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11848		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11849		msg_info.hdr.original_sc = NULL;
11850		msg_info.hdr.serializing_sc = NULL;
11851		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11852		    sizeof(msg_info.task), M_WAITOK);
11853	}
11854	retval = 0;
11855
11856	mtx_lock(&softc->ctl_lock);
11857	port = ctl_io_port(&io->io_hdr);
11858	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11859		if (port != NULL &&
11860		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11861			continue;
11862		retval += ctl_do_lun_reset(lun, io, ua_type);
11863	}
11864	mtx_unlock(&softc->ctl_lock);
11865	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11866	return (retval);
11867}
11868
11869/*
11870 * The LUN should always be set.  The I/O is optional, and is used to
11871 * distinguish between I/Os sent by this initiator, and by other
11872 * initiators.  We set unit attention for initiators other than this one.
11873 * SAM-3 is vague on this point.  It does say that a unit attention should
11874 * be established for other initiators when a LUN is reset (see section
11875 * 5.7.3), but it doesn't specifically say that the unit attention should
11876 * be established for this particular initiator when a LUN is reset.  Here
11877 * is the relevant text, from SAM-3 rev 8:
11878 *
11879 * 5.7.2 When a SCSI initiator port aborts its own tasks
11880 *
11881 * When a SCSI initiator port causes its own task(s) to be aborted, no
11882 * notification that the task(s) have been aborted shall be returned to
11883 * the SCSI initiator port other than the completion response for the
11884 * command or task management function action that caused the task(s) to
11885 * be aborted and notification(s) associated with related effects of the
11886 * action (e.g., a reset unit attention condition).
11887 *
11888 * XXX KDM for now, we're setting unit attention for all initiators.
11889 */
11890static int
11891ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11892{
11893	union ctl_io *xio;
11894#if 0
11895	uint32_t initidx;
11896#endif
11897	int i;
11898
11899	mtx_lock(&lun->lun_lock);
11900	/*
11901	 * Run through the OOA queue and abort each I/O.
11902	 */
11903	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11904	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11905		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11906	}
11907
11908	/*
11909	 * This version sets unit attention for every
11910	 */
11911#if 0
11912	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11913	ctl_est_ua_all(lun, initidx, ua_type);
11914#else
11915	ctl_est_ua_all(lun, -1, ua_type);
11916#endif
11917
11918	/*
11919	 * A reset (any kind, really) clears reservations established with
11920	 * RESERVE/RELEASE.  It does not clear reservations established
11921	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11922	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11923	 * reservations made with the RESERVE/RELEASE commands, because
11924	 * those commands are obsolete in SPC-3.
11925	 */
11926	lun->flags &= ~CTL_LUN_RESERVED;
11927
11928#ifdef CTL_WITH_CA
11929	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11930		ctl_clear_mask(lun->have_ca, i);
11931#endif
11932	lun->prevent_count = 0;
11933	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11934		ctl_clear_mask(lun->prevent, i);
11935	mtx_unlock(&lun->lun_lock);
11936
11937	return (0);
11938}
11939
11940static int
11941ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11942{
11943	struct ctl_lun *lun;
11944	uint32_t targ_lun;
11945	int retval;
11946
11947	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11948	mtx_lock(&softc->ctl_lock);
11949	if (targ_lun >= CTL_MAX_LUNS ||
11950	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11951		mtx_unlock(&softc->ctl_lock);
11952		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11953		return (1);
11954	}
11955	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11956	mtx_unlock(&softc->ctl_lock);
11957	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11958
11959	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11960		union ctl_ha_msg msg_info;
11961
11962		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11963		msg_info.hdr.nexus = io->io_hdr.nexus;
11964		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11965		msg_info.hdr.original_sc = NULL;
11966		msg_info.hdr.serializing_sc = NULL;
11967		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11968		    sizeof(msg_info.task), M_WAITOK);
11969	}
11970	return (retval);
11971}
11972
11973static void
11974ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11975    int other_sc)
11976{
11977	union ctl_io *xio;
11978
11979	mtx_assert(&lun->lun_lock, MA_OWNED);
11980
11981	/*
11982	 * Run through the OOA queue and attempt to find the given I/O.
11983	 * The target port, initiator ID, tag type and tag number have to
11984	 * match the values that we got from the initiator.  If we have an
11985	 * untagged command to abort, simply abort the first untagged command
11986	 * we come to.  We only allow one untagged command at a time of course.
11987	 */
11988	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11989	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11990
11991		if ((targ_port == UINT32_MAX ||
11992		     targ_port == xio->io_hdr.nexus.targ_port) &&
11993		    (init_id == UINT32_MAX ||
11994		     init_id == xio->io_hdr.nexus.initid)) {
11995			if (targ_port != xio->io_hdr.nexus.targ_port ||
11996			    init_id != xio->io_hdr.nexus.initid)
11997				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11998			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11999			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12000				union ctl_ha_msg msg_info;
12001
12002				msg_info.hdr.nexus = xio->io_hdr.nexus;
12003				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12004				msg_info.task.tag_num = xio->scsiio.tag_num;
12005				msg_info.task.tag_type = xio->scsiio.tag_type;
12006				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12007				msg_info.hdr.original_sc = NULL;
12008				msg_info.hdr.serializing_sc = NULL;
12009				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12010				    sizeof(msg_info.task), M_NOWAIT);
12011			}
12012		}
12013	}
12014}
12015
12016static int
12017ctl_abort_task_set(union ctl_io *io)
12018{
12019	struct ctl_softc *softc = control_softc;
12020	struct ctl_lun *lun;
12021	uint32_t targ_lun;
12022
12023	/*
12024	 * Look up the LUN.
12025	 */
12026	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12027	mtx_lock(&softc->ctl_lock);
12028	if (targ_lun >= CTL_MAX_LUNS ||
12029	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12030		mtx_unlock(&softc->ctl_lock);
12031		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12032		return (1);
12033	}
12034
12035	mtx_lock(&lun->lun_lock);
12036	mtx_unlock(&softc->ctl_lock);
12037	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12038		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12039		    io->io_hdr.nexus.initid,
12040		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12041	} else { /* CTL_TASK_CLEAR_TASK_SET */
12042		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12043		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12044	}
12045	mtx_unlock(&lun->lun_lock);
12046	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12047	return (0);
12048}
12049
12050static int
12051ctl_i_t_nexus_reset(union ctl_io *io)
12052{
12053	struct ctl_softc *softc = control_softc;
12054	struct ctl_lun *lun;
12055	uint32_t initidx;
12056
12057	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12058		union ctl_ha_msg msg_info;
12059
12060		msg_info.hdr.nexus = io->io_hdr.nexus;
12061		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12062		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12063		msg_info.hdr.original_sc = NULL;
12064		msg_info.hdr.serializing_sc = NULL;
12065		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12066		    sizeof(msg_info.task), M_WAITOK);
12067	}
12068
12069	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12070	mtx_lock(&softc->ctl_lock);
12071	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12072		mtx_lock(&lun->lun_lock);
12073		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12074		    io->io_hdr.nexus.initid, 1);
12075#ifdef CTL_WITH_CA
12076		ctl_clear_mask(lun->have_ca, initidx);
12077#endif
12078		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12079			lun->flags &= ~CTL_LUN_RESERVED;
12080		if (ctl_is_set(lun->prevent, initidx)) {
12081			ctl_clear_mask(lun->prevent, initidx);
12082			lun->prevent_count--;
12083		}
12084		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12085		mtx_unlock(&lun->lun_lock);
12086	}
12087	mtx_unlock(&softc->ctl_lock);
12088	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12089	return (0);
12090}
12091
12092static int
12093ctl_abort_task(union ctl_io *io)
12094{
12095	union ctl_io *xio;
12096	struct ctl_lun *lun;
12097	struct ctl_softc *softc;
12098#if 0
12099	struct sbuf sb;
12100	char printbuf[128];
12101#endif
12102	int found;
12103	uint32_t targ_lun;
12104
12105	softc = control_softc;
12106	found = 0;
12107
12108	/*
12109	 * Look up the LUN.
12110	 */
12111	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12112	mtx_lock(&softc->ctl_lock);
12113	if (targ_lun >= CTL_MAX_LUNS ||
12114	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12115		mtx_unlock(&softc->ctl_lock);
12116		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12117		return (1);
12118	}
12119
12120#if 0
12121	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12122	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12123#endif
12124
12125	mtx_lock(&lun->lun_lock);
12126	mtx_unlock(&softc->ctl_lock);
12127	/*
12128	 * Run through the OOA queue and attempt to find the given I/O.
12129	 * The target port, initiator ID, tag type and tag number have to
12130	 * match the values that we got from the initiator.  If we have an
12131	 * untagged command to abort, simply abort the first untagged command
12132	 * we come to.  We only allow one untagged command at a time of course.
12133	 */
12134	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12135	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12136#if 0
12137		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12138
12139		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12140			    lun->lun, xio->scsiio.tag_num,
12141			    xio->scsiio.tag_type,
12142			    (xio->io_hdr.blocked_links.tqe_prev
12143			    == NULL) ? "" : " BLOCKED",
12144			    (xio->io_hdr.flags &
12145			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12146			    (xio->io_hdr.flags &
12147			    CTL_FLAG_ABORT) ? " ABORT" : "",
12148			    (xio->io_hdr.flags &
12149			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12150		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12151		sbuf_finish(&sb);
12152		printf("%s\n", sbuf_data(&sb));
12153#endif
12154
12155		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12156		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12157		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12158			continue;
12159
12160		/*
12161		 * If the abort says that the task is untagged, the
12162		 * task in the queue must be untagged.  Otherwise,
12163		 * we just check to see whether the tag numbers
12164		 * match.  This is because the QLogic firmware
12165		 * doesn't pass back the tag type in an abort
12166		 * request.
12167		 */
12168#if 0
12169		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12170		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12171		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12172#endif
12173		/*
12174		 * XXX KDM we've got problems with FC, because it
12175		 * doesn't send down a tag type with aborts.  So we
12176		 * can only really go by the tag number...
12177		 * This may cause problems with parallel SCSI.
12178		 * Need to figure that out!!
12179		 */
12180		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12181			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12182			found = 1;
12183			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12184			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12185				union ctl_ha_msg msg_info;
12186
12187				msg_info.hdr.nexus = io->io_hdr.nexus;
12188				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12189				msg_info.task.tag_num = io->taskio.tag_num;
12190				msg_info.task.tag_type = io->taskio.tag_type;
12191				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12192				msg_info.hdr.original_sc = NULL;
12193				msg_info.hdr.serializing_sc = NULL;
12194#if 0
12195				printf("Sent Abort to other side\n");
12196#endif
12197				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12198				    sizeof(msg_info.task), M_NOWAIT);
12199			}
12200#if 0
12201			printf("ctl_abort_task: found I/O to abort\n");
12202#endif
12203		}
12204	}
12205	mtx_unlock(&lun->lun_lock);
12206
12207	if (found == 0) {
12208		/*
12209		 * This isn't really an error.  It's entirely possible for
12210		 * the abort and command completion to cross on the wire.
12211		 * This is more of an informative/diagnostic error.
12212		 */
12213#if 0
12214		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12215		       "%u:%u:%u tag %d type %d\n",
12216		       io->io_hdr.nexus.initid,
12217		       io->io_hdr.nexus.targ_port,
12218		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12219		       io->taskio.tag_type);
12220#endif
12221	}
12222	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12223	return (0);
12224}
12225
12226static int
12227ctl_query_task(union ctl_io *io, int task_set)
12228{
12229	union ctl_io *xio;
12230	struct ctl_lun *lun;
12231	struct ctl_softc *softc;
12232	int found = 0;
12233	uint32_t targ_lun;
12234
12235	softc = control_softc;
12236	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12237	mtx_lock(&softc->ctl_lock);
12238	if (targ_lun >= CTL_MAX_LUNS ||
12239	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12240		mtx_unlock(&softc->ctl_lock);
12241		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12242		return (1);
12243	}
12244	mtx_lock(&lun->lun_lock);
12245	mtx_unlock(&softc->ctl_lock);
12246	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12247	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12248
12249		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12250		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12251		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12252			continue;
12253
12254		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12255			found = 1;
12256			break;
12257		}
12258	}
12259	mtx_unlock(&lun->lun_lock);
12260	if (found)
12261		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12262	else
12263		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12264	return (0);
12265}
12266
12267static int
12268ctl_query_async_event(union ctl_io *io)
12269{
12270	struct ctl_lun *lun;
12271	struct ctl_softc *softc;
12272	ctl_ua_type ua;
12273	uint32_t targ_lun, initidx;
12274
12275	softc = control_softc;
12276	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12277	mtx_lock(&softc->ctl_lock);
12278	if (targ_lun >= CTL_MAX_LUNS ||
12279	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12280		mtx_unlock(&softc->ctl_lock);
12281		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12282		return (1);
12283	}
12284	mtx_lock(&lun->lun_lock);
12285	mtx_unlock(&softc->ctl_lock);
12286	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12287	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12288	mtx_unlock(&lun->lun_lock);
12289	if (ua != CTL_UA_NONE)
12290		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12291	else
12292		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12293	return (0);
12294}
12295
12296static void
12297ctl_run_task(union ctl_io *io)
12298{
12299	struct ctl_softc *softc = control_softc;
12300	int retval = 1;
12301
12302	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12303	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12304	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12305	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12306	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12307	switch (io->taskio.task_action) {
12308	case CTL_TASK_ABORT_TASK:
12309		retval = ctl_abort_task(io);
12310		break;
12311	case CTL_TASK_ABORT_TASK_SET:
12312	case CTL_TASK_CLEAR_TASK_SET:
12313		retval = ctl_abort_task_set(io);
12314		break;
12315	case CTL_TASK_CLEAR_ACA:
12316		break;
12317	case CTL_TASK_I_T_NEXUS_RESET:
12318		retval = ctl_i_t_nexus_reset(io);
12319		break;
12320	case CTL_TASK_LUN_RESET:
12321		retval = ctl_lun_reset(softc, io);
12322		break;
12323	case CTL_TASK_TARGET_RESET:
12324		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12325		break;
12326	case CTL_TASK_BUS_RESET:
12327		retval = ctl_bus_reset(softc, io);
12328		break;
12329	case CTL_TASK_PORT_LOGIN:
12330		break;
12331	case CTL_TASK_PORT_LOGOUT:
12332		break;
12333	case CTL_TASK_QUERY_TASK:
12334		retval = ctl_query_task(io, 0);
12335		break;
12336	case CTL_TASK_QUERY_TASK_SET:
12337		retval = ctl_query_task(io, 1);
12338		break;
12339	case CTL_TASK_QUERY_ASYNC_EVENT:
12340		retval = ctl_query_async_event(io);
12341		break;
12342	default:
12343		printf("%s: got unknown task management event %d\n",
12344		       __func__, io->taskio.task_action);
12345		break;
12346	}
12347	if (retval == 0)
12348		io->io_hdr.status = CTL_SUCCESS;
12349	else
12350		io->io_hdr.status = CTL_ERROR;
12351	ctl_done(io);
12352}
12353
12354/*
12355 * For HA operation.  Handle commands that come in from the other
12356 * controller.
12357 */
12358static void
12359ctl_handle_isc(union ctl_io *io)
12360{
12361	struct ctl_softc *softc = control_softc;
12362	struct ctl_lun *lun;
12363	const struct ctl_cmd_entry *entry;
12364	uint32_t targ_lun;
12365
12366	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12367	switch (io->io_hdr.msg_type) {
12368	case CTL_MSG_SERIALIZE:
12369		ctl_serialize_other_sc_cmd(&io->scsiio);
12370		break;
12371	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12372		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12373		if (targ_lun >= CTL_MAX_LUNS ||
12374		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12375			ctl_done(io);
12376			break;
12377		}
12378		mtx_lock(&lun->lun_lock);
12379		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12380			mtx_unlock(&lun->lun_lock);
12381			ctl_done(io);
12382			break;
12383		}
12384		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12385		mtx_unlock(&lun->lun_lock);
12386		ctl_enqueue_rtr(io);
12387		break;
12388	case CTL_MSG_FINISH_IO:
12389		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12390			ctl_done(io);
12391			break;
12392		}
12393		if (targ_lun >= CTL_MAX_LUNS ||
12394		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12395			ctl_free_io(io);
12396			break;
12397		}
12398		mtx_lock(&lun->lun_lock);
12399		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12400		ctl_check_blocked(lun);
12401		mtx_unlock(&lun->lun_lock);
12402		ctl_free_io(io);
12403		break;
12404	case CTL_MSG_PERS_ACTION:
12405		ctl_hndl_per_res_out_on_other_sc(
12406			(union ctl_ha_msg *)&io->presio.pr_msg);
12407		ctl_free_io(io);
12408		break;
12409	case CTL_MSG_BAD_JUJU:
12410		ctl_done(io);
12411		break;
12412	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12413		ctl_datamove_remote(io);
12414		break;
12415	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12416		io->scsiio.be_move_done(io);
12417		break;
12418	case CTL_MSG_FAILOVER:
12419		ctl_failover_lun(io);
12420		ctl_free_io(io);
12421		break;
12422	default:
12423		printf("%s: Invalid message type %d\n",
12424		       __func__, io->io_hdr.msg_type);
12425		ctl_free_io(io);
12426		break;
12427	}
12428
12429}
12430
12431
12432/*
12433 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12434 * there is no match.
12435 */
12436static ctl_lun_error_pattern
12437ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12438{
12439	const struct ctl_cmd_entry *entry;
12440	ctl_lun_error_pattern filtered_pattern, pattern;
12441
12442	pattern = desc->error_pattern;
12443
12444	/*
12445	 * XXX KDM we need more data passed into this function to match a
12446	 * custom pattern, and we actually need to implement custom pattern
12447	 * matching.
12448	 */
12449	if (pattern & CTL_LUN_PAT_CMD)
12450		return (CTL_LUN_PAT_CMD);
12451
12452	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12453		return (CTL_LUN_PAT_ANY);
12454
12455	entry = ctl_get_cmd_entry(ctsio, NULL);
12456
12457	filtered_pattern = entry->pattern & pattern;
12458
12459	/*
12460	 * If the user requested specific flags in the pattern (e.g.
12461	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12462	 * flags.
12463	 *
12464	 * If the user did not specify any flags, it doesn't matter whether
12465	 * or not the command supports the flags.
12466	 */
12467	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12468	     (pattern & ~CTL_LUN_PAT_MASK))
12469		return (CTL_LUN_PAT_NONE);
12470
12471	/*
12472	 * If the user asked for a range check, see if the requested LBA
12473	 * range overlaps with this command's LBA range.
12474	 */
12475	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12476		uint64_t lba1;
12477		uint64_t len1;
12478		ctl_action action;
12479		int retval;
12480
12481		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12482		if (retval != 0)
12483			return (CTL_LUN_PAT_NONE);
12484
12485		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12486					      desc->lba_range.len, FALSE);
12487		/*
12488		 * A "pass" means that the LBA ranges don't overlap, so
12489		 * this doesn't match the user's range criteria.
12490		 */
12491		if (action == CTL_ACTION_PASS)
12492			return (CTL_LUN_PAT_NONE);
12493	}
12494
12495	return (filtered_pattern);
12496}
12497
12498static void
12499ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12500{
12501	struct ctl_error_desc *desc, *desc2;
12502
12503	mtx_assert(&lun->lun_lock, MA_OWNED);
12504
12505	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12506		ctl_lun_error_pattern pattern;
12507		/*
12508		 * Check to see whether this particular command matches
12509		 * the pattern in the descriptor.
12510		 */
12511		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12512		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12513			continue;
12514
12515		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12516		case CTL_LUN_INJ_ABORTED:
12517			ctl_set_aborted(&io->scsiio);
12518			break;
12519		case CTL_LUN_INJ_MEDIUM_ERR:
12520			ctl_set_medium_error(&io->scsiio,
12521			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12522			     CTL_FLAG_DATA_OUT);
12523			break;
12524		case CTL_LUN_INJ_UA:
12525			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12526			 * OCCURRED */
12527			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12528			break;
12529		case CTL_LUN_INJ_CUSTOM:
12530			/*
12531			 * We're assuming the user knows what he is doing.
12532			 * Just copy the sense information without doing
12533			 * checks.
12534			 */
12535			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12536			      MIN(sizeof(desc->custom_sense),
12537				  sizeof(io->scsiio.sense_data)));
12538			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12539			io->scsiio.sense_len = SSD_FULL_SIZE;
12540			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12541			break;
12542		case CTL_LUN_INJ_NONE:
12543		default:
12544			/*
12545			 * If this is an error injection type we don't know
12546			 * about, clear the continuous flag (if it is set)
12547			 * so it will get deleted below.
12548			 */
12549			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12550			break;
12551		}
12552		/*
12553		 * By default, each error injection action is a one-shot
12554		 */
12555		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12556			continue;
12557
12558		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12559
12560		free(desc, M_CTL);
12561	}
12562}
12563
12564#ifdef CTL_IO_DELAY
12565static void
12566ctl_datamove_timer_wakeup(void *arg)
12567{
12568	union ctl_io *io;
12569
12570	io = (union ctl_io *)arg;
12571
12572	ctl_datamove(io);
12573}
12574#endif /* CTL_IO_DELAY */
12575
12576void
12577ctl_datamove(union ctl_io *io)
12578{
12579	struct ctl_lun *lun;
12580	void (*fe_datamove)(union ctl_io *io);
12581
12582	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12583
12584	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12585
12586	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12587#ifdef CTL_TIME_IO
12588	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12589		char str[256];
12590		char path_str[64];
12591		struct sbuf sb;
12592
12593		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12594		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12595
12596		sbuf_cat(&sb, path_str);
12597		switch (io->io_hdr.io_type) {
12598		case CTL_IO_SCSI:
12599			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12600			sbuf_printf(&sb, "\n");
12601			sbuf_cat(&sb, path_str);
12602			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12603				    io->scsiio.tag_num, io->scsiio.tag_type);
12604			break;
12605		case CTL_IO_TASK:
12606			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12607				    "Tag Type: %d\n", io->taskio.task_action,
12608				    io->taskio.tag_num, io->taskio.tag_type);
12609			break;
12610		default:
12611			panic("%s: Invalid CTL I/O type %d\n",
12612			    __func__, io->io_hdr.io_type);
12613		}
12614		sbuf_cat(&sb, path_str);
12615		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12616			    (intmax_t)time_uptime - io->io_hdr.start_time);
12617		sbuf_finish(&sb);
12618		printf("%s", sbuf_data(&sb));
12619	}
12620#endif /* CTL_TIME_IO */
12621
12622#ifdef CTL_IO_DELAY
12623	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12624		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12625	} else {
12626		if ((lun != NULL)
12627		 && (lun->delay_info.datamove_delay > 0)) {
12628
12629			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12630			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12631			callout_reset(&io->io_hdr.delay_callout,
12632				      lun->delay_info.datamove_delay * hz,
12633				      ctl_datamove_timer_wakeup, io);
12634			if (lun->delay_info.datamove_type ==
12635			    CTL_DELAY_TYPE_ONESHOT)
12636				lun->delay_info.datamove_delay = 0;
12637			return;
12638		}
12639	}
12640#endif
12641
12642	/*
12643	 * This command has been aborted.  Set the port status, so we fail
12644	 * the data move.
12645	 */
12646	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12647		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12648		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12649		       io->io_hdr.nexus.targ_port,
12650		       io->io_hdr.nexus.targ_lun);
12651		io->io_hdr.port_status = 31337;
12652		/*
12653		 * Note that the backend, in this case, will get the
12654		 * callback in its context.  In other cases it may get
12655		 * called in the frontend's interrupt thread context.
12656		 */
12657		io->scsiio.be_move_done(io);
12658		return;
12659	}
12660
12661	/* Don't confuse frontend with zero length data move. */
12662	if (io->scsiio.kern_data_len == 0) {
12663		io->scsiio.be_move_done(io);
12664		return;
12665	}
12666
12667	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12668	fe_datamove(io);
12669}
12670
12671static void
12672ctl_send_datamove_done(union ctl_io *io, int have_lock)
12673{
12674	union ctl_ha_msg msg;
12675#ifdef CTL_TIME_IO
12676	struct bintime cur_bt;
12677#endif
12678
12679	memset(&msg, 0, sizeof(msg));
12680	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12681	msg.hdr.original_sc = io;
12682	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12683	msg.hdr.nexus = io->io_hdr.nexus;
12684	msg.hdr.status = io->io_hdr.status;
12685	msg.scsi.tag_num = io->scsiio.tag_num;
12686	msg.scsi.tag_type = io->scsiio.tag_type;
12687	msg.scsi.scsi_status = io->scsiio.scsi_status;
12688	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12689	       io->scsiio.sense_len);
12690	msg.scsi.sense_len = io->scsiio.sense_len;
12691	msg.scsi.sense_residual = io->scsiio.sense_residual;
12692	msg.scsi.fetd_status = io->io_hdr.port_status;
12693	msg.scsi.residual = io->scsiio.residual;
12694	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12695	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12696		ctl_failover_io(io, /*have_lock*/ have_lock);
12697		return;
12698	}
12699	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12700	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12701	    msg.scsi.sense_len, M_WAITOK);
12702
12703#ifdef CTL_TIME_IO
12704	getbinuptime(&cur_bt);
12705	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12706	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12707#endif
12708	io->io_hdr.num_dmas++;
12709}
12710
12711/*
12712 * The DMA to the remote side is done, now we need to tell the other side
12713 * we're done so it can continue with its data movement.
12714 */
12715static void
12716ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12717{
12718	union ctl_io *io;
12719	uint32_t i;
12720
12721	io = rq->context;
12722
12723	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12724		printf("%s: ISC DMA write failed with error %d", __func__,
12725		       rq->ret);
12726		ctl_set_internal_failure(&io->scsiio,
12727					 /*sks_valid*/ 1,
12728					 /*retry_count*/ rq->ret);
12729	}
12730
12731	ctl_dt_req_free(rq);
12732
12733	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12734		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12735	free(io->io_hdr.remote_sglist, M_CTL);
12736	io->io_hdr.remote_sglist = NULL;
12737	io->io_hdr.local_sglist = NULL;
12738
12739	/*
12740	 * The data is in local and remote memory, so now we need to send
12741	 * status (good or back) back to the other side.
12742	 */
12743	ctl_send_datamove_done(io, /*have_lock*/ 0);
12744}
12745
12746/*
12747 * We've moved the data from the host/controller into local memory.  Now we
12748 * need to push it over to the remote controller's memory.
12749 */
12750static int
12751ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12752{
12753	int retval;
12754
12755	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12756					  ctl_datamove_remote_write_cb);
12757	return (retval);
12758}
12759
12760static void
12761ctl_datamove_remote_write(union ctl_io *io)
12762{
12763	int retval;
12764	void (*fe_datamove)(union ctl_io *io);
12765
12766	/*
12767	 * - Get the data from the host/HBA into local memory.
12768	 * - DMA memory from the local controller to the remote controller.
12769	 * - Send status back to the remote controller.
12770	 */
12771
12772	retval = ctl_datamove_remote_sgl_setup(io);
12773	if (retval != 0)
12774		return;
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_write_cb;
12784
12785	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12786	fe_datamove(io);
12787}
12788
12789static int
12790ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12791{
12792#if 0
12793	char str[256];
12794	char path_str[64];
12795	struct sbuf sb;
12796#endif
12797	uint32_t i;
12798
12799	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12800		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12801	free(io->io_hdr.remote_sglist, M_CTL);
12802	io->io_hdr.remote_sglist = NULL;
12803	io->io_hdr.local_sglist = NULL;
12804
12805#if 0
12806	scsi_path_string(io, path_str, sizeof(path_str));
12807	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12808	sbuf_cat(&sb, path_str);
12809	scsi_command_string(&io->scsiio, NULL, &sb);
12810	sbuf_printf(&sb, "\n");
12811	sbuf_cat(&sb, path_str);
12812	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12813		    io->scsiio.tag_num, io->scsiio.tag_type);
12814	sbuf_cat(&sb, path_str);
12815	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12816		    io->io_hdr.flags, io->io_hdr.status);
12817	sbuf_finish(&sb);
12818	printk("%s", sbuf_data(&sb));
12819#endif
12820
12821
12822	/*
12823	 * The read is done, now we need to send status (good or bad) back
12824	 * to the other side.
12825	 */
12826	ctl_send_datamove_done(io, /*have_lock*/ 0);
12827
12828	return (0);
12829}
12830
12831static void
12832ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12833{
12834	union ctl_io *io;
12835	void (*fe_datamove)(union ctl_io *io);
12836
12837	io = rq->context;
12838
12839	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12840		printf("%s: ISC DMA read failed with error %d\n", __func__,
12841		       rq->ret);
12842		ctl_set_internal_failure(&io->scsiio,
12843					 /*sks_valid*/ 1,
12844					 /*retry_count*/ rq->ret);
12845	}
12846
12847	ctl_dt_req_free(rq);
12848
12849	/* Switch the pointer over so the FETD knows what to do */
12850	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12851
12852	/*
12853	 * Use a custom move done callback, since we need to send completion
12854	 * back to the other controller, not to the backend on this side.
12855	 */
12856	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12857
12858	/* XXX KDM add checks like the ones in ctl_datamove? */
12859
12860	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12861	fe_datamove(io);
12862}
12863
12864static int
12865ctl_datamove_remote_sgl_setup(union ctl_io *io)
12866{
12867	struct ctl_sg_entry *local_sglist;
12868	uint32_t len_to_go;
12869	int retval;
12870	int i;
12871
12872	retval = 0;
12873	local_sglist = io->io_hdr.local_sglist;
12874	len_to_go = io->scsiio.kern_data_len;
12875
12876	/*
12877	 * The difficult thing here is that the size of the various
12878	 * S/G segments may be different than the size from the
12879	 * remote controller.  That'll make it harder when DMAing
12880	 * the data back to the other side.
12881	 */
12882	for (i = 0; len_to_go > 0; i++) {
12883		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12884		local_sglist[i].addr =
12885		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12886
12887		len_to_go -= local_sglist[i].len;
12888	}
12889	/*
12890	 * Reset the number of S/G entries accordingly.  The original
12891	 * number of S/G entries is available in rem_sg_entries.
12892	 */
12893	io->scsiio.kern_sg_entries = i;
12894
12895#if 0
12896	printf("%s: kern_sg_entries = %d\n", __func__,
12897	       io->scsiio.kern_sg_entries);
12898	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12899		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12900		       local_sglist[i].addr, local_sglist[i].len);
12901#endif
12902
12903	return (retval);
12904}
12905
12906static int
12907ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12908			 ctl_ha_dt_cb callback)
12909{
12910	struct ctl_ha_dt_req *rq;
12911	struct ctl_sg_entry *remote_sglist, *local_sglist;
12912	uint32_t local_used, remote_used, total_used;
12913	int i, j, isc_ret;
12914
12915	rq = ctl_dt_req_alloc();
12916
12917	/*
12918	 * If we failed to allocate the request, and if the DMA didn't fail
12919	 * anyway, set busy status.  This is just a resource allocation
12920	 * failure.
12921	 */
12922	if ((rq == NULL)
12923	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12924	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12925		ctl_set_busy(&io->scsiio);
12926
12927	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12928	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12929
12930		if (rq != NULL)
12931			ctl_dt_req_free(rq);
12932
12933		/*
12934		 * The data move failed.  We need to return status back
12935		 * to the other controller.  No point in trying to DMA
12936		 * data to the remote controller.
12937		 */
12938
12939		ctl_send_datamove_done(io, /*have_lock*/ 0);
12940
12941		return (1);
12942	}
12943
12944	local_sglist = io->io_hdr.local_sglist;
12945	remote_sglist = io->io_hdr.remote_sglist;
12946	local_used = 0;
12947	remote_used = 0;
12948	total_used = 0;
12949
12950	/*
12951	 * Pull/push the data over the wire from/to the other controller.
12952	 * This takes into account the possibility that the local and
12953	 * remote sglists may not be identical in terms of the size of
12954	 * the elements and the number of elements.
12955	 *
12956	 * One fundamental assumption here is that the length allocated for
12957	 * both the local and remote sglists is identical.  Otherwise, we've
12958	 * essentially got a coding error of some sort.
12959	 */
12960	isc_ret = CTL_HA_STATUS_SUCCESS;
12961	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12962		uint32_t cur_len;
12963		uint8_t *tmp_ptr;
12964
12965		rq->command = command;
12966		rq->context = io;
12967
12968		/*
12969		 * Both pointers should be aligned.  But it is possible
12970		 * that the allocation length is not.  They should both
12971		 * also have enough slack left over at the end, though,
12972		 * to round up to the next 8 byte boundary.
12973		 */
12974		cur_len = MIN(local_sglist[i].len - local_used,
12975			      remote_sglist[j].len - remote_used);
12976		rq->size = cur_len;
12977
12978		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12979		tmp_ptr += local_used;
12980
12981#if 0
12982		/* Use physical addresses when talking to ISC hardware */
12983		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12984			/* XXX KDM use busdma */
12985			rq->local = vtophys(tmp_ptr);
12986		} else
12987			rq->local = tmp_ptr;
12988#else
12989		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12990		    ("HA does not support BUS_ADDR"));
12991		rq->local = tmp_ptr;
12992#endif
12993
12994		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12995		tmp_ptr += remote_used;
12996		rq->remote = tmp_ptr;
12997
12998		rq->callback = NULL;
12999
13000		local_used += cur_len;
13001		if (local_used >= local_sglist[i].len) {
13002			i++;
13003			local_used = 0;
13004		}
13005
13006		remote_used += cur_len;
13007		if (remote_used >= remote_sglist[j].len) {
13008			j++;
13009			remote_used = 0;
13010		}
13011		total_used += cur_len;
13012
13013		if (total_used >= io->scsiio.kern_data_len)
13014			rq->callback = callback;
13015
13016#if 0
13017		printf("%s: %s: local %p remote %p size %d\n", __func__,
13018		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13019		       rq->local, rq->remote, rq->size);
13020#endif
13021
13022		isc_ret = ctl_dt_single(rq);
13023		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13024			break;
13025	}
13026	if (isc_ret != CTL_HA_STATUS_WAIT) {
13027		rq->ret = isc_ret;
13028		callback(rq);
13029	}
13030
13031	return (0);
13032}
13033
13034static void
13035ctl_datamove_remote_read(union ctl_io *io)
13036{
13037	int retval;
13038	uint32_t i;
13039
13040	/*
13041	 * This will send an error to the other controller in the case of a
13042	 * failure.
13043	 */
13044	retval = ctl_datamove_remote_sgl_setup(io);
13045	if (retval != 0)
13046		return;
13047
13048	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13049					  ctl_datamove_remote_read_cb);
13050	if (retval != 0) {
13051		/*
13052		 * Make sure we free memory if there was an error..  The
13053		 * ctl_datamove_remote_xfer() function will send the
13054		 * datamove done message, or call the callback with an
13055		 * error if there is a problem.
13056		 */
13057		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13058			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13059		free(io->io_hdr.remote_sglist, M_CTL);
13060		io->io_hdr.remote_sglist = NULL;
13061		io->io_hdr.local_sglist = NULL;
13062	}
13063}
13064
13065/*
13066 * Process a datamove request from the other controller.  This is used for
13067 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13068 * first.  Once that is complete, the data gets DMAed into the remote
13069 * controller's memory.  For reads, we DMA from the remote controller's
13070 * memory into our memory first, and then move it out to the FETD.
13071 */
13072static void
13073ctl_datamove_remote(union ctl_io *io)
13074{
13075
13076	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13077
13078	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13079		ctl_failover_io(io, /*have_lock*/ 0);
13080		return;
13081	}
13082
13083	/*
13084	 * Note that we look for an aborted I/O here, but don't do some of
13085	 * the other checks that ctl_datamove() normally does.
13086	 * We don't need to run the datamove delay code, since that should
13087	 * have been done if need be on the other controller.
13088	 */
13089	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13090		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13091		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13092		       io->io_hdr.nexus.targ_port,
13093		       io->io_hdr.nexus.targ_lun);
13094		io->io_hdr.port_status = 31338;
13095		ctl_send_datamove_done(io, /*have_lock*/ 0);
13096		return;
13097	}
13098
13099	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13100		ctl_datamove_remote_write(io);
13101	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13102		ctl_datamove_remote_read(io);
13103	else {
13104		io->io_hdr.port_status = 31339;
13105		ctl_send_datamove_done(io, /*have_lock*/ 0);
13106	}
13107}
13108
13109static void
13110ctl_process_done(union ctl_io *io)
13111{
13112	struct ctl_lun *lun;
13113	struct ctl_softc *softc = control_softc;
13114	void (*fe_done)(union ctl_io *io);
13115	union ctl_ha_msg msg;
13116	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13117
13118	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13119	fe_done = softc->ctl_ports[targ_port]->fe_done;
13120
13121#ifdef CTL_TIME_IO
13122	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13123		char str[256];
13124		char path_str[64];
13125		struct sbuf sb;
13126
13127		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13128		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13129
13130		sbuf_cat(&sb, path_str);
13131		switch (io->io_hdr.io_type) {
13132		case CTL_IO_SCSI:
13133			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13134			sbuf_printf(&sb, "\n");
13135			sbuf_cat(&sb, path_str);
13136			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13137				    io->scsiio.tag_num, io->scsiio.tag_type);
13138			break;
13139		case CTL_IO_TASK:
13140			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13141				    "Tag Type: %d\n", io->taskio.task_action,
13142				    io->taskio.tag_num, io->taskio.tag_type);
13143			break;
13144		default:
13145			panic("%s: Invalid CTL I/O type %d\n",
13146			    __func__, io->io_hdr.io_type);
13147		}
13148		sbuf_cat(&sb, path_str);
13149		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13150			    (intmax_t)time_uptime - io->io_hdr.start_time);
13151		sbuf_finish(&sb);
13152		printf("%s", sbuf_data(&sb));
13153	}
13154#endif /* CTL_TIME_IO */
13155
13156	switch (io->io_hdr.io_type) {
13157	case CTL_IO_SCSI:
13158		break;
13159	case CTL_IO_TASK:
13160		if (ctl_debug & CTL_DEBUG_INFO)
13161			ctl_io_error_print(io, NULL);
13162		fe_done(io);
13163		return;
13164	default:
13165		panic("%s: Invalid CTL I/O type %d\n",
13166		    __func__, io->io_hdr.io_type);
13167	}
13168
13169	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13170	if (lun == NULL) {
13171		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13172				 io->io_hdr.nexus.targ_mapped_lun));
13173		goto bailout;
13174	}
13175
13176	mtx_lock(&lun->lun_lock);
13177
13178	/*
13179	 * Check to see if we have any informational exception and status
13180	 * of this command can be modified to report it in form of either
13181	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13182	 */
13183	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13184	    io->io_hdr.status == CTL_SUCCESS &&
13185	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13186		uint8_t mrie = lun->MODE_IE.mrie;
13187		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13188		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13189		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13190		     mrie == SIEP_MRIE_REC_UNCOND ||
13191		     mrie == SIEP_MRIE_NO_SENSE) &&
13192		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13193		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13194			ctl_set_sense(&io->scsiio,
13195			      /*current_error*/ 1,
13196			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13197			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13198			      /*asc*/ lun->ie_asc,
13199			      /*ascq*/ lun->ie_ascq,
13200			      SSD_ELEM_NONE);
13201			lun->ie_reported = 1;
13202		}
13203	} else if (lun->ie_reported < 0)
13204		lun->ie_reported = 0;
13205
13206	/*
13207	 * Check to see if we have any errors to inject here.  We only
13208	 * inject errors for commands that don't already have errors set.
13209	 */
13210	if (!STAILQ_EMPTY(&lun->error_list) &&
13211	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13212	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13213		ctl_inject_error(lun, io);
13214
13215	/*
13216	 * XXX KDM how do we treat commands that aren't completed
13217	 * successfully?
13218	 *
13219	 * XXX KDM should we also track I/O latency?
13220	 */
13221	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13222	    io->io_hdr.io_type == CTL_IO_SCSI) {
13223#ifdef CTL_TIME_IO
13224		struct bintime cur_bt;
13225#endif
13226		int type;
13227
13228		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13229		    CTL_FLAG_DATA_IN)
13230			type = CTL_STATS_READ;
13231		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13232		    CTL_FLAG_DATA_OUT)
13233			type = CTL_STATS_WRITE;
13234		else
13235			type = CTL_STATS_NO_IO;
13236
13237		lun->stats.ports[targ_port].bytes[type] +=
13238		    io->scsiio.kern_total_len;
13239		lun->stats.ports[targ_port].operations[type]++;
13240#ifdef CTL_TIME_IO
13241		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13242		   &io->io_hdr.dma_bt);
13243		getbinuptime(&cur_bt);
13244		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13245		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13246#endif
13247		lun->stats.ports[targ_port].num_dmas[type] +=
13248		    io->io_hdr.num_dmas;
13249	}
13250
13251	/*
13252	 * Remove this from the OOA queue.
13253	 */
13254	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13255#ifdef CTL_TIME_IO
13256	if (TAILQ_EMPTY(&lun->ooa_queue))
13257		lun->last_busy = getsbinuptime();
13258#endif
13259
13260	/*
13261	 * Run through the blocked queue on this LUN and see if anything
13262	 * has become unblocked, now that this transaction is done.
13263	 */
13264	ctl_check_blocked(lun);
13265
13266	/*
13267	 * If the LUN has been invalidated, free it if there is nothing
13268	 * left on its OOA queue.
13269	 */
13270	if ((lun->flags & CTL_LUN_INVALID)
13271	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13272		mtx_unlock(&lun->lun_lock);
13273		mtx_lock(&softc->ctl_lock);
13274		ctl_free_lun(lun);
13275		mtx_unlock(&softc->ctl_lock);
13276	} else
13277		mtx_unlock(&lun->lun_lock);
13278
13279bailout:
13280
13281	/*
13282	 * If this command has been aborted, make sure we set the status
13283	 * properly.  The FETD is responsible for freeing the I/O and doing
13284	 * whatever it needs to do to clean up its state.
13285	 */
13286	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13287		ctl_set_task_aborted(&io->scsiio);
13288
13289	/*
13290	 * If enabled, print command error status.
13291	 */
13292	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13293	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13294		ctl_io_error_print(io, NULL);
13295
13296	/*
13297	 * Tell the FETD or the other shelf controller we're done with this
13298	 * command.  Note that only SCSI commands get to this point.  Task
13299	 * management commands are completed above.
13300	 */
13301	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13302	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13303		memset(&msg, 0, sizeof(msg));
13304		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13305		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13306		msg.hdr.nexus = io->io_hdr.nexus;
13307		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13308		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13309		    M_WAITOK);
13310	}
13311
13312	fe_done(io);
13313}
13314
13315#ifdef CTL_WITH_CA
13316/*
13317 * Front end should call this if it doesn't do autosense.  When the request
13318 * sense comes back in from the initiator, we'll dequeue this and send it.
13319 */
13320int
13321ctl_queue_sense(union ctl_io *io)
13322{
13323	struct ctl_lun *lun;
13324	struct ctl_port *port;
13325	struct ctl_softc *softc;
13326	uint32_t initidx, targ_lun;
13327
13328	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13329
13330	softc = control_softc;
13331	port = ctl_io_port(&ctsio->io_hdr);
13332	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13333
13334	/*
13335	 * LUN lookup will likely move to the ctl_work_thread() once we
13336	 * have our new queueing infrastructure (that doesn't put things on
13337	 * a per-LUN queue initially).  That is so that we can handle
13338	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13339	 * can't deal with that right now.
13340	 * If we don't have a LUN for this, just toss the sense information.
13341	 */
13342	mtx_lock(&softc->ctl_lock);
13343	if (targ_lun >= CTL_MAX_LUNS ||
13344	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13345		mtx_unlock(&softc->ctl_lock);
13346		goto bailout;
13347	}
13348	mtx_lock(&lun->lun_lock);
13349	mtx_unlock(&softc->ctl_lock);
13350
13351	/*
13352	 * Already have CA set for this LUN...toss the sense information.
13353	 */
13354	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13355	if (ctl_is_set(lun->have_ca, initidx)) {
13356		mtx_unlock(&lun->lun_lock);
13357		goto bailout;
13358	}
13359
13360	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13361	       MIN(sizeof(lun->pending_sense[initidx]),
13362	       sizeof(io->scsiio.sense_data)));
13363	ctl_set_mask(lun->have_ca, initidx);
13364	mtx_unlock(&lun->lun_lock);
13365
13366bailout:
13367	ctl_free_io(io);
13368	return (CTL_RETVAL_COMPLETE);
13369}
13370#endif
13371
13372/*
13373 * Primary command inlet from frontend ports.  All SCSI and task I/O
13374 * requests must go through this function.
13375 */
13376int
13377ctl_queue(union ctl_io *io)
13378{
13379	struct ctl_port *port;
13380
13381	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13382
13383#ifdef CTL_TIME_IO
13384	io->io_hdr.start_time = time_uptime;
13385	getbinuptime(&io->io_hdr.start_bt);
13386#endif /* CTL_TIME_IO */
13387
13388	/* Map FE-specific LUN ID into global one. */
13389	port = ctl_io_port(&io->io_hdr);
13390	io->io_hdr.nexus.targ_mapped_lun =
13391	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13392
13393	switch (io->io_hdr.io_type) {
13394	case CTL_IO_SCSI:
13395	case CTL_IO_TASK:
13396		if (ctl_debug & CTL_DEBUG_CDB)
13397			ctl_io_print(io);
13398		ctl_enqueue_incoming(io);
13399		break;
13400	default:
13401		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13402		return (EINVAL);
13403	}
13404
13405	return (CTL_RETVAL_COMPLETE);
13406}
13407
13408#ifdef CTL_IO_DELAY
13409static void
13410ctl_done_timer_wakeup(void *arg)
13411{
13412	union ctl_io *io;
13413
13414	io = (union ctl_io *)arg;
13415	ctl_done(io);
13416}
13417#endif /* CTL_IO_DELAY */
13418
13419void
13420ctl_serseq_done(union ctl_io *io)
13421{
13422	struct ctl_lun *lun;
13423
13424	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13425	if (lun->be_lun == NULL ||
13426	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13427		return;
13428	mtx_lock(&lun->lun_lock);
13429	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13430	ctl_check_blocked(lun);
13431	mtx_unlock(&lun->lun_lock);
13432}
13433
13434void
13435ctl_done(union ctl_io *io)
13436{
13437
13438	/*
13439	 * Enable this to catch duplicate completion issues.
13440	 */
13441#if 0
13442	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13443		printf("%s: type %d msg %d cdb %x iptl: "
13444		       "%u:%u:%u tag 0x%04x "
13445		       "flag %#x status %x\n",
13446			__func__,
13447			io->io_hdr.io_type,
13448			io->io_hdr.msg_type,
13449			io->scsiio.cdb[0],
13450			io->io_hdr.nexus.initid,
13451			io->io_hdr.nexus.targ_port,
13452			io->io_hdr.nexus.targ_lun,
13453			(io->io_hdr.io_type ==
13454			CTL_IO_TASK) ?
13455			io->taskio.tag_num :
13456			io->scsiio.tag_num,
13457		        io->io_hdr.flags,
13458			io->io_hdr.status);
13459	} else
13460		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13461#endif
13462
13463	/*
13464	 * This is an internal copy of an I/O, and should not go through
13465	 * the normal done processing logic.
13466	 */
13467	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13468		return;
13469
13470#ifdef CTL_IO_DELAY
13471	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13472		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13473	} else {
13474		struct ctl_lun *lun;
13475
13476		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13477
13478		if ((lun != NULL)
13479		 && (lun->delay_info.done_delay > 0)) {
13480
13481			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13482			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13483			callout_reset(&io->io_hdr.delay_callout,
13484				      lun->delay_info.done_delay * hz,
13485				      ctl_done_timer_wakeup, io);
13486			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13487				lun->delay_info.done_delay = 0;
13488			return;
13489		}
13490	}
13491#endif /* CTL_IO_DELAY */
13492
13493	ctl_enqueue_done(io);
13494}
13495
13496static void
13497ctl_work_thread(void *arg)
13498{
13499	struct ctl_thread *thr = (struct ctl_thread *)arg;
13500	struct ctl_softc *softc = thr->ctl_softc;
13501	union ctl_io *io;
13502	int retval;
13503
13504	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13505
13506	for (;;) {
13507		/*
13508		 * We handle the queues in this order:
13509		 * - ISC
13510		 * - done queue (to free up resources, unblock other commands)
13511		 * - RtR queue
13512		 * - incoming queue
13513		 *
13514		 * If those queues are empty, we break out of the loop and
13515		 * go to sleep.
13516		 */
13517		mtx_lock(&thr->queue_lock);
13518		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13519		if (io != NULL) {
13520			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13521			mtx_unlock(&thr->queue_lock);
13522			ctl_handle_isc(io);
13523			continue;
13524		}
13525		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13526		if (io != NULL) {
13527			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13528			/* clear any blocked commands, call fe_done */
13529			mtx_unlock(&thr->queue_lock);
13530			ctl_process_done(io);
13531			continue;
13532		}
13533		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13534		if (io != NULL) {
13535			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13536			mtx_unlock(&thr->queue_lock);
13537			if (io->io_hdr.io_type == CTL_IO_TASK)
13538				ctl_run_task(io);
13539			else
13540				ctl_scsiio_precheck(softc, &io->scsiio);
13541			continue;
13542		}
13543		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13544		if (io != NULL) {
13545			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13546			mtx_unlock(&thr->queue_lock);
13547			retval = ctl_scsiio(&io->scsiio);
13548			if (retval != CTL_RETVAL_COMPLETE)
13549				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13550			continue;
13551		}
13552
13553		/* Sleep until we have something to do. */
13554		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13555	}
13556}
13557
13558static void
13559ctl_lun_thread(void *arg)
13560{
13561	struct ctl_softc *softc = (struct ctl_softc *)arg;
13562	struct ctl_be_lun *be_lun;
13563
13564	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13565
13566	for (;;) {
13567		mtx_lock(&softc->ctl_lock);
13568		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13569		if (be_lun != NULL) {
13570			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13571			mtx_unlock(&softc->ctl_lock);
13572			ctl_create_lun(be_lun);
13573			continue;
13574		}
13575
13576		/* Sleep until we have something to do. */
13577		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13578		    PDROP | PRIBIO, "-", 0);
13579	}
13580}
13581
13582static void
13583ctl_thresh_thread(void *arg)
13584{
13585	struct ctl_softc *softc = (struct ctl_softc *)arg;
13586	struct ctl_lun *lun;
13587	struct ctl_logical_block_provisioning_page *page;
13588	const char *attr;
13589	union ctl_ha_msg msg;
13590	uint64_t thres, val;
13591	int i, e, set;
13592
13593	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13594
13595	for (;;) {
13596		mtx_lock(&softc->ctl_lock);
13597		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13598			if ((lun->flags & CTL_LUN_DISABLED) ||
13599			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13600			    lun->backend->lun_attr == NULL)
13601				continue;
13602			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13603			    softc->ha_mode == CTL_HA_MODE_XFER)
13604				continue;
13605			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13606				continue;
13607			e = 0;
13608			page = &lun->MODE_LBP;
13609			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13610				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13611					continue;
13612				thres = scsi_4btoul(page->descr[i].count);
13613				thres <<= CTL_LBP_EXPONENT;
13614				switch (page->descr[i].resource) {
13615				case 0x01:
13616					attr = "blocksavail";
13617					break;
13618				case 0x02:
13619					attr = "blocksused";
13620					break;
13621				case 0xf1:
13622					attr = "poolblocksavail";
13623					break;
13624				case 0xf2:
13625					attr = "poolblocksused";
13626					break;
13627				default:
13628					continue;
13629				}
13630				mtx_unlock(&softc->ctl_lock); // XXX
13631				val = lun->backend->lun_attr(
13632				    lun->be_lun->be_lun, attr);
13633				mtx_lock(&softc->ctl_lock);
13634				if (val == UINT64_MAX)
13635					continue;
13636				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13637				    == SLBPPD_ARMING_INC)
13638					e = (val >= thres);
13639				else
13640					e = (val <= thres);
13641				if (e)
13642					break;
13643			}
13644			mtx_lock(&lun->lun_lock);
13645			if (e) {
13646				scsi_u64to8b((uint8_t *)&page->descr[i] -
13647				    (uint8_t *)page, lun->ua_tpt_info);
13648				if (lun->lasttpt == 0 ||
13649				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13650					lun->lasttpt = time_uptime;
13651					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13652					set = 1;
13653				} else
13654					set = 0;
13655			} else {
13656				lun->lasttpt = 0;
13657				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13658				set = -1;
13659			}
13660			mtx_unlock(&lun->lun_lock);
13661			if (set != 0 &&
13662			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13663				/* Send msg to other side. */
13664				bzero(&msg.ua, sizeof(msg.ua));
13665				msg.hdr.msg_type = CTL_MSG_UA;
13666				msg.hdr.nexus.initid = -1;
13667				msg.hdr.nexus.targ_port = -1;
13668				msg.hdr.nexus.targ_lun = lun->lun;
13669				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13670				msg.ua.ua_all = 1;
13671				msg.ua.ua_set = (set > 0);
13672				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13673				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13674				mtx_unlock(&softc->ctl_lock); // XXX
13675				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13676				    sizeof(msg.ua), M_WAITOK);
13677				mtx_lock(&softc->ctl_lock);
13678			}
13679		}
13680		mtx_unlock(&softc->ctl_lock);
13681		pause("-", CTL_LBP_PERIOD * hz);
13682	}
13683}
13684
13685static void
13686ctl_enqueue_incoming(union ctl_io *io)
13687{
13688	struct ctl_softc *softc = control_softc;
13689	struct ctl_thread *thr;
13690	u_int idx;
13691
13692	idx = (io->io_hdr.nexus.targ_port * 127 +
13693	       io->io_hdr.nexus.initid) % worker_threads;
13694	thr = &softc->threads[idx];
13695	mtx_lock(&thr->queue_lock);
13696	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13697	mtx_unlock(&thr->queue_lock);
13698	wakeup(thr);
13699}
13700
13701static void
13702ctl_enqueue_rtr(union ctl_io *io)
13703{
13704	struct ctl_softc *softc = control_softc;
13705	struct ctl_thread *thr;
13706
13707	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13708	mtx_lock(&thr->queue_lock);
13709	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13710	mtx_unlock(&thr->queue_lock);
13711	wakeup(thr);
13712}
13713
13714static void
13715ctl_enqueue_done(union ctl_io *io)
13716{
13717	struct ctl_softc *softc = control_softc;
13718	struct ctl_thread *thr;
13719
13720	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13721	mtx_lock(&thr->queue_lock);
13722	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13723	mtx_unlock(&thr->queue_lock);
13724	wakeup(thr);
13725}
13726
13727static void
13728ctl_enqueue_isc(union ctl_io *io)
13729{
13730	struct ctl_softc *softc = control_softc;
13731	struct ctl_thread *thr;
13732
13733	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13734	mtx_lock(&thr->queue_lock);
13735	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13736	mtx_unlock(&thr->queue_lock);
13737	wakeup(thr);
13738}
13739
13740/*
13741 *  vim: ts=8
13742 */
13743