ctl.c revision 317988
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * Copyright (c) 2014-2017 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 317988 2017-05-08 22:24:06Z 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");
410static int ctl_lun_map_size = 1024;
411SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
412    &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
413
414/*
415 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
416 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
417 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
418 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
419 */
420#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
421
422static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
423				  int param);
424static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
425static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
426static int ctl_init(void);
427static int ctl_shutdown(void);
428static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
429static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
430static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
431static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
432			      struct ctl_ooa *ooa_hdr,
433			      struct ctl_ooa_entry *kern_entries);
434static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
435		     struct thread *td);
436static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
437			 struct ctl_be_lun *be_lun);
438static int ctl_free_lun(struct ctl_lun *lun);
439static void ctl_create_lun(struct ctl_be_lun *be_lun);
440
441static int ctl_do_mode_select(union ctl_io *io);
442static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443			   uint64_t res_key, uint64_t sa_res_key,
444			   uint8_t type, uint32_t residx,
445			   struct ctl_scsiio *ctsio,
446			   struct scsi_per_res_out *cdb,
447			   struct scsi_per_res_out_parms* param);
448static void ctl_pro_preempt_other(struct ctl_lun *lun,
449				  union ctl_ha_msg *msg);
450static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
451static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457					 int alloc_len);
458static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459					 int alloc_len);
460static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466    bool seq);
467static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469    union ctl_io *pending_io, union ctl_io *ooa_io);
470static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471				union ctl_io *starting_io);
472static int ctl_check_blocked(struct ctl_lun *lun);
473static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474				const struct ctl_cmd_entry *entry,
475				struct ctl_scsiio *ctsio);
476static void ctl_failover_lun(union ctl_io *io);
477static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478			       struct ctl_scsiio *ctsio);
479static int ctl_scsiio(struct ctl_scsiio *ctsio);
480
481static int ctl_target_reset(union ctl_io *io);
482static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
483			 ctl_ua_type ua_type);
484static int ctl_lun_reset(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 void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
489			      ctl_ua_type ua_type);
490static int ctl_i_t_nexus_reset(union ctl_io *io);
491static int ctl_query_async_event(union ctl_io *io);
492static void ctl_run_task(union ctl_io *io);
493#ifdef CTL_IO_DELAY
494static void ctl_datamove_timer_wakeup(void *arg);
495static void ctl_done_timer_wakeup(void *arg);
496#endif /* CTL_IO_DELAY */
497
498static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501static void ctl_datamove_remote_write(union ctl_io *io);
502static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506				    ctl_ha_dt_cb callback);
507static void ctl_datamove_remote_read(union ctl_io *io);
508static void ctl_datamove_remote(union ctl_io *io);
509static void ctl_process_done(union ctl_io *io);
510static void ctl_lun_thread(void *arg);
511static void ctl_thresh_thread(void *arg);
512static void ctl_work_thread(void *arg);
513static void ctl_enqueue_incoming(union ctl_io *io);
514static void ctl_enqueue_rtr(union ctl_io *io);
515static void ctl_enqueue_done(union ctl_io *io);
516static void ctl_enqueue_isc(union ctl_io *io);
517static const struct ctl_cmd_entry *
518    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519static const struct ctl_cmd_entry *
520    ctl_validate_command(struct ctl_scsiio *ctsio);
521static int ctl_cmd_applicable(uint8_t lun_type,
522    const struct ctl_cmd_entry *entry);
523static int ctl_ha_init(void);
524static int ctl_ha_shutdown(void);
525
526static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
527static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
528static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
529static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
530
531/*
532 * Load the serialization table.  This isn't very pretty, but is probably
533 * the easiest way to do it.
534 */
535#include "ctl_ser_table.c"
536
537/*
538 * We only need to define open, close and ioctl routines for this driver.
539 */
540static struct cdevsw ctl_cdevsw = {
541	.d_version =	D_VERSION,
542	.d_flags =	0,
543	.d_open =	ctl_open,
544	.d_close =	ctl_close,
545	.d_ioctl =	ctl_ioctl,
546	.d_name =	"ctl",
547};
548
549
550MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
551
552static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
553
554static moduledata_t ctl_moduledata = {
555	"ctl",
556	ctl_module_event_handler,
557	NULL
558};
559
560DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
561MODULE_VERSION(ctl, 1);
562
563static struct ctl_frontend ha_frontend =
564{
565	.name = "ha",
566	.init = ctl_ha_init,
567	.shutdown = ctl_ha_shutdown,
568};
569
570static int
571ctl_ha_init(void)
572{
573	struct ctl_softc *softc = control_softc;
574
575	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
576	                    &softc->othersc_pool) != 0)
577		return (ENOMEM);
578	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
579		ctl_pool_free(softc->othersc_pool);
580		return (EIO);
581	}
582	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
583	    != CTL_HA_STATUS_SUCCESS) {
584		ctl_ha_msg_destroy(softc);
585		ctl_pool_free(softc->othersc_pool);
586		return (EIO);
587	}
588	return (0);
589};
590
591static int
592ctl_ha_shutdown(void)
593{
594	struct ctl_softc *softc = control_softc;
595	struct ctl_port *port;
596
597	ctl_ha_msg_shutdown(softc);
598	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
599		return (EIO);
600	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
601		return (EIO);
602	ctl_pool_free(softc->othersc_pool);
603	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
604		ctl_port_deregister(port);
605		free(port->port_name, M_CTL);
606		free(port, M_CTL);
607	}
608	return (0);
609};
610
611static void
612ctl_ha_datamove(union ctl_io *io)
613{
614	struct ctl_lun *lun = CTL_LUN(io);
615	struct ctl_sg_entry *sgl;
616	union ctl_ha_msg msg;
617	uint32_t sg_entries_sent;
618	int do_sg_copy, i, j;
619
620	memset(&msg.dt, 0, sizeof(msg.dt));
621	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
622	msg.hdr.original_sc = io->io_hdr.original_sc;
623	msg.hdr.serializing_sc = io;
624	msg.hdr.nexus = io->io_hdr.nexus;
625	msg.hdr.status = io->io_hdr.status;
626	msg.dt.flags = io->io_hdr.flags;
627
628	/*
629	 * We convert everything into a S/G list here.  We can't
630	 * pass by reference, only by value between controllers.
631	 * So we can't pass a pointer to the S/G list, only as many
632	 * S/G entries as we can fit in here.  If it's possible for
633	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
634	 * then we need to break this up into multiple transfers.
635	 */
636	if (io->scsiio.kern_sg_entries == 0) {
637		msg.dt.kern_sg_entries = 1;
638#if 0
639		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
640			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
641		} else {
642			/* XXX KDM use busdma here! */
643			msg.dt.sg_list[0].addr =
644			    (void *)vtophys(io->scsiio.kern_data_ptr);
645		}
646#else
647		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
648		    ("HA does not support BUS_ADDR"));
649		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
650#endif
651		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
652		do_sg_copy = 0;
653	} else {
654		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
655		do_sg_copy = 1;
656	}
657
658	msg.dt.kern_data_len = io->scsiio.kern_data_len;
659	msg.dt.kern_total_len = io->scsiio.kern_total_len;
660	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
661	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
662	msg.dt.sg_sequence = 0;
663
664	/*
665	 * Loop until we've sent all of the S/G entries.  On the
666	 * other end, we'll recompose these S/G entries into one
667	 * contiguous list before processing.
668	 */
669	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
670	    msg.dt.sg_sequence++) {
671		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
672		    sizeof(msg.dt.sg_list[0])),
673		    msg.dt.kern_sg_entries - sg_entries_sent);
674		if (do_sg_copy != 0) {
675			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
676			for (i = sg_entries_sent, j = 0;
677			     i < msg.dt.cur_sg_entries; i++, j++) {
678#if 0
679				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
680					msg.dt.sg_list[j].addr = sgl[i].addr;
681				} else {
682					/* XXX KDM use busdma here! */
683					msg.dt.sg_list[j].addr =
684					    (void *)vtophys(sgl[i].addr);
685				}
686#else
687				KASSERT((io->io_hdr.flags &
688				    CTL_FLAG_BUS_ADDR) == 0,
689				    ("HA does not support BUS_ADDR"));
690				msg.dt.sg_list[j].addr = sgl[i].addr;
691#endif
692				msg.dt.sg_list[j].len = sgl[i].len;
693			}
694		}
695
696		sg_entries_sent += msg.dt.cur_sg_entries;
697		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
698		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
699		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
700		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
701		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
702			io->io_hdr.port_status = 31341;
703			io->scsiio.be_move_done(io);
704			return;
705		}
706		msg.dt.sent_sg_entries = sg_entries_sent;
707	}
708
709	/*
710	 * Officially handover the request from us to peer.
711	 * If failover has just happened, then we must return error.
712	 * If failover happen just after, then it is not our problem.
713	 */
714	if (lun)
715		mtx_lock(&lun->lun_lock);
716	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
717		if (lun)
718			mtx_unlock(&lun->lun_lock);
719		io->io_hdr.port_status = 31342;
720		io->scsiio.be_move_done(io);
721		return;
722	}
723	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
724	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
725	if (lun)
726		mtx_unlock(&lun->lun_lock);
727}
728
729static void
730ctl_ha_done(union ctl_io *io)
731{
732	union ctl_ha_msg msg;
733
734	if (io->io_hdr.io_type == CTL_IO_SCSI) {
735		memset(&msg, 0, sizeof(msg));
736		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
737		msg.hdr.original_sc = io->io_hdr.original_sc;
738		msg.hdr.nexus = io->io_hdr.nexus;
739		msg.hdr.status = io->io_hdr.status;
740		msg.scsi.scsi_status = io->scsiio.scsi_status;
741		msg.scsi.tag_num = io->scsiio.tag_num;
742		msg.scsi.tag_type = io->scsiio.tag_type;
743		msg.scsi.sense_len = io->scsiio.sense_len;
744		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
745		    io->scsiio.sense_len);
746		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
747		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
748		    msg.scsi.sense_len, M_WAITOK);
749	}
750	ctl_free_io(io);
751}
752
753static void
754ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
755			    union ctl_ha_msg *msg_info)
756{
757	struct ctl_scsiio *ctsio;
758
759	if (msg_info->hdr.original_sc == NULL) {
760		printf("%s: original_sc == NULL!\n", __func__);
761		/* XXX KDM now what? */
762		return;
763	}
764
765	ctsio = &msg_info->hdr.original_sc->scsiio;
766	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
767	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
768	ctsio->io_hdr.status = msg_info->hdr.status;
769	ctsio->scsi_status = msg_info->scsi.scsi_status;
770	ctsio->sense_len = msg_info->scsi.sense_len;
771	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
772	       msg_info->scsi.sense_len);
773	ctl_enqueue_isc((union ctl_io *)ctsio);
774}
775
776static void
777ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
778				union ctl_ha_msg *msg_info)
779{
780	struct ctl_scsiio *ctsio;
781
782	if (msg_info->hdr.serializing_sc == NULL) {
783		printf("%s: serializing_sc == NULL!\n", __func__);
784		/* XXX KDM now what? */
785		return;
786	}
787
788	ctsio = &msg_info->hdr.serializing_sc->scsiio;
789	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
790	ctl_enqueue_isc((union ctl_io *)ctsio);
791}
792
793void
794ctl_isc_announce_lun(struct ctl_lun *lun)
795{
796	struct ctl_softc *softc = lun->ctl_softc;
797	union ctl_ha_msg *msg;
798	struct ctl_ha_msg_lun_pr_key pr_key;
799	int i, k;
800
801	if (softc->ha_link != CTL_HA_LINK_ONLINE)
802		return;
803	mtx_lock(&lun->lun_lock);
804	i = sizeof(msg->lun);
805	if (lun->lun_devid)
806		i += lun->lun_devid->len;
807	i += sizeof(pr_key) * lun->pr_key_count;
808alloc:
809	mtx_unlock(&lun->lun_lock);
810	msg = malloc(i, M_CTL, M_WAITOK);
811	mtx_lock(&lun->lun_lock);
812	k = sizeof(msg->lun);
813	if (lun->lun_devid)
814		k += lun->lun_devid->len;
815	k += sizeof(pr_key) * lun->pr_key_count;
816	if (i < k) {
817		free(msg, M_CTL);
818		i = k;
819		goto alloc;
820	}
821	bzero(&msg->lun, sizeof(msg->lun));
822	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
823	msg->hdr.nexus.targ_lun = lun->lun;
824	msg->hdr.nexus.targ_mapped_lun = lun->lun;
825	msg->lun.flags = lun->flags;
826	msg->lun.pr_generation = lun->pr_generation;
827	msg->lun.pr_res_idx = lun->pr_res_idx;
828	msg->lun.pr_res_type = lun->pr_res_type;
829	msg->lun.pr_key_count = lun->pr_key_count;
830	i = 0;
831	if (lun->lun_devid) {
832		msg->lun.lun_devid_len = lun->lun_devid->len;
833		memcpy(&msg->lun.data[i], lun->lun_devid->data,
834		    msg->lun.lun_devid_len);
835		i += msg->lun.lun_devid_len;
836	}
837	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
838		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
839			continue;
840		pr_key.pr_iid = k;
841		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
842		i += sizeof(pr_key);
843	}
844	mtx_unlock(&lun->lun_lock);
845	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
846	    M_WAITOK);
847	free(msg, M_CTL);
848
849	if (lun->flags & CTL_LUN_PRIMARY_SC) {
850		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
851			ctl_isc_announce_mode(lun, -1,
852			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
853			    lun->mode_pages.index[i].subpage);
854		}
855	}
856}
857
858void
859ctl_isc_announce_port(struct ctl_port *port)
860{
861	struct ctl_softc *softc = port->ctl_softc;
862	union ctl_ha_msg *msg;
863	int i;
864
865	if (port->targ_port < softc->port_min ||
866	    port->targ_port >= softc->port_max ||
867	    softc->ha_link != CTL_HA_LINK_ONLINE)
868		return;
869	i = sizeof(msg->port) + strlen(port->port_name) + 1;
870	if (port->lun_map)
871		i += port->lun_map_size * sizeof(uint32_t);
872	if (port->port_devid)
873		i += port->port_devid->len;
874	if (port->target_devid)
875		i += port->target_devid->len;
876	if (port->init_devid)
877		i += port->init_devid->len;
878	msg = malloc(i, M_CTL, M_WAITOK);
879	bzero(&msg->port, sizeof(msg->port));
880	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
881	msg->hdr.nexus.targ_port = port->targ_port;
882	msg->port.port_type = port->port_type;
883	msg->port.physical_port = port->physical_port;
884	msg->port.virtual_port = port->virtual_port;
885	msg->port.status = port->status;
886	i = 0;
887	msg->port.name_len = sprintf(&msg->port.data[i],
888	    "%d:%s", softc->ha_id, port->port_name) + 1;
889	i += msg->port.name_len;
890	if (port->lun_map) {
891		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
892		memcpy(&msg->port.data[i], port->lun_map,
893		    msg->port.lun_map_len);
894		i += msg->port.lun_map_len;
895	}
896	if (port->port_devid) {
897		msg->port.port_devid_len = port->port_devid->len;
898		memcpy(&msg->port.data[i], port->port_devid->data,
899		    msg->port.port_devid_len);
900		i += msg->port.port_devid_len;
901	}
902	if (port->target_devid) {
903		msg->port.target_devid_len = port->target_devid->len;
904		memcpy(&msg->port.data[i], port->target_devid->data,
905		    msg->port.target_devid_len);
906		i += msg->port.target_devid_len;
907	}
908	if (port->init_devid) {
909		msg->port.init_devid_len = port->init_devid->len;
910		memcpy(&msg->port.data[i], port->init_devid->data,
911		    msg->port.init_devid_len);
912		i += msg->port.init_devid_len;
913	}
914	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
915	    M_WAITOK);
916	free(msg, M_CTL);
917}
918
919void
920ctl_isc_announce_iid(struct ctl_port *port, int iid)
921{
922	struct ctl_softc *softc = port->ctl_softc;
923	union ctl_ha_msg *msg;
924	int i, l;
925
926	if (port->targ_port < softc->port_min ||
927	    port->targ_port >= softc->port_max ||
928	    softc->ha_link != CTL_HA_LINK_ONLINE)
929		return;
930	mtx_lock(&softc->ctl_lock);
931	i = sizeof(msg->iid);
932	l = 0;
933	if (port->wwpn_iid[iid].name)
934		l = strlen(port->wwpn_iid[iid].name) + 1;
935	i += l;
936	msg = malloc(i, M_CTL, M_NOWAIT);
937	if (msg == NULL) {
938		mtx_unlock(&softc->ctl_lock);
939		return;
940	}
941	bzero(&msg->iid, sizeof(msg->iid));
942	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
943	msg->hdr.nexus.targ_port = port->targ_port;
944	msg->hdr.nexus.initid = iid;
945	msg->iid.in_use = port->wwpn_iid[iid].in_use;
946	msg->iid.name_len = l;
947	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
948	if (port->wwpn_iid[iid].name)
949		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
950	mtx_unlock(&softc->ctl_lock);
951	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
952	free(msg, M_CTL);
953}
954
955void
956ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
957    uint8_t page, uint8_t subpage)
958{
959	struct ctl_softc *softc = lun->ctl_softc;
960	union ctl_ha_msg msg;
961	u_int i;
962
963	if (softc->ha_link != CTL_HA_LINK_ONLINE)
964		return;
965	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
966		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
967		    page && lun->mode_pages.index[i].subpage == subpage)
968			break;
969	}
970	if (i == CTL_NUM_MODE_PAGES)
971		return;
972
973	/* Don't try to replicate pages not present on this device. */
974	if (lun->mode_pages.index[i].page_data == NULL)
975		return;
976
977	bzero(&msg.mode, sizeof(msg.mode));
978	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
979	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
980	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
981	msg.hdr.nexus.targ_lun = lun->lun;
982	msg.hdr.nexus.targ_mapped_lun = lun->lun;
983	msg.mode.page_code = page;
984	msg.mode.subpage = subpage;
985	msg.mode.page_len = lun->mode_pages.index[i].page_len;
986	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
987	    msg.mode.page_len);
988	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
989	    M_WAITOK);
990}
991
992static void
993ctl_isc_ha_link_up(struct ctl_softc *softc)
994{
995	struct ctl_port *port;
996	struct ctl_lun *lun;
997	union ctl_ha_msg msg;
998	int i;
999
1000	/* Announce this node parameters to peer for validation. */
1001	msg.login.msg_type = CTL_MSG_LOGIN;
1002	msg.login.version = CTL_HA_VERSION;
1003	msg.login.ha_mode = softc->ha_mode;
1004	msg.login.ha_id = softc->ha_id;
1005	msg.login.max_luns = CTL_MAX_LUNS;
1006	msg.login.max_ports = CTL_MAX_PORTS;
1007	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1008	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1009	    M_WAITOK);
1010
1011	STAILQ_FOREACH(port, &softc->port_list, links) {
1012		ctl_isc_announce_port(port);
1013		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1014			if (port->wwpn_iid[i].in_use)
1015				ctl_isc_announce_iid(port, i);
1016		}
1017	}
1018	STAILQ_FOREACH(lun, &softc->lun_list, links)
1019		ctl_isc_announce_lun(lun);
1020}
1021
1022static void
1023ctl_isc_ha_link_down(struct ctl_softc *softc)
1024{
1025	struct ctl_port *port;
1026	struct ctl_lun *lun;
1027	union ctl_io *io;
1028	int i;
1029
1030	mtx_lock(&softc->ctl_lock);
1031	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1032		mtx_lock(&lun->lun_lock);
1033		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1034			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1035			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1036		}
1037		mtx_unlock(&lun->lun_lock);
1038
1039		mtx_unlock(&softc->ctl_lock);
1040		io = ctl_alloc_io(softc->othersc_pool);
1041		mtx_lock(&softc->ctl_lock);
1042		ctl_zero_io(io);
1043		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1044		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1045		ctl_enqueue_isc(io);
1046	}
1047
1048	STAILQ_FOREACH(port, &softc->port_list, links) {
1049		if (port->targ_port >= softc->port_min &&
1050		    port->targ_port < softc->port_max)
1051			continue;
1052		port->status &= ~CTL_PORT_STATUS_ONLINE;
1053		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1054			port->wwpn_iid[i].in_use = 0;
1055			free(port->wwpn_iid[i].name, M_CTL);
1056			port->wwpn_iid[i].name = NULL;
1057		}
1058	}
1059	mtx_unlock(&softc->ctl_lock);
1060}
1061
1062static void
1063ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1064{
1065	struct ctl_lun *lun;
1066	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1067
1068	mtx_lock(&softc->ctl_lock);
1069	if (msg->hdr.nexus.targ_mapped_lun >= CTL_MAX_LUNS ||
1070	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1071		mtx_unlock(&softc->ctl_lock);
1072		return;
1073	}
1074	mtx_lock(&lun->lun_lock);
1075	mtx_unlock(&softc->ctl_lock);
1076	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1077		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1078	if (msg->ua.ua_all) {
1079		if (msg->ua.ua_set)
1080			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1081		else
1082			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1083	} else {
1084		if (msg->ua.ua_set)
1085			ctl_est_ua(lun, iid, msg->ua.ua_type);
1086		else
1087			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1088	}
1089	mtx_unlock(&lun->lun_lock);
1090}
1091
1092static void
1093ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1094{
1095	struct ctl_lun *lun;
1096	struct ctl_ha_msg_lun_pr_key pr_key;
1097	int i, k;
1098	ctl_lun_flags oflags;
1099	uint32_t targ_lun;
1100
1101	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1102	mtx_lock(&softc->ctl_lock);
1103	if (targ_lun >= CTL_MAX_LUNS ||
1104	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1105		mtx_unlock(&softc->ctl_lock);
1106		return;
1107	}
1108	mtx_lock(&lun->lun_lock);
1109	mtx_unlock(&softc->ctl_lock);
1110	if (lun->flags & CTL_LUN_DISABLED) {
1111		mtx_unlock(&lun->lun_lock);
1112		return;
1113	}
1114	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1115	if (msg->lun.lun_devid_len != i || (i > 0 &&
1116	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1117		mtx_unlock(&lun->lun_lock);
1118		printf("%s: Received conflicting HA LUN %d\n",
1119		    __func__, targ_lun);
1120		return;
1121	} else {
1122		/* Record whether peer is primary. */
1123		oflags = lun->flags;
1124		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1125		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1126			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1127		else
1128			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1129		if (oflags != lun->flags)
1130			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1131
1132		/* If peer is primary and we are not -- use data */
1133		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1134		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1135			lun->pr_generation = msg->lun.pr_generation;
1136			lun->pr_res_idx = msg->lun.pr_res_idx;
1137			lun->pr_res_type = msg->lun.pr_res_type;
1138			lun->pr_key_count = msg->lun.pr_key_count;
1139			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1140				ctl_clr_prkey(lun, k);
1141			for (k = 0; k < msg->lun.pr_key_count; k++) {
1142				memcpy(&pr_key, &msg->lun.data[i],
1143				    sizeof(pr_key));
1144				ctl_alloc_prkey(lun, pr_key.pr_iid);
1145				ctl_set_prkey(lun, pr_key.pr_iid,
1146				    pr_key.pr_key);
1147				i += sizeof(pr_key);
1148			}
1149		}
1150
1151		mtx_unlock(&lun->lun_lock);
1152		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1153		    __func__, targ_lun,
1154		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1155		    "primary" : "secondary"));
1156
1157		/* If we are primary but peer doesn't know -- notify */
1158		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1159		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1160			ctl_isc_announce_lun(lun);
1161	}
1162}
1163
1164static void
1165ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1166{
1167	struct ctl_port *port;
1168	struct ctl_lun *lun;
1169	int i, new;
1170
1171	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1172	if (port == NULL) {
1173		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1174		    msg->hdr.nexus.targ_port));
1175		new = 1;
1176		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1177		port->frontend = &ha_frontend;
1178		port->targ_port = msg->hdr.nexus.targ_port;
1179		port->fe_datamove = ctl_ha_datamove;
1180		port->fe_done = ctl_ha_done;
1181	} else if (port->frontend == &ha_frontend) {
1182		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1183		    msg->hdr.nexus.targ_port));
1184		new = 0;
1185	} else {
1186		printf("%s: Received conflicting HA port %d\n",
1187		    __func__, msg->hdr.nexus.targ_port);
1188		return;
1189	}
1190	port->port_type = msg->port.port_type;
1191	port->physical_port = msg->port.physical_port;
1192	port->virtual_port = msg->port.virtual_port;
1193	port->status = msg->port.status;
1194	i = 0;
1195	free(port->port_name, M_CTL);
1196	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1197	    M_CTL);
1198	i += msg->port.name_len;
1199	if (msg->port.lun_map_len != 0) {
1200		if (port->lun_map == NULL ||
1201		    port->lun_map_size * sizeof(uint32_t) <
1202		    msg->port.lun_map_len) {
1203			port->lun_map_size = 0;
1204			free(port->lun_map, M_CTL);
1205			port->lun_map = malloc(msg->port.lun_map_len,
1206			    M_CTL, M_WAITOK);
1207		}
1208		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1209		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1210		i += msg->port.lun_map_len;
1211	} else {
1212		port->lun_map_size = 0;
1213		free(port->lun_map, M_CTL);
1214		port->lun_map = NULL;
1215	}
1216	if (msg->port.port_devid_len != 0) {
1217		if (port->port_devid == NULL ||
1218		    port->port_devid->len < msg->port.port_devid_len) {
1219			free(port->port_devid, M_CTL);
1220			port->port_devid = malloc(sizeof(struct ctl_devid) +
1221			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1222		}
1223		memcpy(port->port_devid->data, &msg->port.data[i],
1224		    msg->port.port_devid_len);
1225		port->port_devid->len = msg->port.port_devid_len;
1226		i += msg->port.port_devid_len;
1227	} else {
1228		free(port->port_devid, M_CTL);
1229		port->port_devid = NULL;
1230	}
1231	if (msg->port.target_devid_len != 0) {
1232		if (port->target_devid == NULL ||
1233		    port->target_devid->len < msg->port.target_devid_len) {
1234			free(port->target_devid, M_CTL);
1235			port->target_devid = malloc(sizeof(struct ctl_devid) +
1236			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1237		}
1238		memcpy(port->target_devid->data, &msg->port.data[i],
1239		    msg->port.target_devid_len);
1240		port->target_devid->len = msg->port.target_devid_len;
1241		i += msg->port.target_devid_len;
1242	} else {
1243		free(port->target_devid, M_CTL);
1244		port->target_devid = NULL;
1245	}
1246	if (msg->port.init_devid_len != 0) {
1247		if (port->init_devid == NULL ||
1248		    port->init_devid->len < msg->port.init_devid_len) {
1249			free(port->init_devid, M_CTL);
1250			port->init_devid = malloc(sizeof(struct ctl_devid) +
1251			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1252		}
1253		memcpy(port->init_devid->data, &msg->port.data[i],
1254		    msg->port.init_devid_len);
1255		port->init_devid->len = msg->port.init_devid_len;
1256		i += msg->port.init_devid_len;
1257	} else {
1258		free(port->init_devid, M_CTL);
1259		port->init_devid = NULL;
1260	}
1261	if (new) {
1262		if (ctl_port_register(port) != 0) {
1263			printf("%s: ctl_port_register() failed with error\n",
1264			    __func__);
1265		}
1266	}
1267	mtx_lock(&softc->ctl_lock);
1268	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1269		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1270			continue;
1271		mtx_lock(&lun->lun_lock);
1272		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1273		mtx_unlock(&lun->lun_lock);
1274	}
1275	mtx_unlock(&softc->ctl_lock);
1276}
1277
1278static void
1279ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1280{
1281	struct ctl_port *port;
1282	int iid;
1283
1284	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1285	if (port == NULL) {
1286		printf("%s: Received IID for unknown port %d\n",
1287		    __func__, msg->hdr.nexus.targ_port);
1288		return;
1289	}
1290	iid = msg->hdr.nexus.initid;
1291	if (port->wwpn_iid[iid].in_use != 0 &&
1292	    msg->iid.in_use == 0)
1293		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1294	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1295	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1296	free(port->wwpn_iid[iid].name, M_CTL);
1297	if (msg->iid.name_len) {
1298		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1299		    msg->iid.name_len, M_CTL);
1300	} else
1301		port->wwpn_iid[iid].name = NULL;
1302}
1303
1304static void
1305ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1306{
1307
1308	if (msg->login.version != CTL_HA_VERSION) {
1309		printf("CTL HA peers have different versions %d != %d\n",
1310		    msg->login.version, CTL_HA_VERSION);
1311		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1312		return;
1313	}
1314	if (msg->login.ha_mode != softc->ha_mode) {
1315		printf("CTL HA peers have different ha_mode %d != %d\n",
1316		    msg->login.ha_mode, softc->ha_mode);
1317		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1318		return;
1319	}
1320	if (msg->login.ha_id == softc->ha_id) {
1321		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1322		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1323		return;
1324	}
1325	if (msg->login.max_luns != CTL_MAX_LUNS ||
1326	    msg->login.max_ports != CTL_MAX_PORTS ||
1327	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1328		printf("CTL HA peers have different limits\n");
1329		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1330		return;
1331	}
1332}
1333
1334static void
1335ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1336{
1337	struct ctl_lun *lun;
1338	u_int i;
1339	uint32_t initidx, targ_lun;
1340
1341	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1342	mtx_lock(&softc->ctl_lock);
1343	if (targ_lun >= CTL_MAX_LUNS ||
1344	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1345		mtx_unlock(&softc->ctl_lock);
1346		return;
1347	}
1348	mtx_lock(&lun->lun_lock);
1349	mtx_unlock(&softc->ctl_lock);
1350	if (lun->flags & CTL_LUN_DISABLED) {
1351		mtx_unlock(&lun->lun_lock);
1352		return;
1353	}
1354	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1355		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1356		    msg->mode.page_code &&
1357		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1358			break;
1359	}
1360	if (i == CTL_NUM_MODE_PAGES) {
1361		mtx_unlock(&lun->lun_lock);
1362		return;
1363	}
1364	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1365	    lun->mode_pages.index[i].page_len);
1366	initidx = ctl_get_initindex(&msg->hdr.nexus);
1367	if (initidx != -1)
1368		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1369	mtx_unlock(&lun->lun_lock);
1370}
1371
1372/*
1373 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1374 * subsystem come in here.
1375 */
1376static void
1377ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1378{
1379	struct ctl_softc *softc = control_softc;
1380	union ctl_io *io;
1381	struct ctl_prio *presio;
1382	ctl_ha_status isc_status;
1383
1384	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1385	if (event == CTL_HA_EVT_MSG_RECV) {
1386		union ctl_ha_msg *msg, msgbuf;
1387
1388		if (param > sizeof(msgbuf))
1389			msg = malloc(param, M_CTL, M_WAITOK);
1390		else
1391			msg = &msgbuf;
1392		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1393		    M_WAITOK);
1394		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1395			printf("%s: Error receiving message: %d\n",
1396			    __func__, isc_status);
1397			if (msg != &msgbuf)
1398				free(msg, M_CTL);
1399			return;
1400		}
1401
1402		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1403		switch (msg->hdr.msg_type) {
1404		case CTL_MSG_SERIALIZE:
1405			io = ctl_alloc_io(softc->othersc_pool);
1406			ctl_zero_io(io);
1407			// populate ctsio from msg
1408			io->io_hdr.io_type = CTL_IO_SCSI;
1409			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1410			io->io_hdr.original_sc = msg->hdr.original_sc;
1411			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1412					    CTL_FLAG_IO_ACTIVE;
1413			/*
1414			 * If we're in serialization-only mode, we don't
1415			 * want to go through full done processing.  Thus
1416			 * the COPY flag.
1417			 *
1418			 * XXX KDM add another flag that is more specific.
1419			 */
1420			if (softc->ha_mode != CTL_HA_MODE_XFER)
1421				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1422			io->io_hdr.nexus = msg->hdr.nexus;
1423#if 0
1424			printf("port %u, iid %u, lun %u\n",
1425			       io->io_hdr.nexus.targ_port,
1426			       io->io_hdr.nexus.initid,
1427			       io->io_hdr.nexus.targ_lun);
1428#endif
1429			io->scsiio.tag_num = msg->scsi.tag_num;
1430			io->scsiio.tag_type = msg->scsi.tag_type;
1431#ifdef CTL_TIME_IO
1432			io->io_hdr.start_time = time_uptime;
1433			getbinuptime(&io->io_hdr.start_bt);
1434#endif /* CTL_TIME_IO */
1435			io->scsiio.cdb_len = msg->scsi.cdb_len;
1436			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1437			       CTL_MAX_CDBLEN);
1438			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1439				const struct ctl_cmd_entry *entry;
1440
1441				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1442				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1443				io->io_hdr.flags |=
1444					entry->flags & CTL_FLAG_DATA_MASK;
1445			}
1446			ctl_enqueue_isc(io);
1447			break;
1448
1449		/* Performed on the Originating SC, XFER mode only */
1450		case CTL_MSG_DATAMOVE: {
1451			struct ctl_sg_entry *sgl;
1452			int i, j;
1453
1454			io = msg->hdr.original_sc;
1455			if (io == NULL) {
1456				printf("%s: original_sc == NULL!\n", __func__);
1457				/* XXX KDM do something here */
1458				break;
1459			}
1460			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1461			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1462			/*
1463			 * Keep track of this, we need to send it back over
1464			 * when the datamove is complete.
1465			 */
1466			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1467			if (msg->hdr.status == CTL_SUCCESS)
1468				io->io_hdr.status = msg->hdr.status;
1469
1470			if (msg->dt.sg_sequence == 0) {
1471#ifdef CTL_TIME_IO
1472				getbinuptime(&io->io_hdr.dma_start_bt);
1473#endif
1474				i = msg->dt.kern_sg_entries +
1475				    msg->dt.kern_data_len /
1476				    CTL_HA_DATAMOVE_SEGMENT + 1;
1477				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1478				    M_WAITOK | M_ZERO);
1479				io->io_hdr.remote_sglist = sgl;
1480				io->io_hdr.local_sglist =
1481				    &sgl[msg->dt.kern_sg_entries];
1482
1483				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1484
1485				io->scsiio.kern_sg_entries =
1486					msg->dt.kern_sg_entries;
1487				io->scsiio.rem_sg_entries =
1488					msg->dt.kern_sg_entries;
1489				io->scsiio.kern_data_len =
1490					msg->dt.kern_data_len;
1491				io->scsiio.kern_total_len =
1492					msg->dt.kern_total_len;
1493				io->scsiio.kern_data_resid =
1494					msg->dt.kern_data_resid;
1495				io->scsiio.kern_rel_offset =
1496					msg->dt.kern_rel_offset;
1497				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1498				io->io_hdr.flags |= msg->dt.flags &
1499				    CTL_FLAG_BUS_ADDR;
1500			} else
1501				sgl = (struct ctl_sg_entry *)
1502					io->scsiio.kern_data_ptr;
1503
1504			for (i = msg->dt.sent_sg_entries, j = 0;
1505			     i < (msg->dt.sent_sg_entries +
1506			     msg->dt.cur_sg_entries); i++, j++) {
1507				sgl[i].addr = msg->dt.sg_list[j].addr;
1508				sgl[i].len = msg->dt.sg_list[j].len;
1509
1510#if 0
1511				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1512				    __func__, sgl[i].addr, sgl[i].len, j, i);
1513#endif
1514			}
1515
1516			/*
1517			 * If this is the last piece of the I/O, we've got
1518			 * the full S/G list.  Queue processing in the thread.
1519			 * Otherwise wait for the next piece.
1520			 */
1521			if (msg->dt.sg_last != 0)
1522				ctl_enqueue_isc(io);
1523			break;
1524		}
1525		/* Performed on the Serializing (primary) SC, XFER mode only */
1526		case CTL_MSG_DATAMOVE_DONE: {
1527			if (msg->hdr.serializing_sc == NULL) {
1528				printf("%s: serializing_sc == NULL!\n",
1529				       __func__);
1530				/* XXX KDM now what? */
1531				break;
1532			}
1533			/*
1534			 * We grab the sense information here in case
1535			 * there was a failure, so we can return status
1536			 * back to the initiator.
1537			 */
1538			io = msg->hdr.serializing_sc;
1539			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1540			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1541			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1542			io->io_hdr.port_status = msg->scsi.port_status;
1543			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1544			if (msg->hdr.status != CTL_STATUS_NONE) {
1545				io->io_hdr.status = msg->hdr.status;
1546				io->scsiio.scsi_status = msg->scsi.scsi_status;
1547				io->scsiio.sense_len = msg->scsi.sense_len;
1548				memcpy(&io->scsiio.sense_data,
1549				    &msg->scsi.sense_data,
1550				    msg->scsi.sense_len);
1551				if (msg->hdr.status == CTL_SUCCESS)
1552					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1553			}
1554			ctl_enqueue_isc(io);
1555			break;
1556		}
1557
1558		/* Preformed on Originating SC, SER_ONLY mode */
1559		case CTL_MSG_R2R:
1560			io = msg->hdr.original_sc;
1561			if (io == NULL) {
1562				printf("%s: original_sc == NULL!\n",
1563				    __func__);
1564				break;
1565			}
1566			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1567			io->io_hdr.msg_type = CTL_MSG_R2R;
1568			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1569			ctl_enqueue_isc(io);
1570			break;
1571
1572		/*
1573		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1574		 * mode.
1575		 * Performed on the Originating (i.e. secondary) SC in XFER
1576		 * mode
1577		 */
1578		case CTL_MSG_FINISH_IO:
1579			if (softc->ha_mode == CTL_HA_MODE_XFER)
1580				ctl_isc_handler_finish_xfer(softc, msg);
1581			else
1582				ctl_isc_handler_finish_ser_only(softc, msg);
1583			break;
1584
1585		/* Preformed on Originating SC */
1586		case CTL_MSG_BAD_JUJU:
1587			io = msg->hdr.original_sc;
1588			if (io == NULL) {
1589				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1590				       __func__);
1591				break;
1592			}
1593			ctl_copy_sense_data(msg, io);
1594			/*
1595			 * IO should have already been cleaned up on other
1596			 * SC so clear this flag so we won't send a message
1597			 * back to finish the IO there.
1598			 */
1599			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1600			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1601
1602			/* io = msg->hdr.serializing_sc; */
1603			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1604			ctl_enqueue_isc(io);
1605			break;
1606
1607		/* Handle resets sent from the other side */
1608		case CTL_MSG_MANAGE_TASKS: {
1609			struct ctl_taskio *taskio;
1610			taskio = (struct ctl_taskio *)ctl_alloc_io(
1611			    softc->othersc_pool);
1612			ctl_zero_io((union ctl_io *)taskio);
1613			taskio->io_hdr.io_type = CTL_IO_TASK;
1614			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1615			taskio->io_hdr.nexus = msg->hdr.nexus;
1616			taskio->task_action = msg->task.task_action;
1617			taskio->tag_num = msg->task.tag_num;
1618			taskio->tag_type = msg->task.tag_type;
1619#ifdef CTL_TIME_IO
1620			taskio->io_hdr.start_time = time_uptime;
1621			getbinuptime(&taskio->io_hdr.start_bt);
1622#endif /* CTL_TIME_IO */
1623			ctl_run_task((union ctl_io *)taskio);
1624			break;
1625		}
1626		/* Persistent Reserve action which needs attention */
1627		case CTL_MSG_PERS_ACTION:
1628			presio = (struct ctl_prio *)ctl_alloc_io(
1629			    softc->othersc_pool);
1630			ctl_zero_io((union ctl_io *)presio);
1631			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1632			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1633			presio->io_hdr.nexus = msg->hdr.nexus;
1634			presio->pr_msg = msg->pr;
1635			ctl_enqueue_isc((union ctl_io *)presio);
1636			break;
1637		case CTL_MSG_UA:
1638			ctl_isc_ua(softc, msg, param);
1639			break;
1640		case CTL_MSG_PORT_SYNC:
1641			ctl_isc_port_sync(softc, msg, param);
1642			break;
1643		case CTL_MSG_LUN_SYNC:
1644			ctl_isc_lun_sync(softc, msg, param);
1645			break;
1646		case CTL_MSG_IID_SYNC:
1647			ctl_isc_iid_sync(softc, msg, param);
1648			break;
1649		case CTL_MSG_LOGIN:
1650			ctl_isc_login(softc, msg, param);
1651			break;
1652		case CTL_MSG_MODE_SYNC:
1653			ctl_isc_mode_sync(softc, msg, param);
1654			break;
1655		default:
1656			printf("Received HA message of unknown type %d\n",
1657			    msg->hdr.msg_type);
1658			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1659			break;
1660		}
1661		if (msg != &msgbuf)
1662			free(msg, M_CTL);
1663	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1664		printf("CTL: HA link status changed from %d to %d\n",
1665		    softc->ha_link, param);
1666		if (param == softc->ha_link)
1667			return;
1668		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1669			softc->ha_link = param;
1670			ctl_isc_ha_link_down(softc);
1671		} else {
1672			softc->ha_link = param;
1673			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1674				ctl_isc_ha_link_up(softc);
1675		}
1676		return;
1677	} else {
1678		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1679		return;
1680	}
1681}
1682
1683static void
1684ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1685{
1686
1687	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1688	    src->scsi.sense_len);
1689	dest->scsiio.scsi_status = src->scsi.scsi_status;
1690	dest->scsiio.sense_len = src->scsi.sense_len;
1691	dest->io_hdr.status = src->hdr.status;
1692}
1693
1694static void
1695ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1696{
1697
1698	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1699	    src->scsiio.sense_len);
1700	dest->scsi.scsi_status = src->scsiio.scsi_status;
1701	dest->scsi.sense_len = src->scsiio.sense_len;
1702	dest->hdr.status = src->io_hdr.status;
1703}
1704
1705void
1706ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1707{
1708	struct ctl_softc *softc = lun->ctl_softc;
1709	ctl_ua_type *pu;
1710
1711	if (initidx < softc->init_min || initidx >= softc->init_max)
1712		return;
1713	mtx_assert(&lun->lun_lock, MA_OWNED);
1714	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1715	if (pu == NULL)
1716		return;
1717	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1718}
1719
1720void
1721ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1722{
1723	int i;
1724
1725	mtx_assert(&lun->lun_lock, MA_OWNED);
1726	if (lun->pending_ua[port] == NULL)
1727		return;
1728	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1729		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1730			continue;
1731		lun->pending_ua[port][i] |= ua;
1732	}
1733}
1734
1735void
1736ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1737{
1738	struct ctl_softc *softc = lun->ctl_softc;
1739	int i;
1740
1741	mtx_assert(&lun->lun_lock, MA_OWNED);
1742	for (i = softc->port_min; i < softc->port_max; i++)
1743		ctl_est_ua_port(lun, i, except, ua);
1744}
1745
1746void
1747ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1748{
1749	struct ctl_softc *softc = lun->ctl_softc;
1750	ctl_ua_type *pu;
1751
1752	if (initidx < softc->init_min || initidx >= softc->init_max)
1753		return;
1754	mtx_assert(&lun->lun_lock, MA_OWNED);
1755	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1756	if (pu == NULL)
1757		return;
1758	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1759}
1760
1761void
1762ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1763{
1764	struct ctl_softc *softc = lun->ctl_softc;
1765	int i, j;
1766
1767	mtx_assert(&lun->lun_lock, MA_OWNED);
1768	for (i = softc->port_min; i < softc->port_max; i++) {
1769		if (lun->pending_ua[i] == NULL)
1770			continue;
1771		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1772			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1773				continue;
1774			lun->pending_ua[i][j] &= ~ua;
1775		}
1776	}
1777}
1778
1779void
1780ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1781    ctl_ua_type ua_type)
1782{
1783	struct ctl_lun *lun;
1784
1785	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1786	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1787		mtx_lock(&lun->lun_lock);
1788		ctl_clr_ua(lun, initidx, ua_type);
1789		mtx_unlock(&lun->lun_lock);
1790	}
1791}
1792
1793static int
1794ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1795{
1796	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1797	struct ctl_lun *lun;
1798	struct ctl_lun_req ireq;
1799	int error, value;
1800
1801	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1802	error = sysctl_handle_int(oidp, &value, 0, req);
1803	if ((error != 0) || (req->newptr == NULL))
1804		return (error);
1805
1806	mtx_lock(&softc->ctl_lock);
1807	if (value == 0)
1808		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1809	else
1810		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1811	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1812		mtx_unlock(&softc->ctl_lock);
1813		bzero(&ireq, sizeof(ireq));
1814		ireq.reqtype = CTL_LUNREQ_MODIFY;
1815		ireq.reqdata.modify.lun_id = lun->lun;
1816		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1817		    curthread);
1818		if (ireq.status != CTL_LUN_OK) {
1819			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1820			    __func__, ireq.status, ireq.error_str);
1821		}
1822		mtx_lock(&softc->ctl_lock);
1823	}
1824	mtx_unlock(&softc->ctl_lock);
1825	return (0);
1826}
1827
1828static int
1829ctl_init(void)
1830{
1831	struct make_dev_args args;
1832	struct ctl_softc *softc;
1833	int i, error;
1834
1835	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1836			       M_WAITOK | M_ZERO);
1837
1838	make_dev_args_init(&args);
1839	args.mda_devsw = &ctl_cdevsw;
1840	args.mda_uid = UID_ROOT;
1841	args.mda_gid = GID_OPERATOR;
1842	args.mda_mode = 0600;
1843	args.mda_si_drv1 = softc;
1844	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1845	if (error != 0) {
1846		free(softc, M_DEVBUF);
1847		control_softc = NULL;
1848		return (error);
1849	}
1850
1851	sysctl_ctx_init(&softc->sysctl_ctx);
1852	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1853		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1854		CTLFLAG_RD, 0, "CAM Target Layer");
1855
1856	if (softc->sysctl_tree == NULL) {
1857		printf("%s: unable to allocate sysctl tree\n", __func__);
1858		destroy_dev(softc->dev);
1859		free(softc, M_DEVBUF);
1860		control_softc = NULL;
1861		return (ENOMEM);
1862	}
1863
1864	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1865	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1866	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1867	softc->flags = 0;
1868
1869	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1870	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1871	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1872
1873	/*
1874	 * In Copan's HA scheme, the "master" and "slave" roles are
1875	 * figured out through the slot the controller is in.  Although it
1876	 * is an active/active system, someone has to be in charge.
1877	 */
1878	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1879	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1880	    "HA head ID (0 - no HA)");
1881	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1882		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1883		softc->is_single = 1;
1884		softc->port_cnt = CTL_MAX_PORTS;
1885		softc->port_min = 0;
1886	} else {
1887		softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1888		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1889	}
1890	softc->port_max = softc->port_min + softc->port_cnt;
1891	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1892	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1893
1894	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1895	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1896	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1897
1898	STAILQ_INIT(&softc->lun_list);
1899	STAILQ_INIT(&softc->pending_lun_queue);
1900	STAILQ_INIT(&softc->fe_list);
1901	STAILQ_INIT(&softc->port_list);
1902	STAILQ_INIT(&softc->be_list);
1903	ctl_tpc_init(softc);
1904
1905	if (worker_threads <= 0)
1906		worker_threads = max(1, mp_ncpus / 4);
1907	if (worker_threads > CTL_MAX_THREADS)
1908		worker_threads = CTL_MAX_THREADS;
1909
1910	for (i = 0; i < worker_threads; i++) {
1911		struct ctl_thread *thr = &softc->threads[i];
1912
1913		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1914		thr->ctl_softc = softc;
1915		STAILQ_INIT(&thr->incoming_queue);
1916		STAILQ_INIT(&thr->rtr_queue);
1917		STAILQ_INIT(&thr->done_queue);
1918		STAILQ_INIT(&thr->isc_queue);
1919
1920		error = kproc_kthread_add(ctl_work_thread, thr,
1921		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1922		if (error != 0) {
1923			printf("error creating CTL work thread!\n");
1924			return (error);
1925		}
1926	}
1927	error = kproc_kthread_add(ctl_lun_thread, softc,
1928	    &softc->ctl_proc, &softc->lun_thread, 0, 0, "ctl", "lun");
1929	if (error != 0) {
1930		printf("error creating CTL lun thread!\n");
1931		return (error);
1932	}
1933	error = kproc_kthread_add(ctl_thresh_thread, softc,
1934	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1935	if (error != 0) {
1936		printf("error creating CTL threshold thread!\n");
1937		return (error);
1938	}
1939
1940	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1941	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1942	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1943
1944	if (softc->is_single == 0) {
1945		if (ctl_frontend_register(&ha_frontend) != 0)
1946			softc->is_single = 1;
1947	}
1948	return (0);
1949}
1950
1951static int
1952ctl_shutdown(void)
1953{
1954	struct ctl_softc *softc = control_softc;
1955	int i;
1956
1957	if (softc->is_single == 0)
1958		ctl_frontend_deregister(&ha_frontend);
1959
1960	destroy_dev(softc->dev);
1961
1962	/* Shutdown CTL threads. */
1963	softc->shutdown = 1;
1964	for (i = 0; i < worker_threads; i++) {
1965		struct ctl_thread *thr = &softc->threads[i];
1966		while (thr->thread != NULL) {
1967			wakeup(thr);
1968			if (thr->thread != NULL)
1969				pause("CTL thr shutdown", 1);
1970		}
1971		mtx_destroy(&thr->queue_lock);
1972	}
1973	while (softc->lun_thread != NULL) {
1974		wakeup(&softc->pending_lun_queue);
1975		if (softc->lun_thread != NULL)
1976			pause("CTL thr shutdown", 1);
1977	}
1978	while (softc->thresh_thread != NULL) {
1979		wakeup(softc->thresh_thread);
1980		if (softc->thresh_thread != NULL)
1981			pause("CTL thr shutdown", 1);
1982	}
1983
1984	ctl_tpc_shutdown(softc);
1985	uma_zdestroy(softc->io_zone);
1986	mtx_destroy(&softc->ctl_lock);
1987
1988	sysctl_ctx_free(&softc->sysctl_ctx);
1989
1990	free(softc, M_DEVBUF);
1991	control_softc = NULL;
1992	return (0);
1993}
1994
1995static int
1996ctl_module_event_handler(module_t mod, int what, void *arg)
1997{
1998
1999	switch (what) {
2000	case MOD_LOAD:
2001		return (ctl_init());
2002	case MOD_UNLOAD:
2003		return (ctl_shutdown());
2004	default:
2005		return (EOPNOTSUPP);
2006	}
2007}
2008
2009/*
2010 * XXX KDM should we do some access checks here?  Bump a reference count to
2011 * prevent a CTL module from being unloaded while someone has it open?
2012 */
2013static int
2014ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2015{
2016	return (0);
2017}
2018
2019static int
2020ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2021{
2022	return (0);
2023}
2024
2025/*
2026 * Remove an initiator by port number and initiator ID.
2027 * Returns 0 for success, -1 for failure.
2028 */
2029int
2030ctl_remove_initiator(struct ctl_port *port, int iid)
2031{
2032	struct ctl_softc *softc = port->ctl_softc;
2033	int last;
2034
2035	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2036
2037	if (iid > CTL_MAX_INIT_PER_PORT) {
2038		printf("%s: initiator ID %u > maximun %u!\n",
2039		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2040		return (-1);
2041	}
2042
2043	mtx_lock(&softc->ctl_lock);
2044	last = (--port->wwpn_iid[iid].in_use == 0);
2045	port->wwpn_iid[iid].last_use = time_uptime;
2046	mtx_unlock(&softc->ctl_lock);
2047	if (last)
2048		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2049	ctl_isc_announce_iid(port, iid);
2050
2051	return (0);
2052}
2053
2054/*
2055 * Add an initiator to the initiator map.
2056 * Returns iid for success, < 0 for failure.
2057 */
2058int
2059ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2060{
2061	struct ctl_softc *softc = port->ctl_softc;
2062	time_t best_time;
2063	int i, best;
2064
2065	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2066
2067	if (iid >= CTL_MAX_INIT_PER_PORT) {
2068		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2069		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2070		free(name, M_CTL);
2071		return (-1);
2072	}
2073
2074	mtx_lock(&softc->ctl_lock);
2075
2076	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2077		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2078			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2079				iid = i;
2080				break;
2081			}
2082			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2083			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2084				iid = i;
2085				break;
2086			}
2087		}
2088	}
2089
2090	if (iid < 0) {
2091		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2092			if (port->wwpn_iid[i].in_use == 0 &&
2093			    port->wwpn_iid[i].wwpn == 0 &&
2094			    port->wwpn_iid[i].name == NULL) {
2095				iid = i;
2096				break;
2097			}
2098		}
2099	}
2100
2101	if (iid < 0) {
2102		best = -1;
2103		best_time = INT32_MAX;
2104		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2105			if (port->wwpn_iid[i].in_use == 0) {
2106				if (port->wwpn_iid[i].last_use < best_time) {
2107					best = i;
2108					best_time = port->wwpn_iid[i].last_use;
2109				}
2110			}
2111		}
2112		iid = best;
2113	}
2114
2115	if (iid < 0) {
2116		mtx_unlock(&softc->ctl_lock);
2117		free(name, M_CTL);
2118		return (-2);
2119	}
2120
2121	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2122		/*
2123		 * This is not an error yet.
2124		 */
2125		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2126#if 0
2127			printf("%s: port %d iid %u WWPN %#jx arrived"
2128			    " again\n", __func__, port->targ_port,
2129			    iid, (uintmax_t)wwpn);
2130#endif
2131			goto take;
2132		}
2133		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2134		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2135#if 0
2136			printf("%s: port %d iid %u name '%s' arrived"
2137			    " again\n", __func__, port->targ_port,
2138			    iid, name);
2139#endif
2140			goto take;
2141		}
2142
2143		/*
2144		 * This is an error, but what do we do about it?  The
2145		 * driver is telling us we have a new WWPN for this
2146		 * initiator ID, so we pretty much need to use it.
2147		 */
2148		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2149		    " but WWPN %#jx '%s' is still at that address\n",
2150		    __func__, port->targ_port, iid, wwpn, name,
2151		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2152		    port->wwpn_iid[iid].name);
2153	}
2154take:
2155	free(port->wwpn_iid[iid].name, M_CTL);
2156	port->wwpn_iid[iid].name = name;
2157	port->wwpn_iid[iid].wwpn = wwpn;
2158	port->wwpn_iid[iid].in_use++;
2159	mtx_unlock(&softc->ctl_lock);
2160	ctl_isc_announce_iid(port, iid);
2161
2162	return (iid);
2163}
2164
2165static int
2166ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2167{
2168	int len;
2169
2170	switch (port->port_type) {
2171	case CTL_PORT_FC:
2172	{
2173		struct scsi_transportid_fcp *id =
2174		    (struct scsi_transportid_fcp *)buf;
2175		if (port->wwpn_iid[iid].wwpn == 0)
2176			return (0);
2177		memset(id, 0, sizeof(*id));
2178		id->format_protocol = SCSI_PROTO_FC;
2179		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2180		return (sizeof(*id));
2181	}
2182	case CTL_PORT_ISCSI:
2183	{
2184		struct scsi_transportid_iscsi_port *id =
2185		    (struct scsi_transportid_iscsi_port *)buf;
2186		if (port->wwpn_iid[iid].name == NULL)
2187			return (0);
2188		memset(id, 0, 256);
2189		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2190		    SCSI_PROTO_ISCSI;
2191		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2192		len = roundup2(min(len, 252), 4);
2193		scsi_ulto2b(len, id->additional_length);
2194		return (sizeof(*id) + len);
2195	}
2196	case CTL_PORT_SAS:
2197	{
2198		struct scsi_transportid_sas *id =
2199		    (struct scsi_transportid_sas *)buf;
2200		if (port->wwpn_iid[iid].wwpn == 0)
2201			return (0);
2202		memset(id, 0, sizeof(*id));
2203		id->format_protocol = SCSI_PROTO_SAS;
2204		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2205		return (sizeof(*id));
2206	}
2207	default:
2208	{
2209		struct scsi_transportid_spi *id =
2210		    (struct scsi_transportid_spi *)buf;
2211		memset(id, 0, sizeof(*id));
2212		id->format_protocol = SCSI_PROTO_SPI;
2213		scsi_ulto2b(iid, id->scsi_addr);
2214		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2215		return (sizeof(*id));
2216	}
2217	}
2218}
2219
2220/*
2221 * Serialize a command that went down the "wrong" side, and so was sent to
2222 * this controller for execution.  The logic is a little different than the
2223 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2224 * sent back to the other side, but in the success case, we execute the
2225 * command on this side (XFER mode) or tell the other side to execute it
2226 * (SER_ONLY mode).
2227 */
2228static void
2229ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2230{
2231	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2232	struct ctl_port *port = CTL_PORT(ctsio);
2233	union ctl_ha_msg msg_info;
2234	struct ctl_lun *lun;
2235	const struct ctl_cmd_entry *entry;
2236	uint32_t targ_lun;
2237
2238	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2239
2240	/* Make sure that we know about this port. */
2241	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2242		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2243					 /*retry_count*/ 1);
2244		goto badjuju;
2245	}
2246
2247	/* Make sure that we know about this LUN. */
2248	mtx_lock(&softc->ctl_lock);
2249	if (targ_lun >= CTL_MAX_LUNS ||
2250	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2251		mtx_unlock(&softc->ctl_lock);
2252
2253		/*
2254		 * The other node would not send this request to us unless
2255		 * received announce that we are primary node for this LUN.
2256		 * If this LUN does not exist now, it is probably result of
2257		 * a race, so respond to initiator in the most opaque way.
2258		 */
2259		ctl_set_busy(ctsio);
2260		goto badjuju;
2261	}
2262	mtx_lock(&lun->lun_lock);
2263	mtx_unlock(&softc->ctl_lock);
2264
2265	/*
2266	 * If the LUN is invalid, pretend that it doesn't exist.
2267	 * It will go away as soon as all pending I/Os completed.
2268	 */
2269	if (lun->flags & CTL_LUN_DISABLED) {
2270		mtx_unlock(&lun->lun_lock);
2271		ctl_set_busy(ctsio);
2272		goto badjuju;
2273	}
2274
2275	entry = ctl_get_cmd_entry(ctsio, NULL);
2276	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2277		mtx_unlock(&lun->lun_lock);
2278		goto badjuju;
2279	}
2280
2281	CTL_LUN(ctsio) = lun;
2282	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2283
2284	/*
2285	 * Every I/O goes into the OOA queue for a
2286	 * particular LUN, and stays there until completion.
2287	 */
2288#ifdef CTL_TIME_IO
2289	if (TAILQ_EMPTY(&lun->ooa_queue))
2290		lun->idle_time += getsbinuptime() - lun->last_busy;
2291#endif
2292	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2293
2294	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2295		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2296		 ooa_links))) {
2297	case CTL_ACTION_BLOCK:
2298		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2299		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2300				  blocked_links);
2301		mtx_unlock(&lun->lun_lock);
2302		break;
2303	case CTL_ACTION_PASS:
2304	case CTL_ACTION_SKIP:
2305		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2306			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2307			ctl_enqueue_rtr((union ctl_io *)ctsio);
2308			mtx_unlock(&lun->lun_lock);
2309		} else {
2310			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2311			mtx_unlock(&lun->lun_lock);
2312
2313			/* send msg back to other side */
2314			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2315			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2316			msg_info.hdr.msg_type = CTL_MSG_R2R;
2317			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2318			    sizeof(msg_info.hdr), M_WAITOK);
2319		}
2320		break;
2321	case CTL_ACTION_OVERLAP:
2322		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2323		mtx_unlock(&lun->lun_lock);
2324		ctl_set_overlapped_cmd(ctsio);
2325		goto badjuju;
2326	case CTL_ACTION_OVERLAP_TAG:
2327		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2328		mtx_unlock(&lun->lun_lock);
2329		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2330		goto badjuju;
2331	case CTL_ACTION_ERROR:
2332	default:
2333		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2334		mtx_unlock(&lun->lun_lock);
2335
2336		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2337					 /*retry_count*/ 0);
2338badjuju:
2339		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2340		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2341		msg_info.hdr.serializing_sc = NULL;
2342		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2343		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2344		    sizeof(msg_info.scsi), M_WAITOK);
2345		ctl_free_io((union ctl_io *)ctsio);
2346		break;
2347	}
2348}
2349
2350/*
2351 * Returns 0 for success, errno for failure.
2352 */
2353static void
2354ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2355		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2356{
2357	union ctl_io *io;
2358
2359	mtx_lock(&lun->lun_lock);
2360	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2361	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2362	     ooa_links)) {
2363		struct ctl_ooa_entry *entry;
2364
2365		/*
2366		 * If we've got more than we can fit, just count the
2367		 * remaining entries.
2368		 */
2369		if (*cur_fill_num >= ooa_hdr->alloc_num)
2370			continue;
2371
2372		entry = &kern_entries[*cur_fill_num];
2373
2374		entry->tag_num = io->scsiio.tag_num;
2375		entry->lun_num = lun->lun;
2376#ifdef CTL_TIME_IO
2377		entry->start_bt = io->io_hdr.start_bt;
2378#endif
2379		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2380		entry->cdb_len = io->scsiio.cdb_len;
2381		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2382			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2383
2384		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2385			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2386
2387		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2388			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2389
2390		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2391			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2392
2393		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2394			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2395	}
2396	mtx_unlock(&lun->lun_lock);
2397}
2398
2399static void *
2400ctl_copyin_alloc(void *user_addr, unsigned int len, char *error_str,
2401		 size_t error_str_len)
2402{
2403	void *kptr;
2404
2405	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2406
2407	if (copyin(user_addr, kptr, len) != 0) {
2408		snprintf(error_str, error_str_len, "Error copying %d bytes "
2409			 "from user address %p to kernel address %p", len,
2410			 user_addr, kptr);
2411		free(kptr, M_CTL);
2412		return (NULL);
2413	}
2414
2415	return (kptr);
2416}
2417
2418static void
2419ctl_free_args(int num_args, struct ctl_be_arg *args)
2420{
2421	int i;
2422
2423	if (args == NULL)
2424		return;
2425
2426	for (i = 0; i < num_args; i++) {
2427		free(args[i].kname, M_CTL);
2428		free(args[i].kvalue, M_CTL);
2429	}
2430
2431	free(args, M_CTL);
2432}
2433
2434static struct ctl_be_arg *
2435ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2436		char *error_str, size_t error_str_len)
2437{
2438	struct ctl_be_arg *args;
2439	int i;
2440
2441	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2442				error_str, error_str_len);
2443
2444	if (args == NULL)
2445		goto bailout;
2446
2447	for (i = 0; i < num_args; i++) {
2448		args[i].kname = NULL;
2449		args[i].kvalue = NULL;
2450	}
2451
2452	for (i = 0; i < num_args; i++) {
2453		uint8_t *tmpptr;
2454
2455		if (args[i].namelen == 0) {
2456			snprintf(error_str, error_str_len, "Argument %d "
2457				 "name length is zero", i);
2458			goto bailout;
2459		}
2460
2461		args[i].kname = ctl_copyin_alloc(args[i].name,
2462			args[i].namelen, error_str, error_str_len);
2463		if (args[i].kname == NULL)
2464			goto bailout;
2465
2466		if (args[i].kname[args[i].namelen - 1] != '\0') {
2467			snprintf(error_str, error_str_len, "Argument %d "
2468				 "name is not NUL-terminated", i);
2469			goto bailout;
2470		}
2471
2472		if (args[i].flags & CTL_BEARG_RD) {
2473			if (args[i].vallen == 0) {
2474				snprintf(error_str, error_str_len, "Argument %d "
2475					 "value length is zero", i);
2476				goto bailout;
2477			}
2478
2479			tmpptr = ctl_copyin_alloc(args[i].value,
2480				args[i].vallen, error_str, error_str_len);
2481			if (tmpptr == NULL)
2482				goto bailout;
2483
2484			if ((args[i].flags & CTL_BEARG_ASCII)
2485			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2486				snprintf(error_str, error_str_len, "Argument "
2487				    "%d value is not NUL-terminated", i);
2488				free(tmpptr, M_CTL);
2489				goto bailout;
2490			}
2491			args[i].kvalue = tmpptr;
2492		} else {
2493			args[i].kvalue = malloc(args[i].vallen,
2494			    M_CTL, M_WAITOK | M_ZERO);
2495		}
2496	}
2497
2498	return (args);
2499bailout:
2500
2501	ctl_free_args(num_args, args);
2502
2503	return (NULL);
2504}
2505
2506static void
2507ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2508{
2509	int i;
2510
2511	for (i = 0; i < num_args; i++) {
2512		if (args[i].flags & CTL_BEARG_WR)
2513			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2514	}
2515}
2516
2517/*
2518 * Escape characters that are illegal or not recommended in XML.
2519 */
2520int
2521ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2522{
2523	char *end = str + size;
2524	int retval;
2525
2526	retval = 0;
2527
2528	for (; *str && str < end; str++) {
2529		switch (*str) {
2530		case '&':
2531			retval = sbuf_printf(sb, "&amp;");
2532			break;
2533		case '>':
2534			retval = sbuf_printf(sb, "&gt;");
2535			break;
2536		case '<':
2537			retval = sbuf_printf(sb, "&lt;");
2538			break;
2539		default:
2540			retval = sbuf_putc(sb, *str);
2541			break;
2542		}
2543
2544		if (retval != 0)
2545			break;
2546
2547	}
2548
2549	return (retval);
2550}
2551
2552static void
2553ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2554{
2555	struct scsi_vpd_id_descriptor *desc;
2556	int i;
2557
2558	if (id == NULL || id->len < 4)
2559		return;
2560	desc = (struct scsi_vpd_id_descriptor *)id->data;
2561	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2562	case SVPD_ID_TYPE_T10:
2563		sbuf_printf(sb, "t10.");
2564		break;
2565	case SVPD_ID_TYPE_EUI64:
2566		sbuf_printf(sb, "eui.");
2567		break;
2568	case SVPD_ID_TYPE_NAA:
2569		sbuf_printf(sb, "naa.");
2570		break;
2571	case SVPD_ID_TYPE_SCSI_NAME:
2572		break;
2573	}
2574	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2575	case SVPD_ID_CODESET_BINARY:
2576		for (i = 0; i < desc->length; i++)
2577			sbuf_printf(sb, "%02x", desc->identifier[i]);
2578		break;
2579	case SVPD_ID_CODESET_ASCII:
2580		sbuf_printf(sb, "%.*s", (int)desc->length,
2581		    (char *)desc->identifier);
2582		break;
2583	case SVPD_ID_CODESET_UTF8:
2584		sbuf_printf(sb, "%s", (char *)desc->identifier);
2585		break;
2586	}
2587}
2588
2589static int
2590ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2591	  struct thread *td)
2592{
2593	struct ctl_softc *softc = dev->si_drv1;
2594	struct ctl_port *port;
2595	struct ctl_lun *lun;
2596	int retval;
2597
2598	retval = 0;
2599
2600	switch (cmd) {
2601	case CTL_IO:
2602		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2603		break;
2604	case CTL_ENABLE_PORT:
2605	case CTL_DISABLE_PORT:
2606	case CTL_SET_PORT_WWNS: {
2607		struct ctl_port *port;
2608		struct ctl_port_entry *entry;
2609
2610		entry = (struct ctl_port_entry *)addr;
2611
2612		mtx_lock(&softc->ctl_lock);
2613		STAILQ_FOREACH(port, &softc->port_list, links) {
2614			int action, done;
2615
2616			if (port->targ_port < softc->port_min ||
2617			    port->targ_port >= softc->port_max)
2618				continue;
2619
2620			action = 0;
2621			done = 0;
2622			if ((entry->port_type == CTL_PORT_NONE)
2623			 && (entry->targ_port == port->targ_port)) {
2624				/*
2625				 * If the user only wants to enable or
2626				 * disable or set WWNs on a specific port,
2627				 * do the operation and we're done.
2628				 */
2629				action = 1;
2630				done = 1;
2631			} else if (entry->port_type & port->port_type) {
2632				/*
2633				 * Compare the user's type mask with the
2634				 * particular frontend type to see if we
2635				 * have a match.
2636				 */
2637				action = 1;
2638				done = 0;
2639
2640				/*
2641				 * Make sure the user isn't trying to set
2642				 * WWNs on multiple ports at the same time.
2643				 */
2644				if (cmd == CTL_SET_PORT_WWNS) {
2645					printf("%s: Can't set WWNs on "
2646					       "multiple ports\n", __func__);
2647					retval = EINVAL;
2648					break;
2649				}
2650			}
2651			if (action == 0)
2652				continue;
2653
2654			/*
2655			 * XXX KDM we have to drop the lock here, because
2656			 * the online/offline operations can potentially
2657			 * block.  We need to reference count the frontends
2658			 * so they can't go away,
2659			 */
2660			if (cmd == CTL_ENABLE_PORT) {
2661				mtx_unlock(&softc->ctl_lock);
2662				ctl_port_online(port);
2663				mtx_lock(&softc->ctl_lock);
2664			} else if (cmd == CTL_DISABLE_PORT) {
2665				mtx_unlock(&softc->ctl_lock);
2666				ctl_port_offline(port);
2667				mtx_lock(&softc->ctl_lock);
2668			} else if (cmd == CTL_SET_PORT_WWNS) {
2669				ctl_port_set_wwns(port,
2670				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2671				    1 : 0, entry->wwnn,
2672				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2673				    1 : 0, entry->wwpn);
2674			}
2675			if (done != 0)
2676				break;
2677		}
2678		mtx_unlock(&softc->ctl_lock);
2679		break;
2680	}
2681	case CTL_GET_OOA: {
2682		struct ctl_ooa *ooa_hdr;
2683		struct ctl_ooa_entry *entries;
2684		uint32_t cur_fill_num;
2685
2686		ooa_hdr = (struct ctl_ooa *)addr;
2687
2688		if ((ooa_hdr->alloc_len == 0)
2689		 || (ooa_hdr->alloc_num == 0)) {
2690			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2691			       "must be non-zero\n", __func__,
2692			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2693			retval = EINVAL;
2694			break;
2695		}
2696
2697		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2698		    sizeof(struct ctl_ooa_entry))) {
2699			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2700			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2701			       __func__, ooa_hdr->alloc_len,
2702			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2703			retval = EINVAL;
2704			break;
2705		}
2706
2707		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2708		if (entries == NULL) {
2709			printf("%s: could not allocate %d bytes for OOA "
2710			       "dump\n", __func__, ooa_hdr->alloc_len);
2711			retval = ENOMEM;
2712			break;
2713		}
2714
2715		mtx_lock(&softc->ctl_lock);
2716		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2717		    (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2718		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2719			mtx_unlock(&softc->ctl_lock);
2720			free(entries, M_CTL);
2721			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2722			       __func__, (uintmax_t)ooa_hdr->lun_num);
2723			retval = EINVAL;
2724			break;
2725		}
2726
2727		cur_fill_num = 0;
2728
2729		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2730			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2731				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2732				    ooa_hdr, entries);
2733			}
2734		} else {
2735			lun = softc->ctl_luns[ooa_hdr->lun_num];
2736			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2737			    entries);
2738		}
2739		mtx_unlock(&softc->ctl_lock);
2740
2741		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2742		ooa_hdr->fill_len = ooa_hdr->fill_num *
2743			sizeof(struct ctl_ooa_entry);
2744		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2745		if (retval != 0) {
2746			printf("%s: error copying out %d bytes for OOA dump\n",
2747			       __func__, ooa_hdr->fill_len);
2748		}
2749
2750		getbinuptime(&ooa_hdr->cur_bt);
2751
2752		if (cur_fill_num > ooa_hdr->alloc_num) {
2753			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2754			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2755		} else {
2756			ooa_hdr->dropped_num = 0;
2757			ooa_hdr->status = CTL_OOA_OK;
2758		}
2759
2760		free(entries, M_CTL);
2761		break;
2762	}
2763	case CTL_DELAY_IO: {
2764		struct ctl_io_delay_info *delay_info;
2765
2766		delay_info = (struct ctl_io_delay_info *)addr;
2767
2768#ifdef CTL_IO_DELAY
2769		mtx_lock(&softc->ctl_lock);
2770		if (delay_info->lun_id >= CTL_MAX_LUNS ||
2771		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2772			mtx_unlock(&softc->ctl_lock);
2773			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2774			break;
2775		}
2776		mtx_lock(&lun->lun_lock);
2777		mtx_unlock(&softc->ctl_lock);
2778		delay_info->status = CTL_DELAY_STATUS_OK;
2779		switch (delay_info->delay_type) {
2780		case CTL_DELAY_TYPE_CONT:
2781		case CTL_DELAY_TYPE_ONESHOT:
2782			break;
2783		default:
2784			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2785			break;
2786		}
2787		switch (delay_info->delay_loc) {
2788		case CTL_DELAY_LOC_DATAMOVE:
2789			lun->delay_info.datamove_type = delay_info->delay_type;
2790			lun->delay_info.datamove_delay = delay_info->delay_secs;
2791			break;
2792		case CTL_DELAY_LOC_DONE:
2793			lun->delay_info.done_type = delay_info->delay_type;
2794			lun->delay_info.done_delay = delay_info->delay_secs;
2795			break;
2796		default:
2797			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2798			break;
2799		}
2800		mtx_unlock(&lun->lun_lock);
2801#else
2802		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2803#endif /* CTL_IO_DELAY */
2804		break;
2805	}
2806#ifdef CTL_LEGACY_STATS
2807	case CTL_GETSTATS: {
2808		struct ctl_stats *stats = (struct ctl_stats *)addr;
2809		int i;
2810
2811		/*
2812		 * XXX KDM no locking here.  If the LUN list changes,
2813		 * things can blow up.
2814		 */
2815		i = 0;
2816		stats->status = CTL_SS_OK;
2817		stats->fill_len = 0;
2818		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2819			if (stats->fill_len + sizeof(lun->legacy_stats) >
2820			    stats->alloc_len) {
2821				stats->status = CTL_SS_NEED_MORE_SPACE;
2822				break;
2823			}
2824			retval = copyout(&lun->legacy_stats, &stats->lun_stats[i++],
2825					 sizeof(lun->legacy_stats));
2826			if (retval != 0)
2827				break;
2828			stats->fill_len += sizeof(lun->legacy_stats);
2829		}
2830		stats->num_luns = softc->num_luns;
2831		stats->flags = CTL_STATS_FLAG_NONE;
2832#ifdef CTL_TIME_IO
2833		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
2834#endif
2835		getnanouptime(&stats->timestamp);
2836		break;
2837	}
2838#endif /* CTL_LEGACY_STATS */
2839	case CTL_ERROR_INJECT: {
2840		struct ctl_error_desc *err_desc, *new_err_desc;
2841
2842		err_desc = (struct ctl_error_desc *)addr;
2843
2844		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2845				      M_WAITOK | M_ZERO);
2846		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2847
2848		mtx_lock(&softc->ctl_lock);
2849		if (err_desc->lun_id >= CTL_MAX_LUNS ||
2850		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2851			mtx_unlock(&softc->ctl_lock);
2852			free(new_err_desc, M_CTL);
2853			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2854			       __func__, (uintmax_t)err_desc->lun_id);
2855			retval = EINVAL;
2856			break;
2857		}
2858		mtx_lock(&lun->lun_lock);
2859		mtx_unlock(&softc->ctl_lock);
2860
2861		/*
2862		 * We could do some checking here to verify the validity
2863		 * of the request, but given the complexity of error
2864		 * injection requests, the checking logic would be fairly
2865		 * complex.
2866		 *
2867		 * For now, if the request is invalid, it just won't get
2868		 * executed and might get deleted.
2869		 */
2870		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2871
2872		/*
2873		 * XXX KDM check to make sure the serial number is unique,
2874		 * in case we somehow manage to wrap.  That shouldn't
2875		 * happen for a very long time, but it's the right thing to
2876		 * do.
2877		 */
2878		new_err_desc->serial = lun->error_serial;
2879		err_desc->serial = lun->error_serial;
2880		lun->error_serial++;
2881
2882		mtx_unlock(&lun->lun_lock);
2883		break;
2884	}
2885	case CTL_ERROR_INJECT_DELETE: {
2886		struct ctl_error_desc *delete_desc, *desc, *desc2;
2887		int delete_done;
2888
2889		delete_desc = (struct ctl_error_desc *)addr;
2890		delete_done = 0;
2891
2892		mtx_lock(&softc->ctl_lock);
2893		if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2894		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2895			mtx_unlock(&softc->ctl_lock);
2896			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2897			       __func__, (uintmax_t)delete_desc->lun_id);
2898			retval = EINVAL;
2899			break;
2900		}
2901		mtx_lock(&lun->lun_lock);
2902		mtx_unlock(&softc->ctl_lock);
2903		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2904			if (desc->serial != delete_desc->serial)
2905				continue;
2906
2907			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2908				      links);
2909			free(desc, M_CTL);
2910			delete_done = 1;
2911		}
2912		mtx_unlock(&lun->lun_lock);
2913		if (delete_done == 0) {
2914			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2915			       "error serial %ju on LUN %u\n", __func__,
2916			       delete_desc->serial, delete_desc->lun_id);
2917			retval = EINVAL;
2918			break;
2919		}
2920		break;
2921	}
2922	case CTL_DUMP_STRUCTS: {
2923		int j, k;
2924		struct ctl_port *port;
2925		struct ctl_frontend *fe;
2926
2927		mtx_lock(&softc->ctl_lock);
2928		printf("CTL Persistent Reservation information start:\n");
2929		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2930			mtx_lock(&lun->lun_lock);
2931			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2932				mtx_unlock(&lun->lun_lock);
2933				continue;
2934			}
2935
2936			for (j = 0; j < CTL_MAX_PORTS; j++) {
2937				if (lun->pr_keys[j] == NULL)
2938					continue;
2939				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2940					if (lun->pr_keys[j][k] == 0)
2941						continue;
2942					printf("  LUN %ju port %d iid %d key "
2943					       "%#jx\n", lun->lun, j, k,
2944					       (uintmax_t)lun->pr_keys[j][k]);
2945				}
2946			}
2947			mtx_unlock(&lun->lun_lock);
2948		}
2949		printf("CTL Persistent Reservation information end\n");
2950		printf("CTL Ports:\n");
2951		STAILQ_FOREACH(port, &softc->port_list, links) {
2952			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2953			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2954			       port->frontend->name, port->port_type,
2955			       port->physical_port, port->virtual_port,
2956			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2957			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2958				if (port->wwpn_iid[j].in_use == 0 &&
2959				    port->wwpn_iid[j].wwpn == 0 &&
2960				    port->wwpn_iid[j].name == NULL)
2961					continue;
2962
2963				printf("    iid %u use %d WWPN %#jx '%s'\n",
2964				    j, port->wwpn_iid[j].in_use,
2965				    (uintmax_t)port->wwpn_iid[j].wwpn,
2966				    port->wwpn_iid[j].name);
2967			}
2968		}
2969		printf("CTL Port information end\n");
2970		mtx_unlock(&softc->ctl_lock);
2971		/*
2972		 * XXX KDM calling this without a lock.  We'd likely want
2973		 * to drop the lock before calling the frontend's dump
2974		 * routine anyway.
2975		 */
2976		printf("CTL Frontends:\n");
2977		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2978			printf("  Frontend '%s'\n", fe->name);
2979			if (fe->fe_dump != NULL)
2980				fe->fe_dump();
2981		}
2982		printf("CTL Frontend information end\n");
2983		break;
2984	}
2985	case CTL_LUN_REQ: {
2986		struct ctl_lun_req *lun_req;
2987		struct ctl_backend_driver *backend;
2988
2989		lun_req = (struct ctl_lun_req *)addr;
2990
2991		backend = ctl_backend_find(lun_req->backend);
2992		if (backend == NULL) {
2993			lun_req->status = CTL_LUN_ERROR;
2994			snprintf(lun_req->error_str,
2995				 sizeof(lun_req->error_str),
2996				 "Backend \"%s\" not found.",
2997				 lun_req->backend);
2998			break;
2999		}
3000		if (lun_req->num_be_args > 0) {
3001			lun_req->kern_be_args = ctl_copyin_args(
3002				lun_req->num_be_args,
3003				lun_req->be_args,
3004				lun_req->error_str,
3005				sizeof(lun_req->error_str));
3006			if (lun_req->kern_be_args == NULL) {
3007				lun_req->status = CTL_LUN_ERROR;
3008				break;
3009			}
3010		}
3011
3012		retval = backend->ioctl(dev, cmd, addr, flag, td);
3013
3014		if (lun_req->num_be_args > 0) {
3015			ctl_copyout_args(lun_req->num_be_args,
3016				      lun_req->kern_be_args);
3017			ctl_free_args(lun_req->num_be_args,
3018				      lun_req->kern_be_args);
3019		}
3020		break;
3021	}
3022	case CTL_LUN_LIST: {
3023		struct sbuf *sb;
3024		struct ctl_lun_list *list;
3025		struct ctl_option *opt;
3026
3027		list = (struct ctl_lun_list *)addr;
3028
3029		/*
3030		 * Allocate a fixed length sbuf here, based on the length
3031		 * of the user's buffer.  We could allocate an auto-extending
3032		 * buffer, and then tell the user how much larger our
3033		 * amount of data is than his buffer, but that presents
3034		 * some problems:
3035		 *
3036		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3037		 *     we can't hold a lock while calling them with an
3038		 *     auto-extending buffer.
3039 		 *
3040		 * 2.  There is not currently a LUN reference counting
3041		 *     mechanism, outside of outstanding transactions on
3042		 *     the LUN's OOA queue.  So a LUN could go away on us
3043		 *     while we're getting the LUN number, backend-specific
3044		 *     information, etc.  Thus, given the way things
3045		 *     currently work, we need to hold the CTL lock while
3046		 *     grabbing LUN information.
3047		 *
3048		 * So, from the user's standpoint, the best thing to do is
3049		 * allocate what he thinks is a reasonable buffer length,
3050		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3051		 * double the buffer length and try again.  (And repeat
3052		 * that until he succeeds.)
3053		 */
3054		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3055		if (sb == NULL) {
3056			list->status = CTL_LUN_LIST_ERROR;
3057			snprintf(list->error_str, sizeof(list->error_str),
3058				 "Unable to allocate %d bytes for LUN list",
3059				 list->alloc_len);
3060			break;
3061		}
3062
3063		sbuf_printf(sb, "<ctllunlist>\n");
3064
3065		mtx_lock(&softc->ctl_lock);
3066		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3067			mtx_lock(&lun->lun_lock);
3068			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3069					     (uintmax_t)lun->lun);
3070
3071			/*
3072			 * Bail out as soon as we see that we've overfilled
3073			 * the buffer.
3074			 */
3075			if (retval != 0)
3076				break;
3077
3078			retval = sbuf_printf(sb, "\t<backend_type>%s"
3079					     "</backend_type>\n",
3080					     (lun->backend == NULL) ?  "none" :
3081					     lun->backend->name);
3082
3083			if (retval != 0)
3084				break;
3085
3086			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3087					     lun->be_lun->lun_type);
3088
3089			if (retval != 0)
3090				break;
3091
3092			if (lun->backend == NULL) {
3093				retval = sbuf_printf(sb, "</lun>\n");
3094				if (retval != 0)
3095					break;
3096				continue;
3097			}
3098
3099			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3100					     (lun->be_lun->maxlba > 0) ?
3101					     lun->be_lun->maxlba + 1 : 0);
3102
3103			if (retval != 0)
3104				break;
3105
3106			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3107					     lun->be_lun->blocksize);
3108
3109			if (retval != 0)
3110				break;
3111
3112			retval = sbuf_printf(sb, "\t<serial_number>");
3113
3114			if (retval != 0)
3115				break;
3116
3117			retval = ctl_sbuf_printf_esc(sb,
3118			    lun->be_lun->serial_num,
3119			    sizeof(lun->be_lun->serial_num));
3120
3121			if (retval != 0)
3122				break;
3123
3124			retval = sbuf_printf(sb, "</serial_number>\n");
3125
3126			if (retval != 0)
3127				break;
3128
3129			retval = sbuf_printf(sb, "\t<device_id>");
3130
3131			if (retval != 0)
3132				break;
3133
3134			retval = ctl_sbuf_printf_esc(sb,
3135			    lun->be_lun->device_id,
3136			    sizeof(lun->be_lun->device_id));
3137
3138			if (retval != 0)
3139				break;
3140
3141			retval = sbuf_printf(sb, "</device_id>\n");
3142
3143			if (retval != 0)
3144				break;
3145
3146			if (lun->backend->lun_info != NULL) {
3147				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3148				if (retval != 0)
3149					break;
3150			}
3151			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3152				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3153				    opt->name, opt->value, opt->name);
3154				if (retval != 0)
3155					break;
3156			}
3157
3158			retval = sbuf_printf(sb, "</lun>\n");
3159
3160			if (retval != 0)
3161				break;
3162			mtx_unlock(&lun->lun_lock);
3163		}
3164		if (lun != NULL)
3165			mtx_unlock(&lun->lun_lock);
3166		mtx_unlock(&softc->ctl_lock);
3167
3168		if ((retval != 0)
3169		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3170			retval = 0;
3171			sbuf_delete(sb);
3172			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3173			snprintf(list->error_str, sizeof(list->error_str),
3174				 "Out of space, %d bytes is too small",
3175				 list->alloc_len);
3176			break;
3177		}
3178
3179		sbuf_finish(sb);
3180
3181		retval = copyout(sbuf_data(sb), list->lun_xml,
3182				 sbuf_len(sb) + 1);
3183
3184		list->fill_len = sbuf_len(sb) + 1;
3185		list->status = CTL_LUN_LIST_OK;
3186		sbuf_delete(sb);
3187		break;
3188	}
3189	case CTL_ISCSI: {
3190		struct ctl_iscsi *ci;
3191		struct ctl_frontend *fe;
3192
3193		ci = (struct ctl_iscsi *)addr;
3194
3195		fe = ctl_frontend_find("iscsi");
3196		if (fe == NULL) {
3197			ci->status = CTL_ISCSI_ERROR;
3198			snprintf(ci->error_str, sizeof(ci->error_str),
3199			    "Frontend \"iscsi\" not found.");
3200			break;
3201		}
3202
3203		retval = fe->ioctl(dev, cmd, addr, flag, td);
3204		break;
3205	}
3206	case CTL_PORT_REQ: {
3207		struct ctl_req *req;
3208		struct ctl_frontend *fe;
3209
3210		req = (struct ctl_req *)addr;
3211
3212		fe = ctl_frontend_find(req->driver);
3213		if (fe == NULL) {
3214			req->status = CTL_LUN_ERROR;
3215			snprintf(req->error_str, sizeof(req->error_str),
3216			    "Frontend \"%s\" not found.", req->driver);
3217			break;
3218		}
3219		if (req->num_args > 0) {
3220			req->kern_args = ctl_copyin_args(req->num_args,
3221			    req->args, req->error_str, sizeof(req->error_str));
3222			if (req->kern_args == NULL) {
3223				req->status = CTL_LUN_ERROR;
3224				break;
3225			}
3226		}
3227
3228		if (fe->ioctl)
3229			retval = fe->ioctl(dev, cmd, addr, flag, td);
3230		else
3231			retval = ENODEV;
3232
3233		if (req->num_args > 0) {
3234			ctl_copyout_args(req->num_args, req->kern_args);
3235			ctl_free_args(req->num_args, req->kern_args);
3236		}
3237		break;
3238	}
3239	case CTL_PORT_LIST: {
3240		struct sbuf *sb;
3241		struct ctl_port *port;
3242		struct ctl_lun_list *list;
3243		struct ctl_option *opt;
3244		int j;
3245		uint32_t plun;
3246
3247		list = (struct ctl_lun_list *)addr;
3248
3249		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3250		if (sb == NULL) {
3251			list->status = CTL_LUN_LIST_ERROR;
3252			snprintf(list->error_str, sizeof(list->error_str),
3253				 "Unable to allocate %d bytes for LUN list",
3254				 list->alloc_len);
3255			break;
3256		}
3257
3258		sbuf_printf(sb, "<ctlportlist>\n");
3259
3260		mtx_lock(&softc->ctl_lock);
3261		STAILQ_FOREACH(port, &softc->port_list, links) {
3262			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3263					     (uintmax_t)port->targ_port);
3264
3265			/*
3266			 * Bail out as soon as we see that we've overfilled
3267			 * the buffer.
3268			 */
3269			if (retval != 0)
3270				break;
3271
3272			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3273			    "</frontend_type>\n", port->frontend->name);
3274			if (retval != 0)
3275				break;
3276
3277			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3278					     port->port_type);
3279			if (retval != 0)
3280				break;
3281
3282			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3283			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3284			if (retval != 0)
3285				break;
3286
3287			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3288			    port->port_name);
3289			if (retval != 0)
3290				break;
3291
3292			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3293			    port->physical_port);
3294			if (retval != 0)
3295				break;
3296
3297			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3298			    port->virtual_port);
3299			if (retval != 0)
3300				break;
3301
3302			if (port->target_devid != NULL) {
3303				sbuf_printf(sb, "\t<target>");
3304				ctl_id_sbuf(port->target_devid, sb);
3305				sbuf_printf(sb, "</target>\n");
3306			}
3307
3308			if (port->port_devid != NULL) {
3309				sbuf_printf(sb, "\t<port>");
3310				ctl_id_sbuf(port->port_devid, sb);
3311				sbuf_printf(sb, "</port>\n");
3312			}
3313
3314			if (port->port_info != NULL) {
3315				retval = port->port_info(port->onoff_arg, sb);
3316				if (retval != 0)
3317					break;
3318			}
3319			STAILQ_FOREACH(opt, &port->options, links) {
3320				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3321				    opt->name, opt->value, opt->name);
3322				if (retval != 0)
3323					break;
3324			}
3325
3326			if (port->lun_map != NULL) {
3327				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3328				for (j = 0; j < port->lun_map_size; j++) {
3329					plun = ctl_lun_map_from_port(port, j);
3330					if (plun == UINT32_MAX)
3331						continue;
3332					sbuf_printf(sb,
3333					    "\t<lun id=\"%u\">%u</lun>\n",
3334					    j, plun);
3335				}
3336			}
3337
3338			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3339				if (port->wwpn_iid[j].in_use == 0 ||
3340				    (port->wwpn_iid[j].wwpn == 0 &&
3341				     port->wwpn_iid[j].name == NULL))
3342					continue;
3343
3344				if (port->wwpn_iid[j].name != NULL)
3345					retval = sbuf_printf(sb,
3346					    "\t<initiator id=\"%u\">%s</initiator>\n",
3347					    j, port->wwpn_iid[j].name);
3348				else
3349					retval = sbuf_printf(sb,
3350					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3351					    j, port->wwpn_iid[j].wwpn);
3352				if (retval != 0)
3353					break;
3354			}
3355			if (retval != 0)
3356				break;
3357
3358			retval = sbuf_printf(sb, "</targ_port>\n");
3359			if (retval != 0)
3360				break;
3361		}
3362		mtx_unlock(&softc->ctl_lock);
3363
3364		if ((retval != 0)
3365		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3366			retval = 0;
3367			sbuf_delete(sb);
3368			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3369			snprintf(list->error_str, sizeof(list->error_str),
3370				 "Out of space, %d bytes is too small",
3371				 list->alloc_len);
3372			break;
3373		}
3374
3375		sbuf_finish(sb);
3376
3377		retval = copyout(sbuf_data(sb), list->lun_xml,
3378				 sbuf_len(sb) + 1);
3379
3380		list->fill_len = sbuf_len(sb) + 1;
3381		list->status = CTL_LUN_LIST_OK;
3382		sbuf_delete(sb);
3383		break;
3384	}
3385	case CTL_LUN_MAP: {
3386		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3387		struct ctl_port *port;
3388
3389		mtx_lock(&softc->ctl_lock);
3390		if (lm->port < softc->port_min ||
3391		    lm->port >= softc->port_max ||
3392		    (port = softc->ctl_ports[lm->port]) == NULL) {
3393			mtx_unlock(&softc->ctl_lock);
3394			return (ENXIO);
3395		}
3396		if (port->status & CTL_PORT_STATUS_ONLINE) {
3397			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3398				if (ctl_lun_map_to_port(port, lun->lun) ==
3399				    UINT32_MAX)
3400					continue;
3401				mtx_lock(&lun->lun_lock);
3402				ctl_est_ua_port(lun, lm->port, -1,
3403				    CTL_UA_LUN_CHANGE);
3404				mtx_unlock(&lun->lun_lock);
3405			}
3406		}
3407		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3408		if (lm->plun != UINT32_MAX) {
3409			if (lm->lun == UINT32_MAX)
3410				retval = ctl_lun_map_unset(port, lm->plun);
3411			else if (lm->lun < CTL_MAX_LUNS &&
3412			    softc->ctl_luns[lm->lun] != NULL)
3413				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3414			else
3415				return (ENXIO);
3416		} else {
3417			if (lm->lun == UINT32_MAX)
3418				retval = ctl_lun_map_deinit(port);
3419			else
3420				retval = ctl_lun_map_init(port);
3421		}
3422		if (port->status & CTL_PORT_STATUS_ONLINE)
3423			ctl_isc_announce_port(port);
3424		break;
3425	}
3426	case CTL_GET_LUN_STATS: {
3427		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3428		int i;
3429
3430		/*
3431		 * XXX KDM no locking here.  If the LUN list changes,
3432		 * things can blow up.
3433		 */
3434		i = 0;
3435		stats->status = CTL_SS_OK;
3436		stats->fill_len = 0;
3437		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3438			if (lun->lun < stats->first_item)
3439				continue;
3440			if (stats->fill_len + sizeof(lun->stats) >
3441			    stats->alloc_len) {
3442				stats->status = CTL_SS_NEED_MORE_SPACE;
3443				break;
3444			}
3445			retval = copyout(&lun->stats, &stats->stats[i++],
3446					 sizeof(lun->stats));
3447			if (retval != 0)
3448				break;
3449			stats->fill_len += sizeof(lun->stats);
3450		}
3451		stats->num_items = softc->num_luns;
3452		stats->flags = CTL_STATS_FLAG_NONE;
3453#ifdef CTL_TIME_IO
3454		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3455#endif
3456		getnanouptime(&stats->timestamp);
3457		break;
3458	}
3459	case CTL_GET_PORT_STATS: {
3460		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3461		int i;
3462
3463		/*
3464		 * XXX KDM no locking here.  If the LUN list changes,
3465		 * things can blow up.
3466		 */
3467		i = 0;
3468		stats->status = CTL_SS_OK;
3469		stats->fill_len = 0;
3470		STAILQ_FOREACH(port, &softc->port_list, links) {
3471			if (port->targ_port < stats->first_item)
3472				continue;
3473			if (stats->fill_len + sizeof(port->stats) >
3474			    stats->alloc_len) {
3475				stats->status = CTL_SS_NEED_MORE_SPACE;
3476				break;
3477			}
3478			retval = copyout(&port->stats, &stats->stats[i++],
3479					 sizeof(port->stats));
3480			if (retval != 0)
3481				break;
3482			stats->fill_len += sizeof(port->stats);
3483		}
3484		stats->num_items = softc->num_ports;
3485		stats->flags = CTL_STATS_FLAG_NONE;
3486#ifdef CTL_TIME_IO
3487		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3488#endif
3489		getnanouptime(&stats->timestamp);
3490		break;
3491	}
3492	default: {
3493		/* XXX KDM should we fix this? */
3494#if 0
3495		struct ctl_backend_driver *backend;
3496		unsigned int type;
3497		int found;
3498
3499		found = 0;
3500
3501		/*
3502		 * We encode the backend type as the ioctl type for backend
3503		 * ioctls.  So parse it out here, and then search for a
3504		 * backend of this type.
3505		 */
3506		type = _IOC_TYPE(cmd);
3507
3508		STAILQ_FOREACH(backend, &softc->be_list, links) {
3509			if (backend->type == type) {
3510				found = 1;
3511				break;
3512			}
3513		}
3514		if (found == 0) {
3515			printf("ctl: unknown ioctl command %#lx or backend "
3516			       "%d\n", cmd, type);
3517			retval = EINVAL;
3518			break;
3519		}
3520		retval = backend->ioctl(dev, cmd, addr, flag, td);
3521#endif
3522		retval = ENOTTY;
3523		break;
3524	}
3525	}
3526	return (retval);
3527}
3528
3529uint32_t
3530ctl_get_initindex(struct ctl_nexus *nexus)
3531{
3532	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3533}
3534
3535int
3536ctl_lun_map_init(struct ctl_port *port)
3537{
3538	struct ctl_softc *softc = port->ctl_softc;
3539	struct ctl_lun *lun;
3540	int size = ctl_lun_map_size;
3541	uint32_t i;
3542
3543	if (port->lun_map == NULL || port->lun_map_size < size) {
3544		port->lun_map_size = 0;
3545		free(port->lun_map, M_CTL);
3546		port->lun_map = malloc(size * sizeof(uint32_t),
3547		    M_CTL, M_NOWAIT);
3548	}
3549	if (port->lun_map == NULL)
3550		return (ENOMEM);
3551	for (i = 0; i < size; i++)
3552		port->lun_map[i] = UINT32_MAX;
3553	port->lun_map_size = size;
3554	if (port->status & CTL_PORT_STATUS_ONLINE) {
3555		if (port->lun_disable != NULL) {
3556			STAILQ_FOREACH(lun, &softc->lun_list, links)
3557				port->lun_disable(port->targ_lun_arg, lun->lun);
3558		}
3559		ctl_isc_announce_port(port);
3560	}
3561	return (0);
3562}
3563
3564int
3565ctl_lun_map_deinit(struct ctl_port *port)
3566{
3567	struct ctl_softc *softc = port->ctl_softc;
3568	struct ctl_lun *lun;
3569
3570	if (port->lun_map == NULL)
3571		return (0);
3572	port->lun_map_size = 0;
3573	free(port->lun_map, M_CTL);
3574	port->lun_map = NULL;
3575	if (port->status & CTL_PORT_STATUS_ONLINE) {
3576		if (port->lun_enable != NULL) {
3577			STAILQ_FOREACH(lun, &softc->lun_list, links)
3578				port->lun_enable(port->targ_lun_arg, lun->lun);
3579		}
3580		ctl_isc_announce_port(port);
3581	}
3582	return (0);
3583}
3584
3585int
3586ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3587{
3588	int status;
3589	uint32_t old;
3590
3591	if (port->lun_map == NULL) {
3592		status = ctl_lun_map_init(port);
3593		if (status != 0)
3594			return (status);
3595	}
3596	if (plun >= port->lun_map_size)
3597		return (EINVAL);
3598	old = port->lun_map[plun];
3599	port->lun_map[plun] = glun;
3600	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3601		if (port->lun_enable != NULL)
3602			port->lun_enable(port->targ_lun_arg, plun);
3603		ctl_isc_announce_port(port);
3604	}
3605	return (0);
3606}
3607
3608int
3609ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3610{
3611	uint32_t old;
3612
3613	if (port->lun_map == NULL || plun >= port->lun_map_size)
3614		return (0);
3615	old = port->lun_map[plun];
3616	port->lun_map[plun] = UINT32_MAX;
3617	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3618		if (port->lun_disable != NULL)
3619			port->lun_disable(port->targ_lun_arg, plun);
3620		ctl_isc_announce_port(port);
3621	}
3622	return (0);
3623}
3624
3625uint32_t
3626ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3627{
3628
3629	if (port == NULL)
3630		return (UINT32_MAX);
3631	if (port->lun_map == NULL)
3632		return (lun_id);
3633	if (lun_id > port->lun_map_size)
3634		return (UINT32_MAX);
3635	return (port->lun_map[lun_id]);
3636}
3637
3638uint32_t
3639ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3640{
3641	uint32_t i;
3642
3643	if (port == NULL)
3644		return (UINT32_MAX);
3645	if (port->lun_map == NULL)
3646		return (lun_id);
3647	for (i = 0; i < port->lun_map_size; i++) {
3648		if (port->lun_map[i] == lun_id)
3649			return (i);
3650	}
3651	return (UINT32_MAX);
3652}
3653
3654uint32_t
3655ctl_decode_lun(uint64_t encoded)
3656{
3657	uint8_t lun[8];
3658	uint32_t result = 0xffffffff;
3659
3660	be64enc(lun, encoded);
3661	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3662	case RPL_LUNDATA_ATYP_PERIPH:
3663		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3664		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3665			result = lun[1];
3666		break;
3667	case RPL_LUNDATA_ATYP_FLAT:
3668		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3669		    lun[6] == 0 && lun[7] == 0)
3670			result = ((lun[0] & 0x3f) << 8) + lun[1];
3671		break;
3672	case RPL_LUNDATA_ATYP_EXTLUN:
3673		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3674		case 0x02:
3675			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3676			case 0x00:
3677				result = lun[1];
3678				break;
3679			case 0x10:
3680				result = (lun[1] << 16) + (lun[2] << 8) +
3681				    lun[3];
3682				break;
3683			case 0x20:
3684				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3685					result = (lun[2] << 24) +
3686					    (lun[3] << 16) + (lun[4] << 8) +
3687					    lun[5];
3688				break;
3689			}
3690			break;
3691		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3692			result = 0xffffffff;
3693			break;
3694		}
3695		break;
3696	}
3697	return (result);
3698}
3699
3700uint64_t
3701ctl_encode_lun(uint32_t decoded)
3702{
3703	uint64_t l = decoded;
3704
3705	if (l <= 0xff)
3706		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3707	if (l <= 0x3fff)
3708		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3709	if (l <= 0xffffff)
3710		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3711		    (l << 32));
3712	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3713}
3714
3715int
3716ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3717{
3718	int i;
3719
3720	for (i = first; i < last; i++) {
3721		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3722			return (i);
3723	}
3724	return (-1);
3725}
3726
3727int
3728ctl_set_mask(uint32_t *mask, uint32_t bit)
3729{
3730	uint32_t chunk, piece;
3731
3732	chunk = bit >> 5;
3733	piece = bit % (sizeof(uint32_t) * 8);
3734
3735	if ((mask[chunk] & (1 << piece)) != 0)
3736		return (-1);
3737	else
3738		mask[chunk] |= (1 << piece);
3739
3740	return (0);
3741}
3742
3743int
3744ctl_clear_mask(uint32_t *mask, uint32_t bit)
3745{
3746	uint32_t chunk, piece;
3747
3748	chunk = bit >> 5;
3749	piece = bit % (sizeof(uint32_t) * 8);
3750
3751	if ((mask[chunk] & (1 << piece)) == 0)
3752		return (-1);
3753	else
3754		mask[chunk] &= ~(1 << piece);
3755
3756	return (0);
3757}
3758
3759int
3760ctl_is_set(uint32_t *mask, uint32_t bit)
3761{
3762	uint32_t chunk, piece;
3763
3764	chunk = bit >> 5;
3765	piece = bit % (sizeof(uint32_t) * 8);
3766
3767	if ((mask[chunk] & (1 << piece)) == 0)
3768		return (0);
3769	else
3770		return (1);
3771}
3772
3773static uint64_t
3774ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3775{
3776	uint64_t *t;
3777
3778	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3779	if (t == NULL)
3780		return (0);
3781	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3782}
3783
3784static void
3785ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3786{
3787	uint64_t *t;
3788
3789	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3790	if (t == NULL)
3791		return;
3792	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3793}
3794
3795static void
3796ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3797{
3798	uint64_t *p;
3799	u_int i;
3800
3801	i = residx/CTL_MAX_INIT_PER_PORT;
3802	if (lun->pr_keys[i] != NULL)
3803		return;
3804	mtx_unlock(&lun->lun_lock);
3805	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3806	    M_WAITOK | M_ZERO);
3807	mtx_lock(&lun->lun_lock);
3808	if (lun->pr_keys[i] == NULL)
3809		lun->pr_keys[i] = p;
3810	else
3811		free(p, M_CTL);
3812}
3813
3814static void
3815ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3816{
3817	uint64_t *t;
3818
3819	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3820	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3821	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3822}
3823
3824/*
3825 * ctl_softc, pool_name, total_ctl_io are passed in.
3826 * npool is passed out.
3827 */
3828int
3829ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3830		uint32_t total_ctl_io, void **npool)
3831{
3832	struct ctl_io_pool *pool;
3833
3834	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3835					    M_NOWAIT | M_ZERO);
3836	if (pool == NULL)
3837		return (ENOMEM);
3838
3839	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3840	pool->ctl_softc = ctl_softc;
3841#ifdef IO_POOLS
3842	pool->zone = uma_zsecond_create(pool->name, NULL,
3843	    NULL, NULL, NULL, ctl_softc->io_zone);
3844	/* uma_prealloc(pool->zone, total_ctl_io); */
3845#else
3846	pool->zone = ctl_softc->io_zone;
3847#endif
3848
3849	*npool = pool;
3850	return (0);
3851}
3852
3853void
3854ctl_pool_free(struct ctl_io_pool *pool)
3855{
3856
3857	if (pool == NULL)
3858		return;
3859
3860#ifdef IO_POOLS
3861	uma_zdestroy(pool->zone);
3862#endif
3863	free(pool, M_CTL);
3864}
3865
3866union ctl_io *
3867ctl_alloc_io(void *pool_ref)
3868{
3869	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3870	union ctl_io *io;
3871
3872	io = uma_zalloc(pool->zone, M_WAITOK);
3873	if (io != NULL) {
3874		io->io_hdr.pool = pool_ref;
3875		CTL_SOFTC(io) = pool->ctl_softc;
3876	}
3877	return (io);
3878}
3879
3880union ctl_io *
3881ctl_alloc_io_nowait(void *pool_ref)
3882{
3883	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3884	union ctl_io *io;
3885
3886	io = uma_zalloc(pool->zone, M_NOWAIT);
3887	if (io != NULL) {
3888		io->io_hdr.pool = pool_ref;
3889		CTL_SOFTC(io) = pool->ctl_softc;
3890	}
3891	return (io);
3892}
3893
3894void
3895ctl_free_io(union ctl_io *io)
3896{
3897	struct ctl_io_pool *pool;
3898
3899	if (io == NULL)
3900		return;
3901
3902	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3903	uma_zfree(pool->zone, io);
3904}
3905
3906void
3907ctl_zero_io(union ctl_io *io)
3908{
3909	struct ctl_io_pool *pool;
3910
3911	if (io == NULL)
3912		return;
3913
3914	/*
3915	 * May need to preserve linked list pointers at some point too.
3916	 */
3917	pool = io->io_hdr.pool;
3918	memset(io, 0, sizeof(*io));
3919	io->io_hdr.pool = pool;
3920	CTL_SOFTC(io) = pool->ctl_softc;
3921}
3922
3923int
3924ctl_expand_number(const char *buf, uint64_t *num)
3925{
3926	char *endptr;
3927	uint64_t number;
3928	unsigned shift;
3929
3930	number = strtoq(buf, &endptr, 0);
3931
3932	switch (tolower((unsigned char)*endptr)) {
3933	case 'e':
3934		shift = 60;
3935		break;
3936	case 'p':
3937		shift = 50;
3938		break;
3939	case 't':
3940		shift = 40;
3941		break;
3942	case 'g':
3943		shift = 30;
3944		break;
3945	case 'm':
3946		shift = 20;
3947		break;
3948	case 'k':
3949		shift = 10;
3950		break;
3951	case 'b':
3952	case '\0': /* No unit. */
3953		*num = number;
3954		return (0);
3955	default:
3956		/* Unrecognized unit. */
3957		return (-1);
3958	}
3959
3960	if ((number << shift) >> shift != number) {
3961		/* Overflow */
3962		return (-1);
3963	}
3964	*num = number << shift;
3965	return (0);
3966}
3967
3968
3969/*
3970 * This routine could be used in the future to load default and/or saved
3971 * mode page parameters for a particuar lun.
3972 */
3973static int
3974ctl_init_page_index(struct ctl_lun *lun)
3975{
3976	int i, page_code;
3977	struct ctl_page_index *page_index;
3978	const char *value;
3979	uint64_t ival;
3980
3981	memcpy(&lun->mode_pages.index, page_index_template,
3982	       sizeof(page_index_template));
3983
3984	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3985
3986		page_index = &lun->mode_pages.index[i];
3987		if (lun->be_lun->lun_type == T_DIRECT &&
3988		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3989			continue;
3990		if (lun->be_lun->lun_type == T_PROCESSOR &&
3991		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3992			continue;
3993		if (lun->be_lun->lun_type == T_CDROM &&
3994		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3995			continue;
3996
3997		page_code = page_index->page_code & SMPH_PC_MASK;
3998		switch (page_code) {
3999		case SMS_RW_ERROR_RECOVERY_PAGE: {
4000			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4001			    ("subpage %#x for page %#x is incorrect!",
4002			    page_index->subpage, page_code));
4003			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4004			       &rw_er_page_default,
4005			       sizeof(rw_er_page_default));
4006			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4007			       &rw_er_page_changeable,
4008			       sizeof(rw_er_page_changeable));
4009			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4010			       &rw_er_page_default,
4011			       sizeof(rw_er_page_default));
4012			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4013			       &rw_er_page_default,
4014			       sizeof(rw_er_page_default));
4015			page_index->page_data =
4016				(uint8_t *)lun->mode_pages.rw_er_page;
4017			break;
4018		}
4019		case SMS_FORMAT_DEVICE_PAGE: {
4020			struct scsi_format_page *format_page;
4021
4022			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4023			    ("subpage %#x for page %#x is incorrect!",
4024			    page_index->subpage, page_code));
4025
4026			/*
4027			 * Sectors per track are set above.  Bytes per
4028			 * sector need to be set here on a per-LUN basis.
4029			 */
4030			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4031			       &format_page_default,
4032			       sizeof(format_page_default));
4033			memcpy(&lun->mode_pages.format_page[
4034			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4035			       sizeof(format_page_changeable));
4036			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4037			       &format_page_default,
4038			       sizeof(format_page_default));
4039			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4040			       &format_page_default,
4041			       sizeof(format_page_default));
4042
4043			format_page = &lun->mode_pages.format_page[
4044				CTL_PAGE_CURRENT];
4045			scsi_ulto2b(lun->be_lun->blocksize,
4046				    format_page->bytes_per_sector);
4047
4048			format_page = &lun->mode_pages.format_page[
4049				CTL_PAGE_DEFAULT];
4050			scsi_ulto2b(lun->be_lun->blocksize,
4051				    format_page->bytes_per_sector);
4052
4053			format_page = &lun->mode_pages.format_page[
4054				CTL_PAGE_SAVED];
4055			scsi_ulto2b(lun->be_lun->blocksize,
4056				    format_page->bytes_per_sector);
4057
4058			page_index->page_data =
4059				(uint8_t *)lun->mode_pages.format_page;
4060			break;
4061		}
4062		case SMS_RIGID_DISK_PAGE: {
4063			struct scsi_rigid_disk_page *rigid_disk_page;
4064			uint32_t sectors_per_cylinder;
4065			uint64_t cylinders;
4066#ifndef	__XSCALE__
4067			int shift;
4068#endif /* !__XSCALE__ */
4069
4070			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4071			    ("subpage %#x for page %#x is incorrect!",
4072			    page_index->subpage, page_code));
4073
4074			/*
4075			 * Rotation rate and sectors per track are set
4076			 * above.  We calculate the cylinders here based on
4077			 * capacity.  Due to the number of heads and
4078			 * sectors per track we're using, smaller arrays
4079			 * may turn out to have 0 cylinders.  Linux and
4080			 * FreeBSD don't pay attention to these mode pages
4081			 * to figure out capacity, but Solaris does.  It
4082			 * seems to deal with 0 cylinders just fine, and
4083			 * works out a fake geometry based on the capacity.
4084			 */
4085			memcpy(&lun->mode_pages.rigid_disk_page[
4086			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4087			       sizeof(rigid_disk_page_default));
4088			memcpy(&lun->mode_pages.rigid_disk_page[
4089			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4090			       sizeof(rigid_disk_page_changeable));
4091
4092			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4093				CTL_DEFAULT_HEADS;
4094
4095			/*
4096			 * The divide method here will be more accurate,
4097			 * probably, but results in floating point being
4098			 * used in the kernel on i386 (__udivdi3()).  On the
4099			 * XScale, though, __udivdi3() is implemented in
4100			 * software.
4101			 *
4102			 * The shift method for cylinder calculation is
4103			 * accurate if sectors_per_cylinder is a power of
4104			 * 2.  Otherwise it might be slightly off -- you
4105			 * might have a bit of a truncation problem.
4106			 */
4107#ifdef	__XSCALE__
4108			cylinders = (lun->be_lun->maxlba + 1) /
4109				sectors_per_cylinder;
4110#else
4111			for (shift = 31; shift > 0; shift--) {
4112				if (sectors_per_cylinder & (1 << shift))
4113					break;
4114			}
4115			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4116#endif
4117
4118			/*
4119			 * We've basically got 3 bytes, or 24 bits for the
4120			 * cylinder size in the mode page.  If we're over,
4121			 * just round down to 2^24.
4122			 */
4123			if (cylinders > 0xffffff)
4124				cylinders = 0xffffff;
4125
4126			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4127				CTL_PAGE_DEFAULT];
4128			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4129
4130			if ((value = ctl_get_opt(&lun->be_lun->options,
4131			    "rpm")) != NULL) {
4132				scsi_ulto2b(strtol(value, NULL, 0),
4133				     rigid_disk_page->rotation_rate);
4134			}
4135
4136			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4137			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4138			       sizeof(rigid_disk_page_default));
4139			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4140			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4141			       sizeof(rigid_disk_page_default));
4142
4143			page_index->page_data =
4144				(uint8_t *)lun->mode_pages.rigid_disk_page;
4145			break;
4146		}
4147		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4148			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4149			    ("subpage %#x for page %#x is incorrect!",
4150			    page_index->subpage, page_code));
4151			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4152			       &verify_er_page_default,
4153			       sizeof(verify_er_page_default));
4154			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4155			       &verify_er_page_changeable,
4156			       sizeof(verify_er_page_changeable));
4157			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4158			       &verify_er_page_default,
4159			       sizeof(verify_er_page_default));
4160			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4161			       &verify_er_page_default,
4162			       sizeof(verify_er_page_default));
4163			page_index->page_data =
4164				(uint8_t *)lun->mode_pages.verify_er_page;
4165			break;
4166		}
4167		case SMS_CACHING_PAGE: {
4168			struct scsi_caching_page *caching_page;
4169
4170			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4171			    ("subpage %#x for page %#x is incorrect!",
4172			    page_index->subpage, page_code));
4173			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4174			       &caching_page_default,
4175			       sizeof(caching_page_default));
4176			memcpy(&lun->mode_pages.caching_page[
4177			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4178			       sizeof(caching_page_changeable));
4179			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4180			       &caching_page_default,
4181			       sizeof(caching_page_default));
4182			caching_page = &lun->mode_pages.caching_page[
4183			    CTL_PAGE_SAVED];
4184			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4185			if (value != NULL && strcmp(value, "off") == 0)
4186				caching_page->flags1 &= ~SCP_WCE;
4187			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4188			if (value != NULL && strcmp(value, "off") == 0)
4189				caching_page->flags1 |= SCP_RCD;
4190			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4191			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4192			       sizeof(caching_page_default));
4193			page_index->page_data =
4194				(uint8_t *)lun->mode_pages.caching_page;
4195			break;
4196		}
4197		case SMS_CONTROL_MODE_PAGE: {
4198			switch (page_index->subpage) {
4199			case SMS_SUBPAGE_PAGE_0: {
4200				struct scsi_control_page *control_page;
4201
4202				memcpy(&lun->mode_pages.control_page[
4203				    CTL_PAGE_DEFAULT],
4204				       &control_page_default,
4205				       sizeof(control_page_default));
4206				memcpy(&lun->mode_pages.control_page[
4207				    CTL_PAGE_CHANGEABLE],
4208				       &control_page_changeable,
4209				       sizeof(control_page_changeable));
4210				memcpy(&lun->mode_pages.control_page[
4211				    CTL_PAGE_SAVED],
4212				       &control_page_default,
4213				       sizeof(control_page_default));
4214				control_page = &lun->mode_pages.control_page[
4215				    CTL_PAGE_SAVED];
4216				value = ctl_get_opt(&lun->be_lun->options,
4217				    "reordering");
4218				if (value != NULL &&
4219				    strcmp(value, "unrestricted") == 0) {
4220					control_page->queue_flags &=
4221					    ~SCP_QUEUE_ALG_MASK;
4222					control_page->queue_flags |=
4223					    SCP_QUEUE_ALG_UNRESTRICTED;
4224				}
4225				memcpy(&lun->mode_pages.control_page[
4226				    CTL_PAGE_CURRENT],
4227				       &lun->mode_pages.control_page[
4228				    CTL_PAGE_SAVED],
4229				       sizeof(control_page_default));
4230				page_index->page_data =
4231				    (uint8_t *)lun->mode_pages.control_page;
4232				break;
4233			}
4234			case 0x01:
4235				memcpy(&lun->mode_pages.control_ext_page[
4236				    CTL_PAGE_DEFAULT],
4237				       &control_ext_page_default,
4238				       sizeof(control_ext_page_default));
4239				memcpy(&lun->mode_pages.control_ext_page[
4240				    CTL_PAGE_CHANGEABLE],
4241				       &control_ext_page_changeable,
4242				       sizeof(control_ext_page_changeable));
4243				memcpy(&lun->mode_pages.control_ext_page[
4244				    CTL_PAGE_SAVED],
4245				       &control_ext_page_default,
4246				       sizeof(control_ext_page_default));
4247				memcpy(&lun->mode_pages.control_ext_page[
4248				    CTL_PAGE_CURRENT],
4249				       &lun->mode_pages.control_ext_page[
4250				    CTL_PAGE_SAVED],
4251				       sizeof(control_ext_page_default));
4252				page_index->page_data =
4253				    (uint8_t *)lun->mode_pages.control_ext_page;
4254				break;
4255			default:
4256				panic("subpage %#x for page %#x is incorrect!",
4257				      page_index->subpage, page_code);
4258			}
4259			break;
4260		}
4261		case SMS_INFO_EXCEPTIONS_PAGE: {
4262			switch (page_index->subpage) {
4263			case SMS_SUBPAGE_PAGE_0:
4264				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4265				       &ie_page_default,
4266				       sizeof(ie_page_default));
4267				memcpy(&lun->mode_pages.ie_page[
4268				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4269				       sizeof(ie_page_changeable));
4270				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4271				       &ie_page_default,
4272				       sizeof(ie_page_default));
4273				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4274				       &ie_page_default,
4275				       sizeof(ie_page_default));
4276				page_index->page_data =
4277					(uint8_t *)lun->mode_pages.ie_page;
4278				break;
4279			case 0x02: {
4280				struct ctl_logical_block_provisioning_page *page;
4281
4282				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4283				       &lbp_page_default,
4284				       sizeof(lbp_page_default));
4285				memcpy(&lun->mode_pages.lbp_page[
4286				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4287				       sizeof(lbp_page_changeable));
4288				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4289				       &lbp_page_default,
4290				       sizeof(lbp_page_default));
4291				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4292				value = ctl_get_opt(&lun->be_lun->options,
4293				    "avail-threshold");
4294				if (value != NULL &&
4295				    ctl_expand_number(value, &ival) == 0) {
4296					page->descr[0].flags |= SLBPPD_ENABLED |
4297					    SLBPPD_ARMING_DEC;
4298					if (lun->be_lun->blocksize)
4299						ival /= lun->be_lun->blocksize;
4300					else
4301						ival /= 512;
4302					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4303					    page->descr[0].count);
4304				}
4305				value = ctl_get_opt(&lun->be_lun->options,
4306				    "used-threshold");
4307				if (value != NULL &&
4308				    ctl_expand_number(value, &ival) == 0) {
4309					page->descr[1].flags |= SLBPPD_ENABLED |
4310					    SLBPPD_ARMING_INC;
4311					if (lun->be_lun->blocksize)
4312						ival /= lun->be_lun->blocksize;
4313					else
4314						ival /= 512;
4315					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4316					    page->descr[1].count);
4317				}
4318				value = ctl_get_opt(&lun->be_lun->options,
4319				    "pool-avail-threshold");
4320				if (value != NULL &&
4321				    ctl_expand_number(value, &ival) == 0) {
4322					page->descr[2].flags |= SLBPPD_ENABLED |
4323					    SLBPPD_ARMING_DEC;
4324					if (lun->be_lun->blocksize)
4325						ival /= lun->be_lun->blocksize;
4326					else
4327						ival /= 512;
4328					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4329					    page->descr[2].count);
4330				}
4331				value = ctl_get_opt(&lun->be_lun->options,
4332				    "pool-used-threshold");
4333				if (value != NULL &&
4334				    ctl_expand_number(value, &ival) == 0) {
4335					page->descr[3].flags |= SLBPPD_ENABLED |
4336					    SLBPPD_ARMING_INC;
4337					if (lun->be_lun->blocksize)
4338						ival /= lun->be_lun->blocksize;
4339					else
4340						ival /= 512;
4341					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4342					    page->descr[3].count);
4343				}
4344				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4345				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4346				       sizeof(lbp_page_default));
4347				page_index->page_data =
4348					(uint8_t *)lun->mode_pages.lbp_page;
4349				break;
4350			}
4351			default:
4352				panic("subpage %#x for page %#x is incorrect!",
4353				      page_index->subpage, page_code);
4354			}
4355			break;
4356		}
4357		case SMS_CDDVD_CAPS_PAGE:{
4358			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4359			    ("subpage %#x for page %#x is incorrect!",
4360			    page_index->subpage, page_code));
4361			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4362			       &cddvd_page_default,
4363			       sizeof(cddvd_page_default));
4364			memcpy(&lun->mode_pages.cddvd_page[
4365			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4366			       sizeof(cddvd_page_changeable));
4367			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4368			       &cddvd_page_default,
4369			       sizeof(cddvd_page_default));
4370			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4371			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4372			       sizeof(cddvd_page_default));
4373			page_index->page_data =
4374				(uint8_t *)lun->mode_pages.cddvd_page;
4375			break;
4376		}
4377		default:
4378			panic("invalid page code value %#x", page_code);
4379		}
4380	}
4381
4382	return (CTL_RETVAL_COMPLETE);
4383}
4384
4385static int
4386ctl_init_log_page_index(struct ctl_lun *lun)
4387{
4388	struct ctl_page_index *page_index;
4389	int i, j, k, prev;
4390
4391	memcpy(&lun->log_pages.index, log_page_index_template,
4392	       sizeof(log_page_index_template));
4393
4394	prev = -1;
4395	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4396
4397		page_index = &lun->log_pages.index[i];
4398		if (lun->be_lun->lun_type == T_DIRECT &&
4399		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4400			continue;
4401		if (lun->be_lun->lun_type == T_PROCESSOR &&
4402		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4403			continue;
4404		if (lun->be_lun->lun_type == T_CDROM &&
4405		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4406			continue;
4407
4408		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4409		    lun->backend->lun_attr == NULL)
4410			continue;
4411
4412		if (page_index->page_code != prev) {
4413			lun->log_pages.pages_page[j] = page_index->page_code;
4414			prev = page_index->page_code;
4415			j++;
4416		}
4417		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4418		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4419		k++;
4420	}
4421	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4422	lun->log_pages.index[0].page_len = j;
4423	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4424	lun->log_pages.index[1].page_len = k * 2;
4425	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4426	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4427	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4428	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4429	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4430	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4431
4432	return (CTL_RETVAL_COMPLETE);
4433}
4434
4435static int
4436hex2bin(const char *str, uint8_t *buf, int buf_size)
4437{
4438	int i;
4439	u_char c;
4440
4441	memset(buf, 0, buf_size);
4442	while (isspace(str[0]))
4443		str++;
4444	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4445		str += 2;
4446	buf_size *= 2;
4447	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4448		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4449			str++;
4450		c = str[i];
4451		if (isdigit(c))
4452			c -= '0';
4453		else if (isalpha(c))
4454			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4455		else
4456			break;
4457		if (c >= 16)
4458			break;
4459		if ((i & 1) == 0)
4460			buf[i / 2] |= (c << 4);
4461		else
4462			buf[i / 2] |= c;
4463	}
4464	return ((i + 1) / 2);
4465}
4466
4467/*
4468 * LUN allocation.
4469 *
4470 * Requirements:
4471 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4472 *   wants us to allocate the LUN and he can block.
4473 * - ctl_softc is always set
4474 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4475 *
4476 * Returns 0 for success, non-zero (errno) for failure.
4477 */
4478static int
4479ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4480	      struct ctl_be_lun *const be_lun)
4481{
4482	struct ctl_lun *nlun, *lun;
4483	struct scsi_vpd_id_descriptor *desc;
4484	struct scsi_vpd_id_t10 *t10id;
4485	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4486	int lun_number, lun_malloced;
4487	int devidlen, idlen1, idlen2 = 0, len;
4488
4489	if (be_lun == NULL)
4490		return (EINVAL);
4491
4492	/*
4493	 * We currently only support Direct Access or Processor LUN types.
4494	 */
4495	switch (be_lun->lun_type) {
4496	case T_DIRECT:
4497	case T_PROCESSOR:
4498	case T_CDROM:
4499		break;
4500	case T_SEQUENTIAL:
4501	case T_CHANGER:
4502	default:
4503		be_lun->lun_config_status(be_lun->be_lun,
4504					  CTL_LUN_CONFIG_FAILURE);
4505		break;
4506	}
4507	if (ctl_lun == NULL) {
4508		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4509		lun_malloced = 1;
4510	} else {
4511		lun_malloced = 0;
4512		lun = ctl_lun;
4513	}
4514
4515	memset(lun, 0, sizeof(*lun));
4516	if (lun_malloced)
4517		lun->flags = CTL_LUN_MALLOCED;
4518
4519	/* Generate LUN ID. */
4520	devidlen = max(CTL_DEVID_MIN_LEN,
4521	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4522	idlen1 = sizeof(*t10id) + devidlen;
4523	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4524	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4525	if (scsiname != NULL) {
4526		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4527		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4528	}
4529	eui = ctl_get_opt(&be_lun->options, "eui");
4530	if (eui != NULL) {
4531		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4532	}
4533	naa = ctl_get_opt(&be_lun->options, "naa");
4534	if (naa != NULL) {
4535		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4536	}
4537	uuid = ctl_get_opt(&be_lun->options, "uuid");
4538	if (uuid != NULL) {
4539		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4540	}
4541	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4542	    M_CTL, M_WAITOK | M_ZERO);
4543	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4544	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4545	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4546	desc->length = idlen1;
4547	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4548	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4549	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4550		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4551	} else {
4552		strncpy(t10id->vendor, vendor,
4553		    min(sizeof(t10id->vendor), strlen(vendor)));
4554	}
4555	strncpy((char *)t10id->vendor_spec_id,
4556	    (char *)be_lun->device_id, devidlen);
4557	if (scsiname != NULL) {
4558		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4559		    desc->length);
4560		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4561		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4562		    SVPD_ID_TYPE_SCSI_NAME;
4563		desc->length = idlen2;
4564		strlcpy(desc->identifier, scsiname, idlen2);
4565	}
4566	if (eui != NULL) {
4567		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4568		    desc->length);
4569		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4570		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4571		    SVPD_ID_TYPE_EUI64;
4572		desc->length = hex2bin(eui, desc->identifier, 16);
4573		desc->length = desc->length > 12 ? 16 :
4574		    (desc->length > 8 ? 12 : 8);
4575		len -= 16 - desc->length;
4576	}
4577	if (naa != NULL) {
4578		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4579		    desc->length);
4580		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4581		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4582		    SVPD_ID_TYPE_NAA;
4583		desc->length = hex2bin(naa, desc->identifier, 16);
4584		desc->length = desc->length > 8 ? 16 : 8;
4585		len -= 16 - desc->length;
4586	}
4587	if (uuid != NULL) {
4588		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4589		    desc->length);
4590		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4591		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4592		    SVPD_ID_TYPE_UUID;
4593		desc->identifier[0] = 0x10;
4594		hex2bin(uuid, &desc->identifier[2], 16);
4595		desc->length = 18;
4596	}
4597	lun->lun_devid->len = len;
4598
4599	mtx_lock(&ctl_softc->ctl_lock);
4600	/*
4601	 * See if the caller requested a particular LUN number.  If so, see
4602	 * if it is available.  Otherwise, allocate the first available LUN.
4603	 */
4604	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4605		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4606		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4607			mtx_unlock(&ctl_softc->ctl_lock);
4608			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4609				printf("ctl: requested LUN ID %d is higher "
4610				       "than CTL_MAX_LUNS - 1 (%d)\n",
4611				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4612			} else {
4613				/*
4614				 * XXX KDM return an error, or just assign
4615				 * another LUN ID in this case??
4616				 */
4617				printf("ctl: requested LUN ID %d is already "
4618				       "in use\n", be_lun->req_lun_id);
4619			}
4620fail:
4621			free(lun->lun_devid, M_CTL);
4622			if (lun->flags & CTL_LUN_MALLOCED)
4623				free(lun, M_CTL);
4624			be_lun->lun_config_status(be_lun->be_lun,
4625						  CTL_LUN_CONFIG_FAILURE);
4626			return (ENOSPC);
4627		}
4628		lun_number = be_lun->req_lun_id;
4629	} else {
4630		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4631		if (lun_number == -1) {
4632			mtx_unlock(&ctl_softc->ctl_lock);
4633			printf("ctl: can't allocate LUN, out of LUNs\n");
4634			goto fail;
4635		}
4636	}
4637	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4638	mtx_unlock(&ctl_softc->ctl_lock);
4639
4640	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4641	lun->lun = lun_number;
4642	lun->be_lun = be_lun;
4643	/*
4644	 * The processor LUN is always enabled.  Disk LUNs come on line
4645	 * disabled, and must be enabled by the backend.
4646	 */
4647	lun->flags |= CTL_LUN_DISABLED;
4648	lun->backend = be_lun->be;
4649	be_lun->ctl_lun = lun;
4650	be_lun->lun_id = lun_number;
4651	atomic_add_int(&be_lun->be->num_luns, 1);
4652	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4653		lun->flags |= CTL_LUN_EJECTED;
4654	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4655		lun->flags |= CTL_LUN_NO_MEDIA;
4656	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4657		lun->flags |= CTL_LUN_STOPPED;
4658
4659	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4660		lun->flags |= CTL_LUN_PRIMARY_SC;
4661
4662	value = ctl_get_opt(&be_lun->options, "removable");
4663	if (value != NULL) {
4664		if (strcmp(value, "on") == 0)
4665			lun->flags |= CTL_LUN_REMOVABLE;
4666	} else if (be_lun->lun_type == T_CDROM)
4667		lun->flags |= CTL_LUN_REMOVABLE;
4668
4669	lun->ctl_softc = ctl_softc;
4670#ifdef CTL_TIME_IO
4671	lun->last_busy = getsbinuptime();
4672#endif
4673	TAILQ_INIT(&lun->ooa_queue);
4674	TAILQ_INIT(&lun->blocked_queue);
4675	STAILQ_INIT(&lun->error_list);
4676	lun->ie_reported = 1;
4677	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4678	ctl_tpc_lun_init(lun);
4679	if (lun->flags & CTL_LUN_REMOVABLE) {
4680		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4681		    M_CTL, M_WAITOK);
4682	}
4683
4684	/*
4685	 * Initialize the mode and log page index.
4686	 */
4687	ctl_init_page_index(lun);
4688	ctl_init_log_page_index(lun);
4689
4690	/* Setup statistics gathering */
4691#ifdef CTL_LEGACY_STATS
4692	lun->legacy_stats.device_type = be_lun->lun_type;
4693	lun->legacy_stats.lun_number = lun_number;
4694	lun->legacy_stats.blocksize = be_lun->blocksize;
4695	if (be_lun->blocksize == 0)
4696		lun->legacy_stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4697	for (len = 0; len < CTL_MAX_PORTS; len++)
4698		lun->legacy_stats.ports[len].targ_port = len;
4699#endif /* CTL_LEGACY_STATS */
4700	lun->stats.item = lun_number;
4701
4702	/*
4703	 * Now, before we insert this lun on the lun list, set the lun
4704	 * inventory changed UA for all other luns.
4705	 */
4706	mtx_lock(&ctl_softc->ctl_lock);
4707	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4708		mtx_lock(&nlun->lun_lock);
4709		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4710		mtx_unlock(&nlun->lun_lock);
4711	}
4712	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4713	ctl_softc->ctl_luns[lun_number] = lun;
4714	ctl_softc->num_luns++;
4715	mtx_unlock(&ctl_softc->ctl_lock);
4716
4717	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4718	return (0);
4719}
4720
4721/*
4722 * Delete a LUN.
4723 * Assumptions:
4724 * - LUN has already been marked invalid and any pending I/O has been taken
4725 *   care of.
4726 */
4727static int
4728ctl_free_lun(struct ctl_lun *lun)
4729{
4730	struct ctl_softc *softc = lun->ctl_softc;
4731	struct ctl_lun *nlun;
4732	int i;
4733
4734	KASSERT(TAILQ_EMPTY(&lun->ooa_queue),
4735	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4736
4737	mtx_lock(&softc->ctl_lock);
4738	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4739	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4740	softc->ctl_luns[lun->lun] = NULL;
4741	softc->num_luns--;
4742	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4743		mtx_lock(&nlun->lun_lock);
4744		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4745		mtx_unlock(&nlun->lun_lock);
4746	}
4747	mtx_unlock(&softc->ctl_lock);
4748
4749	/*
4750	 * Tell the backend to free resources, if this LUN has a backend.
4751	 */
4752	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4753	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4754
4755	lun->ie_reportcnt = UINT32_MAX;
4756	callout_drain(&lun->ie_callout);
4757	ctl_tpc_lun_shutdown(lun);
4758	mtx_destroy(&lun->lun_lock);
4759	free(lun->lun_devid, M_CTL);
4760	for (i = 0; i < CTL_MAX_PORTS; i++)
4761		free(lun->pending_ua[i], M_CTL);
4762	for (i = 0; i < CTL_MAX_PORTS; i++)
4763		free(lun->pr_keys[i], M_CTL);
4764	free(lun->write_buffer, M_CTL);
4765	free(lun->prevent, M_CTL);
4766	if (lun->flags & CTL_LUN_MALLOCED)
4767		free(lun, M_CTL);
4768
4769	return (0);
4770}
4771
4772static void
4773ctl_create_lun(struct ctl_be_lun *be_lun)
4774{
4775
4776	/*
4777	 * ctl_alloc_lun() should handle all potential failure cases.
4778	 */
4779	ctl_alloc_lun(control_softc, NULL, be_lun);
4780}
4781
4782int
4783ctl_add_lun(struct ctl_be_lun *be_lun)
4784{
4785	struct ctl_softc *softc = control_softc;
4786
4787	mtx_lock(&softc->ctl_lock);
4788	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4789	mtx_unlock(&softc->ctl_lock);
4790	wakeup(&softc->pending_lun_queue);
4791
4792	return (0);
4793}
4794
4795int
4796ctl_enable_lun(struct ctl_be_lun *be_lun)
4797{
4798	struct ctl_softc *softc;
4799	struct ctl_port *port, *nport;
4800	struct ctl_lun *lun;
4801	int retval;
4802
4803	lun = (struct ctl_lun *)be_lun->ctl_lun;
4804	softc = lun->ctl_softc;
4805
4806	mtx_lock(&softc->ctl_lock);
4807	mtx_lock(&lun->lun_lock);
4808	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4809		/*
4810		 * eh?  Why did we get called if the LUN is already
4811		 * enabled?
4812		 */
4813		mtx_unlock(&lun->lun_lock);
4814		mtx_unlock(&softc->ctl_lock);
4815		return (0);
4816	}
4817	lun->flags &= ~CTL_LUN_DISABLED;
4818	mtx_unlock(&lun->lun_lock);
4819
4820	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4821		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4822		    port->lun_map != NULL || port->lun_enable == NULL)
4823			continue;
4824
4825		/*
4826		 * Drop the lock while we call the FETD's enable routine.
4827		 * This can lead to a callback into CTL (at least in the
4828		 * case of the internal initiator frontend.
4829		 */
4830		mtx_unlock(&softc->ctl_lock);
4831		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4832		mtx_lock(&softc->ctl_lock);
4833		if (retval != 0) {
4834			printf("%s: FETD %s port %d returned error "
4835			       "%d for lun_enable on lun %jd\n",
4836			       __func__, port->port_name, port->targ_port,
4837			       retval, (intmax_t)lun->lun);
4838		}
4839	}
4840
4841	mtx_unlock(&softc->ctl_lock);
4842	ctl_isc_announce_lun(lun);
4843
4844	return (0);
4845}
4846
4847int
4848ctl_disable_lun(struct ctl_be_lun *be_lun)
4849{
4850	struct ctl_softc *softc;
4851	struct ctl_port *port;
4852	struct ctl_lun *lun;
4853	int retval;
4854
4855	lun = (struct ctl_lun *)be_lun->ctl_lun;
4856	softc = lun->ctl_softc;
4857
4858	mtx_lock(&softc->ctl_lock);
4859	mtx_lock(&lun->lun_lock);
4860	if (lun->flags & CTL_LUN_DISABLED) {
4861		mtx_unlock(&lun->lun_lock);
4862		mtx_unlock(&softc->ctl_lock);
4863		return (0);
4864	}
4865	lun->flags |= CTL_LUN_DISABLED;
4866	mtx_unlock(&lun->lun_lock);
4867
4868	STAILQ_FOREACH(port, &softc->port_list, links) {
4869		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4870		    port->lun_map != NULL || port->lun_disable == NULL)
4871			continue;
4872
4873		/*
4874		 * Drop the lock before we call the frontend's disable
4875		 * routine, to avoid lock order reversals.
4876		 *
4877		 * XXX KDM what happens if the frontend list changes while
4878		 * we're traversing it?  It's unlikely, but should be handled.
4879		 */
4880		mtx_unlock(&softc->ctl_lock);
4881		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4882		mtx_lock(&softc->ctl_lock);
4883		if (retval != 0) {
4884			printf("%s: FETD %s port %d returned error "
4885			       "%d for lun_disable on lun %jd\n",
4886			       __func__, port->port_name, port->targ_port,
4887			       retval, (intmax_t)lun->lun);
4888		}
4889	}
4890
4891	mtx_unlock(&softc->ctl_lock);
4892	ctl_isc_announce_lun(lun);
4893
4894	return (0);
4895}
4896
4897int
4898ctl_start_lun(struct ctl_be_lun *be_lun)
4899{
4900	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4901
4902	mtx_lock(&lun->lun_lock);
4903	lun->flags &= ~CTL_LUN_STOPPED;
4904	mtx_unlock(&lun->lun_lock);
4905	return (0);
4906}
4907
4908int
4909ctl_stop_lun(struct ctl_be_lun *be_lun)
4910{
4911	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4912
4913	mtx_lock(&lun->lun_lock);
4914	lun->flags |= CTL_LUN_STOPPED;
4915	mtx_unlock(&lun->lun_lock);
4916	return (0);
4917}
4918
4919int
4920ctl_lun_no_media(struct ctl_be_lun *be_lun)
4921{
4922	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4923
4924	mtx_lock(&lun->lun_lock);
4925	lun->flags |= CTL_LUN_NO_MEDIA;
4926	mtx_unlock(&lun->lun_lock);
4927	return (0);
4928}
4929
4930int
4931ctl_lun_has_media(struct ctl_be_lun *be_lun)
4932{
4933	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4934	union ctl_ha_msg msg;
4935
4936	mtx_lock(&lun->lun_lock);
4937	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4938	if (lun->flags & CTL_LUN_REMOVABLE)
4939		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4940	mtx_unlock(&lun->lun_lock);
4941	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4942	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4943		bzero(&msg.ua, sizeof(msg.ua));
4944		msg.hdr.msg_type = CTL_MSG_UA;
4945		msg.hdr.nexus.initid = -1;
4946		msg.hdr.nexus.targ_port = -1;
4947		msg.hdr.nexus.targ_lun = lun->lun;
4948		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4949		msg.ua.ua_all = 1;
4950		msg.ua.ua_set = 1;
4951		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4952		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4953		    M_WAITOK);
4954	}
4955	return (0);
4956}
4957
4958int
4959ctl_lun_ejected(struct ctl_be_lun *be_lun)
4960{
4961	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4962
4963	mtx_lock(&lun->lun_lock);
4964	lun->flags |= CTL_LUN_EJECTED;
4965	mtx_unlock(&lun->lun_lock);
4966	return (0);
4967}
4968
4969int
4970ctl_lun_primary(struct ctl_be_lun *be_lun)
4971{
4972	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4973
4974	mtx_lock(&lun->lun_lock);
4975	lun->flags |= CTL_LUN_PRIMARY_SC;
4976	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4977	mtx_unlock(&lun->lun_lock);
4978	ctl_isc_announce_lun(lun);
4979	return (0);
4980}
4981
4982int
4983ctl_lun_secondary(struct ctl_be_lun *be_lun)
4984{
4985	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4986
4987	mtx_lock(&lun->lun_lock);
4988	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4989	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4990	mtx_unlock(&lun->lun_lock);
4991	ctl_isc_announce_lun(lun);
4992	return (0);
4993}
4994
4995int
4996ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4997{
4998	struct ctl_softc *softc;
4999	struct ctl_lun *lun;
5000
5001	lun = (struct ctl_lun *)be_lun->ctl_lun;
5002	softc = lun->ctl_softc;
5003
5004	mtx_lock(&lun->lun_lock);
5005
5006	/*
5007	 * The LUN needs to be disabled before it can be marked invalid.
5008	 */
5009	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5010		mtx_unlock(&lun->lun_lock);
5011		return (-1);
5012	}
5013	/*
5014	 * Mark the LUN invalid.
5015	 */
5016	lun->flags |= CTL_LUN_INVALID;
5017
5018	/*
5019	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5020	 * If we have something in the OOA queue, we'll free it when the
5021	 * last I/O completes.
5022	 */
5023	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5024		mtx_unlock(&lun->lun_lock);
5025		ctl_free_lun(lun);
5026	} else
5027		mtx_unlock(&lun->lun_lock);
5028
5029	return (0);
5030}
5031
5032void
5033ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5034{
5035	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5036	union ctl_ha_msg msg;
5037
5038	mtx_lock(&lun->lun_lock);
5039	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5040	mtx_unlock(&lun->lun_lock);
5041	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5042		/* Send msg to other side. */
5043		bzero(&msg.ua, sizeof(msg.ua));
5044		msg.hdr.msg_type = CTL_MSG_UA;
5045		msg.hdr.nexus.initid = -1;
5046		msg.hdr.nexus.targ_port = -1;
5047		msg.hdr.nexus.targ_lun = lun->lun;
5048		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5049		msg.ua.ua_all = 1;
5050		msg.ua.ua_set = 1;
5051		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5052		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5053		    M_WAITOK);
5054	}
5055}
5056
5057/*
5058 * Backend "memory move is complete" callback for requests that never
5059 * make it down to say RAIDCore's configuration code.
5060 */
5061int
5062ctl_config_move_done(union ctl_io *io)
5063{
5064	int retval;
5065
5066	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5067	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5068	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5069
5070	if ((io->io_hdr.port_status != 0) &&
5071	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5072	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5073		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5074		    /*retry_count*/ io->io_hdr.port_status);
5075	} else if (io->scsiio.kern_data_resid != 0 &&
5076	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5077	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5078	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5079		ctl_set_invalid_field_ciu(&io->scsiio);
5080	}
5081
5082	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5083		ctl_data_print(io);
5084	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5085	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5086	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5087	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5088		/*
5089		 * XXX KDM just assuming a single pointer here, and not a
5090		 * S/G list.  If we start using S/G lists for config data,
5091		 * we'll need to know how to clean them up here as well.
5092		 */
5093		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5094			free(io->scsiio.kern_data_ptr, M_CTL);
5095		ctl_done(io);
5096		retval = CTL_RETVAL_COMPLETE;
5097	} else {
5098		/*
5099		 * XXX KDM now we need to continue data movement.  Some
5100		 * options:
5101		 * - call ctl_scsiio() again?  We don't do this for data
5102		 *   writes, because for those at least we know ahead of
5103		 *   time where the write will go and how long it is.  For
5104		 *   config writes, though, that information is largely
5105		 *   contained within the write itself, thus we need to
5106		 *   parse out the data again.
5107		 *
5108		 * - Call some other function once the data is in?
5109		 */
5110
5111		/*
5112		 * XXX KDM call ctl_scsiio() again for now, and check flag
5113		 * bits to see whether we're allocated or not.
5114		 */
5115		retval = ctl_scsiio(&io->scsiio);
5116	}
5117	return (retval);
5118}
5119
5120/*
5121 * This gets called by a backend driver when it is done with a
5122 * data_submit method.
5123 */
5124void
5125ctl_data_submit_done(union ctl_io *io)
5126{
5127	/*
5128	 * If the IO_CONT flag is set, we need to call the supplied
5129	 * function to continue processing the I/O, instead of completing
5130	 * the I/O just yet.
5131	 *
5132	 * If there is an error, though, we don't want to keep processing.
5133	 * Instead, just send status back to the initiator.
5134	 */
5135	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5136	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5137	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5138	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5139		io->scsiio.io_cont(io);
5140		return;
5141	}
5142	ctl_done(io);
5143}
5144
5145/*
5146 * This gets called by a backend driver when it is done with a
5147 * configuration write.
5148 */
5149void
5150ctl_config_write_done(union ctl_io *io)
5151{
5152	uint8_t *buf;
5153
5154	/*
5155	 * If the IO_CONT flag is set, we need to call the supplied
5156	 * function to continue processing the I/O, instead of completing
5157	 * the I/O just yet.
5158	 *
5159	 * If there is an error, though, we don't want to keep processing.
5160	 * Instead, just send status back to the initiator.
5161	 */
5162	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5163	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5164	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5165	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5166		io->scsiio.io_cont(io);
5167		return;
5168	}
5169	/*
5170	 * Since a configuration write can be done for commands that actually
5171	 * have data allocated, like write buffer, and commands that have
5172	 * no data, like start/stop unit, we need to check here.
5173	 */
5174	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5175		buf = io->scsiio.kern_data_ptr;
5176	else
5177		buf = NULL;
5178	ctl_done(io);
5179	if (buf)
5180		free(buf, M_CTL);
5181}
5182
5183void
5184ctl_config_read_done(union ctl_io *io)
5185{
5186	uint8_t *buf;
5187
5188	/*
5189	 * If there is some error -- we are done, skip data transfer.
5190	 */
5191	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5192	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5193	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5194		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5195			buf = io->scsiio.kern_data_ptr;
5196		else
5197			buf = NULL;
5198		ctl_done(io);
5199		if (buf)
5200			free(buf, M_CTL);
5201		return;
5202	}
5203
5204	/*
5205	 * If the IO_CONT flag is set, we need to call the supplied
5206	 * function to continue processing the I/O, instead of completing
5207	 * the I/O just yet.
5208	 */
5209	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5210		io->scsiio.io_cont(io);
5211		return;
5212	}
5213
5214	ctl_datamove(io);
5215}
5216
5217/*
5218 * SCSI release command.
5219 */
5220int
5221ctl_scsi_release(struct ctl_scsiio *ctsio)
5222{
5223	struct ctl_lun *lun = CTL_LUN(ctsio);
5224	uint32_t residx;
5225
5226	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5227
5228	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5229
5230	/*
5231	 * XXX KDM right now, we only support LUN reservation.  We don't
5232	 * support 3rd party reservations, or extent reservations, which
5233	 * might actually need the parameter list.  If we've gotten this
5234	 * far, we've got a LUN reservation.  Anything else got kicked out
5235	 * above.  So, according to SPC, ignore the length.
5236	 */
5237
5238	mtx_lock(&lun->lun_lock);
5239
5240	/*
5241	 * According to SPC, it is not an error for an intiator to attempt
5242	 * to release a reservation on a LUN that isn't reserved, or that
5243	 * is reserved by another initiator.  The reservation can only be
5244	 * released, though, by the initiator who made it or by one of
5245	 * several reset type events.
5246	 */
5247	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5248			lun->flags &= ~CTL_LUN_RESERVED;
5249
5250	mtx_unlock(&lun->lun_lock);
5251
5252	ctl_set_success(ctsio);
5253	ctl_done((union ctl_io *)ctsio);
5254	return (CTL_RETVAL_COMPLETE);
5255}
5256
5257int
5258ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5259{
5260	struct ctl_lun *lun = CTL_LUN(ctsio);
5261	uint32_t residx;
5262
5263	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5264
5265	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5266
5267	/*
5268	 * XXX KDM right now, we only support LUN reservation.  We don't
5269	 * support 3rd party reservations, or extent reservations, which
5270	 * might actually need the parameter list.  If we've gotten this
5271	 * far, we've got a LUN reservation.  Anything else got kicked out
5272	 * above.  So, according to SPC, ignore the length.
5273	 */
5274
5275	mtx_lock(&lun->lun_lock);
5276	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5277		ctl_set_reservation_conflict(ctsio);
5278		goto bailout;
5279	}
5280
5281	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5282	if (lun->flags & CTL_LUN_PR_RESERVED) {
5283		ctl_set_success(ctsio);
5284		goto bailout;
5285	}
5286
5287	lun->flags |= CTL_LUN_RESERVED;
5288	lun->res_idx = residx;
5289	ctl_set_success(ctsio);
5290
5291bailout:
5292	mtx_unlock(&lun->lun_lock);
5293	ctl_done((union ctl_io *)ctsio);
5294	return (CTL_RETVAL_COMPLETE);
5295}
5296
5297int
5298ctl_start_stop(struct ctl_scsiio *ctsio)
5299{
5300	struct ctl_lun *lun = CTL_LUN(ctsio);
5301	struct scsi_start_stop_unit *cdb;
5302	int retval;
5303
5304	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5305
5306	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5307
5308	if ((cdb->how & SSS_PC_MASK) == 0) {
5309		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5310		    (cdb->how & SSS_START) == 0) {
5311			uint32_t residx;
5312
5313			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5314			if (ctl_get_prkey(lun, residx) == 0 ||
5315			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5316
5317				ctl_set_reservation_conflict(ctsio);
5318				ctl_done((union ctl_io *)ctsio);
5319				return (CTL_RETVAL_COMPLETE);
5320			}
5321		}
5322
5323		if ((cdb->how & SSS_LOEJ) &&
5324		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5325			ctl_set_invalid_field(ctsio,
5326					      /*sks_valid*/ 1,
5327					      /*command*/ 1,
5328					      /*field*/ 4,
5329					      /*bit_valid*/ 1,
5330					      /*bit*/ 1);
5331			ctl_done((union ctl_io *)ctsio);
5332			return (CTL_RETVAL_COMPLETE);
5333		}
5334
5335		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5336		    lun->prevent_count > 0) {
5337			/* "Medium removal prevented" */
5338			ctl_set_sense(ctsio, /*current_error*/ 1,
5339			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5340			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5341			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5342			ctl_done((union ctl_io *)ctsio);
5343			return (CTL_RETVAL_COMPLETE);
5344		}
5345	}
5346
5347	retval = lun->backend->config_write((union ctl_io *)ctsio);
5348	return (retval);
5349}
5350
5351int
5352ctl_prevent_allow(struct ctl_scsiio *ctsio)
5353{
5354	struct ctl_lun *lun = CTL_LUN(ctsio);
5355	struct scsi_prevent *cdb;
5356	int retval;
5357	uint32_t initidx;
5358
5359	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5360
5361	cdb = (struct scsi_prevent *)ctsio->cdb;
5362
5363	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5364		ctl_set_invalid_opcode(ctsio);
5365		ctl_done((union ctl_io *)ctsio);
5366		return (CTL_RETVAL_COMPLETE);
5367	}
5368
5369	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5370	mtx_lock(&lun->lun_lock);
5371	if ((cdb->how & PR_PREVENT) &&
5372	    ctl_is_set(lun->prevent, initidx) == 0) {
5373		ctl_set_mask(lun->prevent, initidx);
5374		lun->prevent_count++;
5375	} else if ((cdb->how & PR_PREVENT) == 0 &&
5376	    ctl_is_set(lun->prevent, initidx)) {
5377		ctl_clear_mask(lun->prevent, initidx);
5378		lun->prevent_count--;
5379	}
5380	mtx_unlock(&lun->lun_lock);
5381	retval = lun->backend->config_write((union ctl_io *)ctsio);
5382	return (retval);
5383}
5384
5385/*
5386 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5387 * we don't really do anything with the LBA and length fields if the user
5388 * passes them in.  Instead we'll just flush out the cache for the entire
5389 * LUN.
5390 */
5391int
5392ctl_sync_cache(struct ctl_scsiio *ctsio)
5393{
5394	struct ctl_lun *lun = CTL_LUN(ctsio);
5395	struct ctl_lba_len_flags *lbalen;
5396	uint64_t starting_lba;
5397	uint32_t block_count;
5398	int retval;
5399	uint8_t byte2;
5400
5401	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5402
5403	retval = 0;
5404
5405	switch (ctsio->cdb[0]) {
5406	case SYNCHRONIZE_CACHE: {
5407		struct scsi_sync_cache *cdb;
5408		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5409
5410		starting_lba = scsi_4btoul(cdb->begin_lba);
5411		block_count = scsi_2btoul(cdb->lb_count);
5412		byte2 = cdb->byte2;
5413		break;
5414	}
5415	case SYNCHRONIZE_CACHE_16: {
5416		struct scsi_sync_cache_16 *cdb;
5417		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5418
5419		starting_lba = scsi_8btou64(cdb->begin_lba);
5420		block_count = scsi_4btoul(cdb->lb_count);
5421		byte2 = cdb->byte2;
5422		break;
5423	}
5424	default:
5425		ctl_set_invalid_opcode(ctsio);
5426		ctl_done((union ctl_io *)ctsio);
5427		goto bailout;
5428		break; /* NOTREACHED */
5429	}
5430
5431	/*
5432	 * We check the LBA and length, but don't do anything with them.
5433	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5434	 * get flushed.  This check will just help satisfy anyone who wants
5435	 * to see an error for an out of range LBA.
5436	 */
5437	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5438		ctl_set_lba_out_of_range(ctsio,
5439		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5440		ctl_done((union ctl_io *)ctsio);
5441		goto bailout;
5442	}
5443
5444	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5445	lbalen->lba = starting_lba;
5446	lbalen->len = block_count;
5447	lbalen->flags = byte2;
5448	retval = lun->backend->config_write((union ctl_io *)ctsio);
5449
5450bailout:
5451	return (retval);
5452}
5453
5454int
5455ctl_format(struct ctl_scsiio *ctsio)
5456{
5457	struct scsi_format *cdb;
5458	int length, defect_list_len;
5459
5460	CTL_DEBUG_PRINT(("ctl_format\n"));
5461
5462	cdb = (struct scsi_format *)ctsio->cdb;
5463
5464	length = 0;
5465	if (cdb->byte2 & SF_FMTDATA) {
5466		if (cdb->byte2 & SF_LONGLIST)
5467			length = sizeof(struct scsi_format_header_long);
5468		else
5469			length = sizeof(struct scsi_format_header_short);
5470	}
5471
5472	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5473	 && (length > 0)) {
5474		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5475		ctsio->kern_data_len = length;
5476		ctsio->kern_total_len = length;
5477		ctsio->kern_rel_offset = 0;
5478		ctsio->kern_sg_entries = 0;
5479		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5480		ctsio->be_move_done = ctl_config_move_done;
5481		ctl_datamove((union ctl_io *)ctsio);
5482
5483		return (CTL_RETVAL_COMPLETE);
5484	}
5485
5486	defect_list_len = 0;
5487
5488	if (cdb->byte2 & SF_FMTDATA) {
5489		if (cdb->byte2 & SF_LONGLIST) {
5490			struct scsi_format_header_long *header;
5491
5492			header = (struct scsi_format_header_long *)
5493				ctsio->kern_data_ptr;
5494
5495			defect_list_len = scsi_4btoul(header->defect_list_len);
5496			if (defect_list_len != 0) {
5497				ctl_set_invalid_field(ctsio,
5498						      /*sks_valid*/ 1,
5499						      /*command*/ 0,
5500						      /*field*/ 2,
5501						      /*bit_valid*/ 0,
5502						      /*bit*/ 0);
5503				goto bailout;
5504			}
5505		} else {
5506			struct scsi_format_header_short *header;
5507
5508			header = (struct scsi_format_header_short *)
5509				ctsio->kern_data_ptr;
5510
5511			defect_list_len = scsi_2btoul(header->defect_list_len);
5512			if (defect_list_len != 0) {
5513				ctl_set_invalid_field(ctsio,
5514						      /*sks_valid*/ 1,
5515						      /*command*/ 0,
5516						      /*field*/ 2,
5517						      /*bit_valid*/ 0,
5518						      /*bit*/ 0);
5519				goto bailout;
5520			}
5521		}
5522	}
5523
5524	ctl_set_success(ctsio);
5525bailout:
5526
5527	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5528		free(ctsio->kern_data_ptr, M_CTL);
5529		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5530	}
5531
5532	ctl_done((union ctl_io *)ctsio);
5533	return (CTL_RETVAL_COMPLETE);
5534}
5535
5536int
5537ctl_read_buffer(struct ctl_scsiio *ctsio)
5538{
5539	struct ctl_lun *lun = CTL_LUN(ctsio);
5540	uint64_t buffer_offset;
5541	uint32_t len;
5542	uint8_t byte2;
5543	static uint8_t descr[4];
5544	static uint8_t echo_descr[4] = { 0 };
5545
5546	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5547
5548	switch (ctsio->cdb[0]) {
5549	case READ_BUFFER: {
5550		struct scsi_read_buffer *cdb;
5551
5552		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5553		buffer_offset = scsi_3btoul(cdb->offset);
5554		len = scsi_3btoul(cdb->length);
5555		byte2 = cdb->byte2;
5556		break;
5557	}
5558	case READ_BUFFER_16: {
5559		struct scsi_read_buffer_16 *cdb;
5560
5561		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5562		buffer_offset = scsi_8btou64(cdb->offset);
5563		len = scsi_4btoul(cdb->length);
5564		byte2 = cdb->byte2;
5565		break;
5566	}
5567	default: /* This shouldn't happen. */
5568		ctl_set_invalid_opcode(ctsio);
5569		ctl_done((union ctl_io *)ctsio);
5570		return (CTL_RETVAL_COMPLETE);
5571	}
5572
5573	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5574	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5575		ctl_set_invalid_field(ctsio,
5576				      /*sks_valid*/ 1,
5577				      /*command*/ 1,
5578				      /*field*/ 6,
5579				      /*bit_valid*/ 0,
5580				      /*bit*/ 0);
5581		ctl_done((union ctl_io *)ctsio);
5582		return (CTL_RETVAL_COMPLETE);
5583	}
5584
5585	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5586		descr[0] = 0;
5587		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5588		ctsio->kern_data_ptr = descr;
5589		len = min(len, sizeof(descr));
5590	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5591		ctsio->kern_data_ptr = echo_descr;
5592		len = min(len, sizeof(echo_descr));
5593	} else {
5594		if (lun->write_buffer == NULL) {
5595			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5596			    M_CTL, M_WAITOK);
5597		}
5598		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5599	}
5600	ctsio->kern_data_len = len;
5601	ctsio->kern_total_len = len;
5602	ctsio->kern_rel_offset = 0;
5603	ctsio->kern_sg_entries = 0;
5604	ctl_set_success(ctsio);
5605	ctsio->be_move_done = ctl_config_move_done;
5606	ctl_datamove((union ctl_io *)ctsio);
5607	return (CTL_RETVAL_COMPLETE);
5608}
5609
5610int
5611ctl_write_buffer(struct ctl_scsiio *ctsio)
5612{
5613	struct ctl_lun *lun = CTL_LUN(ctsio);
5614	struct scsi_write_buffer *cdb;
5615	int buffer_offset, len;
5616
5617	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5618
5619	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5620
5621	len = scsi_3btoul(cdb->length);
5622	buffer_offset = scsi_3btoul(cdb->offset);
5623
5624	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5625		ctl_set_invalid_field(ctsio,
5626				      /*sks_valid*/ 1,
5627				      /*command*/ 1,
5628				      /*field*/ 6,
5629				      /*bit_valid*/ 0,
5630				      /*bit*/ 0);
5631		ctl_done((union ctl_io *)ctsio);
5632		return (CTL_RETVAL_COMPLETE);
5633	}
5634
5635	/*
5636	 * If we've got a kernel request that hasn't been malloced yet,
5637	 * malloc it and tell the caller the data buffer is here.
5638	 */
5639	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5640		if (lun->write_buffer == NULL) {
5641			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5642			    M_CTL, M_WAITOK);
5643		}
5644		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5645		ctsio->kern_data_len = len;
5646		ctsio->kern_total_len = len;
5647		ctsio->kern_rel_offset = 0;
5648		ctsio->kern_sg_entries = 0;
5649		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5650		ctsio->be_move_done = ctl_config_move_done;
5651		ctl_datamove((union ctl_io *)ctsio);
5652
5653		return (CTL_RETVAL_COMPLETE);
5654	}
5655
5656	ctl_set_success(ctsio);
5657	ctl_done((union ctl_io *)ctsio);
5658	return (CTL_RETVAL_COMPLETE);
5659}
5660
5661int
5662ctl_write_same(struct ctl_scsiio *ctsio)
5663{
5664	struct ctl_lun *lun = CTL_LUN(ctsio);
5665	struct ctl_lba_len_flags *lbalen;
5666	uint64_t lba;
5667	uint32_t num_blocks;
5668	int len, retval;
5669	uint8_t byte2;
5670
5671	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5672
5673	switch (ctsio->cdb[0]) {
5674	case WRITE_SAME_10: {
5675		struct scsi_write_same_10 *cdb;
5676
5677		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5678
5679		lba = scsi_4btoul(cdb->addr);
5680		num_blocks = scsi_2btoul(cdb->length);
5681		byte2 = cdb->byte2;
5682		break;
5683	}
5684	case WRITE_SAME_16: {
5685		struct scsi_write_same_16 *cdb;
5686
5687		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5688
5689		lba = scsi_8btou64(cdb->addr);
5690		num_blocks = scsi_4btoul(cdb->length);
5691		byte2 = cdb->byte2;
5692		break;
5693	}
5694	default:
5695		/*
5696		 * We got a command we don't support.  This shouldn't
5697		 * happen, commands should be filtered out above us.
5698		 */
5699		ctl_set_invalid_opcode(ctsio);
5700		ctl_done((union ctl_io *)ctsio);
5701
5702		return (CTL_RETVAL_COMPLETE);
5703		break; /* NOTREACHED */
5704	}
5705
5706	/* ANCHOR flag can be used only together with UNMAP */
5707	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5708		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5709		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5710		ctl_done((union ctl_io *)ctsio);
5711		return (CTL_RETVAL_COMPLETE);
5712	}
5713
5714	/*
5715	 * The first check is to make sure we're in bounds, the second
5716	 * check is to catch wrap-around problems.  If the lba + num blocks
5717	 * is less than the lba, then we've wrapped around and the block
5718	 * range is invalid anyway.
5719	 */
5720	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5721	 || ((lba + num_blocks) < lba)) {
5722		ctl_set_lba_out_of_range(ctsio,
5723		    MAX(lba, lun->be_lun->maxlba + 1));
5724		ctl_done((union ctl_io *)ctsio);
5725		return (CTL_RETVAL_COMPLETE);
5726	}
5727
5728	/* Zero number of blocks means "to the last logical block" */
5729	if (num_blocks == 0) {
5730		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5731			ctl_set_invalid_field(ctsio,
5732					      /*sks_valid*/ 0,
5733					      /*command*/ 1,
5734					      /*field*/ 0,
5735					      /*bit_valid*/ 0,
5736					      /*bit*/ 0);
5737			ctl_done((union ctl_io *)ctsio);
5738			return (CTL_RETVAL_COMPLETE);
5739		}
5740		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5741	}
5742
5743	len = lun->be_lun->blocksize;
5744
5745	/*
5746	 * If we've got a kernel request that hasn't been malloced yet,
5747	 * malloc it and tell the caller the data buffer is here.
5748	 */
5749	if ((byte2 & SWS_NDOB) == 0 &&
5750	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5751		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5752		ctsio->kern_data_len = len;
5753		ctsio->kern_total_len = len;
5754		ctsio->kern_rel_offset = 0;
5755		ctsio->kern_sg_entries = 0;
5756		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5757		ctsio->be_move_done = ctl_config_move_done;
5758		ctl_datamove((union ctl_io *)ctsio);
5759
5760		return (CTL_RETVAL_COMPLETE);
5761	}
5762
5763	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5764	lbalen->lba = lba;
5765	lbalen->len = num_blocks;
5766	lbalen->flags = byte2;
5767	retval = lun->backend->config_write((union ctl_io *)ctsio);
5768
5769	return (retval);
5770}
5771
5772int
5773ctl_unmap(struct ctl_scsiio *ctsio)
5774{
5775	struct ctl_lun *lun = CTL_LUN(ctsio);
5776	struct scsi_unmap *cdb;
5777	struct ctl_ptr_len_flags *ptrlen;
5778	struct scsi_unmap_header *hdr;
5779	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5780	uint64_t lba;
5781	uint32_t num_blocks;
5782	int len, retval;
5783	uint8_t byte2;
5784
5785	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5786
5787	cdb = (struct scsi_unmap *)ctsio->cdb;
5788	len = scsi_2btoul(cdb->length);
5789	byte2 = cdb->byte2;
5790
5791	/*
5792	 * If we've got a kernel request that hasn't been malloced yet,
5793	 * malloc it and tell the caller the data buffer is here.
5794	 */
5795	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5796		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5797		ctsio->kern_data_len = len;
5798		ctsio->kern_total_len = len;
5799		ctsio->kern_rel_offset = 0;
5800		ctsio->kern_sg_entries = 0;
5801		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5802		ctsio->be_move_done = ctl_config_move_done;
5803		ctl_datamove((union ctl_io *)ctsio);
5804
5805		return (CTL_RETVAL_COMPLETE);
5806	}
5807
5808	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5809	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5810	if (len < sizeof (*hdr) ||
5811	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5812	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5813	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5814		ctl_set_invalid_field(ctsio,
5815				      /*sks_valid*/ 0,
5816				      /*command*/ 0,
5817				      /*field*/ 0,
5818				      /*bit_valid*/ 0,
5819				      /*bit*/ 0);
5820		goto done;
5821	}
5822	len = scsi_2btoul(hdr->desc_length);
5823	buf = (struct scsi_unmap_desc *)(hdr + 1);
5824	end = buf + len / sizeof(*buf);
5825
5826	endnz = buf;
5827	for (range = buf; range < end; range++) {
5828		lba = scsi_8btou64(range->lba);
5829		num_blocks = scsi_4btoul(range->length);
5830		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5831		 || ((lba + num_blocks) < lba)) {
5832			ctl_set_lba_out_of_range(ctsio,
5833			    MAX(lba, lun->be_lun->maxlba + 1));
5834			ctl_done((union ctl_io *)ctsio);
5835			return (CTL_RETVAL_COMPLETE);
5836		}
5837		if (num_blocks != 0)
5838			endnz = range + 1;
5839	}
5840
5841	/*
5842	 * Block backend can not handle zero last range.
5843	 * Filter it out and return if there is nothing left.
5844	 */
5845	len = (uint8_t *)endnz - (uint8_t *)buf;
5846	if (len == 0) {
5847		ctl_set_success(ctsio);
5848		goto done;
5849	}
5850
5851	mtx_lock(&lun->lun_lock);
5852	ptrlen = (struct ctl_ptr_len_flags *)
5853	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5854	ptrlen->ptr = (void *)buf;
5855	ptrlen->len = len;
5856	ptrlen->flags = byte2;
5857	ctl_check_blocked(lun);
5858	mtx_unlock(&lun->lun_lock);
5859
5860	retval = lun->backend->config_write((union ctl_io *)ctsio);
5861	return (retval);
5862
5863done:
5864	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5865		free(ctsio->kern_data_ptr, M_CTL);
5866		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5867	}
5868	ctl_done((union ctl_io *)ctsio);
5869	return (CTL_RETVAL_COMPLETE);
5870}
5871
5872int
5873ctl_default_page_handler(struct ctl_scsiio *ctsio,
5874			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5875{
5876	struct ctl_lun *lun = CTL_LUN(ctsio);
5877	uint8_t *current_cp;
5878	int set_ua;
5879	uint32_t initidx;
5880
5881	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5882	set_ua = 0;
5883
5884	current_cp = (page_index->page_data + (page_index->page_len *
5885	    CTL_PAGE_CURRENT));
5886
5887	mtx_lock(&lun->lun_lock);
5888	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5889		memcpy(current_cp, page_ptr, page_index->page_len);
5890		set_ua = 1;
5891	}
5892	if (set_ua != 0)
5893		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5894	mtx_unlock(&lun->lun_lock);
5895	if (set_ua) {
5896		ctl_isc_announce_mode(lun,
5897		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5898		    page_index->page_code, page_index->subpage);
5899	}
5900	return (CTL_RETVAL_COMPLETE);
5901}
5902
5903static void
5904ctl_ie_timer(void *arg)
5905{
5906	struct ctl_lun *lun = arg;
5907	uint64_t t;
5908
5909	if (lun->ie_asc == 0)
5910		return;
5911
5912	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5913		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5914	else
5915		lun->ie_reported = 0;
5916
5917	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5918		lun->ie_reportcnt++;
5919		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5920		if (t == 0 || t == UINT32_MAX)
5921			t = 3000;  /* 5 min */
5922		callout_schedule(&lun->ie_callout, t * hz / 10);
5923	}
5924}
5925
5926int
5927ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5928			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5929{
5930	struct ctl_lun *lun = CTL_LUN(ctsio);
5931	struct scsi_info_exceptions_page *pg;
5932	uint64_t t;
5933
5934	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5935
5936	pg = (struct scsi_info_exceptions_page *)page_ptr;
5937	mtx_lock(&lun->lun_lock);
5938	if (pg->info_flags & SIEP_FLAGS_TEST) {
5939		lun->ie_asc = 0x5d;
5940		lun->ie_ascq = 0xff;
5941		if (pg->mrie == SIEP_MRIE_UA) {
5942			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5943			lun->ie_reported = 1;
5944		} else {
5945			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5946			lun->ie_reported = -1;
5947		}
5948		lun->ie_reportcnt = 1;
5949		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5950			lun->ie_reportcnt++;
5951			t = scsi_4btoul(pg->interval_timer);
5952			if (t == 0 || t == UINT32_MAX)
5953				t = 3000;  /* 5 min */
5954			callout_reset(&lun->ie_callout, t * hz / 10,
5955			    ctl_ie_timer, lun);
5956		}
5957	} else {
5958		lun->ie_asc = 0;
5959		lun->ie_ascq = 0;
5960		lun->ie_reported = 1;
5961		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5962		lun->ie_reportcnt = UINT32_MAX;
5963		callout_stop(&lun->ie_callout);
5964	}
5965	mtx_unlock(&lun->lun_lock);
5966	return (CTL_RETVAL_COMPLETE);
5967}
5968
5969static int
5970ctl_do_mode_select(union ctl_io *io)
5971{
5972	struct ctl_lun *lun = CTL_LUN(io);
5973	struct scsi_mode_page_header *page_header;
5974	struct ctl_page_index *page_index;
5975	struct ctl_scsiio *ctsio;
5976	int page_len, page_len_offset, page_len_size;
5977	union ctl_modepage_info *modepage_info;
5978	uint16_t *len_left, *len_used;
5979	int retval, i;
5980
5981	ctsio = &io->scsiio;
5982	page_index = NULL;
5983	page_len = 0;
5984
5985	modepage_info = (union ctl_modepage_info *)
5986		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5987	len_left = &modepage_info->header.len_left;
5988	len_used = &modepage_info->header.len_used;
5989
5990do_next_page:
5991
5992	page_header = (struct scsi_mode_page_header *)
5993		(ctsio->kern_data_ptr + *len_used);
5994
5995	if (*len_left == 0) {
5996		free(ctsio->kern_data_ptr, M_CTL);
5997		ctl_set_success(ctsio);
5998		ctl_done((union ctl_io *)ctsio);
5999		return (CTL_RETVAL_COMPLETE);
6000	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6001
6002		free(ctsio->kern_data_ptr, M_CTL);
6003		ctl_set_param_len_error(ctsio);
6004		ctl_done((union ctl_io *)ctsio);
6005		return (CTL_RETVAL_COMPLETE);
6006
6007	} else if ((page_header->page_code & SMPH_SPF)
6008		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6009
6010		free(ctsio->kern_data_ptr, M_CTL);
6011		ctl_set_param_len_error(ctsio);
6012		ctl_done((union ctl_io *)ctsio);
6013		return (CTL_RETVAL_COMPLETE);
6014	}
6015
6016
6017	/*
6018	 * XXX KDM should we do something with the block descriptor?
6019	 */
6020	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6021		page_index = &lun->mode_pages.index[i];
6022		if (lun->be_lun->lun_type == T_DIRECT &&
6023		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6024			continue;
6025		if (lun->be_lun->lun_type == T_PROCESSOR &&
6026		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6027			continue;
6028		if (lun->be_lun->lun_type == T_CDROM &&
6029		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6030			continue;
6031
6032		if ((page_index->page_code & SMPH_PC_MASK) !=
6033		    (page_header->page_code & SMPH_PC_MASK))
6034			continue;
6035
6036		/*
6037		 * If neither page has a subpage code, then we've got a
6038		 * match.
6039		 */
6040		if (((page_index->page_code & SMPH_SPF) == 0)
6041		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6042			page_len = page_header->page_length;
6043			break;
6044		}
6045
6046		/*
6047		 * If both pages have subpages, then the subpage numbers
6048		 * have to match.
6049		 */
6050		if ((page_index->page_code & SMPH_SPF)
6051		  && (page_header->page_code & SMPH_SPF)) {
6052			struct scsi_mode_page_header_sp *sph;
6053
6054			sph = (struct scsi_mode_page_header_sp *)page_header;
6055			if (page_index->subpage == sph->subpage) {
6056				page_len = scsi_2btoul(sph->page_length);
6057				break;
6058			}
6059		}
6060	}
6061
6062	/*
6063	 * If we couldn't find the page, or if we don't have a mode select
6064	 * handler for it, send back an error to the user.
6065	 */
6066	if ((i >= CTL_NUM_MODE_PAGES)
6067	 || (page_index->select_handler == NULL)) {
6068		ctl_set_invalid_field(ctsio,
6069				      /*sks_valid*/ 1,
6070				      /*command*/ 0,
6071				      /*field*/ *len_used,
6072				      /*bit_valid*/ 0,
6073				      /*bit*/ 0);
6074		free(ctsio->kern_data_ptr, M_CTL);
6075		ctl_done((union ctl_io *)ctsio);
6076		return (CTL_RETVAL_COMPLETE);
6077	}
6078
6079	if (page_index->page_code & SMPH_SPF) {
6080		page_len_offset = 2;
6081		page_len_size = 2;
6082	} else {
6083		page_len_size = 1;
6084		page_len_offset = 1;
6085	}
6086
6087	/*
6088	 * If the length the initiator gives us isn't the one we specify in
6089	 * the mode page header, or if they didn't specify enough data in
6090	 * the CDB to avoid truncating this page, kick out the request.
6091	 */
6092	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6093		ctl_set_invalid_field(ctsio,
6094				      /*sks_valid*/ 1,
6095				      /*command*/ 0,
6096				      /*field*/ *len_used + page_len_offset,
6097				      /*bit_valid*/ 0,
6098				      /*bit*/ 0);
6099		free(ctsio->kern_data_ptr, M_CTL);
6100		ctl_done((union ctl_io *)ctsio);
6101		return (CTL_RETVAL_COMPLETE);
6102	}
6103	if (*len_left < page_index->page_len) {
6104		free(ctsio->kern_data_ptr, M_CTL);
6105		ctl_set_param_len_error(ctsio);
6106		ctl_done((union ctl_io *)ctsio);
6107		return (CTL_RETVAL_COMPLETE);
6108	}
6109
6110	/*
6111	 * Run through the mode page, checking to make sure that the bits
6112	 * the user changed are actually legal for him to change.
6113	 */
6114	for (i = 0; i < page_index->page_len; i++) {
6115		uint8_t *user_byte, *change_mask, *current_byte;
6116		int bad_bit;
6117		int j;
6118
6119		user_byte = (uint8_t *)page_header + i;
6120		change_mask = page_index->page_data +
6121			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6122		current_byte = page_index->page_data +
6123			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6124
6125		/*
6126		 * Check to see whether the user set any bits in this byte
6127		 * that he is not allowed to set.
6128		 */
6129		if ((*user_byte & ~(*change_mask)) ==
6130		    (*current_byte & ~(*change_mask)))
6131			continue;
6132
6133		/*
6134		 * Go through bit by bit to determine which one is illegal.
6135		 */
6136		bad_bit = 0;
6137		for (j = 7; j >= 0; j--) {
6138			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6139			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6140				bad_bit = i;
6141				break;
6142			}
6143		}
6144		ctl_set_invalid_field(ctsio,
6145				      /*sks_valid*/ 1,
6146				      /*command*/ 0,
6147				      /*field*/ *len_used + i,
6148				      /*bit_valid*/ 1,
6149				      /*bit*/ bad_bit);
6150		free(ctsio->kern_data_ptr, M_CTL);
6151		ctl_done((union ctl_io *)ctsio);
6152		return (CTL_RETVAL_COMPLETE);
6153	}
6154
6155	/*
6156	 * Decrement these before we call the page handler, since we may
6157	 * end up getting called back one way or another before the handler
6158	 * returns to this context.
6159	 */
6160	*len_left -= page_index->page_len;
6161	*len_used += page_index->page_len;
6162
6163	retval = page_index->select_handler(ctsio, page_index,
6164					    (uint8_t *)page_header);
6165
6166	/*
6167	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6168	 * wait until this queued command completes to finish processing
6169	 * the mode page.  If it returns anything other than
6170	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6171	 * already set the sense information, freed the data pointer, and
6172	 * completed the io for us.
6173	 */
6174	if (retval != CTL_RETVAL_COMPLETE)
6175		goto bailout_no_done;
6176
6177	/*
6178	 * If the initiator sent us more than one page, parse the next one.
6179	 */
6180	if (*len_left > 0)
6181		goto do_next_page;
6182
6183	ctl_set_success(ctsio);
6184	free(ctsio->kern_data_ptr, M_CTL);
6185	ctl_done((union ctl_io *)ctsio);
6186
6187bailout_no_done:
6188
6189	return (CTL_RETVAL_COMPLETE);
6190
6191}
6192
6193int
6194ctl_mode_select(struct ctl_scsiio *ctsio)
6195{
6196	struct ctl_lun *lun = CTL_LUN(ctsio);
6197	union ctl_modepage_info *modepage_info;
6198	int bd_len, i, header_size, param_len, pf, rtd, sp;
6199	uint32_t initidx;
6200
6201	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6202	switch (ctsio->cdb[0]) {
6203	case MODE_SELECT_6: {
6204		struct scsi_mode_select_6 *cdb;
6205
6206		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6207
6208		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6209		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6210		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6211		param_len = cdb->length;
6212		header_size = sizeof(struct scsi_mode_header_6);
6213		break;
6214	}
6215	case MODE_SELECT_10: {
6216		struct scsi_mode_select_10 *cdb;
6217
6218		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6219
6220		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6221		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6222		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6223		param_len = scsi_2btoul(cdb->length);
6224		header_size = sizeof(struct scsi_mode_header_10);
6225		break;
6226	}
6227	default:
6228		ctl_set_invalid_opcode(ctsio);
6229		ctl_done((union ctl_io *)ctsio);
6230		return (CTL_RETVAL_COMPLETE);
6231	}
6232
6233	if (rtd) {
6234		if (param_len != 0) {
6235			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6236			    /*command*/ 1, /*field*/ 0,
6237			    /*bit_valid*/ 0, /*bit*/ 0);
6238			ctl_done((union ctl_io *)ctsio);
6239			return (CTL_RETVAL_COMPLETE);
6240		}
6241
6242		/* Revert to defaults. */
6243		ctl_init_page_index(lun);
6244		mtx_lock(&lun->lun_lock);
6245		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6246		mtx_unlock(&lun->lun_lock);
6247		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6248			ctl_isc_announce_mode(lun, -1,
6249			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6250			    lun->mode_pages.index[i].subpage);
6251		}
6252		ctl_set_success(ctsio);
6253		ctl_done((union ctl_io *)ctsio);
6254		return (CTL_RETVAL_COMPLETE);
6255	}
6256
6257	/*
6258	 * From SPC-3:
6259	 * "A parameter list length of zero indicates that the Data-Out Buffer
6260	 * shall be empty. This condition shall not be considered as an error."
6261	 */
6262	if (param_len == 0) {
6263		ctl_set_success(ctsio);
6264		ctl_done((union ctl_io *)ctsio);
6265		return (CTL_RETVAL_COMPLETE);
6266	}
6267
6268	/*
6269	 * Since we'll hit this the first time through, prior to
6270	 * allocation, we don't need to free a data buffer here.
6271	 */
6272	if (param_len < header_size) {
6273		ctl_set_param_len_error(ctsio);
6274		ctl_done((union ctl_io *)ctsio);
6275		return (CTL_RETVAL_COMPLETE);
6276	}
6277
6278	/*
6279	 * Allocate the data buffer and grab the user's data.  In theory,
6280	 * we shouldn't have to sanity check the parameter list length here
6281	 * because the maximum size is 64K.  We should be able to malloc
6282	 * that much without too many problems.
6283	 */
6284	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6285		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6286		ctsio->kern_data_len = param_len;
6287		ctsio->kern_total_len = param_len;
6288		ctsio->kern_rel_offset = 0;
6289		ctsio->kern_sg_entries = 0;
6290		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6291		ctsio->be_move_done = ctl_config_move_done;
6292		ctl_datamove((union ctl_io *)ctsio);
6293
6294		return (CTL_RETVAL_COMPLETE);
6295	}
6296
6297	switch (ctsio->cdb[0]) {
6298	case MODE_SELECT_6: {
6299		struct scsi_mode_header_6 *mh6;
6300
6301		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6302		bd_len = mh6->blk_desc_len;
6303		break;
6304	}
6305	case MODE_SELECT_10: {
6306		struct scsi_mode_header_10 *mh10;
6307
6308		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6309		bd_len = scsi_2btoul(mh10->blk_desc_len);
6310		break;
6311	}
6312	default:
6313		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6314	}
6315
6316	if (param_len < (header_size + bd_len)) {
6317		free(ctsio->kern_data_ptr, M_CTL);
6318		ctl_set_param_len_error(ctsio);
6319		ctl_done((union ctl_io *)ctsio);
6320		return (CTL_RETVAL_COMPLETE);
6321	}
6322
6323	/*
6324	 * Set the IO_CONT flag, so that if this I/O gets passed to
6325	 * ctl_config_write_done(), it'll get passed back to
6326	 * ctl_do_mode_select() for further processing, or completion if
6327	 * we're all done.
6328	 */
6329	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6330	ctsio->io_cont = ctl_do_mode_select;
6331
6332	modepage_info = (union ctl_modepage_info *)
6333		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6334	memset(modepage_info, 0, sizeof(*modepage_info));
6335	modepage_info->header.len_left = param_len - header_size - bd_len;
6336	modepage_info->header.len_used = header_size + bd_len;
6337
6338	return (ctl_do_mode_select((union ctl_io *)ctsio));
6339}
6340
6341int
6342ctl_mode_sense(struct ctl_scsiio *ctsio)
6343{
6344	struct ctl_lun *lun = CTL_LUN(ctsio);
6345	int pc, page_code, dbd, llba, subpage;
6346	int alloc_len, page_len, header_len, total_len;
6347	struct scsi_mode_block_descr *block_desc;
6348	struct ctl_page_index *page_index;
6349
6350	dbd = 0;
6351	llba = 0;
6352	block_desc = NULL;
6353
6354	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6355
6356	switch (ctsio->cdb[0]) {
6357	case MODE_SENSE_6: {
6358		struct scsi_mode_sense_6 *cdb;
6359
6360		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6361
6362		header_len = sizeof(struct scsi_mode_hdr_6);
6363		if (cdb->byte2 & SMS_DBD)
6364			dbd = 1;
6365		else
6366			header_len += sizeof(struct scsi_mode_block_descr);
6367
6368		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6369		page_code = cdb->page & SMS_PAGE_CODE;
6370		subpage = cdb->subpage;
6371		alloc_len = cdb->length;
6372		break;
6373	}
6374	case MODE_SENSE_10: {
6375		struct scsi_mode_sense_10 *cdb;
6376
6377		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6378
6379		header_len = sizeof(struct scsi_mode_hdr_10);
6380
6381		if (cdb->byte2 & SMS_DBD)
6382			dbd = 1;
6383		else
6384			header_len += sizeof(struct scsi_mode_block_descr);
6385		if (cdb->byte2 & SMS10_LLBAA)
6386			llba = 1;
6387		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6388		page_code = cdb->page & SMS_PAGE_CODE;
6389		subpage = cdb->subpage;
6390		alloc_len = scsi_2btoul(cdb->length);
6391		break;
6392	}
6393	default:
6394		ctl_set_invalid_opcode(ctsio);
6395		ctl_done((union ctl_io *)ctsio);
6396		return (CTL_RETVAL_COMPLETE);
6397		break; /* NOTREACHED */
6398	}
6399
6400	/*
6401	 * We have to make a first pass through to calculate the size of
6402	 * the pages that match the user's query.  Then we allocate enough
6403	 * memory to hold it, and actually copy the data into the buffer.
6404	 */
6405	switch (page_code) {
6406	case SMS_ALL_PAGES_PAGE: {
6407		u_int i;
6408
6409		page_len = 0;
6410
6411		/*
6412		 * At the moment, values other than 0 and 0xff here are
6413		 * reserved according to SPC-3.
6414		 */
6415		if ((subpage != SMS_SUBPAGE_PAGE_0)
6416		 && (subpage != SMS_SUBPAGE_ALL)) {
6417			ctl_set_invalid_field(ctsio,
6418					      /*sks_valid*/ 1,
6419					      /*command*/ 1,
6420					      /*field*/ 3,
6421					      /*bit_valid*/ 0,
6422					      /*bit*/ 0);
6423			ctl_done((union ctl_io *)ctsio);
6424			return (CTL_RETVAL_COMPLETE);
6425		}
6426
6427		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6428			page_index = &lun->mode_pages.index[i];
6429
6430			/* Make sure the page is supported for this dev type */
6431			if (lun->be_lun->lun_type == T_DIRECT &&
6432			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6433				continue;
6434			if (lun->be_lun->lun_type == T_PROCESSOR &&
6435			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6436				continue;
6437			if (lun->be_lun->lun_type == T_CDROM &&
6438			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6439				continue;
6440
6441			/*
6442			 * We don't use this subpage if the user didn't
6443			 * request all subpages.
6444			 */
6445			if ((page_index->subpage != 0)
6446			 && (subpage == SMS_SUBPAGE_PAGE_0))
6447				continue;
6448
6449#if 0
6450			printf("found page %#x len %d\n",
6451			       page_index->page_code & SMPH_PC_MASK,
6452			       page_index->page_len);
6453#endif
6454			page_len += page_index->page_len;
6455		}
6456		break;
6457	}
6458	default: {
6459		u_int i;
6460
6461		page_len = 0;
6462
6463		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6464			page_index = &lun->mode_pages.index[i];
6465
6466			/* Make sure the page is supported for this dev type */
6467			if (lun->be_lun->lun_type == T_DIRECT &&
6468			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6469				continue;
6470			if (lun->be_lun->lun_type == T_PROCESSOR &&
6471			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6472				continue;
6473			if (lun->be_lun->lun_type == T_CDROM &&
6474			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6475				continue;
6476
6477			/* Look for the right page code */
6478			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6479				continue;
6480
6481			/* Look for the right subpage or the subpage wildcard*/
6482			if ((page_index->subpage != subpage)
6483			 && (subpage != SMS_SUBPAGE_ALL))
6484				continue;
6485
6486#if 0
6487			printf("found page %#x len %d\n",
6488			       page_index->page_code & SMPH_PC_MASK,
6489			       page_index->page_len);
6490#endif
6491
6492			page_len += page_index->page_len;
6493		}
6494
6495		if (page_len == 0) {
6496			ctl_set_invalid_field(ctsio,
6497					      /*sks_valid*/ 1,
6498					      /*command*/ 1,
6499					      /*field*/ 2,
6500					      /*bit_valid*/ 1,
6501					      /*bit*/ 5);
6502			ctl_done((union ctl_io *)ctsio);
6503			return (CTL_RETVAL_COMPLETE);
6504		}
6505		break;
6506	}
6507	}
6508
6509	total_len = header_len + page_len;
6510#if 0
6511	printf("header_len = %d, page_len = %d, total_len = %d\n",
6512	       header_len, page_len, total_len);
6513#endif
6514
6515	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6516	ctsio->kern_sg_entries = 0;
6517	ctsio->kern_rel_offset = 0;
6518	ctsio->kern_data_len = min(total_len, alloc_len);
6519	ctsio->kern_total_len = ctsio->kern_data_len;
6520
6521	switch (ctsio->cdb[0]) {
6522	case MODE_SENSE_6: {
6523		struct scsi_mode_hdr_6 *header;
6524
6525		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6526
6527		header->datalen = MIN(total_len - 1, 254);
6528		if (lun->be_lun->lun_type == T_DIRECT) {
6529			header->dev_specific = 0x10; /* DPOFUA */
6530			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6531			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6532				header->dev_specific |= 0x80; /* WP */
6533		}
6534		if (dbd)
6535			header->block_descr_len = 0;
6536		else
6537			header->block_descr_len =
6538				sizeof(struct scsi_mode_block_descr);
6539		block_desc = (struct scsi_mode_block_descr *)&header[1];
6540		break;
6541	}
6542	case MODE_SENSE_10: {
6543		struct scsi_mode_hdr_10 *header;
6544		int datalen;
6545
6546		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6547
6548		datalen = MIN(total_len - 2, 65533);
6549		scsi_ulto2b(datalen, header->datalen);
6550		if (lun->be_lun->lun_type == T_DIRECT) {
6551			header->dev_specific = 0x10; /* DPOFUA */
6552			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6553			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6554				header->dev_specific |= 0x80; /* WP */
6555		}
6556		if (dbd)
6557			scsi_ulto2b(0, header->block_descr_len);
6558		else
6559			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6560				    header->block_descr_len);
6561		block_desc = (struct scsi_mode_block_descr *)&header[1];
6562		break;
6563	}
6564	default:
6565		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6566	}
6567
6568	/*
6569	 * If we've got a disk, use its blocksize in the block
6570	 * descriptor.  Otherwise, just set it to 0.
6571	 */
6572	if (dbd == 0) {
6573		if (lun->be_lun->lun_type == T_DIRECT)
6574			scsi_ulto3b(lun->be_lun->blocksize,
6575				    block_desc->block_len);
6576		else
6577			scsi_ulto3b(0, block_desc->block_len);
6578	}
6579
6580	switch (page_code) {
6581	case SMS_ALL_PAGES_PAGE: {
6582		int i, data_used;
6583
6584		data_used = header_len;
6585		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6586			struct ctl_page_index *page_index;
6587
6588			page_index = &lun->mode_pages.index[i];
6589			if (lun->be_lun->lun_type == T_DIRECT &&
6590			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6591				continue;
6592			if (lun->be_lun->lun_type == T_PROCESSOR &&
6593			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6594				continue;
6595			if (lun->be_lun->lun_type == T_CDROM &&
6596			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6597				continue;
6598
6599			/*
6600			 * We don't use this subpage if the user didn't
6601			 * request all subpages.  We already checked (above)
6602			 * to make sure the user only specified a subpage
6603			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6604			 */
6605			if ((page_index->subpage != 0)
6606			 && (subpage == SMS_SUBPAGE_PAGE_0))
6607				continue;
6608
6609			/*
6610			 * Call the handler, if it exists, to update the
6611			 * page to the latest values.
6612			 */
6613			if (page_index->sense_handler != NULL)
6614				page_index->sense_handler(ctsio, page_index,pc);
6615
6616			memcpy(ctsio->kern_data_ptr + data_used,
6617			       page_index->page_data +
6618			       (page_index->page_len * pc),
6619			       page_index->page_len);
6620			data_used += page_index->page_len;
6621		}
6622		break;
6623	}
6624	default: {
6625		int i, data_used;
6626
6627		data_used = header_len;
6628
6629		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6630			struct ctl_page_index *page_index;
6631
6632			page_index = &lun->mode_pages.index[i];
6633
6634			/* Look for the right page code */
6635			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6636				continue;
6637
6638			/* Look for the right subpage or the subpage wildcard*/
6639			if ((page_index->subpage != subpage)
6640			 && (subpage != SMS_SUBPAGE_ALL))
6641				continue;
6642
6643			/* Make sure the page is supported for this dev type */
6644			if (lun->be_lun->lun_type == T_DIRECT &&
6645			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6646				continue;
6647			if (lun->be_lun->lun_type == T_PROCESSOR &&
6648			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6649				continue;
6650			if (lun->be_lun->lun_type == T_CDROM &&
6651			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6652				continue;
6653
6654			/*
6655			 * Call the handler, if it exists, to update the
6656			 * page to the latest values.
6657			 */
6658			if (page_index->sense_handler != NULL)
6659				page_index->sense_handler(ctsio, page_index,pc);
6660
6661			memcpy(ctsio->kern_data_ptr + data_used,
6662			       page_index->page_data +
6663			       (page_index->page_len * pc),
6664			       page_index->page_len);
6665			data_used += page_index->page_len;
6666		}
6667		break;
6668	}
6669	}
6670
6671	ctl_set_success(ctsio);
6672	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6673	ctsio->be_move_done = ctl_config_move_done;
6674	ctl_datamove((union ctl_io *)ctsio);
6675	return (CTL_RETVAL_COMPLETE);
6676}
6677
6678int
6679ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6680			       struct ctl_page_index *page_index,
6681			       int pc)
6682{
6683	struct ctl_lun *lun = CTL_LUN(ctsio);
6684	struct scsi_log_param_header *phdr;
6685	uint8_t *data;
6686	uint64_t val;
6687
6688	data = page_index->page_data;
6689
6690	if (lun->backend->lun_attr != NULL &&
6691	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6692	     != UINT64_MAX) {
6693		phdr = (struct scsi_log_param_header *)data;
6694		scsi_ulto2b(0x0001, phdr->param_code);
6695		phdr->param_control = SLP_LBIN | SLP_LP;
6696		phdr->param_len = 8;
6697		data = (uint8_t *)(phdr + 1);
6698		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6699		data[4] = 0x02; /* per-pool */
6700		data += phdr->param_len;
6701	}
6702
6703	if (lun->backend->lun_attr != NULL &&
6704	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6705	     != UINT64_MAX) {
6706		phdr = (struct scsi_log_param_header *)data;
6707		scsi_ulto2b(0x0002, phdr->param_code);
6708		phdr->param_control = SLP_LBIN | SLP_LP;
6709		phdr->param_len = 8;
6710		data = (uint8_t *)(phdr + 1);
6711		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6712		data[4] = 0x01; /* per-LUN */
6713		data += phdr->param_len;
6714	}
6715
6716	if (lun->backend->lun_attr != NULL &&
6717	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6718	     != UINT64_MAX) {
6719		phdr = (struct scsi_log_param_header *)data;
6720		scsi_ulto2b(0x00f1, phdr->param_code);
6721		phdr->param_control = SLP_LBIN | SLP_LP;
6722		phdr->param_len = 8;
6723		data = (uint8_t *)(phdr + 1);
6724		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6725		data[4] = 0x02; /* per-pool */
6726		data += phdr->param_len;
6727	}
6728
6729	if (lun->backend->lun_attr != NULL &&
6730	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6731	     != UINT64_MAX) {
6732		phdr = (struct scsi_log_param_header *)data;
6733		scsi_ulto2b(0x00f2, phdr->param_code);
6734		phdr->param_control = SLP_LBIN | SLP_LP;
6735		phdr->param_len = 8;
6736		data = (uint8_t *)(phdr + 1);
6737		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6738		data[4] = 0x02; /* per-pool */
6739		data += phdr->param_len;
6740	}
6741
6742	page_index->page_len = data - page_index->page_data;
6743	return (0);
6744}
6745
6746int
6747ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6748			       struct ctl_page_index *page_index,
6749			       int pc)
6750{
6751	struct ctl_lun *lun = CTL_LUN(ctsio);
6752	struct stat_page *data;
6753	struct bintime *t;
6754
6755	data = (struct stat_page *)page_index->page_data;
6756
6757	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6758	data->sap.hdr.param_control = SLP_LBIN;
6759	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6760	    sizeof(struct scsi_log_param_header);
6761	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6762	    data->sap.read_num);
6763	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6764	    data->sap.write_num);
6765	if (lun->be_lun->blocksize > 0) {
6766		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6767		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6768		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6769		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6770	}
6771	t = &lun->stats.time[CTL_STATS_READ];
6772	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6773	    data->sap.read_int);
6774	t = &lun->stats.time[CTL_STATS_WRITE];
6775	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6776	    data->sap.write_int);
6777	scsi_u64to8b(0, data->sap.weighted_num);
6778	scsi_u64to8b(0, data->sap.weighted_int);
6779	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6780	data->it.hdr.param_control = SLP_LBIN;
6781	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6782	    sizeof(struct scsi_log_param_header);
6783#ifdef CTL_TIME_IO
6784	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6785#endif
6786	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6787	data->it.hdr.param_control = SLP_LBIN;
6788	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6789	    sizeof(struct scsi_log_param_header);
6790	scsi_ulto4b(3, data->ti.exponent);
6791	scsi_ulto4b(1, data->ti.integer);
6792	return (0);
6793}
6794
6795int
6796ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6797			       struct ctl_page_index *page_index,
6798			       int pc)
6799{
6800	struct ctl_lun *lun = CTL_LUN(ctsio);
6801	struct scsi_log_informational_exceptions *data;
6802
6803	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6804
6805	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6806	data->hdr.param_control = SLP_LBIN;
6807	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6808	    sizeof(struct scsi_log_param_header);
6809	data->ie_asc = lun->ie_asc;
6810	data->ie_ascq = lun->ie_ascq;
6811	data->temperature = 0xff;
6812	return (0);
6813}
6814
6815int
6816ctl_log_sense(struct ctl_scsiio *ctsio)
6817{
6818	struct ctl_lun *lun = CTL_LUN(ctsio);
6819	int i, pc, page_code, subpage;
6820	int alloc_len, total_len;
6821	struct ctl_page_index *page_index;
6822	struct scsi_log_sense *cdb;
6823	struct scsi_log_header *header;
6824
6825	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6826
6827	cdb = (struct scsi_log_sense *)ctsio->cdb;
6828	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6829	page_code = cdb->page & SLS_PAGE_CODE;
6830	subpage = cdb->subpage;
6831	alloc_len = scsi_2btoul(cdb->length);
6832
6833	page_index = NULL;
6834	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6835		page_index = &lun->log_pages.index[i];
6836
6837		/* Look for the right page code */
6838		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6839			continue;
6840
6841		/* Look for the right subpage or the subpage wildcard*/
6842		if (page_index->subpage != subpage)
6843			continue;
6844
6845		break;
6846	}
6847	if (i >= CTL_NUM_LOG_PAGES) {
6848		ctl_set_invalid_field(ctsio,
6849				      /*sks_valid*/ 1,
6850				      /*command*/ 1,
6851				      /*field*/ 2,
6852				      /*bit_valid*/ 0,
6853				      /*bit*/ 0);
6854		ctl_done((union ctl_io *)ctsio);
6855		return (CTL_RETVAL_COMPLETE);
6856	}
6857
6858	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6859
6860	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6861	ctsio->kern_sg_entries = 0;
6862	ctsio->kern_rel_offset = 0;
6863	ctsio->kern_data_len = min(total_len, alloc_len);
6864	ctsio->kern_total_len = ctsio->kern_data_len;
6865
6866	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6867	header->page = page_index->page_code;
6868	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6869		header->page |= SL_DS;
6870	if (page_index->subpage) {
6871		header->page |= SL_SPF;
6872		header->subpage = page_index->subpage;
6873	}
6874	scsi_ulto2b(page_index->page_len, header->datalen);
6875
6876	/*
6877	 * Call the handler, if it exists, to update the
6878	 * page to the latest values.
6879	 */
6880	if (page_index->sense_handler != NULL)
6881		page_index->sense_handler(ctsio, page_index, pc);
6882
6883	memcpy(header + 1, page_index->page_data, page_index->page_len);
6884
6885	ctl_set_success(ctsio);
6886	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6887	ctsio->be_move_done = ctl_config_move_done;
6888	ctl_datamove((union ctl_io *)ctsio);
6889	return (CTL_RETVAL_COMPLETE);
6890}
6891
6892int
6893ctl_read_capacity(struct ctl_scsiio *ctsio)
6894{
6895	struct ctl_lun *lun = CTL_LUN(ctsio);
6896	struct scsi_read_capacity *cdb;
6897	struct scsi_read_capacity_data *data;
6898	uint32_t lba;
6899
6900	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6901
6902	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6903
6904	lba = scsi_4btoul(cdb->addr);
6905	if (((cdb->pmi & SRC_PMI) == 0)
6906	 && (lba != 0)) {
6907		ctl_set_invalid_field(/*ctsio*/ ctsio,
6908				      /*sks_valid*/ 1,
6909				      /*command*/ 1,
6910				      /*field*/ 2,
6911				      /*bit_valid*/ 0,
6912				      /*bit*/ 0);
6913		ctl_done((union ctl_io *)ctsio);
6914		return (CTL_RETVAL_COMPLETE);
6915	}
6916
6917	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6918	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6919	ctsio->kern_data_len = sizeof(*data);
6920	ctsio->kern_total_len = sizeof(*data);
6921	ctsio->kern_rel_offset = 0;
6922	ctsio->kern_sg_entries = 0;
6923
6924	/*
6925	 * If the maximum LBA is greater than 0xfffffffe, the user must
6926	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6927	 * serivce action set.
6928	 */
6929	if (lun->be_lun->maxlba > 0xfffffffe)
6930		scsi_ulto4b(0xffffffff, data->addr);
6931	else
6932		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6933
6934	/*
6935	 * XXX KDM this may not be 512 bytes...
6936	 */
6937	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6938
6939	ctl_set_success(ctsio);
6940	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6941	ctsio->be_move_done = ctl_config_move_done;
6942	ctl_datamove((union ctl_io *)ctsio);
6943	return (CTL_RETVAL_COMPLETE);
6944}
6945
6946int
6947ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6948{
6949	struct ctl_lun *lun = CTL_LUN(ctsio);
6950	struct scsi_read_capacity_16 *cdb;
6951	struct scsi_read_capacity_data_long *data;
6952	uint64_t lba;
6953	uint32_t alloc_len;
6954
6955	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6956
6957	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6958
6959	alloc_len = scsi_4btoul(cdb->alloc_len);
6960	lba = scsi_8btou64(cdb->addr);
6961
6962	if ((cdb->reladr & SRC16_PMI)
6963	 && (lba != 0)) {
6964		ctl_set_invalid_field(/*ctsio*/ ctsio,
6965				      /*sks_valid*/ 1,
6966				      /*command*/ 1,
6967				      /*field*/ 2,
6968				      /*bit_valid*/ 0,
6969				      /*bit*/ 0);
6970		ctl_done((union ctl_io *)ctsio);
6971		return (CTL_RETVAL_COMPLETE);
6972	}
6973
6974	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6975	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6976	ctsio->kern_rel_offset = 0;
6977	ctsio->kern_sg_entries = 0;
6978	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
6979	ctsio->kern_total_len = ctsio->kern_data_len;
6980
6981	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6982	/* XXX KDM this may not be 512 bytes... */
6983	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6984	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6985	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6986	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6987		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6988
6989	ctl_set_success(ctsio);
6990	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6991	ctsio->be_move_done = ctl_config_move_done;
6992	ctl_datamove((union ctl_io *)ctsio);
6993	return (CTL_RETVAL_COMPLETE);
6994}
6995
6996int
6997ctl_get_lba_status(struct ctl_scsiio *ctsio)
6998{
6999	struct ctl_lun *lun = CTL_LUN(ctsio);
7000	struct scsi_get_lba_status *cdb;
7001	struct scsi_get_lba_status_data *data;
7002	struct ctl_lba_len_flags *lbalen;
7003	uint64_t lba;
7004	uint32_t alloc_len, total_len;
7005	int retval;
7006
7007	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7008
7009	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7010	lba = scsi_8btou64(cdb->addr);
7011	alloc_len = scsi_4btoul(cdb->alloc_len);
7012
7013	if (lba > lun->be_lun->maxlba) {
7014		ctl_set_lba_out_of_range(ctsio, lba);
7015		ctl_done((union ctl_io *)ctsio);
7016		return (CTL_RETVAL_COMPLETE);
7017	}
7018
7019	total_len = sizeof(*data) + sizeof(data->descr[0]);
7020	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7021	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7022	ctsio->kern_rel_offset = 0;
7023	ctsio->kern_sg_entries = 0;
7024	ctsio->kern_data_len = min(total_len, alloc_len);
7025	ctsio->kern_total_len = ctsio->kern_data_len;
7026
7027	/* Fill dummy data in case backend can't tell anything. */
7028	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7029	scsi_u64to8b(lba, data->descr[0].addr);
7030	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7031	    data->descr[0].length);
7032	data->descr[0].status = 0; /* Mapped or unknown. */
7033
7034	ctl_set_success(ctsio);
7035	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7036	ctsio->be_move_done = ctl_config_move_done;
7037
7038	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7039	lbalen->lba = lba;
7040	lbalen->len = total_len;
7041	lbalen->flags = 0;
7042	retval = lun->backend->config_read((union ctl_io *)ctsio);
7043	return (retval);
7044}
7045
7046int
7047ctl_read_defect(struct ctl_scsiio *ctsio)
7048{
7049	struct scsi_read_defect_data_10 *ccb10;
7050	struct scsi_read_defect_data_12 *ccb12;
7051	struct scsi_read_defect_data_hdr_10 *data10;
7052	struct scsi_read_defect_data_hdr_12 *data12;
7053	uint32_t alloc_len, data_len;
7054	uint8_t format;
7055
7056	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7057
7058	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7059		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7060		format = ccb10->format;
7061		alloc_len = scsi_2btoul(ccb10->alloc_length);
7062		data_len = sizeof(*data10);
7063	} else {
7064		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7065		format = ccb12->format;
7066		alloc_len = scsi_4btoul(ccb12->alloc_length);
7067		data_len = sizeof(*data12);
7068	}
7069	if (alloc_len == 0) {
7070		ctl_set_success(ctsio);
7071		ctl_done((union ctl_io *)ctsio);
7072		return (CTL_RETVAL_COMPLETE);
7073	}
7074
7075	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7076	ctsio->kern_rel_offset = 0;
7077	ctsio->kern_sg_entries = 0;
7078	ctsio->kern_data_len = min(data_len, alloc_len);
7079	ctsio->kern_total_len = ctsio->kern_data_len;
7080
7081	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7082		data10 = (struct scsi_read_defect_data_hdr_10 *)
7083		    ctsio->kern_data_ptr;
7084		data10->format = format;
7085		scsi_ulto2b(0, data10->length);
7086	} else {
7087		data12 = (struct scsi_read_defect_data_hdr_12 *)
7088		    ctsio->kern_data_ptr;
7089		data12->format = format;
7090		scsi_ulto2b(0, data12->generation);
7091		scsi_ulto4b(0, data12->length);
7092	}
7093
7094	ctl_set_success(ctsio);
7095	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7096	ctsio->be_move_done = ctl_config_move_done;
7097	ctl_datamove((union ctl_io *)ctsio);
7098	return (CTL_RETVAL_COMPLETE);
7099}
7100
7101int
7102ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7103{
7104	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7105	struct ctl_lun *lun = CTL_LUN(ctsio);
7106	struct scsi_maintenance_in *cdb;
7107	int retval;
7108	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7109	int num_ha_groups, num_target_ports, shared_group;
7110	struct ctl_port *port;
7111	struct scsi_target_group_data *rtg_ptr;
7112	struct scsi_target_group_data_extended *rtg_ext_ptr;
7113	struct scsi_target_port_group_descriptor *tpg_desc;
7114
7115	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7116
7117	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7118	retval = CTL_RETVAL_COMPLETE;
7119
7120	switch (cdb->byte2 & STG_PDF_MASK) {
7121	case STG_PDF_LENGTH:
7122		ext = 0;
7123		break;
7124	case STG_PDF_EXTENDED:
7125		ext = 1;
7126		break;
7127	default:
7128		ctl_set_invalid_field(/*ctsio*/ ctsio,
7129				      /*sks_valid*/ 1,
7130				      /*command*/ 1,
7131				      /*field*/ 2,
7132				      /*bit_valid*/ 1,
7133				      /*bit*/ 5);
7134		ctl_done((union ctl_io *)ctsio);
7135		return(retval);
7136	}
7137
7138	num_target_ports = 0;
7139	shared_group = (softc->is_single != 0);
7140	mtx_lock(&softc->ctl_lock);
7141	STAILQ_FOREACH(port, &softc->port_list, links) {
7142		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7143			continue;
7144		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7145			continue;
7146		num_target_ports++;
7147		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7148			shared_group = 1;
7149	}
7150	mtx_unlock(&softc->ctl_lock);
7151	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7152
7153	if (ext)
7154		total_len = sizeof(struct scsi_target_group_data_extended);
7155	else
7156		total_len = sizeof(struct scsi_target_group_data);
7157	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7158		(shared_group + num_ha_groups) +
7159	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7160
7161	alloc_len = scsi_4btoul(cdb->length);
7162
7163	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7164	ctsio->kern_sg_entries = 0;
7165	ctsio->kern_rel_offset = 0;
7166	ctsio->kern_data_len = min(total_len, alloc_len);
7167	ctsio->kern_total_len = ctsio->kern_data_len;
7168
7169	if (ext) {
7170		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7171		    ctsio->kern_data_ptr;
7172		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7173		rtg_ext_ptr->format_type = 0x10;
7174		rtg_ext_ptr->implicit_transition_time = 0;
7175		tpg_desc = &rtg_ext_ptr->groups[0];
7176	} else {
7177		rtg_ptr = (struct scsi_target_group_data *)
7178		    ctsio->kern_data_ptr;
7179		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7180		tpg_desc = &rtg_ptr->groups[0];
7181	}
7182
7183	mtx_lock(&softc->ctl_lock);
7184	pg = softc->port_min / softc->port_cnt;
7185	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7186		/* Some shelf is known to be primary. */
7187		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7188			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7189		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7190			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7191		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7192			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7193		else
7194			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7195		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7196			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7197		} else {
7198			ts = os;
7199			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7200		}
7201	} else {
7202		/* No known primary shelf. */
7203		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7204			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7205			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7206		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7207			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7208			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7209		} else {
7210			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7211		}
7212	}
7213	if (shared_group) {
7214		tpg_desc->pref_state = ts;
7215		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7216		    TPG_U_SUP | TPG_T_SUP;
7217		scsi_ulto2b(1, tpg_desc->target_port_group);
7218		tpg_desc->status = TPG_IMPLICIT;
7219		pc = 0;
7220		STAILQ_FOREACH(port, &softc->port_list, links) {
7221			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7222				continue;
7223			if (!softc->is_single &&
7224			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7225				continue;
7226			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7227				continue;
7228			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7229			    relative_target_port_identifier);
7230			pc++;
7231		}
7232		tpg_desc->target_port_count = pc;
7233		tpg_desc = (struct scsi_target_port_group_descriptor *)
7234		    &tpg_desc->descriptors[pc];
7235	}
7236	for (g = 0; g < num_ha_groups; g++) {
7237		tpg_desc->pref_state = (g == pg) ? ts : os;
7238		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7239		    TPG_U_SUP | TPG_T_SUP;
7240		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7241		tpg_desc->status = TPG_IMPLICIT;
7242		pc = 0;
7243		STAILQ_FOREACH(port, &softc->port_list, links) {
7244			if (port->targ_port < g * softc->port_cnt ||
7245			    port->targ_port >= (g + 1) * softc->port_cnt)
7246				continue;
7247			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7248				continue;
7249			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7250				continue;
7251			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7252				continue;
7253			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7254			    relative_target_port_identifier);
7255			pc++;
7256		}
7257		tpg_desc->target_port_count = pc;
7258		tpg_desc = (struct scsi_target_port_group_descriptor *)
7259		    &tpg_desc->descriptors[pc];
7260	}
7261	mtx_unlock(&softc->ctl_lock);
7262
7263	ctl_set_success(ctsio);
7264	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7265	ctsio->be_move_done = ctl_config_move_done;
7266	ctl_datamove((union ctl_io *)ctsio);
7267	return(retval);
7268}
7269
7270int
7271ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7272{
7273	struct ctl_lun *lun = CTL_LUN(ctsio);
7274	struct scsi_report_supported_opcodes *cdb;
7275	const struct ctl_cmd_entry *entry, *sentry;
7276	struct scsi_report_supported_opcodes_all *all;
7277	struct scsi_report_supported_opcodes_descr *descr;
7278	struct scsi_report_supported_opcodes_one *one;
7279	int retval;
7280	int alloc_len, total_len;
7281	int opcode, service_action, i, j, num;
7282
7283	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7284
7285	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7286	retval = CTL_RETVAL_COMPLETE;
7287
7288	opcode = cdb->requested_opcode;
7289	service_action = scsi_2btoul(cdb->requested_service_action);
7290	switch (cdb->options & RSO_OPTIONS_MASK) {
7291	case RSO_OPTIONS_ALL:
7292		num = 0;
7293		for (i = 0; i < 256; i++) {
7294			entry = &ctl_cmd_table[i];
7295			if (entry->flags & CTL_CMD_FLAG_SA5) {
7296				for (j = 0; j < 32; j++) {
7297					sentry = &((const struct ctl_cmd_entry *)
7298					    entry->execute)[j];
7299					if (ctl_cmd_applicable(
7300					    lun->be_lun->lun_type, sentry))
7301						num++;
7302				}
7303			} else {
7304				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7305				    entry))
7306					num++;
7307			}
7308		}
7309		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7310		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7311		break;
7312	case RSO_OPTIONS_OC:
7313		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7314			ctl_set_invalid_field(/*ctsio*/ ctsio,
7315					      /*sks_valid*/ 1,
7316					      /*command*/ 1,
7317					      /*field*/ 2,
7318					      /*bit_valid*/ 1,
7319					      /*bit*/ 2);
7320			ctl_done((union ctl_io *)ctsio);
7321			return (CTL_RETVAL_COMPLETE);
7322		}
7323		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7324		break;
7325	case RSO_OPTIONS_OC_SA:
7326		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7327		    service_action >= 32) {
7328			ctl_set_invalid_field(/*ctsio*/ ctsio,
7329					      /*sks_valid*/ 1,
7330					      /*command*/ 1,
7331					      /*field*/ 2,
7332					      /*bit_valid*/ 1,
7333					      /*bit*/ 2);
7334			ctl_done((union ctl_io *)ctsio);
7335			return (CTL_RETVAL_COMPLETE);
7336		}
7337		/* FALLTHROUGH */
7338	case RSO_OPTIONS_OC_ASA:
7339		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7340		break;
7341	default:
7342		ctl_set_invalid_field(/*ctsio*/ ctsio,
7343				      /*sks_valid*/ 1,
7344				      /*command*/ 1,
7345				      /*field*/ 2,
7346				      /*bit_valid*/ 1,
7347				      /*bit*/ 2);
7348		ctl_done((union ctl_io *)ctsio);
7349		return (CTL_RETVAL_COMPLETE);
7350	}
7351
7352	alloc_len = scsi_4btoul(cdb->length);
7353
7354	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7355	ctsio->kern_sg_entries = 0;
7356	ctsio->kern_rel_offset = 0;
7357	ctsio->kern_data_len = min(total_len, alloc_len);
7358	ctsio->kern_total_len = ctsio->kern_data_len;
7359
7360	switch (cdb->options & RSO_OPTIONS_MASK) {
7361	case RSO_OPTIONS_ALL:
7362		all = (struct scsi_report_supported_opcodes_all *)
7363		    ctsio->kern_data_ptr;
7364		num = 0;
7365		for (i = 0; i < 256; i++) {
7366			entry = &ctl_cmd_table[i];
7367			if (entry->flags & CTL_CMD_FLAG_SA5) {
7368				for (j = 0; j < 32; j++) {
7369					sentry = &((const struct ctl_cmd_entry *)
7370					    entry->execute)[j];
7371					if (!ctl_cmd_applicable(
7372					    lun->be_lun->lun_type, sentry))
7373						continue;
7374					descr = &all->descr[num++];
7375					descr->opcode = i;
7376					scsi_ulto2b(j, descr->service_action);
7377					descr->flags = RSO_SERVACTV;
7378					scsi_ulto2b(sentry->length,
7379					    descr->cdb_length);
7380				}
7381			} else {
7382				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7383				    entry))
7384					continue;
7385				descr = &all->descr[num++];
7386				descr->opcode = i;
7387				scsi_ulto2b(0, descr->service_action);
7388				descr->flags = 0;
7389				scsi_ulto2b(entry->length, descr->cdb_length);
7390			}
7391		}
7392		scsi_ulto4b(
7393		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7394		    all->length);
7395		break;
7396	case RSO_OPTIONS_OC:
7397		one = (struct scsi_report_supported_opcodes_one *)
7398		    ctsio->kern_data_ptr;
7399		entry = &ctl_cmd_table[opcode];
7400		goto fill_one;
7401	case RSO_OPTIONS_OC_SA:
7402		one = (struct scsi_report_supported_opcodes_one *)
7403		    ctsio->kern_data_ptr;
7404		entry = &ctl_cmd_table[opcode];
7405		entry = &((const struct ctl_cmd_entry *)
7406		    entry->execute)[service_action];
7407fill_one:
7408		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7409			one->support = 3;
7410			scsi_ulto2b(entry->length, one->cdb_length);
7411			one->cdb_usage[0] = opcode;
7412			memcpy(&one->cdb_usage[1], entry->usage,
7413			    entry->length - 1);
7414		} else
7415			one->support = 1;
7416		break;
7417	case RSO_OPTIONS_OC_ASA:
7418		one = (struct scsi_report_supported_opcodes_one *)
7419		    ctsio->kern_data_ptr;
7420		entry = &ctl_cmd_table[opcode];
7421		if (entry->flags & CTL_CMD_FLAG_SA5) {
7422			entry = &((const struct ctl_cmd_entry *)
7423			    entry->execute)[service_action];
7424		} else if (service_action != 0) {
7425			one->support = 1;
7426			break;
7427		}
7428		goto fill_one;
7429	}
7430
7431	ctl_set_success(ctsio);
7432	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7433	ctsio->be_move_done = ctl_config_move_done;
7434	ctl_datamove((union ctl_io *)ctsio);
7435	return(retval);
7436}
7437
7438int
7439ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7440{
7441	struct scsi_report_supported_tmf *cdb;
7442	struct scsi_report_supported_tmf_ext_data *data;
7443	int retval;
7444	int alloc_len, total_len;
7445
7446	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7447
7448	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7449
7450	retval = CTL_RETVAL_COMPLETE;
7451
7452	if (cdb->options & RST_REPD)
7453		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7454	else
7455		total_len = sizeof(struct scsi_report_supported_tmf_data);
7456	alloc_len = scsi_4btoul(cdb->length);
7457
7458	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7459	ctsio->kern_sg_entries = 0;
7460	ctsio->kern_rel_offset = 0;
7461	ctsio->kern_data_len = min(total_len, alloc_len);
7462	ctsio->kern_total_len = ctsio->kern_data_len;
7463
7464	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7465	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7466	    RST_TRS;
7467	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7468	data->length = total_len - 4;
7469
7470	ctl_set_success(ctsio);
7471	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7472	ctsio->be_move_done = ctl_config_move_done;
7473	ctl_datamove((union ctl_io *)ctsio);
7474	return (retval);
7475}
7476
7477int
7478ctl_report_timestamp(struct ctl_scsiio *ctsio)
7479{
7480	struct scsi_report_timestamp *cdb;
7481	struct scsi_report_timestamp_data *data;
7482	struct timeval tv;
7483	int64_t timestamp;
7484	int retval;
7485	int alloc_len, total_len;
7486
7487	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7488
7489	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7490
7491	retval = CTL_RETVAL_COMPLETE;
7492
7493	total_len = sizeof(struct scsi_report_timestamp_data);
7494	alloc_len = scsi_4btoul(cdb->length);
7495
7496	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7497	ctsio->kern_sg_entries = 0;
7498	ctsio->kern_rel_offset = 0;
7499	ctsio->kern_data_len = min(total_len, alloc_len);
7500	ctsio->kern_total_len = ctsio->kern_data_len;
7501
7502	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7503	scsi_ulto2b(sizeof(*data) - 2, data->length);
7504	data->origin = RTS_ORIG_OUTSIDE;
7505	getmicrotime(&tv);
7506	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7507	scsi_ulto4b(timestamp >> 16, data->timestamp);
7508	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7509
7510	ctl_set_success(ctsio);
7511	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7512	ctsio->be_move_done = ctl_config_move_done;
7513	ctl_datamove((union ctl_io *)ctsio);
7514	return (retval);
7515}
7516
7517int
7518ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7519{
7520	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7521	struct ctl_lun *lun = CTL_LUN(ctsio);
7522	struct scsi_per_res_in *cdb;
7523	int alloc_len, total_len = 0;
7524	/* struct scsi_per_res_in_rsrv in_data; */
7525	uint64_t key;
7526
7527	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7528
7529	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7530
7531	alloc_len = scsi_2btoul(cdb->length);
7532
7533retry:
7534	mtx_lock(&lun->lun_lock);
7535	switch (cdb->action) {
7536	case SPRI_RK: /* read keys */
7537		total_len = sizeof(struct scsi_per_res_in_keys) +
7538			lun->pr_key_count *
7539			sizeof(struct scsi_per_res_key);
7540		break;
7541	case SPRI_RR: /* read reservation */
7542		if (lun->flags & CTL_LUN_PR_RESERVED)
7543			total_len = sizeof(struct scsi_per_res_in_rsrv);
7544		else
7545			total_len = sizeof(struct scsi_per_res_in_header);
7546		break;
7547	case SPRI_RC: /* report capabilities */
7548		total_len = sizeof(struct scsi_per_res_cap);
7549		break;
7550	case SPRI_RS: /* read full status */
7551		total_len = sizeof(struct scsi_per_res_in_header) +
7552		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7553		    lun->pr_key_count;
7554		break;
7555	default:
7556		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7557	}
7558	mtx_unlock(&lun->lun_lock);
7559
7560	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7561	ctsio->kern_rel_offset = 0;
7562	ctsio->kern_sg_entries = 0;
7563	ctsio->kern_data_len = min(total_len, alloc_len);
7564	ctsio->kern_total_len = ctsio->kern_data_len;
7565
7566	mtx_lock(&lun->lun_lock);
7567	switch (cdb->action) {
7568	case SPRI_RK: { // read keys
7569        struct scsi_per_res_in_keys *res_keys;
7570		int i, key_count;
7571
7572		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7573
7574		/*
7575		 * We had to drop the lock to allocate our buffer, which
7576		 * leaves time for someone to come in with another
7577		 * persistent reservation.  (That is unlikely, though,
7578		 * since this should be the only persistent reservation
7579		 * command active right now.)
7580		 */
7581		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7582		    (lun->pr_key_count *
7583		     sizeof(struct scsi_per_res_key)))){
7584			mtx_unlock(&lun->lun_lock);
7585			free(ctsio->kern_data_ptr, M_CTL);
7586			printf("%s: reservation length changed, retrying\n",
7587			       __func__);
7588			goto retry;
7589		}
7590
7591		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7592
7593		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7594			     lun->pr_key_count, res_keys->header.length);
7595
7596		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7597			if ((key = ctl_get_prkey(lun, i)) == 0)
7598				continue;
7599
7600			/*
7601			 * We used lun->pr_key_count to calculate the
7602			 * size to allocate.  If it turns out the number of
7603			 * initiators with the registered flag set is
7604			 * larger than that (i.e. they haven't been kept in
7605			 * sync), we've got a problem.
7606			 */
7607			if (key_count >= lun->pr_key_count) {
7608				key_count++;
7609				continue;
7610			}
7611			scsi_u64to8b(key, res_keys->keys[key_count].key);
7612			key_count++;
7613		}
7614		break;
7615	}
7616	case SPRI_RR: { // read reservation
7617		struct scsi_per_res_in_rsrv *res;
7618		int tmp_len, header_only;
7619
7620		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7621
7622		scsi_ulto4b(lun->pr_generation, res->header.generation);
7623
7624		if (lun->flags & CTL_LUN_PR_RESERVED)
7625		{
7626			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7627			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7628				    res->header.length);
7629			header_only = 0;
7630		} else {
7631			tmp_len = sizeof(struct scsi_per_res_in_header);
7632			scsi_ulto4b(0, res->header.length);
7633			header_only = 1;
7634		}
7635
7636		/*
7637		 * We had to drop the lock to allocate our buffer, which
7638		 * leaves time for someone to come in with another
7639		 * persistent reservation.  (That is unlikely, though,
7640		 * since this should be the only persistent reservation
7641		 * command active right now.)
7642		 */
7643		if (tmp_len != total_len) {
7644			mtx_unlock(&lun->lun_lock);
7645			free(ctsio->kern_data_ptr, M_CTL);
7646			printf("%s: reservation status changed, retrying\n",
7647			       __func__);
7648			goto retry;
7649		}
7650
7651		/*
7652		 * No reservation held, so we're done.
7653		 */
7654		if (header_only != 0)
7655			break;
7656
7657		/*
7658		 * If the registration is an All Registrants type, the key
7659		 * is 0, since it doesn't really matter.
7660		 */
7661		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7662			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7663			    res->data.reservation);
7664		}
7665		res->data.scopetype = lun->pr_res_type;
7666		break;
7667	}
7668	case SPRI_RC:     //report capabilities
7669	{
7670		struct scsi_per_res_cap *res_cap;
7671		uint16_t type_mask;
7672
7673		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7674		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7675		res_cap->flags1 = SPRI_CRH;
7676		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7677		type_mask = SPRI_TM_WR_EX_AR |
7678			    SPRI_TM_EX_AC_RO |
7679			    SPRI_TM_WR_EX_RO |
7680			    SPRI_TM_EX_AC |
7681			    SPRI_TM_WR_EX |
7682			    SPRI_TM_EX_AC_AR;
7683		scsi_ulto2b(type_mask, res_cap->type_mask);
7684		break;
7685	}
7686	case SPRI_RS: { // read full status
7687		struct scsi_per_res_in_full *res_status;
7688		struct scsi_per_res_in_full_desc *res_desc;
7689		struct ctl_port *port;
7690		int i, len;
7691
7692		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7693
7694		/*
7695		 * We had to drop the lock to allocate our buffer, which
7696		 * leaves time for someone to come in with another
7697		 * persistent reservation.  (That is unlikely, though,
7698		 * since this should be the only persistent reservation
7699		 * command active right now.)
7700		 */
7701		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7702		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7703		     lun->pr_key_count)){
7704			mtx_unlock(&lun->lun_lock);
7705			free(ctsio->kern_data_ptr, M_CTL);
7706			printf("%s: reservation length changed, retrying\n",
7707			       __func__);
7708			goto retry;
7709		}
7710
7711		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7712
7713		res_desc = &res_status->desc[0];
7714		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7715			if ((key = ctl_get_prkey(lun, i)) == 0)
7716				continue;
7717
7718			scsi_u64to8b(key, res_desc->res_key.key);
7719			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7720			    (lun->pr_res_idx == i ||
7721			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7722				res_desc->flags = SPRI_FULL_R_HOLDER;
7723				res_desc->scopetype = lun->pr_res_type;
7724			}
7725			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7726			    res_desc->rel_trgt_port_id);
7727			len = 0;
7728			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7729			if (port != NULL)
7730				len = ctl_create_iid(port,
7731				    i % CTL_MAX_INIT_PER_PORT,
7732				    res_desc->transport_id);
7733			scsi_ulto4b(len, res_desc->additional_length);
7734			res_desc = (struct scsi_per_res_in_full_desc *)
7735			    &res_desc->transport_id[len];
7736		}
7737		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7738		    res_status->header.length);
7739		break;
7740	}
7741	default:
7742		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7743	}
7744	mtx_unlock(&lun->lun_lock);
7745
7746	ctl_set_success(ctsio);
7747	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7748	ctsio->be_move_done = ctl_config_move_done;
7749	ctl_datamove((union ctl_io *)ctsio);
7750	return (CTL_RETVAL_COMPLETE);
7751}
7752
7753/*
7754 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7755 * it should return.
7756 */
7757static int
7758ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7759		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7760		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7761		struct scsi_per_res_out_parms* param)
7762{
7763	union ctl_ha_msg persis_io;
7764	int i;
7765
7766	mtx_lock(&lun->lun_lock);
7767	if (sa_res_key == 0) {
7768		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7769			/* validate scope and type */
7770			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7771			     SPR_LU_SCOPE) {
7772				mtx_unlock(&lun->lun_lock);
7773				ctl_set_invalid_field(/*ctsio*/ ctsio,
7774						      /*sks_valid*/ 1,
7775						      /*command*/ 1,
7776						      /*field*/ 2,
7777						      /*bit_valid*/ 1,
7778						      /*bit*/ 4);
7779				ctl_done((union ctl_io *)ctsio);
7780				return (1);
7781			}
7782
7783		        if (type>8 || type==2 || type==4 || type==0) {
7784				mtx_unlock(&lun->lun_lock);
7785				ctl_set_invalid_field(/*ctsio*/ ctsio,
7786       	           				      /*sks_valid*/ 1,
7787						      /*command*/ 1,
7788						      /*field*/ 2,
7789						      /*bit_valid*/ 1,
7790						      /*bit*/ 0);
7791				ctl_done((union ctl_io *)ctsio);
7792				return (1);
7793		        }
7794
7795			/*
7796			 * Unregister everybody else and build UA for
7797			 * them
7798			 */
7799			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7800				if (i == residx || ctl_get_prkey(lun, i) == 0)
7801					continue;
7802
7803				ctl_clr_prkey(lun, i);
7804				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7805			}
7806			lun->pr_key_count = 1;
7807			lun->pr_res_type = type;
7808			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7809			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7810				lun->pr_res_idx = residx;
7811			lun->pr_generation++;
7812			mtx_unlock(&lun->lun_lock);
7813
7814			/* send msg to other side */
7815			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7816			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7817			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7818			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7819			persis_io.pr.pr_info.res_type = type;
7820			memcpy(persis_io.pr.pr_info.sa_res_key,
7821			       param->serv_act_res_key,
7822			       sizeof(param->serv_act_res_key));
7823			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7824			    sizeof(persis_io.pr), M_WAITOK);
7825		} else {
7826			/* not all registrants */
7827			mtx_unlock(&lun->lun_lock);
7828			free(ctsio->kern_data_ptr, M_CTL);
7829			ctl_set_invalid_field(ctsio,
7830					      /*sks_valid*/ 1,
7831					      /*command*/ 0,
7832					      /*field*/ 8,
7833					      /*bit_valid*/ 0,
7834					      /*bit*/ 0);
7835			ctl_done((union ctl_io *)ctsio);
7836			return (1);
7837		}
7838	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7839		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7840		int found = 0;
7841
7842		if (res_key == sa_res_key) {
7843			/* special case */
7844			/*
7845			 * The spec implies this is not good but doesn't
7846			 * say what to do. There are two choices either
7847			 * generate a res conflict or check condition
7848			 * with illegal field in parameter data. Since
7849			 * that is what is done when the sa_res_key is
7850			 * zero I'll take that approach since this has
7851			 * to do with the sa_res_key.
7852			 */
7853			mtx_unlock(&lun->lun_lock);
7854			free(ctsio->kern_data_ptr, M_CTL);
7855			ctl_set_invalid_field(ctsio,
7856					      /*sks_valid*/ 1,
7857					      /*command*/ 0,
7858					      /*field*/ 8,
7859					      /*bit_valid*/ 0,
7860					      /*bit*/ 0);
7861			ctl_done((union ctl_io *)ctsio);
7862			return (1);
7863		}
7864
7865		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7866			if (ctl_get_prkey(lun, i) != sa_res_key)
7867				continue;
7868
7869			found = 1;
7870			ctl_clr_prkey(lun, i);
7871			lun->pr_key_count--;
7872			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7873		}
7874		if (!found) {
7875			mtx_unlock(&lun->lun_lock);
7876			free(ctsio->kern_data_ptr, M_CTL);
7877			ctl_set_reservation_conflict(ctsio);
7878			ctl_done((union ctl_io *)ctsio);
7879			return (CTL_RETVAL_COMPLETE);
7880		}
7881		lun->pr_generation++;
7882		mtx_unlock(&lun->lun_lock);
7883
7884		/* send msg to other side */
7885		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7886		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7887		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7888		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7889		persis_io.pr.pr_info.res_type = type;
7890		memcpy(persis_io.pr.pr_info.sa_res_key,
7891		       param->serv_act_res_key,
7892		       sizeof(param->serv_act_res_key));
7893		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7894		    sizeof(persis_io.pr), M_WAITOK);
7895	} else {
7896		/* Reserved but not all registrants */
7897		/* sa_res_key is res holder */
7898		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7899			/* validate scope and type */
7900			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7901			     SPR_LU_SCOPE) {
7902				mtx_unlock(&lun->lun_lock);
7903				ctl_set_invalid_field(/*ctsio*/ ctsio,
7904						      /*sks_valid*/ 1,
7905						      /*command*/ 1,
7906						      /*field*/ 2,
7907						      /*bit_valid*/ 1,
7908						      /*bit*/ 4);
7909				ctl_done((union ctl_io *)ctsio);
7910				return (1);
7911			}
7912
7913			if (type>8 || type==2 || type==4 || type==0) {
7914				mtx_unlock(&lun->lun_lock);
7915				ctl_set_invalid_field(/*ctsio*/ ctsio,
7916						      /*sks_valid*/ 1,
7917						      /*command*/ 1,
7918						      /*field*/ 2,
7919						      /*bit_valid*/ 1,
7920						      /*bit*/ 0);
7921				ctl_done((union ctl_io *)ctsio);
7922				return (1);
7923			}
7924
7925			/*
7926			 * Do the following:
7927			 * if sa_res_key != res_key remove all
7928			 * registrants w/sa_res_key and generate UA
7929			 * for these registrants(Registrations
7930			 * Preempted) if it wasn't an exclusive
7931			 * reservation generate UA(Reservations
7932			 * Preempted) for all other registered nexuses
7933			 * if the type has changed. Establish the new
7934			 * reservation and holder. If res_key and
7935			 * sa_res_key are the same do the above
7936			 * except don't unregister the res holder.
7937			 */
7938
7939			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7940				if (i == residx || ctl_get_prkey(lun, i) == 0)
7941					continue;
7942
7943				if (sa_res_key == ctl_get_prkey(lun, i)) {
7944					ctl_clr_prkey(lun, i);
7945					lun->pr_key_count--;
7946					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7947				} else if (type != lun->pr_res_type &&
7948				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7949				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7950					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7951				}
7952			}
7953			lun->pr_res_type = type;
7954			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7955			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7956				lun->pr_res_idx = residx;
7957			else
7958				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7959			lun->pr_generation++;
7960			mtx_unlock(&lun->lun_lock);
7961
7962			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7963			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7964			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7965			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7966			persis_io.pr.pr_info.res_type = type;
7967			memcpy(persis_io.pr.pr_info.sa_res_key,
7968			       param->serv_act_res_key,
7969			       sizeof(param->serv_act_res_key));
7970			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7971			    sizeof(persis_io.pr), M_WAITOK);
7972		} else {
7973			/*
7974			 * sa_res_key is not the res holder just
7975			 * remove registrants
7976			 */
7977			int found=0;
7978
7979			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7980				if (sa_res_key != ctl_get_prkey(lun, i))
7981					continue;
7982
7983				found = 1;
7984				ctl_clr_prkey(lun, i);
7985				lun->pr_key_count--;
7986				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7987			}
7988
7989			if (!found) {
7990				mtx_unlock(&lun->lun_lock);
7991				free(ctsio->kern_data_ptr, M_CTL);
7992				ctl_set_reservation_conflict(ctsio);
7993				ctl_done((union ctl_io *)ctsio);
7994		        	return (1);
7995			}
7996			lun->pr_generation++;
7997			mtx_unlock(&lun->lun_lock);
7998
7999			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8000			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8001			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8002			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8003			persis_io.pr.pr_info.res_type = type;
8004			memcpy(persis_io.pr.pr_info.sa_res_key,
8005			       param->serv_act_res_key,
8006			       sizeof(param->serv_act_res_key));
8007			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8008			    sizeof(persis_io.pr), M_WAITOK);
8009		}
8010	}
8011	return (0);
8012}
8013
8014static void
8015ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8016{
8017	uint64_t sa_res_key;
8018	int i;
8019
8020	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8021
8022	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8023	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8024	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8025		if (sa_res_key == 0) {
8026			/*
8027			 * Unregister everybody else and build UA for
8028			 * them
8029			 */
8030			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8031				if (i == msg->pr.pr_info.residx ||
8032				    ctl_get_prkey(lun, i) == 0)
8033					continue;
8034
8035				ctl_clr_prkey(lun, i);
8036				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8037			}
8038
8039			lun->pr_key_count = 1;
8040			lun->pr_res_type = msg->pr.pr_info.res_type;
8041			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8042			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8043				lun->pr_res_idx = msg->pr.pr_info.residx;
8044		} else {
8045		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8046				if (sa_res_key == ctl_get_prkey(lun, i))
8047					continue;
8048
8049				ctl_clr_prkey(lun, i);
8050				lun->pr_key_count--;
8051				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8052			}
8053		}
8054	} else {
8055		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8056			if (i == msg->pr.pr_info.residx ||
8057			    ctl_get_prkey(lun, i) == 0)
8058				continue;
8059
8060			if (sa_res_key == ctl_get_prkey(lun, i)) {
8061				ctl_clr_prkey(lun, i);
8062				lun->pr_key_count--;
8063				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8064			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8065			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8066			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8067				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8068			}
8069		}
8070		lun->pr_res_type = msg->pr.pr_info.res_type;
8071		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8072		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8073			lun->pr_res_idx = msg->pr.pr_info.residx;
8074		else
8075			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8076	}
8077	lun->pr_generation++;
8078
8079}
8080
8081
8082int
8083ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8084{
8085	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8086	struct ctl_lun *lun = CTL_LUN(ctsio);
8087	int retval;
8088	u_int32_t param_len;
8089	struct scsi_per_res_out *cdb;
8090	struct scsi_per_res_out_parms* param;
8091	uint32_t residx;
8092	uint64_t res_key, sa_res_key, key;
8093	uint8_t type;
8094	union ctl_ha_msg persis_io;
8095	int    i;
8096
8097	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8098
8099	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8100	retval = CTL_RETVAL_COMPLETE;
8101
8102	/*
8103	 * We only support whole-LUN scope.  The scope & type are ignored for
8104	 * register, register and ignore existing key and clear.
8105	 * We sometimes ignore scope and type on preempts too!!
8106	 * Verify reservation type here as well.
8107	 */
8108	type = cdb->scope_type & SPR_TYPE_MASK;
8109	if ((cdb->action == SPRO_RESERVE)
8110	 || (cdb->action == SPRO_RELEASE)) {
8111		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8112			ctl_set_invalid_field(/*ctsio*/ ctsio,
8113					      /*sks_valid*/ 1,
8114					      /*command*/ 1,
8115					      /*field*/ 2,
8116					      /*bit_valid*/ 1,
8117					      /*bit*/ 4);
8118			ctl_done((union ctl_io *)ctsio);
8119			return (CTL_RETVAL_COMPLETE);
8120		}
8121
8122		if (type>8 || type==2 || type==4 || type==0) {
8123			ctl_set_invalid_field(/*ctsio*/ ctsio,
8124					      /*sks_valid*/ 1,
8125					      /*command*/ 1,
8126					      /*field*/ 2,
8127					      /*bit_valid*/ 1,
8128					      /*bit*/ 0);
8129			ctl_done((union ctl_io *)ctsio);
8130			return (CTL_RETVAL_COMPLETE);
8131		}
8132	}
8133
8134	param_len = scsi_4btoul(cdb->length);
8135
8136	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8137		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8138		ctsio->kern_data_len = param_len;
8139		ctsio->kern_total_len = param_len;
8140		ctsio->kern_rel_offset = 0;
8141		ctsio->kern_sg_entries = 0;
8142		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8143		ctsio->be_move_done = ctl_config_move_done;
8144		ctl_datamove((union ctl_io *)ctsio);
8145
8146		return (CTL_RETVAL_COMPLETE);
8147	}
8148
8149	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8150
8151	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8152	res_key = scsi_8btou64(param->res_key.key);
8153	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8154
8155	/*
8156	 * Validate the reservation key here except for SPRO_REG_IGNO
8157	 * This must be done for all other service actions
8158	 */
8159	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8160		mtx_lock(&lun->lun_lock);
8161		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8162			if (res_key != key) {
8163				/*
8164				 * The current key passed in doesn't match
8165				 * the one the initiator previously
8166				 * registered.
8167				 */
8168				mtx_unlock(&lun->lun_lock);
8169				free(ctsio->kern_data_ptr, M_CTL);
8170				ctl_set_reservation_conflict(ctsio);
8171				ctl_done((union ctl_io *)ctsio);
8172				return (CTL_RETVAL_COMPLETE);
8173			}
8174		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8175			/*
8176			 * We are not registered
8177			 */
8178			mtx_unlock(&lun->lun_lock);
8179			free(ctsio->kern_data_ptr, M_CTL);
8180			ctl_set_reservation_conflict(ctsio);
8181			ctl_done((union ctl_io *)ctsio);
8182			return (CTL_RETVAL_COMPLETE);
8183		} else if (res_key != 0) {
8184			/*
8185			 * We are not registered and trying to register but
8186			 * the register key isn't zero.
8187			 */
8188			mtx_unlock(&lun->lun_lock);
8189			free(ctsio->kern_data_ptr, M_CTL);
8190			ctl_set_reservation_conflict(ctsio);
8191			ctl_done((union ctl_io *)ctsio);
8192			return (CTL_RETVAL_COMPLETE);
8193		}
8194		mtx_unlock(&lun->lun_lock);
8195	}
8196
8197	switch (cdb->action & SPRO_ACTION_MASK) {
8198	case SPRO_REGISTER:
8199	case SPRO_REG_IGNO: {
8200
8201#if 0
8202		printf("Registration received\n");
8203#endif
8204
8205		/*
8206		 * We don't support any of these options, as we report in
8207		 * the read capabilities request (see
8208		 * ctl_persistent_reserve_in(), above).
8209		 */
8210		if ((param->flags & SPR_SPEC_I_PT)
8211		 || (param->flags & SPR_ALL_TG_PT)
8212		 || (param->flags & SPR_APTPL)) {
8213			int bit_ptr;
8214
8215			if (param->flags & SPR_APTPL)
8216				bit_ptr = 0;
8217			else if (param->flags & SPR_ALL_TG_PT)
8218				bit_ptr = 2;
8219			else /* SPR_SPEC_I_PT */
8220				bit_ptr = 3;
8221
8222			free(ctsio->kern_data_ptr, M_CTL);
8223			ctl_set_invalid_field(ctsio,
8224					      /*sks_valid*/ 1,
8225					      /*command*/ 0,
8226					      /*field*/ 20,
8227					      /*bit_valid*/ 1,
8228					      /*bit*/ bit_ptr);
8229			ctl_done((union ctl_io *)ctsio);
8230			return (CTL_RETVAL_COMPLETE);
8231		}
8232
8233		mtx_lock(&lun->lun_lock);
8234
8235		/*
8236		 * The initiator wants to clear the
8237		 * key/unregister.
8238		 */
8239		if (sa_res_key == 0) {
8240			if ((res_key == 0
8241			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8242			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8243			  && ctl_get_prkey(lun, residx) == 0)) {
8244				mtx_unlock(&lun->lun_lock);
8245				goto done;
8246			}
8247
8248			ctl_clr_prkey(lun, residx);
8249			lun->pr_key_count--;
8250
8251			if (residx == lun->pr_res_idx) {
8252				lun->flags &= ~CTL_LUN_PR_RESERVED;
8253				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8254
8255				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8256				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8257				    lun->pr_key_count) {
8258					/*
8259					 * If the reservation is a registrants
8260					 * only type we need to generate a UA
8261					 * for other registered inits.  The
8262					 * sense code should be RESERVATIONS
8263					 * RELEASED
8264					 */
8265
8266					for (i = softc->init_min; i < softc->init_max; i++){
8267						if (ctl_get_prkey(lun, i) == 0)
8268							continue;
8269						ctl_est_ua(lun, i,
8270						    CTL_UA_RES_RELEASE);
8271					}
8272				}
8273				lun->pr_res_type = 0;
8274			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8275				if (lun->pr_key_count==0) {
8276					lun->flags &= ~CTL_LUN_PR_RESERVED;
8277					lun->pr_res_type = 0;
8278					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8279				}
8280			}
8281			lun->pr_generation++;
8282			mtx_unlock(&lun->lun_lock);
8283
8284			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8285			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8286			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8287			persis_io.pr.pr_info.residx = residx;
8288			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8289			    sizeof(persis_io.pr), M_WAITOK);
8290		} else /* sa_res_key != 0 */ {
8291
8292			/*
8293			 * If we aren't registered currently then increment
8294			 * the key count and set the registered flag.
8295			 */
8296			ctl_alloc_prkey(lun, residx);
8297			if (ctl_get_prkey(lun, residx) == 0)
8298				lun->pr_key_count++;
8299			ctl_set_prkey(lun, residx, sa_res_key);
8300			lun->pr_generation++;
8301			mtx_unlock(&lun->lun_lock);
8302
8303			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8304			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8305			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8306			persis_io.pr.pr_info.residx = residx;
8307			memcpy(persis_io.pr.pr_info.sa_res_key,
8308			       param->serv_act_res_key,
8309			       sizeof(param->serv_act_res_key));
8310			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8311			    sizeof(persis_io.pr), M_WAITOK);
8312		}
8313
8314		break;
8315	}
8316	case SPRO_RESERVE:
8317#if 0
8318                printf("Reserve executed type %d\n", type);
8319#endif
8320		mtx_lock(&lun->lun_lock);
8321		if (lun->flags & CTL_LUN_PR_RESERVED) {
8322			/*
8323			 * if this isn't the reservation holder and it's
8324			 * not a "all registrants" type or if the type is
8325			 * different then we have a conflict
8326			 */
8327			if ((lun->pr_res_idx != residx
8328			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8329			 || lun->pr_res_type != type) {
8330				mtx_unlock(&lun->lun_lock);
8331				free(ctsio->kern_data_ptr, M_CTL);
8332				ctl_set_reservation_conflict(ctsio);
8333				ctl_done((union ctl_io *)ctsio);
8334				return (CTL_RETVAL_COMPLETE);
8335			}
8336			mtx_unlock(&lun->lun_lock);
8337		} else /* create a reservation */ {
8338			/*
8339			 * If it's not an "all registrants" type record
8340			 * reservation holder
8341			 */
8342			if (type != SPR_TYPE_WR_EX_AR
8343			 && type != SPR_TYPE_EX_AC_AR)
8344				lun->pr_res_idx = residx; /* Res holder */
8345			else
8346				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8347
8348			lun->flags |= CTL_LUN_PR_RESERVED;
8349			lun->pr_res_type = type;
8350
8351			mtx_unlock(&lun->lun_lock);
8352
8353			/* send msg to other side */
8354			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8355			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8356			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8357			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8358			persis_io.pr.pr_info.res_type = type;
8359			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8360			    sizeof(persis_io.pr), M_WAITOK);
8361		}
8362		break;
8363
8364	case SPRO_RELEASE:
8365		mtx_lock(&lun->lun_lock);
8366		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8367			/* No reservation exists return good status */
8368			mtx_unlock(&lun->lun_lock);
8369			goto done;
8370		}
8371		/*
8372		 * Is this nexus a reservation holder?
8373		 */
8374		if (lun->pr_res_idx != residx
8375		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8376			/*
8377			 * not a res holder return good status but
8378			 * do nothing
8379			 */
8380			mtx_unlock(&lun->lun_lock);
8381			goto done;
8382		}
8383
8384		if (lun->pr_res_type != type) {
8385			mtx_unlock(&lun->lun_lock);
8386			free(ctsio->kern_data_ptr, M_CTL);
8387			ctl_set_illegal_pr_release(ctsio);
8388			ctl_done((union ctl_io *)ctsio);
8389			return (CTL_RETVAL_COMPLETE);
8390		}
8391
8392		/* okay to release */
8393		lun->flags &= ~CTL_LUN_PR_RESERVED;
8394		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8395		lun->pr_res_type = 0;
8396
8397		/*
8398		 * If this isn't an exclusive access reservation and NUAR
8399		 * is not set, generate UA for all other registrants.
8400		 */
8401		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8402		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8403			for (i = softc->init_min; i < softc->init_max; i++) {
8404				if (i == residx || ctl_get_prkey(lun, i) == 0)
8405					continue;
8406				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8407			}
8408		}
8409		mtx_unlock(&lun->lun_lock);
8410
8411		/* Send msg to other side */
8412		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8413		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8414		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8415		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8416		     sizeof(persis_io.pr), M_WAITOK);
8417		break;
8418
8419	case SPRO_CLEAR:
8420		/* send msg to other side */
8421
8422		mtx_lock(&lun->lun_lock);
8423		lun->flags &= ~CTL_LUN_PR_RESERVED;
8424		lun->pr_res_type = 0;
8425		lun->pr_key_count = 0;
8426		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8427
8428		ctl_clr_prkey(lun, residx);
8429		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8430			if (ctl_get_prkey(lun, i) != 0) {
8431				ctl_clr_prkey(lun, i);
8432				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8433			}
8434		lun->pr_generation++;
8435		mtx_unlock(&lun->lun_lock);
8436
8437		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8438		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8439		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8440		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8441		     sizeof(persis_io.pr), M_WAITOK);
8442		break;
8443
8444	case SPRO_PREEMPT:
8445	case SPRO_PRE_ABO: {
8446		int nretval;
8447
8448		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8449					  residx, ctsio, cdb, param);
8450		if (nretval != 0)
8451			return (CTL_RETVAL_COMPLETE);
8452		break;
8453	}
8454	default:
8455		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8456	}
8457
8458done:
8459	free(ctsio->kern_data_ptr, M_CTL);
8460	ctl_set_success(ctsio);
8461	ctl_done((union ctl_io *)ctsio);
8462
8463	return (retval);
8464}
8465
8466/*
8467 * This routine is for handling a message from the other SC pertaining to
8468 * persistent reserve out. All the error checking will have been done
8469 * so only perorming the action need be done here to keep the two
8470 * in sync.
8471 */
8472static void
8473ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8474{
8475	struct ctl_softc *softc = CTL_SOFTC(io);
8476	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8477	struct ctl_lun *lun;
8478	int i;
8479	uint32_t residx, targ_lun;
8480
8481	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8482	mtx_lock(&softc->ctl_lock);
8483	if (targ_lun >= CTL_MAX_LUNS ||
8484	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8485		mtx_unlock(&softc->ctl_lock);
8486		return;
8487	}
8488	mtx_lock(&lun->lun_lock);
8489	mtx_unlock(&softc->ctl_lock);
8490	if (lun->flags & CTL_LUN_DISABLED) {
8491		mtx_unlock(&lun->lun_lock);
8492		return;
8493	}
8494	residx = ctl_get_initindex(&msg->hdr.nexus);
8495	switch(msg->pr.pr_info.action) {
8496	case CTL_PR_REG_KEY:
8497		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8498		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8499			lun->pr_key_count++;
8500		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8501		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8502		lun->pr_generation++;
8503		break;
8504
8505	case CTL_PR_UNREG_KEY:
8506		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8507		lun->pr_key_count--;
8508
8509		/* XXX Need to see if the reservation has been released */
8510		/* if so do we need to generate UA? */
8511		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8512			lun->flags &= ~CTL_LUN_PR_RESERVED;
8513			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8514
8515			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8516			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8517			    lun->pr_key_count) {
8518				/*
8519				 * If the reservation is a registrants
8520				 * only type we need to generate a UA
8521				 * for other registered inits.  The
8522				 * sense code should be RESERVATIONS
8523				 * RELEASED
8524				 */
8525
8526				for (i = softc->init_min; i < softc->init_max; i++) {
8527					if (ctl_get_prkey(lun, i) == 0)
8528						continue;
8529
8530					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8531				}
8532			}
8533			lun->pr_res_type = 0;
8534		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8535			if (lun->pr_key_count==0) {
8536				lun->flags &= ~CTL_LUN_PR_RESERVED;
8537				lun->pr_res_type = 0;
8538				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8539			}
8540		}
8541		lun->pr_generation++;
8542		break;
8543
8544	case CTL_PR_RESERVE:
8545		lun->flags |= CTL_LUN_PR_RESERVED;
8546		lun->pr_res_type = msg->pr.pr_info.res_type;
8547		lun->pr_res_idx = msg->pr.pr_info.residx;
8548
8549		break;
8550
8551	case CTL_PR_RELEASE:
8552		/*
8553		 * If this isn't an exclusive access reservation and NUAR
8554		 * is not set, generate UA for all other registrants.
8555		 */
8556		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8557		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8558		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8559			for (i = softc->init_min; i < softc->init_max; i++)
8560				if (i == residx || ctl_get_prkey(lun, i) == 0)
8561					continue;
8562				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8563		}
8564
8565		lun->flags &= ~CTL_LUN_PR_RESERVED;
8566		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8567		lun->pr_res_type = 0;
8568		break;
8569
8570	case CTL_PR_PREEMPT:
8571		ctl_pro_preempt_other(lun, msg);
8572		break;
8573	case CTL_PR_CLEAR:
8574		lun->flags &= ~CTL_LUN_PR_RESERVED;
8575		lun->pr_res_type = 0;
8576		lun->pr_key_count = 0;
8577		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8578
8579		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8580			if (ctl_get_prkey(lun, i) == 0)
8581				continue;
8582			ctl_clr_prkey(lun, i);
8583			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8584		}
8585		lun->pr_generation++;
8586		break;
8587	}
8588
8589	mtx_unlock(&lun->lun_lock);
8590}
8591
8592int
8593ctl_read_write(struct ctl_scsiio *ctsio)
8594{
8595	struct ctl_lun *lun = CTL_LUN(ctsio);
8596	struct ctl_lba_len_flags *lbalen;
8597	uint64_t lba;
8598	uint32_t num_blocks;
8599	int flags, retval;
8600	int isread;
8601
8602	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8603
8604	flags = 0;
8605	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8606	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8607	switch (ctsio->cdb[0]) {
8608	case READ_6:
8609	case WRITE_6: {
8610		struct scsi_rw_6 *cdb;
8611
8612		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8613
8614		lba = scsi_3btoul(cdb->addr);
8615		/* only 5 bits are valid in the most significant address byte */
8616		lba &= 0x1fffff;
8617		num_blocks = cdb->length;
8618		/*
8619		 * This is correct according to SBC-2.
8620		 */
8621		if (num_blocks == 0)
8622			num_blocks = 256;
8623		break;
8624	}
8625	case READ_10:
8626	case WRITE_10: {
8627		struct scsi_rw_10 *cdb;
8628
8629		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8630		if (cdb->byte2 & SRW10_FUA)
8631			flags |= CTL_LLF_FUA;
8632		if (cdb->byte2 & SRW10_DPO)
8633			flags |= CTL_LLF_DPO;
8634		lba = scsi_4btoul(cdb->addr);
8635		num_blocks = scsi_2btoul(cdb->length);
8636		break;
8637	}
8638	case WRITE_VERIFY_10: {
8639		struct scsi_write_verify_10 *cdb;
8640
8641		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8642		flags |= CTL_LLF_FUA;
8643		if (cdb->byte2 & SWV_DPO)
8644			flags |= CTL_LLF_DPO;
8645		lba = scsi_4btoul(cdb->addr);
8646		num_blocks = scsi_2btoul(cdb->length);
8647		break;
8648	}
8649	case READ_12:
8650	case WRITE_12: {
8651		struct scsi_rw_12 *cdb;
8652
8653		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8654		if (cdb->byte2 & SRW12_FUA)
8655			flags |= CTL_LLF_FUA;
8656		if (cdb->byte2 & SRW12_DPO)
8657			flags |= CTL_LLF_DPO;
8658		lba = scsi_4btoul(cdb->addr);
8659		num_blocks = scsi_4btoul(cdb->length);
8660		break;
8661	}
8662	case WRITE_VERIFY_12: {
8663		struct scsi_write_verify_12 *cdb;
8664
8665		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8666		flags |= CTL_LLF_FUA;
8667		if (cdb->byte2 & SWV_DPO)
8668			flags |= CTL_LLF_DPO;
8669		lba = scsi_4btoul(cdb->addr);
8670		num_blocks = scsi_4btoul(cdb->length);
8671		break;
8672	}
8673	case READ_16:
8674	case WRITE_16: {
8675		struct scsi_rw_16 *cdb;
8676
8677		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8678		if (cdb->byte2 & SRW12_FUA)
8679			flags |= CTL_LLF_FUA;
8680		if (cdb->byte2 & SRW12_DPO)
8681			flags |= CTL_LLF_DPO;
8682		lba = scsi_8btou64(cdb->addr);
8683		num_blocks = scsi_4btoul(cdb->length);
8684		break;
8685	}
8686	case WRITE_ATOMIC_16: {
8687		struct scsi_write_atomic_16 *cdb;
8688
8689		if (lun->be_lun->atomicblock == 0) {
8690			ctl_set_invalid_opcode(ctsio);
8691			ctl_done((union ctl_io *)ctsio);
8692			return (CTL_RETVAL_COMPLETE);
8693		}
8694
8695		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8696		if (cdb->byte2 & SRW12_FUA)
8697			flags |= CTL_LLF_FUA;
8698		if (cdb->byte2 & SRW12_DPO)
8699			flags |= CTL_LLF_DPO;
8700		lba = scsi_8btou64(cdb->addr);
8701		num_blocks = scsi_2btoul(cdb->length);
8702		if (num_blocks > lun->be_lun->atomicblock) {
8703			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8704			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8705			    /*bit*/ 0);
8706			ctl_done((union ctl_io *)ctsio);
8707			return (CTL_RETVAL_COMPLETE);
8708		}
8709		break;
8710	}
8711	case WRITE_VERIFY_16: {
8712		struct scsi_write_verify_16 *cdb;
8713
8714		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8715		flags |= CTL_LLF_FUA;
8716		if (cdb->byte2 & SWV_DPO)
8717			flags |= CTL_LLF_DPO;
8718		lba = scsi_8btou64(cdb->addr);
8719		num_blocks = scsi_4btoul(cdb->length);
8720		break;
8721	}
8722	default:
8723		/*
8724		 * We got a command we don't support.  This shouldn't
8725		 * happen, commands should be filtered out above us.
8726		 */
8727		ctl_set_invalid_opcode(ctsio);
8728		ctl_done((union ctl_io *)ctsio);
8729
8730		return (CTL_RETVAL_COMPLETE);
8731		break; /* NOTREACHED */
8732	}
8733
8734	/*
8735	 * The first check is to make sure we're in bounds, the second
8736	 * check is to catch wrap-around problems.  If the lba + num blocks
8737	 * is less than the lba, then we've wrapped around and the block
8738	 * range is invalid anyway.
8739	 */
8740	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8741	 || ((lba + num_blocks) < lba)) {
8742		ctl_set_lba_out_of_range(ctsio,
8743		    MAX(lba, lun->be_lun->maxlba + 1));
8744		ctl_done((union ctl_io *)ctsio);
8745		return (CTL_RETVAL_COMPLETE);
8746	}
8747
8748	/*
8749	 * According to SBC-3, a transfer length of 0 is not an error.
8750	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8751	 * translates to 256 blocks for those commands.
8752	 */
8753	if (num_blocks == 0) {
8754		ctl_set_success(ctsio);
8755		ctl_done((union ctl_io *)ctsio);
8756		return (CTL_RETVAL_COMPLETE);
8757	}
8758
8759	/* Set FUA and/or DPO if caches are disabled. */
8760	if (isread) {
8761		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8762			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8763	} else {
8764		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8765			flags |= CTL_LLF_FUA;
8766	}
8767
8768	lbalen = (struct ctl_lba_len_flags *)
8769	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8770	lbalen->lba = lba;
8771	lbalen->len = num_blocks;
8772	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8773
8774	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8775	ctsio->kern_rel_offset = 0;
8776
8777	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8778
8779	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8780	return (retval);
8781}
8782
8783static int
8784ctl_cnw_cont(union ctl_io *io)
8785{
8786	struct ctl_lun *lun = CTL_LUN(io);
8787	struct ctl_scsiio *ctsio;
8788	struct ctl_lba_len_flags *lbalen;
8789	int retval;
8790
8791	ctsio = &io->scsiio;
8792	ctsio->io_hdr.status = CTL_STATUS_NONE;
8793	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8794	lbalen = (struct ctl_lba_len_flags *)
8795	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8796	lbalen->flags &= ~CTL_LLF_COMPARE;
8797	lbalen->flags |= CTL_LLF_WRITE;
8798
8799	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8800	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8801	return (retval);
8802}
8803
8804int
8805ctl_cnw(struct ctl_scsiio *ctsio)
8806{
8807	struct ctl_lun *lun = CTL_LUN(ctsio);
8808	struct ctl_lba_len_flags *lbalen;
8809	uint64_t lba;
8810	uint32_t num_blocks;
8811	int flags, retval;
8812
8813	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8814
8815	flags = 0;
8816	switch (ctsio->cdb[0]) {
8817	case COMPARE_AND_WRITE: {
8818		struct scsi_compare_and_write *cdb;
8819
8820		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8821		if (cdb->byte2 & SRW10_FUA)
8822			flags |= CTL_LLF_FUA;
8823		if (cdb->byte2 & SRW10_DPO)
8824			flags |= CTL_LLF_DPO;
8825		lba = scsi_8btou64(cdb->addr);
8826		num_blocks = cdb->length;
8827		break;
8828	}
8829	default:
8830		/*
8831		 * We got a command we don't support.  This shouldn't
8832		 * happen, commands should be filtered out above us.
8833		 */
8834		ctl_set_invalid_opcode(ctsio);
8835		ctl_done((union ctl_io *)ctsio);
8836
8837		return (CTL_RETVAL_COMPLETE);
8838		break; /* NOTREACHED */
8839	}
8840
8841	/*
8842	 * The first check is to make sure we're in bounds, the second
8843	 * check is to catch wrap-around problems.  If the lba + num blocks
8844	 * is less than the lba, then we've wrapped around and the block
8845	 * range is invalid anyway.
8846	 */
8847	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8848	 || ((lba + num_blocks) < lba)) {
8849		ctl_set_lba_out_of_range(ctsio,
8850		    MAX(lba, lun->be_lun->maxlba + 1));
8851		ctl_done((union ctl_io *)ctsio);
8852		return (CTL_RETVAL_COMPLETE);
8853	}
8854
8855	/*
8856	 * According to SBC-3, a transfer length of 0 is not an error.
8857	 */
8858	if (num_blocks == 0) {
8859		ctl_set_success(ctsio);
8860		ctl_done((union ctl_io *)ctsio);
8861		return (CTL_RETVAL_COMPLETE);
8862	}
8863
8864	/* Set FUA if write cache is disabled. */
8865	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8866		flags |= CTL_LLF_FUA;
8867
8868	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8869	ctsio->kern_rel_offset = 0;
8870
8871	/*
8872	 * Set the IO_CONT flag, so that if this I/O gets passed to
8873	 * ctl_data_submit_done(), it'll get passed back to
8874	 * ctl_ctl_cnw_cont() for further processing.
8875	 */
8876	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8877	ctsio->io_cont = ctl_cnw_cont;
8878
8879	lbalen = (struct ctl_lba_len_flags *)
8880	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8881	lbalen->lba = lba;
8882	lbalen->len = num_blocks;
8883	lbalen->flags = CTL_LLF_COMPARE | flags;
8884
8885	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8886	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8887	return (retval);
8888}
8889
8890int
8891ctl_verify(struct ctl_scsiio *ctsio)
8892{
8893	struct ctl_lun *lun = CTL_LUN(ctsio);
8894	struct ctl_lba_len_flags *lbalen;
8895	uint64_t lba;
8896	uint32_t num_blocks;
8897	int bytchk, flags;
8898	int retval;
8899
8900	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8901
8902	bytchk = 0;
8903	flags = CTL_LLF_FUA;
8904	switch (ctsio->cdb[0]) {
8905	case VERIFY_10: {
8906		struct scsi_verify_10 *cdb;
8907
8908		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8909		if (cdb->byte2 & SVFY_BYTCHK)
8910			bytchk = 1;
8911		if (cdb->byte2 & SVFY_DPO)
8912			flags |= CTL_LLF_DPO;
8913		lba = scsi_4btoul(cdb->addr);
8914		num_blocks = scsi_2btoul(cdb->length);
8915		break;
8916	}
8917	case VERIFY_12: {
8918		struct scsi_verify_12 *cdb;
8919
8920		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8921		if (cdb->byte2 & SVFY_BYTCHK)
8922			bytchk = 1;
8923		if (cdb->byte2 & SVFY_DPO)
8924			flags |= CTL_LLF_DPO;
8925		lba = scsi_4btoul(cdb->addr);
8926		num_blocks = scsi_4btoul(cdb->length);
8927		break;
8928	}
8929	case VERIFY_16: {
8930		struct scsi_rw_16 *cdb;
8931
8932		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8933		if (cdb->byte2 & SVFY_BYTCHK)
8934			bytchk = 1;
8935		if (cdb->byte2 & SVFY_DPO)
8936			flags |= CTL_LLF_DPO;
8937		lba = scsi_8btou64(cdb->addr);
8938		num_blocks = scsi_4btoul(cdb->length);
8939		break;
8940	}
8941	default:
8942		/*
8943		 * We got a command we don't support.  This shouldn't
8944		 * happen, commands should be filtered out above us.
8945		 */
8946		ctl_set_invalid_opcode(ctsio);
8947		ctl_done((union ctl_io *)ctsio);
8948		return (CTL_RETVAL_COMPLETE);
8949	}
8950
8951	/*
8952	 * The first check is to make sure we're in bounds, the second
8953	 * check is to catch wrap-around problems.  If the lba + num blocks
8954	 * is less than the lba, then we've wrapped around and the block
8955	 * range is invalid anyway.
8956	 */
8957	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8958	 || ((lba + num_blocks) < lba)) {
8959		ctl_set_lba_out_of_range(ctsio,
8960		    MAX(lba, lun->be_lun->maxlba + 1));
8961		ctl_done((union ctl_io *)ctsio);
8962		return (CTL_RETVAL_COMPLETE);
8963	}
8964
8965	/*
8966	 * According to SBC-3, a transfer length of 0 is not an error.
8967	 */
8968	if (num_blocks == 0) {
8969		ctl_set_success(ctsio);
8970		ctl_done((union ctl_io *)ctsio);
8971		return (CTL_RETVAL_COMPLETE);
8972	}
8973
8974	lbalen = (struct ctl_lba_len_flags *)
8975	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8976	lbalen->lba = lba;
8977	lbalen->len = num_blocks;
8978	if (bytchk) {
8979		lbalen->flags = CTL_LLF_COMPARE | flags;
8980		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8981	} else {
8982		lbalen->flags = CTL_LLF_VERIFY | flags;
8983		ctsio->kern_total_len = 0;
8984	}
8985	ctsio->kern_rel_offset = 0;
8986
8987	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8988	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8989	return (retval);
8990}
8991
8992int
8993ctl_report_luns(struct ctl_scsiio *ctsio)
8994{
8995	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8996	struct ctl_port *port = CTL_PORT(ctsio);
8997	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
8998	struct scsi_report_luns *cdb;
8999	struct scsi_report_luns_data *lun_data;
9000	int num_filled, num_luns, num_port_luns, retval;
9001	uint32_t alloc_len, lun_datalen;
9002	uint32_t initidx, targ_lun_id, lun_id;
9003
9004	retval = CTL_RETVAL_COMPLETE;
9005	cdb = (struct scsi_report_luns *)ctsio->cdb;
9006
9007	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9008
9009	num_luns = 0;
9010	num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9011	mtx_lock(&softc->ctl_lock);
9012	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9013		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9014			num_luns++;
9015	}
9016	mtx_unlock(&softc->ctl_lock);
9017
9018	switch (cdb->select_report) {
9019	case RPL_REPORT_DEFAULT:
9020	case RPL_REPORT_ALL:
9021	case RPL_REPORT_NONSUBSID:
9022		break;
9023	case RPL_REPORT_WELLKNOWN:
9024	case RPL_REPORT_ADMIN:
9025	case RPL_REPORT_CONGLOM:
9026		num_luns = 0;
9027		break;
9028	default:
9029		ctl_set_invalid_field(ctsio,
9030				      /*sks_valid*/ 1,
9031				      /*command*/ 1,
9032				      /*field*/ 2,
9033				      /*bit_valid*/ 0,
9034				      /*bit*/ 0);
9035		ctl_done((union ctl_io *)ctsio);
9036		return (retval);
9037		break; /* NOTREACHED */
9038	}
9039
9040	alloc_len = scsi_4btoul(cdb->length);
9041	/*
9042	 * The initiator has to allocate at least 16 bytes for this request,
9043	 * so he can at least get the header and the first LUN.  Otherwise
9044	 * we reject the request (per SPC-3 rev 14, section 6.21).
9045	 */
9046	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9047	    sizeof(struct scsi_report_luns_lundata))) {
9048		ctl_set_invalid_field(ctsio,
9049				      /*sks_valid*/ 1,
9050				      /*command*/ 1,
9051				      /*field*/ 6,
9052				      /*bit_valid*/ 0,
9053				      /*bit*/ 0);
9054		ctl_done((union ctl_io *)ctsio);
9055		return (retval);
9056	}
9057
9058	lun_datalen = sizeof(*lun_data) +
9059		(num_luns * sizeof(struct scsi_report_luns_lundata));
9060
9061	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9062	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9063	ctsio->kern_sg_entries = 0;
9064
9065	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9066
9067	mtx_lock(&softc->ctl_lock);
9068	for (targ_lun_id = 0, num_filled = 0;
9069	    targ_lun_id < num_port_luns && num_filled < num_luns;
9070	    targ_lun_id++) {
9071		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9072		if (lun_id == UINT32_MAX)
9073			continue;
9074		lun = softc->ctl_luns[lun_id];
9075		if (lun == NULL)
9076			continue;
9077
9078		be64enc(lun_data->luns[num_filled++].lundata,
9079		    ctl_encode_lun(targ_lun_id));
9080
9081		/*
9082		 * According to SPC-3, rev 14 section 6.21:
9083		 *
9084		 * "The execution of a REPORT LUNS command to any valid and
9085		 * installed logical unit shall clear the REPORTED LUNS DATA
9086		 * HAS CHANGED unit attention condition for all logical
9087		 * units of that target with respect to the requesting
9088		 * initiator. A valid and installed logical unit is one
9089		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9090		 * INQUIRY data (see 6.4.2)."
9091		 *
9092		 * If request_lun is NULL, the LUN this report luns command
9093		 * was issued to is either disabled or doesn't exist. In that
9094		 * case, we shouldn't clear any pending lun change unit
9095		 * attention.
9096		 */
9097		if (request_lun != NULL) {
9098			mtx_lock(&lun->lun_lock);
9099			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9100			mtx_unlock(&lun->lun_lock);
9101		}
9102	}
9103	mtx_unlock(&softc->ctl_lock);
9104
9105	/*
9106	 * It's quite possible that we've returned fewer LUNs than we allocated
9107	 * space for.  Trim it.
9108	 */
9109	lun_datalen = sizeof(*lun_data) +
9110		(num_filled * sizeof(struct scsi_report_luns_lundata));
9111	ctsio->kern_rel_offset = 0;
9112	ctsio->kern_sg_entries = 0;
9113	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9114	ctsio->kern_total_len = ctsio->kern_data_len;
9115
9116	/*
9117	 * We set this to the actual data length, regardless of how much
9118	 * space we actually have to return results.  If the user looks at
9119	 * this value, he'll know whether or not he allocated enough space
9120	 * and reissue the command if necessary.  We don't support well
9121	 * known logical units, so if the user asks for that, return none.
9122	 */
9123	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9124
9125	/*
9126	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9127	 * this request.
9128	 */
9129	ctl_set_success(ctsio);
9130	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9131	ctsio->be_move_done = ctl_config_move_done;
9132	ctl_datamove((union ctl_io *)ctsio);
9133	return (retval);
9134}
9135
9136int
9137ctl_request_sense(struct ctl_scsiio *ctsio)
9138{
9139	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9140	struct ctl_lun *lun = CTL_LUN(ctsio);
9141	struct scsi_request_sense *cdb;
9142	struct scsi_sense_data *sense_ptr, *ps;
9143	uint32_t initidx;
9144	int have_error;
9145	u_int sense_len = SSD_FULL_SIZE;
9146	scsi_sense_data_type sense_format;
9147	ctl_ua_type ua_type;
9148	uint8_t asc = 0, ascq = 0;
9149
9150	cdb = (struct scsi_request_sense *)ctsio->cdb;
9151
9152	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9153
9154	/*
9155	 * Determine which sense format the user wants.
9156	 */
9157	if (cdb->byte2 & SRS_DESC)
9158		sense_format = SSD_TYPE_DESC;
9159	else
9160		sense_format = SSD_TYPE_FIXED;
9161
9162	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9163	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9164	ctsio->kern_sg_entries = 0;
9165	ctsio->kern_rel_offset = 0;
9166
9167	/*
9168	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9169	 * larger than the largest allowed value for the length field in the
9170	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9171	 */
9172	ctsio->kern_data_len = cdb->length;
9173	ctsio->kern_total_len = cdb->length;
9174
9175	/*
9176	 * If we don't have a LUN, we don't have any pending sense.
9177	 */
9178	if (lun == NULL ||
9179	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9180	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9181		/* "Logical unit not supported" */
9182		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9183		    /*current_error*/ 1,
9184		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9185		    /*asc*/ 0x25,
9186		    /*ascq*/ 0x00,
9187		    SSD_ELEM_NONE);
9188		goto send;
9189	}
9190
9191	have_error = 0;
9192	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9193	/*
9194	 * Check for pending sense, and then for pending unit attentions.
9195	 * Pending sense gets returned first, then pending unit attentions.
9196	 */
9197	mtx_lock(&lun->lun_lock);
9198	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9199	if (ps != NULL)
9200		ps += initidx % CTL_MAX_INIT_PER_PORT;
9201	if (ps != NULL && ps->error_code != 0) {
9202		scsi_sense_data_type stored_format;
9203
9204		/*
9205		 * Check to see which sense format was used for the stored
9206		 * sense data.
9207		 */
9208		stored_format = scsi_sense_type(ps);
9209
9210		/*
9211		 * If the user requested a different sense format than the
9212		 * one we stored, then we need to convert it to the other
9213		 * format.  If we're going from descriptor to fixed format
9214		 * sense data, we may lose things in translation, depending
9215		 * on what options were used.
9216		 *
9217		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9218		 * for some reason we'll just copy it out as-is.
9219		 */
9220		if ((stored_format == SSD_TYPE_FIXED)
9221		 && (sense_format == SSD_TYPE_DESC))
9222			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9223			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9224		else if ((stored_format == SSD_TYPE_DESC)
9225		      && (sense_format == SSD_TYPE_FIXED))
9226			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9227			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9228		else
9229			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9230
9231		ps->error_code = 0;
9232		have_error = 1;
9233	} else {
9234		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9235		    sense_format);
9236		if (ua_type != CTL_UA_NONE)
9237			have_error = 1;
9238	}
9239	if (have_error == 0) {
9240		/*
9241		 * Report informational exception if have one and allowed.
9242		 */
9243		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9244			asc = lun->ie_asc;
9245			ascq = lun->ie_ascq;
9246		}
9247		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9248		    /*current_error*/ 1,
9249		    /*sense_key*/ SSD_KEY_NO_SENSE,
9250		    /*asc*/ asc,
9251		    /*ascq*/ ascq,
9252		    SSD_ELEM_NONE);
9253	}
9254	mtx_unlock(&lun->lun_lock);
9255
9256send:
9257	/*
9258	 * We report the SCSI status as OK, since the status of the command
9259	 * itself is OK.  We're reporting sense as parameter data.
9260	 */
9261	ctl_set_success(ctsio);
9262	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9263	ctsio->be_move_done = ctl_config_move_done;
9264	ctl_datamove((union ctl_io *)ctsio);
9265	return (CTL_RETVAL_COMPLETE);
9266}
9267
9268int
9269ctl_tur(struct ctl_scsiio *ctsio)
9270{
9271
9272	CTL_DEBUG_PRINT(("ctl_tur\n"));
9273
9274	ctl_set_success(ctsio);
9275	ctl_done((union ctl_io *)ctsio);
9276
9277	return (CTL_RETVAL_COMPLETE);
9278}
9279
9280/*
9281 * SCSI VPD page 0x00, the Supported VPD Pages page.
9282 */
9283static int
9284ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9285{
9286	struct ctl_lun *lun = CTL_LUN(ctsio);
9287	struct scsi_vpd_supported_pages *pages;
9288	int sup_page_size;
9289	int p;
9290
9291	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9292	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9293	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9294	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9295	ctsio->kern_rel_offset = 0;
9296	ctsio->kern_sg_entries = 0;
9297	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9298	ctsio->kern_total_len = ctsio->kern_data_len;
9299
9300	/*
9301	 * The control device is always connected.  The disk device, on the
9302	 * other hand, may not be online all the time.  Need to change this
9303	 * to figure out whether the disk device is actually online or not.
9304	 */
9305	if (lun != NULL)
9306		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9307				lun->be_lun->lun_type;
9308	else
9309		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9310
9311	p = 0;
9312	/* Supported VPD pages */
9313	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9314	/* Serial Number */
9315	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9316	/* Device Identification */
9317	pages->page_list[p++] = SVPD_DEVICE_ID;
9318	/* Extended INQUIRY Data */
9319	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9320	/* Mode Page Policy */
9321	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9322	/* SCSI Ports */
9323	pages->page_list[p++] = SVPD_SCSI_PORTS;
9324	/* Third-party Copy */
9325	pages->page_list[p++] = SVPD_SCSI_TPC;
9326	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9327		/* Block limits */
9328		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9329		/* Block Device Characteristics */
9330		pages->page_list[p++] = SVPD_BDC;
9331		/* Logical Block Provisioning */
9332		pages->page_list[p++] = SVPD_LBP;
9333	}
9334	pages->length = p;
9335
9336	ctl_set_success(ctsio);
9337	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9338	ctsio->be_move_done = ctl_config_move_done;
9339	ctl_datamove((union ctl_io *)ctsio);
9340	return (CTL_RETVAL_COMPLETE);
9341}
9342
9343/*
9344 * SCSI VPD page 0x80, the Unit Serial Number page.
9345 */
9346static int
9347ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9348{
9349	struct ctl_lun *lun = CTL_LUN(ctsio);
9350	struct scsi_vpd_unit_serial_number *sn_ptr;
9351	int data_len;
9352
9353	data_len = 4 + CTL_SN_LEN;
9354	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9355	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9356	ctsio->kern_rel_offset = 0;
9357	ctsio->kern_sg_entries = 0;
9358	ctsio->kern_data_len = min(data_len, alloc_len);
9359	ctsio->kern_total_len = ctsio->kern_data_len;
9360
9361	/*
9362	 * The control device is always connected.  The disk device, on the
9363	 * other hand, may not be online all the time.  Need to change this
9364	 * to figure out whether the disk device is actually online or not.
9365	 */
9366	if (lun != NULL)
9367		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9368				  lun->be_lun->lun_type;
9369	else
9370		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9371
9372	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9373	sn_ptr->length = CTL_SN_LEN;
9374	/*
9375	 * If we don't have a LUN, we just leave the serial number as
9376	 * all spaces.
9377	 */
9378	if (lun != NULL) {
9379		strncpy((char *)sn_ptr->serial_num,
9380			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9381	} else
9382		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9383
9384	ctl_set_success(ctsio);
9385	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9386	ctsio->be_move_done = ctl_config_move_done;
9387	ctl_datamove((union ctl_io *)ctsio);
9388	return (CTL_RETVAL_COMPLETE);
9389}
9390
9391
9392/*
9393 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9394 */
9395static int
9396ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9397{
9398	struct ctl_lun *lun = CTL_LUN(ctsio);
9399	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9400	int data_len;
9401
9402	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9403	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9404	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9405	ctsio->kern_sg_entries = 0;
9406	ctsio->kern_rel_offset = 0;
9407	ctsio->kern_data_len = min(data_len, alloc_len);
9408	ctsio->kern_total_len = ctsio->kern_data_len;
9409
9410	/*
9411	 * The control device is always connected.  The disk device, on the
9412	 * other hand, may not be online all the time.
9413	 */
9414	if (lun != NULL)
9415		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9416				     lun->be_lun->lun_type;
9417	else
9418		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9419	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9420	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9421	/*
9422	 * We support head of queue, ordered and simple tags.
9423	 */
9424	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9425	/*
9426	 * Volatile cache supported.
9427	 */
9428	eid_ptr->flags3 = SVPD_EID_V_SUP;
9429
9430	/*
9431	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9432	 * attention for a particular IT nexus on all LUNs once we report
9433	 * it to that nexus once.  This bit is required as of SPC-4.
9434	 */
9435	eid_ptr->flags4 = SVPD_EID_LUICLR;
9436
9437	/*
9438	 * We support revert to defaults (RTD) bit in MODE SELECT.
9439	 */
9440	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9441
9442	/*
9443	 * XXX KDM in order to correctly answer this, we would need
9444	 * information from the SIM to determine how much sense data it
9445	 * can send.  So this would really be a path inquiry field, most
9446	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9447	 * but the hardware may or may not be able to support that much.
9448	 * 0 just means that the maximum sense data length is not reported.
9449	 */
9450	eid_ptr->max_sense_length = 0;
9451
9452	ctl_set_success(ctsio);
9453	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9454	ctsio->be_move_done = ctl_config_move_done;
9455	ctl_datamove((union ctl_io *)ctsio);
9456	return (CTL_RETVAL_COMPLETE);
9457}
9458
9459static int
9460ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9461{
9462	struct ctl_lun *lun = CTL_LUN(ctsio);
9463	struct scsi_vpd_mode_page_policy *mpp_ptr;
9464	int data_len;
9465
9466	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9467	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9468
9469	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9470	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9471	ctsio->kern_rel_offset = 0;
9472	ctsio->kern_sg_entries = 0;
9473	ctsio->kern_data_len = min(data_len, alloc_len);
9474	ctsio->kern_total_len = ctsio->kern_data_len;
9475
9476	/*
9477	 * The control device is always connected.  The disk device, on the
9478	 * other hand, may not be online all the time.
9479	 */
9480	if (lun != NULL)
9481		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9482				     lun->be_lun->lun_type;
9483	else
9484		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9485	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9486	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9487	mpp_ptr->descr[0].page_code = 0x3f;
9488	mpp_ptr->descr[0].subpage_code = 0xff;
9489	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9490
9491	ctl_set_success(ctsio);
9492	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9493	ctsio->be_move_done = ctl_config_move_done;
9494	ctl_datamove((union ctl_io *)ctsio);
9495	return (CTL_RETVAL_COMPLETE);
9496}
9497
9498/*
9499 * SCSI VPD page 0x83, the Device Identification page.
9500 */
9501static int
9502ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9503{
9504	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9505	struct ctl_port *port = CTL_PORT(ctsio);
9506	struct ctl_lun *lun = CTL_LUN(ctsio);
9507	struct scsi_vpd_device_id *devid_ptr;
9508	struct scsi_vpd_id_descriptor *desc;
9509	int data_len, g;
9510	uint8_t proto;
9511
9512	data_len = sizeof(struct scsi_vpd_device_id) +
9513	    sizeof(struct scsi_vpd_id_descriptor) +
9514		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9515	    sizeof(struct scsi_vpd_id_descriptor) +
9516		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9517	if (lun && lun->lun_devid)
9518		data_len += lun->lun_devid->len;
9519	if (port && port->port_devid)
9520		data_len += port->port_devid->len;
9521	if (port && port->target_devid)
9522		data_len += port->target_devid->len;
9523
9524	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9525	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9526	ctsio->kern_sg_entries = 0;
9527	ctsio->kern_rel_offset = 0;
9528	ctsio->kern_sg_entries = 0;
9529	ctsio->kern_data_len = min(data_len, alloc_len);
9530	ctsio->kern_total_len = ctsio->kern_data_len;
9531
9532	/*
9533	 * The control device is always connected.  The disk device, on the
9534	 * other hand, may not be online all the time.
9535	 */
9536	if (lun != NULL)
9537		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9538				     lun->be_lun->lun_type;
9539	else
9540		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9541	devid_ptr->page_code = SVPD_DEVICE_ID;
9542	scsi_ulto2b(data_len - 4, devid_ptr->length);
9543
9544	if (port && port->port_type == CTL_PORT_FC)
9545		proto = SCSI_PROTO_FC << 4;
9546	else if (port && port->port_type == CTL_PORT_SAS)
9547		proto = SCSI_PROTO_SAS << 4;
9548	else if (port && port->port_type == CTL_PORT_ISCSI)
9549		proto = SCSI_PROTO_ISCSI << 4;
9550	else
9551		proto = SCSI_PROTO_SPI << 4;
9552	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9553
9554	/*
9555	 * We're using a LUN association here.  i.e., this device ID is a
9556	 * per-LUN identifier.
9557	 */
9558	if (lun && lun->lun_devid) {
9559		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9560		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9561		    lun->lun_devid->len);
9562	}
9563
9564	/*
9565	 * This is for the WWPN which is a port association.
9566	 */
9567	if (port && port->port_devid) {
9568		memcpy(desc, port->port_devid->data, port->port_devid->len);
9569		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9570		    port->port_devid->len);
9571	}
9572
9573	/*
9574	 * This is for the Relative Target Port(type 4h) identifier
9575	 */
9576	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9577	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9578	    SVPD_ID_TYPE_RELTARG;
9579	desc->length = 4;
9580	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9581	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9582	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9583
9584	/*
9585	 * This is for the Target Port Group(type 5h) identifier
9586	 */
9587	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9588	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9589	    SVPD_ID_TYPE_TPORTGRP;
9590	desc->length = 4;
9591	if (softc->is_single ||
9592	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9593		g = 1;
9594	else
9595		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9596	scsi_ulto2b(g, &desc->identifier[2]);
9597	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9598	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9599
9600	/*
9601	 * This is for the Target identifier
9602	 */
9603	if (port && port->target_devid) {
9604		memcpy(desc, port->target_devid->data, port->target_devid->len);
9605	}
9606
9607	ctl_set_success(ctsio);
9608	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9609	ctsio->be_move_done = ctl_config_move_done;
9610	ctl_datamove((union ctl_io *)ctsio);
9611	return (CTL_RETVAL_COMPLETE);
9612}
9613
9614static int
9615ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9616{
9617	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9618	struct ctl_lun *lun = CTL_LUN(ctsio);
9619	struct scsi_vpd_scsi_ports *sp;
9620	struct scsi_vpd_port_designation *pd;
9621	struct scsi_vpd_port_designation_cont *pdc;
9622	struct ctl_port *port;
9623	int data_len, num_target_ports, iid_len, id_len;
9624
9625	num_target_ports = 0;
9626	iid_len = 0;
9627	id_len = 0;
9628	mtx_lock(&softc->ctl_lock);
9629	STAILQ_FOREACH(port, &softc->port_list, links) {
9630		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9631			continue;
9632		if (lun != NULL &&
9633		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9634			continue;
9635		num_target_ports++;
9636		if (port->init_devid)
9637			iid_len += port->init_devid->len;
9638		if (port->port_devid)
9639			id_len += port->port_devid->len;
9640	}
9641	mtx_unlock(&softc->ctl_lock);
9642
9643	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9644	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9645	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9646	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9647	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9648	ctsio->kern_sg_entries = 0;
9649	ctsio->kern_rel_offset = 0;
9650	ctsio->kern_sg_entries = 0;
9651	ctsio->kern_data_len = min(data_len, alloc_len);
9652	ctsio->kern_total_len = ctsio->kern_data_len;
9653
9654	/*
9655	 * The control device is always connected.  The disk device, on the
9656	 * other hand, may not be online all the time.  Need to change this
9657	 * to figure out whether the disk device is actually online or not.
9658	 */
9659	if (lun != NULL)
9660		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9661				  lun->be_lun->lun_type;
9662	else
9663		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9664
9665	sp->page_code = SVPD_SCSI_PORTS;
9666	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9667	    sp->page_length);
9668	pd = &sp->design[0];
9669
9670	mtx_lock(&softc->ctl_lock);
9671	STAILQ_FOREACH(port, &softc->port_list, links) {
9672		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9673			continue;
9674		if (lun != NULL &&
9675		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9676			continue;
9677		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9678		if (port->init_devid) {
9679			iid_len = port->init_devid->len;
9680			memcpy(pd->initiator_transportid,
9681			    port->init_devid->data, port->init_devid->len);
9682		} else
9683			iid_len = 0;
9684		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9685		pdc = (struct scsi_vpd_port_designation_cont *)
9686		    (&pd->initiator_transportid[iid_len]);
9687		if (port->port_devid) {
9688			id_len = port->port_devid->len;
9689			memcpy(pdc->target_port_descriptors,
9690			    port->port_devid->data, port->port_devid->len);
9691		} else
9692			id_len = 0;
9693		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9694		pd = (struct scsi_vpd_port_designation *)
9695		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9696	}
9697	mtx_unlock(&softc->ctl_lock);
9698
9699	ctl_set_success(ctsio);
9700	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9701	ctsio->be_move_done = ctl_config_move_done;
9702	ctl_datamove((union ctl_io *)ctsio);
9703	return (CTL_RETVAL_COMPLETE);
9704}
9705
9706static int
9707ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9708{
9709	struct ctl_lun *lun = CTL_LUN(ctsio);
9710	struct scsi_vpd_block_limits *bl_ptr;
9711	uint64_t ival;
9712
9713	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9714	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9715	ctsio->kern_sg_entries = 0;
9716	ctsio->kern_rel_offset = 0;
9717	ctsio->kern_sg_entries = 0;
9718	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9719	ctsio->kern_total_len = ctsio->kern_data_len;
9720
9721	/*
9722	 * The control device is always connected.  The disk device, on the
9723	 * other hand, may not be online all the time.  Need to change this
9724	 * to figure out whether the disk device is actually online or not.
9725	 */
9726	if (lun != NULL)
9727		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9728				  lun->be_lun->lun_type;
9729	else
9730		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9731
9732	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9733	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9734	bl_ptr->max_cmp_write_len = 0xff;
9735	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9736	if (lun != NULL) {
9737		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9738		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9739			ival = 0xffffffff;
9740			ctl_get_opt_number(&lun->be_lun->options,
9741			    "unmap_max_lba", &ival);
9742			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9743			ival = 0xffffffff;
9744			ctl_get_opt_number(&lun->be_lun->options,
9745			    "unmap_max_descr", &ival);
9746			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9747			if (lun->be_lun->ublockexp != 0) {
9748				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9749				    bl_ptr->opt_unmap_grain);
9750				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9751				    bl_ptr->unmap_grain_align);
9752			}
9753		}
9754		scsi_ulto4b(lun->be_lun->atomicblock,
9755		    bl_ptr->max_atomic_transfer_length);
9756		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9757		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9758		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9759		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9760		ival = UINT64_MAX;
9761		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9762		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9763	}
9764
9765	ctl_set_success(ctsio);
9766	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9767	ctsio->be_move_done = ctl_config_move_done;
9768	ctl_datamove((union ctl_io *)ctsio);
9769	return (CTL_RETVAL_COMPLETE);
9770}
9771
9772static int
9773ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9774{
9775	struct ctl_lun *lun = CTL_LUN(ctsio);
9776	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9777	const char *value;
9778	u_int i;
9779
9780	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9781	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9782	ctsio->kern_sg_entries = 0;
9783	ctsio->kern_rel_offset = 0;
9784	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9785	ctsio->kern_total_len = ctsio->kern_data_len;
9786
9787	/*
9788	 * The control device is always connected.  The disk device, on the
9789	 * other hand, may not be online all the time.  Need to change this
9790	 * to figure out whether the disk device is actually online or not.
9791	 */
9792	if (lun != NULL)
9793		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9794				  lun->be_lun->lun_type;
9795	else
9796		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9797	bdc_ptr->page_code = SVPD_BDC;
9798	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9799	if (lun != NULL &&
9800	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9801		i = strtol(value, NULL, 0);
9802	else
9803		i = CTL_DEFAULT_ROTATION_RATE;
9804	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9805	if (lun != NULL &&
9806	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9807		i = strtol(value, NULL, 0);
9808	else
9809		i = 0;
9810	bdc_ptr->wab_wac_ff = (i & 0x0f);
9811	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9812
9813	ctl_set_success(ctsio);
9814	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9815	ctsio->be_move_done = ctl_config_move_done;
9816	ctl_datamove((union ctl_io *)ctsio);
9817	return (CTL_RETVAL_COMPLETE);
9818}
9819
9820static int
9821ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9822{
9823	struct ctl_lun *lun = CTL_LUN(ctsio);
9824	struct scsi_vpd_logical_block_prov *lbp_ptr;
9825	const char *value;
9826
9827	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9828	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9829	ctsio->kern_sg_entries = 0;
9830	ctsio->kern_rel_offset = 0;
9831	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9832	ctsio->kern_total_len = ctsio->kern_data_len;
9833
9834	/*
9835	 * The control device is always connected.  The disk device, on the
9836	 * other hand, may not be online all the time.  Need to change this
9837	 * to figure out whether the disk device is actually online or not.
9838	 */
9839	if (lun != NULL)
9840		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9841				  lun->be_lun->lun_type;
9842	else
9843		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9844
9845	lbp_ptr->page_code = SVPD_LBP;
9846	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9847	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9848	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9849		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9850		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9851		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
9852		if (value != NULL) {
9853			if (strcmp(value, "resource") == 0)
9854				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9855			else if (strcmp(value, "thin") == 0)
9856				lbp_ptr->prov_type = SVPD_LBP_THIN;
9857		} else
9858			lbp_ptr->prov_type = SVPD_LBP_THIN;
9859	}
9860
9861	ctl_set_success(ctsio);
9862	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9863	ctsio->be_move_done = ctl_config_move_done;
9864	ctl_datamove((union ctl_io *)ctsio);
9865	return (CTL_RETVAL_COMPLETE);
9866}
9867
9868/*
9869 * INQUIRY with the EVPD bit set.
9870 */
9871static int
9872ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9873{
9874	struct ctl_lun *lun = CTL_LUN(ctsio);
9875	struct scsi_inquiry *cdb;
9876	int alloc_len, retval;
9877
9878	cdb = (struct scsi_inquiry *)ctsio->cdb;
9879	alloc_len = scsi_2btoul(cdb->length);
9880
9881	switch (cdb->page_code) {
9882	case SVPD_SUPPORTED_PAGES:
9883		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9884		break;
9885	case SVPD_UNIT_SERIAL_NUMBER:
9886		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9887		break;
9888	case SVPD_DEVICE_ID:
9889		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9890		break;
9891	case SVPD_EXTENDED_INQUIRY_DATA:
9892		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9893		break;
9894	case SVPD_MODE_PAGE_POLICY:
9895		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9896		break;
9897	case SVPD_SCSI_PORTS:
9898		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9899		break;
9900	case SVPD_SCSI_TPC:
9901		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9902		break;
9903	case SVPD_BLOCK_LIMITS:
9904		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9905			goto err;
9906		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9907		break;
9908	case SVPD_BDC:
9909		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9910			goto err;
9911		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9912		break;
9913	case SVPD_LBP:
9914		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9915			goto err;
9916		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9917		break;
9918	default:
9919err:
9920		ctl_set_invalid_field(ctsio,
9921				      /*sks_valid*/ 1,
9922				      /*command*/ 1,
9923				      /*field*/ 2,
9924				      /*bit_valid*/ 0,
9925				      /*bit*/ 0);
9926		ctl_done((union ctl_io *)ctsio);
9927		retval = CTL_RETVAL_COMPLETE;
9928		break;
9929	}
9930
9931	return (retval);
9932}
9933
9934/*
9935 * Standard INQUIRY data.
9936 */
9937static int
9938ctl_inquiry_std(struct ctl_scsiio *ctsio)
9939{
9940	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9941	struct ctl_port *port = CTL_PORT(ctsio);
9942	struct ctl_lun *lun = CTL_LUN(ctsio);
9943	struct scsi_inquiry_data *inq_ptr;
9944	struct scsi_inquiry *cdb;
9945	char *val;
9946	uint32_t alloc_len, data_len;
9947	ctl_port_type port_type;
9948
9949	port_type = port->port_type;
9950	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
9951		port_type = CTL_PORT_SCSI;
9952
9953	cdb = (struct scsi_inquiry *)ctsio->cdb;
9954	alloc_len = scsi_2btoul(cdb->length);
9955
9956	/*
9957	 * We malloc the full inquiry data size here and fill it
9958	 * in.  If the user only asks for less, we'll give him
9959	 * that much.
9960	 */
9961	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
9962	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9963	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9964	ctsio->kern_sg_entries = 0;
9965	ctsio->kern_rel_offset = 0;
9966	ctsio->kern_data_len = min(data_len, alloc_len);
9967	ctsio->kern_total_len = ctsio->kern_data_len;
9968
9969	if (lun != NULL) {
9970		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
9971		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
9972			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9973			    lun->be_lun->lun_type;
9974		} else {
9975			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
9976			    lun->be_lun->lun_type;
9977		}
9978		if (lun->flags & CTL_LUN_REMOVABLE)
9979			inq_ptr->dev_qual2 |= SID_RMB;
9980	} else
9981		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
9982
9983	/* RMB in byte 2 is 0 */
9984	inq_ptr->version = SCSI_REV_SPC5;
9985
9986	/*
9987	 * According to SAM-3, even if a device only supports a single
9988	 * level of LUN addressing, it should still set the HISUP bit:
9989	 *
9990	 * 4.9.1 Logical unit numbers overview
9991	 *
9992	 * All logical unit number formats described in this standard are
9993	 * hierarchical in structure even when only a single level in that
9994	 * hierarchy is used. The HISUP bit shall be set to one in the
9995	 * standard INQUIRY data (see SPC-2) when any logical unit number
9996	 * format described in this standard is used.  Non-hierarchical
9997	 * formats are outside the scope of this standard.
9998	 *
9999	 * Therefore we set the HiSup bit here.
10000	 *
10001	 * The response format is 2, per SPC-3.
10002	 */
10003	inq_ptr->response_format = SID_HiSup | 2;
10004
10005	inq_ptr->additional_length = data_len -
10006	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10007	CTL_DEBUG_PRINT(("additional_length = %d\n",
10008			 inq_ptr->additional_length));
10009
10010	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10011	if (port_type == CTL_PORT_SCSI)
10012		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10013	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10014	inq_ptr->flags = SID_CmdQue;
10015	if (port_type == CTL_PORT_SCSI)
10016		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10017
10018	/*
10019	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10020	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10021	 * name and 4 bytes for the revision.
10022	 */
10023	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10024	    "vendor")) == NULL) {
10025		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10026	} else {
10027		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10028		strncpy(inq_ptr->vendor, val,
10029		    min(sizeof(inq_ptr->vendor), strlen(val)));
10030	}
10031	if (lun == NULL) {
10032		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10033		    sizeof(inq_ptr->product));
10034	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10035		switch (lun->be_lun->lun_type) {
10036		case T_DIRECT:
10037			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10038			    sizeof(inq_ptr->product));
10039			break;
10040		case T_PROCESSOR:
10041			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10042			    sizeof(inq_ptr->product));
10043			break;
10044		case T_CDROM:
10045			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10046			    sizeof(inq_ptr->product));
10047			break;
10048		default:
10049			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10050			    sizeof(inq_ptr->product));
10051			break;
10052		}
10053	} else {
10054		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10055		strncpy(inq_ptr->product, val,
10056		    min(sizeof(inq_ptr->product), strlen(val)));
10057	}
10058
10059	/*
10060	 * XXX make this a macro somewhere so it automatically gets
10061	 * incremented when we make changes.
10062	 */
10063	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10064	    "revision")) == NULL) {
10065		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10066	} else {
10067		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10068		strncpy(inq_ptr->revision, val,
10069		    min(sizeof(inq_ptr->revision), strlen(val)));
10070	}
10071
10072	/*
10073	 * For parallel SCSI, we support double transition and single
10074	 * transition clocking.  We also support QAS (Quick Arbitration
10075	 * and Selection) and Information Unit transfers on both the
10076	 * control and array devices.
10077	 */
10078	if (port_type == CTL_PORT_SCSI)
10079		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10080				    SID_SPI_IUS;
10081
10082	/* SAM-6 (no version claimed) */
10083	scsi_ulto2b(0x00C0, inq_ptr->version1);
10084	/* SPC-5 (no version claimed) */
10085	scsi_ulto2b(0x05C0, inq_ptr->version2);
10086	if (port_type == CTL_PORT_FC) {
10087		/* FCP-2 ANSI INCITS.350:2003 */
10088		scsi_ulto2b(0x0917, inq_ptr->version3);
10089	} else if (port_type == CTL_PORT_SCSI) {
10090		/* SPI-4 ANSI INCITS.362:200x */
10091		scsi_ulto2b(0x0B56, inq_ptr->version3);
10092	} else if (port_type == CTL_PORT_ISCSI) {
10093		/* iSCSI (no version claimed) */
10094		scsi_ulto2b(0x0960, inq_ptr->version3);
10095	} else if (port_type == CTL_PORT_SAS) {
10096		/* SAS (no version claimed) */
10097		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10098	} else if (port_type == CTL_PORT_UMASS) {
10099		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10100		scsi_ulto2b(0x1730, inq_ptr->version3);
10101	}
10102
10103	if (lun == NULL) {
10104		/* SBC-4 (no version claimed) */
10105		scsi_ulto2b(0x0600, inq_ptr->version4);
10106	} else {
10107		switch (lun->be_lun->lun_type) {
10108		case T_DIRECT:
10109			/* SBC-4 (no version claimed) */
10110			scsi_ulto2b(0x0600, inq_ptr->version4);
10111			break;
10112		case T_PROCESSOR:
10113			break;
10114		case T_CDROM:
10115			/* MMC-6 (no version claimed) */
10116			scsi_ulto2b(0x04E0, inq_ptr->version4);
10117			break;
10118		default:
10119			break;
10120		}
10121	}
10122
10123	ctl_set_success(ctsio);
10124	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10125	ctsio->be_move_done = ctl_config_move_done;
10126	ctl_datamove((union ctl_io *)ctsio);
10127	return (CTL_RETVAL_COMPLETE);
10128}
10129
10130int
10131ctl_inquiry(struct ctl_scsiio *ctsio)
10132{
10133	struct scsi_inquiry *cdb;
10134	int retval;
10135
10136	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10137
10138	cdb = (struct scsi_inquiry *)ctsio->cdb;
10139	if (cdb->byte2 & SI_EVPD)
10140		retval = ctl_inquiry_evpd(ctsio);
10141	else if (cdb->page_code == 0)
10142		retval = ctl_inquiry_std(ctsio);
10143	else {
10144		ctl_set_invalid_field(ctsio,
10145				      /*sks_valid*/ 1,
10146				      /*command*/ 1,
10147				      /*field*/ 2,
10148				      /*bit_valid*/ 0,
10149				      /*bit*/ 0);
10150		ctl_done((union ctl_io *)ctsio);
10151		return (CTL_RETVAL_COMPLETE);
10152	}
10153
10154	return (retval);
10155}
10156
10157int
10158ctl_get_config(struct ctl_scsiio *ctsio)
10159{
10160	struct ctl_lun *lun = CTL_LUN(ctsio);
10161	struct scsi_get_config_header *hdr;
10162	struct scsi_get_config_feature *feature;
10163	struct scsi_get_config *cdb;
10164	uint32_t alloc_len, data_len;
10165	int rt, starting;
10166
10167	cdb = (struct scsi_get_config *)ctsio->cdb;
10168	rt = (cdb->rt & SGC_RT_MASK);
10169	starting = scsi_2btoul(cdb->starting_feature);
10170	alloc_len = scsi_2btoul(cdb->length);
10171
10172	data_len = sizeof(struct scsi_get_config_header) +
10173	    sizeof(struct scsi_get_config_feature) + 8 +
10174	    sizeof(struct scsi_get_config_feature) + 8 +
10175	    sizeof(struct scsi_get_config_feature) + 4 +
10176	    sizeof(struct scsi_get_config_feature) + 4 +
10177	    sizeof(struct scsi_get_config_feature) + 8 +
10178	    sizeof(struct scsi_get_config_feature) +
10179	    sizeof(struct scsi_get_config_feature) + 4 +
10180	    sizeof(struct scsi_get_config_feature) + 4 +
10181	    sizeof(struct scsi_get_config_feature) + 4 +
10182	    sizeof(struct scsi_get_config_feature) + 4 +
10183	    sizeof(struct scsi_get_config_feature) + 4 +
10184	    sizeof(struct scsi_get_config_feature) + 4;
10185	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10186	ctsio->kern_sg_entries = 0;
10187	ctsio->kern_rel_offset = 0;
10188
10189	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10190	if (lun->flags & CTL_LUN_NO_MEDIA)
10191		scsi_ulto2b(0x0000, hdr->current_profile);
10192	else
10193		scsi_ulto2b(0x0010, hdr->current_profile);
10194	feature = (struct scsi_get_config_feature *)(hdr + 1);
10195
10196	if (starting > 0x003b)
10197		goto done;
10198	if (starting > 0x003a)
10199		goto f3b;
10200	if (starting > 0x002b)
10201		goto f3a;
10202	if (starting > 0x002a)
10203		goto f2b;
10204	if (starting > 0x001f)
10205		goto f2a;
10206	if (starting > 0x001e)
10207		goto f1f;
10208	if (starting > 0x001d)
10209		goto f1e;
10210	if (starting > 0x0010)
10211		goto f1d;
10212	if (starting > 0x0003)
10213		goto f10;
10214	if (starting > 0x0002)
10215		goto f3;
10216	if (starting > 0x0001)
10217		goto f2;
10218	if (starting > 0x0000)
10219		goto f1;
10220
10221	/* Profile List */
10222	scsi_ulto2b(0x0000, feature->feature_code);
10223	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10224	feature->add_length = 8;
10225	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10226	feature->feature_data[2] = 0x00;
10227	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10228	feature->feature_data[6] = 0x01;
10229	feature = (struct scsi_get_config_feature *)
10230	    &feature->feature_data[feature->add_length];
10231
10232f1:	/* Core */
10233	scsi_ulto2b(0x0001, feature->feature_code);
10234	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10235	feature->add_length = 8;
10236	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10237	feature->feature_data[4] = 0x03;
10238	feature = (struct scsi_get_config_feature *)
10239	    &feature->feature_data[feature->add_length];
10240
10241f2:	/* Morphing */
10242	scsi_ulto2b(0x0002, feature->feature_code);
10243	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10244	feature->add_length = 4;
10245	feature->feature_data[0] = 0x02;
10246	feature = (struct scsi_get_config_feature *)
10247	    &feature->feature_data[feature->add_length];
10248
10249f3:	/* Removable Medium */
10250	scsi_ulto2b(0x0003, feature->feature_code);
10251	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10252	feature->add_length = 4;
10253	feature->feature_data[0] = 0x39;
10254	feature = (struct scsi_get_config_feature *)
10255	    &feature->feature_data[feature->add_length];
10256
10257	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10258		goto done;
10259
10260f10:	/* Random Read */
10261	scsi_ulto2b(0x0010, feature->feature_code);
10262	feature->flags = 0x00;
10263	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10264		feature->flags |= SGC_F_CURRENT;
10265	feature->add_length = 8;
10266	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10267	scsi_ulto2b(1, &feature->feature_data[4]);
10268	feature->feature_data[6] = 0x00;
10269	feature = (struct scsi_get_config_feature *)
10270	    &feature->feature_data[feature->add_length];
10271
10272f1d:	/* Multi-Read */
10273	scsi_ulto2b(0x001D, feature->feature_code);
10274	feature->flags = 0x00;
10275	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10276		feature->flags |= SGC_F_CURRENT;
10277	feature->add_length = 0;
10278	feature = (struct scsi_get_config_feature *)
10279	    &feature->feature_data[feature->add_length];
10280
10281f1e:	/* CD Read */
10282	scsi_ulto2b(0x001E, feature->feature_code);
10283	feature->flags = 0x00;
10284	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10285		feature->flags |= SGC_F_CURRENT;
10286	feature->add_length = 4;
10287	feature->feature_data[0] = 0x00;
10288	feature = (struct scsi_get_config_feature *)
10289	    &feature->feature_data[feature->add_length];
10290
10291f1f:	/* DVD Read */
10292	scsi_ulto2b(0x001F, feature->feature_code);
10293	feature->flags = 0x08;
10294	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10295		feature->flags |= SGC_F_CURRENT;
10296	feature->add_length = 4;
10297	feature->feature_data[0] = 0x01;
10298	feature->feature_data[2] = 0x03;
10299	feature = (struct scsi_get_config_feature *)
10300	    &feature->feature_data[feature->add_length];
10301
10302f2a:	/* DVD+RW */
10303	scsi_ulto2b(0x002A, feature->feature_code);
10304	feature->flags = 0x04;
10305	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10306		feature->flags |= SGC_F_CURRENT;
10307	feature->add_length = 4;
10308	feature->feature_data[0] = 0x00;
10309	feature->feature_data[1] = 0x00;
10310	feature = (struct scsi_get_config_feature *)
10311	    &feature->feature_data[feature->add_length];
10312
10313f2b:	/* DVD+R */
10314	scsi_ulto2b(0x002B, feature->feature_code);
10315	feature->flags = 0x00;
10316	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10317		feature->flags |= SGC_F_CURRENT;
10318	feature->add_length = 4;
10319	feature->feature_data[0] = 0x00;
10320	feature = (struct scsi_get_config_feature *)
10321	    &feature->feature_data[feature->add_length];
10322
10323f3a:	/* DVD+RW Dual Layer */
10324	scsi_ulto2b(0x003A, feature->feature_code);
10325	feature->flags = 0x00;
10326	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10327		feature->flags |= SGC_F_CURRENT;
10328	feature->add_length = 4;
10329	feature->feature_data[0] = 0x00;
10330	feature->feature_data[1] = 0x00;
10331	feature = (struct scsi_get_config_feature *)
10332	    &feature->feature_data[feature->add_length];
10333
10334f3b:	/* DVD+R Dual Layer */
10335	scsi_ulto2b(0x003B, feature->feature_code);
10336	feature->flags = 0x00;
10337	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10338		feature->flags |= SGC_F_CURRENT;
10339	feature->add_length = 4;
10340	feature->feature_data[0] = 0x00;
10341	feature = (struct scsi_get_config_feature *)
10342	    &feature->feature_data[feature->add_length];
10343
10344done:
10345	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10346	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10347		feature = (struct scsi_get_config_feature *)(hdr + 1);
10348		if (scsi_2btoul(feature->feature_code) == starting)
10349			feature = (struct scsi_get_config_feature *)
10350			    &feature->feature_data[feature->add_length];
10351		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10352	}
10353	scsi_ulto4b(data_len - 4, hdr->data_length);
10354	ctsio->kern_data_len = min(data_len, alloc_len);
10355	ctsio->kern_total_len = ctsio->kern_data_len;
10356
10357	ctl_set_success(ctsio);
10358	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10359	ctsio->be_move_done = ctl_config_move_done;
10360	ctl_datamove((union ctl_io *)ctsio);
10361	return (CTL_RETVAL_COMPLETE);
10362}
10363
10364int
10365ctl_get_event_status(struct ctl_scsiio *ctsio)
10366{
10367	struct scsi_get_event_status_header *hdr;
10368	struct scsi_get_event_status *cdb;
10369	uint32_t alloc_len, data_len;
10370	int notif_class;
10371
10372	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10373	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10374		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10375		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10376		ctl_done((union ctl_io *)ctsio);
10377		return (CTL_RETVAL_COMPLETE);
10378	}
10379	notif_class = cdb->notif_class;
10380	alloc_len = scsi_2btoul(cdb->length);
10381
10382	data_len = sizeof(struct scsi_get_event_status_header);
10383	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10384	ctsio->kern_sg_entries = 0;
10385	ctsio->kern_rel_offset = 0;
10386	ctsio->kern_data_len = min(data_len, alloc_len);
10387	ctsio->kern_total_len = ctsio->kern_data_len;
10388
10389	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10390	scsi_ulto2b(0, hdr->descr_length);
10391	hdr->nea_class = SGESN_NEA;
10392	hdr->supported_class = 0;
10393
10394	ctl_set_success(ctsio);
10395	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10396	ctsio->be_move_done = ctl_config_move_done;
10397	ctl_datamove((union ctl_io *)ctsio);
10398	return (CTL_RETVAL_COMPLETE);
10399}
10400
10401int
10402ctl_mechanism_status(struct ctl_scsiio *ctsio)
10403{
10404	struct scsi_mechanism_status_header *hdr;
10405	struct scsi_mechanism_status *cdb;
10406	uint32_t alloc_len, data_len;
10407
10408	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10409	alloc_len = scsi_2btoul(cdb->length);
10410
10411	data_len = sizeof(struct scsi_mechanism_status_header);
10412	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10413	ctsio->kern_sg_entries = 0;
10414	ctsio->kern_rel_offset = 0;
10415	ctsio->kern_data_len = min(data_len, alloc_len);
10416	ctsio->kern_total_len = ctsio->kern_data_len;
10417
10418	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10419	hdr->state1 = 0x00;
10420	hdr->state2 = 0xe0;
10421	scsi_ulto3b(0, hdr->lba);
10422	hdr->slots_num = 0;
10423	scsi_ulto2b(0, hdr->slots_length);
10424
10425	ctl_set_success(ctsio);
10426	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10427	ctsio->be_move_done = ctl_config_move_done;
10428	ctl_datamove((union ctl_io *)ctsio);
10429	return (CTL_RETVAL_COMPLETE);
10430}
10431
10432static void
10433ctl_ultomsf(uint32_t lba, uint8_t *buf)
10434{
10435
10436	lba += 150;
10437	buf[0] = 0;
10438	buf[1] = bin2bcd((lba / 75) / 60);
10439	buf[2] = bin2bcd((lba / 75) % 60);
10440	buf[3] = bin2bcd(lba % 75);
10441}
10442
10443int
10444ctl_read_toc(struct ctl_scsiio *ctsio)
10445{
10446	struct ctl_lun *lun = CTL_LUN(ctsio);
10447	struct scsi_read_toc_hdr *hdr;
10448	struct scsi_read_toc_type01_descr *descr;
10449	struct scsi_read_toc *cdb;
10450	uint32_t alloc_len, data_len;
10451	int format, msf;
10452
10453	cdb = (struct scsi_read_toc *)ctsio->cdb;
10454	msf = (cdb->byte2 & CD_MSF) != 0;
10455	format = cdb->format;
10456	alloc_len = scsi_2btoul(cdb->data_len);
10457
10458	data_len = sizeof(struct scsi_read_toc_hdr);
10459	if (format == 0)
10460		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10461	else
10462		data_len += sizeof(struct scsi_read_toc_type01_descr);
10463	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10464	ctsio->kern_sg_entries = 0;
10465	ctsio->kern_rel_offset = 0;
10466	ctsio->kern_data_len = min(data_len, alloc_len);
10467	ctsio->kern_total_len = ctsio->kern_data_len;
10468
10469	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10470	if (format == 0) {
10471		scsi_ulto2b(0x12, hdr->data_length);
10472		hdr->first = 1;
10473		hdr->last = 1;
10474		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10475		descr->addr_ctl = 0x14;
10476		descr->track_number = 1;
10477		if (msf)
10478			ctl_ultomsf(0, descr->track_start);
10479		else
10480			scsi_ulto4b(0, descr->track_start);
10481		descr++;
10482		descr->addr_ctl = 0x14;
10483		descr->track_number = 0xaa;
10484		if (msf)
10485			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10486		else
10487			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10488	} else {
10489		scsi_ulto2b(0x0a, hdr->data_length);
10490		hdr->first = 1;
10491		hdr->last = 1;
10492		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10493		descr->addr_ctl = 0x14;
10494		descr->track_number = 1;
10495		if (msf)
10496			ctl_ultomsf(0, descr->track_start);
10497		else
10498			scsi_ulto4b(0, descr->track_start);
10499	}
10500
10501	ctl_set_success(ctsio);
10502	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10503	ctsio->be_move_done = ctl_config_move_done;
10504	ctl_datamove((union ctl_io *)ctsio);
10505	return (CTL_RETVAL_COMPLETE);
10506}
10507
10508/*
10509 * For known CDB types, parse the LBA and length.
10510 */
10511static int
10512ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10513{
10514	if (io->io_hdr.io_type != CTL_IO_SCSI)
10515		return (1);
10516
10517	switch (io->scsiio.cdb[0]) {
10518	case COMPARE_AND_WRITE: {
10519		struct scsi_compare_and_write *cdb;
10520
10521		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10522
10523		*lba = scsi_8btou64(cdb->addr);
10524		*len = cdb->length;
10525		break;
10526	}
10527	case READ_6:
10528	case WRITE_6: {
10529		struct scsi_rw_6 *cdb;
10530
10531		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10532
10533		*lba = scsi_3btoul(cdb->addr);
10534		/* only 5 bits are valid in the most significant address byte */
10535		*lba &= 0x1fffff;
10536		*len = cdb->length;
10537		break;
10538	}
10539	case READ_10:
10540	case WRITE_10: {
10541		struct scsi_rw_10 *cdb;
10542
10543		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10544
10545		*lba = scsi_4btoul(cdb->addr);
10546		*len = scsi_2btoul(cdb->length);
10547		break;
10548	}
10549	case WRITE_VERIFY_10: {
10550		struct scsi_write_verify_10 *cdb;
10551
10552		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10553
10554		*lba = scsi_4btoul(cdb->addr);
10555		*len = scsi_2btoul(cdb->length);
10556		break;
10557	}
10558	case READ_12:
10559	case WRITE_12: {
10560		struct scsi_rw_12 *cdb;
10561
10562		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10563
10564		*lba = scsi_4btoul(cdb->addr);
10565		*len = scsi_4btoul(cdb->length);
10566		break;
10567	}
10568	case WRITE_VERIFY_12: {
10569		struct scsi_write_verify_12 *cdb;
10570
10571		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10572
10573		*lba = scsi_4btoul(cdb->addr);
10574		*len = scsi_4btoul(cdb->length);
10575		break;
10576	}
10577	case READ_16:
10578	case WRITE_16: {
10579		struct scsi_rw_16 *cdb;
10580
10581		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10582
10583		*lba = scsi_8btou64(cdb->addr);
10584		*len = scsi_4btoul(cdb->length);
10585		break;
10586	}
10587	case WRITE_ATOMIC_16: {
10588		struct scsi_write_atomic_16 *cdb;
10589
10590		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10591
10592		*lba = scsi_8btou64(cdb->addr);
10593		*len = scsi_2btoul(cdb->length);
10594		break;
10595	}
10596	case WRITE_VERIFY_16: {
10597		struct scsi_write_verify_16 *cdb;
10598
10599		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10600
10601		*lba = scsi_8btou64(cdb->addr);
10602		*len = scsi_4btoul(cdb->length);
10603		break;
10604	}
10605	case WRITE_SAME_10: {
10606		struct scsi_write_same_10 *cdb;
10607
10608		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10609
10610		*lba = scsi_4btoul(cdb->addr);
10611		*len = scsi_2btoul(cdb->length);
10612		break;
10613	}
10614	case WRITE_SAME_16: {
10615		struct scsi_write_same_16 *cdb;
10616
10617		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10618
10619		*lba = scsi_8btou64(cdb->addr);
10620		*len = scsi_4btoul(cdb->length);
10621		break;
10622	}
10623	case VERIFY_10: {
10624		struct scsi_verify_10 *cdb;
10625
10626		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10627
10628		*lba = scsi_4btoul(cdb->addr);
10629		*len = scsi_2btoul(cdb->length);
10630		break;
10631	}
10632	case VERIFY_12: {
10633		struct scsi_verify_12 *cdb;
10634
10635		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10636
10637		*lba = scsi_4btoul(cdb->addr);
10638		*len = scsi_4btoul(cdb->length);
10639		break;
10640	}
10641	case VERIFY_16: {
10642		struct scsi_verify_16 *cdb;
10643
10644		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10645
10646		*lba = scsi_8btou64(cdb->addr);
10647		*len = scsi_4btoul(cdb->length);
10648		break;
10649	}
10650	case UNMAP: {
10651		*lba = 0;
10652		*len = UINT64_MAX;
10653		break;
10654	}
10655	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10656		struct scsi_get_lba_status *cdb;
10657
10658		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10659		*lba = scsi_8btou64(cdb->addr);
10660		*len = UINT32_MAX;
10661		break;
10662	}
10663	default:
10664		return (1);
10665		break; /* NOTREACHED */
10666	}
10667
10668	return (0);
10669}
10670
10671static ctl_action
10672ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10673    bool seq)
10674{
10675	uint64_t endlba1, endlba2;
10676
10677	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10678	endlba2 = lba2 + len2 - 1;
10679
10680	if ((endlba1 < lba2) || (endlba2 < lba1))
10681		return (CTL_ACTION_PASS);
10682	else
10683		return (CTL_ACTION_BLOCK);
10684}
10685
10686static int
10687ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10688{
10689	struct ctl_ptr_len_flags *ptrlen;
10690	struct scsi_unmap_desc *buf, *end, *range;
10691	uint64_t lba;
10692	uint32_t len;
10693
10694	/* If not UNMAP -- go other way. */
10695	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10696	    io->scsiio.cdb[0] != UNMAP)
10697		return (CTL_ACTION_ERROR);
10698
10699	/* If UNMAP without data -- block and wait for data. */
10700	ptrlen = (struct ctl_ptr_len_flags *)
10701	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10702	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10703	    ptrlen->ptr == NULL)
10704		return (CTL_ACTION_BLOCK);
10705
10706	/* UNMAP with data -- check for collision. */
10707	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10708	end = buf + ptrlen->len / sizeof(*buf);
10709	for (range = buf; range < end; range++) {
10710		lba = scsi_8btou64(range->lba);
10711		len = scsi_4btoul(range->length);
10712		if ((lba < lba2 + len2) && (lba + len > lba2))
10713			return (CTL_ACTION_BLOCK);
10714	}
10715	return (CTL_ACTION_PASS);
10716}
10717
10718static ctl_action
10719ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10720{
10721	uint64_t lba1, lba2;
10722	uint64_t len1, len2;
10723	int retval;
10724
10725	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10726		return (CTL_ACTION_ERROR);
10727
10728	retval = ctl_extent_check_unmap(io1, lba2, len2);
10729	if (retval != CTL_ACTION_ERROR)
10730		return (retval);
10731
10732	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10733		return (CTL_ACTION_ERROR);
10734
10735	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10736		seq = FALSE;
10737	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10738}
10739
10740static ctl_action
10741ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10742{
10743	uint64_t lba1, lba2;
10744	uint64_t len1, len2;
10745
10746	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10747		return (CTL_ACTION_PASS);
10748	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10749		return (CTL_ACTION_ERROR);
10750	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10751		return (CTL_ACTION_ERROR);
10752
10753	if (lba1 + len1 == lba2)
10754		return (CTL_ACTION_BLOCK);
10755	return (CTL_ACTION_PASS);
10756}
10757
10758static ctl_action
10759ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10760    union ctl_io *ooa_io)
10761{
10762	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10763	const ctl_serialize_action *serialize_row;
10764
10765	/*
10766	 * The initiator attempted multiple untagged commands at the same
10767	 * time.  Can't do that.
10768	 */
10769	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10770	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10771	 && ((pending_io->io_hdr.nexus.targ_port ==
10772	      ooa_io->io_hdr.nexus.targ_port)
10773	  && (pending_io->io_hdr.nexus.initid ==
10774	      ooa_io->io_hdr.nexus.initid))
10775	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10776	      CTL_FLAG_STATUS_SENT)) == 0))
10777		return (CTL_ACTION_OVERLAP);
10778
10779	/*
10780	 * The initiator attempted to send multiple tagged commands with
10781	 * the same ID.  (It's fine if different initiators have the same
10782	 * tag ID.)
10783	 *
10784	 * Even if all of those conditions are true, we don't kill the I/O
10785	 * if the command ahead of us has been aborted.  We won't end up
10786	 * sending it to the FETD, and it's perfectly legal to resend a
10787	 * command with the same tag number as long as the previous
10788	 * instance of this tag number has been aborted somehow.
10789	 */
10790	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10791	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10792	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10793	 && ((pending_io->io_hdr.nexus.targ_port ==
10794	      ooa_io->io_hdr.nexus.targ_port)
10795	  && (pending_io->io_hdr.nexus.initid ==
10796	      ooa_io->io_hdr.nexus.initid))
10797	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10798	      CTL_FLAG_STATUS_SENT)) == 0))
10799		return (CTL_ACTION_OVERLAP_TAG);
10800
10801	/*
10802	 * If we get a head of queue tag, SAM-3 says that we should
10803	 * immediately execute it.
10804	 *
10805	 * What happens if this command would normally block for some other
10806	 * reason?  e.g. a request sense with a head of queue tag
10807	 * immediately after a write.  Normally that would block, but this
10808	 * will result in its getting executed immediately...
10809	 *
10810	 * We currently return "pass" instead of "skip", so we'll end up
10811	 * going through the rest of the queue to check for overlapped tags.
10812	 *
10813	 * XXX KDM check for other types of blockage first??
10814	 */
10815	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10816		return (CTL_ACTION_PASS);
10817
10818	/*
10819	 * Ordered tags have to block until all items ahead of them
10820	 * have completed.  If we get called with an ordered tag, we always
10821	 * block, if something else is ahead of us in the queue.
10822	 */
10823	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10824		return (CTL_ACTION_BLOCK);
10825
10826	/*
10827	 * Simple tags get blocked until all head of queue and ordered tags
10828	 * ahead of them have completed.  I'm lumping untagged commands in
10829	 * with simple tags here.  XXX KDM is that the right thing to do?
10830	 */
10831	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10832	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10833	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10834	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10835		return (CTL_ACTION_BLOCK);
10836
10837	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10838	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
10839	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
10840	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
10841	     pending_io->scsiio.cdb[1], pending_io));
10842	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10843	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
10844		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
10845	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
10846	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
10847	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
10848	     ooa_io->scsiio.cdb[1], ooa_io));
10849
10850	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10851
10852	switch (serialize_row[pending_entry->seridx]) {
10853	case CTL_SER_BLOCK:
10854		return (CTL_ACTION_BLOCK);
10855	case CTL_SER_EXTENT:
10856		return (ctl_extent_check(ooa_io, pending_io,
10857		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10858	case CTL_SER_EXTENTOPT:
10859		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10860		    SCP_QUEUE_ALG_UNRESTRICTED)
10861			return (ctl_extent_check(ooa_io, pending_io,
10862			    (lun->be_lun &&
10863			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10864		return (CTL_ACTION_PASS);
10865	case CTL_SER_EXTENTSEQ:
10866		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10867			return (ctl_extent_check_seq(ooa_io, pending_io));
10868		return (CTL_ACTION_PASS);
10869	case CTL_SER_PASS:
10870		return (CTL_ACTION_PASS);
10871	case CTL_SER_BLOCKOPT:
10872		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10873		    SCP_QUEUE_ALG_UNRESTRICTED)
10874			return (CTL_ACTION_BLOCK);
10875		return (CTL_ACTION_PASS);
10876	case CTL_SER_SKIP:
10877		return (CTL_ACTION_SKIP);
10878	default:
10879		panic("%s: Invalid serialization value %d for %d => %d",
10880		    __func__, serialize_row[pending_entry->seridx],
10881		    pending_entry->seridx, ooa_entry->seridx);
10882	}
10883
10884	return (CTL_ACTION_ERROR);
10885}
10886
10887/*
10888 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10889 * Assumptions:
10890 * - pending_io is generally either incoming, or on the blocked queue
10891 * - starting I/O is the I/O we want to start the check with.
10892 */
10893static ctl_action
10894ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10895	      union ctl_io *starting_io)
10896{
10897	union ctl_io *ooa_io;
10898	ctl_action action;
10899
10900	mtx_assert(&lun->lun_lock, MA_OWNED);
10901
10902	/*
10903	 * Run back along the OOA queue, starting with the current
10904	 * blocked I/O and going through every I/O before it on the
10905	 * queue.  If starting_io is NULL, we'll just end up returning
10906	 * CTL_ACTION_PASS.
10907	 */
10908	for (ooa_io = starting_io; ooa_io != NULL;
10909	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10910	     ooa_links)){
10911
10912		/*
10913		 * This routine just checks to see whether
10914		 * cur_blocked is blocked by ooa_io, which is ahead
10915		 * of it in the queue.  It doesn't queue/dequeue
10916		 * cur_blocked.
10917		 */
10918		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10919		switch (action) {
10920		case CTL_ACTION_BLOCK:
10921		case CTL_ACTION_OVERLAP:
10922		case CTL_ACTION_OVERLAP_TAG:
10923		case CTL_ACTION_SKIP:
10924		case CTL_ACTION_ERROR:
10925			return (action);
10926			break; /* NOTREACHED */
10927		case CTL_ACTION_PASS:
10928			break;
10929		default:
10930			panic("%s: Invalid action %d\n", __func__, action);
10931		}
10932	}
10933
10934	return (CTL_ACTION_PASS);
10935}
10936
10937/*
10938 * Assumptions:
10939 * - An I/O has just completed, and has been removed from the per-LUN OOA
10940 *   queue, so some items on the blocked queue may now be unblocked.
10941 */
10942static int
10943ctl_check_blocked(struct ctl_lun *lun)
10944{
10945	struct ctl_softc *softc = lun->ctl_softc;
10946	union ctl_io *cur_blocked, *next_blocked;
10947
10948	mtx_assert(&lun->lun_lock, MA_OWNED);
10949
10950	/*
10951	 * Run forward from the head of the blocked queue, checking each
10952	 * entry against the I/Os prior to it on the OOA queue to see if
10953	 * there is still any blockage.
10954	 *
10955	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10956	 * with our removing a variable on it while it is traversing the
10957	 * list.
10958	 */
10959	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10960	     cur_blocked != NULL; cur_blocked = next_blocked) {
10961		union ctl_io *prev_ooa;
10962		ctl_action action;
10963
10964		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10965							  blocked_links);
10966
10967		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10968						      ctl_ooaq, ooa_links);
10969
10970		/*
10971		 * If cur_blocked happens to be the first item in the OOA
10972		 * queue now, prev_ooa will be NULL, and the action
10973		 * returned will just be CTL_ACTION_PASS.
10974		 */
10975		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10976
10977		switch (action) {
10978		case CTL_ACTION_BLOCK:
10979			/* Nothing to do here, still blocked */
10980			break;
10981		case CTL_ACTION_OVERLAP:
10982		case CTL_ACTION_OVERLAP_TAG:
10983			/*
10984			 * This shouldn't happen!  In theory we've already
10985			 * checked this command for overlap...
10986			 */
10987			break;
10988		case CTL_ACTION_PASS:
10989		case CTL_ACTION_SKIP: {
10990			const struct ctl_cmd_entry *entry;
10991
10992			/*
10993			 * The skip case shouldn't happen, this transaction
10994			 * should have never made it onto the blocked queue.
10995			 */
10996			/*
10997			 * This I/O is no longer blocked, we can remove it
10998			 * from the blocked queue.  Since this is a TAILQ
10999			 * (doubly linked list), we can do O(1) removals
11000			 * from any place on the list.
11001			 */
11002			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11003				     blocked_links);
11004			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11005
11006			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11007			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11008				/*
11009				 * Need to send IO back to original side to
11010				 * run
11011				 */
11012				union ctl_ha_msg msg_info;
11013
11014				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11015				msg_info.hdr.original_sc =
11016					cur_blocked->io_hdr.original_sc;
11017				msg_info.hdr.serializing_sc = cur_blocked;
11018				msg_info.hdr.msg_type = CTL_MSG_R2R;
11019				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11020				    sizeof(msg_info.hdr), M_NOWAIT);
11021				break;
11022			}
11023			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11024
11025			/*
11026			 * Check this I/O for LUN state changes that may
11027			 * have happened while this command was blocked.
11028			 * The LUN state may have been changed by a command
11029			 * ahead of us in the queue, so we need to re-check
11030			 * for any states that can be caused by SCSI
11031			 * commands.
11032			 */
11033			if (ctl_scsiio_lun_check(lun, entry,
11034						 &cur_blocked->scsiio) == 0) {
11035				cur_blocked->io_hdr.flags |=
11036				                      CTL_FLAG_IS_WAS_ON_RTR;
11037				ctl_enqueue_rtr(cur_blocked);
11038			} else
11039				ctl_done(cur_blocked);
11040			break;
11041		}
11042		default:
11043			/*
11044			 * This probably shouldn't happen -- we shouldn't
11045			 * get CTL_ACTION_ERROR, or anything else.
11046			 */
11047			break;
11048		}
11049	}
11050
11051	return (CTL_RETVAL_COMPLETE);
11052}
11053
11054/*
11055 * This routine (with one exception) checks LUN flags that can be set by
11056 * commands ahead of us in the OOA queue.  These flags have to be checked
11057 * when a command initially comes in, and when we pull a command off the
11058 * blocked queue and are preparing to execute it.  The reason we have to
11059 * check these flags for commands on the blocked queue is that the LUN
11060 * state may have been changed by a command ahead of us while we're on the
11061 * blocked queue.
11062 *
11063 * Ordering is somewhat important with these checks, so please pay
11064 * careful attention to the placement of any new checks.
11065 */
11066static int
11067ctl_scsiio_lun_check(struct ctl_lun *lun,
11068    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11069{
11070	struct ctl_softc *softc = lun->ctl_softc;
11071	int retval;
11072	uint32_t residx;
11073
11074	retval = 0;
11075
11076	mtx_assert(&lun->lun_lock, MA_OWNED);
11077
11078	/*
11079	 * If this shelf is a secondary shelf controller, we may have to
11080	 * reject some commands disallowed by HA mode and link state.
11081	 */
11082	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11083		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11084		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11085			ctl_set_lun_unavail(ctsio);
11086			retval = 1;
11087			goto bailout;
11088		}
11089		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11090		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11091			ctl_set_lun_transit(ctsio);
11092			retval = 1;
11093			goto bailout;
11094		}
11095		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11096		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11097			ctl_set_lun_standby(ctsio);
11098			retval = 1;
11099			goto bailout;
11100		}
11101
11102		/* The rest of checks are only done on executing side */
11103		if (softc->ha_mode == CTL_HA_MODE_XFER)
11104			goto bailout;
11105	}
11106
11107	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11108		if (lun->be_lun &&
11109		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11110			ctl_set_hw_write_protected(ctsio);
11111			retval = 1;
11112			goto bailout;
11113		}
11114		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11115			ctl_set_sense(ctsio, /*current_error*/ 1,
11116			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11117			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11118			retval = 1;
11119			goto bailout;
11120		}
11121	}
11122
11123	/*
11124	 * Check for a reservation conflict.  If this command isn't allowed
11125	 * even on reserved LUNs, and if this initiator isn't the one who
11126	 * reserved us, reject the command with a reservation conflict.
11127	 */
11128	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11129	if ((lun->flags & CTL_LUN_RESERVED)
11130	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11131		if (lun->res_idx != residx) {
11132			ctl_set_reservation_conflict(ctsio);
11133			retval = 1;
11134			goto bailout;
11135		}
11136	}
11137
11138	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11139	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11140		/* No reservation or command is allowed. */;
11141	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11142	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11143	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11144	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11145		/* The command is allowed for Write Exclusive resv. */;
11146	} else {
11147		/*
11148		 * if we aren't registered or it's a res holder type
11149		 * reservation and this isn't the res holder then set a
11150		 * conflict.
11151		 */
11152		if (ctl_get_prkey(lun, residx) == 0 ||
11153		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11154			ctl_set_reservation_conflict(ctsio);
11155			retval = 1;
11156			goto bailout;
11157		}
11158	}
11159
11160	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11161		if (lun->flags & CTL_LUN_EJECTED)
11162			ctl_set_lun_ejected(ctsio);
11163		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11164			if (lun->flags & CTL_LUN_REMOVABLE)
11165				ctl_set_lun_no_media(ctsio);
11166			else
11167				ctl_set_lun_int_reqd(ctsio);
11168		} else if (lun->flags & CTL_LUN_STOPPED)
11169			ctl_set_lun_stopped(ctsio);
11170		else
11171			goto bailout;
11172		retval = 1;
11173		goto bailout;
11174	}
11175
11176bailout:
11177	return (retval);
11178}
11179
11180static void
11181ctl_failover_io(union ctl_io *io, int have_lock)
11182{
11183	ctl_set_busy(&io->scsiio);
11184	ctl_done(io);
11185}
11186
11187static void
11188ctl_failover_lun(union ctl_io *rio)
11189{
11190	struct ctl_softc *softc = CTL_SOFTC(rio);
11191	struct ctl_lun *lun;
11192	struct ctl_io_hdr *io, *next_io;
11193	uint32_t targ_lun;
11194
11195	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11196	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11197
11198	/* Find and lock the LUN. */
11199	mtx_lock(&softc->ctl_lock);
11200	if (targ_lun > CTL_MAX_LUNS ||
11201	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11202		mtx_unlock(&softc->ctl_lock);
11203		return;
11204	}
11205	mtx_lock(&lun->lun_lock);
11206	mtx_unlock(&softc->ctl_lock);
11207	if (lun->flags & CTL_LUN_DISABLED) {
11208		mtx_unlock(&lun->lun_lock);
11209		return;
11210	}
11211
11212	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11213		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11214			/* We are master */
11215			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11216				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11217					io->flags |= CTL_FLAG_ABORT;
11218					io->flags |= CTL_FLAG_FAILOVER;
11219				} else { /* This can be only due to DATAMOVE */
11220					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11221					io->flags &= ~CTL_FLAG_DMA_INPROG;
11222					io->flags |= CTL_FLAG_IO_ACTIVE;
11223					io->port_status = 31340;
11224					ctl_enqueue_isc((union ctl_io *)io);
11225				}
11226			}
11227			/* We are slave */
11228			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11229				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11230				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11231					io->flags |= CTL_FLAG_FAILOVER;
11232				} else {
11233					ctl_set_busy(&((union ctl_io *)io)->
11234					    scsiio);
11235					ctl_done((union ctl_io *)io);
11236				}
11237			}
11238		}
11239	} else { /* SERIALIZE modes */
11240		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11241		    next_io) {
11242			/* We are master */
11243			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11244				TAILQ_REMOVE(&lun->blocked_queue, io,
11245				    blocked_links);
11246				io->flags &= ~CTL_FLAG_BLOCKED;
11247				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11248				ctl_free_io((union ctl_io *)io);
11249			}
11250		}
11251		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11252			/* We are master */
11253			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11254				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11255				ctl_free_io((union ctl_io *)io);
11256			}
11257			/* We are slave */
11258			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11259				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11260				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11261					ctl_set_busy(&((union ctl_io *)io)->
11262					    scsiio);
11263					ctl_done((union ctl_io *)io);
11264				}
11265			}
11266		}
11267		ctl_check_blocked(lun);
11268	}
11269	mtx_unlock(&lun->lun_lock);
11270}
11271
11272static int
11273ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11274{
11275	struct ctl_lun *lun;
11276	const struct ctl_cmd_entry *entry;
11277	uint32_t initidx, targ_lun;
11278	int retval = 0;
11279
11280	lun = NULL;
11281	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11282	if (targ_lun < CTL_MAX_LUNS)
11283		lun = softc->ctl_luns[targ_lun];
11284	if (lun) {
11285		/*
11286		 * If the LUN is invalid, pretend that it doesn't exist.
11287		 * It will go away as soon as all pending I/O has been
11288		 * completed.
11289		 */
11290		mtx_lock(&lun->lun_lock);
11291		if (lun->flags & CTL_LUN_DISABLED) {
11292			mtx_unlock(&lun->lun_lock);
11293			lun = NULL;
11294		}
11295	}
11296	CTL_LUN(ctsio) = lun;
11297	if (lun) {
11298		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11299
11300		/*
11301		 * Every I/O goes into the OOA queue for a particular LUN,
11302		 * and stays there until completion.
11303		 */
11304#ifdef CTL_TIME_IO
11305		if (TAILQ_EMPTY(&lun->ooa_queue))
11306			lun->idle_time += getsbinuptime() - lun->last_busy;
11307#endif
11308		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11309	}
11310
11311	/* Get command entry and return error if it is unsuppotyed. */
11312	entry = ctl_validate_command(ctsio);
11313	if (entry == NULL) {
11314		if (lun)
11315			mtx_unlock(&lun->lun_lock);
11316		return (retval);
11317	}
11318
11319	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11320	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11321
11322	/*
11323	 * Check to see whether we can send this command to LUNs that don't
11324	 * exist.  This should pretty much only be the case for inquiry
11325	 * and request sense.  Further checks, below, really require having
11326	 * a LUN, so we can't really check the command anymore.  Just put
11327	 * it on the rtr queue.
11328	 */
11329	if (lun == NULL) {
11330		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11331			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11332			ctl_enqueue_rtr((union ctl_io *)ctsio);
11333			return (retval);
11334		}
11335
11336		ctl_set_unsupported_lun(ctsio);
11337		ctl_done((union ctl_io *)ctsio);
11338		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11339		return (retval);
11340	} else {
11341		/*
11342		 * Make sure we support this particular command on this LUN.
11343		 * e.g., we don't support writes to the control LUN.
11344		 */
11345		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11346			mtx_unlock(&lun->lun_lock);
11347			ctl_set_invalid_opcode(ctsio);
11348			ctl_done((union ctl_io *)ctsio);
11349			return (retval);
11350		}
11351	}
11352
11353	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11354
11355	/*
11356	 * If we've got a request sense, it'll clear the contingent
11357	 * allegiance condition.  Otherwise, if we have a CA condition for
11358	 * this initiator, clear it, because it sent down a command other
11359	 * than request sense.
11360	 */
11361	if (ctsio->cdb[0] != REQUEST_SENSE) {
11362		struct scsi_sense_data *ps;
11363
11364		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11365		if (ps != NULL)
11366			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11367	}
11368
11369	/*
11370	 * If the command has this flag set, it handles its own unit
11371	 * attention reporting, we shouldn't do anything.  Otherwise we
11372	 * check for any pending unit attentions, and send them back to the
11373	 * initiator.  We only do this when a command initially comes in,
11374	 * not when we pull it off the blocked queue.
11375	 *
11376	 * According to SAM-3, section 5.3.2, the order that things get
11377	 * presented back to the host is basically unit attentions caused
11378	 * by some sort of reset event, busy status, reservation conflicts
11379	 * or task set full, and finally any other status.
11380	 *
11381	 * One issue here is that some of the unit attentions we report
11382	 * don't fall into the "reset" category (e.g. "reported luns data
11383	 * has changed").  So reporting it here, before the reservation
11384	 * check, may be technically wrong.  I guess the only thing to do
11385	 * would be to check for and report the reset events here, and then
11386	 * check for the other unit attention types after we check for a
11387	 * reservation conflict.
11388	 *
11389	 * XXX KDM need to fix this
11390	 */
11391	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11392		ctl_ua_type ua_type;
11393		u_int sense_len = 0;
11394
11395		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11396		    &sense_len, SSD_TYPE_NONE);
11397		if (ua_type != CTL_UA_NONE) {
11398			mtx_unlock(&lun->lun_lock);
11399			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11400			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11401			ctsio->sense_len = sense_len;
11402			ctl_done((union ctl_io *)ctsio);
11403			return (retval);
11404		}
11405	}
11406
11407
11408	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11409		mtx_unlock(&lun->lun_lock);
11410		ctl_done((union ctl_io *)ctsio);
11411		return (retval);
11412	}
11413
11414	/*
11415	 * XXX CHD this is where we want to send IO to other side if
11416	 * this LUN is secondary on this SC. We will need to make a copy
11417	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11418	 * the copy we send as FROM_OTHER.
11419	 * We also need to stuff the address of the original IO so we can
11420	 * find it easily. Something similar will need be done on the other
11421	 * side so when we are done we can find the copy.
11422	 */
11423	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11424	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11425	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11426		union ctl_ha_msg msg_info;
11427		int isc_retval;
11428
11429		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11430		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11431		mtx_unlock(&lun->lun_lock);
11432
11433		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11434		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11435		msg_info.hdr.serializing_sc = NULL;
11436		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11437		msg_info.scsi.tag_num = ctsio->tag_num;
11438		msg_info.scsi.tag_type = ctsio->tag_type;
11439		msg_info.scsi.cdb_len = ctsio->cdb_len;
11440		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11441
11442		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11443		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11444		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11445			ctl_set_busy(ctsio);
11446			ctl_done((union ctl_io *)ctsio);
11447			return (retval);
11448		}
11449		return (retval);
11450	}
11451
11452	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11453			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11454			      ctl_ooaq, ooa_links))) {
11455	case CTL_ACTION_BLOCK:
11456		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11457		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11458				  blocked_links);
11459		mtx_unlock(&lun->lun_lock);
11460		return (retval);
11461	case CTL_ACTION_PASS:
11462	case CTL_ACTION_SKIP:
11463		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11464		mtx_unlock(&lun->lun_lock);
11465		ctl_enqueue_rtr((union ctl_io *)ctsio);
11466		break;
11467	case CTL_ACTION_OVERLAP:
11468		mtx_unlock(&lun->lun_lock);
11469		ctl_set_overlapped_cmd(ctsio);
11470		ctl_done((union ctl_io *)ctsio);
11471		break;
11472	case CTL_ACTION_OVERLAP_TAG:
11473		mtx_unlock(&lun->lun_lock);
11474		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11475		ctl_done((union ctl_io *)ctsio);
11476		break;
11477	case CTL_ACTION_ERROR:
11478	default:
11479		mtx_unlock(&lun->lun_lock);
11480		ctl_set_internal_failure(ctsio,
11481					 /*sks_valid*/ 0,
11482					 /*retry_count*/ 0);
11483		ctl_done((union ctl_io *)ctsio);
11484		break;
11485	}
11486	return (retval);
11487}
11488
11489const struct ctl_cmd_entry *
11490ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11491{
11492	const struct ctl_cmd_entry *entry;
11493	int service_action;
11494
11495	entry = &ctl_cmd_table[ctsio->cdb[0]];
11496	if (sa)
11497		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11498	if (entry->flags & CTL_CMD_FLAG_SA5) {
11499		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11500		entry = &((const struct ctl_cmd_entry *)
11501		    entry->execute)[service_action];
11502	}
11503	return (entry);
11504}
11505
11506const struct ctl_cmd_entry *
11507ctl_validate_command(struct ctl_scsiio *ctsio)
11508{
11509	const struct ctl_cmd_entry *entry;
11510	int i, sa;
11511	uint8_t diff;
11512
11513	entry = ctl_get_cmd_entry(ctsio, &sa);
11514	if (entry->execute == NULL) {
11515		if (sa)
11516			ctl_set_invalid_field(ctsio,
11517					      /*sks_valid*/ 1,
11518					      /*command*/ 1,
11519					      /*field*/ 1,
11520					      /*bit_valid*/ 1,
11521					      /*bit*/ 4);
11522		else
11523			ctl_set_invalid_opcode(ctsio);
11524		ctl_done((union ctl_io *)ctsio);
11525		return (NULL);
11526	}
11527	KASSERT(entry->length > 0,
11528	    ("Not defined length for command 0x%02x/0x%02x",
11529	     ctsio->cdb[0], ctsio->cdb[1]));
11530	for (i = 1; i < entry->length; i++) {
11531		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11532		if (diff == 0)
11533			continue;
11534		ctl_set_invalid_field(ctsio,
11535				      /*sks_valid*/ 1,
11536				      /*command*/ 1,
11537				      /*field*/ i,
11538				      /*bit_valid*/ 1,
11539				      /*bit*/ fls(diff) - 1);
11540		ctl_done((union ctl_io *)ctsio);
11541		return (NULL);
11542	}
11543	return (entry);
11544}
11545
11546static int
11547ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11548{
11549
11550	switch (lun_type) {
11551	case T_DIRECT:
11552		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11553			return (0);
11554		break;
11555	case T_PROCESSOR:
11556		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11557			return (0);
11558		break;
11559	case T_CDROM:
11560		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11561			return (0);
11562		break;
11563	default:
11564		return (0);
11565	}
11566	return (1);
11567}
11568
11569static int
11570ctl_scsiio(struct ctl_scsiio *ctsio)
11571{
11572	int retval;
11573	const struct ctl_cmd_entry *entry;
11574
11575	retval = CTL_RETVAL_COMPLETE;
11576
11577	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11578
11579	entry = ctl_get_cmd_entry(ctsio, NULL);
11580
11581	/*
11582	 * If this I/O has been aborted, just send it straight to
11583	 * ctl_done() without executing it.
11584	 */
11585	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11586		ctl_done((union ctl_io *)ctsio);
11587		goto bailout;
11588	}
11589
11590	/*
11591	 * All the checks should have been handled by ctl_scsiio_precheck().
11592	 * We should be clear now to just execute the I/O.
11593	 */
11594	retval = entry->execute(ctsio);
11595
11596bailout:
11597	return (retval);
11598}
11599
11600static int
11601ctl_target_reset(union ctl_io *io)
11602{
11603	struct ctl_softc *softc = CTL_SOFTC(io);
11604	struct ctl_port *port = CTL_PORT(io);
11605	struct ctl_lun *lun;
11606	uint32_t initidx;
11607	ctl_ua_type ua_type;
11608
11609	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11610		union ctl_ha_msg msg_info;
11611
11612		msg_info.hdr.nexus = io->io_hdr.nexus;
11613		msg_info.task.task_action = io->taskio.task_action;
11614		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11615		msg_info.hdr.original_sc = NULL;
11616		msg_info.hdr.serializing_sc = NULL;
11617		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11618		    sizeof(msg_info.task), M_WAITOK);
11619	}
11620
11621	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11622	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11623		ua_type = CTL_UA_TARG_RESET;
11624	else
11625		ua_type = CTL_UA_BUS_RESET;
11626	mtx_lock(&softc->ctl_lock);
11627	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11628		if (port != NULL &&
11629		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11630			continue;
11631		ctl_do_lun_reset(lun, initidx, ua_type);
11632	}
11633	mtx_unlock(&softc->ctl_lock);
11634	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11635	return (0);
11636}
11637
11638/*
11639 * The LUN should always be set.  The I/O is optional, and is used to
11640 * distinguish between I/Os sent by this initiator, and by other
11641 * initiators.  We set unit attention for initiators other than this one.
11642 * SAM-3 is vague on this point.  It does say that a unit attention should
11643 * be established for other initiators when a LUN is reset (see section
11644 * 5.7.3), but it doesn't specifically say that the unit attention should
11645 * be established for this particular initiator when a LUN is reset.  Here
11646 * is the relevant text, from SAM-3 rev 8:
11647 *
11648 * 5.7.2 When a SCSI initiator port aborts its own tasks
11649 *
11650 * When a SCSI initiator port causes its own task(s) to be aborted, no
11651 * notification that the task(s) have been aborted shall be returned to
11652 * the SCSI initiator port other than the completion response for the
11653 * command or task management function action that caused the task(s) to
11654 * be aborted and notification(s) associated with related effects of the
11655 * action (e.g., a reset unit attention condition).
11656 *
11657 * XXX KDM for now, we're setting unit attention for all initiators.
11658 */
11659static void
11660ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11661{
11662	union ctl_io *xio;
11663	int i;
11664
11665	mtx_lock(&lun->lun_lock);
11666	/* Abort tasks. */
11667	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11668	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11669		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11670	}
11671	/* Clear CA. */
11672	for (i = 0; i < CTL_MAX_PORTS; i++) {
11673		free(lun->pending_sense[i], M_CTL);
11674		lun->pending_sense[i] = NULL;
11675	}
11676	/* Clear reservation. */
11677	lun->flags &= ~CTL_LUN_RESERVED;
11678	/* Clear prevent media removal. */
11679	if (lun->prevent) {
11680		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11681			ctl_clear_mask(lun->prevent, i);
11682		lun->prevent_count = 0;
11683	}
11684	/* Clear TPC status */
11685	ctl_tpc_lun_clear(lun, -1);
11686	/* Establish UA. */
11687#if 0
11688	ctl_est_ua_all(lun, initidx, ua_type);
11689#else
11690	ctl_est_ua_all(lun, -1, ua_type);
11691#endif
11692	mtx_unlock(&lun->lun_lock);
11693}
11694
11695static int
11696ctl_lun_reset(union ctl_io *io)
11697{
11698	struct ctl_softc *softc = CTL_SOFTC(io);
11699	struct ctl_lun *lun;
11700	uint32_t targ_lun, initidx;
11701
11702	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11703	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11704	mtx_lock(&softc->ctl_lock);
11705	if (targ_lun >= CTL_MAX_LUNS ||
11706	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11707		mtx_unlock(&softc->ctl_lock);
11708		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11709		return (1);
11710	}
11711	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11712	mtx_unlock(&softc->ctl_lock);
11713	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11714
11715	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11716		union ctl_ha_msg msg_info;
11717
11718		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11719		msg_info.hdr.nexus = io->io_hdr.nexus;
11720		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11721		msg_info.hdr.original_sc = NULL;
11722		msg_info.hdr.serializing_sc = NULL;
11723		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11724		    sizeof(msg_info.task), M_WAITOK);
11725	}
11726	return (0);
11727}
11728
11729static void
11730ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11731    int other_sc)
11732{
11733	union ctl_io *xio;
11734
11735	mtx_assert(&lun->lun_lock, MA_OWNED);
11736
11737	/*
11738	 * Run through the OOA queue and attempt to find the given I/O.
11739	 * The target port, initiator ID, tag type and tag number have to
11740	 * match the values that we got from the initiator.  If we have an
11741	 * untagged command to abort, simply abort the first untagged command
11742	 * we come to.  We only allow one untagged command at a time of course.
11743	 */
11744	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11745	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11746
11747		if ((targ_port == UINT32_MAX ||
11748		     targ_port == xio->io_hdr.nexus.targ_port) &&
11749		    (init_id == UINT32_MAX ||
11750		     init_id == xio->io_hdr.nexus.initid)) {
11751			if (targ_port != xio->io_hdr.nexus.targ_port ||
11752			    init_id != xio->io_hdr.nexus.initid)
11753				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11754			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11755			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11756				union ctl_ha_msg msg_info;
11757
11758				msg_info.hdr.nexus = xio->io_hdr.nexus;
11759				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11760				msg_info.task.tag_num = xio->scsiio.tag_num;
11761				msg_info.task.tag_type = xio->scsiio.tag_type;
11762				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11763				msg_info.hdr.original_sc = NULL;
11764				msg_info.hdr.serializing_sc = NULL;
11765				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11766				    sizeof(msg_info.task), M_NOWAIT);
11767			}
11768		}
11769	}
11770}
11771
11772static int
11773ctl_abort_task_set(union ctl_io *io)
11774{
11775	struct ctl_softc *softc = CTL_SOFTC(io);
11776	struct ctl_lun *lun;
11777	uint32_t targ_lun;
11778
11779	/*
11780	 * Look up the LUN.
11781	 */
11782	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11783	mtx_lock(&softc->ctl_lock);
11784	if (targ_lun >= CTL_MAX_LUNS ||
11785	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11786		mtx_unlock(&softc->ctl_lock);
11787		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11788		return (1);
11789	}
11790
11791	mtx_lock(&lun->lun_lock);
11792	mtx_unlock(&softc->ctl_lock);
11793	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11794		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11795		    io->io_hdr.nexus.initid,
11796		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11797	} else { /* CTL_TASK_CLEAR_TASK_SET */
11798		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11799		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11800	}
11801	mtx_unlock(&lun->lun_lock);
11802	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11803	return (0);
11804}
11805
11806static void
11807ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11808    ctl_ua_type ua_type)
11809{
11810	struct ctl_lun *lun;
11811	struct scsi_sense_data *ps;
11812	uint32_t p, i;
11813
11814	p = initidx / CTL_MAX_INIT_PER_PORT;
11815	i = initidx % CTL_MAX_INIT_PER_PORT;
11816	mtx_lock(&softc->ctl_lock);
11817	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11818		mtx_lock(&lun->lun_lock);
11819		/* Abort tasks. */
11820		ctl_abort_tasks_lun(lun, p, i, 1);
11821		/* Clear CA. */
11822		ps = lun->pending_sense[p];
11823		if (ps != NULL)
11824			ps[i].error_code = 0;
11825		/* Clear reservation. */
11826		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11827			lun->flags &= ~CTL_LUN_RESERVED;
11828		/* Clear prevent media removal. */
11829		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11830			ctl_clear_mask(lun->prevent, initidx);
11831			lun->prevent_count--;
11832		}
11833		/* Clear TPC status */
11834		ctl_tpc_lun_clear(lun, initidx);
11835		/* Establish UA. */
11836		ctl_est_ua(lun, initidx, ua_type);
11837		mtx_unlock(&lun->lun_lock);
11838	}
11839	mtx_unlock(&softc->ctl_lock);
11840}
11841
11842static int
11843ctl_i_t_nexus_reset(union ctl_io *io)
11844{
11845	struct ctl_softc *softc = CTL_SOFTC(io);
11846	uint32_t initidx;
11847
11848	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11849		union ctl_ha_msg msg_info;
11850
11851		msg_info.hdr.nexus = io->io_hdr.nexus;
11852		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11853		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11854		msg_info.hdr.original_sc = NULL;
11855		msg_info.hdr.serializing_sc = NULL;
11856		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11857		    sizeof(msg_info.task), M_WAITOK);
11858	}
11859
11860	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11861	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
11862	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11863	return (0);
11864}
11865
11866static int
11867ctl_abort_task(union ctl_io *io)
11868{
11869	struct ctl_softc *softc = CTL_SOFTC(io);
11870	union ctl_io *xio;
11871	struct ctl_lun *lun;
11872#if 0
11873	struct sbuf sb;
11874	char printbuf[128];
11875#endif
11876	int found;
11877	uint32_t targ_lun;
11878
11879	found = 0;
11880
11881	/*
11882	 * Look up the LUN.
11883	 */
11884	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11885	mtx_lock(&softc->ctl_lock);
11886	if (targ_lun >= CTL_MAX_LUNS ||
11887	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11888		mtx_unlock(&softc->ctl_lock);
11889		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11890		return (1);
11891	}
11892
11893#if 0
11894	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11895	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11896#endif
11897
11898	mtx_lock(&lun->lun_lock);
11899	mtx_unlock(&softc->ctl_lock);
11900	/*
11901	 * Run through the OOA queue and attempt to find the given I/O.
11902	 * The target port, initiator ID, tag type and tag number have to
11903	 * match the values that we got from the initiator.  If we have an
11904	 * untagged command to abort, simply abort the first untagged command
11905	 * we come to.  We only allow one untagged command at a time of course.
11906	 */
11907	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11908	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11909#if 0
11910		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11911
11912		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11913			    lun->lun, xio->scsiio.tag_num,
11914			    xio->scsiio.tag_type,
11915			    (xio->io_hdr.blocked_links.tqe_prev
11916			    == NULL) ? "" : " BLOCKED",
11917			    (xio->io_hdr.flags &
11918			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11919			    (xio->io_hdr.flags &
11920			    CTL_FLAG_ABORT) ? " ABORT" : "",
11921			    (xio->io_hdr.flags &
11922			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11923		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11924		sbuf_finish(&sb);
11925		printf("%s\n", sbuf_data(&sb));
11926#endif
11927
11928		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11929		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11930		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11931			continue;
11932
11933		/*
11934		 * If the abort says that the task is untagged, the
11935		 * task in the queue must be untagged.  Otherwise,
11936		 * we just check to see whether the tag numbers
11937		 * match.  This is because the QLogic firmware
11938		 * doesn't pass back the tag type in an abort
11939		 * request.
11940		 */
11941#if 0
11942		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11943		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11944		 || (xio->scsiio.tag_num == io->taskio.tag_num))
11945#endif
11946		/*
11947		 * XXX KDM we've got problems with FC, because it
11948		 * doesn't send down a tag type with aborts.  So we
11949		 * can only really go by the tag number...
11950		 * This may cause problems with parallel SCSI.
11951		 * Need to figure that out!!
11952		 */
11953		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11954			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11955			found = 1;
11956			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11957			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11958				union ctl_ha_msg msg_info;
11959
11960				msg_info.hdr.nexus = io->io_hdr.nexus;
11961				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11962				msg_info.task.tag_num = io->taskio.tag_num;
11963				msg_info.task.tag_type = io->taskio.tag_type;
11964				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11965				msg_info.hdr.original_sc = NULL;
11966				msg_info.hdr.serializing_sc = NULL;
11967#if 0
11968				printf("Sent Abort to other side\n");
11969#endif
11970				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11971				    sizeof(msg_info.task), M_NOWAIT);
11972			}
11973#if 0
11974			printf("ctl_abort_task: found I/O to abort\n");
11975#endif
11976		}
11977	}
11978	mtx_unlock(&lun->lun_lock);
11979
11980	if (found == 0) {
11981		/*
11982		 * This isn't really an error.  It's entirely possible for
11983		 * the abort and command completion to cross on the wire.
11984		 * This is more of an informative/diagnostic error.
11985		 */
11986#if 0
11987		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11988		       "%u:%u:%u tag %d type %d\n",
11989		       io->io_hdr.nexus.initid,
11990		       io->io_hdr.nexus.targ_port,
11991		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11992		       io->taskio.tag_type);
11993#endif
11994	}
11995	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11996	return (0);
11997}
11998
11999static int
12000ctl_query_task(union ctl_io *io, int task_set)
12001{
12002	struct ctl_softc *softc = CTL_SOFTC(io);
12003	union ctl_io *xio;
12004	struct ctl_lun *lun;
12005	int found = 0;
12006	uint32_t targ_lun;
12007
12008	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12009	mtx_lock(&softc->ctl_lock);
12010	if (targ_lun >= CTL_MAX_LUNS ||
12011	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12012		mtx_unlock(&softc->ctl_lock);
12013		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12014		return (1);
12015	}
12016	mtx_lock(&lun->lun_lock);
12017	mtx_unlock(&softc->ctl_lock);
12018	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12019	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12020
12021		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12022		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12023		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12024			continue;
12025
12026		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12027			found = 1;
12028			break;
12029		}
12030	}
12031	mtx_unlock(&lun->lun_lock);
12032	if (found)
12033		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12034	else
12035		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12036	return (0);
12037}
12038
12039static int
12040ctl_query_async_event(union ctl_io *io)
12041{
12042	struct ctl_softc *softc = CTL_SOFTC(io);
12043	struct ctl_lun *lun;
12044	ctl_ua_type ua;
12045	uint32_t targ_lun, initidx;
12046
12047	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12048	mtx_lock(&softc->ctl_lock);
12049	if (targ_lun >= CTL_MAX_LUNS ||
12050	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12051		mtx_unlock(&softc->ctl_lock);
12052		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12053		return (1);
12054	}
12055	mtx_lock(&lun->lun_lock);
12056	mtx_unlock(&softc->ctl_lock);
12057	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12058	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12059	mtx_unlock(&lun->lun_lock);
12060	if (ua != CTL_UA_NONE)
12061		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12062	else
12063		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12064	return (0);
12065}
12066
12067static void
12068ctl_run_task(union ctl_io *io)
12069{
12070	int retval = 1;
12071
12072	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12073	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12074	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12075	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12076	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12077	switch (io->taskio.task_action) {
12078	case CTL_TASK_ABORT_TASK:
12079		retval = ctl_abort_task(io);
12080		break;
12081	case CTL_TASK_ABORT_TASK_SET:
12082	case CTL_TASK_CLEAR_TASK_SET:
12083		retval = ctl_abort_task_set(io);
12084		break;
12085	case CTL_TASK_CLEAR_ACA:
12086		break;
12087	case CTL_TASK_I_T_NEXUS_RESET:
12088		retval = ctl_i_t_nexus_reset(io);
12089		break;
12090	case CTL_TASK_LUN_RESET:
12091		retval = ctl_lun_reset(io);
12092		break;
12093	case CTL_TASK_TARGET_RESET:
12094	case CTL_TASK_BUS_RESET:
12095		retval = ctl_target_reset(io);
12096		break;
12097	case CTL_TASK_PORT_LOGIN:
12098		break;
12099	case CTL_TASK_PORT_LOGOUT:
12100		break;
12101	case CTL_TASK_QUERY_TASK:
12102		retval = ctl_query_task(io, 0);
12103		break;
12104	case CTL_TASK_QUERY_TASK_SET:
12105		retval = ctl_query_task(io, 1);
12106		break;
12107	case CTL_TASK_QUERY_ASYNC_EVENT:
12108		retval = ctl_query_async_event(io);
12109		break;
12110	default:
12111		printf("%s: got unknown task management event %d\n",
12112		       __func__, io->taskio.task_action);
12113		break;
12114	}
12115	if (retval == 0)
12116		io->io_hdr.status = CTL_SUCCESS;
12117	else
12118		io->io_hdr.status = CTL_ERROR;
12119	ctl_done(io);
12120}
12121
12122/*
12123 * For HA operation.  Handle commands that come in from the other
12124 * controller.
12125 */
12126static void
12127ctl_handle_isc(union ctl_io *io)
12128{
12129	struct ctl_softc *softc = CTL_SOFTC(io);
12130	struct ctl_lun *lun;
12131	const struct ctl_cmd_entry *entry;
12132	uint32_t targ_lun;
12133
12134	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12135	switch (io->io_hdr.msg_type) {
12136	case CTL_MSG_SERIALIZE:
12137		ctl_serialize_other_sc_cmd(&io->scsiio);
12138		break;
12139	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12140		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12141		if (targ_lun >= CTL_MAX_LUNS ||
12142		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12143			ctl_done(io);
12144			break;
12145		}
12146		mtx_lock(&lun->lun_lock);
12147		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12148			mtx_unlock(&lun->lun_lock);
12149			ctl_done(io);
12150			break;
12151		}
12152		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12153		mtx_unlock(&lun->lun_lock);
12154		ctl_enqueue_rtr(io);
12155		break;
12156	case CTL_MSG_FINISH_IO:
12157		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12158			ctl_done(io);
12159			break;
12160		}
12161		if (targ_lun >= CTL_MAX_LUNS ||
12162		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12163			ctl_free_io(io);
12164			break;
12165		}
12166		mtx_lock(&lun->lun_lock);
12167		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12168		ctl_check_blocked(lun);
12169		mtx_unlock(&lun->lun_lock);
12170		ctl_free_io(io);
12171		break;
12172	case CTL_MSG_PERS_ACTION:
12173		ctl_hndl_per_res_out_on_other_sc(io);
12174		ctl_free_io(io);
12175		break;
12176	case CTL_MSG_BAD_JUJU:
12177		ctl_done(io);
12178		break;
12179	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12180		ctl_datamove_remote(io);
12181		break;
12182	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12183		io->scsiio.be_move_done(io);
12184		break;
12185	case CTL_MSG_FAILOVER:
12186		ctl_failover_lun(io);
12187		ctl_free_io(io);
12188		break;
12189	default:
12190		printf("%s: Invalid message type %d\n",
12191		       __func__, io->io_hdr.msg_type);
12192		ctl_free_io(io);
12193		break;
12194	}
12195
12196}
12197
12198
12199/*
12200 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12201 * there is no match.
12202 */
12203static ctl_lun_error_pattern
12204ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12205{
12206	const struct ctl_cmd_entry *entry;
12207	ctl_lun_error_pattern filtered_pattern, pattern;
12208
12209	pattern = desc->error_pattern;
12210
12211	/*
12212	 * XXX KDM we need more data passed into this function to match a
12213	 * custom pattern, and we actually need to implement custom pattern
12214	 * matching.
12215	 */
12216	if (pattern & CTL_LUN_PAT_CMD)
12217		return (CTL_LUN_PAT_CMD);
12218
12219	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12220		return (CTL_LUN_PAT_ANY);
12221
12222	entry = ctl_get_cmd_entry(ctsio, NULL);
12223
12224	filtered_pattern = entry->pattern & pattern;
12225
12226	/*
12227	 * If the user requested specific flags in the pattern (e.g.
12228	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12229	 * flags.
12230	 *
12231	 * If the user did not specify any flags, it doesn't matter whether
12232	 * or not the command supports the flags.
12233	 */
12234	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12235	     (pattern & ~CTL_LUN_PAT_MASK))
12236		return (CTL_LUN_PAT_NONE);
12237
12238	/*
12239	 * If the user asked for a range check, see if the requested LBA
12240	 * range overlaps with this command's LBA range.
12241	 */
12242	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12243		uint64_t lba1;
12244		uint64_t len1;
12245		ctl_action action;
12246		int retval;
12247
12248		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12249		if (retval != 0)
12250			return (CTL_LUN_PAT_NONE);
12251
12252		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12253					      desc->lba_range.len, FALSE);
12254		/*
12255		 * A "pass" means that the LBA ranges don't overlap, so
12256		 * this doesn't match the user's range criteria.
12257		 */
12258		if (action == CTL_ACTION_PASS)
12259			return (CTL_LUN_PAT_NONE);
12260	}
12261
12262	return (filtered_pattern);
12263}
12264
12265static void
12266ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12267{
12268	struct ctl_error_desc *desc, *desc2;
12269
12270	mtx_assert(&lun->lun_lock, MA_OWNED);
12271
12272	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12273		ctl_lun_error_pattern pattern;
12274		/*
12275		 * Check to see whether this particular command matches
12276		 * the pattern in the descriptor.
12277		 */
12278		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12279		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12280			continue;
12281
12282		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12283		case CTL_LUN_INJ_ABORTED:
12284			ctl_set_aborted(&io->scsiio);
12285			break;
12286		case CTL_LUN_INJ_MEDIUM_ERR:
12287			ctl_set_medium_error(&io->scsiio,
12288			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12289			     CTL_FLAG_DATA_OUT);
12290			break;
12291		case CTL_LUN_INJ_UA:
12292			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12293			 * OCCURRED */
12294			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12295			break;
12296		case CTL_LUN_INJ_CUSTOM:
12297			/*
12298			 * We're assuming the user knows what he is doing.
12299			 * Just copy the sense information without doing
12300			 * checks.
12301			 */
12302			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12303			      MIN(sizeof(desc->custom_sense),
12304				  sizeof(io->scsiio.sense_data)));
12305			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12306			io->scsiio.sense_len = SSD_FULL_SIZE;
12307			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12308			break;
12309		case CTL_LUN_INJ_NONE:
12310		default:
12311			/*
12312			 * If this is an error injection type we don't know
12313			 * about, clear the continuous flag (if it is set)
12314			 * so it will get deleted below.
12315			 */
12316			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12317			break;
12318		}
12319		/*
12320		 * By default, each error injection action is a one-shot
12321		 */
12322		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12323			continue;
12324
12325		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12326
12327		free(desc, M_CTL);
12328	}
12329}
12330
12331#ifdef CTL_IO_DELAY
12332static void
12333ctl_datamove_timer_wakeup(void *arg)
12334{
12335	union ctl_io *io;
12336
12337	io = (union ctl_io *)arg;
12338
12339	ctl_datamove(io);
12340}
12341#endif /* CTL_IO_DELAY */
12342
12343void
12344ctl_datamove(union ctl_io *io)
12345{
12346	void (*fe_datamove)(union ctl_io *io);
12347
12348	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12349
12350	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12351
12352	/* No data transferred yet.  Frontend must update this when done. */
12353	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12354
12355#ifdef CTL_TIME_IO
12356	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12357		char str[256];
12358		char path_str[64];
12359		struct sbuf sb;
12360
12361		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12362		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12363
12364		sbuf_cat(&sb, path_str);
12365		switch (io->io_hdr.io_type) {
12366		case CTL_IO_SCSI:
12367			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12368			sbuf_printf(&sb, "\n");
12369			sbuf_cat(&sb, path_str);
12370			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12371				    io->scsiio.tag_num, io->scsiio.tag_type);
12372			break;
12373		case CTL_IO_TASK:
12374			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12375				    "Tag Type: %d\n", io->taskio.task_action,
12376				    io->taskio.tag_num, io->taskio.tag_type);
12377			break;
12378		default:
12379			panic("%s: Invalid CTL I/O type %d\n",
12380			    __func__, io->io_hdr.io_type);
12381		}
12382		sbuf_cat(&sb, path_str);
12383		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12384			    (intmax_t)time_uptime - io->io_hdr.start_time);
12385		sbuf_finish(&sb);
12386		printf("%s", sbuf_data(&sb));
12387	}
12388#endif /* CTL_TIME_IO */
12389
12390#ifdef CTL_IO_DELAY
12391	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12392		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12393	} else {
12394		struct ctl_lun *lun;
12395
12396		lun = CTL_LUN(io);
12397		if ((lun != NULL)
12398		 && (lun->delay_info.datamove_delay > 0)) {
12399
12400			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12401			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12402			callout_reset(&io->io_hdr.delay_callout,
12403				      lun->delay_info.datamove_delay * hz,
12404				      ctl_datamove_timer_wakeup, io);
12405			if (lun->delay_info.datamove_type ==
12406			    CTL_DELAY_TYPE_ONESHOT)
12407				lun->delay_info.datamove_delay = 0;
12408			return;
12409		}
12410	}
12411#endif
12412
12413	/*
12414	 * This command has been aborted.  Set the port status, so we fail
12415	 * the data move.
12416	 */
12417	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12418		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12419		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12420		       io->io_hdr.nexus.targ_port,
12421		       io->io_hdr.nexus.targ_lun);
12422		io->io_hdr.port_status = 31337;
12423		/*
12424		 * Note that the backend, in this case, will get the
12425		 * callback in its context.  In other cases it may get
12426		 * called in the frontend's interrupt thread context.
12427		 */
12428		io->scsiio.be_move_done(io);
12429		return;
12430	}
12431
12432	/* Don't confuse frontend with zero length data move. */
12433	if (io->scsiio.kern_data_len == 0) {
12434		io->scsiio.be_move_done(io);
12435		return;
12436	}
12437
12438	fe_datamove = CTL_PORT(io)->fe_datamove;
12439	fe_datamove(io);
12440}
12441
12442static void
12443ctl_send_datamove_done(union ctl_io *io, int have_lock)
12444{
12445	union ctl_ha_msg msg;
12446#ifdef CTL_TIME_IO
12447	struct bintime cur_bt;
12448#endif
12449
12450	memset(&msg, 0, sizeof(msg));
12451	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12452	msg.hdr.original_sc = io;
12453	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12454	msg.hdr.nexus = io->io_hdr.nexus;
12455	msg.hdr.status = io->io_hdr.status;
12456	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12457	msg.scsi.tag_num = io->scsiio.tag_num;
12458	msg.scsi.tag_type = io->scsiio.tag_type;
12459	msg.scsi.scsi_status = io->scsiio.scsi_status;
12460	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12461	       io->scsiio.sense_len);
12462	msg.scsi.sense_len = io->scsiio.sense_len;
12463	msg.scsi.port_status = io->io_hdr.port_status;
12464	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12465	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12466		ctl_failover_io(io, /*have_lock*/ have_lock);
12467		return;
12468	}
12469	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12470	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12471	    msg.scsi.sense_len, M_WAITOK);
12472
12473#ifdef CTL_TIME_IO
12474	getbinuptime(&cur_bt);
12475	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12476	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12477#endif
12478	io->io_hdr.num_dmas++;
12479}
12480
12481/*
12482 * The DMA to the remote side is done, now we need to tell the other side
12483 * we're done so it can continue with its data movement.
12484 */
12485static void
12486ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12487{
12488	union ctl_io *io;
12489	uint32_t i;
12490
12491	io = rq->context;
12492
12493	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12494		printf("%s: ISC DMA write failed with error %d", __func__,
12495		       rq->ret);
12496		ctl_set_internal_failure(&io->scsiio,
12497					 /*sks_valid*/ 1,
12498					 /*retry_count*/ rq->ret);
12499	}
12500
12501	ctl_dt_req_free(rq);
12502
12503	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12504		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12505	free(io->io_hdr.remote_sglist, M_CTL);
12506	io->io_hdr.remote_sglist = NULL;
12507	io->io_hdr.local_sglist = NULL;
12508
12509	/*
12510	 * The data is in local and remote memory, so now we need to send
12511	 * status (good or back) back to the other side.
12512	 */
12513	ctl_send_datamove_done(io, /*have_lock*/ 0);
12514}
12515
12516/*
12517 * We've moved the data from the host/controller into local memory.  Now we
12518 * need to push it over to the remote controller's memory.
12519 */
12520static int
12521ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12522{
12523	int retval;
12524
12525	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12526					  ctl_datamove_remote_write_cb);
12527	return (retval);
12528}
12529
12530static void
12531ctl_datamove_remote_write(union ctl_io *io)
12532{
12533	int retval;
12534	void (*fe_datamove)(union ctl_io *io);
12535
12536	/*
12537	 * - Get the data from the host/HBA into local memory.
12538	 * - DMA memory from the local controller to the remote controller.
12539	 * - Send status back to the remote controller.
12540	 */
12541
12542	retval = ctl_datamove_remote_sgl_setup(io);
12543	if (retval != 0)
12544		return;
12545
12546	/* Switch the pointer over so the FETD knows what to do */
12547	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12548
12549	/*
12550	 * Use a custom move done callback, since we need to send completion
12551	 * back to the other controller, not to the backend on this side.
12552	 */
12553	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12554
12555	fe_datamove = CTL_PORT(io)->fe_datamove;
12556	fe_datamove(io);
12557}
12558
12559static int
12560ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12561{
12562#if 0
12563	char str[256];
12564	char path_str[64];
12565	struct sbuf sb;
12566#endif
12567	uint32_t i;
12568
12569	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12570		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12571	free(io->io_hdr.remote_sglist, M_CTL);
12572	io->io_hdr.remote_sglist = NULL;
12573	io->io_hdr.local_sglist = NULL;
12574
12575#if 0
12576	scsi_path_string(io, path_str, sizeof(path_str));
12577	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12578	sbuf_cat(&sb, path_str);
12579	scsi_command_string(&io->scsiio, NULL, &sb);
12580	sbuf_printf(&sb, "\n");
12581	sbuf_cat(&sb, path_str);
12582	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12583		    io->scsiio.tag_num, io->scsiio.tag_type);
12584	sbuf_cat(&sb, path_str);
12585	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12586		    io->io_hdr.flags, io->io_hdr.status);
12587	sbuf_finish(&sb);
12588	printk("%s", sbuf_data(&sb));
12589#endif
12590
12591
12592	/*
12593	 * The read is done, now we need to send status (good or bad) back
12594	 * to the other side.
12595	 */
12596	ctl_send_datamove_done(io, /*have_lock*/ 0);
12597
12598	return (0);
12599}
12600
12601static void
12602ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12603{
12604	union ctl_io *io;
12605	void (*fe_datamove)(union ctl_io *io);
12606
12607	io = rq->context;
12608
12609	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12610		printf("%s: ISC DMA read failed with error %d\n", __func__,
12611		       rq->ret);
12612		ctl_set_internal_failure(&io->scsiio,
12613					 /*sks_valid*/ 1,
12614					 /*retry_count*/ rq->ret);
12615	}
12616
12617	ctl_dt_req_free(rq);
12618
12619	/* Switch the pointer over so the FETD knows what to do */
12620	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12621
12622	/*
12623	 * Use a custom move done callback, since we need to send completion
12624	 * back to the other controller, not to the backend on this side.
12625	 */
12626	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12627
12628	/* XXX KDM add checks like the ones in ctl_datamove? */
12629
12630	fe_datamove = CTL_PORT(io)->fe_datamove;
12631	fe_datamove(io);
12632}
12633
12634static int
12635ctl_datamove_remote_sgl_setup(union ctl_io *io)
12636{
12637	struct ctl_sg_entry *local_sglist;
12638	uint32_t len_to_go;
12639	int retval;
12640	int i;
12641
12642	retval = 0;
12643	local_sglist = io->io_hdr.local_sglist;
12644	len_to_go = io->scsiio.kern_data_len;
12645
12646	/*
12647	 * The difficult thing here is that the size of the various
12648	 * S/G segments may be different than the size from the
12649	 * remote controller.  That'll make it harder when DMAing
12650	 * the data back to the other side.
12651	 */
12652	for (i = 0; len_to_go > 0; i++) {
12653		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12654		local_sglist[i].addr =
12655		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12656
12657		len_to_go -= local_sglist[i].len;
12658	}
12659	/*
12660	 * Reset the number of S/G entries accordingly.  The original
12661	 * number of S/G entries is available in rem_sg_entries.
12662	 */
12663	io->scsiio.kern_sg_entries = i;
12664
12665#if 0
12666	printf("%s: kern_sg_entries = %d\n", __func__,
12667	       io->scsiio.kern_sg_entries);
12668	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12669		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12670		       local_sglist[i].addr, local_sglist[i].len);
12671#endif
12672
12673	return (retval);
12674}
12675
12676static int
12677ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12678			 ctl_ha_dt_cb callback)
12679{
12680	struct ctl_ha_dt_req *rq;
12681	struct ctl_sg_entry *remote_sglist, *local_sglist;
12682	uint32_t local_used, remote_used, total_used;
12683	int i, j, isc_ret;
12684
12685	rq = ctl_dt_req_alloc();
12686
12687	/*
12688	 * If we failed to allocate the request, and if the DMA didn't fail
12689	 * anyway, set busy status.  This is just a resource allocation
12690	 * failure.
12691	 */
12692	if ((rq == NULL)
12693	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12694	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12695		ctl_set_busy(&io->scsiio);
12696
12697	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12698	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12699
12700		if (rq != NULL)
12701			ctl_dt_req_free(rq);
12702
12703		/*
12704		 * The data move failed.  We need to return status back
12705		 * to the other controller.  No point in trying to DMA
12706		 * data to the remote controller.
12707		 */
12708
12709		ctl_send_datamove_done(io, /*have_lock*/ 0);
12710
12711		return (1);
12712	}
12713
12714	local_sglist = io->io_hdr.local_sglist;
12715	remote_sglist = io->io_hdr.remote_sglist;
12716	local_used = 0;
12717	remote_used = 0;
12718	total_used = 0;
12719
12720	/*
12721	 * Pull/push the data over the wire from/to the other controller.
12722	 * This takes into account the possibility that the local and
12723	 * remote sglists may not be identical in terms of the size of
12724	 * the elements and the number of elements.
12725	 *
12726	 * One fundamental assumption here is that the length allocated for
12727	 * both the local and remote sglists is identical.  Otherwise, we've
12728	 * essentially got a coding error of some sort.
12729	 */
12730	isc_ret = CTL_HA_STATUS_SUCCESS;
12731	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12732		uint32_t cur_len;
12733		uint8_t *tmp_ptr;
12734
12735		rq->command = command;
12736		rq->context = io;
12737
12738		/*
12739		 * Both pointers should be aligned.  But it is possible
12740		 * that the allocation length is not.  They should both
12741		 * also have enough slack left over at the end, though,
12742		 * to round up to the next 8 byte boundary.
12743		 */
12744		cur_len = MIN(local_sglist[i].len - local_used,
12745			      remote_sglist[j].len - remote_used);
12746		rq->size = cur_len;
12747
12748		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12749		tmp_ptr += local_used;
12750
12751#if 0
12752		/* Use physical addresses when talking to ISC hardware */
12753		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12754			/* XXX KDM use busdma */
12755			rq->local = vtophys(tmp_ptr);
12756		} else
12757			rq->local = tmp_ptr;
12758#else
12759		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12760		    ("HA does not support BUS_ADDR"));
12761		rq->local = tmp_ptr;
12762#endif
12763
12764		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12765		tmp_ptr += remote_used;
12766		rq->remote = tmp_ptr;
12767
12768		rq->callback = NULL;
12769
12770		local_used += cur_len;
12771		if (local_used >= local_sglist[i].len) {
12772			i++;
12773			local_used = 0;
12774		}
12775
12776		remote_used += cur_len;
12777		if (remote_used >= remote_sglist[j].len) {
12778			j++;
12779			remote_used = 0;
12780		}
12781		total_used += cur_len;
12782
12783		if (total_used >= io->scsiio.kern_data_len)
12784			rq->callback = callback;
12785
12786#if 0
12787		printf("%s: %s: local %p remote %p size %d\n", __func__,
12788		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12789		       rq->local, rq->remote, rq->size);
12790#endif
12791
12792		isc_ret = ctl_dt_single(rq);
12793		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12794			break;
12795	}
12796	if (isc_ret != CTL_HA_STATUS_WAIT) {
12797		rq->ret = isc_ret;
12798		callback(rq);
12799	}
12800
12801	return (0);
12802}
12803
12804static void
12805ctl_datamove_remote_read(union ctl_io *io)
12806{
12807	int retval;
12808	uint32_t i;
12809
12810	/*
12811	 * This will send an error to the other controller in the case of a
12812	 * failure.
12813	 */
12814	retval = ctl_datamove_remote_sgl_setup(io);
12815	if (retval != 0)
12816		return;
12817
12818	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12819					  ctl_datamove_remote_read_cb);
12820	if (retval != 0) {
12821		/*
12822		 * Make sure we free memory if there was an error..  The
12823		 * ctl_datamove_remote_xfer() function will send the
12824		 * datamove done message, or call the callback with an
12825		 * error if there is a problem.
12826		 */
12827		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12828			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12829		free(io->io_hdr.remote_sglist, M_CTL);
12830		io->io_hdr.remote_sglist = NULL;
12831		io->io_hdr.local_sglist = NULL;
12832	}
12833}
12834
12835/*
12836 * Process a datamove request from the other controller.  This is used for
12837 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12838 * first.  Once that is complete, the data gets DMAed into the remote
12839 * controller's memory.  For reads, we DMA from the remote controller's
12840 * memory into our memory first, and then move it out to the FETD.
12841 */
12842static void
12843ctl_datamove_remote(union ctl_io *io)
12844{
12845
12846	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12847
12848	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12849		ctl_failover_io(io, /*have_lock*/ 0);
12850		return;
12851	}
12852
12853	/*
12854	 * Note that we look for an aborted I/O here, but don't do some of
12855	 * the other checks that ctl_datamove() normally does.
12856	 * We don't need to run the datamove delay code, since that should
12857	 * have been done if need be on the other controller.
12858	 */
12859	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12860		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12861		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12862		       io->io_hdr.nexus.targ_port,
12863		       io->io_hdr.nexus.targ_lun);
12864		io->io_hdr.port_status = 31338;
12865		ctl_send_datamove_done(io, /*have_lock*/ 0);
12866		return;
12867	}
12868
12869	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12870		ctl_datamove_remote_write(io);
12871	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12872		ctl_datamove_remote_read(io);
12873	else {
12874		io->io_hdr.port_status = 31339;
12875		ctl_send_datamove_done(io, /*have_lock*/ 0);
12876	}
12877}
12878
12879static void
12880ctl_process_done(union ctl_io *io)
12881{
12882	struct ctl_softc *softc = CTL_SOFTC(io);
12883	struct ctl_port *port = CTL_PORT(io);
12884	struct ctl_lun *lun = CTL_LUN(io);
12885	void (*fe_done)(union ctl_io *io);
12886	union ctl_ha_msg msg;
12887
12888	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12889	fe_done = port->fe_done;
12890
12891#ifdef CTL_TIME_IO
12892	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12893		char str[256];
12894		char path_str[64];
12895		struct sbuf sb;
12896
12897		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12898		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12899
12900		sbuf_cat(&sb, path_str);
12901		switch (io->io_hdr.io_type) {
12902		case CTL_IO_SCSI:
12903			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12904			sbuf_printf(&sb, "\n");
12905			sbuf_cat(&sb, path_str);
12906			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12907				    io->scsiio.tag_num, io->scsiio.tag_type);
12908			break;
12909		case CTL_IO_TASK:
12910			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12911				    "Tag Type: %d\n", io->taskio.task_action,
12912				    io->taskio.tag_num, io->taskio.tag_type);
12913			break;
12914		default:
12915			panic("%s: Invalid CTL I/O type %d\n",
12916			    __func__, io->io_hdr.io_type);
12917		}
12918		sbuf_cat(&sb, path_str);
12919		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12920			    (intmax_t)time_uptime - io->io_hdr.start_time);
12921		sbuf_finish(&sb);
12922		printf("%s", sbuf_data(&sb));
12923	}
12924#endif /* CTL_TIME_IO */
12925
12926	switch (io->io_hdr.io_type) {
12927	case CTL_IO_SCSI:
12928		break;
12929	case CTL_IO_TASK:
12930		if (ctl_debug & CTL_DEBUG_INFO)
12931			ctl_io_error_print(io, NULL);
12932		fe_done(io);
12933		return;
12934	default:
12935		panic("%s: Invalid CTL I/O type %d\n",
12936		    __func__, io->io_hdr.io_type);
12937	}
12938
12939	if (lun == NULL) {
12940		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12941				 io->io_hdr.nexus.targ_mapped_lun));
12942		goto bailout;
12943	}
12944
12945	mtx_lock(&lun->lun_lock);
12946
12947	/*
12948	 * Check to see if we have any informational exception and status
12949	 * of this command can be modified to report it in form of either
12950	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
12951	 */
12952	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
12953	    io->io_hdr.status == CTL_SUCCESS &&
12954	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
12955		uint8_t mrie = lun->MODE_IE.mrie;
12956		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
12957		    (lun->MODE_VER.byte3 & SMS_VER_PER));
12958		if (((mrie == SIEP_MRIE_REC_COND && per) ||
12959		     mrie == SIEP_MRIE_REC_UNCOND ||
12960		     mrie == SIEP_MRIE_NO_SENSE) &&
12961		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
12962		     CTL_CMD_FLAG_NO_SENSE) == 0) {
12963			ctl_set_sense(&io->scsiio,
12964			      /*current_error*/ 1,
12965			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
12966			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
12967			      /*asc*/ lun->ie_asc,
12968			      /*ascq*/ lun->ie_ascq,
12969			      SSD_ELEM_NONE);
12970			lun->ie_reported = 1;
12971		}
12972	} else if (lun->ie_reported < 0)
12973		lun->ie_reported = 0;
12974
12975	/*
12976	 * Check to see if we have any errors to inject here.  We only
12977	 * inject errors for commands that don't already have errors set.
12978	 */
12979	if (!STAILQ_EMPTY(&lun->error_list) &&
12980	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12981	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12982		ctl_inject_error(lun, io);
12983
12984	/*
12985	 * XXX KDM how do we treat commands that aren't completed
12986	 * successfully?
12987	 *
12988	 * XXX KDM should we also track I/O latency?
12989	 */
12990	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12991	    io->io_hdr.io_type == CTL_IO_SCSI) {
12992		int type;
12993#ifdef CTL_TIME_IO
12994		struct bintime bt;
12995
12996		getbinuptime(&bt);
12997		bintime_sub(&bt, &io->io_hdr.start_bt);
12998#endif
12999		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13000		    CTL_FLAG_DATA_IN)
13001			type = CTL_STATS_READ;
13002		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13003		    CTL_FLAG_DATA_OUT)
13004			type = CTL_STATS_WRITE;
13005		else
13006			type = CTL_STATS_NO_IO;
13007
13008#ifdef CTL_LEGACY_STATS
13009		uint32_t targ_port = port->targ_port;
13010		lun->legacy_stats.ports[targ_port].bytes[type] +=
13011		    io->scsiio.kern_total_len;
13012		lun->legacy_stats.ports[targ_port].operations[type] ++;
13013		lun->legacy_stats.ports[targ_port].num_dmas[type] +=
13014		    io->io_hdr.num_dmas;
13015#ifdef CTL_TIME_IO
13016		bintime_add(&lun->legacy_stats.ports[targ_port].dma_time[type],
13017		   &io->io_hdr.dma_bt);
13018		bintime_add(&lun->legacy_stats.ports[targ_port].time[type],
13019		    &bt);
13020#endif
13021#endif /* CTL_LEGACY_STATS */
13022
13023		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13024		lun->stats.operations[type] ++;
13025		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13026#ifdef CTL_TIME_IO
13027		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13028		bintime_add(&lun->stats.time[type], &bt);
13029#endif
13030
13031		mtx_lock(&port->port_lock);
13032		port->stats.bytes[type] += io->scsiio.kern_total_len;
13033		port->stats.operations[type] ++;
13034		port->stats.dmas[type] += io->io_hdr.num_dmas;
13035#ifdef CTL_TIME_IO
13036		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13037		bintime_add(&port->stats.time[type], &bt);
13038#endif
13039		mtx_unlock(&port->port_lock);
13040	}
13041
13042	/*
13043	 * Remove this from the OOA queue.
13044	 */
13045	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13046#ifdef CTL_TIME_IO
13047	if (TAILQ_EMPTY(&lun->ooa_queue))
13048		lun->last_busy = getsbinuptime();
13049#endif
13050
13051	/*
13052	 * Run through the blocked queue on this LUN and see if anything
13053	 * has become unblocked, now that this transaction is done.
13054	 */
13055	ctl_check_blocked(lun);
13056
13057	/*
13058	 * If the LUN has been invalidated, free it if there is nothing
13059	 * left on its OOA queue.
13060	 */
13061	if ((lun->flags & CTL_LUN_INVALID)
13062	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13063		mtx_unlock(&lun->lun_lock);
13064		ctl_free_lun(lun);
13065	} else
13066		mtx_unlock(&lun->lun_lock);
13067
13068bailout:
13069
13070	/*
13071	 * If this command has been aborted, make sure we set the status
13072	 * properly.  The FETD is responsible for freeing the I/O and doing
13073	 * whatever it needs to do to clean up its state.
13074	 */
13075	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13076		ctl_set_task_aborted(&io->scsiio);
13077
13078	/*
13079	 * If enabled, print command error status.
13080	 */
13081	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13082	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13083		ctl_io_error_print(io, NULL);
13084
13085	/*
13086	 * Tell the FETD or the other shelf controller we're done with this
13087	 * command.  Note that only SCSI commands get to this point.  Task
13088	 * management commands are completed above.
13089	 */
13090	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13091	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13092		memset(&msg, 0, sizeof(msg));
13093		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13094		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13095		msg.hdr.nexus = io->io_hdr.nexus;
13096		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13097		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13098		    M_WAITOK);
13099	}
13100
13101	fe_done(io);
13102}
13103
13104/*
13105 * Front end should call this if it doesn't do autosense.  When the request
13106 * sense comes back in from the initiator, we'll dequeue this and send it.
13107 */
13108int
13109ctl_queue_sense(union ctl_io *io)
13110{
13111	struct ctl_softc *softc = CTL_SOFTC(io);
13112	struct ctl_port *port = CTL_PORT(io);
13113	struct ctl_lun *lun;
13114	struct scsi_sense_data *ps;
13115	uint32_t initidx, p, targ_lun;
13116
13117	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13118
13119	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13120
13121	/*
13122	 * LUN lookup will likely move to the ctl_work_thread() once we
13123	 * have our new queueing infrastructure (that doesn't put things on
13124	 * a per-LUN queue initially).  That is so that we can handle
13125	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13126	 * can't deal with that right now.
13127	 * If we don't have a LUN for this, just toss the sense information.
13128	 */
13129	mtx_lock(&softc->ctl_lock);
13130	if (targ_lun >= CTL_MAX_LUNS ||
13131	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13132		mtx_unlock(&softc->ctl_lock);
13133		goto bailout;
13134	}
13135	mtx_lock(&lun->lun_lock);
13136	mtx_unlock(&softc->ctl_lock);
13137
13138	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13139	p = initidx / CTL_MAX_INIT_PER_PORT;
13140	if (lun->pending_sense[p] == NULL) {
13141		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13142		    M_CTL, M_NOWAIT | M_ZERO);
13143	}
13144	if ((ps = lun->pending_sense[p]) != NULL) {
13145		ps += initidx % CTL_MAX_INIT_PER_PORT;
13146		memset(ps, 0, sizeof(*ps));
13147		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13148	}
13149	mtx_unlock(&lun->lun_lock);
13150
13151bailout:
13152	ctl_free_io(io);
13153	return (CTL_RETVAL_COMPLETE);
13154}
13155
13156/*
13157 * Primary command inlet from frontend ports.  All SCSI and task I/O
13158 * requests must go through this function.
13159 */
13160int
13161ctl_queue(union ctl_io *io)
13162{
13163	struct ctl_port *port = CTL_PORT(io);
13164
13165	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13166
13167#ifdef CTL_TIME_IO
13168	io->io_hdr.start_time = time_uptime;
13169	getbinuptime(&io->io_hdr.start_bt);
13170#endif /* CTL_TIME_IO */
13171
13172	/* Map FE-specific LUN ID into global one. */
13173	io->io_hdr.nexus.targ_mapped_lun =
13174	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13175
13176	switch (io->io_hdr.io_type) {
13177	case CTL_IO_SCSI:
13178	case CTL_IO_TASK:
13179		if (ctl_debug & CTL_DEBUG_CDB)
13180			ctl_io_print(io);
13181		ctl_enqueue_incoming(io);
13182		break;
13183	default:
13184		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13185		return (EINVAL);
13186	}
13187
13188	return (CTL_RETVAL_COMPLETE);
13189}
13190
13191#ifdef CTL_IO_DELAY
13192static void
13193ctl_done_timer_wakeup(void *arg)
13194{
13195	union ctl_io *io;
13196
13197	io = (union ctl_io *)arg;
13198	ctl_done(io);
13199}
13200#endif /* CTL_IO_DELAY */
13201
13202void
13203ctl_serseq_done(union ctl_io *io)
13204{
13205	struct ctl_lun *lun = CTL_LUN(io);;
13206
13207	if (lun->be_lun == NULL ||
13208	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13209		return;
13210	mtx_lock(&lun->lun_lock);
13211	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13212	ctl_check_blocked(lun);
13213	mtx_unlock(&lun->lun_lock);
13214}
13215
13216void
13217ctl_done(union ctl_io *io)
13218{
13219
13220	/*
13221	 * Enable this to catch duplicate completion issues.
13222	 */
13223#if 0
13224	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13225		printf("%s: type %d msg %d cdb %x iptl: "
13226		       "%u:%u:%u tag 0x%04x "
13227		       "flag %#x status %x\n",
13228			__func__,
13229			io->io_hdr.io_type,
13230			io->io_hdr.msg_type,
13231			io->scsiio.cdb[0],
13232			io->io_hdr.nexus.initid,
13233			io->io_hdr.nexus.targ_port,
13234			io->io_hdr.nexus.targ_lun,
13235			(io->io_hdr.io_type ==
13236			CTL_IO_TASK) ?
13237			io->taskio.tag_num :
13238			io->scsiio.tag_num,
13239		        io->io_hdr.flags,
13240			io->io_hdr.status);
13241	} else
13242		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13243#endif
13244
13245	/*
13246	 * This is an internal copy of an I/O, and should not go through
13247	 * the normal done processing logic.
13248	 */
13249	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13250		return;
13251
13252#ifdef CTL_IO_DELAY
13253	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13254		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13255	} else {
13256		struct ctl_lun *lun = CTL_LUN(io);
13257
13258		if ((lun != NULL)
13259		 && (lun->delay_info.done_delay > 0)) {
13260
13261			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13262			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13263			callout_reset(&io->io_hdr.delay_callout,
13264				      lun->delay_info.done_delay * hz,
13265				      ctl_done_timer_wakeup, io);
13266			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13267				lun->delay_info.done_delay = 0;
13268			return;
13269		}
13270	}
13271#endif /* CTL_IO_DELAY */
13272
13273	ctl_enqueue_done(io);
13274}
13275
13276static void
13277ctl_work_thread(void *arg)
13278{
13279	struct ctl_thread *thr = (struct ctl_thread *)arg;
13280	struct ctl_softc *softc = thr->ctl_softc;
13281	union ctl_io *io;
13282	int retval;
13283
13284	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13285
13286	while (!softc->shutdown) {
13287		/*
13288		 * We handle the queues in this order:
13289		 * - ISC
13290		 * - done queue (to free up resources, unblock other commands)
13291		 * - RtR queue
13292		 * - incoming queue
13293		 *
13294		 * If those queues are empty, we break out of the loop and
13295		 * go to sleep.
13296		 */
13297		mtx_lock(&thr->queue_lock);
13298		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13299		if (io != NULL) {
13300			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13301			mtx_unlock(&thr->queue_lock);
13302			ctl_handle_isc(io);
13303			continue;
13304		}
13305		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13306		if (io != NULL) {
13307			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13308			/* clear any blocked commands, call fe_done */
13309			mtx_unlock(&thr->queue_lock);
13310			ctl_process_done(io);
13311			continue;
13312		}
13313		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13314		if (io != NULL) {
13315			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13316			mtx_unlock(&thr->queue_lock);
13317			if (io->io_hdr.io_type == CTL_IO_TASK)
13318				ctl_run_task(io);
13319			else
13320				ctl_scsiio_precheck(softc, &io->scsiio);
13321			continue;
13322		}
13323		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13324		if (io != NULL) {
13325			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13326			mtx_unlock(&thr->queue_lock);
13327			retval = ctl_scsiio(&io->scsiio);
13328			if (retval != CTL_RETVAL_COMPLETE)
13329				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13330			continue;
13331		}
13332
13333		/* Sleep until we have something to do. */
13334		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13335	}
13336	thr->thread = NULL;
13337	kthread_exit();
13338}
13339
13340static void
13341ctl_lun_thread(void *arg)
13342{
13343	struct ctl_softc *softc = (struct ctl_softc *)arg;
13344	struct ctl_be_lun *be_lun;
13345
13346	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13347
13348	while (!softc->shutdown) {
13349		mtx_lock(&softc->ctl_lock);
13350		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13351		if (be_lun != NULL) {
13352			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13353			mtx_unlock(&softc->ctl_lock);
13354			ctl_create_lun(be_lun);
13355			continue;
13356		}
13357
13358		/* Sleep until we have something to do. */
13359		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13360		    PDROP | PRIBIO, "-", 0);
13361	}
13362	softc->lun_thread = NULL;
13363	kthread_exit();
13364}
13365
13366static void
13367ctl_thresh_thread(void *arg)
13368{
13369	struct ctl_softc *softc = (struct ctl_softc *)arg;
13370	struct ctl_lun *lun;
13371	struct ctl_logical_block_provisioning_page *page;
13372	const char *attr;
13373	union ctl_ha_msg msg;
13374	uint64_t thres, val;
13375	int i, e, set;
13376
13377	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13378
13379	while (!softc->shutdown) {
13380		mtx_lock(&softc->ctl_lock);
13381		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13382			if ((lun->flags & CTL_LUN_DISABLED) ||
13383			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13384			    lun->backend->lun_attr == NULL)
13385				continue;
13386			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13387			    softc->ha_mode == CTL_HA_MODE_XFER)
13388				continue;
13389			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13390				continue;
13391			e = 0;
13392			page = &lun->MODE_LBP;
13393			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13394				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13395					continue;
13396				thres = scsi_4btoul(page->descr[i].count);
13397				thres <<= CTL_LBP_EXPONENT;
13398				switch (page->descr[i].resource) {
13399				case 0x01:
13400					attr = "blocksavail";
13401					break;
13402				case 0x02:
13403					attr = "blocksused";
13404					break;
13405				case 0xf1:
13406					attr = "poolblocksavail";
13407					break;
13408				case 0xf2:
13409					attr = "poolblocksused";
13410					break;
13411				default:
13412					continue;
13413				}
13414				mtx_unlock(&softc->ctl_lock); // XXX
13415				val = lun->backend->lun_attr(
13416				    lun->be_lun->be_lun, attr);
13417				mtx_lock(&softc->ctl_lock);
13418				if (val == UINT64_MAX)
13419					continue;
13420				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13421				    == SLBPPD_ARMING_INC)
13422					e = (val >= thres);
13423				else
13424					e = (val <= thres);
13425				if (e)
13426					break;
13427			}
13428			mtx_lock(&lun->lun_lock);
13429			if (e) {
13430				scsi_u64to8b((uint8_t *)&page->descr[i] -
13431				    (uint8_t *)page, lun->ua_tpt_info);
13432				if (lun->lasttpt == 0 ||
13433				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13434					lun->lasttpt = time_uptime;
13435					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13436					set = 1;
13437				} else
13438					set = 0;
13439			} else {
13440				lun->lasttpt = 0;
13441				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13442				set = -1;
13443			}
13444			mtx_unlock(&lun->lun_lock);
13445			if (set != 0 &&
13446			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13447				/* Send msg to other side. */
13448				bzero(&msg.ua, sizeof(msg.ua));
13449				msg.hdr.msg_type = CTL_MSG_UA;
13450				msg.hdr.nexus.initid = -1;
13451				msg.hdr.nexus.targ_port = -1;
13452				msg.hdr.nexus.targ_lun = lun->lun;
13453				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13454				msg.ua.ua_all = 1;
13455				msg.ua.ua_set = (set > 0);
13456				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13457				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13458				mtx_unlock(&softc->ctl_lock); // XXX
13459				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13460				    sizeof(msg.ua), M_WAITOK);
13461				mtx_lock(&softc->ctl_lock);
13462			}
13463		}
13464		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13465		    PDROP | PRIBIO, "-", CTL_LBP_PERIOD * hz);
13466	}
13467	softc->thresh_thread = NULL;
13468	kthread_exit();
13469}
13470
13471static void
13472ctl_enqueue_incoming(union ctl_io *io)
13473{
13474	struct ctl_softc *softc = CTL_SOFTC(io);
13475	struct ctl_thread *thr;
13476	u_int idx;
13477
13478	idx = (io->io_hdr.nexus.targ_port * 127 +
13479	       io->io_hdr.nexus.initid) % worker_threads;
13480	thr = &softc->threads[idx];
13481	mtx_lock(&thr->queue_lock);
13482	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13483	mtx_unlock(&thr->queue_lock);
13484	wakeup(thr);
13485}
13486
13487static void
13488ctl_enqueue_rtr(union ctl_io *io)
13489{
13490	struct ctl_softc *softc = CTL_SOFTC(io);
13491	struct ctl_thread *thr;
13492
13493	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13494	mtx_lock(&thr->queue_lock);
13495	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13496	mtx_unlock(&thr->queue_lock);
13497	wakeup(thr);
13498}
13499
13500static void
13501ctl_enqueue_done(union ctl_io *io)
13502{
13503	struct ctl_softc *softc = CTL_SOFTC(io);
13504	struct ctl_thread *thr;
13505
13506	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13507	mtx_lock(&thr->queue_lock);
13508	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13509	mtx_unlock(&thr->queue_lock);
13510	wakeup(thr);
13511}
13512
13513static void
13514ctl_enqueue_isc(union ctl_io *io)
13515{
13516	struct ctl_softc *softc = CTL_SOFTC(io);
13517	struct ctl_thread *thr;
13518
13519	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13520	mtx_lock(&thr->queue_lock);
13521	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13522	mtx_unlock(&thr->queue_lock);
13523	wakeup(thr);
13524}
13525
13526/*
13527 *  vim: ts=8
13528 */
13529