ctl.c revision 275894
155505Sshin/*-
255505Sshin * Copyright (c) 2003-2009 Silicon Graphics International Corp.
355505Sshin * Copyright (c) 2012 The FreeBSD Foundation
455505Sshin * All rights reserved.
555505Sshin *
655505Sshin * Portions of this software were developed by Edward Tomasz Napierala
755505Sshin * under sponsorship from the FreeBSD Foundation.
855505Sshin *
955505Sshin * Redistribution and use in source and binary forms, with or without
1055505Sshin * modification, are permitted provided that the following conditions
1155505Sshin * are met:
1255505Sshin * 1. Redistributions of source code must retain the above copyright
1355505Sshin *    notice, this list of conditions, and the following disclaimer,
1455505Sshin *    without modification.
1555505Sshin * 2. Redistributions in binary form must reproduce at minimum a disclaimer
1655505Sshin *    substantially similar to the "NO WARRANTY" disclaimer below
1755505Sshin *    ("Disclaimer") and any redistribution must be conditioned upon
1855505Sshin *    including a substantially similar Disclaimer requirement for further
1955505Sshin *    binary redistribution.
2055505Sshin *
2155505Sshin * NO WARRANTY
2255505Sshin * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2355505Sshin * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2455505Sshin * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
2555505Sshin * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2655505Sshin * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27122107Sume * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2855505Sshin * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2955505Sshin * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30156837Sru * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31156837Sru * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32156813Sru * POSSIBILITY OF SUCH DAMAGES.
33156813Sru *
3455505Sshin * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35195767Skensmith */
3669640Sobrien/*
3759266Ssteve * CAM Target Layer, a SCSI device emulation subsystem.
38156813Sru *
3959266Ssteve * Author: Ken Merry <ken@FreeBSD.org>
4059266Ssteve */
4155505Sshin
42171135Sgnn#define _CTL_C
4362583Sitojun
4455505Sshin#include <sys/cdefs.h>
4555505Sshin__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 275894 2014-12-18 08:45:28Z mav $");
4662583Sitojun
4755505Sshin#include <sys/param.h>
4858906Sshin#include <sys/systm.h>
4958906Sshin#include <sys/ctype.h>
5055505Sshin#include <sys/kernel.h>
51201381Sed#include <sys/types.h>
52201381Sed#include <sys/kthread.h>
5374870Sru#include <sys/bio.h>
5455505Sshin#include <sys/fcntl.h>
5555505Sshin#include <sys/lock.h>
5655505Sshin#include <sys/module.h>
5755505Sshin#include <sys/mutex.h>
5855505Sshin#include <sys/condvar.h>
5955505Sshin#include <sys/malloc.h>
6055505Sshin#include <sys/conf.h>
61#include <sys/ioccom.h>
62#include <sys/queue.h>
63#include <sys/sbuf.h>
64#include <sys/smp.h>
65#include <sys/endian.h>
66#include <sys/sysctl.h>
67#include <vm/uma.h>
68
69#include <cam/cam.h>
70#include <cam/scsi/scsi_all.h>
71#include <cam/scsi/scsi_da.h>
72#include <cam/ctl/ctl_io.h>
73#include <cam/ctl/ctl.h>
74#include <cam/ctl/ctl_frontend.h>
75#include <cam/ctl/ctl_frontend_internal.h>
76#include <cam/ctl/ctl_util.h>
77#include <cam/ctl/ctl_backend.h>
78#include <cam/ctl/ctl_ioctl.h>
79#include <cam/ctl/ctl_ha.h>
80#include <cam/ctl/ctl_private.h>
81#include <cam/ctl/ctl_debug.h>
82#include <cam/ctl/ctl_scsi_all.h>
83#include <cam/ctl/ctl_error.h>
84
85struct ctl_softc *control_softc = NULL;
86
87/*
88 * Size and alignment macros needed for Copan-specific HA hardware.  These
89 * can go away when the HA code is re-written, and uses busdma for any
90 * hardware.
91 */
92#define	CTL_ALIGN_8B(target, source, type)				\
93	if (((uint32_t)source & 0x7) != 0)				\
94		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95	else								\
96		target = (type)source;
97
98#define	CTL_SIZE_8B(target, size)					\
99	if ((size & 0x7) != 0)						\
100		target = size + (0x8 - (size & 0x7));			\
101	else								\
102		target = size;
103
104#define CTL_ALIGN_8B_MARGIN	16
105
106/*
107 * Template mode pages.
108 */
109
110/*
111 * Note that these are default values only.  The actual values will be
112 * filled in when the user does a mode sense.
113 */
114static struct copan_debugconf_subpage debugconf_page_default = {
115	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
116	DBGCNF_SUBPAGE_CODE,		/* subpage */
117	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119	DBGCNF_VERSION,			/* page_version */
120	{CTL_TIME_IO_DEFAULT_SECS>>8,
121	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
122};
123
124static struct copan_debugconf_subpage debugconf_page_changeable = {
125	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
126	DBGCNF_SUBPAGE_CODE,		/* subpage */
127	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129	0,				/* page_version */
130	{0xff,0xff},			/* ctl_time_io_secs */
131};
132
133static struct scsi_da_rw_recovery_page rw_er_page_default = {
134	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137	/*read_retry_count*/0,
138	/*correction_span*/0,
139	/*head_offset_count*/0,
140	/*data_strobe_offset_cnt*/0,
141	/*byte8*/SMS_RWER_LBPERE,
142	/*write_retry_count*/0,
143	/*reserved2*/0,
144	/*recovery_time_limit*/{0, 0},
145};
146
147static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150	/*byte3*/0,
151	/*read_retry_count*/0,
152	/*correction_span*/0,
153	/*head_offset_count*/0,
154	/*data_strobe_offset_cnt*/0,
155	/*byte8*/0,
156	/*write_retry_count*/0,
157	/*reserved2*/0,
158	/*recovery_time_limit*/{0, 0},
159};
160
161static struct scsi_format_page format_page_default = {
162	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
163	/*page_length*/sizeof(struct scsi_format_page) - 2,
164	/*tracks_per_zone*/ {0, 0},
165	/*alt_sectors_per_zone*/ {0, 0},
166	/*alt_tracks_per_zone*/ {0, 0},
167	/*alt_tracks_per_lun*/ {0, 0},
168	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170	/*bytes_per_sector*/ {0, 0},
171	/*interleave*/ {0, 0},
172	/*track_skew*/ {0, 0},
173	/*cylinder_skew*/ {0, 0},
174	/*flags*/ SFP_HSEC,
175	/*reserved*/ {0, 0, 0}
176};
177
178static struct scsi_format_page format_page_changeable = {
179	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
180	/*page_length*/sizeof(struct scsi_format_page) - 2,
181	/*tracks_per_zone*/ {0, 0},
182	/*alt_sectors_per_zone*/ {0, 0},
183	/*alt_tracks_per_zone*/ {0, 0},
184	/*alt_tracks_per_lun*/ {0, 0},
185	/*sectors_per_track*/ {0, 0},
186	/*bytes_per_sector*/ {0, 0},
187	/*interleave*/ {0, 0},
188	/*track_skew*/ {0, 0},
189	/*cylinder_skew*/ {0, 0},
190	/*flags*/ 0,
191	/*reserved*/ {0, 0, 0}
192};
193
194static struct scsi_rigid_disk_page rigid_disk_page_default = {
195	/*page_code*/SMS_RIGID_DISK_PAGE,
196	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197	/*cylinders*/ {0, 0, 0},
198	/*heads*/ CTL_DEFAULT_HEADS,
199	/*start_write_precomp*/ {0, 0, 0},
200	/*start_reduced_current*/ {0, 0, 0},
201	/*step_rate*/ {0, 0},
202	/*landing_zone_cylinder*/ {0, 0, 0},
203	/*rpl*/ SRDP_RPL_DISABLED,
204	/*rotational_offset*/ 0,
205	/*reserved1*/ 0,
206	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207			   CTL_DEFAULT_ROTATION_RATE & 0xff},
208	/*reserved2*/ {0, 0}
209};
210
211static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212	/*page_code*/SMS_RIGID_DISK_PAGE,
213	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214	/*cylinders*/ {0, 0, 0},
215	/*heads*/ 0,
216	/*start_write_precomp*/ {0, 0, 0},
217	/*start_reduced_current*/ {0, 0, 0},
218	/*step_rate*/ {0, 0},
219	/*landing_zone_cylinder*/ {0, 0, 0},
220	/*rpl*/ 0,
221	/*rotational_offset*/ 0,
222	/*reserved1*/ 0,
223	/*rotation_rate*/ {0, 0},
224	/*reserved2*/ {0, 0}
225};
226
227static struct scsi_caching_page caching_page_default = {
228	/*page_code*/SMS_CACHING_PAGE,
229	/*page_length*/sizeof(struct scsi_caching_page) - 2,
230	/*flags1*/ SCP_DISC | SCP_WCE,
231	/*ret_priority*/ 0,
232	/*disable_pf_transfer_len*/ {0xff, 0xff},
233	/*min_prefetch*/ {0, 0},
234	/*max_prefetch*/ {0xff, 0xff},
235	/*max_pf_ceiling*/ {0xff, 0xff},
236	/*flags2*/ 0,
237	/*cache_segments*/ 0,
238	/*cache_seg_size*/ {0, 0},
239	/*reserved*/ 0,
240	/*non_cache_seg_size*/ {0, 0, 0}
241};
242
243static struct scsi_caching_page caching_page_changeable = {
244	/*page_code*/SMS_CACHING_PAGE,
245	/*page_length*/sizeof(struct scsi_caching_page) - 2,
246	/*flags1*/ SCP_WCE | SCP_RCD,
247	/*ret_priority*/ 0,
248	/*disable_pf_transfer_len*/ {0, 0},
249	/*min_prefetch*/ {0, 0},
250	/*max_prefetch*/ {0, 0},
251	/*max_pf_ceiling*/ {0, 0},
252	/*flags2*/ 0,
253	/*cache_segments*/ 0,
254	/*cache_seg_size*/ {0, 0},
255	/*reserved*/ 0,
256	/*non_cache_seg_size*/ {0, 0, 0}
257};
258
259static struct scsi_control_page control_page_default = {
260	/*page_code*/SMS_CONTROL_MODE_PAGE,
261	/*page_length*/sizeof(struct scsi_control_page) - 2,
262	/*rlec*/0,
263	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264	/*eca_and_aen*/0,
265	/*flags4*/SCP_TAS,
266	/*aen_holdoff_period*/{0, 0},
267	/*busy_timeout_period*/{0, 0},
268	/*extended_selftest_completion_time*/{0, 0}
269};
270
271static struct scsi_control_page control_page_changeable = {
272	/*page_code*/SMS_CONTROL_MODE_PAGE,
273	/*page_length*/sizeof(struct scsi_control_page) - 2,
274	/*rlec*/SCP_DSENSE,
275	/*queue_flags*/SCP_QUEUE_ALG_MASK,
276	/*eca_and_aen*/SCP_SWP,
277	/*flags4*/0,
278	/*aen_holdoff_period*/{0, 0},
279	/*busy_timeout_period*/{0, 0},
280	/*extended_selftest_completion_time*/{0, 0}
281};
282
283static struct scsi_info_exceptions_page ie_page_default = {
284	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286	/*info_flags*/SIEP_FLAGS_DEXCPT,
287	/*mrie*/0,
288	/*interval_timer*/{0, 0, 0, 0},
289	/*report_count*/{0, 0, 0, 0}
290};
291
292static struct scsi_info_exceptions_page ie_page_changeable = {
293	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295	/*info_flags*/0,
296	/*mrie*/0,
297	/*interval_timer*/{0, 0, 0, 0},
298	/*report_count*/{0, 0, 0, 0}
299};
300
301#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305	/*subpage_code*/0x02,
306	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307	/*flags*/0,
308	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309	/*descr*/{}},
310	{{/*flags*/0,
311	  /*resource*/0x01,
312	  /*reserved*/{0, 0},
313	  /*count*/{0, 0, 0, 0}},
314	 {/*flags*/0,
315	  /*resource*/0x02,
316	  /*reserved*/{0, 0},
317	  /*count*/{0, 0, 0, 0}},
318	 {/*flags*/0,
319	  /*resource*/0xf1,
320	  /*reserved*/{0, 0},
321	  /*count*/{0, 0, 0, 0}},
322	 {/*flags*/0,
323	  /*resource*/0xf2,
324	  /*reserved*/{0, 0},
325	  /*count*/{0, 0, 0, 0}}
326	}
327};
328
329static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331	/*subpage_code*/0x02,
332	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333	/*flags*/0,
334	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335	/*descr*/{}},
336	{{/*flags*/0,
337	  /*resource*/0,
338	  /*reserved*/{0, 0},
339	  /*count*/{0, 0, 0, 0}},
340	 {/*flags*/0,
341	  /*resource*/0,
342	  /*reserved*/{0, 0},
343	  /*count*/{0, 0, 0, 0}},
344	 {/*flags*/0,
345	  /*resource*/0,
346	  /*reserved*/{0, 0},
347	  /*count*/{0, 0, 0, 0}},
348	 {/*flags*/0,
349	  /*resource*/0,
350	  /*reserved*/{0, 0},
351	  /*count*/{0, 0, 0, 0}}
352	}
353};
354
355/*
356 * XXX KDM move these into the softc.
357 */
358static int rcv_sync_msg;
359static uint8_t ctl_pause_rtr;
360
361SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362static int worker_threads = -1;
363TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
364SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
365    &worker_threads, 1, "Number of worker threads");
366static int ctl_debug = CTL_DEBUG_NONE;
367TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
368SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
369    &ctl_debug, 0, "Enabled debug flags");
370
371/*
372 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
373 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
374 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
375 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
376 */
377#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
378
379static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380				  int param);
381static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382static int ctl_init(void);
383void ctl_shutdown(void);
384static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
385static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
386static void ctl_ioctl_online(void *arg);
387static void ctl_ioctl_offline(void *arg);
388static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
389static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
390static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
391static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
392static int ctl_ioctl_submit_wait(union ctl_io *io);
393static void ctl_ioctl_datamove(union ctl_io *io);
394static void ctl_ioctl_done(union ctl_io *io);
395static void ctl_ioctl_hard_startstop_callback(void *arg,
396					      struct cfi_metatask *metatask);
397static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
398static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
399			      struct ctl_ooa *ooa_hdr,
400			      struct ctl_ooa_entry *kern_entries);
401static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
402		     struct thread *td);
403static uint32_t ctl_map_lun(int port_num, uint32_t lun);
404static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
405static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
406			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
407static int ctl_free_lun(struct ctl_lun *lun);
408static void ctl_create_lun(struct ctl_be_lun *be_lun);
409/**
410static void ctl_failover_change_pages(struct ctl_softc *softc,
411				      struct ctl_scsiio *ctsio, int master);
412**/
413
414static int ctl_do_mode_select(union ctl_io *io);
415static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
416			   uint64_t res_key, uint64_t sa_res_key,
417			   uint8_t type, uint32_t residx,
418			   struct ctl_scsiio *ctsio,
419			   struct scsi_per_res_out *cdb,
420			   struct scsi_per_res_out_parms* param);
421static void ctl_pro_preempt_other(struct ctl_lun *lun,
422				  union ctl_ha_msg *msg);
423static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
424static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
425static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
426static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
427static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
428static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
429static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
430					 int alloc_len);
431static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
432					 int alloc_len);
433static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
434static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
435static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
436static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
437static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
438static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
439static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
440    union ctl_io *pending_io, union ctl_io *ooa_io);
441static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
442				union ctl_io *starting_io);
443static int ctl_check_blocked(struct ctl_lun *lun);
444static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
445				struct ctl_lun *lun,
446				const struct ctl_cmd_entry *entry,
447				struct ctl_scsiio *ctsio);
448//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
449static void ctl_failover(void);
450static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
451			       struct ctl_scsiio *ctsio);
452static int ctl_scsiio(struct ctl_scsiio *ctsio);
453
454static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
455static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
456			    ctl_ua_type ua_type);
457static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
458			 ctl_ua_type ua_type);
459static int ctl_abort_task(union ctl_io *io);
460static int ctl_abort_task_set(union ctl_io *io);
461static int ctl_i_t_nexus_reset(union ctl_io *io);
462static void ctl_run_task(union ctl_io *io);
463#ifdef CTL_IO_DELAY
464static void ctl_datamove_timer_wakeup(void *arg);
465static void ctl_done_timer_wakeup(void *arg);
466#endif /* CTL_IO_DELAY */
467
468static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
469static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
470static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
471static void ctl_datamove_remote_write(union ctl_io *io);
472static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
473static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
474static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
475static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
476				    ctl_ha_dt_cb callback);
477static void ctl_datamove_remote_read(union ctl_io *io);
478static void ctl_datamove_remote(union ctl_io *io);
479static int ctl_process_done(union ctl_io *io);
480static void ctl_lun_thread(void *arg);
481static void ctl_thresh_thread(void *arg);
482static void ctl_work_thread(void *arg);
483static void ctl_enqueue_incoming(union ctl_io *io);
484static void ctl_enqueue_rtr(union ctl_io *io);
485static void ctl_enqueue_done(union ctl_io *io);
486static void ctl_enqueue_isc(union ctl_io *io);
487static const struct ctl_cmd_entry *
488    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
489static const struct ctl_cmd_entry *
490    ctl_validate_command(struct ctl_scsiio *ctsio);
491static int ctl_cmd_applicable(uint8_t lun_type,
492    const struct ctl_cmd_entry *entry);
493
494/*
495 * Load the serialization table.  This isn't very pretty, but is probably
496 * the easiest way to do it.
497 */
498#include "ctl_ser_table.c"
499
500/*
501 * We only need to define open, close and ioctl routines for this driver.
502 */
503static struct cdevsw ctl_cdevsw = {
504	.d_version =	D_VERSION,
505	.d_flags =	0,
506	.d_open =	ctl_open,
507	.d_close =	ctl_close,
508	.d_ioctl =	ctl_ioctl,
509	.d_name =	"ctl",
510};
511
512
513MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
514MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
515
516static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
517
518static moduledata_t ctl_moduledata = {
519	"ctl",
520	ctl_module_event_handler,
521	NULL
522};
523
524DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
525MODULE_VERSION(ctl, 1);
526
527static struct ctl_frontend ioctl_frontend =
528{
529	.name = "ioctl",
530};
531
532static void
533ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
534			    union ctl_ha_msg *msg_info)
535{
536	struct ctl_scsiio *ctsio;
537
538	if (msg_info->hdr.original_sc == NULL) {
539		printf("%s: original_sc == NULL!\n", __func__);
540		/* XXX KDM now what? */
541		return;
542	}
543
544	ctsio = &msg_info->hdr.original_sc->scsiio;
545	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
546	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
547	ctsio->io_hdr.status = msg_info->hdr.status;
548	ctsio->scsi_status = msg_info->scsi.scsi_status;
549	ctsio->sense_len = msg_info->scsi.sense_len;
550	ctsio->sense_residual = msg_info->scsi.sense_residual;
551	ctsio->residual = msg_info->scsi.residual;
552	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
553	       sizeof(ctsio->sense_data));
554	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
555	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
556	ctl_enqueue_isc((union ctl_io *)ctsio);
557}
558
559static void
560ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
561				union ctl_ha_msg *msg_info)
562{
563	struct ctl_scsiio *ctsio;
564
565	if (msg_info->hdr.serializing_sc == NULL) {
566		printf("%s: serializing_sc == NULL!\n", __func__);
567		/* XXX KDM now what? */
568		return;
569	}
570
571	ctsio = &msg_info->hdr.serializing_sc->scsiio;
572#if 0
573	/*
574	 * Attempt to catch the situation where an I/O has
575	 * been freed, and we're using it again.
576	 */
577	if (ctsio->io_hdr.io_type == 0xff) {
578		union ctl_io *tmp_io;
579		tmp_io = (union ctl_io *)ctsio;
580		printf("%s: %p use after free!\n", __func__,
581		       ctsio);
582		printf("%s: type %d msg %d cdb %x iptl: "
583		       "%d:%d:%d:%d tag 0x%04x "
584		       "flag %#x status %x\n",
585			__func__,
586			tmp_io->io_hdr.io_type,
587			tmp_io->io_hdr.msg_type,
588			tmp_io->scsiio.cdb[0],
589			tmp_io->io_hdr.nexus.initid.id,
590			tmp_io->io_hdr.nexus.targ_port,
591			tmp_io->io_hdr.nexus.targ_target.id,
592			tmp_io->io_hdr.nexus.targ_lun,
593			(tmp_io->io_hdr.io_type ==
594			CTL_IO_TASK) ?
595			tmp_io->taskio.tag_num :
596			tmp_io->scsiio.tag_num,
597		        tmp_io->io_hdr.flags,
598			tmp_io->io_hdr.status);
599	}
600#endif
601	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
602	ctl_enqueue_isc((union ctl_io *)ctsio);
603}
604
605/*
606 * ISC (Inter Shelf Communication) event handler.  Events from the HA
607 * subsystem come in here.
608 */
609static void
610ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
611{
612	struct ctl_softc *ctl_softc;
613	union ctl_io *io;
614	struct ctl_prio *presio;
615	ctl_ha_status isc_status;
616
617	ctl_softc = control_softc;
618	io = NULL;
619
620
621#if 0
622	printf("CTL: Isc Msg event %d\n", event);
623#endif
624	if (event == CTL_HA_EVT_MSG_RECV) {
625		union ctl_ha_msg msg_info;
626
627		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
628					     sizeof(msg_info), /*wait*/ 0);
629#if 0
630		printf("CTL: msg_type %d\n", msg_info.msg_type);
631#endif
632		if (isc_status != 0) {
633			printf("Error receiving message, status = %d\n",
634			       isc_status);
635			return;
636		}
637
638		switch (msg_info.hdr.msg_type) {
639		case CTL_MSG_SERIALIZE:
640#if 0
641			printf("Serialize\n");
642#endif
643			io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
644			if (io == NULL) {
645				printf("ctl_isc_event_handler: can't allocate "
646				       "ctl_io!\n");
647				/* Bad Juju */
648				/* Need to set busy and send msg back */
649				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
650				msg_info.hdr.status = CTL_SCSI_ERROR;
651				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
652				msg_info.scsi.sense_len = 0;
653			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
654				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
655				}
656				goto bailout;
657			}
658			ctl_zero_io(io);
659			// populate ctsio from msg_info
660			io->io_hdr.io_type = CTL_IO_SCSI;
661			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
662			io->io_hdr.original_sc = msg_info.hdr.original_sc;
663#if 0
664			printf("pOrig %x\n", (int)msg_info.original_sc);
665#endif
666			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
667					    CTL_FLAG_IO_ACTIVE;
668			/*
669			 * If we're in serialization-only mode, we don't
670			 * want to go through full done processing.  Thus
671			 * the COPY flag.
672			 *
673			 * XXX KDM add another flag that is more specific.
674			 */
675			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
676				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
677			io->io_hdr.nexus = msg_info.hdr.nexus;
678#if 0
679			printf("targ %d, port %d, iid %d, lun %d\n",
680			       io->io_hdr.nexus.targ_target.id,
681			       io->io_hdr.nexus.targ_port,
682			       io->io_hdr.nexus.initid.id,
683			       io->io_hdr.nexus.targ_lun);
684#endif
685			io->scsiio.tag_num = msg_info.scsi.tag_num;
686			io->scsiio.tag_type = msg_info.scsi.tag_type;
687			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
688			       CTL_MAX_CDBLEN);
689			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
690				const struct ctl_cmd_entry *entry;
691
692				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
693				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
694				io->io_hdr.flags |=
695					entry->flags & CTL_FLAG_DATA_MASK;
696			}
697			ctl_enqueue_isc(io);
698			break;
699
700		/* Performed on the Originating SC, XFER mode only */
701		case CTL_MSG_DATAMOVE: {
702			struct ctl_sg_entry *sgl;
703			int i, j;
704
705			io = msg_info.hdr.original_sc;
706			if (io == NULL) {
707				printf("%s: original_sc == NULL!\n", __func__);
708				/* XXX KDM do something here */
709				break;
710			}
711			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
712			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
713			/*
714			 * Keep track of this, we need to send it back over
715			 * when the datamove is complete.
716			 */
717			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
718
719			if (msg_info.dt.sg_sequence == 0) {
720				/*
721				 * XXX KDM we use the preallocated S/G list
722				 * here, but we'll need to change this to
723				 * dynamic allocation if we need larger S/G
724				 * lists.
725				 */
726				if (msg_info.dt.kern_sg_entries >
727				    sizeof(io->io_hdr.remote_sglist) /
728				    sizeof(io->io_hdr.remote_sglist[0])) {
729					printf("%s: number of S/G entries "
730					    "needed %u > allocated num %zd\n",
731					    __func__,
732					    msg_info.dt.kern_sg_entries,
733					    sizeof(io->io_hdr.remote_sglist)/
734					    sizeof(io->io_hdr.remote_sglist[0]));
735
736					/*
737					 * XXX KDM send a message back to
738					 * the other side to shut down the
739					 * DMA.  The error will come back
740					 * through via the normal channel.
741					 */
742					break;
743				}
744				sgl = io->io_hdr.remote_sglist;
745				memset(sgl, 0,
746				       sizeof(io->io_hdr.remote_sglist));
747
748				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
749
750				io->scsiio.kern_sg_entries =
751					msg_info.dt.kern_sg_entries;
752				io->scsiio.rem_sg_entries =
753					msg_info.dt.kern_sg_entries;
754				io->scsiio.kern_data_len =
755					msg_info.dt.kern_data_len;
756				io->scsiio.kern_total_len =
757					msg_info.dt.kern_total_len;
758				io->scsiio.kern_data_resid =
759					msg_info.dt.kern_data_resid;
760				io->scsiio.kern_rel_offset =
761					msg_info.dt.kern_rel_offset;
762				/*
763				 * Clear out per-DMA flags.
764				 */
765				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
766				/*
767				 * Add per-DMA flags that are set for this
768				 * particular DMA request.
769				 */
770				io->io_hdr.flags |= msg_info.dt.flags &
771						    CTL_FLAG_RDMA_MASK;
772			} else
773				sgl = (struct ctl_sg_entry *)
774					io->scsiio.kern_data_ptr;
775
776			for (i = msg_info.dt.sent_sg_entries, j = 0;
777			     i < (msg_info.dt.sent_sg_entries +
778			     msg_info.dt.cur_sg_entries); i++, j++) {
779				sgl[i].addr = msg_info.dt.sg_list[j].addr;
780				sgl[i].len = msg_info.dt.sg_list[j].len;
781
782#if 0
783				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
784				       __func__,
785				       msg_info.dt.sg_list[j].addr,
786				       msg_info.dt.sg_list[j].len,
787				       sgl[i].addr, sgl[i].len, j, i);
788#endif
789			}
790#if 0
791			memcpy(&sgl[msg_info.dt.sent_sg_entries],
792			       msg_info.dt.sg_list,
793			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
794#endif
795
796			/*
797			 * If this is the last piece of the I/O, we've got
798			 * the full S/G list.  Queue processing in the thread.
799			 * Otherwise wait for the next piece.
800			 */
801			if (msg_info.dt.sg_last != 0)
802				ctl_enqueue_isc(io);
803			break;
804		}
805		/* Performed on the Serializing (primary) SC, XFER mode only */
806		case CTL_MSG_DATAMOVE_DONE: {
807			if (msg_info.hdr.serializing_sc == NULL) {
808				printf("%s: serializing_sc == NULL!\n",
809				       __func__);
810				/* XXX KDM now what? */
811				break;
812			}
813			/*
814			 * We grab the sense information here in case
815			 * there was a failure, so we can return status
816			 * back to the initiator.
817			 */
818			io = msg_info.hdr.serializing_sc;
819			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
820			io->io_hdr.status = msg_info.hdr.status;
821			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
822			io->scsiio.sense_len = msg_info.scsi.sense_len;
823			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
824			io->io_hdr.port_status = msg_info.scsi.fetd_status;
825			io->scsiio.residual = msg_info.scsi.residual;
826			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
827			       sizeof(io->scsiio.sense_data));
828			ctl_enqueue_isc(io);
829			break;
830		}
831
832		/* Preformed on Originating SC, SER_ONLY mode */
833		case CTL_MSG_R2R:
834			io = msg_info.hdr.original_sc;
835			if (io == NULL) {
836				printf("%s: Major Bummer\n", __func__);
837				return;
838			} else {
839#if 0
840				printf("pOrig %x\n",(int) ctsio);
841#endif
842			}
843			io->io_hdr.msg_type = CTL_MSG_R2R;
844			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
845			ctl_enqueue_isc(io);
846			break;
847
848		/*
849		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
850		 * mode.
851		 * Performed on the Originating (i.e. secondary) SC in XFER
852		 * mode
853		 */
854		case CTL_MSG_FINISH_IO:
855			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
856				ctl_isc_handler_finish_xfer(ctl_softc,
857							    &msg_info);
858			else
859				ctl_isc_handler_finish_ser_only(ctl_softc,
860								&msg_info);
861			break;
862
863		/* Preformed on Originating SC */
864		case CTL_MSG_BAD_JUJU:
865			io = msg_info.hdr.original_sc;
866			if (io == NULL) {
867				printf("%s: Bad JUJU!, original_sc is NULL!\n",
868				       __func__);
869				break;
870			}
871			ctl_copy_sense_data(&msg_info, io);
872			/*
873			 * IO should have already been cleaned up on other
874			 * SC so clear this flag so we won't send a message
875			 * back to finish the IO there.
876			 */
877			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
878			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
879
880			/* io = msg_info.hdr.serializing_sc; */
881			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
882			ctl_enqueue_isc(io);
883			break;
884
885		/* Handle resets sent from the other side */
886		case CTL_MSG_MANAGE_TASKS: {
887			struct ctl_taskio *taskio;
888			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
889			    ctl_softc->othersc_pool);
890			if (taskio == NULL) {
891				printf("ctl_isc_event_handler: can't allocate "
892				       "ctl_io!\n");
893				/* Bad Juju */
894				/* should I just call the proper reset func
895				   here??? */
896				goto bailout;
897			}
898			ctl_zero_io((union ctl_io *)taskio);
899			taskio->io_hdr.io_type = CTL_IO_TASK;
900			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
901			taskio->io_hdr.nexus = msg_info.hdr.nexus;
902			taskio->task_action = msg_info.task.task_action;
903			taskio->tag_num = msg_info.task.tag_num;
904			taskio->tag_type = msg_info.task.tag_type;
905#ifdef CTL_TIME_IO
906			taskio->io_hdr.start_time = time_uptime;
907			getbintime(&taskio->io_hdr.start_bt);
908#if 0
909			cs_prof_gettime(&taskio->io_hdr.start_ticks);
910#endif
911#endif /* CTL_TIME_IO */
912			ctl_run_task((union ctl_io *)taskio);
913			break;
914		}
915		/* Persistent Reserve action which needs attention */
916		case CTL_MSG_PERS_ACTION:
917			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
918			    ctl_softc->othersc_pool);
919			if (presio == NULL) {
920				printf("ctl_isc_event_handler: can't allocate "
921				       "ctl_io!\n");
922				/* Bad Juju */
923				/* Need to set busy and send msg back */
924				goto bailout;
925			}
926			ctl_zero_io((union ctl_io *)presio);
927			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
928			presio->pr_msg = msg_info.pr;
929			ctl_enqueue_isc((union ctl_io *)presio);
930			break;
931		case CTL_MSG_SYNC_FE:
932			rcv_sync_msg = 1;
933			break;
934		default:
935		        printf("How did I get here?\n");
936		}
937	} else if (event == CTL_HA_EVT_MSG_SENT) {
938		if (param != CTL_HA_STATUS_SUCCESS) {
939			printf("Bad status from ctl_ha_msg_send status %d\n",
940			       param);
941		}
942		return;
943	} else if (event == CTL_HA_EVT_DISCONNECT) {
944		printf("CTL: Got a disconnect from Isc\n");
945		return;
946	} else {
947		printf("ctl_isc_event_handler: Unknown event %d\n", event);
948		return;
949	}
950
951bailout:
952	return;
953}
954
955static void
956ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
957{
958	struct scsi_sense_data *sense;
959
960	sense = &dest->scsiio.sense_data;
961	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
962	dest->scsiio.scsi_status = src->scsi.scsi_status;
963	dest->scsiio.sense_len = src->scsi.sense_len;
964	dest->io_hdr.status = src->hdr.status;
965}
966
967static void
968ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
969{
970	ctl_ua_type *pu;
971
972	mtx_assert(&lun->lun_lock, MA_OWNED);
973	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
974	if (pu == NULL)
975		return;
976	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
977}
978
979static void
980ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
981{
982	int i, j;
983
984	mtx_assert(&lun->lun_lock, MA_OWNED);
985	for (i = 0; i < CTL_MAX_PORTS; i++) {
986		if (lun->pending_ua[i] == NULL)
987			continue;
988		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
989			if (i * CTL_MAX_INIT_PER_PORT + j == except)
990				continue;
991			lun->pending_ua[i][j] |= ua;
992		}
993	}
994}
995
996static void
997ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
998{
999	ctl_ua_type *pu;
1000
1001	mtx_assert(&lun->lun_lock, MA_OWNED);
1002	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1003	if (pu == NULL)
1004		return;
1005	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1006}
1007
1008static void
1009ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1010{
1011	int i, j;
1012
1013	mtx_assert(&lun->lun_lock, MA_OWNED);
1014	for (i = 0; i < CTL_MAX_PORTS; i++) {
1015		if (lun->pending_ua[i] == NULL)
1016			continue;
1017		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1018			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1019				continue;
1020			lun->pending_ua[i][j] &= ~ua;
1021		}
1022	}
1023}
1024
1025static int
1026ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1027{
1028	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1029	struct ctl_lun *lun;
1030	int error, value;
1031
1032	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1033		value = 0;
1034	else
1035		value = 1;
1036
1037	error = sysctl_handle_int(oidp, &value, 0, req);
1038	if ((error != 0) || (req->newptr == NULL))
1039		return (error);
1040
1041	mtx_lock(&softc->ctl_lock);
1042	if (value == 0)
1043		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1044	else
1045		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1046	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1047		mtx_lock(&lun->lun_lock);
1048		ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1049		mtx_unlock(&lun->lun_lock);
1050	}
1051	mtx_unlock(&softc->ctl_lock);
1052	return (0);
1053}
1054
1055static int
1056ctl_init(void)
1057{
1058	struct ctl_softc *softc;
1059	void *other_pool;
1060	struct ctl_port *port;
1061	int i, error, retval;
1062	//int isc_retval;
1063
1064	retval = 0;
1065	ctl_pause_rtr = 0;
1066        rcv_sync_msg = 0;
1067
1068	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1069			       M_WAITOK | M_ZERO);
1070	softc = control_softc;
1071
1072	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1073			      "cam/ctl");
1074
1075	softc->dev->si_drv1 = softc;
1076
1077	/*
1078	 * By default, return a "bad LUN" peripheral qualifier for unknown
1079	 * LUNs.  The user can override this default using the tunable or
1080	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1081	 */
1082	softc->inquiry_pq_no_lun = 1;
1083	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1084			  &softc->inquiry_pq_no_lun);
1085	sysctl_ctx_init(&softc->sysctl_ctx);
1086	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1087		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1088		CTLFLAG_RD, 0, "CAM Target Layer");
1089
1090	if (softc->sysctl_tree == NULL) {
1091		printf("%s: unable to allocate sysctl tree\n", __func__);
1092		destroy_dev(softc->dev);
1093		free(control_softc, M_DEVBUF);
1094		control_softc = NULL;
1095		return (ENOMEM);
1096	}
1097
1098	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1099		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1100		       "inquiry_pq_no_lun", CTLFLAG_RW,
1101		       &softc->inquiry_pq_no_lun, 0,
1102		       "Report no lun possible for invalid LUNs");
1103
1104	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1105	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1106	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1107	softc->open_count = 0;
1108
1109	/*
1110	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1111	 * the drive.
1112	 */
1113	softc->flags = CTL_FLAG_REAL_SYNC;
1114
1115	/*
1116	 * In Copan's HA scheme, the "master" and "slave" roles are
1117	 * figured out through the slot the controller is in.  Although it
1118	 * is an active/active system, someone has to be in charge.
1119	 */
1120	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1121	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1122	    "HA head ID (0 - no HA)");
1123	if (softc->ha_id == 0) {
1124		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1125		softc->is_single = 1;
1126		softc->port_offset = 0;
1127	} else
1128		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1129	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1130
1131	/*
1132	 * XXX KDM need to figure out where we want to get our target ID
1133	 * and WWID.  Is it different on each port?
1134	 */
1135	softc->target.id = 0;
1136	softc->target.wwid[0] = 0x12345678;
1137	softc->target.wwid[1] = 0x87654321;
1138	STAILQ_INIT(&softc->lun_list);
1139	STAILQ_INIT(&softc->pending_lun_queue);
1140	STAILQ_INIT(&softc->fe_list);
1141	STAILQ_INIT(&softc->port_list);
1142	STAILQ_INIT(&softc->be_list);
1143	ctl_tpc_init(softc);
1144
1145	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1146	                    &other_pool) != 0)
1147	{
1148		printf("ctl: can't allocate %d entry other SC pool, "
1149		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1150		return (ENOMEM);
1151	}
1152	softc->othersc_pool = other_pool;
1153
1154	if (worker_threads <= 0)
1155		worker_threads = max(1, mp_ncpus / 4);
1156	if (worker_threads > CTL_MAX_THREADS)
1157		worker_threads = CTL_MAX_THREADS;
1158
1159	for (i = 0; i < worker_threads; i++) {
1160		struct ctl_thread *thr = &softc->threads[i];
1161
1162		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1163		thr->ctl_softc = softc;
1164		STAILQ_INIT(&thr->incoming_queue);
1165		STAILQ_INIT(&thr->rtr_queue);
1166		STAILQ_INIT(&thr->done_queue);
1167		STAILQ_INIT(&thr->isc_queue);
1168
1169		error = kproc_kthread_add(ctl_work_thread, thr,
1170		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1171		if (error != 0) {
1172			printf("error creating CTL work thread!\n");
1173			ctl_pool_free(other_pool);
1174			return (error);
1175		}
1176	}
1177	error = kproc_kthread_add(ctl_lun_thread, softc,
1178	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1179	if (error != 0) {
1180		printf("error creating CTL lun thread!\n");
1181		ctl_pool_free(other_pool);
1182		return (error);
1183	}
1184	error = kproc_kthread_add(ctl_thresh_thread, softc,
1185	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1186	if (error != 0) {
1187		printf("error creating CTL threshold thread!\n");
1188		ctl_pool_free(other_pool);
1189		return (error);
1190	}
1191	if (bootverbose)
1192		printf("ctl: CAM Target Layer loaded\n");
1193
1194	/*
1195	 * Initialize the ioctl front end.
1196	 */
1197	ctl_frontend_register(&ioctl_frontend);
1198	port = &softc->ioctl_info.port;
1199	port->frontend = &ioctl_frontend;
1200	sprintf(softc->ioctl_info.port_name, "ioctl");
1201	port->port_type = CTL_PORT_IOCTL;
1202	port->num_requested_ctl_io = 100;
1203	port->port_name = softc->ioctl_info.port_name;
1204	port->port_online = ctl_ioctl_online;
1205	port->port_offline = ctl_ioctl_offline;
1206	port->onoff_arg = &softc->ioctl_info;
1207	port->lun_enable = ctl_ioctl_lun_enable;
1208	port->lun_disable = ctl_ioctl_lun_disable;
1209	port->targ_lun_arg = &softc->ioctl_info;
1210	port->fe_datamove = ctl_ioctl_datamove;
1211	port->fe_done = ctl_ioctl_done;
1212	port->max_targets = 15;
1213	port->max_target_id = 15;
1214
1215	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1216		printf("ctl: ioctl front end registration failed, will "
1217		       "continue anyway\n");
1218	}
1219
1220	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1221	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1222	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1223
1224#ifdef CTL_IO_DELAY
1225	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1226		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1227		       sizeof(struct callout), CTL_TIMER_BYTES);
1228		return (EINVAL);
1229	}
1230#endif /* CTL_IO_DELAY */
1231
1232	return (0);
1233}
1234
1235void
1236ctl_shutdown(void)
1237{
1238	struct ctl_softc *softc;
1239	struct ctl_lun *lun, *next_lun;
1240
1241	softc = (struct ctl_softc *)control_softc;
1242
1243	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1244		printf("ctl: ioctl front end deregistration failed\n");
1245
1246	mtx_lock(&softc->ctl_lock);
1247
1248	/*
1249	 * Free up each LUN.
1250	 */
1251	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1252		next_lun = STAILQ_NEXT(lun, links);
1253		ctl_free_lun(lun);
1254	}
1255
1256	mtx_unlock(&softc->ctl_lock);
1257
1258	ctl_frontend_deregister(&ioctl_frontend);
1259
1260#if 0
1261	ctl_shutdown_thread(softc->work_thread);
1262	mtx_destroy(&softc->queue_lock);
1263#endif
1264
1265	ctl_tpc_shutdown(softc);
1266	uma_zdestroy(softc->io_zone);
1267	mtx_destroy(&softc->ctl_lock);
1268
1269	destroy_dev(softc->dev);
1270
1271	sysctl_ctx_free(&softc->sysctl_ctx);
1272
1273	free(control_softc, M_DEVBUF);
1274	control_softc = NULL;
1275
1276	if (bootverbose)
1277		printf("ctl: CAM Target Layer unloaded\n");
1278}
1279
1280static int
1281ctl_module_event_handler(module_t mod, int what, void *arg)
1282{
1283
1284	switch (what) {
1285	case MOD_LOAD:
1286		return (ctl_init());
1287	case MOD_UNLOAD:
1288		return (EBUSY);
1289	default:
1290		return (EOPNOTSUPP);
1291	}
1292}
1293
1294/*
1295 * XXX KDM should we do some access checks here?  Bump a reference count to
1296 * prevent a CTL module from being unloaded while someone has it open?
1297 */
1298static int
1299ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1300{
1301	return (0);
1302}
1303
1304static int
1305ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1306{
1307	return (0);
1308}
1309
1310int
1311ctl_port_enable(ctl_port_type port_type)
1312{
1313	struct ctl_softc *softc = control_softc;
1314	struct ctl_port *port;
1315
1316	if (softc->is_single == 0) {
1317		union ctl_ha_msg msg_info;
1318		int isc_retval;
1319
1320#if 0
1321		printf("%s: HA mode, synchronizing frontend enable\n",
1322		        __func__);
1323#endif
1324		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1325	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1326		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1327			printf("Sync msg send error retval %d\n", isc_retval);
1328		}
1329		if (!rcv_sync_msg) {
1330			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1331			        sizeof(msg_info), 1);
1332		}
1333#if 0
1334        	printf("CTL:Frontend Enable\n");
1335	} else {
1336		printf("%s: single mode, skipping frontend synchronization\n",
1337		        __func__);
1338#endif
1339	}
1340
1341	STAILQ_FOREACH(port, &softc->port_list, links) {
1342		if (port_type & port->port_type)
1343		{
1344#if 0
1345			printf("port %d\n", port->targ_port);
1346#endif
1347			ctl_port_online(port);
1348		}
1349	}
1350
1351	return (0);
1352}
1353
1354int
1355ctl_port_disable(ctl_port_type port_type)
1356{
1357	struct ctl_softc *softc;
1358	struct ctl_port *port;
1359
1360	softc = control_softc;
1361
1362	STAILQ_FOREACH(port, &softc->port_list, links) {
1363		if (port_type & port->port_type)
1364			ctl_port_offline(port);
1365	}
1366
1367	return (0);
1368}
1369
1370/*
1371 * Returns 0 for success, 1 for failure.
1372 * Currently the only failure mode is if there aren't enough entries
1373 * allocated.  So, in case of a failure, look at num_entries_dropped,
1374 * reallocate and try again.
1375 */
1376int
1377ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1378	      int *num_entries_filled, int *num_entries_dropped,
1379	      ctl_port_type port_type, int no_virtual)
1380{
1381	struct ctl_softc *softc;
1382	struct ctl_port *port;
1383	int entries_dropped, entries_filled;
1384	int retval;
1385	int i;
1386
1387	softc = control_softc;
1388
1389	retval = 0;
1390	entries_filled = 0;
1391	entries_dropped = 0;
1392
1393	i = 0;
1394	mtx_lock(&softc->ctl_lock);
1395	STAILQ_FOREACH(port, &softc->port_list, links) {
1396		struct ctl_port_entry *entry;
1397
1398		if ((port->port_type & port_type) == 0)
1399			continue;
1400
1401		if ((no_virtual != 0)
1402		 && (port->virtual_port != 0))
1403			continue;
1404
1405		if (entries_filled >= num_entries_alloced) {
1406			entries_dropped++;
1407			continue;
1408		}
1409		entry = &entries[i];
1410
1411		entry->port_type = port->port_type;
1412		strlcpy(entry->port_name, port->port_name,
1413			sizeof(entry->port_name));
1414		entry->physical_port = port->physical_port;
1415		entry->virtual_port = port->virtual_port;
1416		entry->wwnn = port->wwnn;
1417		entry->wwpn = port->wwpn;
1418
1419		i++;
1420		entries_filled++;
1421	}
1422
1423	mtx_unlock(&softc->ctl_lock);
1424
1425	if (entries_dropped > 0)
1426		retval = 1;
1427
1428	*num_entries_dropped = entries_dropped;
1429	*num_entries_filled = entries_filled;
1430
1431	return (retval);
1432}
1433
1434static void
1435ctl_ioctl_online(void *arg)
1436{
1437	struct ctl_ioctl_info *ioctl_info;
1438
1439	ioctl_info = (struct ctl_ioctl_info *)arg;
1440
1441	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1442}
1443
1444static void
1445ctl_ioctl_offline(void *arg)
1446{
1447	struct ctl_ioctl_info *ioctl_info;
1448
1449	ioctl_info = (struct ctl_ioctl_info *)arg;
1450
1451	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1452}
1453
1454/*
1455 * Remove an initiator by port number and initiator ID.
1456 * Returns 0 for success, -1 for failure.
1457 */
1458int
1459ctl_remove_initiator(struct ctl_port *port, int iid)
1460{
1461	struct ctl_softc *softc = control_softc;
1462
1463	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1464
1465	if (iid > CTL_MAX_INIT_PER_PORT) {
1466		printf("%s: initiator ID %u > maximun %u!\n",
1467		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1468		return (-1);
1469	}
1470
1471	mtx_lock(&softc->ctl_lock);
1472	port->wwpn_iid[iid].in_use--;
1473	port->wwpn_iid[iid].last_use = time_uptime;
1474	mtx_unlock(&softc->ctl_lock);
1475
1476	return (0);
1477}
1478
1479/*
1480 * Add an initiator to the initiator map.
1481 * Returns iid for success, < 0 for failure.
1482 */
1483int
1484ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1485{
1486	struct ctl_softc *softc = control_softc;
1487	time_t best_time;
1488	int i, best;
1489
1490	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1491
1492	if (iid >= CTL_MAX_INIT_PER_PORT) {
1493		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1494		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1495		free(name, M_CTL);
1496		return (-1);
1497	}
1498
1499	mtx_lock(&softc->ctl_lock);
1500
1501	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1502		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1503			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1504				iid = i;
1505				break;
1506			}
1507			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1508			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1509				iid = i;
1510				break;
1511			}
1512		}
1513	}
1514
1515	if (iid < 0) {
1516		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1517			if (port->wwpn_iid[i].in_use == 0 &&
1518			    port->wwpn_iid[i].wwpn == 0 &&
1519			    port->wwpn_iid[i].name == NULL) {
1520				iid = i;
1521				break;
1522			}
1523		}
1524	}
1525
1526	if (iid < 0) {
1527		best = -1;
1528		best_time = INT32_MAX;
1529		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1530			if (port->wwpn_iid[i].in_use == 0) {
1531				if (port->wwpn_iid[i].last_use < best_time) {
1532					best = i;
1533					best_time = port->wwpn_iid[i].last_use;
1534				}
1535			}
1536		}
1537		iid = best;
1538	}
1539
1540	if (iid < 0) {
1541		mtx_unlock(&softc->ctl_lock);
1542		free(name, M_CTL);
1543		return (-2);
1544	}
1545
1546	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1547		/*
1548		 * This is not an error yet.
1549		 */
1550		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1551#if 0
1552			printf("%s: port %d iid %u WWPN %#jx arrived"
1553			    " again\n", __func__, port->targ_port,
1554			    iid, (uintmax_t)wwpn);
1555#endif
1556			goto take;
1557		}
1558		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1559		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1560#if 0
1561			printf("%s: port %d iid %u name '%s' arrived"
1562			    " again\n", __func__, port->targ_port,
1563			    iid, name);
1564#endif
1565			goto take;
1566		}
1567
1568		/*
1569		 * This is an error, but what do we do about it?  The
1570		 * driver is telling us we have a new WWPN for this
1571		 * initiator ID, so we pretty much need to use it.
1572		 */
1573		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1574		    " but WWPN %#jx '%s' is still at that address\n",
1575		    __func__, port->targ_port, iid, wwpn, name,
1576		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1577		    port->wwpn_iid[iid].name);
1578
1579		/*
1580		 * XXX KDM clear have_ca and ua_pending on each LUN for
1581		 * this initiator.
1582		 */
1583	}
1584take:
1585	free(port->wwpn_iid[iid].name, M_CTL);
1586	port->wwpn_iid[iid].name = name;
1587	port->wwpn_iid[iid].wwpn = wwpn;
1588	port->wwpn_iid[iid].in_use++;
1589	mtx_unlock(&softc->ctl_lock);
1590
1591	return (iid);
1592}
1593
1594static int
1595ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1596{
1597	int len;
1598
1599	switch (port->port_type) {
1600	case CTL_PORT_FC:
1601	{
1602		struct scsi_transportid_fcp *id =
1603		    (struct scsi_transportid_fcp *)buf;
1604		if (port->wwpn_iid[iid].wwpn == 0)
1605			return (0);
1606		memset(id, 0, sizeof(*id));
1607		id->format_protocol = SCSI_PROTO_FC;
1608		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1609		return (sizeof(*id));
1610	}
1611	case CTL_PORT_ISCSI:
1612	{
1613		struct scsi_transportid_iscsi_port *id =
1614		    (struct scsi_transportid_iscsi_port *)buf;
1615		if (port->wwpn_iid[iid].name == NULL)
1616			return (0);
1617		memset(id, 0, 256);
1618		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1619		    SCSI_PROTO_ISCSI;
1620		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1621		len = roundup2(min(len, 252), 4);
1622		scsi_ulto2b(len, id->additional_length);
1623		return (sizeof(*id) + len);
1624	}
1625	case CTL_PORT_SAS:
1626	{
1627		struct scsi_transportid_sas *id =
1628		    (struct scsi_transportid_sas *)buf;
1629		if (port->wwpn_iid[iid].wwpn == 0)
1630			return (0);
1631		memset(id, 0, sizeof(*id));
1632		id->format_protocol = SCSI_PROTO_SAS;
1633		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1634		return (sizeof(*id));
1635	}
1636	default:
1637	{
1638		struct scsi_transportid_spi *id =
1639		    (struct scsi_transportid_spi *)buf;
1640		memset(id, 0, sizeof(*id));
1641		id->format_protocol = SCSI_PROTO_SPI;
1642		scsi_ulto2b(iid, id->scsi_addr);
1643		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1644		return (sizeof(*id));
1645	}
1646	}
1647}
1648
1649static int
1650ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1651{
1652	return (0);
1653}
1654
1655static int
1656ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1657{
1658	return (0);
1659}
1660
1661/*
1662 * Data movement routine for the CTL ioctl frontend port.
1663 */
1664static int
1665ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1666{
1667	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1668	struct ctl_sg_entry ext_entry, kern_entry;
1669	int ext_sglen, ext_sg_entries, kern_sg_entries;
1670	int ext_sg_start, ext_offset;
1671	int len_to_copy, len_copied;
1672	int kern_watermark, ext_watermark;
1673	int ext_sglist_malloced;
1674	int i, j;
1675
1676	ext_sglist_malloced = 0;
1677	ext_sg_start = 0;
1678	ext_offset = 0;
1679
1680	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1681
1682	/*
1683	 * If this flag is set, fake the data transfer.
1684	 */
1685	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1686		ctsio->ext_data_filled = ctsio->ext_data_len;
1687		goto bailout;
1688	}
1689
1690	/*
1691	 * To simplify things here, if we have a single buffer, stick it in
1692	 * a S/G entry and just make it a single entry S/G list.
1693	 */
1694	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1695		int len_seen;
1696
1697		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1698
1699		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1700							   M_WAITOK);
1701		ext_sglist_malloced = 1;
1702		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1703				   ext_sglen) != 0) {
1704			ctl_set_internal_failure(ctsio,
1705						 /*sks_valid*/ 0,
1706						 /*retry_count*/ 0);
1707			goto bailout;
1708		}
1709		ext_sg_entries = ctsio->ext_sg_entries;
1710		len_seen = 0;
1711		for (i = 0; i < ext_sg_entries; i++) {
1712			if ((len_seen + ext_sglist[i].len) >=
1713			     ctsio->ext_data_filled) {
1714				ext_sg_start = i;
1715				ext_offset = ctsio->ext_data_filled - len_seen;
1716				break;
1717			}
1718			len_seen += ext_sglist[i].len;
1719		}
1720	} else {
1721		ext_sglist = &ext_entry;
1722		ext_sglist->addr = ctsio->ext_data_ptr;
1723		ext_sglist->len = ctsio->ext_data_len;
1724		ext_sg_entries = 1;
1725		ext_sg_start = 0;
1726		ext_offset = ctsio->ext_data_filled;
1727	}
1728
1729	if (ctsio->kern_sg_entries > 0) {
1730		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1731		kern_sg_entries = ctsio->kern_sg_entries;
1732	} else {
1733		kern_sglist = &kern_entry;
1734		kern_sglist->addr = ctsio->kern_data_ptr;
1735		kern_sglist->len = ctsio->kern_data_len;
1736		kern_sg_entries = 1;
1737	}
1738
1739
1740	kern_watermark = 0;
1741	ext_watermark = ext_offset;
1742	len_copied = 0;
1743	for (i = ext_sg_start, j = 0;
1744	     i < ext_sg_entries && j < kern_sg_entries;) {
1745		uint8_t *ext_ptr, *kern_ptr;
1746
1747		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1748				      kern_sglist[j].len - kern_watermark);
1749
1750		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1751		ext_ptr = ext_ptr + ext_watermark;
1752		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1753			/*
1754			 * XXX KDM fix this!
1755			 */
1756			panic("need to implement bus address support");
1757#if 0
1758			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1759#endif
1760		} else
1761			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1762		kern_ptr = kern_ptr + kern_watermark;
1763
1764		kern_watermark += len_to_copy;
1765		ext_watermark += len_to_copy;
1766
1767		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1768		     CTL_FLAG_DATA_IN) {
1769			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1770					 "bytes to user\n", len_to_copy));
1771			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1772					 "to %p\n", kern_ptr, ext_ptr));
1773			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1774				ctl_set_internal_failure(ctsio,
1775							 /*sks_valid*/ 0,
1776							 /*retry_count*/ 0);
1777				goto bailout;
1778			}
1779		} else {
1780			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1781					 "bytes from user\n", len_to_copy));
1782			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1783					 "to %p\n", ext_ptr, kern_ptr));
1784			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1785				ctl_set_internal_failure(ctsio,
1786							 /*sks_valid*/ 0,
1787							 /*retry_count*/0);
1788				goto bailout;
1789			}
1790		}
1791
1792		len_copied += len_to_copy;
1793
1794		if (ext_sglist[i].len == ext_watermark) {
1795			i++;
1796			ext_watermark = 0;
1797		}
1798
1799		if (kern_sglist[j].len == kern_watermark) {
1800			j++;
1801			kern_watermark = 0;
1802		}
1803	}
1804
1805	ctsio->ext_data_filled += len_copied;
1806
1807	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1808			 "kern_sg_entries: %d\n", ext_sg_entries,
1809			 kern_sg_entries));
1810	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1811			 "kern_data_len = %d\n", ctsio->ext_data_len,
1812			 ctsio->kern_data_len));
1813
1814
1815	/* XXX KDM set residual?? */
1816bailout:
1817
1818	if (ext_sglist_malloced != 0)
1819		free(ext_sglist, M_CTL);
1820
1821	return (CTL_RETVAL_COMPLETE);
1822}
1823
1824/*
1825 * Serialize a command that went down the "wrong" side, and so was sent to
1826 * this controller for execution.  The logic is a little different than the
1827 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1828 * sent back to the other side, but in the success case, we execute the
1829 * command on this side (XFER mode) or tell the other side to execute it
1830 * (SER_ONLY mode).
1831 */
1832static int
1833ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1834{
1835	struct ctl_softc *ctl_softc;
1836	union ctl_ha_msg msg_info;
1837	struct ctl_lun *lun;
1838	int retval = 0;
1839	uint32_t targ_lun;
1840
1841	ctl_softc = control_softc;
1842
1843	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1844	lun = ctl_softc->ctl_luns[targ_lun];
1845	if (lun==NULL)
1846	{
1847		/*
1848		 * Why isn't LUN defined? The other side wouldn't
1849		 * send a cmd if the LUN is undefined.
1850		 */
1851		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1852
1853		/* "Logical unit not supported" */
1854		ctl_set_sense_data(&msg_info.scsi.sense_data,
1855				   lun,
1856				   /*sense_format*/SSD_TYPE_NONE,
1857				   /*current_error*/ 1,
1858				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1859				   /*asc*/ 0x25,
1860				   /*ascq*/ 0x00,
1861				   SSD_ELEM_NONE);
1862
1863		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1864		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1865		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1866		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1867		msg_info.hdr.serializing_sc = NULL;
1868		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1869	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871		}
1872		return(1);
1873
1874	}
1875
1876	mtx_lock(&lun->lun_lock);
1877    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1878
1879	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1880		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1881		 ooa_links))) {
1882	case CTL_ACTION_BLOCK:
1883		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1884		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1885				  blocked_links);
1886		break;
1887	case CTL_ACTION_PASS:
1888	case CTL_ACTION_SKIP:
1889		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1890			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1891			ctl_enqueue_rtr((union ctl_io *)ctsio);
1892		} else {
1893
1894			/* send msg back to other side */
1895			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1896			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1897			msg_info.hdr.msg_type = CTL_MSG_R2R;
1898#if 0
1899			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1900#endif
1901		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1902			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1903			}
1904		}
1905		break;
1906	case CTL_ACTION_OVERLAP:
1907		/* OVERLAPPED COMMANDS ATTEMPTED */
1908		ctl_set_sense_data(&msg_info.scsi.sense_data,
1909				   lun,
1910				   /*sense_format*/SSD_TYPE_NONE,
1911				   /*current_error*/ 1,
1912				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1913				   /*asc*/ 0x4E,
1914				   /*ascq*/ 0x00,
1915				   SSD_ELEM_NONE);
1916
1917		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1918		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1919		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1920		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1921		msg_info.hdr.serializing_sc = NULL;
1922		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1923#if 0
1924		printf("BAD JUJU:Major Bummer Overlap\n");
1925#endif
1926		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1927		retval = 1;
1928		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1929		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1930		}
1931		break;
1932	case CTL_ACTION_OVERLAP_TAG:
1933		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1934		ctl_set_sense_data(&msg_info.scsi.sense_data,
1935				   lun,
1936				   /*sense_format*/SSD_TYPE_NONE,
1937				   /*current_error*/ 1,
1938				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1939				   /*asc*/ 0x4D,
1940				   /*ascq*/ ctsio->tag_num & 0xff,
1941				   SSD_ELEM_NONE);
1942
1943		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1944		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1945		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1946		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1947		msg_info.hdr.serializing_sc = NULL;
1948		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1949#if 0
1950		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1951#endif
1952		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1953		retval = 1;
1954		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1955		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1956		}
1957		break;
1958	case CTL_ACTION_ERROR:
1959	default:
1960		/* "Internal target failure" */
1961		ctl_set_sense_data(&msg_info.scsi.sense_data,
1962				   lun,
1963				   /*sense_format*/SSD_TYPE_NONE,
1964				   /*current_error*/ 1,
1965				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1966				   /*asc*/ 0x44,
1967				   /*ascq*/ 0x00,
1968				   SSD_ELEM_NONE);
1969
1970		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1971		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1972		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1973		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1974		msg_info.hdr.serializing_sc = NULL;
1975		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1976#if 0
1977		printf("BAD JUJU:Major Bummer HW Error\n");
1978#endif
1979		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1980		retval = 1;
1981		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1982		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1983		}
1984		break;
1985	}
1986	mtx_unlock(&lun->lun_lock);
1987	return (retval);
1988}
1989
1990static int
1991ctl_ioctl_submit_wait(union ctl_io *io)
1992{
1993	struct ctl_fe_ioctl_params params;
1994	ctl_fe_ioctl_state last_state;
1995	int done, retval;
1996
1997	retval = 0;
1998
1999	bzero(&params, sizeof(params));
2000
2001	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2002	cv_init(&params.sem, "ctlioccv");
2003	params.state = CTL_IOCTL_INPROG;
2004	last_state = params.state;
2005
2006	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2007
2008	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2009
2010	/* This shouldn't happen */
2011	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2012		return (retval);
2013
2014	done = 0;
2015
2016	do {
2017		mtx_lock(&params.ioctl_mtx);
2018		/*
2019		 * Check the state here, and don't sleep if the state has
2020		 * already changed (i.e. wakeup has already occured, but we
2021		 * weren't waiting yet).
2022		 */
2023		if (params.state == last_state) {
2024			/* XXX KDM cv_wait_sig instead? */
2025			cv_wait(&params.sem, &params.ioctl_mtx);
2026		}
2027		last_state = params.state;
2028
2029		switch (params.state) {
2030		case CTL_IOCTL_INPROG:
2031			/* Why did we wake up? */
2032			/* XXX KDM error here? */
2033			mtx_unlock(&params.ioctl_mtx);
2034			break;
2035		case CTL_IOCTL_DATAMOVE:
2036			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2037
2038			/*
2039			 * change last_state back to INPROG to avoid
2040			 * deadlock on subsequent data moves.
2041			 */
2042			params.state = last_state = CTL_IOCTL_INPROG;
2043
2044			mtx_unlock(&params.ioctl_mtx);
2045			ctl_ioctl_do_datamove(&io->scsiio);
2046			/*
2047			 * Note that in some cases, most notably writes,
2048			 * this will queue the I/O and call us back later.
2049			 * In other cases, generally reads, this routine
2050			 * will immediately call back and wake us up,
2051			 * probably using our own context.
2052			 */
2053			io->scsiio.be_move_done(io);
2054			break;
2055		case CTL_IOCTL_DONE:
2056			mtx_unlock(&params.ioctl_mtx);
2057			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2058			done = 1;
2059			break;
2060		default:
2061			mtx_unlock(&params.ioctl_mtx);
2062			/* XXX KDM error here? */
2063			break;
2064		}
2065	} while (done == 0);
2066
2067	mtx_destroy(&params.ioctl_mtx);
2068	cv_destroy(&params.sem);
2069
2070	return (CTL_RETVAL_COMPLETE);
2071}
2072
2073static void
2074ctl_ioctl_datamove(union ctl_io *io)
2075{
2076	struct ctl_fe_ioctl_params *params;
2077
2078	params = (struct ctl_fe_ioctl_params *)
2079		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2080
2081	mtx_lock(&params->ioctl_mtx);
2082	params->state = CTL_IOCTL_DATAMOVE;
2083	cv_broadcast(&params->sem);
2084	mtx_unlock(&params->ioctl_mtx);
2085}
2086
2087static void
2088ctl_ioctl_done(union ctl_io *io)
2089{
2090	struct ctl_fe_ioctl_params *params;
2091
2092	params = (struct ctl_fe_ioctl_params *)
2093		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2094
2095	mtx_lock(&params->ioctl_mtx);
2096	params->state = CTL_IOCTL_DONE;
2097	cv_broadcast(&params->sem);
2098	mtx_unlock(&params->ioctl_mtx);
2099}
2100
2101static void
2102ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2103{
2104	struct ctl_fe_ioctl_startstop_info *sd_info;
2105
2106	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2107
2108	sd_info->hs_info.status = metatask->status;
2109	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2110	sd_info->hs_info.luns_complete =
2111		metatask->taskinfo.startstop.luns_complete;
2112	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2113
2114	cv_broadcast(&sd_info->sem);
2115}
2116
2117static void
2118ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2119{
2120	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2121
2122	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2123
2124	mtx_lock(fe_bbr_info->lock);
2125	fe_bbr_info->bbr_info->status = metatask->status;
2126	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2127	fe_bbr_info->wakeup_done = 1;
2128	mtx_unlock(fe_bbr_info->lock);
2129
2130	cv_broadcast(&fe_bbr_info->sem);
2131}
2132
2133/*
2134 * Returns 0 for success, errno for failure.
2135 */
2136static int
2137ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2138		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2139{
2140	union ctl_io *io;
2141	int retval;
2142
2143	retval = 0;
2144
2145	mtx_lock(&lun->lun_lock);
2146	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2147	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2148	     ooa_links)) {
2149		struct ctl_ooa_entry *entry;
2150
2151		/*
2152		 * If we've got more than we can fit, just count the
2153		 * remaining entries.
2154		 */
2155		if (*cur_fill_num >= ooa_hdr->alloc_num)
2156			continue;
2157
2158		entry = &kern_entries[*cur_fill_num];
2159
2160		entry->tag_num = io->scsiio.tag_num;
2161		entry->lun_num = lun->lun;
2162#ifdef CTL_TIME_IO
2163		entry->start_bt = io->io_hdr.start_bt;
2164#endif
2165		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2166		entry->cdb_len = io->scsiio.cdb_len;
2167		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2168			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2169
2170		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2171			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2172
2173		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2174			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2175
2176		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2177			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2178
2179		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2180			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2181	}
2182	mtx_unlock(&lun->lun_lock);
2183
2184	return (retval);
2185}
2186
2187static void *
2188ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2189		 size_t error_str_len)
2190{
2191	void *kptr;
2192
2193	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2194
2195	if (copyin(user_addr, kptr, len) != 0) {
2196		snprintf(error_str, error_str_len, "Error copying %d bytes "
2197			 "from user address %p to kernel address %p", len,
2198			 user_addr, kptr);
2199		free(kptr, M_CTL);
2200		return (NULL);
2201	}
2202
2203	return (kptr);
2204}
2205
2206static void
2207ctl_free_args(int num_args, struct ctl_be_arg *args)
2208{
2209	int i;
2210
2211	if (args == NULL)
2212		return;
2213
2214	for (i = 0; i < num_args; i++) {
2215		free(args[i].kname, M_CTL);
2216		free(args[i].kvalue, M_CTL);
2217	}
2218
2219	free(args, M_CTL);
2220}
2221
2222static struct ctl_be_arg *
2223ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2224		char *error_str, size_t error_str_len)
2225{
2226	struct ctl_be_arg *args;
2227	int i;
2228
2229	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2230				error_str, error_str_len);
2231
2232	if (args == NULL)
2233		goto bailout;
2234
2235	for (i = 0; i < num_args; i++) {
2236		args[i].kname = NULL;
2237		args[i].kvalue = NULL;
2238	}
2239
2240	for (i = 0; i < num_args; i++) {
2241		uint8_t *tmpptr;
2242
2243		args[i].kname = ctl_copyin_alloc(args[i].name,
2244			args[i].namelen, error_str, error_str_len);
2245		if (args[i].kname == NULL)
2246			goto bailout;
2247
2248		if (args[i].kname[args[i].namelen - 1] != '\0') {
2249			snprintf(error_str, error_str_len, "Argument %d "
2250				 "name is not NUL-terminated", i);
2251			goto bailout;
2252		}
2253
2254		if (args[i].flags & CTL_BEARG_RD) {
2255			tmpptr = ctl_copyin_alloc(args[i].value,
2256				args[i].vallen, error_str, error_str_len);
2257			if (tmpptr == NULL)
2258				goto bailout;
2259			if ((args[i].flags & CTL_BEARG_ASCII)
2260			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2261				snprintf(error_str, error_str_len, "Argument "
2262				    "%d value is not NUL-terminated", i);
2263				goto bailout;
2264			}
2265			args[i].kvalue = tmpptr;
2266		} else {
2267			args[i].kvalue = malloc(args[i].vallen,
2268			    M_CTL, M_WAITOK | M_ZERO);
2269		}
2270	}
2271
2272	return (args);
2273bailout:
2274
2275	ctl_free_args(num_args, args);
2276
2277	return (NULL);
2278}
2279
2280static void
2281ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2282{
2283	int i;
2284
2285	for (i = 0; i < num_args; i++) {
2286		if (args[i].flags & CTL_BEARG_WR)
2287			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2288	}
2289}
2290
2291/*
2292 * Escape characters that are illegal or not recommended in XML.
2293 */
2294int
2295ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2296{
2297	char *end = str + size;
2298	int retval;
2299
2300	retval = 0;
2301
2302	for (; *str && str < end; str++) {
2303		switch (*str) {
2304		case '&':
2305			retval = sbuf_printf(sb, "&amp;");
2306			break;
2307		case '>':
2308			retval = sbuf_printf(sb, "&gt;");
2309			break;
2310		case '<':
2311			retval = sbuf_printf(sb, "&lt;");
2312			break;
2313		default:
2314			retval = sbuf_putc(sb, *str);
2315			break;
2316		}
2317
2318		if (retval != 0)
2319			break;
2320
2321	}
2322
2323	return (retval);
2324}
2325
2326static void
2327ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2328{
2329	struct scsi_vpd_id_descriptor *desc;
2330	int i;
2331
2332	if (id == NULL || id->len < 4)
2333		return;
2334	desc = (struct scsi_vpd_id_descriptor *)id->data;
2335	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2336	case SVPD_ID_TYPE_T10:
2337		sbuf_printf(sb, "t10.");
2338		break;
2339	case SVPD_ID_TYPE_EUI64:
2340		sbuf_printf(sb, "eui.");
2341		break;
2342	case SVPD_ID_TYPE_NAA:
2343		sbuf_printf(sb, "naa.");
2344		break;
2345	case SVPD_ID_TYPE_SCSI_NAME:
2346		break;
2347	}
2348	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2349	case SVPD_ID_CODESET_BINARY:
2350		for (i = 0; i < desc->length; i++)
2351			sbuf_printf(sb, "%02x", desc->identifier[i]);
2352		break;
2353	case SVPD_ID_CODESET_ASCII:
2354		sbuf_printf(sb, "%.*s", (int)desc->length,
2355		    (char *)desc->identifier);
2356		break;
2357	case SVPD_ID_CODESET_UTF8:
2358		sbuf_printf(sb, "%s", (char *)desc->identifier);
2359		break;
2360	}
2361}
2362
2363static int
2364ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2365	  struct thread *td)
2366{
2367	struct ctl_softc *softc;
2368	int retval;
2369
2370	softc = control_softc;
2371
2372	retval = 0;
2373
2374	switch (cmd) {
2375	case CTL_IO: {
2376		union ctl_io *io;
2377		void *pool_tmp;
2378
2379		/*
2380		 * If we haven't been "enabled", don't allow any SCSI I/O
2381		 * to this FETD.
2382		 */
2383		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2384			retval = EPERM;
2385			break;
2386		}
2387
2388		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2389
2390		/*
2391		 * Need to save the pool reference so it doesn't get
2392		 * spammed by the user's ctl_io.
2393		 */
2394		pool_tmp = io->io_hdr.pool;
2395		memcpy(io, (void *)addr, sizeof(*io));
2396		io->io_hdr.pool = pool_tmp;
2397
2398		/*
2399		 * No status yet, so make sure the status is set properly.
2400		 */
2401		io->io_hdr.status = CTL_STATUS_NONE;
2402
2403		/*
2404		 * The user sets the initiator ID, target and LUN IDs.
2405		 */
2406		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2407		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2408		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2409		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2410			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2411
2412		retval = ctl_ioctl_submit_wait(io);
2413
2414		if (retval != 0) {
2415			ctl_free_io(io);
2416			break;
2417		}
2418
2419		memcpy((void *)addr, io, sizeof(*io));
2420
2421		/* return this to our pool */
2422		ctl_free_io(io);
2423
2424		break;
2425	}
2426	case CTL_ENABLE_PORT:
2427	case CTL_DISABLE_PORT:
2428	case CTL_SET_PORT_WWNS: {
2429		struct ctl_port *port;
2430		struct ctl_port_entry *entry;
2431
2432		entry = (struct ctl_port_entry *)addr;
2433
2434		mtx_lock(&softc->ctl_lock);
2435		STAILQ_FOREACH(port, &softc->port_list, links) {
2436			int action, done;
2437
2438			action = 0;
2439			done = 0;
2440
2441			if ((entry->port_type == CTL_PORT_NONE)
2442			 && (entry->targ_port == port->targ_port)) {
2443				/*
2444				 * If the user only wants to enable or
2445				 * disable or set WWNs on a specific port,
2446				 * do the operation and we're done.
2447				 */
2448				action = 1;
2449				done = 1;
2450			} else if (entry->port_type & port->port_type) {
2451				/*
2452				 * Compare the user's type mask with the
2453				 * particular frontend type to see if we
2454				 * have a match.
2455				 */
2456				action = 1;
2457				done = 0;
2458
2459				/*
2460				 * Make sure the user isn't trying to set
2461				 * WWNs on multiple ports at the same time.
2462				 */
2463				if (cmd == CTL_SET_PORT_WWNS) {
2464					printf("%s: Can't set WWNs on "
2465					       "multiple ports\n", __func__);
2466					retval = EINVAL;
2467					break;
2468				}
2469			}
2470			if (action != 0) {
2471				/*
2472				 * XXX KDM we have to drop the lock here,
2473				 * because the online/offline operations
2474				 * can potentially block.  We need to
2475				 * reference count the frontends so they
2476				 * can't go away,
2477				 */
2478				mtx_unlock(&softc->ctl_lock);
2479
2480				if (cmd == CTL_ENABLE_PORT) {
2481					struct ctl_lun *lun;
2482
2483					STAILQ_FOREACH(lun, &softc->lun_list,
2484						       links) {
2485						port->lun_enable(port->targ_lun_arg,
2486						    lun->target,
2487						    lun->lun);
2488					}
2489
2490					ctl_port_online(port);
2491				} else if (cmd == CTL_DISABLE_PORT) {
2492					struct ctl_lun *lun;
2493
2494					ctl_port_offline(port);
2495
2496					STAILQ_FOREACH(lun, &softc->lun_list,
2497						       links) {
2498						port->lun_disable(
2499						    port->targ_lun_arg,
2500						    lun->target,
2501						    lun->lun);
2502					}
2503				}
2504
2505				mtx_lock(&softc->ctl_lock);
2506
2507				if (cmd == CTL_SET_PORT_WWNS)
2508					ctl_port_set_wwns(port,
2509					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2510					    1 : 0, entry->wwnn,
2511					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2512					    1 : 0, entry->wwpn);
2513			}
2514			if (done != 0)
2515				break;
2516		}
2517		mtx_unlock(&softc->ctl_lock);
2518		break;
2519	}
2520	case CTL_GET_PORT_LIST: {
2521		struct ctl_port *port;
2522		struct ctl_port_list *list;
2523		int i;
2524
2525		list = (struct ctl_port_list *)addr;
2526
2527		if (list->alloc_len != (list->alloc_num *
2528		    sizeof(struct ctl_port_entry))) {
2529			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2530			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2531			       "%zu\n", __func__, list->alloc_len,
2532			       list->alloc_num, sizeof(struct ctl_port_entry));
2533			retval = EINVAL;
2534			break;
2535		}
2536		list->fill_len = 0;
2537		list->fill_num = 0;
2538		list->dropped_num = 0;
2539		i = 0;
2540		mtx_lock(&softc->ctl_lock);
2541		STAILQ_FOREACH(port, &softc->port_list, links) {
2542			struct ctl_port_entry entry, *list_entry;
2543
2544			if (list->fill_num >= list->alloc_num) {
2545				list->dropped_num++;
2546				continue;
2547			}
2548
2549			entry.port_type = port->port_type;
2550			strlcpy(entry.port_name, port->port_name,
2551				sizeof(entry.port_name));
2552			entry.targ_port = port->targ_port;
2553			entry.physical_port = port->physical_port;
2554			entry.virtual_port = port->virtual_port;
2555			entry.wwnn = port->wwnn;
2556			entry.wwpn = port->wwpn;
2557			if (port->status & CTL_PORT_STATUS_ONLINE)
2558				entry.online = 1;
2559			else
2560				entry.online = 0;
2561
2562			list_entry = &list->entries[i];
2563
2564			retval = copyout(&entry, list_entry, sizeof(entry));
2565			if (retval != 0) {
2566				printf("%s: CTL_GET_PORT_LIST: copyout "
2567				       "returned %d\n", __func__, retval);
2568				break;
2569			}
2570			i++;
2571			list->fill_num++;
2572			list->fill_len += sizeof(entry);
2573		}
2574		mtx_unlock(&softc->ctl_lock);
2575
2576		/*
2577		 * If this is non-zero, we had a copyout fault, so there's
2578		 * probably no point in attempting to set the status inside
2579		 * the structure.
2580		 */
2581		if (retval != 0)
2582			break;
2583
2584		if (list->dropped_num > 0)
2585			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2586		else
2587			list->status = CTL_PORT_LIST_OK;
2588		break;
2589	}
2590	case CTL_DUMP_OOA: {
2591		struct ctl_lun *lun;
2592		union ctl_io *io;
2593		char printbuf[128];
2594		struct sbuf sb;
2595
2596		mtx_lock(&softc->ctl_lock);
2597		printf("Dumping OOA queues:\n");
2598		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2599			mtx_lock(&lun->lun_lock);
2600			for (io = (union ctl_io *)TAILQ_FIRST(
2601			     &lun->ooa_queue); io != NULL;
2602			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2603			     ooa_links)) {
2604				sbuf_new(&sb, printbuf, sizeof(printbuf),
2605					 SBUF_FIXEDLEN);
2606				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2607					    (intmax_t)lun->lun,
2608					    io->scsiio.tag_num,
2609					    (io->io_hdr.flags &
2610					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2611					    (io->io_hdr.flags &
2612					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2613					    (io->io_hdr.flags &
2614					    CTL_FLAG_ABORT) ? " ABORT" : "",
2615			                    (io->io_hdr.flags &
2616		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2617				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2618				sbuf_finish(&sb);
2619				printf("%s\n", sbuf_data(&sb));
2620			}
2621			mtx_unlock(&lun->lun_lock);
2622		}
2623		printf("OOA queues dump done\n");
2624		mtx_unlock(&softc->ctl_lock);
2625		break;
2626	}
2627	case CTL_GET_OOA: {
2628		struct ctl_lun *lun;
2629		struct ctl_ooa *ooa_hdr;
2630		struct ctl_ooa_entry *entries;
2631		uint32_t cur_fill_num;
2632
2633		ooa_hdr = (struct ctl_ooa *)addr;
2634
2635		if ((ooa_hdr->alloc_len == 0)
2636		 || (ooa_hdr->alloc_num == 0)) {
2637			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2638			       "must be non-zero\n", __func__,
2639			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2640			retval = EINVAL;
2641			break;
2642		}
2643
2644		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2645		    sizeof(struct ctl_ooa_entry))) {
2646			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2647			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2648			       __func__, ooa_hdr->alloc_len,
2649			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2650			retval = EINVAL;
2651			break;
2652		}
2653
2654		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2655		if (entries == NULL) {
2656			printf("%s: could not allocate %d bytes for OOA "
2657			       "dump\n", __func__, ooa_hdr->alloc_len);
2658			retval = ENOMEM;
2659			break;
2660		}
2661
2662		mtx_lock(&softc->ctl_lock);
2663		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2664		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2665		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2666			mtx_unlock(&softc->ctl_lock);
2667			free(entries, M_CTL);
2668			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2669			       __func__, (uintmax_t)ooa_hdr->lun_num);
2670			retval = EINVAL;
2671			break;
2672		}
2673
2674		cur_fill_num = 0;
2675
2676		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2677			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2678				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2679					ooa_hdr, entries);
2680				if (retval != 0)
2681					break;
2682			}
2683			if (retval != 0) {
2684				mtx_unlock(&softc->ctl_lock);
2685				free(entries, M_CTL);
2686				break;
2687			}
2688		} else {
2689			lun = softc->ctl_luns[ooa_hdr->lun_num];
2690
2691			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2692						    entries);
2693		}
2694		mtx_unlock(&softc->ctl_lock);
2695
2696		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2697		ooa_hdr->fill_len = ooa_hdr->fill_num *
2698			sizeof(struct ctl_ooa_entry);
2699		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2700		if (retval != 0) {
2701			printf("%s: error copying out %d bytes for OOA dump\n",
2702			       __func__, ooa_hdr->fill_len);
2703		}
2704
2705		getbintime(&ooa_hdr->cur_bt);
2706
2707		if (cur_fill_num > ooa_hdr->alloc_num) {
2708			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2709			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2710		} else {
2711			ooa_hdr->dropped_num = 0;
2712			ooa_hdr->status = CTL_OOA_OK;
2713		}
2714
2715		free(entries, M_CTL);
2716		break;
2717	}
2718	case CTL_CHECK_OOA: {
2719		union ctl_io *io;
2720		struct ctl_lun *lun;
2721		struct ctl_ooa_info *ooa_info;
2722
2723
2724		ooa_info = (struct ctl_ooa_info *)addr;
2725
2726		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2727			ooa_info->status = CTL_OOA_INVALID_LUN;
2728			break;
2729		}
2730		mtx_lock(&softc->ctl_lock);
2731		lun = softc->ctl_luns[ooa_info->lun_id];
2732		if (lun == NULL) {
2733			mtx_unlock(&softc->ctl_lock);
2734			ooa_info->status = CTL_OOA_INVALID_LUN;
2735			break;
2736		}
2737		mtx_lock(&lun->lun_lock);
2738		mtx_unlock(&softc->ctl_lock);
2739		ooa_info->num_entries = 0;
2740		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2741		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2742		     &io->io_hdr, ooa_links)) {
2743			ooa_info->num_entries++;
2744		}
2745		mtx_unlock(&lun->lun_lock);
2746
2747		ooa_info->status = CTL_OOA_SUCCESS;
2748
2749		break;
2750	}
2751	case CTL_HARD_START:
2752	case CTL_HARD_STOP: {
2753		struct ctl_fe_ioctl_startstop_info ss_info;
2754		struct cfi_metatask *metatask;
2755		struct mtx hs_mtx;
2756
2757		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2758
2759		cv_init(&ss_info.sem, "hard start/stop cv" );
2760
2761		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2762		if (metatask == NULL) {
2763			retval = ENOMEM;
2764			mtx_destroy(&hs_mtx);
2765			break;
2766		}
2767
2768		if (cmd == CTL_HARD_START)
2769			metatask->tasktype = CFI_TASK_STARTUP;
2770		else
2771			metatask->tasktype = CFI_TASK_SHUTDOWN;
2772
2773		metatask->callback = ctl_ioctl_hard_startstop_callback;
2774		metatask->callback_arg = &ss_info;
2775
2776		cfi_action(metatask);
2777
2778		/* Wait for the callback */
2779		mtx_lock(&hs_mtx);
2780		cv_wait_sig(&ss_info.sem, &hs_mtx);
2781		mtx_unlock(&hs_mtx);
2782
2783		/*
2784		 * All information has been copied from the metatask by the
2785		 * time cv_broadcast() is called, so we free the metatask here.
2786		 */
2787		cfi_free_metatask(metatask);
2788
2789		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2790
2791		mtx_destroy(&hs_mtx);
2792		break;
2793	}
2794	case CTL_BBRREAD: {
2795		struct ctl_bbrread_info *bbr_info;
2796		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2797		struct mtx bbr_mtx;
2798		struct cfi_metatask *metatask;
2799
2800		bbr_info = (struct ctl_bbrread_info *)addr;
2801
2802		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2803
2804		bzero(&bbr_mtx, sizeof(bbr_mtx));
2805		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2806
2807		fe_bbr_info.bbr_info = bbr_info;
2808		fe_bbr_info.lock = &bbr_mtx;
2809
2810		cv_init(&fe_bbr_info.sem, "BBR read cv");
2811		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2812
2813		if (metatask == NULL) {
2814			mtx_destroy(&bbr_mtx);
2815			cv_destroy(&fe_bbr_info.sem);
2816			retval = ENOMEM;
2817			break;
2818		}
2819		metatask->tasktype = CFI_TASK_BBRREAD;
2820		metatask->callback = ctl_ioctl_bbrread_callback;
2821		metatask->callback_arg = &fe_bbr_info;
2822		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2823		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2824		metatask->taskinfo.bbrread.len = bbr_info->len;
2825
2826		cfi_action(metatask);
2827
2828		mtx_lock(&bbr_mtx);
2829		while (fe_bbr_info.wakeup_done == 0)
2830			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2831		mtx_unlock(&bbr_mtx);
2832
2833		bbr_info->status = metatask->status;
2834		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2835		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2836		memcpy(&bbr_info->sense_data,
2837		       &metatask->taskinfo.bbrread.sense_data,
2838		       ctl_min(sizeof(bbr_info->sense_data),
2839			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2840
2841		cfi_free_metatask(metatask);
2842
2843		mtx_destroy(&bbr_mtx);
2844		cv_destroy(&fe_bbr_info.sem);
2845
2846		break;
2847	}
2848	case CTL_DELAY_IO: {
2849		struct ctl_io_delay_info *delay_info;
2850#ifdef CTL_IO_DELAY
2851		struct ctl_lun *lun;
2852#endif /* CTL_IO_DELAY */
2853
2854		delay_info = (struct ctl_io_delay_info *)addr;
2855
2856#ifdef CTL_IO_DELAY
2857		mtx_lock(&softc->ctl_lock);
2858
2859		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2860		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2861			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2862		} else {
2863			lun = softc->ctl_luns[delay_info->lun_id];
2864			mtx_lock(&lun->lun_lock);
2865
2866			delay_info->status = CTL_DELAY_STATUS_OK;
2867
2868			switch (delay_info->delay_type) {
2869			case CTL_DELAY_TYPE_CONT:
2870				break;
2871			case CTL_DELAY_TYPE_ONESHOT:
2872				break;
2873			default:
2874				delay_info->status =
2875					CTL_DELAY_STATUS_INVALID_TYPE;
2876				break;
2877			}
2878
2879			switch (delay_info->delay_loc) {
2880			case CTL_DELAY_LOC_DATAMOVE:
2881				lun->delay_info.datamove_type =
2882					delay_info->delay_type;
2883				lun->delay_info.datamove_delay =
2884					delay_info->delay_secs;
2885				break;
2886			case CTL_DELAY_LOC_DONE:
2887				lun->delay_info.done_type =
2888					delay_info->delay_type;
2889				lun->delay_info.done_delay =
2890					delay_info->delay_secs;
2891				break;
2892			default:
2893				delay_info->status =
2894					CTL_DELAY_STATUS_INVALID_LOC;
2895				break;
2896			}
2897			mtx_unlock(&lun->lun_lock);
2898		}
2899
2900		mtx_unlock(&softc->ctl_lock);
2901#else
2902		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2903#endif /* CTL_IO_DELAY */
2904		break;
2905	}
2906	case CTL_REALSYNC_SET: {
2907		int *syncstate;
2908
2909		syncstate = (int *)addr;
2910
2911		mtx_lock(&softc->ctl_lock);
2912		switch (*syncstate) {
2913		case 0:
2914			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2915			break;
2916		case 1:
2917			softc->flags |= CTL_FLAG_REAL_SYNC;
2918			break;
2919		default:
2920			retval = EINVAL;
2921			break;
2922		}
2923		mtx_unlock(&softc->ctl_lock);
2924		break;
2925	}
2926	case CTL_REALSYNC_GET: {
2927		int *syncstate;
2928
2929		syncstate = (int*)addr;
2930
2931		mtx_lock(&softc->ctl_lock);
2932		if (softc->flags & CTL_FLAG_REAL_SYNC)
2933			*syncstate = 1;
2934		else
2935			*syncstate = 0;
2936		mtx_unlock(&softc->ctl_lock);
2937
2938		break;
2939	}
2940	case CTL_SETSYNC:
2941	case CTL_GETSYNC: {
2942		struct ctl_sync_info *sync_info;
2943		struct ctl_lun *lun;
2944
2945		sync_info = (struct ctl_sync_info *)addr;
2946
2947		mtx_lock(&softc->ctl_lock);
2948		lun = softc->ctl_luns[sync_info->lun_id];
2949		if (lun == NULL) {
2950			mtx_unlock(&softc->ctl_lock);
2951			sync_info->status = CTL_GS_SYNC_NO_LUN;
2952		}
2953		/*
2954		 * Get or set the sync interval.  We're not bounds checking
2955		 * in the set case, hopefully the user won't do something
2956		 * silly.
2957		 */
2958		mtx_lock(&lun->lun_lock);
2959		mtx_unlock(&softc->ctl_lock);
2960		if (cmd == CTL_GETSYNC)
2961			sync_info->sync_interval = lun->sync_interval;
2962		else
2963			lun->sync_interval = sync_info->sync_interval;
2964		mtx_unlock(&lun->lun_lock);
2965
2966		sync_info->status = CTL_GS_SYNC_OK;
2967
2968		break;
2969	}
2970	case CTL_GETSTATS: {
2971		struct ctl_stats *stats;
2972		struct ctl_lun *lun;
2973		int i;
2974
2975		stats = (struct ctl_stats *)addr;
2976
2977		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2978		     stats->alloc_len) {
2979			stats->status = CTL_SS_NEED_MORE_SPACE;
2980			stats->num_luns = softc->num_luns;
2981			break;
2982		}
2983		/*
2984		 * XXX KDM no locking here.  If the LUN list changes,
2985		 * things can blow up.
2986		 */
2987		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2988		     i++, lun = STAILQ_NEXT(lun, links)) {
2989			retval = copyout(&lun->stats, &stats->lun_stats[i],
2990					 sizeof(lun->stats));
2991			if (retval != 0)
2992				break;
2993		}
2994		stats->num_luns = softc->num_luns;
2995		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2996				 softc->num_luns;
2997		stats->status = CTL_SS_OK;
2998#ifdef CTL_TIME_IO
2999		stats->flags = CTL_STATS_FLAG_TIME_VALID;
3000#else
3001		stats->flags = CTL_STATS_FLAG_NONE;
3002#endif
3003		getnanouptime(&stats->timestamp);
3004		break;
3005	}
3006	case CTL_ERROR_INJECT: {
3007		struct ctl_error_desc *err_desc, *new_err_desc;
3008		struct ctl_lun *lun;
3009
3010		err_desc = (struct ctl_error_desc *)addr;
3011
3012		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3013				      M_WAITOK | M_ZERO);
3014		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3015
3016		mtx_lock(&softc->ctl_lock);
3017		lun = softc->ctl_luns[err_desc->lun_id];
3018		if (lun == NULL) {
3019			mtx_unlock(&softc->ctl_lock);
3020			free(new_err_desc, M_CTL);
3021			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3022			       __func__, (uintmax_t)err_desc->lun_id);
3023			retval = EINVAL;
3024			break;
3025		}
3026		mtx_lock(&lun->lun_lock);
3027		mtx_unlock(&softc->ctl_lock);
3028
3029		/*
3030		 * We could do some checking here to verify the validity
3031		 * of the request, but given the complexity of error
3032		 * injection requests, the checking logic would be fairly
3033		 * complex.
3034		 *
3035		 * For now, if the request is invalid, it just won't get
3036		 * executed and might get deleted.
3037		 */
3038		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3039
3040		/*
3041		 * XXX KDM check to make sure the serial number is unique,
3042		 * in case we somehow manage to wrap.  That shouldn't
3043		 * happen for a very long time, but it's the right thing to
3044		 * do.
3045		 */
3046		new_err_desc->serial = lun->error_serial;
3047		err_desc->serial = lun->error_serial;
3048		lun->error_serial++;
3049
3050		mtx_unlock(&lun->lun_lock);
3051		break;
3052	}
3053	case CTL_ERROR_INJECT_DELETE: {
3054		struct ctl_error_desc *delete_desc, *desc, *desc2;
3055		struct ctl_lun *lun;
3056		int delete_done;
3057
3058		delete_desc = (struct ctl_error_desc *)addr;
3059		delete_done = 0;
3060
3061		mtx_lock(&softc->ctl_lock);
3062		lun = softc->ctl_luns[delete_desc->lun_id];
3063		if (lun == NULL) {
3064			mtx_unlock(&softc->ctl_lock);
3065			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3066			       __func__, (uintmax_t)delete_desc->lun_id);
3067			retval = EINVAL;
3068			break;
3069		}
3070		mtx_lock(&lun->lun_lock);
3071		mtx_unlock(&softc->ctl_lock);
3072		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3073			if (desc->serial != delete_desc->serial)
3074				continue;
3075
3076			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3077				      links);
3078			free(desc, M_CTL);
3079			delete_done = 1;
3080		}
3081		mtx_unlock(&lun->lun_lock);
3082		if (delete_done == 0) {
3083			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3084			       "error serial %ju on LUN %u\n", __func__,
3085			       delete_desc->serial, delete_desc->lun_id);
3086			retval = EINVAL;
3087			break;
3088		}
3089		break;
3090	}
3091	case CTL_DUMP_STRUCTS: {
3092		int i, j, k;
3093		struct ctl_port *port;
3094		struct ctl_frontend *fe;
3095
3096		mtx_lock(&softc->ctl_lock);
3097		printf("CTL Persistent Reservation information start:\n");
3098		for (i = 0; i < CTL_MAX_LUNS; i++) {
3099			struct ctl_lun *lun;
3100
3101			lun = softc->ctl_luns[i];
3102
3103			if ((lun == NULL)
3104			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3105				continue;
3106
3107			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3108				if (lun->pr_keys[j] == NULL)
3109					continue;
3110				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3111					if (lun->pr_keys[j][k] == 0)
3112						continue;
3113					printf("  LUN %d port %d iid %d key "
3114					       "%#jx\n", i, j, k,
3115					       (uintmax_t)lun->pr_keys[j][k]);
3116				}
3117			}
3118		}
3119		printf("CTL Persistent Reservation information end\n");
3120		printf("CTL Ports:\n");
3121		STAILQ_FOREACH(port, &softc->port_list, links) {
3122			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3123			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3124			       port->frontend->name, port->port_type,
3125			       port->physical_port, port->virtual_port,
3126			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3127			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3128				if (port->wwpn_iid[j].in_use == 0 &&
3129				    port->wwpn_iid[j].wwpn == 0 &&
3130				    port->wwpn_iid[j].name == NULL)
3131					continue;
3132
3133				printf("    iid %u use %d WWPN %#jx '%s'\n",
3134				    j, port->wwpn_iid[j].in_use,
3135				    (uintmax_t)port->wwpn_iid[j].wwpn,
3136				    port->wwpn_iid[j].name);
3137			}
3138		}
3139		printf("CTL Port information end\n");
3140		mtx_unlock(&softc->ctl_lock);
3141		/*
3142		 * XXX KDM calling this without a lock.  We'd likely want
3143		 * to drop the lock before calling the frontend's dump
3144		 * routine anyway.
3145		 */
3146		printf("CTL Frontends:\n");
3147		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3148			printf("  Frontend '%s'\n", fe->name);
3149			if (fe->fe_dump != NULL)
3150				fe->fe_dump();
3151		}
3152		printf("CTL Frontend information end\n");
3153		break;
3154	}
3155	case CTL_LUN_REQ: {
3156		struct ctl_lun_req *lun_req;
3157		struct ctl_backend_driver *backend;
3158
3159		lun_req = (struct ctl_lun_req *)addr;
3160
3161		backend = ctl_backend_find(lun_req->backend);
3162		if (backend == NULL) {
3163			lun_req->status = CTL_LUN_ERROR;
3164			snprintf(lun_req->error_str,
3165				 sizeof(lun_req->error_str),
3166				 "Backend \"%s\" not found.",
3167				 lun_req->backend);
3168			break;
3169		}
3170		if (lun_req->num_be_args > 0) {
3171			lun_req->kern_be_args = ctl_copyin_args(
3172				lun_req->num_be_args,
3173				lun_req->be_args,
3174				lun_req->error_str,
3175				sizeof(lun_req->error_str));
3176			if (lun_req->kern_be_args == NULL) {
3177				lun_req->status = CTL_LUN_ERROR;
3178				break;
3179			}
3180		}
3181
3182		retval = backend->ioctl(dev, cmd, addr, flag, td);
3183
3184		if (lun_req->num_be_args > 0) {
3185			ctl_copyout_args(lun_req->num_be_args,
3186				      lun_req->kern_be_args);
3187			ctl_free_args(lun_req->num_be_args,
3188				      lun_req->kern_be_args);
3189		}
3190		break;
3191	}
3192	case CTL_LUN_LIST: {
3193		struct sbuf *sb;
3194		struct ctl_lun *lun;
3195		struct ctl_lun_list *list;
3196		struct ctl_option *opt;
3197
3198		list = (struct ctl_lun_list *)addr;
3199
3200		/*
3201		 * Allocate a fixed length sbuf here, based on the length
3202		 * of the user's buffer.  We could allocate an auto-extending
3203		 * buffer, and then tell the user how much larger our
3204		 * amount of data is than his buffer, but that presents
3205		 * some problems:
3206		 *
3207		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3208		 *     we can't hold a lock while calling them with an
3209		 *     auto-extending buffer.
3210 		 *
3211		 * 2.  There is not currently a LUN reference counting
3212		 *     mechanism, outside of outstanding transactions on
3213		 *     the LUN's OOA queue.  So a LUN could go away on us
3214		 *     while we're getting the LUN number, backend-specific
3215		 *     information, etc.  Thus, given the way things
3216		 *     currently work, we need to hold the CTL lock while
3217		 *     grabbing LUN information.
3218		 *
3219		 * So, from the user's standpoint, the best thing to do is
3220		 * allocate what he thinks is a reasonable buffer length,
3221		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3222		 * double the buffer length and try again.  (And repeat
3223		 * that until he succeeds.)
3224		 */
3225		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3226		if (sb == NULL) {
3227			list->status = CTL_LUN_LIST_ERROR;
3228			snprintf(list->error_str, sizeof(list->error_str),
3229				 "Unable to allocate %d bytes for LUN list",
3230				 list->alloc_len);
3231			break;
3232		}
3233
3234		sbuf_printf(sb, "<ctllunlist>\n");
3235
3236		mtx_lock(&softc->ctl_lock);
3237		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3238			mtx_lock(&lun->lun_lock);
3239			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3240					     (uintmax_t)lun->lun);
3241
3242			/*
3243			 * Bail out as soon as we see that we've overfilled
3244			 * the buffer.
3245			 */
3246			if (retval != 0)
3247				break;
3248
3249			retval = sbuf_printf(sb, "\t<backend_type>%s"
3250					     "</backend_type>\n",
3251					     (lun->backend == NULL) ?  "none" :
3252					     lun->backend->name);
3253
3254			if (retval != 0)
3255				break;
3256
3257			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3258					     lun->be_lun->lun_type);
3259
3260			if (retval != 0)
3261				break;
3262
3263			if (lun->backend == NULL) {
3264				retval = sbuf_printf(sb, "</lun>\n");
3265				if (retval != 0)
3266					break;
3267				continue;
3268			}
3269
3270			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3271					     (lun->be_lun->maxlba > 0) ?
3272					     lun->be_lun->maxlba + 1 : 0);
3273
3274			if (retval != 0)
3275				break;
3276
3277			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3278					     lun->be_lun->blocksize);
3279
3280			if (retval != 0)
3281				break;
3282
3283			retval = sbuf_printf(sb, "\t<serial_number>");
3284
3285			if (retval != 0)
3286				break;
3287
3288			retval = ctl_sbuf_printf_esc(sb,
3289			    lun->be_lun->serial_num,
3290			    sizeof(lun->be_lun->serial_num));
3291
3292			if (retval != 0)
3293				break;
3294
3295			retval = sbuf_printf(sb, "</serial_number>\n");
3296
3297			if (retval != 0)
3298				break;
3299
3300			retval = sbuf_printf(sb, "\t<device_id>");
3301
3302			if (retval != 0)
3303				break;
3304
3305			retval = ctl_sbuf_printf_esc(sb,
3306			    lun->be_lun->device_id,
3307			    sizeof(lun->be_lun->device_id));
3308
3309			if (retval != 0)
3310				break;
3311
3312			retval = sbuf_printf(sb, "</device_id>\n");
3313
3314			if (retval != 0)
3315				break;
3316
3317			if (lun->backend->lun_info != NULL) {
3318				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3319				if (retval != 0)
3320					break;
3321			}
3322			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3323				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3324				    opt->name, opt->value, opt->name);
3325				if (retval != 0)
3326					break;
3327			}
3328
3329			retval = sbuf_printf(sb, "</lun>\n");
3330
3331			if (retval != 0)
3332				break;
3333			mtx_unlock(&lun->lun_lock);
3334		}
3335		if (lun != NULL)
3336			mtx_unlock(&lun->lun_lock);
3337		mtx_unlock(&softc->ctl_lock);
3338
3339		if ((retval != 0)
3340		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3341			retval = 0;
3342			sbuf_delete(sb);
3343			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3344			snprintf(list->error_str, sizeof(list->error_str),
3345				 "Out of space, %d bytes is too small",
3346				 list->alloc_len);
3347			break;
3348		}
3349
3350		sbuf_finish(sb);
3351
3352		retval = copyout(sbuf_data(sb), list->lun_xml,
3353				 sbuf_len(sb) + 1);
3354
3355		list->fill_len = sbuf_len(sb) + 1;
3356		list->status = CTL_LUN_LIST_OK;
3357		sbuf_delete(sb);
3358		break;
3359	}
3360	case CTL_ISCSI: {
3361		struct ctl_iscsi *ci;
3362		struct ctl_frontend *fe;
3363
3364		ci = (struct ctl_iscsi *)addr;
3365
3366		fe = ctl_frontend_find("iscsi");
3367		if (fe == NULL) {
3368			ci->status = CTL_ISCSI_ERROR;
3369			snprintf(ci->error_str, sizeof(ci->error_str),
3370			    "Frontend \"iscsi\" not found.");
3371			break;
3372		}
3373
3374		retval = fe->ioctl(dev, cmd, addr, flag, td);
3375		break;
3376	}
3377	case CTL_PORT_REQ: {
3378		struct ctl_req *req;
3379		struct ctl_frontend *fe;
3380
3381		req = (struct ctl_req *)addr;
3382
3383		fe = ctl_frontend_find(req->driver);
3384		if (fe == NULL) {
3385			req->status = CTL_LUN_ERROR;
3386			snprintf(req->error_str, sizeof(req->error_str),
3387			    "Frontend \"%s\" not found.", req->driver);
3388			break;
3389		}
3390		if (req->num_args > 0) {
3391			req->kern_args = ctl_copyin_args(req->num_args,
3392			    req->args, req->error_str, sizeof(req->error_str));
3393			if (req->kern_args == NULL) {
3394				req->status = CTL_LUN_ERROR;
3395				break;
3396			}
3397		}
3398
3399		retval = fe->ioctl(dev, cmd, addr, flag, td);
3400
3401		if (req->num_args > 0) {
3402			ctl_copyout_args(req->num_args, req->kern_args);
3403			ctl_free_args(req->num_args, req->kern_args);
3404		}
3405		break;
3406	}
3407	case CTL_PORT_LIST: {
3408		struct sbuf *sb;
3409		struct ctl_port *port;
3410		struct ctl_lun_list *list;
3411		struct ctl_option *opt;
3412		int j;
3413
3414		list = (struct ctl_lun_list *)addr;
3415
3416		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3417		if (sb == NULL) {
3418			list->status = CTL_LUN_LIST_ERROR;
3419			snprintf(list->error_str, sizeof(list->error_str),
3420				 "Unable to allocate %d bytes for LUN list",
3421				 list->alloc_len);
3422			break;
3423		}
3424
3425		sbuf_printf(sb, "<ctlportlist>\n");
3426
3427		mtx_lock(&softc->ctl_lock);
3428		STAILQ_FOREACH(port, &softc->port_list, links) {
3429			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3430					     (uintmax_t)port->targ_port);
3431
3432			/*
3433			 * Bail out as soon as we see that we've overfilled
3434			 * the buffer.
3435			 */
3436			if (retval != 0)
3437				break;
3438
3439			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3440			    "</frontend_type>\n", port->frontend->name);
3441			if (retval != 0)
3442				break;
3443
3444			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3445					     port->port_type);
3446			if (retval != 0)
3447				break;
3448
3449			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3450			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3451			if (retval != 0)
3452				break;
3453
3454			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3455			    port->port_name);
3456			if (retval != 0)
3457				break;
3458
3459			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3460			    port->physical_port);
3461			if (retval != 0)
3462				break;
3463
3464			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3465			    port->virtual_port);
3466			if (retval != 0)
3467				break;
3468
3469			if (port->target_devid != NULL) {
3470				sbuf_printf(sb, "\t<target>");
3471				ctl_id_sbuf(port->target_devid, sb);
3472				sbuf_printf(sb, "</target>\n");
3473			}
3474
3475			if (port->port_devid != NULL) {
3476				sbuf_printf(sb, "\t<port>");
3477				ctl_id_sbuf(port->port_devid, sb);
3478				sbuf_printf(sb, "</port>\n");
3479			}
3480
3481			if (port->port_info != NULL) {
3482				retval = port->port_info(port->onoff_arg, sb);
3483				if (retval != 0)
3484					break;
3485			}
3486			STAILQ_FOREACH(opt, &port->options, links) {
3487				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3488				    opt->name, opt->value, opt->name);
3489				if (retval != 0)
3490					break;
3491			}
3492
3493			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3494				if (port->wwpn_iid[j].in_use == 0 ||
3495				    (port->wwpn_iid[j].wwpn == 0 &&
3496				     port->wwpn_iid[j].name == NULL))
3497					continue;
3498
3499				if (port->wwpn_iid[j].name != NULL)
3500					retval = sbuf_printf(sb,
3501					    "\t<initiator>%u %s</initiator>\n",
3502					    j, port->wwpn_iid[j].name);
3503				else
3504					retval = sbuf_printf(sb,
3505					    "\t<initiator>%u naa.%08jx</initiator>\n",
3506					    j, port->wwpn_iid[j].wwpn);
3507				if (retval != 0)
3508					break;
3509			}
3510			if (retval != 0)
3511				break;
3512
3513			retval = sbuf_printf(sb, "</targ_port>\n");
3514			if (retval != 0)
3515				break;
3516		}
3517		mtx_unlock(&softc->ctl_lock);
3518
3519		if ((retval != 0)
3520		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3521			retval = 0;
3522			sbuf_delete(sb);
3523			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3524			snprintf(list->error_str, sizeof(list->error_str),
3525				 "Out of space, %d bytes is too small",
3526				 list->alloc_len);
3527			break;
3528		}
3529
3530		sbuf_finish(sb);
3531
3532		retval = copyout(sbuf_data(sb), list->lun_xml,
3533				 sbuf_len(sb) + 1);
3534
3535		list->fill_len = sbuf_len(sb) + 1;
3536		list->status = CTL_LUN_LIST_OK;
3537		sbuf_delete(sb);
3538		break;
3539	}
3540	default: {
3541		/* XXX KDM should we fix this? */
3542#if 0
3543		struct ctl_backend_driver *backend;
3544		unsigned int type;
3545		int found;
3546
3547		found = 0;
3548
3549		/*
3550		 * We encode the backend type as the ioctl type for backend
3551		 * ioctls.  So parse it out here, and then search for a
3552		 * backend of this type.
3553		 */
3554		type = _IOC_TYPE(cmd);
3555
3556		STAILQ_FOREACH(backend, &softc->be_list, links) {
3557			if (backend->type == type) {
3558				found = 1;
3559				break;
3560			}
3561		}
3562		if (found == 0) {
3563			printf("ctl: unknown ioctl command %#lx or backend "
3564			       "%d\n", cmd, type);
3565			retval = EINVAL;
3566			break;
3567		}
3568		retval = backend->ioctl(dev, cmd, addr, flag, td);
3569#endif
3570		retval = ENOTTY;
3571		break;
3572	}
3573	}
3574	return (retval);
3575}
3576
3577uint32_t
3578ctl_get_initindex(struct ctl_nexus *nexus)
3579{
3580	if (nexus->targ_port < CTL_MAX_PORTS)
3581		return (nexus->initid.id +
3582			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3583	else
3584		return (nexus->initid.id +
3585		       ((nexus->targ_port - CTL_MAX_PORTS) *
3586			CTL_MAX_INIT_PER_PORT));
3587}
3588
3589uint32_t
3590ctl_get_resindex(struct ctl_nexus *nexus)
3591{
3592	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3593}
3594
3595uint32_t
3596ctl_port_idx(int port_num)
3597{
3598	if (port_num < CTL_MAX_PORTS)
3599		return(port_num);
3600	else
3601		return(port_num - CTL_MAX_PORTS);
3602}
3603
3604static uint32_t
3605ctl_map_lun(int port_num, uint32_t lun_id)
3606{
3607	struct ctl_port *port;
3608
3609	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3610	if (port == NULL)
3611		return (UINT32_MAX);
3612	if (port->lun_map == NULL)
3613		return (lun_id);
3614	return (port->lun_map(port->targ_lun_arg, lun_id));
3615}
3616
3617static uint32_t
3618ctl_map_lun_back(int port_num, uint32_t lun_id)
3619{
3620	struct ctl_port *port;
3621	uint32_t i;
3622
3623	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3624	if (port->lun_map == NULL)
3625		return (lun_id);
3626	for (i = 0; i < CTL_MAX_LUNS; i++) {
3627		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3628			return (i);
3629	}
3630	return (UINT32_MAX);
3631}
3632
3633/*
3634 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3635 * that are a power of 2.
3636 */
3637int
3638ctl_ffz(uint32_t *mask, uint32_t size)
3639{
3640	uint32_t num_chunks, num_pieces;
3641	int i, j;
3642
3643	num_chunks = (size >> 5);
3644	if (num_chunks == 0)
3645		num_chunks++;
3646	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3647
3648	for (i = 0; i < num_chunks; i++) {
3649		for (j = 0; j < num_pieces; j++) {
3650			if ((mask[i] & (1 << j)) == 0)
3651				return ((i << 5) + j);
3652		}
3653	}
3654
3655	return (-1);
3656}
3657
3658int
3659ctl_set_mask(uint32_t *mask, uint32_t bit)
3660{
3661	uint32_t chunk, piece;
3662
3663	chunk = bit >> 5;
3664	piece = bit % (sizeof(uint32_t) * 8);
3665
3666	if ((mask[chunk] & (1 << piece)) != 0)
3667		return (-1);
3668	else
3669		mask[chunk] |= (1 << piece);
3670
3671	return (0);
3672}
3673
3674int
3675ctl_clear_mask(uint32_t *mask, uint32_t bit)
3676{
3677	uint32_t chunk, piece;
3678
3679	chunk = bit >> 5;
3680	piece = bit % (sizeof(uint32_t) * 8);
3681
3682	if ((mask[chunk] & (1 << piece)) == 0)
3683		return (-1);
3684	else
3685		mask[chunk] &= ~(1 << piece);
3686
3687	return (0);
3688}
3689
3690int
3691ctl_is_set(uint32_t *mask, uint32_t bit)
3692{
3693	uint32_t chunk, piece;
3694
3695	chunk = bit >> 5;
3696	piece = bit % (sizeof(uint32_t) * 8);
3697
3698	if ((mask[chunk] & (1 << piece)) == 0)
3699		return (0);
3700	else
3701		return (1);
3702}
3703
3704static uint64_t
3705ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3706{
3707	uint64_t *t;
3708
3709	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3710	if (t == NULL)
3711		return (0);
3712	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3713}
3714
3715static void
3716ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3717{
3718	uint64_t *t;
3719
3720	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3721	if (t == NULL)
3722		return;
3723	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3724}
3725
3726static void
3727ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3728{
3729	uint64_t *p;
3730	u_int i;
3731
3732	i = residx/CTL_MAX_INIT_PER_PORT;
3733	if (lun->pr_keys[i] != NULL)
3734		return;
3735	mtx_unlock(&lun->lun_lock);
3736	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3737	    M_WAITOK | M_ZERO);
3738	mtx_lock(&lun->lun_lock);
3739	if (lun->pr_keys[i] == NULL)
3740		lun->pr_keys[i] = p;
3741	else
3742		free(p, M_CTL);
3743}
3744
3745static void
3746ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3747{
3748	uint64_t *t;
3749
3750	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3751	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3752	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3753}
3754
3755/*
3756 * ctl_softc, pool_name, total_ctl_io are passed in.
3757 * npool is passed out.
3758 */
3759int
3760ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3761		uint32_t total_ctl_io, void **npool)
3762{
3763#ifdef IO_POOLS
3764	struct ctl_io_pool *pool;
3765
3766	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3767					    M_NOWAIT | M_ZERO);
3768	if (pool == NULL)
3769		return (ENOMEM);
3770
3771	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3772	pool->ctl_softc = ctl_softc;
3773	pool->zone = uma_zsecond_create(pool->name, NULL,
3774	    NULL, NULL, NULL, ctl_softc->io_zone);
3775	/* uma_prealloc(pool->zone, total_ctl_io); */
3776
3777	*npool = pool;
3778#else
3779	*npool = ctl_softc->io_zone;
3780#endif
3781	return (0);
3782}
3783
3784void
3785ctl_pool_free(struct ctl_io_pool *pool)
3786{
3787
3788	if (pool == NULL)
3789		return;
3790
3791#ifdef IO_POOLS
3792	uma_zdestroy(pool->zone);
3793	free(pool, M_CTL);
3794#endif
3795}
3796
3797union ctl_io *
3798ctl_alloc_io(void *pool_ref)
3799{
3800	union ctl_io *io;
3801#ifdef IO_POOLS
3802	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3803
3804	io = uma_zalloc(pool->zone, M_WAITOK);
3805#else
3806	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3807#endif
3808	if (io != NULL)
3809		io->io_hdr.pool = pool_ref;
3810	return (io);
3811}
3812
3813union ctl_io *
3814ctl_alloc_io_nowait(void *pool_ref)
3815{
3816	union ctl_io *io;
3817#ifdef IO_POOLS
3818	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3819
3820	io = uma_zalloc(pool->zone, M_NOWAIT);
3821#else
3822	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3823#endif
3824	if (io != NULL)
3825		io->io_hdr.pool = pool_ref;
3826	return (io);
3827}
3828
3829void
3830ctl_free_io(union ctl_io *io)
3831{
3832#ifdef IO_POOLS
3833	struct ctl_io_pool *pool;
3834#endif
3835
3836	if (io == NULL)
3837		return;
3838
3839#ifdef IO_POOLS
3840	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3841	uma_zfree(pool->zone, io);
3842#else
3843	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3844#endif
3845}
3846
3847void
3848ctl_zero_io(union ctl_io *io)
3849{
3850	void *pool_ref;
3851
3852	if (io == NULL)
3853		return;
3854
3855	/*
3856	 * May need to preserve linked list pointers at some point too.
3857	 */
3858	pool_ref = io->io_hdr.pool;
3859	memset(io, 0, sizeof(*io));
3860	io->io_hdr.pool = pool_ref;
3861}
3862
3863/*
3864 * This routine is currently used for internal copies of ctl_ios that need
3865 * to persist for some reason after we've already returned status to the
3866 * FETD.  (Thus the flag set.)
3867 *
3868 * XXX XXX
3869 * Note that this makes a blind copy of all fields in the ctl_io, except
3870 * for the pool reference.  This includes any memory that has been
3871 * allocated!  That memory will no longer be valid after done has been
3872 * called, so this would be VERY DANGEROUS for command that actually does
3873 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3874 * start and stop commands, which don't transfer any data, so this is not a
3875 * problem.  If it is used for anything else, the caller would also need to
3876 * allocate data buffer space and this routine would need to be modified to
3877 * copy the data buffer(s) as well.
3878 */
3879void
3880ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3881{
3882	void *pool_ref;
3883
3884	if ((src == NULL)
3885	 || (dest == NULL))
3886		return;
3887
3888	/*
3889	 * May need to preserve linked list pointers at some point too.
3890	 */
3891	pool_ref = dest->io_hdr.pool;
3892
3893	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3894
3895	dest->io_hdr.pool = pool_ref;
3896	/*
3897	 * We need to know that this is an internal copy, and doesn't need
3898	 * to get passed back to the FETD that allocated it.
3899	 */
3900	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3901}
3902
3903static int
3904ctl_expand_number(const char *buf, uint64_t *num)
3905{
3906	char *endptr;
3907	uint64_t number;
3908	unsigned shift;
3909
3910	number = strtoq(buf, &endptr, 0);
3911
3912	switch (tolower((unsigned char)*endptr)) {
3913	case 'e':
3914		shift = 60;
3915		break;
3916	case 'p':
3917		shift = 50;
3918		break;
3919	case 't':
3920		shift = 40;
3921		break;
3922	case 'g':
3923		shift = 30;
3924		break;
3925	case 'm':
3926		shift = 20;
3927		break;
3928	case 'k':
3929		shift = 10;
3930		break;
3931	case 'b':
3932	case '\0': /* No unit. */
3933		*num = number;
3934		return (0);
3935	default:
3936		/* Unrecognized unit. */
3937		return (-1);
3938	}
3939
3940	if ((number << shift) >> shift != number) {
3941		/* Overflow */
3942		return (-1);
3943	}
3944	*num = number << shift;
3945	return (0);
3946}
3947
3948
3949/*
3950 * This routine could be used in the future to load default and/or saved
3951 * mode page parameters for a particuar lun.
3952 */
3953static int
3954ctl_init_page_index(struct ctl_lun *lun)
3955{
3956	int i;
3957	struct ctl_page_index *page_index;
3958	const char *value;
3959	uint64_t ival;
3960
3961	memcpy(&lun->mode_pages.index, page_index_template,
3962	       sizeof(page_index_template));
3963
3964	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3965
3966		page_index = &lun->mode_pages.index[i];
3967		/*
3968		 * If this is a disk-only mode page, there's no point in
3969		 * setting it up.  For some pages, we have to have some
3970		 * basic information about the disk in order to calculate the
3971		 * mode page data.
3972		 */
3973		if ((lun->be_lun->lun_type != T_DIRECT)
3974		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3975			continue;
3976
3977		switch (page_index->page_code & SMPH_PC_MASK) {
3978		case SMS_RW_ERROR_RECOVERY_PAGE: {
3979			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3980				panic("subpage is incorrect!");
3981			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3982			       &rw_er_page_default,
3983			       sizeof(rw_er_page_default));
3984			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3985			       &rw_er_page_changeable,
3986			       sizeof(rw_er_page_changeable));
3987			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3988			       &rw_er_page_default,
3989			       sizeof(rw_er_page_default));
3990			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3991			       &rw_er_page_default,
3992			       sizeof(rw_er_page_default));
3993			page_index->page_data =
3994				(uint8_t *)lun->mode_pages.rw_er_page;
3995			break;
3996		}
3997		case SMS_FORMAT_DEVICE_PAGE: {
3998			struct scsi_format_page *format_page;
3999
4000			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4001				panic("subpage is incorrect!");
4002
4003			/*
4004			 * Sectors per track are set above.  Bytes per
4005			 * sector need to be set here on a per-LUN basis.
4006			 */
4007			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4008			       &format_page_default,
4009			       sizeof(format_page_default));
4010			memcpy(&lun->mode_pages.format_page[
4011			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4012			       sizeof(format_page_changeable));
4013			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4014			       &format_page_default,
4015			       sizeof(format_page_default));
4016			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4017			       &format_page_default,
4018			       sizeof(format_page_default));
4019
4020			format_page = &lun->mode_pages.format_page[
4021				CTL_PAGE_CURRENT];
4022			scsi_ulto2b(lun->be_lun->blocksize,
4023				    format_page->bytes_per_sector);
4024
4025			format_page = &lun->mode_pages.format_page[
4026				CTL_PAGE_DEFAULT];
4027			scsi_ulto2b(lun->be_lun->blocksize,
4028				    format_page->bytes_per_sector);
4029
4030			format_page = &lun->mode_pages.format_page[
4031				CTL_PAGE_SAVED];
4032			scsi_ulto2b(lun->be_lun->blocksize,
4033				    format_page->bytes_per_sector);
4034
4035			page_index->page_data =
4036				(uint8_t *)lun->mode_pages.format_page;
4037			break;
4038		}
4039		case SMS_RIGID_DISK_PAGE: {
4040			struct scsi_rigid_disk_page *rigid_disk_page;
4041			uint32_t sectors_per_cylinder;
4042			uint64_t cylinders;
4043#ifndef	__XSCALE__
4044			int shift;
4045#endif /* !__XSCALE__ */
4046
4047			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4048				panic("invalid subpage value %d",
4049				      page_index->subpage);
4050
4051			/*
4052			 * Rotation rate and sectors per track are set
4053			 * above.  We calculate the cylinders here based on
4054			 * capacity.  Due to the number of heads and
4055			 * sectors per track we're using, smaller arrays
4056			 * may turn out to have 0 cylinders.  Linux and
4057			 * FreeBSD don't pay attention to these mode pages
4058			 * to figure out capacity, but Solaris does.  It
4059			 * seems to deal with 0 cylinders just fine, and
4060			 * works out a fake geometry based on the capacity.
4061			 */
4062			memcpy(&lun->mode_pages.rigid_disk_page[
4063			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4064			       sizeof(rigid_disk_page_default));
4065			memcpy(&lun->mode_pages.rigid_disk_page[
4066			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4067			       sizeof(rigid_disk_page_changeable));
4068
4069			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4070				CTL_DEFAULT_HEADS;
4071
4072			/*
4073			 * The divide method here will be more accurate,
4074			 * probably, but results in floating point being
4075			 * used in the kernel on i386 (__udivdi3()).  On the
4076			 * XScale, though, __udivdi3() is implemented in
4077			 * software.
4078			 *
4079			 * The shift method for cylinder calculation is
4080			 * accurate if sectors_per_cylinder is a power of
4081			 * 2.  Otherwise it might be slightly off -- you
4082			 * might have a bit of a truncation problem.
4083			 */
4084#ifdef	__XSCALE__
4085			cylinders = (lun->be_lun->maxlba + 1) /
4086				sectors_per_cylinder;
4087#else
4088			for (shift = 31; shift > 0; shift--) {
4089				if (sectors_per_cylinder & (1 << shift))
4090					break;
4091			}
4092			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4093#endif
4094
4095			/*
4096			 * We've basically got 3 bytes, or 24 bits for the
4097			 * cylinder size in the mode page.  If we're over,
4098			 * just round down to 2^24.
4099			 */
4100			if (cylinders > 0xffffff)
4101				cylinders = 0xffffff;
4102
4103			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4104				CTL_PAGE_DEFAULT];
4105			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4106
4107			if ((value = ctl_get_opt(&lun->be_lun->options,
4108			    "rpm")) != NULL) {
4109				scsi_ulto2b(strtol(value, NULL, 0),
4110				     rigid_disk_page->rotation_rate);
4111			}
4112
4113			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4114			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4115			       sizeof(rigid_disk_page_default));
4116			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4117			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4118			       sizeof(rigid_disk_page_default));
4119
4120			page_index->page_data =
4121				(uint8_t *)lun->mode_pages.rigid_disk_page;
4122			break;
4123		}
4124		case SMS_CACHING_PAGE: {
4125			struct scsi_caching_page *caching_page;
4126
4127			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4128				panic("invalid subpage value %d",
4129				      page_index->subpage);
4130			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4131			       &caching_page_default,
4132			       sizeof(caching_page_default));
4133			memcpy(&lun->mode_pages.caching_page[
4134			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4135			       sizeof(caching_page_changeable));
4136			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4137			       &caching_page_default,
4138			       sizeof(caching_page_default));
4139			caching_page = &lun->mode_pages.caching_page[
4140			    CTL_PAGE_SAVED];
4141			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4142			if (value != NULL && strcmp(value, "off") == 0)
4143				caching_page->flags1 &= ~SCP_WCE;
4144			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4145			if (value != NULL && strcmp(value, "off") == 0)
4146				caching_page->flags1 |= SCP_RCD;
4147			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4148			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4149			       sizeof(caching_page_default));
4150			page_index->page_data =
4151				(uint8_t *)lun->mode_pages.caching_page;
4152			break;
4153		}
4154		case SMS_CONTROL_MODE_PAGE: {
4155			struct scsi_control_page *control_page;
4156
4157			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4158				panic("invalid subpage value %d",
4159				      page_index->subpage);
4160
4161			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4162			       &control_page_default,
4163			       sizeof(control_page_default));
4164			memcpy(&lun->mode_pages.control_page[
4165			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4166			       sizeof(control_page_changeable));
4167			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4168			       &control_page_default,
4169			       sizeof(control_page_default));
4170			control_page = &lun->mode_pages.control_page[
4171			    CTL_PAGE_SAVED];
4172			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4173			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4174				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4175				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4176			}
4177			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4178			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4179			       sizeof(control_page_default));
4180			page_index->page_data =
4181				(uint8_t *)lun->mode_pages.control_page;
4182			break;
4183
4184		}
4185		case SMS_INFO_EXCEPTIONS_PAGE: {
4186			switch (page_index->subpage) {
4187			case SMS_SUBPAGE_PAGE_0:
4188				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4189				       &ie_page_default,
4190				       sizeof(ie_page_default));
4191				memcpy(&lun->mode_pages.ie_page[
4192				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4193				       sizeof(ie_page_changeable));
4194				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4195				       &ie_page_default,
4196				       sizeof(ie_page_default));
4197				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4198				       &ie_page_default,
4199				       sizeof(ie_page_default));
4200				page_index->page_data =
4201					(uint8_t *)lun->mode_pages.ie_page;
4202				break;
4203			case 0x02: {
4204				struct ctl_logical_block_provisioning_page *page;
4205
4206				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4207				       &lbp_page_default,
4208				       sizeof(lbp_page_default));
4209				memcpy(&lun->mode_pages.lbp_page[
4210				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4211				       sizeof(lbp_page_changeable));
4212				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4213				       &lbp_page_default,
4214				       sizeof(lbp_page_default));
4215				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4216				value = ctl_get_opt(&lun->be_lun->options,
4217				    "avail-threshold");
4218				if (value != NULL &&
4219				    ctl_expand_number(value, &ival) == 0) {
4220					page->descr[0].flags |= SLBPPD_ENABLED |
4221					    SLBPPD_ARMING_DEC;
4222					if (lun->be_lun->blocksize)
4223						ival /= lun->be_lun->blocksize;
4224					else
4225						ival /= 512;
4226					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4227					    page->descr[0].count);
4228				}
4229				value = ctl_get_opt(&lun->be_lun->options,
4230				    "used-threshold");
4231				if (value != NULL &&
4232				    ctl_expand_number(value, &ival) == 0) {
4233					page->descr[1].flags |= SLBPPD_ENABLED |
4234					    SLBPPD_ARMING_INC;
4235					if (lun->be_lun->blocksize)
4236						ival /= lun->be_lun->blocksize;
4237					else
4238						ival /= 512;
4239					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4240					    page->descr[1].count);
4241				}
4242				value = ctl_get_opt(&lun->be_lun->options,
4243				    "pool-avail-threshold");
4244				if (value != NULL &&
4245				    ctl_expand_number(value, &ival) == 0) {
4246					page->descr[2].flags |= SLBPPD_ENABLED |
4247					    SLBPPD_ARMING_DEC;
4248					if (lun->be_lun->blocksize)
4249						ival /= lun->be_lun->blocksize;
4250					else
4251						ival /= 512;
4252					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4253					    page->descr[2].count);
4254				}
4255				value = ctl_get_opt(&lun->be_lun->options,
4256				    "pool-used-threshold");
4257				if (value != NULL &&
4258				    ctl_expand_number(value, &ival) == 0) {
4259					page->descr[3].flags |= SLBPPD_ENABLED |
4260					    SLBPPD_ARMING_INC;
4261					if (lun->be_lun->blocksize)
4262						ival /= lun->be_lun->blocksize;
4263					else
4264						ival /= 512;
4265					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4266					    page->descr[3].count);
4267				}
4268				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4269				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4270				       sizeof(lbp_page_default));
4271				page_index->page_data =
4272					(uint8_t *)lun->mode_pages.lbp_page;
4273			}}
4274			break;
4275		}
4276		case SMS_VENDOR_SPECIFIC_PAGE:{
4277			switch (page_index->subpage) {
4278			case DBGCNF_SUBPAGE_CODE: {
4279				struct copan_debugconf_subpage *current_page,
4280							       *saved_page;
4281
4282				memcpy(&lun->mode_pages.debugconf_subpage[
4283				       CTL_PAGE_CURRENT],
4284				       &debugconf_page_default,
4285				       sizeof(debugconf_page_default));
4286				memcpy(&lun->mode_pages.debugconf_subpage[
4287				       CTL_PAGE_CHANGEABLE],
4288				       &debugconf_page_changeable,
4289				       sizeof(debugconf_page_changeable));
4290				memcpy(&lun->mode_pages.debugconf_subpage[
4291				       CTL_PAGE_DEFAULT],
4292				       &debugconf_page_default,
4293				       sizeof(debugconf_page_default));
4294				memcpy(&lun->mode_pages.debugconf_subpage[
4295				       CTL_PAGE_SAVED],
4296				       &debugconf_page_default,
4297				       sizeof(debugconf_page_default));
4298				page_index->page_data =
4299					(uint8_t *)lun->mode_pages.debugconf_subpage;
4300
4301				current_page = (struct copan_debugconf_subpage *)
4302					(page_index->page_data +
4303					 (page_index->page_len *
4304					  CTL_PAGE_CURRENT));
4305				saved_page = (struct copan_debugconf_subpage *)
4306					(page_index->page_data +
4307					 (page_index->page_len *
4308					  CTL_PAGE_SAVED));
4309				break;
4310			}
4311			default:
4312				panic("invalid subpage value %d",
4313				      page_index->subpage);
4314				break;
4315			}
4316   			break;
4317		}
4318		default:
4319			panic("invalid page value %d",
4320			      page_index->page_code & SMPH_PC_MASK);
4321			break;
4322    	}
4323	}
4324
4325	return (CTL_RETVAL_COMPLETE);
4326}
4327
4328static int
4329ctl_init_log_page_index(struct ctl_lun *lun)
4330{
4331	struct ctl_page_index *page_index;
4332	int i, j, k, prev;
4333
4334	memcpy(&lun->log_pages.index, log_page_index_template,
4335	       sizeof(log_page_index_template));
4336
4337	prev = -1;
4338	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4339
4340		page_index = &lun->log_pages.index[i];
4341		/*
4342		 * If this is a disk-only mode page, there's no point in
4343		 * setting it up.  For some pages, we have to have some
4344		 * basic information about the disk in order to calculate the
4345		 * mode page data.
4346		 */
4347		if ((lun->be_lun->lun_type != T_DIRECT)
4348		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4349			continue;
4350
4351		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4352		     lun->backend->lun_attr == NULL)
4353			continue;
4354
4355		if (page_index->page_code != prev) {
4356			lun->log_pages.pages_page[j] = page_index->page_code;
4357			prev = page_index->page_code;
4358			j++;
4359		}
4360		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4361		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4362		k++;
4363	}
4364	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4365	lun->log_pages.index[0].page_len = j;
4366	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4367	lun->log_pages.index[1].page_len = k * 2;
4368	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4369	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4370
4371	return (CTL_RETVAL_COMPLETE);
4372}
4373
4374static int
4375hex2bin(const char *str, uint8_t *buf, int buf_size)
4376{
4377	int i;
4378	u_char c;
4379
4380	memset(buf, 0, buf_size);
4381	while (isspace(str[0]))
4382		str++;
4383	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4384		str += 2;
4385	buf_size *= 2;
4386	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4387		c = str[i];
4388		if (isdigit(c))
4389			c -= '0';
4390		else if (isalpha(c))
4391			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4392		else
4393			break;
4394		if (c >= 16)
4395			break;
4396		if ((i & 1) == 0)
4397			buf[i / 2] |= (c << 4);
4398		else
4399			buf[i / 2] |= c;
4400	}
4401	return ((i + 1) / 2);
4402}
4403
4404/*
4405 * LUN allocation.
4406 *
4407 * Requirements:
4408 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4409 *   wants us to allocate the LUN and he can block.
4410 * - ctl_softc is always set
4411 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4412 *
4413 * Returns 0 for success, non-zero (errno) for failure.
4414 */
4415static int
4416ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4417	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4418{
4419	struct ctl_lun *nlun, *lun;
4420	struct ctl_port *port;
4421	struct scsi_vpd_id_descriptor *desc;
4422	struct scsi_vpd_id_t10 *t10id;
4423	const char *eui, *naa, *scsiname, *vendor, *value;
4424	int lun_number, i, lun_malloced;
4425	int devidlen, idlen1, idlen2 = 0, len;
4426
4427	if (be_lun == NULL)
4428		return (EINVAL);
4429
4430	/*
4431	 * We currently only support Direct Access or Processor LUN types.
4432	 */
4433	switch (be_lun->lun_type) {
4434	case T_DIRECT:
4435		break;
4436	case T_PROCESSOR:
4437		break;
4438	case T_SEQUENTIAL:
4439	case T_CHANGER:
4440	default:
4441		be_lun->lun_config_status(be_lun->be_lun,
4442					  CTL_LUN_CONFIG_FAILURE);
4443		break;
4444	}
4445	if (ctl_lun == NULL) {
4446		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4447		lun_malloced = 1;
4448	} else {
4449		lun_malloced = 0;
4450		lun = ctl_lun;
4451	}
4452
4453	memset(lun, 0, sizeof(*lun));
4454	if (lun_malloced)
4455		lun->flags = CTL_LUN_MALLOCED;
4456
4457	/* Generate LUN ID. */
4458	devidlen = max(CTL_DEVID_MIN_LEN,
4459	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4460	idlen1 = sizeof(*t10id) + devidlen;
4461	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4462	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4463	if (scsiname != NULL) {
4464		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4465		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4466	}
4467	eui = ctl_get_opt(&be_lun->options, "eui");
4468	if (eui != NULL) {
4469		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4470	}
4471	naa = ctl_get_opt(&be_lun->options, "naa");
4472	if (naa != NULL) {
4473		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4474	}
4475	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4476	    M_CTL, M_WAITOK | M_ZERO);
4477	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4478	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4479	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4480	desc->length = idlen1;
4481	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4482	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4483	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4484		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4485	} else {
4486		strncpy(t10id->vendor, vendor,
4487		    min(sizeof(t10id->vendor), strlen(vendor)));
4488	}
4489	strncpy((char *)t10id->vendor_spec_id,
4490	    (char *)be_lun->device_id, devidlen);
4491	if (scsiname != NULL) {
4492		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4493		    desc->length);
4494		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4495		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4496		    SVPD_ID_TYPE_SCSI_NAME;
4497		desc->length = idlen2;
4498		strlcpy(desc->identifier, scsiname, idlen2);
4499	}
4500	if (eui != NULL) {
4501		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4502		    desc->length);
4503		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4504		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4505		    SVPD_ID_TYPE_EUI64;
4506		desc->length = hex2bin(eui, desc->identifier, 16);
4507		desc->length = desc->length > 12 ? 16 :
4508		    (desc->length > 8 ? 12 : 8);
4509		len -= 16 - desc->length;
4510	}
4511	if (naa != NULL) {
4512		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4513		    desc->length);
4514		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4515		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4516		    SVPD_ID_TYPE_NAA;
4517		desc->length = hex2bin(naa, desc->identifier, 16);
4518		desc->length = desc->length > 8 ? 16 : 8;
4519		len -= 16 - desc->length;
4520	}
4521	lun->lun_devid->len = len;
4522
4523	mtx_lock(&ctl_softc->ctl_lock);
4524	/*
4525	 * See if the caller requested a particular LUN number.  If so, see
4526	 * if it is available.  Otherwise, allocate the first available LUN.
4527	 */
4528	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4529		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4530		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4531			mtx_unlock(&ctl_softc->ctl_lock);
4532			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4533				printf("ctl: requested LUN ID %d is higher "
4534				       "than CTL_MAX_LUNS - 1 (%d)\n",
4535				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4536			} else {
4537				/*
4538				 * XXX KDM return an error, or just assign
4539				 * another LUN ID in this case??
4540				 */
4541				printf("ctl: requested LUN ID %d is already "
4542				       "in use\n", be_lun->req_lun_id);
4543			}
4544			if (lun->flags & CTL_LUN_MALLOCED)
4545				free(lun, M_CTL);
4546			be_lun->lun_config_status(be_lun->be_lun,
4547						  CTL_LUN_CONFIG_FAILURE);
4548			return (ENOSPC);
4549		}
4550		lun_number = be_lun->req_lun_id;
4551	} else {
4552		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4553		if (lun_number == -1) {
4554			mtx_unlock(&ctl_softc->ctl_lock);
4555			printf("ctl: can't allocate LUN on target %ju, out of "
4556			       "LUNs\n", (uintmax_t)target_id.id);
4557			if (lun->flags & CTL_LUN_MALLOCED)
4558				free(lun, M_CTL);
4559			be_lun->lun_config_status(be_lun->be_lun,
4560						  CTL_LUN_CONFIG_FAILURE);
4561			return (ENOSPC);
4562		}
4563	}
4564	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4565
4566	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4567	lun->target = target_id;
4568	lun->lun = lun_number;
4569	lun->be_lun = be_lun;
4570	/*
4571	 * The processor LUN is always enabled.  Disk LUNs come on line
4572	 * disabled, and must be enabled by the backend.
4573	 */
4574	lun->flags |= CTL_LUN_DISABLED;
4575	lun->backend = be_lun->be;
4576	be_lun->ctl_lun = lun;
4577	be_lun->lun_id = lun_number;
4578	atomic_add_int(&be_lun->be->num_luns, 1);
4579	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4580		lun->flags |= CTL_LUN_OFFLINE;
4581
4582	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4583		lun->flags |= CTL_LUN_STOPPED;
4584
4585	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4586		lun->flags |= CTL_LUN_INOPERABLE;
4587
4588	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4589		lun->flags |= CTL_LUN_PRIMARY_SC;
4590
4591	value = ctl_get_opt(&be_lun->options, "readonly");
4592	if (value != NULL && strcmp(value, "on") == 0)
4593		lun->flags |= CTL_LUN_READONLY;
4594
4595	lun->ctl_softc = ctl_softc;
4596	TAILQ_INIT(&lun->ooa_queue);
4597	TAILQ_INIT(&lun->blocked_queue);
4598	STAILQ_INIT(&lun->error_list);
4599	ctl_tpc_lun_init(lun);
4600
4601	/*
4602	 * Initialize the mode and log page index.
4603	 */
4604	ctl_init_page_index(lun);
4605	ctl_init_log_page_index(lun);
4606
4607	/*
4608	 * Now, before we insert this lun on the lun list, set the lun
4609	 * inventory changed UA for all other luns.
4610	 */
4611	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4612		mtx_lock(&nlun->lun_lock);
4613		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4614		mtx_unlock(&nlun->lun_lock);
4615	}
4616
4617	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4618
4619	ctl_softc->ctl_luns[lun_number] = lun;
4620
4621	ctl_softc->num_luns++;
4622
4623	/* Setup statistics gathering */
4624	lun->stats.device_type = be_lun->lun_type;
4625	lun->stats.lun_number = lun_number;
4626	if (lun->stats.device_type == T_DIRECT)
4627		lun->stats.blocksize = be_lun->blocksize;
4628	else
4629		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4630	for (i = 0;i < CTL_MAX_PORTS;i++)
4631		lun->stats.ports[i].targ_port = i;
4632
4633	mtx_unlock(&ctl_softc->ctl_lock);
4634
4635	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4636
4637	/*
4638	 * Run through each registered FETD and bring it online if it isn't
4639	 * already.  Enable the target ID if it hasn't been enabled, and
4640	 * enable this particular LUN.
4641	 */
4642	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4643		int retval;
4644
4645		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4646		if (retval != 0) {
4647			printf("ctl_alloc_lun: FETD %s port %d returned error "
4648			       "%d for lun_enable on target %ju lun %d\n",
4649			       port->port_name, port->targ_port, retval,
4650			       (uintmax_t)target_id.id, lun_number);
4651		} else
4652			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4653	}
4654	return (0);
4655}
4656
4657/*
4658 * Delete a LUN.
4659 * Assumptions:
4660 * - LUN has already been marked invalid and any pending I/O has been taken
4661 *   care of.
4662 */
4663static int
4664ctl_free_lun(struct ctl_lun *lun)
4665{
4666	struct ctl_softc *softc;
4667#if 0
4668	struct ctl_port *port;
4669#endif
4670	struct ctl_lun *nlun;
4671	int i;
4672
4673	softc = lun->ctl_softc;
4674
4675	mtx_assert(&softc->ctl_lock, MA_OWNED);
4676
4677	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4678
4679	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4680
4681	softc->ctl_luns[lun->lun] = NULL;
4682
4683	if (!TAILQ_EMPTY(&lun->ooa_queue))
4684		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4685
4686	softc->num_luns--;
4687
4688	/*
4689	 * XXX KDM this scheme only works for a single target/multiple LUN
4690	 * setup.  It needs to be revamped for a multiple target scheme.
4691	 *
4692	 * XXX KDM this results in port->lun_disable() getting called twice,
4693	 * once when ctl_disable_lun() is called, and a second time here.
4694	 * We really need to re-think the LUN disable semantics.  There
4695	 * should probably be several steps/levels to LUN removal:
4696	 *  - disable
4697	 *  - invalidate
4698	 *  - free
4699 	 *
4700	 * Right now we only have a disable method when communicating to
4701	 * the front end ports, at least for individual LUNs.
4702	 */
4703#if 0
4704	STAILQ_FOREACH(port, &softc->port_list, links) {
4705		int retval;
4706
4707		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4708					 lun->lun);
4709		if (retval != 0) {
4710			printf("ctl_free_lun: FETD %s port %d returned error "
4711			       "%d for lun_disable on target %ju lun %jd\n",
4712			       port->port_name, port->targ_port, retval,
4713			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4714		}
4715
4716		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4717			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4718
4719			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4720			if (retval != 0) {
4721				printf("ctl_free_lun: FETD %s port %d "
4722				       "returned error %d for targ_disable on "
4723				       "target %ju\n", port->port_name,
4724				       port->targ_port, retval,
4725				       (uintmax_t)lun->target.id);
4726			} else
4727				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4728
4729			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4730				continue;
4731
4732#if 0
4733			port->port_offline(port->onoff_arg);
4734			port->status &= ~CTL_PORT_STATUS_ONLINE;
4735#endif
4736		}
4737	}
4738#endif
4739
4740	/*
4741	 * Tell the backend to free resources, if this LUN has a backend.
4742	 */
4743	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4744	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4745
4746	ctl_tpc_lun_shutdown(lun);
4747	mtx_destroy(&lun->lun_lock);
4748	free(lun->lun_devid, M_CTL);
4749	for (i = 0; i < CTL_MAX_PORTS; i++)
4750		free(lun->pending_ua[i], M_CTL);
4751	for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4752		free(lun->pr_keys[i], M_CTL);
4753	free(lun->write_buffer, M_CTL);
4754	if (lun->flags & CTL_LUN_MALLOCED)
4755		free(lun, M_CTL);
4756
4757	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4758		mtx_lock(&nlun->lun_lock);
4759		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4760		mtx_unlock(&nlun->lun_lock);
4761	}
4762
4763	return (0);
4764}
4765
4766static void
4767ctl_create_lun(struct ctl_be_lun *be_lun)
4768{
4769	struct ctl_softc *ctl_softc;
4770
4771	ctl_softc = control_softc;
4772
4773	/*
4774	 * ctl_alloc_lun() should handle all potential failure cases.
4775	 */
4776	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4777}
4778
4779int
4780ctl_add_lun(struct ctl_be_lun *be_lun)
4781{
4782	struct ctl_softc *ctl_softc = control_softc;
4783
4784	mtx_lock(&ctl_softc->ctl_lock);
4785	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4786	mtx_unlock(&ctl_softc->ctl_lock);
4787	wakeup(&ctl_softc->pending_lun_queue);
4788
4789	return (0);
4790}
4791
4792int
4793ctl_enable_lun(struct ctl_be_lun *be_lun)
4794{
4795	struct ctl_softc *ctl_softc;
4796	struct ctl_port *port, *nport;
4797	struct ctl_lun *lun;
4798	int retval;
4799
4800	ctl_softc = control_softc;
4801
4802	lun = (struct ctl_lun *)be_lun->ctl_lun;
4803
4804	mtx_lock(&ctl_softc->ctl_lock);
4805	mtx_lock(&lun->lun_lock);
4806	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4807		/*
4808		 * eh?  Why did we get called if the LUN is already
4809		 * enabled?
4810		 */
4811		mtx_unlock(&lun->lun_lock);
4812		mtx_unlock(&ctl_softc->ctl_lock);
4813		return (0);
4814	}
4815	lun->flags &= ~CTL_LUN_DISABLED;
4816	mtx_unlock(&lun->lun_lock);
4817
4818	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4819		nport = STAILQ_NEXT(port, links);
4820
4821		/*
4822		 * Drop the lock while we call the FETD's enable routine.
4823		 * This can lead to a callback into CTL (at least in the
4824		 * case of the internal initiator frontend.
4825		 */
4826		mtx_unlock(&ctl_softc->ctl_lock);
4827		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4828		mtx_lock(&ctl_softc->ctl_lock);
4829		if (retval != 0) {
4830			printf("%s: FETD %s port %d returned error "
4831			       "%d for lun_enable on target %ju lun %jd\n",
4832			       __func__, port->port_name, port->targ_port, retval,
4833			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4834		}
4835#if 0
4836		 else {
4837            /* NOTE:  TODO:  why does lun enable affect port status? */
4838			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4839		}
4840#endif
4841	}
4842
4843	mtx_unlock(&ctl_softc->ctl_lock);
4844
4845	return (0);
4846}
4847
4848int
4849ctl_disable_lun(struct ctl_be_lun *be_lun)
4850{
4851	struct ctl_softc *ctl_softc;
4852	struct ctl_port *port;
4853	struct ctl_lun *lun;
4854	int retval;
4855
4856	ctl_softc = control_softc;
4857
4858	lun = (struct ctl_lun *)be_lun->ctl_lun;
4859
4860	mtx_lock(&ctl_softc->ctl_lock);
4861	mtx_lock(&lun->lun_lock);
4862	if (lun->flags & CTL_LUN_DISABLED) {
4863		mtx_unlock(&lun->lun_lock);
4864		mtx_unlock(&ctl_softc->ctl_lock);
4865		return (0);
4866	}
4867	lun->flags |= CTL_LUN_DISABLED;
4868	mtx_unlock(&lun->lun_lock);
4869
4870	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4871		mtx_unlock(&ctl_softc->ctl_lock);
4872		/*
4873		 * Drop the lock before we call the frontend's disable
4874		 * routine, to avoid lock order reversals.
4875		 *
4876		 * XXX KDM what happens if the frontend list changes while
4877		 * we're traversing it?  It's unlikely, but should be handled.
4878		 */
4879		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4880					 lun->lun);
4881		mtx_lock(&ctl_softc->ctl_lock);
4882		if (retval != 0) {
4883			printf("ctl_alloc_lun: FETD %s port %d returned error "
4884			       "%d for lun_disable on target %ju lun %jd\n",
4885			       port->port_name, port->targ_port, retval,
4886			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4887		}
4888	}
4889
4890	mtx_unlock(&ctl_softc->ctl_lock);
4891
4892	return (0);
4893}
4894
4895int
4896ctl_start_lun(struct ctl_be_lun *be_lun)
4897{
4898	struct ctl_softc *ctl_softc;
4899	struct ctl_lun *lun;
4900
4901	ctl_softc = control_softc;
4902
4903	lun = (struct ctl_lun *)be_lun->ctl_lun;
4904
4905	mtx_lock(&lun->lun_lock);
4906	lun->flags &= ~CTL_LUN_STOPPED;
4907	mtx_unlock(&lun->lun_lock);
4908
4909	return (0);
4910}
4911
4912int
4913ctl_stop_lun(struct ctl_be_lun *be_lun)
4914{
4915	struct ctl_softc *ctl_softc;
4916	struct ctl_lun *lun;
4917
4918	ctl_softc = control_softc;
4919
4920	lun = (struct ctl_lun *)be_lun->ctl_lun;
4921
4922	mtx_lock(&lun->lun_lock);
4923	lun->flags |= CTL_LUN_STOPPED;
4924	mtx_unlock(&lun->lun_lock);
4925
4926	return (0);
4927}
4928
4929int
4930ctl_lun_offline(struct ctl_be_lun *be_lun)
4931{
4932	struct ctl_softc *ctl_softc;
4933	struct ctl_lun *lun;
4934
4935	ctl_softc = control_softc;
4936
4937	lun = (struct ctl_lun *)be_lun->ctl_lun;
4938
4939	mtx_lock(&lun->lun_lock);
4940	lun->flags |= CTL_LUN_OFFLINE;
4941	mtx_unlock(&lun->lun_lock);
4942
4943	return (0);
4944}
4945
4946int
4947ctl_lun_online(struct ctl_be_lun *be_lun)
4948{
4949	struct ctl_softc *ctl_softc;
4950	struct ctl_lun *lun;
4951
4952	ctl_softc = control_softc;
4953
4954	lun = (struct ctl_lun *)be_lun->ctl_lun;
4955
4956	mtx_lock(&lun->lun_lock);
4957	lun->flags &= ~CTL_LUN_OFFLINE;
4958	mtx_unlock(&lun->lun_lock);
4959
4960	return (0);
4961}
4962
4963int
4964ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4965{
4966	struct ctl_softc *ctl_softc;
4967	struct ctl_lun *lun;
4968
4969	ctl_softc = control_softc;
4970
4971	lun = (struct ctl_lun *)be_lun->ctl_lun;
4972
4973	mtx_lock(&lun->lun_lock);
4974
4975	/*
4976	 * The LUN needs to be disabled before it can be marked invalid.
4977	 */
4978	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4979		mtx_unlock(&lun->lun_lock);
4980		return (-1);
4981	}
4982	/*
4983	 * Mark the LUN invalid.
4984	 */
4985	lun->flags |= CTL_LUN_INVALID;
4986
4987	/*
4988	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4989	 * If we have something in the OOA queue, we'll free it when the
4990	 * last I/O completes.
4991	 */
4992	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4993		mtx_unlock(&lun->lun_lock);
4994		mtx_lock(&ctl_softc->ctl_lock);
4995		ctl_free_lun(lun);
4996		mtx_unlock(&ctl_softc->ctl_lock);
4997	} else
4998		mtx_unlock(&lun->lun_lock);
4999
5000	return (0);
5001}
5002
5003int
5004ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5005{
5006	struct ctl_softc *ctl_softc;
5007	struct ctl_lun *lun;
5008
5009	ctl_softc = control_softc;
5010	lun = (struct ctl_lun *)be_lun->ctl_lun;
5011
5012	mtx_lock(&lun->lun_lock);
5013	lun->flags |= CTL_LUN_INOPERABLE;
5014	mtx_unlock(&lun->lun_lock);
5015
5016	return (0);
5017}
5018
5019int
5020ctl_lun_operable(struct ctl_be_lun *be_lun)
5021{
5022	struct ctl_softc *ctl_softc;
5023	struct ctl_lun *lun;
5024
5025	ctl_softc = control_softc;
5026	lun = (struct ctl_lun *)be_lun->ctl_lun;
5027
5028	mtx_lock(&lun->lun_lock);
5029	lun->flags &= ~CTL_LUN_INOPERABLE;
5030	mtx_unlock(&lun->lun_lock);
5031
5032	return (0);
5033}
5034
5035void
5036ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5037{
5038	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5039
5040	mtx_lock(&lun->lun_lock);
5041	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5042	mtx_unlock(&lun->lun_lock);
5043}
5044
5045/*
5046 * Backend "memory move is complete" callback for requests that never
5047 * make it down to say RAIDCore's configuration code.
5048 */
5049int
5050ctl_config_move_done(union ctl_io *io)
5051{
5052	int retval;
5053
5054	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5055	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5056	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5057
5058	if ((io->io_hdr.port_status != 0) &&
5059	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5060	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5061		/*
5062		 * For hardware error sense keys, the sense key
5063		 * specific value is defined to be a retry count,
5064		 * but we use it to pass back an internal FETD
5065		 * error code.  XXX KDM  Hopefully the FETD is only
5066		 * using 16 bits for an error code, since that's
5067		 * all the space we have in the sks field.
5068		 */
5069		ctl_set_internal_failure(&io->scsiio,
5070					 /*sks_valid*/ 1,
5071					 /*retry_count*/
5072					 io->io_hdr.port_status);
5073	}
5074
5075	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5076	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5077	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5078	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5079		/*
5080		 * XXX KDM just assuming a single pointer here, and not a
5081		 * S/G list.  If we start using S/G lists for config data,
5082		 * we'll need to know how to clean them up here as well.
5083		 */
5084		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5085			free(io->scsiio.kern_data_ptr, M_CTL);
5086		ctl_done(io);
5087		retval = CTL_RETVAL_COMPLETE;
5088	} else {
5089		/*
5090		 * XXX KDM now we need to continue data movement.  Some
5091		 * options:
5092		 * - call ctl_scsiio() again?  We don't do this for data
5093		 *   writes, because for those at least we know ahead of
5094		 *   time where the write will go and how long it is.  For
5095		 *   config writes, though, that information is largely
5096		 *   contained within the write itself, thus we need to
5097		 *   parse out the data again.
5098		 *
5099		 * - Call some other function once the data is in?
5100		 */
5101		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5102			ctl_data_print(io);
5103
5104		/*
5105		 * XXX KDM call ctl_scsiio() again for now, and check flag
5106		 * bits to see whether we're allocated or not.
5107		 */
5108		retval = ctl_scsiio(&io->scsiio);
5109	}
5110	return (retval);
5111}
5112
5113/*
5114 * This gets called by a backend driver when it is done with a
5115 * data_submit method.
5116 */
5117void
5118ctl_data_submit_done(union ctl_io *io)
5119{
5120	/*
5121	 * If the IO_CONT flag is set, we need to call the supplied
5122	 * function to continue processing the I/O, instead of completing
5123	 * the I/O just yet.
5124	 *
5125	 * If there is an error, though, we don't want to keep processing.
5126	 * Instead, just send status back to the initiator.
5127	 */
5128	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5129	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5130	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5131	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5132		io->scsiio.io_cont(io);
5133		return;
5134	}
5135	ctl_done(io);
5136}
5137
5138/*
5139 * This gets called by a backend driver when it is done with a
5140 * configuration write.
5141 */
5142void
5143ctl_config_write_done(union ctl_io *io)
5144{
5145	uint8_t *buf;
5146
5147	/*
5148	 * If the IO_CONT flag is set, we need to call the supplied
5149	 * function to continue processing the I/O, instead of completing
5150	 * the I/O just yet.
5151	 *
5152	 * If there is an error, though, we don't want to keep processing.
5153	 * Instead, just send status back to the initiator.
5154	 */
5155	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5156	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5157	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5158	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5159		io->scsiio.io_cont(io);
5160		return;
5161	}
5162	/*
5163	 * Since a configuration write can be done for commands that actually
5164	 * have data allocated, like write buffer, and commands that have
5165	 * no data, like start/stop unit, we need to check here.
5166	 */
5167	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5168		buf = io->scsiio.kern_data_ptr;
5169	else
5170		buf = NULL;
5171	ctl_done(io);
5172	if (buf)
5173		free(buf, M_CTL);
5174}
5175
5176void
5177ctl_config_read_done(union ctl_io *io)
5178{
5179	uint8_t *buf;
5180
5181	/*
5182	 * If there is some error -- we are done, skip data transfer.
5183	 */
5184	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5185	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5186	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5187		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5188			buf = io->scsiio.kern_data_ptr;
5189		else
5190			buf = NULL;
5191		ctl_done(io);
5192		if (buf)
5193			free(buf, M_CTL);
5194		return;
5195	}
5196
5197	/*
5198	 * If the IO_CONT flag is set, we need to call the supplied
5199	 * function to continue processing the I/O, instead of completing
5200	 * the I/O just yet.
5201	 */
5202	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5203		io->scsiio.io_cont(io);
5204		return;
5205	}
5206
5207	ctl_datamove(io);
5208}
5209
5210/*
5211 * SCSI release command.
5212 */
5213int
5214ctl_scsi_release(struct ctl_scsiio *ctsio)
5215{
5216	int length, longid, thirdparty_id, resv_id;
5217	struct ctl_softc *ctl_softc;
5218	struct ctl_lun *lun;
5219	uint32_t residx;
5220
5221	length = 0;
5222	resv_id = 0;
5223
5224	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5225
5226	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5227	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5228	ctl_softc = control_softc;
5229
5230	switch (ctsio->cdb[0]) {
5231	case RELEASE_10: {
5232		struct scsi_release_10 *cdb;
5233
5234		cdb = (struct scsi_release_10 *)ctsio->cdb;
5235
5236		if (cdb->byte2 & SR10_LONGID)
5237			longid = 1;
5238		else
5239			thirdparty_id = cdb->thirdparty_id;
5240
5241		resv_id = cdb->resv_id;
5242		length = scsi_2btoul(cdb->length);
5243		break;
5244	}
5245	}
5246
5247
5248	/*
5249	 * XXX KDM right now, we only support LUN reservation.  We don't
5250	 * support 3rd party reservations, or extent reservations, which
5251	 * might actually need the parameter list.  If we've gotten this
5252	 * far, we've got a LUN reservation.  Anything else got kicked out
5253	 * above.  So, according to SPC, ignore the length.
5254	 */
5255	length = 0;
5256
5257	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5258	 && (length > 0)) {
5259		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5260		ctsio->kern_data_len = length;
5261		ctsio->kern_total_len = length;
5262		ctsio->kern_data_resid = 0;
5263		ctsio->kern_rel_offset = 0;
5264		ctsio->kern_sg_entries = 0;
5265		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5266		ctsio->be_move_done = ctl_config_move_done;
5267		ctl_datamove((union ctl_io *)ctsio);
5268
5269		return (CTL_RETVAL_COMPLETE);
5270	}
5271
5272	if (length > 0)
5273		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5274
5275	mtx_lock(&lun->lun_lock);
5276
5277	/*
5278	 * According to SPC, it is not an error for an intiator to attempt
5279	 * to release a reservation on a LUN that isn't reserved, or that
5280	 * is reserved by another initiator.  The reservation can only be
5281	 * released, though, by the initiator who made it or by one of
5282	 * several reset type events.
5283	 */
5284	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5285			lun->flags &= ~CTL_LUN_RESERVED;
5286
5287	mtx_unlock(&lun->lun_lock);
5288
5289	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5290		free(ctsio->kern_data_ptr, M_CTL);
5291		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5292	}
5293
5294	ctl_set_success(ctsio);
5295	ctl_done((union ctl_io *)ctsio);
5296	return (CTL_RETVAL_COMPLETE);
5297}
5298
5299int
5300ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5301{
5302	int extent, thirdparty, longid;
5303	int resv_id, length;
5304	uint64_t thirdparty_id;
5305	struct ctl_softc *ctl_softc;
5306	struct ctl_lun *lun;
5307	uint32_t residx;
5308
5309	extent = 0;
5310	thirdparty = 0;
5311	longid = 0;
5312	resv_id = 0;
5313	length = 0;
5314	thirdparty_id = 0;
5315
5316	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5317
5318	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5319	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5320	ctl_softc = control_softc;
5321
5322	switch (ctsio->cdb[0]) {
5323	case RESERVE_10: {
5324		struct scsi_reserve_10 *cdb;
5325
5326		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5327
5328		if (cdb->byte2 & SR10_LONGID)
5329			longid = 1;
5330		else
5331			thirdparty_id = cdb->thirdparty_id;
5332
5333		resv_id = cdb->resv_id;
5334		length = scsi_2btoul(cdb->length);
5335		break;
5336	}
5337	}
5338
5339	/*
5340	 * XXX KDM right now, we only support LUN reservation.  We don't
5341	 * support 3rd party reservations, or extent reservations, which
5342	 * might actually need the parameter list.  If we've gotten this
5343	 * far, we've got a LUN reservation.  Anything else got kicked out
5344	 * above.  So, according to SPC, ignore the length.
5345	 */
5346	length = 0;
5347
5348	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5349	 && (length > 0)) {
5350		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5351		ctsio->kern_data_len = length;
5352		ctsio->kern_total_len = length;
5353		ctsio->kern_data_resid = 0;
5354		ctsio->kern_rel_offset = 0;
5355		ctsio->kern_sg_entries = 0;
5356		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5357		ctsio->be_move_done = ctl_config_move_done;
5358		ctl_datamove((union ctl_io *)ctsio);
5359
5360		return (CTL_RETVAL_COMPLETE);
5361	}
5362
5363	if (length > 0)
5364		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5365
5366	mtx_lock(&lun->lun_lock);
5367	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5368		ctl_set_reservation_conflict(ctsio);
5369		goto bailout;
5370	}
5371
5372	lun->flags |= CTL_LUN_RESERVED;
5373	lun->res_idx = residx;
5374
5375	ctl_set_success(ctsio);
5376
5377bailout:
5378	mtx_unlock(&lun->lun_lock);
5379
5380	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5381		free(ctsio->kern_data_ptr, M_CTL);
5382		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5383	}
5384
5385	ctl_done((union ctl_io *)ctsio);
5386	return (CTL_RETVAL_COMPLETE);
5387}
5388
5389int
5390ctl_start_stop(struct ctl_scsiio *ctsio)
5391{
5392	struct scsi_start_stop_unit *cdb;
5393	struct ctl_lun *lun;
5394	struct ctl_softc *ctl_softc;
5395	int retval;
5396
5397	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5398
5399	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5400	ctl_softc = control_softc;
5401	retval = 0;
5402
5403	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5404
5405	/*
5406	 * XXX KDM
5407	 * We don't support the immediate bit on a stop unit.  In order to
5408	 * do that, we would need to code up a way to know that a stop is
5409	 * pending, and hold off any new commands until it completes, one
5410	 * way or another.  Then we could accept or reject those commands
5411	 * depending on its status.  We would almost need to do the reverse
5412	 * of what we do below for an immediate start -- return the copy of
5413	 * the ctl_io to the FETD with status to send to the host (and to
5414	 * free the copy!) and then free the original I/O once the stop
5415	 * actually completes.  That way, the OOA queue mechanism can work
5416	 * to block commands that shouldn't proceed.  Another alternative
5417	 * would be to put the copy in the queue in place of the original,
5418	 * and return the original back to the caller.  That could be
5419	 * slightly safer..
5420	 */
5421	if ((cdb->byte2 & SSS_IMMED)
5422	 && ((cdb->how & SSS_START) == 0)) {
5423		ctl_set_invalid_field(ctsio,
5424				      /*sks_valid*/ 1,
5425				      /*command*/ 1,
5426				      /*field*/ 1,
5427				      /*bit_valid*/ 1,
5428				      /*bit*/ 0);
5429		ctl_done((union ctl_io *)ctsio);
5430		return (CTL_RETVAL_COMPLETE);
5431	}
5432
5433	if ((lun->flags & CTL_LUN_PR_RESERVED)
5434	 && ((cdb->how & SSS_START)==0)) {
5435		uint32_t residx;
5436
5437		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5438		if (ctl_get_prkey(lun, residx) == 0
5439		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5440
5441			ctl_set_reservation_conflict(ctsio);
5442			ctl_done((union ctl_io *)ctsio);
5443			return (CTL_RETVAL_COMPLETE);
5444		}
5445	}
5446
5447	/*
5448	 * If there is no backend on this device, we can't start or stop
5449	 * it.  In theory we shouldn't get any start/stop commands in the
5450	 * first place at this level if the LUN doesn't have a backend.
5451	 * That should get stopped by the command decode code.
5452	 */
5453	if (lun->backend == NULL) {
5454		ctl_set_invalid_opcode(ctsio);
5455		ctl_done((union ctl_io *)ctsio);
5456		return (CTL_RETVAL_COMPLETE);
5457	}
5458
5459	/*
5460	 * XXX KDM Copan-specific offline behavior.
5461	 * Figure out a reasonable way to port this?
5462	 */
5463#ifdef NEEDTOPORT
5464	mtx_lock(&lun->lun_lock);
5465
5466	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5467	 && (lun->flags & CTL_LUN_OFFLINE)) {
5468		/*
5469		 * If the LUN is offline, and the on/offline bit isn't set,
5470		 * reject the start or stop.  Otherwise, let it through.
5471		 */
5472		mtx_unlock(&lun->lun_lock);
5473		ctl_set_lun_not_ready(ctsio);
5474		ctl_done((union ctl_io *)ctsio);
5475	} else {
5476		mtx_unlock(&lun->lun_lock);
5477#endif /* NEEDTOPORT */
5478		/*
5479		 * This could be a start or a stop when we're online,
5480		 * or a stop/offline or start/online.  A start or stop when
5481		 * we're offline is covered in the case above.
5482		 */
5483		/*
5484		 * In the non-immediate case, we send the request to
5485		 * the backend and return status to the user when
5486		 * it is done.
5487		 *
5488		 * In the immediate case, we allocate a new ctl_io
5489		 * to hold a copy of the request, and send that to
5490		 * the backend.  We then set good status on the
5491		 * user's request and return it immediately.
5492		 */
5493		if (cdb->byte2 & SSS_IMMED) {
5494			union ctl_io *new_io;
5495
5496			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5497			ctl_copy_io((union ctl_io *)ctsio, new_io);
5498			retval = lun->backend->config_write(new_io);
5499			ctl_set_success(ctsio);
5500			ctl_done((union ctl_io *)ctsio);
5501		} else {
5502			retval = lun->backend->config_write(
5503				(union ctl_io *)ctsio);
5504		}
5505#ifdef NEEDTOPORT
5506	}
5507#endif
5508	return (retval);
5509}
5510
5511/*
5512 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5513 * we don't really do anything with the LBA and length fields if the user
5514 * passes them in.  Instead we'll just flush out the cache for the entire
5515 * LUN.
5516 */
5517int
5518ctl_sync_cache(struct ctl_scsiio *ctsio)
5519{
5520	struct ctl_lun *lun;
5521	struct ctl_softc *ctl_softc;
5522	uint64_t starting_lba;
5523	uint32_t block_count;
5524	int retval;
5525
5526	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5527
5528	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5529	ctl_softc = control_softc;
5530	retval = 0;
5531
5532	switch (ctsio->cdb[0]) {
5533	case SYNCHRONIZE_CACHE: {
5534		struct scsi_sync_cache *cdb;
5535		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5536
5537		starting_lba = scsi_4btoul(cdb->begin_lba);
5538		block_count = scsi_2btoul(cdb->lb_count);
5539		break;
5540	}
5541	case SYNCHRONIZE_CACHE_16: {
5542		struct scsi_sync_cache_16 *cdb;
5543		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5544
5545		starting_lba = scsi_8btou64(cdb->begin_lba);
5546		block_count = scsi_4btoul(cdb->lb_count);
5547		break;
5548	}
5549	default:
5550		ctl_set_invalid_opcode(ctsio);
5551		ctl_done((union ctl_io *)ctsio);
5552		goto bailout;
5553		break; /* NOTREACHED */
5554	}
5555
5556	/*
5557	 * We check the LBA and length, but don't do anything with them.
5558	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5559	 * get flushed.  This check will just help satisfy anyone who wants
5560	 * to see an error for an out of range LBA.
5561	 */
5562	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5563		ctl_set_lba_out_of_range(ctsio);
5564		ctl_done((union ctl_io *)ctsio);
5565		goto bailout;
5566	}
5567
5568	/*
5569	 * If this LUN has no backend, we can't flush the cache anyway.
5570	 */
5571	if (lun->backend == NULL) {
5572		ctl_set_invalid_opcode(ctsio);
5573		ctl_done((union ctl_io *)ctsio);
5574		goto bailout;
5575	}
5576
5577	/*
5578	 * Check to see whether we're configured to send the SYNCHRONIZE
5579	 * CACHE command directly to the back end.
5580	 */
5581	mtx_lock(&lun->lun_lock);
5582	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5583	 && (++(lun->sync_count) >= lun->sync_interval)) {
5584		lun->sync_count = 0;
5585		mtx_unlock(&lun->lun_lock);
5586		retval = lun->backend->config_write((union ctl_io *)ctsio);
5587	} else {
5588		mtx_unlock(&lun->lun_lock);
5589		ctl_set_success(ctsio);
5590		ctl_done((union ctl_io *)ctsio);
5591	}
5592
5593bailout:
5594
5595	return (retval);
5596}
5597
5598int
5599ctl_format(struct ctl_scsiio *ctsio)
5600{
5601	struct scsi_format *cdb;
5602	struct ctl_lun *lun;
5603	struct ctl_softc *ctl_softc;
5604	int length, defect_list_len;
5605
5606	CTL_DEBUG_PRINT(("ctl_format\n"));
5607
5608	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5609	ctl_softc = control_softc;
5610
5611	cdb = (struct scsi_format *)ctsio->cdb;
5612
5613	length = 0;
5614	if (cdb->byte2 & SF_FMTDATA) {
5615		if (cdb->byte2 & SF_LONGLIST)
5616			length = sizeof(struct scsi_format_header_long);
5617		else
5618			length = sizeof(struct scsi_format_header_short);
5619	}
5620
5621	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5622	 && (length > 0)) {
5623		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5624		ctsio->kern_data_len = length;
5625		ctsio->kern_total_len = length;
5626		ctsio->kern_data_resid = 0;
5627		ctsio->kern_rel_offset = 0;
5628		ctsio->kern_sg_entries = 0;
5629		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5630		ctsio->be_move_done = ctl_config_move_done;
5631		ctl_datamove((union ctl_io *)ctsio);
5632
5633		return (CTL_RETVAL_COMPLETE);
5634	}
5635
5636	defect_list_len = 0;
5637
5638	if (cdb->byte2 & SF_FMTDATA) {
5639		if (cdb->byte2 & SF_LONGLIST) {
5640			struct scsi_format_header_long *header;
5641
5642			header = (struct scsi_format_header_long *)
5643				ctsio->kern_data_ptr;
5644
5645			defect_list_len = scsi_4btoul(header->defect_list_len);
5646			if (defect_list_len != 0) {
5647				ctl_set_invalid_field(ctsio,
5648						      /*sks_valid*/ 1,
5649						      /*command*/ 0,
5650						      /*field*/ 2,
5651						      /*bit_valid*/ 0,
5652						      /*bit*/ 0);
5653				goto bailout;
5654			}
5655		} else {
5656			struct scsi_format_header_short *header;
5657
5658			header = (struct scsi_format_header_short *)
5659				ctsio->kern_data_ptr;
5660
5661			defect_list_len = scsi_2btoul(header->defect_list_len);
5662			if (defect_list_len != 0) {
5663				ctl_set_invalid_field(ctsio,
5664						      /*sks_valid*/ 1,
5665						      /*command*/ 0,
5666						      /*field*/ 2,
5667						      /*bit_valid*/ 0,
5668						      /*bit*/ 0);
5669				goto bailout;
5670			}
5671		}
5672	}
5673
5674	/*
5675	 * The format command will clear out the "Medium format corrupted"
5676	 * status if set by the configuration code.  That status is really
5677	 * just a way to notify the host that we have lost the media, and
5678	 * get them to issue a command that will basically make them think
5679	 * they're blowing away the media.
5680	 */
5681	mtx_lock(&lun->lun_lock);
5682	lun->flags &= ~CTL_LUN_INOPERABLE;
5683	mtx_unlock(&lun->lun_lock);
5684
5685	ctl_set_success(ctsio);
5686bailout:
5687
5688	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5689		free(ctsio->kern_data_ptr, M_CTL);
5690		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5691	}
5692
5693	ctl_done((union ctl_io *)ctsio);
5694	return (CTL_RETVAL_COMPLETE);
5695}
5696
5697int
5698ctl_read_buffer(struct ctl_scsiio *ctsio)
5699{
5700	struct scsi_read_buffer *cdb;
5701	struct ctl_lun *lun;
5702	int buffer_offset, len;
5703	static uint8_t descr[4];
5704	static uint8_t echo_descr[4] = { 0 };
5705
5706	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5707
5708	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5709	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5710
5711	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5712	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5713	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5714		ctl_set_invalid_field(ctsio,
5715				      /*sks_valid*/ 1,
5716				      /*command*/ 1,
5717				      /*field*/ 1,
5718				      /*bit_valid*/ 1,
5719				      /*bit*/ 4);
5720		ctl_done((union ctl_io *)ctsio);
5721		return (CTL_RETVAL_COMPLETE);
5722	}
5723
5724	len = scsi_3btoul(cdb->length);
5725	buffer_offset = scsi_3btoul(cdb->offset);
5726
5727	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5728		ctl_set_invalid_field(ctsio,
5729				      /*sks_valid*/ 1,
5730				      /*command*/ 1,
5731				      /*field*/ 6,
5732				      /*bit_valid*/ 0,
5733				      /*bit*/ 0);
5734		ctl_done((union ctl_io *)ctsio);
5735		return (CTL_RETVAL_COMPLETE);
5736	}
5737
5738	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5739		descr[0] = 0;
5740		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5741		ctsio->kern_data_ptr = descr;
5742		len = min(len, sizeof(descr));
5743	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5744		ctsio->kern_data_ptr = echo_descr;
5745		len = min(len, sizeof(echo_descr));
5746	} else {
5747		if (lun->write_buffer == NULL) {
5748			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5749			    M_CTL, M_WAITOK);
5750		}
5751		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5752	}
5753	ctsio->kern_data_len = len;
5754	ctsio->kern_total_len = len;
5755	ctsio->kern_data_resid = 0;
5756	ctsio->kern_rel_offset = 0;
5757	ctsio->kern_sg_entries = 0;
5758	ctl_set_success(ctsio);
5759	ctsio->be_move_done = ctl_config_move_done;
5760	ctl_datamove((union ctl_io *)ctsio);
5761	return (CTL_RETVAL_COMPLETE);
5762}
5763
5764int
5765ctl_write_buffer(struct ctl_scsiio *ctsio)
5766{
5767	struct scsi_write_buffer *cdb;
5768	struct ctl_lun *lun;
5769	int buffer_offset, len;
5770
5771	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5772
5773	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5774	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5775
5776	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5777		ctl_set_invalid_field(ctsio,
5778				      /*sks_valid*/ 1,
5779				      /*command*/ 1,
5780				      /*field*/ 1,
5781				      /*bit_valid*/ 1,
5782				      /*bit*/ 4);
5783		ctl_done((union ctl_io *)ctsio);
5784		return (CTL_RETVAL_COMPLETE);
5785	}
5786
5787	len = scsi_3btoul(cdb->length);
5788	buffer_offset = scsi_3btoul(cdb->offset);
5789
5790	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5791		ctl_set_invalid_field(ctsio,
5792				      /*sks_valid*/ 1,
5793				      /*command*/ 1,
5794				      /*field*/ 6,
5795				      /*bit_valid*/ 0,
5796				      /*bit*/ 0);
5797		ctl_done((union ctl_io *)ctsio);
5798		return (CTL_RETVAL_COMPLETE);
5799	}
5800
5801	/*
5802	 * If we've got a kernel request that hasn't been malloced yet,
5803	 * malloc it and tell the caller the data buffer is here.
5804	 */
5805	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5806		if (lun->write_buffer == NULL) {
5807			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5808			    M_CTL, M_WAITOK);
5809		}
5810		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5811		ctsio->kern_data_len = len;
5812		ctsio->kern_total_len = len;
5813		ctsio->kern_data_resid = 0;
5814		ctsio->kern_rel_offset = 0;
5815		ctsio->kern_sg_entries = 0;
5816		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5817		ctsio->be_move_done = ctl_config_move_done;
5818		ctl_datamove((union ctl_io *)ctsio);
5819
5820		return (CTL_RETVAL_COMPLETE);
5821	}
5822
5823	ctl_set_success(ctsio);
5824	ctl_done((union ctl_io *)ctsio);
5825	return (CTL_RETVAL_COMPLETE);
5826}
5827
5828int
5829ctl_write_same(struct ctl_scsiio *ctsio)
5830{
5831	struct ctl_lun *lun;
5832	struct ctl_lba_len_flags *lbalen;
5833	uint64_t lba;
5834	uint32_t num_blocks;
5835	int len, retval;
5836	uint8_t byte2;
5837
5838	retval = CTL_RETVAL_COMPLETE;
5839
5840	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5841
5842	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5843
5844	switch (ctsio->cdb[0]) {
5845	case WRITE_SAME_10: {
5846		struct scsi_write_same_10 *cdb;
5847
5848		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5849
5850		lba = scsi_4btoul(cdb->addr);
5851		num_blocks = scsi_2btoul(cdb->length);
5852		byte2 = cdb->byte2;
5853		break;
5854	}
5855	case WRITE_SAME_16: {
5856		struct scsi_write_same_16 *cdb;
5857
5858		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5859
5860		lba = scsi_8btou64(cdb->addr);
5861		num_blocks = scsi_4btoul(cdb->length);
5862		byte2 = cdb->byte2;
5863		break;
5864	}
5865	default:
5866		/*
5867		 * We got a command we don't support.  This shouldn't
5868		 * happen, commands should be filtered out above us.
5869		 */
5870		ctl_set_invalid_opcode(ctsio);
5871		ctl_done((union ctl_io *)ctsio);
5872
5873		return (CTL_RETVAL_COMPLETE);
5874		break; /* NOTREACHED */
5875	}
5876
5877	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5878	if ((byte2 & SWS_UNMAP) == 0 &&
5879	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5880		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5881		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5882		ctl_done((union ctl_io *)ctsio);
5883		return (CTL_RETVAL_COMPLETE);
5884	}
5885
5886	/*
5887	 * The first check is to make sure we're in bounds, the second
5888	 * check is to catch wrap-around problems.  If the lba + num blocks
5889	 * is less than the lba, then we've wrapped around and the block
5890	 * range is invalid anyway.
5891	 */
5892	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5893	 || ((lba + num_blocks) < lba)) {
5894		ctl_set_lba_out_of_range(ctsio);
5895		ctl_done((union ctl_io *)ctsio);
5896		return (CTL_RETVAL_COMPLETE);
5897	}
5898
5899	/* Zero number of blocks means "to the last logical block" */
5900	if (num_blocks == 0) {
5901		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5902			ctl_set_invalid_field(ctsio,
5903					      /*sks_valid*/ 0,
5904					      /*command*/ 1,
5905					      /*field*/ 0,
5906					      /*bit_valid*/ 0,
5907					      /*bit*/ 0);
5908			ctl_done((union ctl_io *)ctsio);
5909			return (CTL_RETVAL_COMPLETE);
5910		}
5911		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5912	}
5913
5914	len = lun->be_lun->blocksize;
5915
5916	/*
5917	 * If we've got a kernel request that hasn't been malloced yet,
5918	 * malloc it and tell the caller the data buffer is here.
5919	 */
5920	if ((byte2 & SWS_NDOB) == 0 &&
5921	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5922		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5923		ctsio->kern_data_len = len;
5924		ctsio->kern_total_len = len;
5925		ctsio->kern_data_resid = 0;
5926		ctsio->kern_rel_offset = 0;
5927		ctsio->kern_sg_entries = 0;
5928		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5929		ctsio->be_move_done = ctl_config_move_done;
5930		ctl_datamove((union ctl_io *)ctsio);
5931
5932		return (CTL_RETVAL_COMPLETE);
5933	}
5934
5935	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5936	lbalen->lba = lba;
5937	lbalen->len = num_blocks;
5938	lbalen->flags = byte2;
5939	retval = lun->backend->config_write((union ctl_io *)ctsio);
5940
5941	return (retval);
5942}
5943
5944int
5945ctl_unmap(struct ctl_scsiio *ctsio)
5946{
5947	struct ctl_lun *lun;
5948	struct scsi_unmap *cdb;
5949	struct ctl_ptr_len_flags *ptrlen;
5950	struct scsi_unmap_header *hdr;
5951	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5952	uint64_t lba;
5953	uint32_t num_blocks;
5954	int len, retval;
5955	uint8_t byte2;
5956
5957	retval = CTL_RETVAL_COMPLETE;
5958
5959	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5960
5961	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5962	cdb = (struct scsi_unmap *)ctsio->cdb;
5963
5964	len = scsi_2btoul(cdb->length);
5965	byte2 = cdb->byte2;
5966
5967	/*
5968	 * If we've got a kernel request that hasn't been malloced yet,
5969	 * malloc it and tell the caller the data buffer is here.
5970	 */
5971	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5972		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5973		ctsio->kern_data_len = len;
5974		ctsio->kern_total_len = len;
5975		ctsio->kern_data_resid = 0;
5976		ctsio->kern_rel_offset = 0;
5977		ctsio->kern_sg_entries = 0;
5978		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5979		ctsio->be_move_done = ctl_config_move_done;
5980		ctl_datamove((union ctl_io *)ctsio);
5981
5982		return (CTL_RETVAL_COMPLETE);
5983	}
5984
5985	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5986	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5987	if (len < sizeof (*hdr) ||
5988	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5989	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5990	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5991		ctl_set_invalid_field(ctsio,
5992				      /*sks_valid*/ 0,
5993				      /*command*/ 0,
5994				      /*field*/ 0,
5995				      /*bit_valid*/ 0,
5996				      /*bit*/ 0);
5997		goto done;
5998	}
5999	len = scsi_2btoul(hdr->desc_length);
6000	buf = (struct scsi_unmap_desc *)(hdr + 1);
6001	end = buf + len / sizeof(*buf);
6002
6003	endnz = buf;
6004	for (range = buf; range < end; range++) {
6005		lba = scsi_8btou64(range->lba);
6006		num_blocks = scsi_4btoul(range->length);
6007		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6008		 || ((lba + num_blocks) < lba)) {
6009			ctl_set_lba_out_of_range(ctsio);
6010			ctl_done((union ctl_io *)ctsio);
6011			return (CTL_RETVAL_COMPLETE);
6012		}
6013		if (num_blocks != 0)
6014			endnz = range + 1;
6015	}
6016
6017	/*
6018	 * Block backend can not handle zero last range.
6019	 * Filter it out and return if there is nothing left.
6020	 */
6021	len = (uint8_t *)endnz - (uint8_t *)buf;
6022	if (len == 0) {
6023		ctl_set_success(ctsio);
6024		goto done;
6025	}
6026
6027	mtx_lock(&lun->lun_lock);
6028	ptrlen = (struct ctl_ptr_len_flags *)
6029	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6030	ptrlen->ptr = (void *)buf;
6031	ptrlen->len = len;
6032	ptrlen->flags = byte2;
6033	ctl_check_blocked(lun);
6034	mtx_unlock(&lun->lun_lock);
6035
6036	retval = lun->backend->config_write((union ctl_io *)ctsio);
6037	return (retval);
6038
6039done:
6040	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6041		free(ctsio->kern_data_ptr, M_CTL);
6042		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6043	}
6044	ctl_done((union ctl_io *)ctsio);
6045	return (CTL_RETVAL_COMPLETE);
6046}
6047
6048/*
6049 * Note that this function currently doesn't actually do anything inside
6050 * CTL to enforce things if the DQue bit is turned on.
6051 *
6052 * Also note that this function can't be used in the default case, because
6053 * the DQue bit isn't set in the changeable mask for the control mode page
6054 * anyway.  This is just here as an example for how to implement a page
6055 * handler, and a placeholder in case we want to allow the user to turn
6056 * tagged queueing on and off.
6057 *
6058 * The D_SENSE bit handling is functional, however, and will turn
6059 * descriptor sense on and off for a given LUN.
6060 */
6061int
6062ctl_control_page_handler(struct ctl_scsiio *ctsio,
6063			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6064{
6065	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6066	struct ctl_lun *lun;
6067	struct ctl_softc *softc;
6068	int set_ua;
6069	uint32_t initidx;
6070
6071	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6072	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6073	set_ua = 0;
6074
6075	user_cp = (struct scsi_control_page *)page_ptr;
6076	current_cp = (struct scsi_control_page *)
6077		(page_index->page_data + (page_index->page_len *
6078		CTL_PAGE_CURRENT));
6079	saved_cp = (struct scsi_control_page *)
6080		(page_index->page_data + (page_index->page_len *
6081		CTL_PAGE_SAVED));
6082
6083	softc = control_softc;
6084
6085	mtx_lock(&lun->lun_lock);
6086	if (((current_cp->rlec & SCP_DSENSE) == 0)
6087	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6088		/*
6089		 * Descriptor sense is currently turned off and the user
6090		 * wants to turn it on.
6091		 */
6092		current_cp->rlec |= SCP_DSENSE;
6093		saved_cp->rlec |= SCP_DSENSE;
6094		lun->flags |= CTL_LUN_SENSE_DESC;
6095		set_ua = 1;
6096	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6097		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6098		/*
6099		 * Descriptor sense is currently turned on, and the user
6100		 * wants to turn it off.
6101		 */
6102		current_cp->rlec &= ~SCP_DSENSE;
6103		saved_cp->rlec &= ~SCP_DSENSE;
6104		lun->flags &= ~CTL_LUN_SENSE_DESC;
6105		set_ua = 1;
6106	}
6107	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6108	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6109		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6110		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6111		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6112		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6113		set_ua = 1;
6114	}
6115	if ((current_cp->eca_and_aen & SCP_SWP) !=
6116	    (user_cp->eca_and_aen & SCP_SWP)) {
6117		current_cp->eca_and_aen &= ~SCP_SWP;
6118		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6119		saved_cp->eca_and_aen &= ~SCP_SWP;
6120		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6121		set_ua = 1;
6122	}
6123	if (set_ua != 0)
6124		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6125	mtx_unlock(&lun->lun_lock);
6126
6127	return (0);
6128}
6129
6130int
6131ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6132		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6133{
6134	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6135	struct ctl_lun *lun;
6136	int set_ua;
6137	uint32_t initidx;
6138
6139	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6140	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6141	set_ua = 0;
6142
6143	user_cp = (struct scsi_caching_page *)page_ptr;
6144	current_cp = (struct scsi_caching_page *)
6145		(page_index->page_data + (page_index->page_len *
6146		CTL_PAGE_CURRENT));
6147	saved_cp = (struct scsi_caching_page *)
6148		(page_index->page_data + (page_index->page_len *
6149		CTL_PAGE_SAVED));
6150
6151	mtx_lock(&lun->lun_lock);
6152	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6153	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6154		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6155		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6156		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6157		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6158		set_ua = 1;
6159	}
6160	if (set_ua != 0)
6161		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6162	mtx_unlock(&lun->lun_lock);
6163
6164	return (0);
6165}
6166
6167int
6168ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6169				struct ctl_page_index *page_index,
6170				uint8_t *page_ptr)
6171{
6172	uint8_t *c;
6173	int i;
6174
6175	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6176	ctl_time_io_secs =
6177		(c[0] << 8) |
6178		(c[1] << 0) |
6179		0;
6180	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6181	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6182	printf("page data:");
6183	for (i=0; i<8; i++)
6184		printf(" %.2x",page_ptr[i]);
6185	printf("\n");
6186	return (0);
6187}
6188
6189int
6190ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6191			       struct ctl_page_index *page_index,
6192			       int pc)
6193{
6194	struct copan_debugconf_subpage *page;
6195
6196	page = (struct copan_debugconf_subpage *)page_index->page_data +
6197		(page_index->page_len * pc);
6198
6199	switch (pc) {
6200	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6201	case SMS_PAGE_CTRL_DEFAULT >> 6:
6202	case SMS_PAGE_CTRL_SAVED >> 6:
6203		/*
6204		 * We don't update the changable or default bits for this page.
6205		 */
6206		break;
6207	case SMS_PAGE_CTRL_CURRENT >> 6:
6208		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6209		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6210		break;
6211	default:
6212#ifdef NEEDTOPORT
6213		EPRINT(0, "Invalid PC %d!!", pc);
6214#endif /* NEEDTOPORT */
6215		break;
6216	}
6217	return (0);
6218}
6219
6220
6221static int
6222ctl_do_mode_select(union ctl_io *io)
6223{
6224	struct scsi_mode_page_header *page_header;
6225	struct ctl_page_index *page_index;
6226	struct ctl_scsiio *ctsio;
6227	int control_dev, page_len;
6228	int page_len_offset, page_len_size;
6229	union ctl_modepage_info *modepage_info;
6230	struct ctl_lun *lun;
6231	int *len_left, *len_used;
6232	int retval, i;
6233
6234	ctsio = &io->scsiio;
6235	page_index = NULL;
6236	page_len = 0;
6237	retval = CTL_RETVAL_COMPLETE;
6238
6239	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6240
6241	if (lun->be_lun->lun_type != T_DIRECT)
6242		control_dev = 1;
6243	else
6244		control_dev = 0;
6245
6246	modepage_info = (union ctl_modepage_info *)
6247		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6248	len_left = &modepage_info->header.len_left;
6249	len_used = &modepage_info->header.len_used;
6250
6251do_next_page:
6252
6253	page_header = (struct scsi_mode_page_header *)
6254		(ctsio->kern_data_ptr + *len_used);
6255
6256	if (*len_left == 0) {
6257		free(ctsio->kern_data_ptr, M_CTL);
6258		ctl_set_success(ctsio);
6259		ctl_done((union ctl_io *)ctsio);
6260		return (CTL_RETVAL_COMPLETE);
6261	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6262
6263		free(ctsio->kern_data_ptr, M_CTL);
6264		ctl_set_param_len_error(ctsio);
6265		ctl_done((union ctl_io *)ctsio);
6266		return (CTL_RETVAL_COMPLETE);
6267
6268	} else if ((page_header->page_code & SMPH_SPF)
6269		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6270
6271		free(ctsio->kern_data_ptr, M_CTL);
6272		ctl_set_param_len_error(ctsio);
6273		ctl_done((union ctl_io *)ctsio);
6274		return (CTL_RETVAL_COMPLETE);
6275	}
6276
6277
6278	/*
6279	 * XXX KDM should we do something with the block descriptor?
6280	 */
6281	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6282
6283		if ((control_dev != 0)
6284		 && (lun->mode_pages.index[i].page_flags &
6285		     CTL_PAGE_FLAG_DISK_ONLY))
6286			continue;
6287
6288		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6289		    (page_header->page_code & SMPH_PC_MASK))
6290			continue;
6291
6292		/*
6293		 * If neither page has a subpage code, then we've got a
6294		 * match.
6295		 */
6296		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6297		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6298			page_index = &lun->mode_pages.index[i];
6299			page_len = page_header->page_length;
6300			break;
6301		}
6302
6303		/*
6304		 * If both pages have subpages, then the subpage numbers
6305		 * have to match.
6306		 */
6307		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6308		  && (page_header->page_code & SMPH_SPF)) {
6309			struct scsi_mode_page_header_sp *sph;
6310
6311			sph = (struct scsi_mode_page_header_sp *)page_header;
6312
6313			if (lun->mode_pages.index[i].subpage ==
6314			    sph->subpage) {
6315				page_index = &lun->mode_pages.index[i];
6316				page_len = scsi_2btoul(sph->page_length);
6317				break;
6318			}
6319		}
6320	}
6321
6322	/*
6323	 * If we couldn't find the page, or if we don't have a mode select
6324	 * handler for it, send back an error to the user.
6325	 */
6326	if ((page_index == NULL)
6327	 || (page_index->select_handler == NULL)) {
6328		ctl_set_invalid_field(ctsio,
6329				      /*sks_valid*/ 1,
6330				      /*command*/ 0,
6331				      /*field*/ *len_used,
6332				      /*bit_valid*/ 0,
6333				      /*bit*/ 0);
6334		free(ctsio->kern_data_ptr, M_CTL);
6335		ctl_done((union ctl_io *)ctsio);
6336		return (CTL_RETVAL_COMPLETE);
6337	}
6338
6339	if (page_index->page_code & SMPH_SPF) {
6340		page_len_offset = 2;
6341		page_len_size = 2;
6342	} else {
6343		page_len_size = 1;
6344		page_len_offset = 1;
6345	}
6346
6347	/*
6348	 * If the length the initiator gives us isn't the one we specify in
6349	 * the mode page header, or if they didn't specify enough data in
6350	 * the CDB to avoid truncating this page, kick out the request.
6351	 */
6352	if ((page_len != (page_index->page_len - page_len_offset -
6353			  page_len_size))
6354	 || (*len_left < page_index->page_len)) {
6355
6356
6357		ctl_set_invalid_field(ctsio,
6358				      /*sks_valid*/ 1,
6359				      /*command*/ 0,
6360				      /*field*/ *len_used + page_len_offset,
6361				      /*bit_valid*/ 0,
6362				      /*bit*/ 0);
6363		free(ctsio->kern_data_ptr, M_CTL);
6364		ctl_done((union ctl_io *)ctsio);
6365		return (CTL_RETVAL_COMPLETE);
6366	}
6367
6368	/*
6369	 * Run through the mode page, checking to make sure that the bits
6370	 * the user changed are actually legal for him to change.
6371	 */
6372	for (i = 0; i < page_index->page_len; i++) {
6373		uint8_t *user_byte, *change_mask, *current_byte;
6374		int bad_bit;
6375		int j;
6376
6377		user_byte = (uint8_t *)page_header + i;
6378		change_mask = page_index->page_data +
6379			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6380		current_byte = page_index->page_data +
6381			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6382
6383		/*
6384		 * Check to see whether the user set any bits in this byte
6385		 * that he is not allowed to set.
6386		 */
6387		if ((*user_byte & ~(*change_mask)) ==
6388		    (*current_byte & ~(*change_mask)))
6389			continue;
6390
6391		/*
6392		 * Go through bit by bit to determine which one is illegal.
6393		 */
6394		bad_bit = 0;
6395		for (j = 7; j >= 0; j--) {
6396			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6397			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6398				bad_bit = i;
6399				break;
6400			}
6401		}
6402		ctl_set_invalid_field(ctsio,
6403				      /*sks_valid*/ 1,
6404				      /*command*/ 0,
6405				      /*field*/ *len_used + i,
6406				      /*bit_valid*/ 1,
6407				      /*bit*/ bad_bit);
6408		free(ctsio->kern_data_ptr, M_CTL);
6409		ctl_done((union ctl_io *)ctsio);
6410		return (CTL_RETVAL_COMPLETE);
6411	}
6412
6413	/*
6414	 * Decrement these before we call the page handler, since we may
6415	 * end up getting called back one way or another before the handler
6416	 * returns to this context.
6417	 */
6418	*len_left -= page_index->page_len;
6419	*len_used += page_index->page_len;
6420
6421	retval = page_index->select_handler(ctsio, page_index,
6422					    (uint8_t *)page_header);
6423
6424	/*
6425	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6426	 * wait until this queued command completes to finish processing
6427	 * the mode page.  If it returns anything other than
6428	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6429	 * already set the sense information, freed the data pointer, and
6430	 * completed the io for us.
6431	 */
6432	if (retval != CTL_RETVAL_COMPLETE)
6433		goto bailout_no_done;
6434
6435	/*
6436	 * If the initiator sent us more than one page, parse the next one.
6437	 */
6438	if (*len_left > 0)
6439		goto do_next_page;
6440
6441	ctl_set_success(ctsio);
6442	free(ctsio->kern_data_ptr, M_CTL);
6443	ctl_done((union ctl_io *)ctsio);
6444
6445bailout_no_done:
6446
6447	return (CTL_RETVAL_COMPLETE);
6448
6449}
6450
6451int
6452ctl_mode_select(struct ctl_scsiio *ctsio)
6453{
6454	int param_len, pf, sp;
6455	int header_size, bd_len;
6456	int len_left, len_used;
6457	struct ctl_page_index *page_index;
6458	struct ctl_lun *lun;
6459	int control_dev, page_len;
6460	union ctl_modepage_info *modepage_info;
6461	int retval;
6462
6463	pf = 0;
6464	sp = 0;
6465	page_len = 0;
6466	len_used = 0;
6467	len_left = 0;
6468	retval = 0;
6469	bd_len = 0;
6470	page_index = NULL;
6471
6472	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6473
6474	if (lun->be_lun->lun_type != T_DIRECT)
6475		control_dev = 1;
6476	else
6477		control_dev = 0;
6478
6479	switch (ctsio->cdb[0]) {
6480	case MODE_SELECT_6: {
6481		struct scsi_mode_select_6 *cdb;
6482
6483		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6484
6485		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6486		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6487
6488		param_len = cdb->length;
6489		header_size = sizeof(struct scsi_mode_header_6);
6490		break;
6491	}
6492	case MODE_SELECT_10: {
6493		struct scsi_mode_select_10 *cdb;
6494
6495		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6496
6497		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6498		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6499
6500		param_len = scsi_2btoul(cdb->length);
6501		header_size = sizeof(struct scsi_mode_header_10);
6502		break;
6503	}
6504	default:
6505		ctl_set_invalid_opcode(ctsio);
6506		ctl_done((union ctl_io *)ctsio);
6507		return (CTL_RETVAL_COMPLETE);
6508		break; /* NOTREACHED */
6509	}
6510
6511	/*
6512	 * From SPC-3:
6513	 * "A parameter list length of zero indicates that the Data-Out Buffer
6514	 * shall be empty. This condition shall not be considered as an error."
6515	 */
6516	if (param_len == 0) {
6517		ctl_set_success(ctsio);
6518		ctl_done((union ctl_io *)ctsio);
6519		return (CTL_RETVAL_COMPLETE);
6520	}
6521
6522	/*
6523	 * Since we'll hit this the first time through, prior to
6524	 * allocation, we don't need to free a data buffer here.
6525	 */
6526	if (param_len < header_size) {
6527		ctl_set_param_len_error(ctsio);
6528		ctl_done((union ctl_io *)ctsio);
6529		return (CTL_RETVAL_COMPLETE);
6530	}
6531
6532	/*
6533	 * Allocate the data buffer and grab the user's data.  In theory,
6534	 * we shouldn't have to sanity check the parameter list length here
6535	 * because the maximum size is 64K.  We should be able to malloc
6536	 * that much without too many problems.
6537	 */
6538	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6539		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6540		ctsio->kern_data_len = param_len;
6541		ctsio->kern_total_len = param_len;
6542		ctsio->kern_data_resid = 0;
6543		ctsio->kern_rel_offset = 0;
6544		ctsio->kern_sg_entries = 0;
6545		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6546		ctsio->be_move_done = ctl_config_move_done;
6547		ctl_datamove((union ctl_io *)ctsio);
6548
6549		return (CTL_RETVAL_COMPLETE);
6550	}
6551
6552	switch (ctsio->cdb[0]) {
6553	case MODE_SELECT_6: {
6554		struct scsi_mode_header_6 *mh6;
6555
6556		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6557		bd_len = mh6->blk_desc_len;
6558		break;
6559	}
6560	case MODE_SELECT_10: {
6561		struct scsi_mode_header_10 *mh10;
6562
6563		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6564		bd_len = scsi_2btoul(mh10->blk_desc_len);
6565		break;
6566	}
6567	default:
6568		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6569		break;
6570	}
6571
6572	if (param_len < (header_size + bd_len)) {
6573		free(ctsio->kern_data_ptr, M_CTL);
6574		ctl_set_param_len_error(ctsio);
6575		ctl_done((union ctl_io *)ctsio);
6576		return (CTL_RETVAL_COMPLETE);
6577	}
6578
6579	/*
6580	 * Set the IO_CONT flag, so that if this I/O gets passed to
6581	 * ctl_config_write_done(), it'll get passed back to
6582	 * ctl_do_mode_select() for further processing, or completion if
6583	 * we're all done.
6584	 */
6585	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6586	ctsio->io_cont = ctl_do_mode_select;
6587
6588	modepage_info = (union ctl_modepage_info *)
6589		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6590
6591	memset(modepage_info, 0, sizeof(*modepage_info));
6592
6593	len_left = param_len - header_size - bd_len;
6594	len_used = header_size + bd_len;
6595
6596	modepage_info->header.len_left = len_left;
6597	modepage_info->header.len_used = len_used;
6598
6599	return (ctl_do_mode_select((union ctl_io *)ctsio));
6600}
6601
6602int
6603ctl_mode_sense(struct ctl_scsiio *ctsio)
6604{
6605	struct ctl_lun *lun;
6606	int pc, page_code, dbd, llba, subpage;
6607	int alloc_len, page_len, header_len, total_len;
6608	struct scsi_mode_block_descr *block_desc;
6609	struct ctl_page_index *page_index;
6610	int control_dev;
6611
6612	dbd = 0;
6613	llba = 0;
6614	block_desc = NULL;
6615	page_index = NULL;
6616
6617	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6618
6619	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6620
6621	if (lun->be_lun->lun_type != T_DIRECT)
6622		control_dev = 1;
6623	else
6624		control_dev = 0;
6625
6626	switch (ctsio->cdb[0]) {
6627	case MODE_SENSE_6: {
6628		struct scsi_mode_sense_6 *cdb;
6629
6630		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6631
6632		header_len = sizeof(struct scsi_mode_hdr_6);
6633		if (cdb->byte2 & SMS_DBD)
6634			dbd = 1;
6635		else
6636			header_len += sizeof(struct scsi_mode_block_descr);
6637
6638		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6639		page_code = cdb->page & SMS_PAGE_CODE;
6640		subpage = cdb->subpage;
6641		alloc_len = cdb->length;
6642		break;
6643	}
6644	case MODE_SENSE_10: {
6645		struct scsi_mode_sense_10 *cdb;
6646
6647		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6648
6649		header_len = sizeof(struct scsi_mode_hdr_10);
6650
6651		if (cdb->byte2 & SMS_DBD)
6652			dbd = 1;
6653		else
6654			header_len += sizeof(struct scsi_mode_block_descr);
6655		if (cdb->byte2 & SMS10_LLBAA)
6656			llba = 1;
6657		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6658		page_code = cdb->page & SMS_PAGE_CODE;
6659		subpage = cdb->subpage;
6660		alloc_len = scsi_2btoul(cdb->length);
6661		break;
6662	}
6663	default:
6664		ctl_set_invalid_opcode(ctsio);
6665		ctl_done((union ctl_io *)ctsio);
6666		return (CTL_RETVAL_COMPLETE);
6667		break; /* NOTREACHED */
6668	}
6669
6670	/*
6671	 * We have to make a first pass through to calculate the size of
6672	 * the pages that match the user's query.  Then we allocate enough
6673	 * memory to hold it, and actually copy the data into the buffer.
6674	 */
6675	switch (page_code) {
6676	case SMS_ALL_PAGES_PAGE: {
6677		int i;
6678
6679		page_len = 0;
6680
6681		/*
6682		 * At the moment, values other than 0 and 0xff here are
6683		 * reserved according to SPC-3.
6684		 */
6685		if ((subpage != SMS_SUBPAGE_PAGE_0)
6686		 && (subpage != SMS_SUBPAGE_ALL)) {
6687			ctl_set_invalid_field(ctsio,
6688					      /*sks_valid*/ 1,
6689					      /*command*/ 1,
6690					      /*field*/ 3,
6691					      /*bit_valid*/ 0,
6692					      /*bit*/ 0);
6693			ctl_done((union ctl_io *)ctsio);
6694			return (CTL_RETVAL_COMPLETE);
6695		}
6696
6697		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6698			if ((control_dev != 0)
6699			 && (lun->mode_pages.index[i].page_flags &
6700			     CTL_PAGE_FLAG_DISK_ONLY))
6701				continue;
6702
6703			/*
6704			 * We don't use this subpage if the user didn't
6705			 * request all subpages.
6706			 */
6707			if ((lun->mode_pages.index[i].subpage != 0)
6708			 && (subpage == SMS_SUBPAGE_PAGE_0))
6709				continue;
6710
6711#if 0
6712			printf("found page %#x len %d\n",
6713			       lun->mode_pages.index[i].page_code &
6714			       SMPH_PC_MASK,
6715			       lun->mode_pages.index[i].page_len);
6716#endif
6717			page_len += lun->mode_pages.index[i].page_len;
6718		}
6719		break;
6720	}
6721	default: {
6722		int i;
6723
6724		page_len = 0;
6725
6726		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6727			/* Look for the right page code */
6728			if ((lun->mode_pages.index[i].page_code &
6729			     SMPH_PC_MASK) != page_code)
6730				continue;
6731
6732			/* Look for the right subpage or the subpage wildcard*/
6733			if ((lun->mode_pages.index[i].subpage != subpage)
6734			 && (subpage != SMS_SUBPAGE_ALL))
6735				continue;
6736
6737			/* Make sure the page is supported for this dev type */
6738			if ((control_dev != 0)
6739			 && (lun->mode_pages.index[i].page_flags &
6740			     CTL_PAGE_FLAG_DISK_ONLY))
6741				continue;
6742
6743#if 0
6744			printf("found page %#x len %d\n",
6745			       lun->mode_pages.index[i].page_code &
6746			       SMPH_PC_MASK,
6747			       lun->mode_pages.index[i].page_len);
6748#endif
6749
6750			page_len += lun->mode_pages.index[i].page_len;
6751		}
6752
6753		if (page_len == 0) {
6754			ctl_set_invalid_field(ctsio,
6755					      /*sks_valid*/ 1,
6756					      /*command*/ 1,
6757					      /*field*/ 2,
6758					      /*bit_valid*/ 1,
6759					      /*bit*/ 5);
6760			ctl_done((union ctl_io *)ctsio);
6761			return (CTL_RETVAL_COMPLETE);
6762		}
6763		break;
6764	}
6765	}
6766
6767	total_len = header_len + page_len;
6768#if 0
6769	printf("header_len = %d, page_len = %d, total_len = %d\n",
6770	       header_len, page_len, total_len);
6771#endif
6772
6773	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6774	ctsio->kern_sg_entries = 0;
6775	ctsio->kern_data_resid = 0;
6776	ctsio->kern_rel_offset = 0;
6777	if (total_len < alloc_len) {
6778		ctsio->residual = alloc_len - total_len;
6779		ctsio->kern_data_len = total_len;
6780		ctsio->kern_total_len = total_len;
6781	} else {
6782		ctsio->residual = 0;
6783		ctsio->kern_data_len = alloc_len;
6784		ctsio->kern_total_len = alloc_len;
6785	}
6786
6787	switch (ctsio->cdb[0]) {
6788	case MODE_SENSE_6: {
6789		struct scsi_mode_hdr_6 *header;
6790
6791		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6792
6793		header->datalen = ctl_min(total_len - 1, 254);
6794		if (control_dev == 0) {
6795			header->dev_specific = 0x10; /* DPOFUA */
6796			if ((lun->flags & CTL_LUN_READONLY) ||
6797			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6798			    .eca_and_aen & SCP_SWP) != 0)
6799				    header->dev_specific |= 0x80; /* WP */
6800		}
6801		if (dbd)
6802			header->block_descr_len = 0;
6803		else
6804			header->block_descr_len =
6805				sizeof(struct scsi_mode_block_descr);
6806		block_desc = (struct scsi_mode_block_descr *)&header[1];
6807		break;
6808	}
6809	case MODE_SENSE_10: {
6810		struct scsi_mode_hdr_10 *header;
6811		int datalen;
6812
6813		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6814
6815		datalen = ctl_min(total_len - 2, 65533);
6816		scsi_ulto2b(datalen, header->datalen);
6817		if (control_dev == 0) {
6818			header->dev_specific = 0x10; /* DPOFUA */
6819			if ((lun->flags & CTL_LUN_READONLY) ||
6820			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6821			    .eca_and_aen & SCP_SWP) != 0)
6822				    header->dev_specific |= 0x80; /* WP */
6823		}
6824		if (dbd)
6825			scsi_ulto2b(0, header->block_descr_len);
6826		else
6827			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6828				    header->block_descr_len);
6829		block_desc = (struct scsi_mode_block_descr *)&header[1];
6830		break;
6831	}
6832	default:
6833		panic("invalid CDB type %#x", ctsio->cdb[0]);
6834		break; /* NOTREACHED */
6835	}
6836
6837	/*
6838	 * If we've got a disk, use its blocksize in the block
6839	 * descriptor.  Otherwise, just set it to 0.
6840	 */
6841	if (dbd == 0) {
6842		if (control_dev == 0)
6843			scsi_ulto3b(lun->be_lun->blocksize,
6844				    block_desc->block_len);
6845		else
6846			scsi_ulto3b(0, block_desc->block_len);
6847	}
6848
6849	switch (page_code) {
6850	case SMS_ALL_PAGES_PAGE: {
6851		int i, data_used;
6852
6853		data_used = header_len;
6854		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6855			struct ctl_page_index *page_index;
6856
6857			page_index = &lun->mode_pages.index[i];
6858
6859			if ((control_dev != 0)
6860			 && (page_index->page_flags &
6861			    CTL_PAGE_FLAG_DISK_ONLY))
6862				continue;
6863
6864			/*
6865			 * We don't use this subpage if the user didn't
6866			 * request all subpages.  We already checked (above)
6867			 * to make sure the user only specified a subpage
6868			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6869			 */
6870			if ((page_index->subpage != 0)
6871			 && (subpage == SMS_SUBPAGE_PAGE_0))
6872				continue;
6873
6874			/*
6875			 * Call the handler, if it exists, to update the
6876			 * page to the latest values.
6877			 */
6878			if (page_index->sense_handler != NULL)
6879				page_index->sense_handler(ctsio, page_index,pc);
6880
6881			memcpy(ctsio->kern_data_ptr + data_used,
6882			       page_index->page_data +
6883			       (page_index->page_len * pc),
6884			       page_index->page_len);
6885			data_used += page_index->page_len;
6886		}
6887		break;
6888	}
6889	default: {
6890		int i, data_used;
6891
6892		data_used = header_len;
6893
6894		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6895			struct ctl_page_index *page_index;
6896
6897			page_index = &lun->mode_pages.index[i];
6898
6899			/* Look for the right page code */
6900			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6901				continue;
6902
6903			/* Look for the right subpage or the subpage wildcard*/
6904			if ((page_index->subpage != subpage)
6905			 && (subpage != SMS_SUBPAGE_ALL))
6906				continue;
6907
6908			/* Make sure the page is supported for this dev type */
6909			if ((control_dev != 0)
6910			 && (page_index->page_flags &
6911			     CTL_PAGE_FLAG_DISK_ONLY))
6912				continue;
6913
6914			/*
6915			 * Call the handler, if it exists, to update the
6916			 * page to the latest values.
6917			 */
6918			if (page_index->sense_handler != NULL)
6919				page_index->sense_handler(ctsio, page_index,pc);
6920
6921			memcpy(ctsio->kern_data_ptr + data_used,
6922			       page_index->page_data +
6923			       (page_index->page_len * pc),
6924			       page_index->page_len);
6925			data_used += page_index->page_len;
6926		}
6927		break;
6928	}
6929	}
6930
6931	ctl_set_success(ctsio);
6932	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6933	ctsio->be_move_done = ctl_config_move_done;
6934	ctl_datamove((union ctl_io *)ctsio);
6935	return (CTL_RETVAL_COMPLETE);
6936}
6937
6938int
6939ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6940			       struct ctl_page_index *page_index,
6941			       int pc)
6942{
6943	struct ctl_lun *lun;
6944	struct scsi_log_param_header *phdr;
6945	uint8_t *data;
6946	uint64_t val;
6947
6948	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6949	data = page_index->page_data;
6950
6951	if (lun->backend->lun_attr != NULL &&
6952	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6953	     != UINT64_MAX) {
6954		phdr = (struct scsi_log_param_header *)data;
6955		scsi_ulto2b(0x0001, phdr->param_code);
6956		phdr->param_control = SLP_LBIN | SLP_LP;
6957		phdr->param_len = 8;
6958		data = (uint8_t *)(phdr + 1);
6959		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6960		data[4] = 0x02; /* per-pool */
6961		data += phdr->param_len;
6962	}
6963
6964	if (lun->backend->lun_attr != NULL &&
6965	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6966	     != UINT64_MAX) {
6967		phdr = (struct scsi_log_param_header *)data;
6968		scsi_ulto2b(0x0002, phdr->param_code);
6969		phdr->param_control = SLP_LBIN | SLP_LP;
6970		phdr->param_len = 8;
6971		data = (uint8_t *)(phdr + 1);
6972		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6973		data[4] = 0x01; /* per-LUN */
6974		data += phdr->param_len;
6975	}
6976
6977	if (lun->backend->lun_attr != NULL &&
6978	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6979	     != UINT64_MAX) {
6980		phdr = (struct scsi_log_param_header *)data;
6981		scsi_ulto2b(0x00f1, phdr->param_code);
6982		phdr->param_control = SLP_LBIN | SLP_LP;
6983		phdr->param_len = 8;
6984		data = (uint8_t *)(phdr + 1);
6985		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6986		data[4] = 0x02; /* per-pool */
6987		data += phdr->param_len;
6988	}
6989
6990	if (lun->backend->lun_attr != NULL &&
6991	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6992	     != UINT64_MAX) {
6993		phdr = (struct scsi_log_param_header *)data;
6994		scsi_ulto2b(0x00f2, phdr->param_code);
6995		phdr->param_control = SLP_LBIN | SLP_LP;
6996		phdr->param_len = 8;
6997		data = (uint8_t *)(phdr + 1);
6998		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6999		data[4] = 0x02; /* per-pool */
7000		data += phdr->param_len;
7001	}
7002
7003	page_index->page_len = data - page_index->page_data;
7004	return (0);
7005}
7006
7007int
7008ctl_log_sense(struct ctl_scsiio *ctsio)
7009{
7010	struct ctl_lun *lun;
7011	int i, pc, page_code, subpage;
7012	int alloc_len, total_len;
7013	struct ctl_page_index *page_index;
7014	struct scsi_log_sense *cdb;
7015	struct scsi_log_header *header;
7016
7017	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7018
7019	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7020	cdb = (struct scsi_log_sense *)ctsio->cdb;
7021	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7022	page_code = cdb->page & SLS_PAGE_CODE;
7023	subpage = cdb->subpage;
7024	alloc_len = scsi_2btoul(cdb->length);
7025
7026	page_index = NULL;
7027	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7028		page_index = &lun->log_pages.index[i];
7029
7030		/* Look for the right page code */
7031		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7032			continue;
7033
7034		/* Look for the right subpage or the subpage wildcard*/
7035		if (page_index->subpage != subpage)
7036			continue;
7037
7038		break;
7039	}
7040	if (i >= CTL_NUM_LOG_PAGES) {
7041		ctl_set_invalid_field(ctsio,
7042				      /*sks_valid*/ 1,
7043				      /*command*/ 1,
7044				      /*field*/ 2,
7045				      /*bit_valid*/ 0,
7046				      /*bit*/ 0);
7047		ctl_done((union ctl_io *)ctsio);
7048		return (CTL_RETVAL_COMPLETE);
7049	}
7050
7051	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7052
7053	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7054	ctsio->kern_sg_entries = 0;
7055	ctsio->kern_data_resid = 0;
7056	ctsio->kern_rel_offset = 0;
7057	if (total_len < alloc_len) {
7058		ctsio->residual = alloc_len - total_len;
7059		ctsio->kern_data_len = total_len;
7060		ctsio->kern_total_len = total_len;
7061	} else {
7062		ctsio->residual = 0;
7063		ctsio->kern_data_len = alloc_len;
7064		ctsio->kern_total_len = alloc_len;
7065	}
7066
7067	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7068	header->page = page_index->page_code;
7069	if (page_index->subpage) {
7070		header->page |= SL_SPF;
7071		header->subpage = page_index->subpage;
7072	}
7073	scsi_ulto2b(page_index->page_len, header->datalen);
7074
7075	/*
7076	 * Call the handler, if it exists, to update the
7077	 * page to the latest values.
7078	 */
7079	if (page_index->sense_handler != NULL)
7080		page_index->sense_handler(ctsio, page_index, pc);
7081
7082	memcpy(header + 1, page_index->page_data, page_index->page_len);
7083
7084	ctl_set_success(ctsio);
7085	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7086	ctsio->be_move_done = ctl_config_move_done;
7087	ctl_datamove((union ctl_io *)ctsio);
7088	return (CTL_RETVAL_COMPLETE);
7089}
7090
7091int
7092ctl_read_capacity(struct ctl_scsiio *ctsio)
7093{
7094	struct scsi_read_capacity *cdb;
7095	struct scsi_read_capacity_data *data;
7096	struct ctl_lun *lun;
7097	uint32_t lba;
7098
7099	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7100
7101	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7102
7103	lba = scsi_4btoul(cdb->addr);
7104	if (((cdb->pmi & SRC_PMI) == 0)
7105	 && (lba != 0)) {
7106		ctl_set_invalid_field(/*ctsio*/ ctsio,
7107				      /*sks_valid*/ 1,
7108				      /*command*/ 1,
7109				      /*field*/ 2,
7110				      /*bit_valid*/ 0,
7111				      /*bit*/ 0);
7112		ctl_done((union ctl_io *)ctsio);
7113		return (CTL_RETVAL_COMPLETE);
7114	}
7115
7116	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7117
7118	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7119	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7120	ctsio->residual = 0;
7121	ctsio->kern_data_len = sizeof(*data);
7122	ctsio->kern_total_len = sizeof(*data);
7123	ctsio->kern_data_resid = 0;
7124	ctsio->kern_rel_offset = 0;
7125	ctsio->kern_sg_entries = 0;
7126
7127	/*
7128	 * If the maximum LBA is greater than 0xfffffffe, the user must
7129	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7130	 * serivce action set.
7131	 */
7132	if (lun->be_lun->maxlba > 0xfffffffe)
7133		scsi_ulto4b(0xffffffff, data->addr);
7134	else
7135		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7136
7137	/*
7138	 * XXX KDM this may not be 512 bytes...
7139	 */
7140	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7141
7142	ctl_set_success(ctsio);
7143	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7144	ctsio->be_move_done = ctl_config_move_done;
7145	ctl_datamove((union ctl_io *)ctsio);
7146	return (CTL_RETVAL_COMPLETE);
7147}
7148
7149int
7150ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7151{
7152	struct scsi_read_capacity_16 *cdb;
7153	struct scsi_read_capacity_data_long *data;
7154	struct ctl_lun *lun;
7155	uint64_t lba;
7156	uint32_t alloc_len;
7157
7158	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7159
7160	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7161
7162	alloc_len = scsi_4btoul(cdb->alloc_len);
7163	lba = scsi_8btou64(cdb->addr);
7164
7165	if ((cdb->reladr & SRC16_PMI)
7166	 && (lba != 0)) {
7167		ctl_set_invalid_field(/*ctsio*/ ctsio,
7168				      /*sks_valid*/ 1,
7169				      /*command*/ 1,
7170				      /*field*/ 2,
7171				      /*bit_valid*/ 0,
7172				      /*bit*/ 0);
7173		ctl_done((union ctl_io *)ctsio);
7174		return (CTL_RETVAL_COMPLETE);
7175	}
7176
7177	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7178
7179	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7180	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7181
7182	if (sizeof(*data) < alloc_len) {
7183		ctsio->residual = alloc_len - sizeof(*data);
7184		ctsio->kern_data_len = sizeof(*data);
7185		ctsio->kern_total_len = sizeof(*data);
7186	} else {
7187		ctsio->residual = 0;
7188		ctsio->kern_data_len = alloc_len;
7189		ctsio->kern_total_len = alloc_len;
7190	}
7191	ctsio->kern_data_resid = 0;
7192	ctsio->kern_rel_offset = 0;
7193	ctsio->kern_sg_entries = 0;
7194
7195	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7196	/* XXX KDM this may not be 512 bytes... */
7197	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7198	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7199	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7200	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7201		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7202
7203	ctl_set_success(ctsio);
7204	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7205	ctsio->be_move_done = ctl_config_move_done;
7206	ctl_datamove((union ctl_io *)ctsio);
7207	return (CTL_RETVAL_COMPLETE);
7208}
7209
7210int
7211ctl_get_lba_status(struct ctl_scsiio *ctsio)
7212{
7213	struct scsi_get_lba_status *cdb;
7214	struct scsi_get_lba_status_data *data;
7215	struct ctl_lun *lun;
7216	struct ctl_lba_len_flags *lbalen;
7217	uint64_t lba;
7218	uint32_t alloc_len, total_len;
7219	int retval;
7220
7221	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7222
7223	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7224	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7225	lba = scsi_8btou64(cdb->addr);
7226	alloc_len = scsi_4btoul(cdb->alloc_len);
7227
7228	if (lba > lun->be_lun->maxlba) {
7229		ctl_set_lba_out_of_range(ctsio);
7230		ctl_done((union ctl_io *)ctsio);
7231		return (CTL_RETVAL_COMPLETE);
7232	}
7233
7234	total_len = sizeof(*data) + sizeof(data->descr[0]);
7235	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7236	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7237
7238	if (total_len < alloc_len) {
7239		ctsio->residual = alloc_len - total_len;
7240		ctsio->kern_data_len = total_len;
7241		ctsio->kern_total_len = total_len;
7242	} else {
7243		ctsio->residual = 0;
7244		ctsio->kern_data_len = alloc_len;
7245		ctsio->kern_total_len = alloc_len;
7246	}
7247	ctsio->kern_data_resid = 0;
7248	ctsio->kern_rel_offset = 0;
7249	ctsio->kern_sg_entries = 0;
7250
7251	/* Fill dummy data in case backend can't tell anything. */
7252	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7253	scsi_u64to8b(lba, data->descr[0].addr);
7254	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7255	    data->descr[0].length);
7256	data->descr[0].status = 0; /* Mapped or unknown. */
7257
7258	ctl_set_success(ctsio);
7259	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7260	ctsio->be_move_done = ctl_config_move_done;
7261
7262	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7263	lbalen->lba = lba;
7264	lbalen->len = total_len;
7265	lbalen->flags = 0;
7266	retval = lun->backend->config_read((union ctl_io *)ctsio);
7267	return (CTL_RETVAL_COMPLETE);
7268}
7269
7270int
7271ctl_read_defect(struct ctl_scsiio *ctsio)
7272{
7273	struct scsi_read_defect_data_10 *ccb10;
7274	struct scsi_read_defect_data_12 *ccb12;
7275	struct scsi_read_defect_data_hdr_10 *data10;
7276	struct scsi_read_defect_data_hdr_12 *data12;
7277	uint32_t alloc_len, data_len;
7278	uint8_t format;
7279
7280	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7281
7282	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7283		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7284		format = ccb10->format;
7285		alloc_len = scsi_2btoul(ccb10->alloc_length);
7286		data_len = sizeof(*data10);
7287	} else {
7288		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7289		format = ccb12->format;
7290		alloc_len = scsi_4btoul(ccb12->alloc_length);
7291		data_len = sizeof(*data12);
7292	}
7293	if (alloc_len == 0) {
7294		ctl_set_success(ctsio);
7295		ctl_done((union ctl_io *)ctsio);
7296		return (CTL_RETVAL_COMPLETE);
7297	}
7298
7299	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7300	if (data_len < alloc_len) {
7301		ctsio->residual = alloc_len - data_len;
7302		ctsio->kern_data_len = data_len;
7303		ctsio->kern_total_len = data_len;
7304	} else {
7305		ctsio->residual = 0;
7306		ctsio->kern_data_len = alloc_len;
7307		ctsio->kern_total_len = alloc_len;
7308	}
7309	ctsio->kern_data_resid = 0;
7310	ctsio->kern_rel_offset = 0;
7311	ctsio->kern_sg_entries = 0;
7312
7313	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7314		data10 = (struct scsi_read_defect_data_hdr_10 *)
7315		    ctsio->kern_data_ptr;
7316		data10->format = format;
7317		scsi_ulto2b(0, data10->length);
7318	} else {
7319		data12 = (struct scsi_read_defect_data_hdr_12 *)
7320		    ctsio->kern_data_ptr;
7321		data12->format = format;
7322		scsi_ulto2b(0, data12->generation);
7323		scsi_ulto4b(0, data12->length);
7324	}
7325
7326	ctl_set_success(ctsio);
7327	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7328	ctsio->be_move_done = ctl_config_move_done;
7329	ctl_datamove((union ctl_io *)ctsio);
7330	return (CTL_RETVAL_COMPLETE);
7331}
7332
7333int
7334ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7335{
7336	struct scsi_maintenance_in *cdb;
7337	int retval;
7338	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7339	int num_target_port_groups, num_target_ports;
7340	struct ctl_lun *lun;
7341	struct ctl_softc *softc;
7342	struct ctl_port *port;
7343	struct scsi_target_group_data *rtg_ptr;
7344	struct scsi_target_group_data_extended *rtg_ext_ptr;
7345	struct scsi_target_port_group_descriptor *tpg_desc;
7346
7347	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7348
7349	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7350	softc = control_softc;
7351	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7352
7353	retval = CTL_RETVAL_COMPLETE;
7354
7355	switch (cdb->byte2 & STG_PDF_MASK) {
7356	case STG_PDF_LENGTH:
7357		ext = 0;
7358		break;
7359	case STG_PDF_EXTENDED:
7360		ext = 1;
7361		break;
7362	default:
7363		ctl_set_invalid_field(/*ctsio*/ ctsio,
7364				      /*sks_valid*/ 1,
7365				      /*command*/ 1,
7366				      /*field*/ 2,
7367				      /*bit_valid*/ 1,
7368				      /*bit*/ 5);
7369		ctl_done((union ctl_io *)ctsio);
7370		return(retval);
7371	}
7372
7373	if (softc->is_single)
7374		num_target_port_groups = 1;
7375	else
7376		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7377	num_target_ports = 0;
7378	mtx_lock(&softc->ctl_lock);
7379	STAILQ_FOREACH(port, &softc->port_list, links) {
7380		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7381			continue;
7382		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7383			continue;
7384		num_target_ports++;
7385	}
7386	mtx_unlock(&softc->ctl_lock);
7387
7388	if (ext)
7389		total_len = sizeof(struct scsi_target_group_data_extended);
7390	else
7391		total_len = sizeof(struct scsi_target_group_data);
7392	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7393		num_target_port_groups +
7394	    sizeof(struct scsi_target_port_descriptor) *
7395		num_target_ports * num_target_port_groups;
7396
7397	alloc_len = scsi_4btoul(cdb->length);
7398
7399	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7400
7401	ctsio->kern_sg_entries = 0;
7402
7403	if (total_len < alloc_len) {
7404		ctsio->residual = alloc_len - total_len;
7405		ctsio->kern_data_len = total_len;
7406		ctsio->kern_total_len = total_len;
7407	} else {
7408		ctsio->residual = 0;
7409		ctsio->kern_data_len = alloc_len;
7410		ctsio->kern_total_len = alloc_len;
7411	}
7412	ctsio->kern_data_resid = 0;
7413	ctsio->kern_rel_offset = 0;
7414
7415	if (ext) {
7416		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7417		    ctsio->kern_data_ptr;
7418		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7419		rtg_ext_ptr->format_type = 0x10;
7420		rtg_ext_ptr->implicit_transition_time = 0;
7421		tpg_desc = &rtg_ext_ptr->groups[0];
7422	} else {
7423		rtg_ptr = (struct scsi_target_group_data *)
7424		    ctsio->kern_data_ptr;
7425		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7426		tpg_desc = &rtg_ptr->groups[0];
7427	}
7428
7429	mtx_lock(&softc->ctl_lock);
7430	pg = softc->port_offset / CTL_MAX_PORTS;
7431	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7432		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7433			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7434			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7435		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7436			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7437			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7438		} else {
7439			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7440			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7441		}
7442	} else {
7443		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7444		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7445	}
7446	for (g = 0; g < num_target_port_groups; g++) {
7447		tpg_desc->pref_state = (g == pg) ? gs : os;
7448		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7449		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7450		tpg_desc->status = TPG_IMPLICIT;
7451		pc = 0;
7452		STAILQ_FOREACH(port, &softc->port_list, links) {
7453			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7454				continue;
7455			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7456			    CTL_MAX_LUNS)
7457				continue;
7458			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7459			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7460			    relative_target_port_identifier);
7461			pc++;
7462		}
7463		tpg_desc->target_port_count = pc;
7464		tpg_desc = (struct scsi_target_port_group_descriptor *)
7465		    &tpg_desc->descriptors[pc];
7466	}
7467	mtx_unlock(&softc->ctl_lock);
7468
7469	ctl_set_success(ctsio);
7470	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7471	ctsio->be_move_done = ctl_config_move_done;
7472	ctl_datamove((union ctl_io *)ctsio);
7473	return(retval);
7474}
7475
7476int
7477ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7478{
7479	struct ctl_lun *lun;
7480	struct scsi_report_supported_opcodes *cdb;
7481	const struct ctl_cmd_entry *entry, *sentry;
7482	struct scsi_report_supported_opcodes_all *all;
7483	struct scsi_report_supported_opcodes_descr *descr;
7484	struct scsi_report_supported_opcodes_one *one;
7485	int retval;
7486	int alloc_len, total_len;
7487	int opcode, service_action, i, j, num;
7488
7489	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7490
7491	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7492	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7493
7494	retval = CTL_RETVAL_COMPLETE;
7495
7496	opcode = cdb->requested_opcode;
7497	service_action = scsi_2btoul(cdb->requested_service_action);
7498	switch (cdb->options & RSO_OPTIONS_MASK) {
7499	case RSO_OPTIONS_ALL:
7500		num = 0;
7501		for (i = 0; i < 256; i++) {
7502			entry = &ctl_cmd_table[i];
7503			if (entry->flags & CTL_CMD_FLAG_SA5) {
7504				for (j = 0; j < 32; j++) {
7505					sentry = &((const struct ctl_cmd_entry *)
7506					    entry->execute)[j];
7507					if (ctl_cmd_applicable(
7508					    lun->be_lun->lun_type, sentry))
7509						num++;
7510				}
7511			} else {
7512				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7513				    entry))
7514					num++;
7515			}
7516		}
7517		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7518		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7519		break;
7520	case RSO_OPTIONS_OC:
7521		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7522			ctl_set_invalid_field(/*ctsio*/ ctsio,
7523					      /*sks_valid*/ 1,
7524					      /*command*/ 1,
7525					      /*field*/ 2,
7526					      /*bit_valid*/ 1,
7527					      /*bit*/ 2);
7528			ctl_done((union ctl_io *)ctsio);
7529			return (CTL_RETVAL_COMPLETE);
7530		}
7531		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7532		break;
7533	case RSO_OPTIONS_OC_SA:
7534		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7535		    service_action >= 32) {
7536			ctl_set_invalid_field(/*ctsio*/ ctsio,
7537					      /*sks_valid*/ 1,
7538					      /*command*/ 1,
7539					      /*field*/ 2,
7540					      /*bit_valid*/ 1,
7541					      /*bit*/ 2);
7542			ctl_done((union ctl_io *)ctsio);
7543			return (CTL_RETVAL_COMPLETE);
7544		}
7545		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7546		break;
7547	default:
7548		ctl_set_invalid_field(/*ctsio*/ ctsio,
7549				      /*sks_valid*/ 1,
7550				      /*command*/ 1,
7551				      /*field*/ 2,
7552				      /*bit_valid*/ 1,
7553				      /*bit*/ 2);
7554		ctl_done((union ctl_io *)ctsio);
7555		return (CTL_RETVAL_COMPLETE);
7556	}
7557
7558	alloc_len = scsi_4btoul(cdb->length);
7559
7560	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7561
7562	ctsio->kern_sg_entries = 0;
7563
7564	if (total_len < alloc_len) {
7565		ctsio->residual = alloc_len - total_len;
7566		ctsio->kern_data_len = total_len;
7567		ctsio->kern_total_len = total_len;
7568	} else {
7569		ctsio->residual = 0;
7570		ctsio->kern_data_len = alloc_len;
7571		ctsio->kern_total_len = alloc_len;
7572	}
7573	ctsio->kern_data_resid = 0;
7574	ctsio->kern_rel_offset = 0;
7575
7576	switch (cdb->options & RSO_OPTIONS_MASK) {
7577	case RSO_OPTIONS_ALL:
7578		all = (struct scsi_report_supported_opcodes_all *)
7579		    ctsio->kern_data_ptr;
7580		num = 0;
7581		for (i = 0; i < 256; i++) {
7582			entry = &ctl_cmd_table[i];
7583			if (entry->flags & CTL_CMD_FLAG_SA5) {
7584				for (j = 0; j < 32; j++) {
7585					sentry = &((const struct ctl_cmd_entry *)
7586					    entry->execute)[j];
7587					if (!ctl_cmd_applicable(
7588					    lun->be_lun->lun_type, sentry))
7589						continue;
7590					descr = &all->descr[num++];
7591					descr->opcode = i;
7592					scsi_ulto2b(j, descr->service_action);
7593					descr->flags = RSO_SERVACTV;
7594					scsi_ulto2b(sentry->length,
7595					    descr->cdb_length);
7596				}
7597			} else {
7598				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7599				    entry))
7600					continue;
7601				descr = &all->descr[num++];
7602				descr->opcode = i;
7603				scsi_ulto2b(0, descr->service_action);
7604				descr->flags = 0;
7605				scsi_ulto2b(entry->length, descr->cdb_length);
7606			}
7607		}
7608		scsi_ulto4b(
7609		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7610		    all->length);
7611		break;
7612	case RSO_OPTIONS_OC:
7613		one = (struct scsi_report_supported_opcodes_one *)
7614		    ctsio->kern_data_ptr;
7615		entry = &ctl_cmd_table[opcode];
7616		goto fill_one;
7617	case RSO_OPTIONS_OC_SA:
7618		one = (struct scsi_report_supported_opcodes_one *)
7619		    ctsio->kern_data_ptr;
7620		entry = &ctl_cmd_table[opcode];
7621		entry = &((const struct ctl_cmd_entry *)
7622		    entry->execute)[service_action];
7623fill_one:
7624		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7625			one->support = 3;
7626			scsi_ulto2b(entry->length, one->cdb_length);
7627			one->cdb_usage[0] = opcode;
7628			memcpy(&one->cdb_usage[1], entry->usage,
7629			    entry->length - 1);
7630		} else
7631			one->support = 1;
7632		break;
7633	}
7634
7635	ctl_set_success(ctsio);
7636	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7637	ctsio->be_move_done = ctl_config_move_done;
7638	ctl_datamove((union ctl_io *)ctsio);
7639	return(retval);
7640}
7641
7642int
7643ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7644{
7645	struct scsi_report_supported_tmf *cdb;
7646	struct scsi_report_supported_tmf_data *data;
7647	int retval;
7648	int alloc_len, total_len;
7649
7650	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7651
7652	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7653
7654	retval = CTL_RETVAL_COMPLETE;
7655
7656	total_len = sizeof(struct scsi_report_supported_tmf_data);
7657	alloc_len = scsi_4btoul(cdb->length);
7658
7659	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7660
7661	ctsio->kern_sg_entries = 0;
7662
7663	if (total_len < alloc_len) {
7664		ctsio->residual = alloc_len - total_len;
7665		ctsio->kern_data_len = total_len;
7666		ctsio->kern_total_len = total_len;
7667	} else {
7668		ctsio->residual = 0;
7669		ctsio->kern_data_len = alloc_len;
7670		ctsio->kern_total_len = alloc_len;
7671	}
7672	ctsio->kern_data_resid = 0;
7673	ctsio->kern_rel_offset = 0;
7674
7675	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7676	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7677	data->byte2 |= RST_ITNRS;
7678
7679	ctl_set_success(ctsio);
7680	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7681	ctsio->be_move_done = ctl_config_move_done;
7682	ctl_datamove((union ctl_io *)ctsio);
7683	return (retval);
7684}
7685
7686int
7687ctl_report_timestamp(struct ctl_scsiio *ctsio)
7688{
7689	struct scsi_report_timestamp *cdb;
7690	struct scsi_report_timestamp_data *data;
7691	struct timeval tv;
7692	int64_t timestamp;
7693	int retval;
7694	int alloc_len, total_len;
7695
7696	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7697
7698	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7699
7700	retval = CTL_RETVAL_COMPLETE;
7701
7702	total_len = sizeof(struct scsi_report_timestamp_data);
7703	alloc_len = scsi_4btoul(cdb->length);
7704
7705	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7706
7707	ctsio->kern_sg_entries = 0;
7708
7709	if (total_len < alloc_len) {
7710		ctsio->residual = alloc_len - total_len;
7711		ctsio->kern_data_len = total_len;
7712		ctsio->kern_total_len = total_len;
7713	} else {
7714		ctsio->residual = 0;
7715		ctsio->kern_data_len = alloc_len;
7716		ctsio->kern_total_len = alloc_len;
7717	}
7718	ctsio->kern_data_resid = 0;
7719	ctsio->kern_rel_offset = 0;
7720
7721	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7722	scsi_ulto2b(sizeof(*data) - 2, data->length);
7723	data->origin = RTS_ORIG_OUTSIDE;
7724	getmicrotime(&tv);
7725	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7726	scsi_ulto4b(timestamp >> 16, data->timestamp);
7727	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7728
7729	ctl_set_success(ctsio);
7730	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7731	ctsio->be_move_done = ctl_config_move_done;
7732	ctl_datamove((union ctl_io *)ctsio);
7733	return (retval);
7734}
7735
7736int
7737ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7738{
7739	struct scsi_per_res_in *cdb;
7740	int alloc_len, total_len = 0;
7741	/* struct scsi_per_res_in_rsrv in_data; */
7742	struct ctl_lun *lun;
7743	struct ctl_softc *softc;
7744	uint64_t key;
7745
7746	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7747
7748	softc = control_softc;
7749
7750	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7751
7752	alloc_len = scsi_2btoul(cdb->length);
7753
7754	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7755
7756retry:
7757	mtx_lock(&lun->lun_lock);
7758	switch (cdb->action) {
7759	case SPRI_RK: /* read keys */
7760		total_len = sizeof(struct scsi_per_res_in_keys) +
7761			lun->pr_key_count *
7762			sizeof(struct scsi_per_res_key);
7763		break;
7764	case SPRI_RR: /* read reservation */
7765		if (lun->flags & CTL_LUN_PR_RESERVED)
7766			total_len = sizeof(struct scsi_per_res_in_rsrv);
7767		else
7768			total_len = sizeof(struct scsi_per_res_in_header);
7769		break;
7770	case SPRI_RC: /* report capabilities */
7771		total_len = sizeof(struct scsi_per_res_cap);
7772		break;
7773	case SPRI_RS: /* read full status */
7774		total_len = sizeof(struct scsi_per_res_in_header) +
7775		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7776		    lun->pr_key_count;
7777		break;
7778	default:
7779		panic("Invalid PR type %x", cdb->action);
7780	}
7781	mtx_unlock(&lun->lun_lock);
7782
7783	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7784
7785	if (total_len < alloc_len) {
7786		ctsio->residual = alloc_len - total_len;
7787		ctsio->kern_data_len = total_len;
7788		ctsio->kern_total_len = total_len;
7789	} else {
7790		ctsio->residual = 0;
7791		ctsio->kern_data_len = alloc_len;
7792		ctsio->kern_total_len = alloc_len;
7793	}
7794
7795	ctsio->kern_data_resid = 0;
7796	ctsio->kern_rel_offset = 0;
7797	ctsio->kern_sg_entries = 0;
7798
7799	mtx_lock(&lun->lun_lock);
7800	switch (cdb->action) {
7801	case SPRI_RK: { // read keys
7802        struct scsi_per_res_in_keys *res_keys;
7803		int i, key_count;
7804
7805		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7806
7807		/*
7808		 * We had to drop the lock to allocate our buffer, which
7809		 * leaves time for someone to come in with another
7810		 * persistent reservation.  (That is unlikely, though,
7811		 * since this should be the only persistent reservation
7812		 * command active right now.)
7813		 */
7814		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7815		    (lun->pr_key_count *
7816		     sizeof(struct scsi_per_res_key)))){
7817			mtx_unlock(&lun->lun_lock);
7818			free(ctsio->kern_data_ptr, M_CTL);
7819			printf("%s: reservation length changed, retrying\n",
7820			       __func__);
7821			goto retry;
7822		}
7823
7824		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7825
7826		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7827			     lun->pr_key_count, res_keys->header.length);
7828
7829		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7830			if ((key = ctl_get_prkey(lun, i)) == 0)
7831				continue;
7832
7833			/*
7834			 * We used lun->pr_key_count to calculate the
7835			 * size to allocate.  If it turns out the number of
7836			 * initiators with the registered flag set is
7837			 * larger than that (i.e. they haven't been kept in
7838			 * sync), we've got a problem.
7839			 */
7840			if (key_count >= lun->pr_key_count) {
7841#ifdef NEEDTOPORT
7842				csevent_log(CSC_CTL | CSC_SHELF_SW |
7843					    CTL_PR_ERROR,
7844					    csevent_LogType_Fault,
7845					    csevent_AlertLevel_Yellow,
7846					    csevent_FRU_ShelfController,
7847					    csevent_FRU_Firmware,
7848				        csevent_FRU_Unknown,
7849					    "registered keys %d >= key "
7850					    "count %d", key_count,
7851					    lun->pr_key_count);
7852#endif
7853				key_count++;
7854				continue;
7855			}
7856			scsi_u64to8b(key, res_keys->keys[key_count].key);
7857			key_count++;
7858		}
7859		break;
7860	}
7861	case SPRI_RR: { // read reservation
7862		struct scsi_per_res_in_rsrv *res;
7863		int tmp_len, header_only;
7864
7865		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7866
7867		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7868
7869		if (lun->flags & CTL_LUN_PR_RESERVED)
7870		{
7871			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7872			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7873				    res->header.length);
7874			header_only = 0;
7875		} else {
7876			tmp_len = sizeof(struct scsi_per_res_in_header);
7877			scsi_ulto4b(0, res->header.length);
7878			header_only = 1;
7879		}
7880
7881		/*
7882		 * We had to drop the lock to allocate our buffer, which
7883		 * leaves time for someone to come in with another
7884		 * persistent reservation.  (That is unlikely, though,
7885		 * since this should be the only persistent reservation
7886		 * command active right now.)
7887		 */
7888		if (tmp_len != total_len) {
7889			mtx_unlock(&lun->lun_lock);
7890			free(ctsio->kern_data_ptr, M_CTL);
7891			printf("%s: reservation status changed, retrying\n",
7892			       __func__);
7893			goto retry;
7894		}
7895
7896		/*
7897		 * No reservation held, so we're done.
7898		 */
7899		if (header_only != 0)
7900			break;
7901
7902		/*
7903		 * If the registration is an All Registrants type, the key
7904		 * is 0, since it doesn't really matter.
7905		 */
7906		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7907			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7908			    res->data.reservation);
7909		}
7910		res->data.scopetype = lun->res_type;
7911		break;
7912	}
7913	case SPRI_RC:     //report capabilities
7914	{
7915		struct scsi_per_res_cap *res_cap;
7916		uint16_t type_mask;
7917
7918		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7919		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7920		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7921		type_mask = SPRI_TM_WR_EX_AR |
7922			    SPRI_TM_EX_AC_RO |
7923			    SPRI_TM_WR_EX_RO |
7924			    SPRI_TM_EX_AC |
7925			    SPRI_TM_WR_EX |
7926			    SPRI_TM_EX_AC_AR;
7927		scsi_ulto2b(type_mask, res_cap->type_mask);
7928		break;
7929	}
7930	case SPRI_RS: { // read full status
7931		struct scsi_per_res_in_full *res_status;
7932		struct scsi_per_res_in_full_desc *res_desc;
7933		struct ctl_port *port;
7934		int i, len;
7935
7936		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7937
7938		/*
7939		 * We had to drop the lock to allocate our buffer, which
7940		 * leaves time for someone to come in with another
7941		 * persistent reservation.  (That is unlikely, though,
7942		 * since this should be the only persistent reservation
7943		 * command active right now.)
7944		 */
7945		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7946		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7947		     lun->pr_key_count)){
7948			mtx_unlock(&lun->lun_lock);
7949			free(ctsio->kern_data_ptr, M_CTL);
7950			printf("%s: reservation length changed, retrying\n",
7951			       __func__);
7952			goto retry;
7953		}
7954
7955		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7956
7957		res_desc = &res_status->desc[0];
7958		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7959			if ((key = ctl_get_prkey(lun, i)) == 0)
7960				continue;
7961
7962			scsi_u64to8b(key, res_desc->res_key.key);
7963			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7964			    (lun->pr_res_idx == i ||
7965			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7966				res_desc->flags = SPRI_FULL_R_HOLDER;
7967				res_desc->scopetype = lun->res_type;
7968			}
7969			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7970			    res_desc->rel_trgt_port_id);
7971			len = 0;
7972			port = softc->ctl_ports[
7973			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7974			if (port != NULL)
7975				len = ctl_create_iid(port,
7976				    i % CTL_MAX_INIT_PER_PORT,
7977				    res_desc->transport_id);
7978			scsi_ulto4b(len, res_desc->additional_length);
7979			res_desc = (struct scsi_per_res_in_full_desc *)
7980			    &res_desc->transport_id[len];
7981		}
7982		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7983		    res_status->header.length);
7984		break;
7985	}
7986	default:
7987		/*
7988		 * This is a bug, because we just checked for this above,
7989		 * and should have returned an error.
7990		 */
7991		panic("Invalid PR type %x", cdb->action);
7992		break; /* NOTREACHED */
7993	}
7994	mtx_unlock(&lun->lun_lock);
7995
7996	ctl_set_success(ctsio);
7997	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7998	ctsio->be_move_done = ctl_config_move_done;
7999	ctl_datamove((union ctl_io *)ctsio);
8000	return (CTL_RETVAL_COMPLETE);
8001}
8002
8003static void
8004ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8005{
8006	int off = lun->ctl_softc->persis_offset;
8007
8008	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8009		ctl_est_ua(lun, residx - off, ua);
8010}
8011
8012/*
8013 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8014 * it should return.
8015 */
8016static int
8017ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8018		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8019		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8020		struct scsi_per_res_out_parms* param)
8021{
8022	union ctl_ha_msg persis_io;
8023	int retval, i;
8024	int isc_retval;
8025
8026	retval = 0;
8027
8028	mtx_lock(&lun->lun_lock);
8029	if (sa_res_key == 0) {
8030		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8031			/* validate scope and type */
8032			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8033			     SPR_LU_SCOPE) {
8034				mtx_unlock(&lun->lun_lock);
8035				ctl_set_invalid_field(/*ctsio*/ ctsio,
8036						      /*sks_valid*/ 1,
8037						      /*command*/ 1,
8038						      /*field*/ 2,
8039						      /*bit_valid*/ 1,
8040						      /*bit*/ 4);
8041				ctl_done((union ctl_io *)ctsio);
8042				return (1);
8043			}
8044
8045		        if (type>8 || type==2 || type==4 || type==0) {
8046				mtx_unlock(&lun->lun_lock);
8047				ctl_set_invalid_field(/*ctsio*/ ctsio,
8048       	           				      /*sks_valid*/ 1,
8049						      /*command*/ 1,
8050						      /*field*/ 2,
8051						      /*bit_valid*/ 1,
8052						      /*bit*/ 0);
8053				ctl_done((union ctl_io *)ctsio);
8054				return (1);
8055		        }
8056
8057			/*
8058			 * Unregister everybody else and build UA for
8059			 * them
8060			 */
8061			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8062				if (i == residx || ctl_get_prkey(lun, i) == 0)
8063					continue;
8064
8065				ctl_clr_prkey(lun, i);
8066				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8067			}
8068			lun->pr_key_count = 1;
8069			lun->res_type = type;
8070			if (lun->res_type != SPR_TYPE_WR_EX_AR
8071			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8072				lun->pr_res_idx = residx;
8073
8074			/* send msg to other side */
8075			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8076			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8077			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8078			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8079			persis_io.pr.pr_info.res_type = type;
8080			memcpy(persis_io.pr.pr_info.sa_res_key,
8081			       param->serv_act_res_key,
8082			       sizeof(param->serv_act_res_key));
8083			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8084			     &persis_io, sizeof(persis_io), 0)) >
8085			     CTL_HA_STATUS_SUCCESS) {
8086				printf("CTL:Persis Out error returned "
8087				       "from ctl_ha_msg_send %d\n",
8088				       isc_retval);
8089			}
8090		} else {
8091			/* not all registrants */
8092			mtx_unlock(&lun->lun_lock);
8093			free(ctsio->kern_data_ptr, M_CTL);
8094			ctl_set_invalid_field(ctsio,
8095					      /*sks_valid*/ 1,
8096					      /*command*/ 0,
8097					      /*field*/ 8,
8098					      /*bit_valid*/ 0,
8099					      /*bit*/ 0);
8100			ctl_done((union ctl_io *)ctsio);
8101			return (1);
8102		}
8103	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8104		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8105		int found = 0;
8106
8107		if (res_key == sa_res_key) {
8108			/* special case */
8109			/*
8110			 * The spec implies this is not good but doesn't
8111			 * say what to do. There are two choices either
8112			 * generate a res conflict or check condition
8113			 * with illegal field in parameter data. Since
8114			 * that is what is done when the sa_res_key is
8115			 * zero I'll take that approach since this has
8116			 * to do with the sa_res_key.
8117			 */
8118			mtx_unlock(&lun->lun_lock);
8119			free(ctsio->kern_data_ptr, M_CTL);
8120			ctl_set_invalid_field(ctsio,
8121					      /*sks_valid*/ 1,
8122					      /*command*/ 0,
8123					      /*field*/ 8,
8124					      /*bit_valid*/ 0,
8125					      /*bit*/ 0);
8126			ctl_done((union ctl_io *)ctsio);
8127			return (1);
8128		}
8129
8130		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8131			if (ctl_get_prkey(lun, i) != sa_res_key)
8132				continue;
8133
8134			found = 1;
8135			ctl_clr_prkey(lun, i);
8136			lun->pr_key_count--;
8137			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8138		}
8139		if (!found) {
8140			mtx_unlock(&lun->lun_lock);
8141			free(ctsio->kern_data_ptr, M_CTL);
8142			ctl_set_reservation_conflict(ctsio);
8143			ctl_done((union ctl_io *)ctsio);
8144			return (CTL_RETVAL_COMPLETE);
8145		}
8146		/* send msg to other side */
8147		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8148		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8149		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8150		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8151		persis_io.pr.pr_info.res_type = type;
8152		memcpy(persis_io.pr.pr_info.sa_res_key,
8153		       param->serv_act_res_key,
8154		       sizeof(param->serv_act_res_key));
8155		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8156		     &persis_io, sizeof(persis_io), 0)) >
8157		     CTL_HA_STATUS_SUCCESS) {
8158			printf("CTL:Persis Out error returned from "
8159			       "ctl_ha_msg_send %d\n", isc_retval);
8160		}
8161	} else {
8162		/* Reserved but not all registrants */
8163		/* sa_res_key is res holder */
8164		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8165			/* validate scope and type */
8166			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8167			     SPR_LU_SCOPE) {
8168				mtx_unlock(&lun->lun_lock);
8169				ctl_set_invalid_field(/*ctsio*/ ctsio,
8170						      /*sks_valid*/ 1,
8171						      /*command*/ 1,
8172						      /*field*/ 2,
8173						      /*bit_valid*/ 1,
8174						      /*bit*/ 4);
8175				ctl_done((union ctl_io *)ctsio);
8176				return (1);
8177			}
8178
8179			if (type>8 || type==2 || type==4 || type==0) {
8180				mtx_unlock(&lun->lun_lock);
8181				ctl_set_invalid_field(/*ctsio*/ ctsio,
8182						      /*sks_valid*/ 1,
8183						      /*command*/ 1,
8184						      /*field*/ 2,
8185						      /*bit_valid*/ 1,
8186						      /*bit*/ 0);
8187				ctl_done((union ctl_io *)ctsio);
8188				return (1);
8189			}
8190
8191			/*
8192			 * Do the following:
8193			 * if sa_res_key != res_key remove all
8194			 * registrants w/sa_res_key and generate UA
8195			 * for these registrants(Registrations
8196			 * Preempted) if it wasn't an exclusive
8197			 * reservation generate UA(Reservations
8198			 * Preempted) for all other registered nexuses
8199			 * if the type has changed. Establish the new
8200			 * reservation and holder. If res_key and
8201			 * sa_res_key are the same do the above
8202			 * except don't unregister the res holder.
8203			 */
8204
8205			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8206				if (i == residx || ctl_get_prkey(lun, i) == 0)
8207					continue;
8208
8209				if (sa_res_key == ctl_get_prkey(lun, i)) {
8210					ctl_clr_prkey(lun, i);
8211					lun->pr_key_count--;
8212					ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8213				} else if (type != lun->res_type
8214					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8215					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8216					ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8217				}
8218			}
8219			lun->res_type = type;
8220			if (lun->res_type != SPR_TYPE_WR_EX_AR
8221			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8222				lun->pr_res_idx = residx;
8223			else
8224				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8225
8226			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8227			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8228			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8229			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8230			persis_io.pr.pr_info.res_type = type;
8231			memcpy(persis_io.pr.pr_info.sa_res_key,
8232			       param->serv_act_res_key,
8233			       sizeof(param->serv_act_res_key));
8234			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8235			     &persis_io, sizeof(persis_io), 0)) >
8236			     CTL_HA_STATUS_SUCCESS) {
8237				printf("CTL:Persis Out error returned "
8238				       "from ctl_ha_msg_send %d\n",
8239				       isc_retval);
8240			}
8241		} else {
8242			/*
8243			 * sa_res_key is not the res holder just
8244			 * remove registrants
8245			 */
8246			int found=0;
8247
8248			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8249				if (sa_res_key != ctl_get_prkey(lun, i))
8250					continue;
8251
8252				found = 1;
8253				ctl_clr_prkey(lun, i);
8254				lun->pr_key_count--;
8255				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8256			}
8257
8258			if (!found) {
8259				mtx_unlock(&lun->lun_lock);
8260				free(ctsio->kern_data_ptr, M_CTL);
8261				ctl_set_reservation_conflict(ctsio);
8262				ctl_done((union ctl_io *)ctsio);
8263		        	return (1);
8264			}
8265			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8266			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8267			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8268			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8269			persis_io.pr.pr_info.res_type = type;
8270			memcpy(persis_io.pr.pr_info.sa_res_key,
8271			       param->serv_act_res_key,
8272			       sizeof(param->serv_act_res_key));
8273			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8274			     &persis_io, sizeof(persis_io), 0)) >
8275			     CTL_HA_STATUS_SUCCESS) {
8276				printf("CTL:Persis Out error returned "
8277				       "from ctl_ha_msg_send %d\n",
8278				isc_retval);
8279			}
8280		}
8281	}
8282
8283	lun->PRGeneration++;
8284	mtx_unlock(&lun->lun_lock);
8285
8286	return (retval);
8287}
8288
8289static void
8290ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8291{
8292	uint64_t sa_res_key;
8293	int i;
8294
8295	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8296
8297	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8298	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8299	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8300		if (sa_res_key == 0) {
8301			/*
8302			 * Unregister everybody else and build UA for
8303			 * them
8304			 */
8305			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8306				if (i == msg->pr.pr_info.residx ||
8307				    ctl_get_prkey(lun, i) == 0)
8308					continue;
8309
8310				ctl_clr_prkey(lun, i);
8311				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8312			}
8313
8314			lun->pr_key_count = 1;
8315			lun->res_type = msg->pr.pr_info.res_type;
8316			if (lun->res_type != SPR_TYPE_WR_EX_AR
8317			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8318				lun->pr_res_idx = msg->pr.pr_info.residx;
8319		} else {
8320		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8321				if (sa_res_key == ctl_get_prkey(lun, i))
8322					continue;
8323
8324				ctl_clr_prkey(lun, i);
8325				lun->pr_key_count--;
8326				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8327			}
8328		}
8329	} else {
8330		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8331			if (i == msg->pr.pr_info.residx ||
8332			    ctl_get_prkey(lun, i) == 0)
8333				continue;
8334
8335			if (sa_res_key == ctl_get_prkey(lun, i)) {
8336				ctl_clr_prkey(lun, i);
8337				lun->pr_key_count--;
8338				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8339			} else if (msg->pr.pr_info.res_type != lun->res_type
8340				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8341				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8342				ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8343			}
8344		}
8345		lun->res_type = msg->pr.pr_info.res_type;
8346		if (lun->res_type != SPR_TYPE_WR_EX_AR
8347		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8348			lun->pr_res_idx = msg->pr.pr_info.residx;
8349		else
8350			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8351	}
8352	lun->PRGeneration++;
8353
8354}
8355
8356
8357int
8358ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8359{
8360	int retval;
8361	int isc_retval;
8362	u_int32_t param_len;
8363	struct scsi_per_res_out *cdb;
8364	struct ctl_lun *lun;
8365	struct scsi_per_res_out_parms* param;
8366	struct ctl_softc *softc;
8367	uint32_t residx;
8368	uint64_t res_key, sa_res_key, key;
8369	uint8_t type;
8370	union ctl_ha_msg persis_io;
8371	int    i;
8372
8373	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8374
8375	retval = CTL_RETVAL_COMPLETE;
8376
8377	softc = control_softc;
8378
8379	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8380	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8381
8382	/*
8383	 * We only support whole-LUN scope.  The scope & type are ignored for
8384	 * register, register and ignore existing key and clear.
8385	 * We sometimes ignore scope and type on preempts too!!
8386	 * Verify reservation type here as well.
8387	 */
8388	type = cdb->scope_type & SPR_TYPE_MASK;
8389	if ((cdb->action == SPRO_RESERVE)
8390	 || (cdb->action == SPRO_RELEASE)) {
8391		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8392			ctl_set_invalid_field(/*ctsio*/ ctsio,
8393					      /*sks_valid*/ 1,
8394					      /*command*/ 1,
8395					      /*field*/ 2,
8396					      /*bit_valid*/ 1,
8397					      /*bit*/ 4);
8398			ctl_done((union ctl_io *)ctsio);
8399			return (CTL_RETVAL_COMPLETE);
8400		}
8401
8402		if (type>8 || type==2 || type==4 || type==0) {
8403			ctl_set_invalid_field(/*ctsio*/ ctsio,
8404					      /*sks_valid*/ 1,
8405					      /*command*/ 1,
8406					      /*field*/ 2,
8407					      /*bit_valid*/ 1,
8408					      /*bit*/ 0);
8409			ctl_done((union ctl_io *)ctsio);
8410			return (CTL_RETVAL_COMPLETE);
8411		}
8412	}
8413
8414	param_len = scsi_4btoul(cdb->length);
8415
8416	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8417		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8418		ctsio->kern_data_len = param_len;
8419		ctsio->kern_total_len = param_len;
8420		ctsio->kern_data_resid = 0;
8421		ctsio->kern_rel_offset = 0;
8422		ctsio->kern_sg_entries = 0;
8423		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8424		ctsio->be_move_done = ctl_config_move_done;
8425		ctl_datamove((union ctl_io *)ctsio);
8426
8427		return (CTL_RETVAL_COMPLETE);
8428	}
8429
8430	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8431
8432	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8433	res_key = scsi_8btou64(param->res_key.key);
8434	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8435
8436	/*
8437	 * Validate the reservation key here except for SPRO_REG_IGNO
8438	 * This must be done for all other service actions
8439	 */
8440	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8441		mtx_lock(&lun->lun_lock);
8442		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8443			if (res_key != key) {
8444				/*
8445				 * The current key passed in doesn't match
8446				 * the one the initiator previously
8447				 * registered.
8448				 */
8449				mtx_unlock(&lun->lun_lock);
8450				free(ctsio->kern_data_ptr, M_CTL);
8451				ctl_set_reservation_conflict(ctsio);
8452				ctl_done((union ctl_io *)ctsio);
8453				return (CTL_RETVAL_COMPLETE);
8454			}
8455		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8456			/*
8457			 * We are not registered
8458			 */
8459			mtx_unlock(&lun->lun_lock);
8460			free(ctsio->kern_data_ptr, M_CTL);
8461			ctl_set_reservation_conflict(ctsio);
8462			ctl_done((union ctl_io *)ctsio);
8463			return (CTL_RETVAL_COMPLETE);
8464		} else if (res_key != 0) {
8465			/*
8466			 * We are not registered and trying to register but
8467			 * the register key isn't zero.
8468			 */
8469			mtx_unlock(&lun->lun_lock);
8470			free(ctsio->kern_data_ptr, M_CTL);
8471			ctl_set_reservation_conflict(ctsio);
8472			ctl_done((union ctl_io *)ctsio);
8473			return (CTL_RETVAL_COMPLETE);
8474		}
8475		mtx_unlock(&lun->lun_lock);
8476	}
8477
8478	switch (cdb->action & SPRO_ACTION_MASK) {
8479	case SPRO_REGISTER:
8480	case SPRO_REG_IGNO: {
8481
8482#if 0
8483		printf("Registration received\n");
8484#endif
8485
8486		/*
8487		 * We don't support any of these options, as we report in
8488		 * the read capabilities request (see
8489		 * ctl_persistent_reserve_in(), above).
8490		 */
8491		if ((param->flags & SPR_SPEC_I_PT)
8492		 || (param->flags & SPR_ALL_TG_PT)
8493		 || (param->flags & SPR_APTPL)) {
8494			int bit_ptr;
8495
8496			if (param->flags & SPR_APTPL)
8497				bit_ptr = 0;
8498			else if (param->flags & SPR_ALL_TG_PT)
8499				bit_ptr = 2;
8500			else /* SPR_SPEC_I_PT */
8501				bit_ptr = 3;
8502
8503			free(ctsio->kern_data_ptr, M_CTL);
8504			ctl_set_invalid_field(ctsio,
8505					      /*sks_valid*/ 1,
8506					      /*command*/ 0,
8507					      /*field*/ 20,
8508					      /*bit_valid*/ 1,
8509					      /*bit*/ bit_ptr);
8510			ctl_done((union ctl_io *)ctsio);
8511			return (CTL_RETVAL_COMPLETE);
8512		}
8513
8514		mtx_lock(&lun->lun_lock);
8515
8516		/*
8517		 * The initiator wants to clear the
8518		 * key/unregister.
8519		 */
8520		if (sa_res_key == 0) {
8521			if ((res_key == 0
8522			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8523			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8524			  && ctl_get_prkey(lun, residx) == 0)) {
8525				mtx_unlock(&lun->lun_lock);
8526				goto done;
8527			}
8528
8529			ctl_clr_prkey(lun, residx);
8530			lun->pr_key_count--;
8531
8532			if (residx == lun->pr_res_idx) {
8533				lun->flags &= ~CTL_LUN_PR_RESERVED;
8534				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8535
8536				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8537				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8538				 && lun->pr_key_count) {
8539					/*
8540					 * If the reservation is a registrants
8541					 * only type we need to generate a UA
8542					 * for other registered inits.  The
8543					 * sense code should be RESERVATIONS
8544					 * RELEASED
8545					 */
8546
8547					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8548						if (ctl_get_prkey(lun, i +
8549						    softc->persis_offset) == 0)
8550							continue;
8551						ctl_est_ua(lun, i,
8552						    CTL_UA_RES_RELEASE);
8553					}
8554				}
8555				lun->res_type = 0;
8556			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8557				if (lun->pr_key_count==0) {
8558					lun->flags &= ~CTL_LUN_PR_RESERVED;
8559					lun->res_type = 0;
8560					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8561				}
8562			}
8563			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8564			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8565			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8566			persis_io.pr.pr_info.residx = residx;
8567			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8568			     &persis_io, sizeof(persis_io), 0 )) >
8569			     CTL_HA_STATUS_SUCCESS) {
8570				printf("CTL:Persis Out error returned from "
8571				       "ctl_ha_msg_send %d\n", isc_retval);
8572			}
8573		} else /* sa_res_key != 0 */ {
8574
8575			/*
8576			 * If we aren't registered currently then increment
8577			 * the key count and set the registered flag.
8578			 */
8579			ctl_alloc_prkey(lun, residx);
8580			if (ctl_get_prkey(lun, residx) == 0)
8581				lun->pr_key_count++;
8582			ctl_set_prkey(lun, residx, sa_res_key);
8583
8584			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8585			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8586			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8587			persis_io.pr.pr_info.residx = residx;
8588			memcpy(persis_io.pr.pr_info.sa_res_key,
8589			       param->serv_act_res_key,
8590			       sizeof(param->serv_act_res_key));
8591			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8592			     &persis_io, sizeof(persis_io), 0)) >
8593			     CTL_HA_STATUS_SUCCESS) {
8594				printf("CTL:Persis Out error returned from "
8595				       "ctl_ha_msg_send %d\n", isc_retval);
8596			}
8597		}
8598		lun->PRGeneration++;
8599		mtx_unlock(&lun->lun_lock);
8600
8601		break;
8602	}
8603	case SPRO_RESERVE:
8604#if 0
8605                printf("Reserve executed type %d\n", type);
8606#endif
8607		mtx_lock(&lun->lun_lock);
8608		if (lun->flags & CTL_LUN_PR_RESERVED) {
8609			/*
8610			 * if this isn't the reservation holder and it's
8611			 * not a "all registrants" type or if the type is
8612			 * different then we have a conflict
8613			 */
8614			if ((lun->pr_res_idx != residx
8615			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8616			 || lun->res_type != type) {
8617				mtx_unlock(&lun->lun_lock);
8618				free(ctsio->kern_data_ptr, M_CTL);
8619				ctl_set_reservation_conflict(ctsio);
8620				ctl_done((union ctl_io *)ctsio);
8621				return (CTL_RETVAL_COMPLETE);
8622			}
8623			mtx_unlock(&lun->lun_lock);
8624		} else /* create a reservation */ {
8625			/*
8626			 * If it's not an "all registrants" type record
8627			 * reservation holder
8628			 */
8629			if (type != SPR_TYPE_WR_EX_AR
8630			 && type != SPR_TYPE_EX_AC_AR)
8631				lun->pr_res_idx = residx; /* Res holder */
8632			else
8633				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8634
8635			lun->flags |= CTL_LUN_PR_RESERVED;
8636			lun->res_type = type;
8637
8638			mtx_unlock(&lun->lun_lock);
8639
8640			/* send msg to other side */
8641			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8642			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8643			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8644			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8645			persis_io.pr.pr_info.res_type = type;
8646			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8647			     &persis_io, sizeof(persis_io), 0)) >
8648			     CTL_HA_STATUS_SUCCESS) {
8649				printf("CTL:Persis Out error returned from "
8650				       "ctl_ha_msg_send %d\n", isc_retval);
8651			}
8652		}
8653		break;
8654
8655	case SPRO_RELEASE:
8656		mtx_lock(&lun->lun_lock);
8657		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8658			/* No reservation exists return good status */
8659			mtx_unlock(&lun->lun_lock);
8660			goto done;
8661		}
8662		/*
8663		 * Is this nexus a reservation holder?
8664		 */
8665		if (lun->pr_res_idx != residx
8666		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8667			/*
8668			 * not a res holder return good status but
8669			 * do nothing
8670			 */
8671			mtx_unlock(&lun->lun_lock);
8672			goto done;
8673		}
8674
8675		if (lun->res_type != type) {
8676			mtx_unlock(&lun->lun_lock);
8677			free(ctsio->kern_data_ptr, M_CTL);
8678			ctl_set_illegal_pr_release(ctsio);
8679			ctl_done((union ctl_io *)ctsio);
8680			return (CTL_RETVAL_COMPLETE);
8681		}
8682
8683		/* okay to release */
8684		lun->flags &= ~CTL_LUN_PR_RESERVED;
8685		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8686		lun->res_type = 0;
8687
8688		/*
8689		 * if this isn't an exclusive access
8690		 * res generate UA for all other
8691		 * registrants.
8692		 */
8693		if (type != SPR_TYPE_EX_AC
8694		 && type != SPR_TYPE_WR_EX) {
8695			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8696				if (i == residx ||
8697				    ctl_get_prkey(lun,
8698				     i + softc->persis_offset) == 0)
8699					continue;
8700				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8701			}
8702		}
8703		mtx_unlock(&lun->lun_lock);
8704		/* Send msg to other side */
8705		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8706		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8707		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8708		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8709		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8710			printf("CTL:Persis Out error returned from "
8711			       "ctl_ha_msg_send %d\n", isc_retval);
8712		}
8713		break;
8714
8715	case SPRO_CLEAR:
8716		/* send msg to other side */
8717
8718		mtx_lock(&lun->lun_lock);
8719		lun->flags &= ~CTL_LUN_PR_RESERVED;
8720		lun->res_type = 0;
8721		lun->pr_key_count = 0;
8722		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8723
8724		ctl_clr_prkey(lun, residx);
8725		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8726			if (ctl_get_prkey(lun, i) != 0) {
8727				ctl_clr_prkey(lun, i);
8728				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8729			}
8730		lun->PRGeneration++;
8731		mtx_unlock(&lun->lun_lock);
8732		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8733		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8734		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8735		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8736		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8737			printf("CTL:Persis Out error returned from "
8738			       "ctl_ha_msg_send %d\n", isc_retval);
8739		}
8740		break;
8741
8742	case SPRO_PREEMPT:
8743	case SPRO_PRE_ABO: {
8744		int nretval;
8745
8746		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8747					  residx, ctsio, cdb, param);
8748		if (nretval != 0)
8749			return (CTL_RETVAL_COMPLETE);
8750		break;
8751	}
8752	default:
8753		panic("Invalid PR type %x", cdb->action);
8754	}
8755
8756done:
8757	free(ctsio->kern_data_ptr, M_CTL);
8758	ctl_set_success(ctsio);
8759	ctl_done((union ctl_io *)ctsio);
8760
8761	return (retval);
8762}
8763
8764/*
8765 * This routine is for handling a message from the other SC pertaining to
8766 * persistent reserve out. All the error checking will have been done
8767 * so only perorming the action need be done here to keep the two
8768 * in sync.
8769 */
8770static void
8771ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8772{
8773	struct ctl_lun *lun;
8774	struct ctl_softc *softc;
8775	int i;
8776	uint32_t targ_lun;
8777
8778	softc = control_softc;
8779
8780	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8781	lun = softc->ctl_luns[targ_lun];
8782	mtx_lock(&lun->lun_lock);
8783	switch(msg->pr.pr_info.action) {
8784	case CTL_PR_REG_KEY:
8785		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8786		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8787			lun->pr_key_count++;
8788		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8789		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8790		lun->PRGeneration++;
8791		break;
8792
8793	case CTL_PR_UNREG_KEY:
8794		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8795		lun->pr_key_count--;
8796
8797		/* XXX Need to see if the reservation has been released */
8798		/* if so do we need to generate UA? */
8799		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8800			lun->flags &= ~CTL_LUN_PR_RESERVED;
8801			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8802
8803			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8804			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8805			 && lun->pr_key_count) {
8806				/*
8807				 * If the reservation is a registrants
8808				 * only type we need to generate a UA
8809				 * for other registered inits.  The
8810				 * sense code should be RESERVATIONS
8811				 * RELEASED
8812				 */
8813
8814				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8815					if (ctl_get_prkey(lun, i +
8816					    softc->persis_offset) == 0)
8817						continue;
8818
8819					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8820				}
8821			}
8822			lun->res_type = 0;
8823		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8824			if (lun->pr_key_count==0) {
8825				lun->flags &= ~CTL_LUN_PR_RESERVED;
8826				lun->res_type = 0;
8827				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8828			}
8829		}
8830		lun->PRGeneration++;
8831		break;
8832
8833	case CTL_PR_RESERVE:
8834		lun->flags |= CTL_LUN_PR_RESERVED;
8835		lun->res_type = msg->pr.pr_info.res_type;
8836		lun->pr_res_idx = msg->pr.pr_info.residx;
8837
8838		break;
8839
8840	case CTL_PR_RELEASE:
8841		/*
8842		 * if this isn't an exclusive access res generate UA for all
8843		 * other registrants.
8844		 */
8845		if (lun->res_type != SPR_TYPE_EX_AC
8846		 && lun->res_type != SPR_TYPE_WR_EX) {
8847			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8848				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8849					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8850		}
8851
8852		lun->flags &= ~CTL_LUN_PR_RESERVED;
8853		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8854		lun->res_type = 0;
8855		break;
8856
8857	case CTL_PR_PREEMPT:
8858		ctl_pro_preempt_other(lun, msg);
8859		break;
8860	case CTL_PR_CLEAR:
8861		lun->flags &= ~CTL_LUN_PR_RESERVED;
8862		lun->res_type = 0;
8863		lun->pr_key_count = 0;
8864		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8865
8866		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8867			if (ctl_get_prkey(lun, i) == 0)
8868				continue;
8869			ctl_clr_prkey(lun, i);
8870			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8871		}
8872		lun->PRGeneration++;
8873		break;
8874	}
8875
8876	mtx_unlock(&lun->lun_lock);
8877}
8878
8879int
8880ctl_read_write(struct ctl_scsiio *ctsio)
8881{
8882	struct ctl_lun *lun;
8883	struct ctl_lba_len_flags *lbalen;
8884	uint64_t lba;
8885	uint32_t num_blocks;
8886	int flags, retval;
8887	int isread;
8888
8889	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8890
8891	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8892
8893	flags = 0;
8894	retval = CTL_RETVAL_COMPLETE;
8895
8896	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8897	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8898	switch (ctsio->cdb[0]) {
8899	case READ_6:
8900	case WRITE_6: {
8901		struct scsi_rw_6 *cdb;
8902
8903		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8904
8905		lba = scsi_3btoul(cdb->addr);
8906		/* only 5 bits are valid in the most significant address byte */
8907		lba &= 0x1fffff;
8908		num_blocks = cdb->length;
8909		/*
8910		 * This is correct according to SBC-2.
8911		 */
8912		if (num_blocks == 0)
8913			num_blocks = 256;
8914		break;
8915	}
8916	case READ_10:
8917	case WRITE_10: {
8918		struct scsi_rw_10 *cdb;
8919
8920		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8921		if (cdb->byte2 & SRW10_FUA)
8922			flags |= CTL_LLF_FUA;
8923		if (cdb->byte2 & SRW10_DPO)
8924			flags |= CTL_LLF_DPO;
8925		lba = scsi_4btoul(cdb->addr);
8926		num_blocks = scsi_2btoul(cdb->length);
8927		break;
8928	}
8929	case WRITE_VERIFY_10: {
8930		struct scsi_write_verify_10 *cdb;
8931
8932		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8933		flags |= CTL_LLF_FUA;
8934		if (cdb->byte2 & SWV_DPO)
8935			flags |= CTL_LLF_DPO;
8936		lba = scsi_4btoul(cdb->addr);
8937		num_blocks = scsi_2btoul(cdb->length);
8938		break;
8939	}
8940	case READ_12:
8941	case WRITE_12: {
8942		struct scsi_rw_12 *cdb;
8943
8944		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8945		if (cdb->byte2 & SRW12_FUA)
8946			flags |= CTL_LLF_FUA;
8947		if (cdb->byte2 & SRW12_DPO)
8948			flags |= CTL_LLF_DPO;
8949		lba = scsi_4btoul(cdb->addr);
8950		num_blocks = scsi_4btoul(cdb->length);
8951		break;
8952	}
8953	case WRITE_VERIFY_12: {
8954		struct scsi_write_verify_12 *cdb;
8955
8956		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8957		flags |= CTL_LLF_FUA;
8958		if (cdb->byte2 & SWV_DPO)
8959			flags |= CTL_LLF_DPO;
8960		lba = scsi_4btoul(cdb->addr);
8961		num_blocks = scsi_4btoul(cdb->length);
8962		break;
8963	}
8964	case READ_16:
8965	case WRITE_16: {
8966		struct scsi_rw_16 *cdb;
8967
8968		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8969		if (cdb->byte2 & SRW12_FUA)
8970			flags |= CTL_LLF_FUA;
8971		if (cdb->byte2 & SRW12_DPO)
8972			flags |= CTL_LLF_DPO;
8973		lba = scsi_8btou64(cdb->addr);
8974		num_blocks = scsi_4btoul(cdb->length);
8975		break;
8976	}
8977	case WRITE_ATOMIC_16: {
8978		struct scsi_rw_16 *cdb;
8979
8980		if (lun->be_lun->atomicblock == 0) {
8981			ctl_set_invalid_opcode(ctsio);
8982			ctl_done((union ctl_io *)ctsio);
8983			return (CTL_RETVAL_COMPLETE);
8984		}
8985
8986		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8987		if (cdb->byte2 & SRW12_FUA)
8988			flags |= CTL_LLF_FUA;
8989		if (cdb->byte2 & SRW12_DPO)
8990			flags |= CTL_LLF_DPO;
8991		lba = scsi_8btou64(cdb->addr);
8992		num_blocks = scsi_4btoul(cdb->length);
8993		if (num_blocks > lun->be_lun->atomicblock) {
8994			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8995			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8996			    /*bit*/ 0);
8997			ctl_done((union ctl_io *)ctsio);
8998			return (CTL_RETVAL_COMPLETE);
8999		}
9000		break;
9001	}
9002	case WRITE_VERIFY_16: {
9003		struct scsi_write_verify_16 *cdb;
9004
9005		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9006		flags |= CTL_LLF_FUA;
9007		if (cdb->byte2 & SWV_DPO)
9008			flags |= CTL_LLF_DPO;
9009		lba = scsi_8btou64(cdb->addr);
9010		num_blocks = scsi_4btoul(cdb->length);
9011		break;
9012	}
9013	default:
9014		/*
9015		 * We got a command we don't support.  This shouldn't
9016		 * happen, commands should be filtered out above us.
9017		 */
9018		ctl_set_invalid_opcode(ctsio);
9019		ctl_done((union ctl_io *)ctsio);
9020
9021		return (CTL_RETVAL_COMPLETE);
9022		break; /* NOTREACHED */
9023	}
9024
9025	/*
9026	 * The first check is to make sure we're in bounds, the second
9027	 * check is to catch wrap-around problems.  If the lba + num blocks
9028	 * is less than the lba, then we've wrapped around and the block
9029	 * range is invalid anyway.
9030	 */
9031	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9032	 || ((lba + num_blocks) < lba)) {
9033		ctl_set_lba_out_of_range(ctsio);
9034		ctl_done((union ctl_io *)ctsio);
9035		return (CTL_RETVAL_COMPLETE);
9036	}
9037
9038	/*
9039	 * According to SBC-3, a transfer length of 0 is not an error.
9040	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9041	 * translates to 256 blocks for those commands.
9042	 */
9043	if (num_blocks == 0) {
9044		ctl_set_success(ctsio);
9045		ctl_done((union ctl_io *)ctsio);
9046		return (CTL_RETVAL_COMPLETE);
9047	}
9048
9049	/* Set FUA and/or DPO if caches are disabled. */
9050	if (isread) {
9051		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9052		    SCP_RCD) != 0)
9053			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9054	} else {
9055		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9056		    SCP_WCE) == 0)
9057			flags |= CTL_LLF_FUA;
9058	}
9059
9060	lbalen = (struct ctl_lba_len_flags *)
9061	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9062	lbalen->lba = lba;
9063	lbalen->len = num_blocks;
9064	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9065
9066	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9067	ctsio->kern_rel_offset = 0;
9068
9069	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9070
9071	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9072
9073	return (retval);
9074}
9075
9076static int
9077ctl_cnw_cont(union ctl_io *io)
9078{
9079	struct ctl_scsiio *ctsio;
9080	struct ctl_lun *lun;
9081	struct ctl_lba_len_flags *lbalen;
9082	int retval;
9083
9084	ctsio = &io->scsiio;
9085	ctsio->io_hdr.status = CTL_STATUS_NONE;
9086	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9087	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9088	lbalen = (struct ctl_lba_len_flags *)
9089	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9090	lbalen->flags &= ~CTL_LLF_COMPARE;
9091	lbalen->flags |= CTL_LLF_WRITE;
9092
9093	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9094	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9095	return (retval);
9096}
9097
9098int
9099ctl_cnw(struct ctl_scsiio *ctsio)
9100{
9101	struct ctl_lun *lun;
9102	struct ctl_lba_len_flags *lbalen;
9103	uint64_t lba;
9104	uint32_t num_blocks;
9105	int flags, retval;
9106
9107	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9108
9109	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9110
9111	flags = 0;
9112	retval = CTL_RETVAL_COMPLETE;
9113
9114	switch (ctsio->cdb[0]) {
9115	case COMPARE_AND_WRITE: {
9116		struct scsi_compare_and_write *cdb;
9117
9118		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9119		if (cdb->byte2 & SRW10_FUA)
9120			flags |= CTL_LLF_FUA;
9121		if (cdb->byte2 & SRW10_DPO)
9122			flags |= CTL_LLF_DPO;
9123		lba = scsi_8btou64(cdb->addr);
9124		num_blocks = cdb->length;
9125		break;
9126	}
9127	default:
9128		/*
9129		 * We got a command we don't support.  This shouldn't
9130		 * happen, commands should be filtered out above us.
9131		 */
9132		ctl_set_invalid_opcode(ctsio);
9133		ctl_done((union ctl_io *)ctsio);
9134
9135		return (CTL_RETVAL_COMPLETE);
9136		break; /* NOTREACHED */
9137	}
9138
9139	/*
9140	 * The first check is to make sure we're in bounds, the second
9141	 * check is to catch wrap-around problems.  If the lba + num blocks
9142	 * is less than the lba, then we've wrapped around and the block
9143	 * range is invalid anyway.
9144	 */
9145	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9146	 || ((lba + num_blocks) < lba)) {
9147		ctl_set_lba_out_of_range(ctsio);
9148		ctl_done((union ctl_io *)ctsio);
9149		return (CTL_RETVAL_COMPLETE);
9150	}
9151
9152	/*
9153	 * According to SBC-3, a transfer length of 0 is not an error.
9154	 */
9155	if (num_blocks == 0) {
9156		ctl_set_success(ctsio);
9157		ctl_done((union ctl_io *)ctsio);
9158		return (CTL_RETVAL_COMPLETE);
9159	}
9160
9161	/* Set FUA if write cache is disabled. */
9162	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9163	    SCP_WCE) == 0)
9164		flags |= CTL_LLF_FUA;
9165
9166	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9167	ctsio->kern_rel_offset = 0;
9168
9169	/*
9170	 * Set the IO_CONT flag, so that if this I/O gets passed to
9171	 * ctl_data_submit_done(), it'll get passed back to
9172	 * ctl_ctl_cnw_cont() for further processing.
9173	 */
9174	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9175	ctsio->io_cont = ctl_cnw_cont;
9176
9177	lbalen = (struct ctl_lba_len_flags *)
9178	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9179	lbalen->lba = lba;
9180	lbalen->len = num_blocks;
9181	lbalen->flags = CTL_LLF_COMPARE | flags;
9182
9183	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9184	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9185	return (retval);
9186}
9187
9188int
9189ctl_verify(struct ctl_scsiio *ctsio)
9190{
9191	struct ctl_lun *lun;
9192	struct ctl_lba_len_flags *lbalen;
9193	uint64_t lba;
9194	uint32_t num_blocks;
9195	int bytchk, flags;
9196	int retval;
9197
9198	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9199
9200	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9201
9202	bytchk = 0;
9203	flags = CTL_LLF_FUA;
9204	retval = CTL_RETVAL_COMPLETE;
9205
9206	switch (ctsio->cdb[0]) {
9207	case VERIFY_10: {
9208		struct scsi_verify_10 *cdb;
9209
9210		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9211		if (cdb->byte2 & SVFY_BYTCHK)
9212			bytchk = 1;
9213		if (cdb->byte2 & SVFY_DPO)
9214			flags |= CTL_LLF_DPO;
9215		lba = scsi_4btoul(cdb->addr);
9216		num_blocks = scsi_2btoul(cdb->length);
9217		break;
9218	}
9219	case VERIFY_12: {
9220		struct scsi_verify_12 *cdb;
9221
9222		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9223		if (cdb->byte2 & SVFY_BYTCHK)
9224			bytchk = 1;
9225		if (cdb->byte2 & SVFY_DPO)
9226			flags |= CTL_LLF_DPO;
9227		lba = scsi_4btoul(cdb->addr);
9228		num_blocks = scsi_4btoul(cdb->length);
9229		break;
9230	}
9231	case VERIFY_16: {
9232		struct scsi_rw_16 *cdb;
9233
9234		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9235		if (cdb->byte2 & SVFY_BYTCHK)
9236			bytchk = 1;
9237		if (cdb->byte2 & SVFY_DPO)
9238			flags |= CTL_LLF_DPO;
9239		lba = scsi_8btou64(cdb->addr);
9240		num_blocks = scsi_4btoul(cdb->length);
9241		break;
9242	}
9243	default:
9244		/*
9245		 * We got a command we don't support.  This shouldn't
9246		 * happen, commands should be filtered out above us.
9247		 */
9248		ctl_set_invalid_opcode(ctsio);
9249		ctl_done((union ctl_io *)ctsio);
9250		return (CTL_RETVAL_COMPLETE);
9251	}
9252
9253	/*
9254	 * The first check is to make sure we're in bounds, the second
9255	 * check is to catch wrap-around problems.  If the lba + num blocks
9256	 * is less than the lba, then we've wrapped around and the block
9257	 * range is invalid anyway.
9258	 */
9259	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9260	 || ((lba + num_blocks) < lba)) {
9261		ctl_set_lba_out_of_range(ctsio);
9262		ctl_done((union ctl_io *)ctsio);
9263		return (CTL_RETVAL_COMPLETE);
9264	}
9265
9266	/*
9267	 * According to SBC-3, a transfer length of 0 is not an error.
9268	 */
9269	if (num_blocks == 0) {
9270		ctl_set_success(ctsio);
9271		ctl_done((union ctl_io *)ctsio);
9272		return (CTL_RETVAL_COMPLETE);
9273	}
9274
9275	lbalen = (struct ctl_lba_len_flags *)
9276	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9277	lbalen->lba = lba;
9278	lbalen->len = num_blocks;
9279	if (bytchk) {
9280		lbalen->flags = CTL_LLF_COMPARE | flags;
9281		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9282	} else {
9283		lbalen->flags = CTL_LLF_VERIFY | flags;
9284		ctsio->kern_total_len = 0;
9285	}
9286	ctsio->kern_rel_offset = 0;
9287
9288	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9289	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9290	return (retval);
9291}
9292
9293int
9294ctl_report_luns(struct ctl_scsiio *ctsio)
9295{
9296	struct scsi_report_luns *cdb;
9297	struct scsi_report_luns_data *lun_data;
9298	struct ctl_lun *lun, *request_lun;
9299	int num_luns, retval;
9300	uint32_t alloc_len, lun_datalen;
9301	int num_filled, well_known;
9302	uint32_t initidx, targ_lun_id, lun_id;
9303
9304	retval = CTL_RETVAL_COMPLETE;
9305	well_known = 0;
9306
9307	cdb = (struct scsi_report_luns *)ctsio->cdb;
9308
9309	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9310
9311	mtx_lock(&control_softc->ctl_lock);
9312	num_luns = control_softc->num_luns;
9313	mtx_unlock(&control_softc->ctl_lock);
9314
9315	switch (cdb->select_report) {
9316	case RPL_REPORT_DEFAULT:
9317	case RPL_REPORT_ALL:
9318		break;
9319	case RPL_REPORT_WELLKNOWN:
9320		well_known = 1;
9321		num_luns = 0;
9322		break;
9323	default:
9324		ctl_set_invalid_field(ctsio,
9325				      /*sks_valid*/ 1,
9326				      /*command*/ 1,
9327				      /*field*/ 2,
9328				      /*bit_valid*/ 0,
9329				      /*bit*/ 0);
9330		ctl_done((union ctl_io *)ctsio);
9331		return (retval);
9332		break; /* NOTREACHED */
9333	}
9334
9335	alloc_len = scsi_4btoul(cdb->length);
9336	/*
9337	 * The initiator has to allocate at least 16 bytes for this request,
9338	 * so he can at least get the header and the first LUN.  Otherwise
9339	 * we reject the request (per SPC-3 rev 14, section 6.21).
9340	 */
9341	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9342	    sizeof(struct scsi_report_luns_lundata))) {
9343		ctl_set_invalid_field(ctsio,
9344				      /*sks_valid*/ 1,
9345				      /*command*/ 1,
9346				      /*field*/ 6,
9347				      /*bit_valid*/ 0,
9348				      /*bit*/ 0);
9349		ctl_done((union ctl_io *)ctsio);
9350		return (retval);
9351	}
9352
9353	request_lun = (struct ctl_lun *)
9354		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9355
9356	lun_datalen = sizeof(*lun_data) +
9357		(num_luns * sizeof(struct scsi_report_luns_lundata));
9358
9359	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9360	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9361	ctsio->kern_sg_entries = 0;
9362
9363	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9364
9365	mtx_lock(&control_softc->ctl_lock);
9366	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9367		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9368		if (lun_id >= CTL_MAX_LUNS)
9369			continue;
9370		lun = control_softc->ctl_luns[lun_id];
9371		if (lun == NULL)
9372			continue;
9373
9374		if (targ_lun_id <= 0xff) {
9375			/*
9376			 * Peripheral addressing method, bus number 0.
9377			 */
9378			lun_data->luns[num_filled].lundata[0] =
9379				RPL_LUNDATA_ATYP_PERIPH;
9380			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9381			num_filled++;
9382		} else if (targ_lun_id <= 0x3fff) {
9383			/*
9384			 * Flat addressing method.
9385			 */
9386			lun_data->luns[num_filled].lundata[0] =
9387				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9388			lun_data->luns[num_filled].lundata[1] =
9389				(targ_lun_id & 0xff);
9390			num_filled++;
9391		} else if (targ_lun_id <= 0xffffff) {
9392			/*
9393			 * Extended flat addressing method.
9394			 */
9395			lun_data->luns[num_filled].lundata[0] =
9396			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9397			scsi_ulto3b(targ_lun_id,
9398			    &lun_data->luns[num_filled].lundata[1]);
9399			num_filled++;
9400		} else {
9401			printf("ctl_report_luns: bogus LUN number %jd, "
9402			       "skipping\n", (intmax_t)targ_lun_id);
9403		}
9404		/*
9405		 * According to SPC-3, rev 14 section 6.21:
9406		 *
9407		 * "The execution of a REPORT LUNS command to any valid and
9408		 * installed logical unit shall clear the REPORTED LUNS DATA
9409		 * HAS CHANGED unit attention condition for all logical
9410		 * units of that target with respect to the requesting
9411		 * initiator. A valid and installed logical unit is one
9412		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9413		 * INQUIRY data (see 6.4.2)."
9414		 *
9415		 * If request_lun is NULL, the LUN this report luns command
9416		 * was issued to is either disabled or doesn't exist. In that
9417		 * case, we shouldn't clear any pending lun change unit
9418		 * attention.
9419		 */
9420		if (request_lun != NULL) {
9421			mtx_lock(&lun->lun_lock);
9422			ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9423			mtx_unlock(&lun->lun_lock);
9424		}
9425	}
9426	mtx_unlock(&control_softc->ctl_lock);
9427
9428	/*
9429	 * It's quite possible that we've returned fewer LUNs than we allocated
9430	 * space for.  Trim it.
9431	 */
9432	lun_datalen = sizeof(*lun_data) +
9433		(num_filled * sizeof(struct scsi_report_luns_lundata));
9434
9435	if (lun_datalen < alloc_len) {
9436		ctsio->residual = alloc_len - lun_datalen;
9437		ctsio->kern_data_len = lun_datalen;
9438		ctsio->kern_total_len = lun_datalen;
9439	} else {
9440		ctsio->residual = 0;
9441		ctsio->kern_data_len = alloc_len;
9442		ctsio->kern_total_len = alloc_len;
9443	}
9444	ctsio->kern_data_resid = 0;
9445	ctsio->kern_rel_offset = 0;
9446	ctsio->kern_sg_entries = 0;
9447
9448	/*
9449	 * We set this to the actual data length, regardless of how much
9450	 * space we actually have to return results.  If the user looks at
9451	 * this value, he'll know whether or not he allocated enough space
9452	 * and reissue the command if necessary.  We don't support well
9453	 * known logical units, so if the user asks for that, return none.
9454	 */
9455	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9456
9457	/*
9458	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9459	 * this request.
9460	 */
9461	ctl_set_success(ctsio);
9462	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9463	ctsio->be_move_done = ctl_config_move_done;
9464	ctl_datamove((union ctl_io *)ctsio);
9465	return (retval);
9466}
9467
9468int
9469ctl_request_sense(struct ctl_scsiio *ctsio)
9470{
9471	struct scsi_request_sense *cdb;
9472	struct scsi_sense_data *sense_ptr;
9473	struct ctl_lun *lun;
9474	uint32_t initidx;
9475	int have_error;
9476	scsi_sense_data_type sense_format;
9477	ctl_ua_type ua_type;
9478
9479	cdb = (struct scsi_request_sense *)ctsio->cdb;
9480
9481	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9482
9483	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9484
9485	/*
9486	 * Determine which sense format the user wants.
9487	 */
9488	if (cdb->byte2 & SRS_DESC)
9489		sense_format = SSD_TYPE_DESC;
9490	else
9491		sense_format = SSD_TYPE_FIXED;
9492
9493	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9494	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9495	ctsio->kern_sg_entries = 0;
9496
9497	/*
9498	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9499	 * larger than the largest allowed value for the length field in the
9500	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9501	 */
9502	ctsio->residual = 0;
9503	ctsio->kern_data_len = cdb->length;
9504	ctsio->kern_total_len = cdb->length;
9505
9506	ctsio->kern_data_resid = 0;
9507	ctsio->kern_rel_offset = 0;
9508	ctsio->kern_sg_entries = 0;
9509
9510	/*
9511	 * If we don't have a LUN, we don't have any pending sense.
9512	 */
9513	if (lun == NULL)
9514		goto no_sense;
9515
9516	have_error = 0;
9517	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9518	/*
9519	 * Check for pending sense, and then for pending unit attentions.
9520	 * Pending sense gets returned first, then pending unit attentions.
9521	 */
9522	mtx_lock(&lun->lun_lock);
9523#ifdef CTL_WITH_CA
9524	if (ctl_is_set(lun->have_ca, initidx)) {
9525		scsi_sense_data_type stored_format;
9526
9527		/*
9528		 * Check to see which sense format was used for the stored
9529		 * sense data.
9530		 */
9531		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9532
9533		/*
9534		 * If the user requested a different sense format than the
9535		 * one we stored, then we need to convert it to the other
9536		 * format.  If we're going from descriptor to fixed format
9537		 * sense data, we may lose things in translation, depending
9538		 * on what options were used.
9539		 *
9540		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9541		 * for some reason we'll just copy it out as-is.
9542		 */
9543		if ((stored_format == SSD_TYPE_FIXED)
9544		 && (sense_format == SSD_TYPE_DESC))
9545			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9546			    &lun->pending_sense[initidx],
9547			    (struct scsi_sense_data_desc *)sense_ptr);
9548		else if ((stored_format == SSD_TYPE_DESC)
9549		      && (sense_format == SSD_TYPE_FIXED))
9550			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9551			    &lun->pending_sense[initidx],
9552			    (struct scsi_sense_data_fixed *)sense_ptr);
9553		else
9554			memcpy(sense_ptr, &lun->pending_sense[initidx],
9555			       ctl_min(sizeof(*sense_ptr),
9556			       sizeof(lun->pending_sense[initidx])));
9557
9558		ctl_clear_mask(lun->have_ca, initidx);
9559		have_error = 1;
9560	} else
9561#endif
9562	{
9563		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9564		if (ua_type != CTL_UA_NONE)
9565			have_error = 1;
9566	}
9567	mtx_unlock(&lun->lun_lock);
9568
9569	/*
9570	 * We already have a pending error, return it.
9571	 */
9572	if (have_error != 0) {
9573		/*
9574		 * We report the SCSI status as OK, since the status of the
9575		 * request sense command itself is OK.
9576		 * We report 0 for the sense length, because we aren't doing
9577		 * autosense in this case.  We're reporting sense as
9578		 * parameter data.
9579		 */
9580		ctl_set_success(ctsio);
9581		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9582		ctsio->be_move_done = ctl_config_move_done;
9583		ctl_datamove((union ctl_io *)ctsio);
9584		return (CTL_RETVAL_COMPLETE);
9585	}
9586
9587no_sense:
9588
9589	/*
9590	 * No sense information to report, so we report that everything is
9591	 * okay.
9592	 */
9593	ctl_set_sense_data(sense_ptr,
9594			   lun,
9595			   sense_format,
9596			   /*current_error*/ 1,
9597			   /*sense_key*/ SSD_KEY_NO_SENSE,
9598			   /*asc*/ 0x00,
9599			   /*ascq*/ 0x00,
9600			   SSD_ELEM_NONE);
9601
9602	/*
9603	 * We report 0 for the sense length, because we aren't doing
9604	 * autosense in this case.  We're reporting sense as parameter data.
9605	 */
9606	ctl_set_success(ctsio);
9607	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9608	ctsio->be_move_done = ctl_config_move_done;
9609	ctl_datamove((union ctl_io *)ctsio);
9610	return (CTL_RETVAL_COMPLETE);
9611}
9612
9613int
9614ctl_tur(struct ctl_scsiio *ctsio)
9615{
9616
9617	CTL_DEBUG_PRINT(("ctl_tur\n"));
9618
9619	ctl_set_success(ctsio);
9620	ctl_done((union ctl_io *)ctsio);
9621
9622	return (CTL_RETVAL_COMPLETE);
9623}
9624
9625#ifdef notyet
9626static int
9627ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9628{
9629
9630}
9631#endif
9632
9633static int
9634ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9635{
9636	struct scsi_vpd_supported_pages *pages;
9637	int sup_page_size;
9638	struct ctl_lun *lun;
9639
9640	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9641
9642	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9643	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9644	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9645	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9646	ctsio->kern_sg_entries = 0;
9647
9648	if (sup_page_size < alloc_len) {
9649		ctsio->residual = alloc_len - sup_page_size;
9650		ctsio->kern_data_len = sup_page_size;
9651		ctsio->kern_total_len = sup_page_size;
9652	} else {
9653		ctsio->residual = 0;
9654		ctsio->kern_data_len = alloc_len;
9655		ctsio->kern_total_len = alloc_len;
9656	}
9657	ctsio->kern_data_resid = 0;
9658	ctsio->kern_rel_offset = 0;
9659	ctsio->kern_sg_entries = 0;
9660
9661	/*
9662	 * The control device is always connected.  The disk device, on the
9663	 * other hand, may not be online all the time.  Need to change this
9664	 * to figure out whether the disk device is actually online or not.
9665	 */
9666	if (lun != NULL)
9667		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9668				lun->be_lun->lun_type;
9669	else
9670		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9671
9672	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9673	/* Supported VPD pages */
9674	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9675	/* Serial Number */
9676	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9677	/* Device Identification */
9678	pages->page_list[2] = SVPD_DEVICE_ID;
9679	/* Extended INQUIRY Data */
9680	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9681	/* Mode Page Policy */
9682	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9683	/* SCSI Ports */
9684	pages->page_list[5] = SVPD_SCSI_PORTS;
9685	/* Third-party Copy */
9686	pages->page_list[6] = SVPD_SCSI_TPC;
9687	/* Block limits */
9688	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9689	/* Block Device Characteristics */
9690	pages->page_list[8] = SVPD_BDC;
9691	/* Logical Block Provisioning */
9692	pages->page_list[9] = SVPD_LBP;
9693
9694	ctl_set_success(ctsio);
9695	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9696	ctsio->be_move_done = ctl_config_move_done;
9697	ctl_datamove((union ctl_io *)ctsio);
9698	return (CTL_RETVAL_COMPLETE);
9699}
9700
9701static int
9702ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9703{
9704	struct scsi_vpd_unit_serial_number *sn_ptr;
9705	struct ctl_lun *lun;
9706	int data_len;
9707
9708	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9709
9710	data_len = 4 + CTL_SN_LEN;
9711	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9712	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9713	if (data_len < alloc_len) {
9714		ctsio->residual = alloc_len - data_len;
9715		ctsio->kern_data_len = data_len;
9716		ctsio->kern_total_len = data_len;
9717	} else {
9718		ctsio->residual = 0;
9719		ctsio->kern_data_len = alloc_len;
9720		ctsio->kern_total_len = alloc_len;
9721	}
9722	ctsio->kern_data_resid = 0;
9723	ctsio->kern_rel_offset = 0;
9724	ctsio->kern_sg_entries = 0;
9725
9726	/*
9727	 * The control device is always connected.  The disk device, on the
9728	 * other hand, may not be online all the time.  Need to change this
9729	 * to figure out whether the disk device is actually online or not.
9730	 */
9731	if (lun != NULL)
9732		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9733				  lun->be_lun->lun_type;
9734	else
9735		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9736
9737	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9738	sn_ptr->length = CTL_SN_LEN;
9739	/*
9740	 * If we don't have a LUN, we just leave the serial number as
9741	 * all spaces.
9742	 */
9743	if (lun != NULL) {
9744		strncpy((char *)sn_ptr->serial_num,
9745			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9746	} else
9747		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9748
9749	ctl_set_success(ctsio);
9750	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9751	ctsio->be_move_done = ctl_config_move_done;
9752	ctl_datamove((union ctl_io *)ctsio);
9753	return (CTL_RETVAL_COMPLETE);
9754}
9755
9756
9757static int
9758ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9759{
9760	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9761	struct ctl_lun *lun;
9762	int data_len;
9763
9764	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9765
9766	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9767	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9768	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9769	ctsio->kern_sg_entries = 0;
9770
9771	if (data_len < alloc_len) {
9772		ctsio->residual = alloc_len - data_len;
9773		ctsio->kern_data_len = data_len;
9774		ctsio->kern_total_len = data_len;
9775	} else {
9776		ctsio->residual = 0;
9777		ctsio->kern_data_len = alloc_len;
9778		ctsio->kern_total_len = alloc_len;
9779	}
9780	ctsio->kern_data_resid = 0;
9781	ctsio->kern_rel_offset = 0;
9782	ctsio->kern_sg_entries = 0;
9783
9784	/*
9785	 * The control device is always connected.  The disk device, on the
9786	 * other hand, may not be online all the time.
9787	 */
9788	if (lun != NULL)
9789		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9790				     lun->be_lun->lun_type;
9791	else
9792		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9793	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9794	eid_ptr->page_length = data_len - 4;
9795	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9796	eid_ptr->flags3 = SVPD_EID_V_SUP;
9797
9798	ctl_set_success(ctsio);
9799	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9800	ctsio->be_move_done = ctl_config_move_done;
9801	ctl_datamove((union ctl_io *)ctsio);
9802	return (CTL_RETVAL_COMPLETE);
9803}
9804
9805static int
9806ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9807{
9808	struct scsi_vpd_mode_page_policy *mpp_ptr;
9809	struct ctl_lun *lun;
9810	int data_len;
9811
9812	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9813
9814	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9815	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9816
9817	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9818	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9819	ctsio->kern_sg_entries = 0;
9820
9821	if (data_len < alloc_len) {
9822		ctsio->residual = alloc_len - data_len;
9823		ctsio->kern_data_len = data_len;
9824		ctsio->kern_total_len = data_len;
9825	} else {
9826		ctsio->residual = 0;
9827		ctsio->kern_data_len = alloc_len;
9828		ctsio->kern_total_len = alloc_len;
9829	}
9830	ctsio->kern_data_resid = 0;
9831	ctsio->kern_rel_offset = 0;
9832	ctsio->kern_sg_entries = 0;
9833
9834	/*
9835	 * The control device is always connected.  The disk device, on the
9836	 * other hand, may not be online all the time.
9837	 */
9838	if (lun != NULL)
9839		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9840				     lun->be_lun->lun_type;
9841	else
9842		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9843	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9844	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9845	mpp_ptr->descr[0].page_code = 0x3f;
9846	mpp_ptr->descr[0].subpage_code = 0xff;
9847	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9848
9849	ctl_set_success(ctsio);
9850	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9851	ctsio->be_move_done = ctl_config_move_done;
9852	ctl_datamove((union ctl_io *)ctsio);
9853	return (CTL_RETVAL_COMPLETE);
9854}
9855
9856static int
9857ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9858{
9859	struct scsi_vpd_device_id *devid_ptr;
9860	struct scsi_vpd_id_descriptor *desc;
9861	struct ctl_softc *ctl_softc;
9862	struct ctl_lun *lun;
9863	struct ctl_port *port;
9864	int data_len;
9865	uint8_t proto;
9866
9867	ctl_softc = control_softc;
9868
9869	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9870	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9871
9872	data_len = sizeof(struct scsi_vpd_device_id) +
9873	    sizeof(struct scsi_vpd_id_descriptor) +
9874		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9875	    sizeof(struct scsi_vpd_id_descriptor) +
9876		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9877	if (lun && lun->lun_devid)
9878		data_len += lun->lun_devid->len;
9879	if (port->port_devid)
9880		data_len += port->port_devid->len;
9881	if (port->target_devid)
9882		data_len += port->target_devid->len;
9883
9884	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9885	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9886	ctsio->kern_sg_entries = 0;
9887
9888	if (data_len < alloc_len) {
9889		ctsio->residual = alloc_len - data_len;
9890		ctsio->kern_data_len = data_len;
9891		ctsio->kern_total_len = data_len;
9892	} else {
9893		ctsio->residual = 0;
9894		ctsio->kern_data_len = alloc_len;
9895		ctsio->kern_total_len = alloc_len;
9896	}
9897	ctsio->kern_data_resid = 0;
9898	ctsio->kern_rel_offset = 0;
9899	ctsio->kern_sg_entries = 0;
9900
9901	/*
9902	 * The control device is always connected.  The disk device, on the
9903	 * other hand, may not be online all the time.
9904	 */
9905	if (lun != NULL)
9906		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9907				     lun->be_lun->lun_type;
9908	else
9909		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9910	devid_ptr->page_code = SVPD_DEVICE_ID;
9911	scsi_ulto2b(data_len - 4, devid_ptr->length);
9912
9913	if (port->port_type == CTL_PORT_FC)
9914		proto = SCSI_PROTO_FC << 4;
9915	else if (port->port_type == CTL_PORT_ISCSI)
9916		proto = SCSI_PROTO_ISCSI << 4;
9917	else
9918		proto = SCSI_PROTO_SPI << 4;
9919	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9920
9921	/*
9922	 * We're using a LUN association here.  i.e., this device ID is a
9923	 * per-LUN identifier.
9924	 */
9925	if (lun && lun->lun_devid) {
9926		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9927		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9928		    lun->lun_devid->len);
9929	}
9930
9931	/*
9932	 * This is for the WWPN which is a port association.
9933	 */
9934	if (port->port_devid) {
9935		memcpy(desc, port->port_devid->data, port->port_devid->len);
9936		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9937		    port->port_devid->len);
9938	}
9939
9940	/*
9941	 * This is for the Relative Target Port(type 4h) identifier
9942	 */
9943	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9944	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9945	    SVPD_ID_TYPE_RELTARG;
9946	desc->length = 4;
9947	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9948	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9949	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9950
9951	/*
9952	 * This is for the Target Port Group(type 5h) identifier
9953	 */
9954	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9955	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9956	    SVPD_ID_TYPE_TPORTGRP;
9957	desc->length = 4;
9958	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9959	    &desc->identifier[2]);
9960	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9961	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9962
9963	/*
9964	 * This is for the Target identifier
9965	 */
9966	if (port->target_devid) {
9967		memcpy(desc, port->target_devid->data, port->target_devid->len);
9968	}
9969
9970	ctl_set_success(ctsio);
9971	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9972	ctsio->be_move_done = ctl_config_move_done;
9973	ctl_datamove((union ctl_io *)ctsio);
9974	return (CTL_RETVAL_COMPLETE);
9975}
9976
9977static int
9978ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9979{
9980	struct ctl_softc *softc = control_softc;
9981	struct scsi_vpd_scsi_ports *sp;
9982	struct scsi_vpd_port_designation *pd;
9983	struct scsi_vpd_port_designation_cont *pdc;
9984	struct ctl_lun *lun;
9985	struct ctl_port *port;
9986	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9987	int num_target_port_groups;
9988
9989	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9990
9991	if (softc->is_single)
9992		num_target_port_groups = 1;
9993	else
9994		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9995	num_target_ports = 0;
9996	iid_len = 0;
9997	id_len = 0;
9998	mtx_lock(&softc->ctl_lock);
9999	STAILQ_FOREACH(port, &softc->port_list, links) {
10000		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10001			continue;
10002		if (lun != NULL &&
10003		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10004		    CTL_MAX_LUNS)
10005			continue;
10006		num_target_ports++;
10007		if (port->init_devid)
10008			iid_len += port->init_devid->len;
10009		if (port->port_devid)
10010			id_len += port->port_devid->len;
10011	}
10012	mtx_unlock(&softc->ctl_lock);
10013
10014	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10015	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10016	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10017	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10018	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10019	ctsio->kern_sg_entries = 0;
10020
10021	if (data_len < alloc_len) {
10022		ctsio->residual = alloc_len - data_len;
10023		ctsio->kern_data_len = data_len;
10024		ctsio->kern_total_len = data_len;
10025	} else {
10026		ctsio->residual = 0;
10027		ctsio->kern_data_len = alloc_len;
10028		ctsio->kern_total_len = alloc_len;
10029	}
10030	ctsio->kern_data_resid = 0;
10031	ctsio->kern_rel_offset = 0;
10032	ctsio->kern_sg_entries = 0;
10033
10034	/*
10035	 * The control device is always connected.  The disk device, on the
10036	 * other hand, may not be online all the time.  Need to change this
10037	 * to figure out whether the disk device is actually online or not.
10038	 */
10039	if (lun != NULL)
10040		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10041				  lun->be_lun->lun_type;
10042	else
10043		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10044
10045	sp->page_code = SVPD_SCSI_PORTS;
10046	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10047	    sp->page_length);
10048	pd = &sp->design[0];
10049
10050	mtx_lock(&softc->ctl_lock);
10051	pg = softc->port_offset / CTL_MAX_PORTS;
10052	for (g = 0; g < num_target_port_groups; g++) {
10053		STAILQ_FOREACH(port, &softc->port_list, links) {
10054			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10055				continue;
10056			if (lun != NULL &&
10057			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10058			    CTL_MAX_LUNS)
10059				continue;
10060			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10061			scsi_ulto2b(p, pd->relative_port_id);
10062			if (port->init_devid && g == pg) {
10063				iid_len = port->init_devid->len;
10064				memcpy(pd->initiator_transportid,
10065				    port->init_devid->data, port->init_devid->len);
10066			} else
10067				iid_len = 0;
10068			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10069			pdc = (struct scsi_vpd_port_designation_cont *)
10070			    (&pd->initiator_transportid[iid_len]);
10071			if (port->port_devid && g == pg) {
10072				id_len = port->port_devid->len;
10073				memcpy(pdc->target_port_descriptors,
10074				    port->port_devid->data, port->port_devid->len);
10075			} else
10076				id_len = 0;
10077			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10078			pd = (struct scsi_vpd_port_designation *)
10079			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10080		}
10081	}
10082	mtx_unlock(&softc->ctl_lock);
10083
10084	ctl_set_success(ctsio);
10085	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10086	ctsio->be_move_done = ctl_config_move_done;
10087	ctl_datamove((union ctl_io *)ctsio);
10088	return (CTL_RETVAL_COMPLETE);
10089}
10090
10091static int
10092ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10093{
10094	struct scsi_vpd_block_limits *bl_ptr;
10095	struct ctl_lun *lun;
10096	int bs;
10097
10098	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10099
10100	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10101	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10102	ctsio->kern_sg_entries = 0;
10103
10104	if (sizeof(*bl_ptr) < alloc_len) {
10105		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10106		ctsio->kern_data_len = sizeof(*bl_ptr);
10107		ctsio->kern_total_len = sizeof(*bl_ptr);
10108	} else {
10109		ctsio->residual = 0;
10110		ctsio->kern_data_len = alloc_len;
10111		ctsio->kern_total_len = alloc_len;
10112	}
10113	ctsio->kern_data_resid = 0;
10114	ctsio->kern_rel_offset = 0;
10115	ctsio->kern_sg_entries = 0;
10116
10117	/*
10118	 * The control device is always connected.  The disk device, on the
10119	 * other hand, may not be online all the time.  Need to change this
10120	 * to figure out whether the disk device is actually online or not.
10121	 */
10122	if (lun != NULL)
10123		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10124				  lun->be_lun->lun_type;
10125	else
10126		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10127
10128	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10129	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10130	bl_ptr->max_cmp_write_len = 0xff;
10131	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10132	if (lun != NULL) {
10133		bs = lun->be_lun->blocksize;
10134		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10135		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10136			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10137			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10138			if (lun->be_lun->pblockexp != 0) {
10139				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10140				    bl_ptr->opt_unmap_grain);
10141				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10142				    bl_ptr->unmap_grain_align);
10143			}
10144		}
10145		scsi_ulto4b(lun->be_lun->atomicblock,
10146		    bl_ptr->max_atomic_transfer_length);
10147		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10148		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10149	}
10150	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10151
10152	ctl_set_success(ctsio);
10153	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10154	ctsio->be_move_done = ctl_config_move_done;
10155	ctl_datamove((union ctl_io *)ctsio);
10156	return (CTL_RETVAL_COMPLETE);
10157}
10158
10159static int
10160ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10161{
10162	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10163	struct ctl_lun *lun;
10164	const char *value;
10165	u_int i;
10166
10167	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10168
10169	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10170	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10171	ctsio->kern_sg_entries = 0;
10172
10173	if (sizeof(*bdc_ptr) < alloc_len) {
10174		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10175		ctsio->kern_data_len = sizeof(*bdc_ptr);
10176		ctsio->kern_total_len = sizeof(*bdc_ptr);
10177	} else {
10178		ctsio->residual = 0;
10179		ctsio->kern_data_len = alloc_len;
10180		ctsio->kern_total_len = alloc_len;
10181	}
10182	ctsio->kern_data_resid = 0;
10183	ctsio->kern_rel_offset = 0;
10184	ctsio->kern_sg_entries = 0;
10185
10186	/*
10187	 * The control device is always connected.  The disk device, on the
10188	 * other hand, may not be online all the time.  Need to change this
10189	 * to figure out whether the disk device is actually online or not.
10190	 */
10191	if (lun != NULL)
10192		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10193				  lun->be_lun->lun_type;
10194	else
10195		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10196	bdc_ptr->page_code = SVPD_BDC;
10197	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10198	if (lun != NULL &&
10199	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10200		i = strtol(value, NULL, 0);
10201	else
10202		i = CTL_DEFAULT_ROTATION_RATE;
10203	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10204	if (lun != NULL &&
10205	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10206		i = strtol(value, NULL, 0);
10207	else
10208		i = 0;
10209	bdc_ptr->wab_wac_ff = (i & 0x0f);
10210	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10211
10212	ctl_set_success(ctsio);
10213	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10214	ctsio->be_move_done = ctl_config_move_done;
10215	ctl_datamove((union ctl_io *)ctsio);
10216	return (CTL_RETVAL_COMPLETE);
10217}
10218
10219static int
10220ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10221{
10222	struct scsi_vpd_logical_block_prov *lbp_ptr;
10223	struct ctl_lun *lun;
10224
10225	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10226
10227	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10228	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10229	ctsio->kern_sg_entries = 0;
10230
10231	if (sizeof(*lbp_ptr) < alloc_len) {
10232		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10233		ctsio->kern_data_len = sizeof(*lbp_ptr);
10234		ctsio->kern_total_len = sizeof(*lbp_ptr);
10235	} else {
10236		ctsio->residual = 0;
10237		ctsio->kern_data_len = alloc_len;
10238		ctsio->kern_total_len = alloc_len;
10239	}
10240	ctsio->kern_data_resid = 0;
10241	ctsio->kern_rel_offset = 0;
10242	ctsio->kern_sg_entries = 0;
10243
10244	/*
10245	 * The control device is always connected.  The disk device, on the
10246	 * other hand, may not be online all the time.  Need to change this
10247	 * to figure out whether the disk device is actually online or not.
10248	 */
10249	if (lun != NULL)
10250		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10251				  lun->be_lun->lun_type;
10252	else
10253		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10254
10255	lbp_ptr->page_code = SVPD_LBP;
10256	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10257	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10258	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10259		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10260		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10261		lbp_ptr->prov_type = SVPD_LBP_THIN;
10262	}
10263
10264	ctl_set_success(ctsio);
10265	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10266	ctsio->be_move_done = ctl_config_move_done;
10267	ctl_datamove((union ctl_io *)ctsio);
10268	return (CTL_RETVAL_COMPLETE);
10269}
10270
10271static int
10272ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10273{
10274	struct scsi_inquiry *cdb;
10275	int alloc_len, retval;
10276
10277	cdb = (struct scsi_inquiry *)ctsio->cdb;
10278
10279	retval = CTL_RETVAL_COMPLETE;
10280
10281	alloc_len = scsi_2btoul(cdb->length);
10282
10283	switch (cdb->page_code) {
10284	case SVPD_SUPPORTED_PAGES:
10285		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10286		break;
10287	case SVPD_UNIT_SERIAL_NUMBER:
10288		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10289		break;
10290	case SVPD_DEVICE_ID:
10291		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10292		break;
10293	case SVPD_EXTENDED_INQUIRY_DATA:
10294		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10295		break;
10296	case SVPD_MODE_PAGE_POLICY:
10297		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10298		break;
10299	case SVPD_SCSI_PORTS:
10300		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10301		break;
10302	case SVPD_SCSI_TPC:
10303		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10304		break;
10305	case SVPD_BLOCK_LIMITS:
10306		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10307		break;
10308	case SVPD_BDC:
10309		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10310		break;
10311	case SVPD_LBP:
10312		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10313		break;
10314	default:
10315		ctl_set_invalid_field(ctsio,
10316				      /*sks_valid*/ 1,
10317				      /*command*/ 1,
10318				      /*field*/ 2,
10319				      /*bit_valid*/ 0,
10320				      /*bit*/ 0);
10321		ctl_done((union ctl_io *)ctsio);
10322		retval = CTL_RETVAL_COMPLETE;
10323		break;
10324	}
10325
10326	return (retval);
10327}
10328
10329static int
10330ctl_inquiry_std(struct ctl_scsiio *ctsio)
10331{
10332	struct scsi_inquiry_data *inq_ptr;
10333	struct scsi_inquiry *cdb;
10334	struct ctl_softc *ctl_softc;
10335	struct ctl_lun *lun;
10336	char *val;
10337	uint32_t alloc_len, data_len;
10338	ctl_port_type port_type;
10339
10340	ctl_softc = control_softc;
10341
10342	/*
10343	 * Figure out whether we're talking to a Fibre Channel port or not.
10344	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10345	 * SCSI front ends.
10346	 */
10347	port_type = ctl_softc->ctl_ports[
10348	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10349	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10350		port_type = CTL_PORT_SCSI;
10351
10352	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10353	cdb = (struct scsi_inquiry *)ctsio->cdb;
10354	alloc_len = scsi_2btoul(cdb->length);
10355
10356	/*
10357	 * We malloc the full inquiry data size here and fill it
10358	 * in.  If the user only asks for less, we'll give him
10359	 * that much.
10360	 */
10361	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10362	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10363	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10364	ctsio->kern_sg_entries = 0;
10365	ctsio->kern_data_resid = 0;
10366	ctsio->kern_rel_offset = 0;
10367
10368	if (data_len < alloc_len) {
10369		ctsio->residual = alloc_len - data_len;
10370		ctsio->kern_data_len = data_len;
10371		ctsio->kern_total_len = data_len;
10372	} else {
10373		ctsio->residual = 0;
10374		ctsio->kern_data_len = alloc_len;
10375		ctsio->kern_total_len = alloc_len;
10376	}
10377
10378	/*
10379	 * If we have a LUN configured, report it as connected.  Otherwise,
10380	 * report that it is offline or no device is supported, depending
10381	 * on the value of inquiry_pq_no_lun.
10382	 *
10383	 * According to the spec (SPC-4 r34), the peripheral qualifier
10384	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10385	 *
10386	 * "A peripheral device having the specified peripheral device type
10387	 * is not connected to this logical unit. However, the device
10388	 * server is capable of supporting the specified peripheral device
10389	 * type on this logical unit."
10390	 *
10391	 * According to the same spec, the peripheral qualifier
10392	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10393	 *
10394	 * "The device server is not capable of supporting a peripheral
10395	 * device on this logical unit. For this peripheral qualifier the
10396	 * peripheral device type shall be set to 1Fh. All other peripheral
10397	 * device type values are reserved for this peripheral qualifier."
10398	 *
10399	 * Given the text, it would seem that we probably want to report that
10400	 * the LUN is offline here.  There is no LUN connected, but we can
10401	 * support a LUN at the given LUN number.
10402	 *
10403	 * In the real world, though, it sounds like things are a little
10404	 * different:
10405	 *
10406	 * - Linux, when presented with a LUN with the offline peripheral
10407	 *   qualifier, will create an sg driver instance for it.  So when
10408	 *   you attach it to CTL, you wind up with a ton of sg driver
10409	 *   instances.  (One for every LUN that Linux bothered to probe.)
10410	 *   Linux does this despite the fact that it issues a REPORT LUNs
10411	 *   to LUN 0 to get the inventory of supported LUNs.
10412	 *
10413	 * - There is other anecdotal evidence (from Emulex folks) about
10414	 *   arrays that use the offline peripheral qualifier for LUNs that
10415	 *   are on the "passive" path in an active/passive array.
10416	 *
10417	 * So the solution is provide a hopefully reasonable default
10418	 * (return bad/no LUN) and allow the user to change the behavior
10419	 * with a tunable/sysctl variable.
10420	 */
10421	if (lun != NULL)
10422		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10423				  lun->be_lun->lun_type;
10424	else if (ctl_softc->inquiry_pq_no_lun == 0)
10425		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10426	else
10427		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10428
10429	/* RMB in byte 2 is 0 */
10430	inq_ptr->version = SCSI_REV_SPC4;
10431
10432	/*
10433	 * According to SAM-3, even if a device only supports a single
10434	 * level of LUN addressing, it should still set the HISUP bit:
10435	 *
10436	 * 4.9.1 Logical unit numbers overview
10437	 *
10438	 * All logical unit number formats described in this standard are
10439	 * hierarchical in structure even when only a single level in that
10440	 * hierarchy is used. The HISUP bit shall be set to one in the
10441	 * standard INQUIRY data (see SPC-2) when any logical unit number
10442	 * format described in this standard is used.  Non-hierarchical
10443	 * formats are outside the scope of this standard.
10444	 *
10445	 * Therefore we set the HiSup bit here.
10446	 *
10447	 * The reponse format is 2, per SPC-3.
10448	 */
10449	inq_ptr->response_format = SID_HiSup | 2;
10450
10451	inq_ptr->additional_length = data_len -
10452	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10453	CTL_DEBUG_PRINT(("additional_length = %d\n",
10454			 inq_ptr->additional_length));
10455
10456	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10457	/* 16 bit addressing */
10458	if (port_type == CTL_PORT_SCSI)
10459		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10460	/* XXX set the SID_MultiP bit here if we're actually going to
10461	   respond on multiple ports */
10462	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10463
10464	/* 16 bit data bus, synchronous transfers */
10465	if (port_type == CTL_PORT_SCSI)
10466		inq_ptr->flags = SID_WBus16 | SID_Sync;
10467	/*
10468	 * XXX KDM do we want to support tagged queueing on the control
10469	 * device at all?
10470	 */
10471	if ((lun == NULL)
10472	 || (lun->be_lun->lun_type != T_PROCESSOR))
10473		inq_ptr->flags |= SID_CmdQue;
10474	/*
10475	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10476	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10477	 * name and 4 bytes for the revision.
10478	 */
10479	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10480	    "vendor")) == NULL) {
10481		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10482	} else {
10483		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10484		strncpy(inq_ptr->vendor, val,
10485		    min(sizeof(inq_ptr->vendor), strlen(val)));
10486	}
10487	if (lun == NULL) {
10488		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10489		    sizeof(inq_ptr->product));
10490	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10491		switch (lun->be_lun->lun_type) {
10492		case T_DIRECT:
10493			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10494			    sizeof(inq_ptr->product));
10495			break;
10496		case T_PROCESSOR:
10497			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10498			    sizeof(inq_ptr->product));
10499			break;
10500		default:
10501			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10502			    sizeof(inq_ptr->product));
10503			break;
10504		}
10505	} else {
10506		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10507		strncpy(inq_ptr->product, val,
10508		    min(sizeof(inq_ptr->product), strlen(val)));
10509	}
10510
10511	/*
10512	 * XXX make this a macro somewhere so it automatically gets
10513	 * incremented when we make changes.
10514	 */
10515	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10516	    "revision")) == NULL) {
10517		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10518	} else {
10519		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10520		strncpy(inq_ptr->revision, val,
10521		    min(sizeof(inq_ptr->revision), strlen(val)));
10522	}
10523
10524	/*
10525	 * For parallel SCSI, we support double transition and single
10526	 * transition clocking.  We also support QAS (Quick Arbitration
10527	 * and Selection) and Information Unit transfers on both the
10528	 * control and array devices.
10529	 */
10530	if (port_type == CTL_PORT_SCSI)
10531		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10532				    SID_SPI_IUS;
10533
10534	/* SAM-5 (no version claimed) */
10535	scsi_ulto2b(0x00A0, inq_ptr->version1);
10536	/* SPC-4 (no version claimed) */
10537	scsi_ulto2b(0x0460, inq_ptr->version2);
10538	if (port_type == CTL_PORT_FC) {
10539		/* FCP-2 ANSI INCITS.350:2003 */
10540		scsi_ulto2b(0x0917, inq_ptr->version3);
10541	} else if (port_type == CTL_PORT_SCSI) {
10542		/* SPI-4 ANSI INCITS.362:200x */
10543		scsi_ulto2b(0x0B56, inq_ptr->version3);
10544	} else if (port_type == CTL_PORT_ISCSI) {
10545		/* iSCSI (no version claimed) */
10546		scsi_ulto2b(0x0960, inq_ptr->version3);
10547	} else if (port_type == CTL_PORT_SAS) {
10548		/* SAS (no version claimed) */
10549		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10550	}
10551
10552	if (lun == NULL) {
10553		/* SBC-4 (no version claimed) */
10554		scsi_ulto2b(0x0600, inq_ptr->version4);
10555	} else {
10556		switch (lun->be_lun->lun_type) {
10557		case T_DIRECT:
10558			/* SBC-4 (no version claimed) */
10559			scsi_ulto2b(0x0600, inq_ptr->version4);
10560			break;
10561		case T_PROCESSOR:
10562		default:
10563			break;
10564		}
10565	}
10566
10567	ctl_set_success(ctsio);
10568	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10569	ctsio->be_move_done = ctl_config_move_done;
10570	ctl_datamove((union ctl_io *)ctsio);
10571	return (CTL_RETVAL_COMPLETE);
10572}
10573
10574int
10575ctl_inquiry(struct ctl_scsiio *ctsio)
10576{
10577	struct scsi_inquiry *cdb;
10578	int retval;
10579
10580	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10581
10582	cdb = (struct scsi_inquiry *)ctsio->cdb;
10583	if (cdb->byte2 & SI_EVPD)
10584		retval = ctl_inquiry_evpd(ctsio);
10585	else if (cdb->page_code == 0)
10586		retval = ctl_inquiry_std(ctsio);
10587	else {
10588		ctl_set_invalid_field(ctsio,
10589				      /*sks_valid*/ 1,
10590				      /*command*/ 1,
10591				      /*field*/ 2,
10592				      /*bit_valid*/ 0,
10593				      /*bit*/ 0);
10594		ctl_done((union ctl_io *)ctsio);
10595		return (CTL_RETVAL_COMPLETE);
10596	}
10597
10598	return (retval);
10599}
10600
10601/*
10602 * For known CDB types, parse the LBA and length.
10603 */
10604static int
10605ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10606{
10607	if (io->io_hdr.io_type != CTL_IO_SCSI)
10608		return (1);
10609
10610	switch (io->scsiio.cdb[0]) {
10611	case COMPARE_AND_WRITE: {
10612		struct scsi_compare_and_write *cdb;
10613
10614		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10615
10616		*lba = scsi_8btou64(cdb->addr);
10617		*len = cdb->length;
10618		break;
10619	}
10620	case READ_6:
10621	case WRITE_6: {
10622		struct scsi_rw_6 *cdb;
10623
10624		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10625
10626		*lba = scsi_3btoul(cdb->addr);
10627		/* only 5 bits are valid in the most significant address byte */
10628		*lba &= 0x1fffff;
10629		*len = cdb->length;
10630		break;
10631	}
10632	case READ_10:
10633	case WRITE_10: {
10634		struct scsi_rw_10 *cdb;
10635
10636		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10637
10638		*lba = scsi_4btoul(cdb->addr);
10639		*len = scsi_2btoul(cdb->length);
10640		break;
10641	}
10642	case WRITE_VERIFY_10: {
10643		struct scsi_write_verify_10 *cdb;
10644
10645		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10646
10647		*lba = scsi_4btoul(cdb->addr);
10648		*len = scsi_2btoul(cdb->length);
10649		break;
10650	}
10651	case READ_12:
10652	case WRITE_12: {
10653		struct scsi_rw_12 *cdb;
10654
10655		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10656
10657		*lba = scsi_4btoul(cdb->addr);
10658		*len = scsi_4btoul(cdb->length);
10659		break;
10660	}
10661	case WRITE_VERIFY_12: {
10662		struct scsi_write_verify_12 *cdb;
10663
10664		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10665
10666		*lba = scsi_4btoul(cdb->addr);
10667		*len = scsi_4btoul(cdb->length);
10668		break;
10669	}
10670	case READ_16:
10671	case WRITE_16:
10672	case WRITE_ATOMIC_16: {
10673		struct scsi_rw_16 *cdb;
10674
10675		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10676
10677		*lba = scsi_8btou64(cdb->addr);
10678		*len = scsi_4btoul(cdb->length);
10679		break;
10680	}
10681	case WRITE_VERIFY_16: {
10682		struct scsi_write_verify_16 *cdb;
10683
10684		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10685
10686		*lba = scsi_8btou64(cdb->addr);
10687		*len = scsi_4btoul(cdb->length);
10688		break;
10689	}
10690	case WRITE_SAME_10: {
10691		struct scsi_write_same_10 *cdb;
10692
10693		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10694
10695		*lba = scsi_4btoul(cdb->addr);
10696		*len = scsi_2btoul(cdb->length);
10697		break;
10698	}
10699	case WRITE_SAME_16: {
10700		struct scsi_write_same_16 *cdb;
10701
10702		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10703
10704		*lba = scsi_8btou64(cdb->addr);
10705		*len = scsi_4btoul(cdb->length);
10706		break;
10707	}
10708	case VERIFY_10: {
10709		struct scsi_verify_10 *cdb;
10710
10711		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10712
10713		*lba = scsi_4btoul(cdb->addr);
10714		*len = scsi_2btoul(cdb->length);
10715		break;
10716	}
10717	case VERIFY_12: {
10718		struct scsi_verify_12 *cdb;
10719
10720		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10721
10722		*lba = scsi_4btoul(cdb->addr);
10723		*len = scsi_4btoul(cdb->length);
10724		break;
10725	}
10726	case VERIFY_16: {
10727		struct scsi_verify_16 *cdb;
10728
10729		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10730
10731		*lba = scsi_8btou64(cdb->addr);
10732		*len = scsi_4btoul(cdb->length);
10733		break;
10734	}
10735	case UNMAP: {
10736		*lba = 0;
10737		*len = UINT64_MAX;
10738		break;
10739	}
10740	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10741		struct scsi_get_lba_status *cdb;
10742
10743		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10744		*lba = scsi_8btou64(cdb->addr);
10745		*len = UINT32_MAX;
10746		break;
10747	}
10748	default:
10749		return (1);
10750		break; /* NOTREACHED */
10751	}
10752
10753	return (0);
10754}
10755
10756static ctl_action
10757ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10758{
10759	uint64_t endlba1, endlba2;
10760
10761	endlba1 = lba1 + len1 - 1;
10762	endlba2 = lba2 + len2 - 1;
10763
10764	if ((endlba1 < lba2)
10765	 || (endlba2 < lba1))
10766		return (CTL_ACTION_PASS);
10767	else
10768		return (CTL_ACTION_BLOCK);
10769}
10770
10771static int
10772ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10773{
10774	struct ctl_ptr_len_flags *ptrlen;
10775	struct scsi_unmap_desc *buf, *end, *range;
10776	uint64_t lba;
10777	uint32_t len;
10778
10779	/* If not UNMAP -- go other way. */
10780	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10781	    io->scsiio.cdb[0] != UNMAP)
10782		return (CTL_ACTION_ERROR);
10783
10784	/* If UNMAP without data -- block and wait for data. */
10785	ptrlen = (struct ctl_ptr_len_flags *)
10786	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10787	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10788	    ptrlen->ptr == NULL)
10789		return (CTL_ACTION_BLOCK);
10790
10791	/* UNMAP with data -- check for collision. */
10792	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10793	end = buf + ptrlen->len / sizeof(*buf);
10794	for (range = buf; range < end; range++) {
10795		lba = scsi_8btou64(range->lba);
10796		len = scsi_4btoul(range->length);
10797		if ((lba < lba2 + len2) && (lba + len > lba2))
10798			return (CTL_ACTION_BLOCK);
10799	}
10800	return (CTL_ACTION_PASS);
10801}
10802
10803static ctl_action
10804ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10805{
10806	uint64_t lba1, lba2;
10807	uint64_t len1, len2;
10808	int retval;
10809
10810	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10811		return (CTL_ACTION_ERROR);
10812
10813	retval = ctl_extent_check_unmap(io2, lba1, len1);
10814	if (retval != CTL_ACTION_ERROR)
10815		return (retval);
10816
10817	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10818		return (CTL_ACTION_ERROR);
10819
10820	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10821}
10822
10823static ctl_action
10824ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10825    union ctl_io *ooa_io)
10826{
10827	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10828	ctl_serialize_action *serialize_row;
10829
10830	/*
10831	 * The initiator attempted multiple untagged commands at the same
10832	 * time.  Can't do that.
10833	 */
10834	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10835	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10836	 && ((pending_io->io_hdr.nexus.targ_port ==
10837	      ooa_io->io_hdr.nexus.targ_port)
10838	  && (pending_io->io_hdr.nexus.initid.id ==
10839	      ooa_io->io_hdr.nexus.initid.id))
10840	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10841		return (CTL_ACTION_OVERLAP);
10842
10843	/*
10844	 * The initiator attempted to send multiple tagged commands with
10845	 * the same ID.  (It's fine if different initiators have the same
10846	 * tag ID.)
10847	 *
10848	 * Even if all of those conditions are true, we don't kill the I/O
10849	 * if the command ahead of us has been aborted.  We won't end up
10850	 * sending it to the FETD, and it's perfectly legal to resend a
10851	 * command with the same tag number as long as the previous
10852	 * instance of this tag number has been aborted somehow.
10853	 */
10854	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10855	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10856	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10857	 && ((pending_io->io_hdr.nexus.targ_port ==
10858	      ooa_io->io_hdr.nexus.targ_port)
10859	  && (pending_io->io_hdr.nexus.initid.id ==
10860	      ooa_io->io_hdr.nexus.initid.id))
10861	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10862		return (CTL_ACTION_OVERLAP_TAG);
10863
10864	/*
10865	 * If we get a head of queue tag, SAM-3 says that we should
10866	 * immediately execute it.
10867	 *
10868	 * What happens if this command would normally block for some other
10869	 * reason?  e.g. a request sense with a head of queue tag
10870	 * immediately after a write.  Normally that would block, but this
10871	 * will result in its getting executed immediately...
10872	 *
10873	 * We currently return "pass" instead of "skip", so we'll end up
10874	 * going through the rest of the queue to check for overlapped tags.
10875	 *
10876	 * XXX KDM check for other types of blockage first??
10877	 */
10878	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10879		return (CTL_ACTION_PASS);
10880
10881	/*
10882	 * Ordered tags have to block until all items ahead of them
10883	 * have completed.  If we get called with an ordered tag, we always
10884	 * block, if something else is ahead of us in the queue.
10885	 */
10886	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10887		return (CTL_ACTION_BLOCK);
10888
10889	/*
10890	 * Simple tags get blocked until all head of queue and ordered tags
10891	 * ahead of them have completed.  I'm lumping untagged commands in
10892	 * with simple tags here.  XXX KDM is that the right thing to do?
10893	 */
10894	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10895	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10896	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10897	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10898		return (CTL_ACTION_BLOCK);
10899
10900	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10901	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10902
10903	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10904
10905	switch (serialize_row[pending_entry->seridx]) {
10906	case CTL_SER_BLOCK:
10907		return (CTL_ACTION_BLOCK);
10908	case CTL_SER_EXTENT:
10909		return (ctl_extent_check(pending_io, ooa_io));
10910	case CTL_SER_EXTENTOPT:
10911		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10912		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10913			return (ctl_extent_check(pending_io, ooa_io));
10914		/* FALLTHROUGH */
10915	case CTL_SER_PASS:
10916		return (CTL_ACTION_PASS);
10917	case CTL_SER_BLOCKOPT:
10918		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10919		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10920			return (CTL_ACTION_BLOCK);
10921		return (CTL_ACTION_PASS);
10922	case CTL_SER_SKIP:
10923		return (CTL_ACTION_SKIP);
10924	default:
10925		panic("invalid serialization value %d",
10926		      serialize_row[pending_entry->seridx]);
10927	}
10928
10929	return (CTL_ACTION_ERROR);
10930}
10931
10932/*
10933 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10934 * Assumptions:
10935 * - pending_io is generally either incoming, or on the blocked queue
10936 * - starting I/O is the I/O we want to start the check with.
10937 */
10938static ctl_action
10939ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10940	      union ctl_io *starting_io)
10941{
10942	union ctl_io *ooa_io;
10943	ctl_action action;
10944
10945	mtx_assert(&lun->lun_lock, MA_OWNED);
10946
10947	/*
10948	 * Run back along the OOA queue, starting with the current
10949	 * blocked I/O and going through every I/O before it on the
10950	 * queue.  If starting_io is NULL, we'll just end up returning
10951	 * CTL_ACTION_PASS.
10952	 */
10953	for (ooa_io = starting_io; ooa_io != NULL;
10954	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10955	     ooa_links)){
10956
10957		/*
10958		 * This routine just checks to see whether
10959		 * cur_blocked is blocked by ooa_io, which is ahead
10960		 * of it in the queue.  It doesn't queue/dequeue
10961		 * cur_blocked.
10962		 */
10963		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10964		switch (action) {
10965		case CTL_ACTION_BLOCK:
10966		case CTL_ACTION_OVERLAP:
10967		case CTL_ACTION_OVERLAP_TAG:
10968		case CTL_ACTION_SKIP:
10969		case CTL_ACTION_ERROR:
10970			return (action);
10971			break; /* NOTREACHED */
10972		case CTL_ACTION_PASS:
10973			break;
10974		default:
10975			panic("invalid action %d", action);
10976			break;  /* NOTREACHED */
10977		}
10978	}
10979
10980	return (CTL_ACTION_PASS);
10981}
10982
10983/*
10984 * Assumptions:
10985 * - An I/O has just completed, and has been removed from the per-LUN OOA
10986 *   queue, so some items on the blocked queue may now be unblocked.
10987 */
10988static int
10989ctl_check_blocked(struct ctl_lun *lun)
10990{
10991	union ctl_io *cur_blocked, *next_blocked;
10992
10993	mtx_assert(&lun->lun_lock, MA_OWNED);
10994
10995	/*
10996	 * Run forward from the head of the blocked queue, checking each
10997	 * entry against the I/Os prior to it on the OOA queue to see if
10998	 * there is still any blockage.
10999	 *
11000	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11001	 * with our removing a variable on it while it is traversing the
11002	 * list.
11003	 */
11004	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11005	     cur_blocked != NULL; cur_blocked = next_blocked) {
11006		union ctl_io *prev_ooa;
11007		ctl_action action;
11008
11009		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11010							  blocked_links);
11011
11012		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11013						      ctl_ooaq, ooa_links);
11014
11015		/*
11016		 * If cur_blocked happens to be the first item in the OOA
11017		 * queue now, prev_ooa will be NULL, and the action
11018		 * returned will just be CTL_ACTION_PASS.
11019		 */
11020		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11021
11022		switch (action) {
11023		case CTL_ACTION_BLOCK:
11024			/* Nothing to do here, still blocked */
11025			break;
11026		case CTL_ACTION_OVERLAP:
11027		case CTL_ACTION_OVERLAP_TAG:
11028			/*
11029			 * This shouldn't happen!  In theory we've already
11030			 * checked this command for overlap...
11031			 */
11032			break;
11033		case CTL_ACTION_PASS:
11034		case CTL_ACTION_SKIP: {
11035			struct ctl_softc *softc;
11036			const struct ctl_cmd_entry *entry;
11037			int isc_retval;
11038
11039			/*
11040			 * The skip case shouldn't happen, this transaction
11041			 * should have never made it onto the blocked queue.
11042			 */
11043			/*
11044			 * This I/O is no longer blocked, we can remove it
11045			 * from the blocked queue.  Since this is a TAILQ
11046			 * (doubly linked list), we can do O(1) removals
11047			 * from any place on the list.
11048			 */
11049			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11050				     blocked_links);
11051			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11052
11053			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11054				/*
11055				 * Need to send IO back to original side to
11056				 * run
11057				 */
11058				union ctl_ha_msg msg_info;
11059
11060				msg_info.hdr.original_sc =
11061					cur_blocked->io_hdr.original_sc;
11062				msg_info.hdr.serializing_sc = cur_blocked;
11063				msg_info.hdr.msg_type = CTL_MSG_R2R;
11064				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11065				     &msg_info, sizeof(msg_info), 0)) >
11066				     CTL_HA_STATUS_SUCCESS) {
11067					printf("CTL:Check Blocked error from "
11068					       "ctl_ha_msg_send %d\n",
11069					       isc_retval);
11070				}
11071				break;
11072			}
11073			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11074			softc = control_softc;
11075
11076			/*
11077			 * Check this I/O for LUN state changes that may
11078			 * have happened while this command was blocked.
11079			 * The LUN state may have been changed by a command
11080			 * ahead of us in the queue, so we need to re-check
11081			 * for any states that can be caused by SCSI
11082			 * commands.
11083			 */
11084			if (ctl_scsiio_lun_check(softc, lun, entry,
11085						 &cur_blocked->scsiio) == 0) {
11086				cur_blocked->io_hdr.flags |=
11087				                      CTL_FLAG_IS_WAS_ON_RTR;
11088				ctl_enqueue_rtr(cur_blocked);
11089			} else
11090				ctl_done(cur_blocked);
11091			break;
11092		}
11093		default:
11094			/*
11095			 * This probably shouldn't happen -- we shouldn't
11096			 * get CTL_ACTION_ERROR, or anything else.
11097			 */
11098			break;
11099		}
11100	}
11101
11102	return (CTL_RETVAL_COMPLETE);
11103}
11104
11105/*
11106 * This routine (with one exception) checks LUN flags that can be set by
11107 * commands ahead of us in the OOA queue.  These flags have to be checked
11108 * when a command initially comes in, and when we pull a command off the
11109 * blocked queue and are preparing to execute it.  The reason we have to
11110 * check these flags for commands on the blocked queue is that the LUN
11111 * state may have been changed by a command ahead of us while we're on the
11112 * blocked queue.
11113 *
11114 * Ordering is somewhat important with these checks, so please pay
11115 * careful attention to the placement of any new checks.
11116 */
11117static int
11118ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11119    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11120{
11121	int retval;
11122	uint32_t residx;
11123
11124	retval = 0;
11125
11126	mtx_assert(&lun->lun_lock, MA_OWNED);
11127
11128	/*
11129	 * If this shelf is a secondary shelf controller, we have to reject
11130	 * any media access commands.
11131	 */
11132	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11133	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11134		ctl_set_lun_standby(ctsio);
11135		retval = 1;
11136		goto bailout;
11137	}
11138
11139	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11140		if (lun->flags & CTL_LUN_READONLY) {
11141			ctl_set_sense(ctsio, /*current_error*/ 1,
11142			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11143			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11144			retval = 1;
11145			goto bailout;
11146		}
11147		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11148		    .eca_and_aen & SCP_SWP) != 0) {
11149			ctl_set_sense(ctsio, /*current_error*/ 1,
11150			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11151			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11152			retval = 1;
11153			goto bailout;
11154		}
11155	}
11156
11157	/*
11158	 * Check for a reservation conflict.  If this command isn't allowed
11159	 * even on reserved LUNs, and if this initiator isn't the one who
11160	 * reserved us, reject the command with a reservation conflict.
11161	 */
11162	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11163	if ((lun->flags & CTL_LUN_RESERVED)
11164	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11165		if (lun->res_idx != residx) {
11166			ctl_set_reservation_conflict(ctsio);
11167			retval = 1;
11168			goto bailout;
11169		}
11170	}
11171
11172	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11173	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11174		/* No reservation or command is allowed. */;
11175	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11176	    (lun->res_type == SPR_TYPE_WR_EX ||
11177	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11178	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11179		/* The command is allowed for Write Exclusive resv. */;
11180	} else {
11181		/*
11182		 * if we aren't registered or it's a res holder type
11183		 * reservation and this isn't the res holder then set a
11184		 * conflict.
11185		 */
11186		if (ctl_get_prkey(lun, residx) == 0
11187		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11188			ctl_set_reservation_conflict(ctsio);
11189			retval = 1;
11190			goto bailout;
11191		}
11192
11193	}
11194
11195	if ((lun->flags & CTL_LUN_OFFLINE)
11196	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11197		ctl_set_lun_not_ready(ctsio);
11198		retval = 1;
11199		goto bailout;
11200	}
11201
11202	/*
11203	 * If the LUN is stopped, see if this particular command is allowed
11204	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11205	 */
11206	if ((lun->flags & CTL_LUN_STOPPED)
11207	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11208		/* "Logical unit not ready, initializing cmd. required" */
11209		ctl_set_lun_stopped(ctsio);
11210		retval = 1;
11211		goto bailout;
11212	}
11213
11214	if ((lun->flags & CTL_LUN_INOPERABLE)
11215	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11216		/* "Medium format corrupted" */
11217		ctl_set_medium_format_corrupted(ctsio);
11218		retval = 1;
11219		goto bailout;
11220	}
11221
11222bailout:
11223	return (retval);
11224
11225}
11226
11227static void
11228ctl_failover_io(union ctl_io *io, int have_lock)
11229{
11230	ctl_set_busy(&io->scsiio);
11231	ctl_done(io);
11232}
11233
11234static void
11235ctl_failover(void)
11236{
11237	struct ctl_lun *lun;
11238	struct ctl_softc *ctl_softc;
11239	union ctl_io *next_io, *pending_io;
11240	union ctl_io *io;
11241	int lun_idx;
11242
11243	ctl_softc = control_softc;
11244
11245	mtx_lock(&ctl_softc->ctl_lock);
11246	/*
11247	 * Remove any cmds from the other SC from the rtr queue.  These
11248	 * will obviously only be for LUNs for which we're the primary.
11249	 * We can't send status or get/send data for these commands.
11250	 * Since they haven't been executed yet, we can just remove them.
11251	 * We'll either abort them or delete them below, depending on
11252	 * which HA mode we're in.
11253	 */
11254#ifdef notyet
11255	mtx_lock(&ctl_softc->queue_lock);
11256	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11257	     io != NULL; io = next_io) {
11258		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11259		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11260			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11261				      ctl_io_hdr, links);
11262	}
11263	mtx_unlock(&ctl_softc->queue_lock);
11264#endif
11265
11266	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11267		lun = ctl_softc->ctl_luns[lun_idx];
11268		if (lun==NULL)
11269			continue;
11270
11271		/*
11272		 * Processor LUNs are primary on both sides.
11273		 * XXX will this always be true?
11274		 */
11275		if (lun->be_lun->lun_type == T_PROCESSOR)
11276			continue;
11277
11278		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11279		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11280			printf("FAILOVER: primary lun %d\n", lun_idx);
11281		        /*
11282			 * Remove all commands from the other SC. First from the
11283			 * blocked queue then from the ooa queue. Once we have
11284			 * removed them. Call ctl_check_blocked to see if there
11285			 * is anything that can run.
11286			 */
11287			for (io = (union ctl_io *)TAILQ_FIRST(
11288			     &lun->blocked_queue); io != NULL; io = next_io) {
11289
11290		        	next_io = (union ctl_io *)TAILQ_NEXT(
11291				    &io->io_hdr, blocked_links);
11292
11293				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11294					TAILQ_REMOVE(&lun->blocked_queue,
11295						     &io->io_hdr,blocked_links);
11296					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11297					TAILQ_REMOVE(&lun->ooa_queue,
11298						     &io->io_hdr, ooa_links);
11299
11300					ctl_free_io(io);
11301				}
11302			}
11303
11304			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11305	     		     io != NULL; io = next_io) {
11306
11307		        	next_io = (union ctl_io *)TAILQ_NEXT(
11308				    &io->io_hdr, ooa_links);
11309
11310				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11311
11312					TAILQ_REMOVE(&lun->ooa_queue,
11313						&io->io_hdr,
11314					     	ooa_links);
11315
11316					ctl_free_io(io);
11317				}
11318			}
11319			ctl_check_blocked(lun);
11320		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11321			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11322
11323			printf("FAILOVER: primary lun %d\n", lun_idx);
11324			/*
11325			 * Abort all commands from the other SC.  We can't
11326			 * send status back for them now.  These should get
11327			 * cleaned up when they are completed or come out
11328			 * for a datamove operation.
11329			 */
11330			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11331	     		     io != NULL; io = next_io) {
11332		        	next_io = (union ctl_io *)TAILQ_NEXT(
11333					&io->io_hdr, ooa_links);
11334
11335				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11336					io->io_hdr.flags |= CTL_FLAG_ABORT;
11337			}
11338		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11339			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11340
11341			printf("FAILOVER: secondary lun %d\n", lun_idx);
11342
11343			lun->flags |= CTL_LUN_PRIMARY_SC;
11344
11345			/*
11346			 * We send all I/O that was sent to this controller
11347			 * and redirected to the other side back with
11348			 * busy status, and have the initiator retry it.
11349			 * Figuring out how much data has been transferred,
11350			 * etc. and picking up where we left off would be
11351			 * very tricky.
11352			 *
11353			 * XXX KDM need to remove I/O from the blocked
11354			 * queue as well!
11355			 */
11356			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11357			     &lun->ooa_queue); pending_io != NULL;
11358			     pending_io = next_io) {
11359
11360				next_io =  (union ctl_io *)TAILQ_NEXT(
11361					&pending_io->io_hdr, ooa_links);
11362
11363				pending_io->io_hdr.flags &=
11364					~CTL_FLAG_SENT_2OTHER_SC;
11365
11366				if (pending_io->io_hdr.flags &
11367				    CTL_FLAG_IO_ACTIVE) {
11368					pending_io->io_hdr.flags |=
11369						CTL_FLAG_FAILOVER;
11370				} else {
11371					ctl_set_busy(&pending_io->scsiio);
11372					ctl_done(pending_io);
11373				}
11374			}
11375
11376			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11377		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11378			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11379			printf("FAILOVER: secondary lun %d\n", lun_idx);
11380			/*
11381			 * if the first io on the OOA is not on the RtR queue
11382			 * add it.
11383			 */
11384			lun->flags |= CTL_LUN_PRIMARY_SC;
11385
11386			pending_io = (union ctl_io *)TAILQ_FIRST(
11387			    &lun->ooa_queue);
11388			if (pending_io==NULL) {
11389				printf("Nothing on OOA queue\n");
11390				continue;
11391			}
11392
11393			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11394			if ((pending_io->io_hdr.flags &
11395			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11396				pending_io->io_hdr.flags |=
11397				    CTL_FLAG_IS_WAS_ON_RTR;
11398				ctl_enqueue_rtr(pending_io);
11399			}
11400#if 0
11401			else
11402			{
11403				printf("Tag 0x%04x is running\n",
11404				      pending_io->scsiio.tag_num);
11405			}
11406#endif
11407
11408			next_io = (union ctl_io *)TAILQ_NEXT(
11409			    &pending_io->io_hdr, ooa_links);
11410			for (pending_io=next_io; pending_io != NULL;
11411			     pending_io = next_io) {
11412				pending_io->io_hdr.flags &=
11413				    ~CTL_FLAG_SENT_2OTHER_SC;
11414				next_io = (union ctl_io *)TAILQ_NEXT(
11415					&pending_io->io_hdr, ooa_links);
11416				if (pending_io->io_hdr.flags &
11417				    CTL_FLAG_IS_WAS_ON_RTR) {
11418#if 0
11419				        printf("Tag 0x%04x is running\n",
11420				      		pending_io->scsiio.tag_num);
11421#endif
11422					continue;
11423				}
11424
11425				switch (ctl_check_ooa(lun, pending_io,
11426			            (union ctl_io *)TAILQ_PREV(
11427				    &pending_io->io_hdr, ctl_ooaq,
11428				    ooa_links))) {
11429
11430				case CTL_ACTION_BLOCK:
11431					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11432							  &pending_io->io_hdr,
11433							  blocked_links);
11434					pending_io->io_hdr.flags |=
11435					    CTL_FLAG_BLOCKED;
11436					break;
11437				case CTL_ACTION_PASS:
11438				case CTL_ACTION_SKIP:
11439					pending_io->io_hdr.flags |=
11440					    CTL_FLAG_IS_WAS_ON_RTR;
11441					ctl_enqueue_rtr(pending_io);
11442					break;
11443				case CTL_ACTION_OVERLAP:
11444					ctl_set_overlapped_cmd(
11445					    (struct ctl_scsiio *)pending_io);
11446					ctl_done(pending_io);
11447					break;
11448				case CTL_ACTION_OVERLAP_TAG:
11449					ctl_set_overlapped_tag(
11450					    (struct ctl_scsiio *)pending_io,
11451					    pending_io->scsiio.tag_num & 0xff);
11452					ctl_done(pending_io);
11453					break;
11454				case CTL_ACTION_ERROR:
11455				default:
11456					ctl_set_internal_failure(
11457						(struct ctl_scsiio *)pending_io,
11458						0,  // sks_valid
11459						0); //retry count
11460					ctl_done(pending_io);
11461					break;
11462				}
11463			}
11464
11465			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11466		} else {
11467			panic("Unhandled HA mode failover, LUN flags = %#x, "
11468			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11469		}
11470	}
11471	ctl_pause_rtr = 0;
11472	mtx_unlock(&ctl_softc->ctl_lock);
11473}
11474
11475static int
11476ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11477{
11478	struct ctl_lun *lun;
11479	const struct ctl_cmd_entry *entry;
11480	uint32_t initidx, targ_lun;
11481	int retval;
11482
11483	retval = 0;
11484
11485	lun = NULL;
11486
11487	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11488	if ((targ_lun < CTL_MAX_LUNS)
11489	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11490		/*
11491		 * If the LUN is invalid, pretend that it doesn't exist.
11492		 * It will go away as soon as all pending I/O has been
11493		 * completed.
11494		 */
11495		mtx_lock(&lun->lun_lock);
11496		if (lun->flags & CTL_LUN_DISABLED) {
11497			mtx_unlock(&lun->lun_lock);
11498			lun = NULL;
11499			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11500			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11501		} else {
11502			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11503			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11504				lun->be_lun;
11505			if (lun->be_lun->lun_type == T_PROCESSOR) {
11506				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11507			}
11508
11509			/*
11510			 * Every I/O goes into the OOA queue for a
11511			 * particular LUN, and stays there until completion.
11512			 */
11513			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11514			    ooa_links);
11515		}
11516	} else {
11517		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11518		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11519	}
11520
11521	/* Get command entry and return error if it is unsuppotyed. */
11522	entry = ctl_validate_command(ctsio);
11523	if (entry == NULL) {
11524		if (lun)
11525			mtx_unlock(&lun->lun_lock);
11526		return (retval);
11527	}
11528
11529	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11530	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11531
11532	/*
11533	 * Check to see whether we can send this command to LUNs that don't
11534	 * exist.  This should pretty much only be the case for inquiry
11535	 * and request sense.  Further checks, below, really require having
11536	 * a LUN, so we can't really check the command anymore.  Just put
11537	 * it on the rtr queue.
11538	 */
11539	if (lun == NULL) {
11540		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11541			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11542			ctl_enqueue_rtr((union ctl_io *)ctsio);
11543			return (retval);
11544		}
11545
11546		ctl_set_unsupported_lun(ctsio);
11547		ctl_done((union ctl_io *)ctsio);
11548		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11549		return (retval);
11550	} else {
11551		/*
11552		 * Make sure we support this particular command on this LUN.
11553		 * e.g., we don't support writes to the control LUN.
11554		 */
11555		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11556			mtx_unlock(&lun->lun_lock);
11557			ctl_set_invalid_opcode(ctsio);
11558			ctl_done((union ctl_io *)ctsio);
11559			return (retval);
11560		}
11561	}
11562
11563	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11564
11565#ifdef CTL_WITH_CA
11566	/*
11567	 * If we've got a request sense, it'll clear the contingent
11568	 * allegiance condition.  Otherwise, if we have a CA condition for
11569	 * this initiator, clear it, because it sent down a command other
11570	 * than request sense.
11571	 */
11572	if ((ctsio->cdb[0] != REQUEST_SENSE)
11573	 && (ctl_is_set(lun->have_ca, initidx)))
11574		ctl_clear_mask(lun->have_ca, initidx);
11575#endif
11576
11577	/*
11578	 * If the command has this flag set, it handles its own unit
11579	 * attention reporting, we shouldn't do anything.  Otherwise we
11580	 * check for any pending unit attentions, and send them back to the
11581	 * initiator.  We only do this when a command initially comes in,
11582	 * not when we pull it off the blocked queue.
11583	 *
11584	 * According to SAM-3, section 5.3.2, the order that things get
11585	 * presented back to the host is basically unit attentions caused
11586	 * by some sort of reset event, busy status, reservation conflicts
11587	 * or task set full, and finally any other status.
11588	 *
11589	 * One issue here is that some of the unit attentions we report
11590	 * don't fall into the "reset" category (e.g. "reported luns data
11591	 * has changed").  So reporting it here, before the reservation
11592	 * check, may be technically wrong.  I guess the only thing to do
11593	 * would be to check for and report the reset events here, and then
11594	 * check for the other unit attention types after we check for a
11595	 * reservation conflict.
11596	 *
11597	 * XXX KDM need to fix this
11598	 */
11599	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11600		ctl_ua_type ua_type;
11601		scsi_sense_data_type sense_format;
11602
11603		if (lun->flags & CTL_LUN_SENSE_DESC)
11604			sense_format = SSD_TYPE_DESC;
11605		else
11606			sense_format = SSD_TYPE_FIXED;
11607
11608		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11609		    sense_format);
11610		if (ua_type != CTL_UA_NONE) {
11611			mtx_unlock(&lun->lun_lock);
11612			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11613			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11614			ctsio->sense_len = SSD_FULL_SIZE;
11615			ctl_done((union ctl_io *)ctsio);
11616			return (retval);
11617		}
11618	}
11619
11620
11621	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11622		mtx_unlock(&lun->lun_lock);
11623		ctl_done((union ctl_io *)ctsio);
11624		return (retval);
11625	}
11626
11627	/*
11628	 * XXX CHD this is where we want to send IO to other side if
11629	 * this LUN is secondary on this SC. We will need to make a copy
11630	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11631	 * the copy we send as FROM_OTHER.
11632	 * We also need to stuff the address of the original IO so we can
11633	 * find it easily. Something similar will need be done on the other
11634	 * side so when we are done we can find the copy.
11635	 */
11636	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11637		union ctl_ha_msg msg_info;
11638		int isc_retval;
11639
11640		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11641
11642		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11643		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11644#if 0
11645		printf("1. ctsio %p\n", ctsio);
11646#endif
11647		msg_info.hdr.serializing_sc = NULL;
11648		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11649		msg_info.scsi.tag_num = ctsio->tag_num;
11650		msg_info.scsi.tag_type = ctsio->tag_type;
11651		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11652
11653		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11654
11655		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11656		    (void *)&msg_info, sizeof(msg_info), 0)) >
11657		    CTL_HA_STATUS_SUCCESS) {
11658			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11659			       isc_retval);
11660			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11661		} else {
11662#if 0
11663			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11664#endif
11665		}
11666
11667		/*
11668		 * XXX KDM this I/O is off the incoming queue, but hasn't
11669		 * been inserted on any other queue.  We may need to come
11670		 * up with a holding queue while we wait for serialization
11671		 * so that we have an idea of what we're waiting for from
11672		 * the other side.
11673		 */
11674		mtx_unlock(&lun->lun_lock);
11675		return (retval);
11676	}
11677
11678	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11679			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11680			      ctl_ooaq, ooa_links))) {
11681	case CTL_ACTION_BLOCK:
11682		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11683		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11684				  blocked_links);
11685		mtx_unlock(&lun->lun_lock);
11686		return (retval);
11687	case CTL_ACTION_PASS:
11688	case CTL_ACTION_SKIP:
11689		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11690		mtx_unlock(&lun->lun_lock);
11691		ctl_enqueue_rtr((union ctl_io *)ctsio);
11692		break;
11693	case CTL_ACTION_OVERLAP:
11694		mtx_unlock(&lun->lun_lock);
11695		ctl_set_overlapped_cmd(ctsio);
11696		ctl_done((union ctl_io *)ctsio);
11697		break;
11698	case CTL_ACTION_OVERLAP_TAG:
11699		mtx_unlock(&lun->lun_lock);
11700		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11701		ctl_done((union ctl_io *)ctsio);
11702		break;
11703	case CTL_ACTION_ERROR:
11704	default:
11705		mtx_unlock(&lun->lun_lock);
11706		ctl_set_internal_failure(ctsio,
11707					 /*sks_valid*/ 0,
11708					 /*retry_count*/ 0);
11709		ctl_done((union ctl_io *)ctsio);
11710		break;
11711	}
11712	return (retval);
11713}
11714
11715const struct ctl_cmd_entry *
11716ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11717{
11718	const struct ctl_cmd_entry *entry;
11719	int service_action;
11720
11721	entry = &ctl_cmd_table[ctsio->cdb[0]];
11722	if (sa)
11723		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11724	if (entry->flags & CTL_CMD_FLAG_SA5) {
11725		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11726		entry = &((const struct ctl_cmd_entry *)
11727		    entry->execute)[service_action];
11728	}
11729	return (entry);
11730}
11731
11732const struct ctl_cmd_entry *
11733ctl_validate_command(struct ctl_scsiio *ctsio)
11734{
11735	const struct ctl_cmd_entry *entry;
11736	int i, sa;
11737	uint8_t diff;
11738
11739	entry = ctl_get_cmd_entry(ctsio, &sa);
11740	if (entry->execute == NULL) {
11741		if (sa)
11742			ctl_set_invalid_field(ctsio,
11743					      /*sks_valid*/ 1,
11744					      /*command*/ 1,
11745					      /*field*/ 1,
11746					      /*bit_valid*/ 1,
11747					      /*bit*/ 4);
11748		else
11749			ctl_set_invalid_opcode(ctsio);
11750		ctl_done((union ctl_io *)ctsio);
11751		return (NULL);
11752	}
11753	KASSERT(entry->length > 0,
11754	    ("Not defined length for command 0x%02x/0x%02x",
11755	     ctsio->cdb[0], ctsio->cdb[1]));
11756	for (i = 1; i < entry->length; i++) {
11757		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11758		if (diff == 0)
11759			continue;
11760		ctl_set_invalid_field(ctsio,
11761				      /*sks_valid*/ 1,
11762				      /*command*/ 1,
11763				      /*field*/ i,
11764				      /*bit_valid*/ 1,
11765				      /*bit*/ fls(diff) - 1);
11766		ctl_done((union ctl_io *)ctsio);
11767		return (NULL);
11768	}
11769	return (entry);
11770}
11771
11772static int
11773ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11774{
11775
11776	switch (lun_type) {
11777	case T_PROCESSOR:
11778		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11779		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11780			return (0);
11781		break;
11782	case T_DIRECT:
11783		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11784		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11785			return (0);
11786		break;
11787	default:
11788		return (0);
11789	}
11790	return (1);
11791}
11792
11793static int
11794ctl_scsiio(struct ctl_scsiio *ctsio)
11795{
11796	int retval;
11797	const struct ctl_cmd_entry *entry;
11798
11799	retval = CTL_RETVAL_COMPLETE;
11800
11801	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11802
11803	entry = ctl_get_cmd_entry(ctsio, NULL);
11804
11805	/*
11806	 * If this I/O has been aborted, just send it straight to
11807	 * ctl_done() without executing it.
11808	 */
11809	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11810		ctl_done((union ctl_io *)ctsio);
11811		goto bailout;
11812	}
11813
11814	/*
11815	 * All the checks should have been handled by ctl_scsiio_precheck().
11816	 * We should be clear now to just execute the I/O.
11817	 */
11818	retval = entry->execute(ctsio);
11819
11820bailout:
11821	return (retval);
11822}
11823
11824/*
11825 * Since we only implement one target right now, a bus reset simply resets
11826 * our single target.
11827 */
11828static int
11829ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11830{
11831	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11832}
11833
11834static int
11835ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11836		 ctl_ua_type ua_type)
11837{
11838	struct ctl_lun *lun;
11839	int retval;
11840
11841	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11842		union ctl_ha_msg msg_info;
11843
11844		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11845		msg_info.hdr.nexus = io->io_hdr.nexus;
11846		if (ua_type==CTL_UA_TARG_RESET)
11847			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11848		else
11849			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11850		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11851		msg_info.hdr.original_sc = NULL;
11852		msg_info.hdr.serializing_sc = NULL;
11853		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11854		    (void *)&msg_info, sizeof(msg_info), 0)) {
11855		}
11856	}
11857	retval = 0;
11858
11859	mtx_lock(&ctl_softc->ctl_lock);
11860	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11861		retval += ctl_lun_reset(lun, io, ua_type);
11862	mtx_unlock(&ctl_softc->ctl_lock);
11863
11864	return (retval);
11865}
11866
11867/*
11868 * The LUN should always be set.  The I/O is optional, and is used to
11869 * distinguish between I/Os sent by this initiator, and by other
11870 * initiators.  We set unit attention for initiators other than this one.
11871 * SAM-3 is vague on this point.  It does say that a unit attention should
11872 * be established for other initiators when a LUN is reset (see section
11873 * 5.7.3), but it doesn't specifically say that the unit attention should
11874 * be established for this particular initiator when a LUN is reset.  Here
11875 * is the relevant text, from SAM-3 rev 8:
11876 *
11877 * 5.7.2 When a SCSI initiator port aborts its own tasks
11878 *
11879 * When a SCSI initiator port causes its own task(s) to be aborted, no
11880 * notification that the task(s) have been aborted shall be returned to
11881 * the SCSI initiator port other than the completion response for the
11882 * command or task management function action that caused the task(s) to
11883 * be aborted and notification(s) associated with related effects of the
11884 * action (e.g., a reset unit attention condition).
11885 *
11886 * XXX KDM for now, we're setting unit attention for all initiators.
11887 */
11888static int
11889ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11890{
11891	union ctl_io *xio;
11892#if 0
11893	uint32_t initidx;
11894#endif
11895#ifdef CTL_WITH_CA
11896	int i;
11897#endif
11898
11899	mtx_lock(&lun->lun_lock);
11900	/*
11901	 * Run through the OOA queue and abort each I/O.
11902	 */
11903#if 0
11904	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11905#endif
11906	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11907	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11908		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11909	}
11910
11911	/*
11912	 * This version sets unit attention for every
11913	 */
11914#if 0
11915	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11916	ctl_est_ua_all(lun, initidx, ua_type);
11917#else
11918	ctl_est_ua_all(lun, -1, ua_type);
11919#endif
11920
11921	/*
11922	 * A reset (any kind, really) clears reservations established with
11923	 * RESERVE/RELEASE.  It does not clear reservations established
11924	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11925	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11926	 * reservations made with the RESERVE/RELEASE commands, because
11927	 * those commands are obsolete in SPC-3.
11928	 */
11929	lun->flags &= ~CTL_LUN_RESERVED;
11930
11931#ifdef CTL_WITH_CA
11932	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11933		ctl_clear_mask(lun->have_ca, i);
11934#endif
11935	mtx_unlock(&lun->lun_lock);
11936
11937	return (0);
11938}
11939
11940static void
11941ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11942    int other_sc)
11943{
11944	union ctl_io *xio;
11945
11946	mtx_assert(&lun->lun_lock, MA_OWNED);
11947
11948	/*
11949	 * Run through the OOA queue and attempt to find the given I/O.
11950	 * The target port, initiator ID, tag type and tag number have to
11951	 * match the values that we got from the initiator.  If we have an
11952	 * untagged command to abort, simply abort the first untagged command
11953	 * we come to.  We only allow one untagged command at a time of course.
11954	 */
11955	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11956	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11957
11958		if ((targ_port == UINT32_MAX ||
11959		     targ_port == xio->io_hdr.nexus.targ_port) &&
11960		    (init_id == UINT32_MAX ||
11961		     init_id == xio->io_hdr.nexus.initid.id)) {
11962			if (targ_port != xio->io_hdr.nexus.targ_port ||
11963			    init_id != xio->io_hdr.nexus.initid.id)
11964				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11965			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11966			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11967				union ctl_ha_msg msg_info;
11968
11969				msg_info.hdr.nexus = xio->io_hdr.nexus;
11970				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11971				msg_info.task.tag_num = xio->scsiio.tag_num;
11972				msg_info.task.tag_type = xio->scsiio.tag_type;
11973				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11974				msg_info.hdr.original_sc = NULL;
11975				msg_info.hdr.serializing_sc = NULL;
11976				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11977				    (void *)&msg_info, sizeof(msg_info), 0);
11978			}
11979		}
11980	}
11981}
11982
11983static int
11984ctl_abort_task_set(union ctl_io *io)
11985{
11986	struct ctl_softc *softc = control_softc;
11987	struct ctl_lun *lun;
11988	uint32_t targ_lun;
11989
11990	/*
11991	 * Look up the LUN.
11992	 */
11993	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11994	mtx_lock(&softc->ctl_lock);
11995	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11996		lun = softc->ctl_luns[targ_lun];
11997	else {
11998		mtx_unlock(&softc->ctl_lock);
11999		return (1);
12000	}
12001
12002	mtx_lock(&lun->lun_lock);
12003	mtx_unlock(&softc->ctl_lock);
12004	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12005		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12006		    io->io_hdr.nexus.initid.id,
12007		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12008	} else { /* CTL_TASK_CLEAR_TASK_SET */
12009		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12010		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12011	}
12012	mtx_unlock(&lun->lun_lock);
12013	return (0);
12014}
12015
12016static int
12017ctl_i_t_nexus_reset(union ctl_io *io)
12018{
12019	struct ctl_softc *softc = control_softc;
12020	struct ctl_lun *lun;
12021	uint32_t initidx, residx;
12022
12023	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12024	residx = ctl_get_resindex(&io->io_hdr.nexus);
12025	mtx_lock(&softc->ctl_lock);
12026	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12027		mtx_lock(&lun->lun_lock);
12028		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12029		    io->io_hdr.nexus.initid.id,
12030		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12031#ifdef CTL_WITH_CA
12032		ctl_clear_mask(lun->have_ca, initidx);
12033#endif
12034		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12035			lun->flags &= ~CTL_LUN_RESERVED;
12036		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12037		mtx_unlock(&lun->lun_lock);
12038	}
12039	mtx_unlock(&softc->ctl_lock);
12040	return (0);
12041}
12042
12043static int
12044ctl_abort_task(union ctl_io *io)
12045{
12046	union ctl_io *xio;
12047	struct ctl_lun *lun;
12048	struct ctl_softc *ctl_softc;
12049#if 0
12050	struct sbuf sb;
12051	char printbuf[128];
12052#endif
12053	int found;
12054	uint32_t targ_lun;
12055
12056	ctl_softc = control_softc;
12057	found = 0;
12058
12059	/*
12060	 * Look up the LUN.
12061	 */
12062	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12063	mtx_lock(&ctl_softc->ctl_lock);
12064	if ((targ_lun < CTL_MAX_LUNS)
12065	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12066		lun = ctl_softc->ctl_luns[targ_lun];
12067	else {
12068		mtx_unlock(&ctl_softc->ctl_lock);
12069		return (1);
12070	}
12071
12072#if 0
12073	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12074	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12075#endif
12076
12077	mtx_lock(&lun->lun_lock);
12078	mtx_unlock(&ctl_softc->ctl_lock);
12079	/*
12080	 * Run through the OOA queue and attempt to find the given I/O.
12081	 * The target port, initiator ID, tag type and tag number have to
12082	 * match the values that we got from the initiator.  If we have an
12083	 * untagged command to abort, simply abort the first untagged command
12084	 * we come to.  We only allow one untagged command at a time of course.
12085	 */
12086#if 0
12087	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12088#endif
12089	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12090	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12091#if 0
12092		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12093
12094		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12095			    lun->lun, xio->scsiio.tag_num,
12096			    xio->scsiio.tag_type,
12097			    (xio->io_hdr.blocked_links.tqe_prev
12098			    == NULL) ? "" : " BLOCKED",
12099			    (xio->io_hdr.flags &
12100			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12101			    (xio->io_hdr.flags &
12102			    CTL_FLAG_ABORT) ? " ABORT" : "",
12103			    (xio->io_hdr.flags &
12104			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12105		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12106		sbuf_finish(&sb);
12107		printf("%s\n", sbuf_data(&sb));
12108#endif
12109
12110		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12111		 && (xio->io_hdr.nexus.initid.id ==
12112		     io->io_hdr.nexus.initid.id)) {
12113			/*
12114			 * If the abort says that the task is untagged, the
12115			 * task in the queue must be untagged.  Otherwise,
12116			 * we just check to see whether the tag numbers
12117			 * match.  This is because the QLogic firmware
12118			 * doesn't pass back the tag type in an abort
12119			 * request.
12120			 */
12121#if 0
12122			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12123			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12124			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12125#endif
12126			/*
12127			 * XXX KDM we've got problems with FC, because it
12128			 * doesn't send down a tag type with aborts.  So we
12129			 * can only really go by the tag number...
12130			 * This may cause problems with parallel SCSI.
12131			 * Need to figure that out!!
12132			 */
12133			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12134				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12135				found = 1;
12136				if ((io->io_hdr.flags &
12137				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12138				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12139					union ctl_ha_msg msg_info;
12140
12141					io->io_hdr.flags |=
12142					                CTL_FLAG_SENT_2OTHER_SC;
12143					msg_info.hdr.nexus = io->io_hdr.nexus;
12144					msg_info.task.task_action =
12145						CTL_TASK_ABORT_TASK;
12146					msg_info.task.tag_num =
12147						io->taskio.tag_num;
12148					msg_info.task.tag_type =
12149						io->taskio.tag_type;
12150					msg_info.hdr.msg_type =
12151						CTL_MSG_MANAGE_TASKS;
12152					msg_info.hdr.original_sc = NULL;
12153					msg_info.hdr.serializing_sc = NULL;
12154#if 0
12155					printf("Sent Abort to other side\n");
12156#endif
12157					if (CTL_HA_STATUS_SUCCESS !=
12158					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12159		    				(void *)&msg_info,
12160						sizeof(msg_info), 0)) {
12161					}
12162				}
12163#if 0
12164				printf("ctl_abort_task: found I/O to abort\n");
12165#endif
12166				break;
12167			}
12168		}
12169	}
12170	mtx_unlock(&lun->lun_lock);
12171
12172	if (found == 0) {
12173		/*
12174		 * This isn't really an error.  It's entirely possible for
12175		 * the abort and command completion to cross on the wire.
12176		 * This is more of an informative/diagnostic error.
12177		 */
12178#if 0
12179		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12180		       "%d:%d:%d:%d tag %d type %d\n",
12181		       io->io_hdr.nexus.initid.id,
12182		       io->io_hdr.nexus.targ_port,
12183		       io->io_hdr.nexus.targ_target.id,
12184		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12185		       io->taskio.tag_type);
12186#endif
12187	}
12188	return (0);
12189}
12190
12191static void
12192ctl_run_task(union ctl_io *io)
12193{
12194	struct ctl_softc *ctl_softc = control_softc;
12195	int retval = 1;
12196	const char *task_desc;
12197
12198	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12199
12200	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12201	    ("ctl_run_task: Unextected io_type %d\n",
12202	     io->io_hdr.io_type));
12203
12204	task_desc = ctl_scsi_task_string(&io->taskio);
12205	if (task_desc != NULL) {
12206#ifdef NEEDTOPORT
12207		csevent_log(CSC_CTL | CSC_SHELF_SW |
12208			    CTL_TASK_REPORT,
12209			    csevent_LogType_Trace,
12210			    csevent_Severity_Information,
12211			    csevent_AlertLevel_Green,
12212			    csevent_FRU_Firmware,
12213			    csevent_FRU_Unknown,
12214			    "CTL: received task: %s",task_desc);
12215#endif
12216	} else {
12217#ifdef NEEDTOPORT
12218		csevent_log(CSC_CTL | CSC_SHELF_SW |
12219			    CTL_TASK_REPORT,
12220			    csevent_LogType_Trace,
12221			    csevent_Severity_Information,
12222			    csevent_AlertLevel_Green,
12223			    csevent_FRU_Firmware,
12224			    csevent_FRU_Unknown,
12225			    "CTL: received unknown task "
12226			    "type: %d (%#x)",
12227			    io->taskio.task_action,
12228			    io->taskio.task_action);
12229#endif
12230	}
12231	switch (io->taskio.task_action) {
12232	case CTL_TASK_ABORT_TASK:
12233		retval = ctl_abort_task(io);
12234		break;
12235	case CTL_TASK_ABORT_TASK_SET:
12236	case CTL_TASK_CLEAR_TASK_SET:
12237		retval = ctl_abort_task_set(io);
12238		break;
12239	case CTL_TASK_CLEAR_ACA:
12240		break;
12241	case CTL_TASK_I_T_NEXUS_RESET:
12242		retval = ctl_i_t_nexus_reset(io);
12243		break;
12244	case CTL_TASK_LUN_RESET: {
12245		struct ctl_lun *lun;
12246		uint32_t targ_lun;
12247
12248		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12249		mtx_lock(&ctl_softc->ctl_lock);
12250		if ((targ_lun < CTL_MAX_LUNS)
12251		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12252			lun = ctl_softc->ctl_luns[targ_lun];
12253		else {
12254			mtx_unlock(&ctl_softc->ctl_lock);
12255			retval = 1;
12256			break;
12257		}
12258
12259		if (!(io->io_hdr.flags &
12260		    CTL_FLAG_FROM_OTHER_SC)) {
12261			union ctl_ha_msg msg_info;
12262
12263			io->io_hdr.flags |=
12264				CTL_FLAG_SENT_2OTHER_SC;
12265			msg_info.hdr.msg_type =
12266				CTL_MSG_MANAGE_TASKS;
12267			msg_info.hdr.nexus = io->io_hdr.nexus;
12268			msg_info.task.task_action =
12269				CTL_TASK_LUN_RESET;
12270			msg_info.hdr.original_sc = NULL;
12271			msg_info.hdr.serializing_sc = NULL;
12272			if (CTL_HA_STATUS_SUCCESS !=
12273			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12274			    (void *)&msg_info,
12275			    sizeof(msg_info), 0)) {
12276			}
12277		}
12278
12279		retval = ctl_lun_reset(lun, io,
12280				       CTL_UA_LUN_RESET);
12281		mtx_unlock(&ctl_softc->ctl_lock);
12282		break;
12283	}
12284	case CTL_TASK_TARGET_RESET:
12285		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12286		break;
12287	case CTL_TASK_BUS_RESET:
12288		retval = ctl_bus_reset(ctl_softc, io);
12289		break;
12290	case CTL_TASK_PORT_LOGIN:
12291		break;
12292	case CTL_TASK_PORT_LOGOUT:
12293		break;
12294	default:
12295		printf("ctl_run_task: got unknown task management event %d\n",
12296		       io->taskio.task_action);
12297		break;
12298	}
12299	if (retval == 0)
12300		io->io_hdr.status = CTL_SUCCESS;
12301	else
12302		io->io_hdr.status = CTL_ERROR;
12303	ctl_done(io);
12304}
12305
12306/*
12307 * For HA operation.  Handle commands that come in from the other
12308 * controller.
12309 */
12310static void
12311ctl_handle_isc(union ctl_io *io)
12312{
12313	int free_io;
12314	struct ctl_lun *lun;
12315	struct ctl_softc *ctl_softc;
12316	uint32_t targ_lun;
12317
12318	ctl_softc = control_softc;
12319
12320	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12321	lun = ctl_softc->ctl_luns[targ_lun];
12322
12323	switch (io->io_hdr.msg_type) {
12324	case CTL_MSG_SERIALIZE:
12325		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12326		break;
12327	case CTL_MSG_R2R: {
12328		const struct ctl_cmd_entry *entry;
12329
12330		/*
12331		 * This is only used in SER_ONLY mode.
12332		 */
12333		free_io = 0;
12334		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12335		mtx_lock(&lun->lun_lock);
12336		if (ctl_scsiio_lun_check(ctl_softc, lun,
12337		    entry, (struct ctl_scsiio *)io) != 0) {
12338			mtx_unlock(&lun->lun_lock);
12339			ctl_done(io);
12340			break;
12341		}
12342		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12343		mtx_unlock(&lun->lun_lock);
12344		ctl_enqueue_rtr(io);
12345		break;
12346	}
12347	case CTL_MSG_FINISH_IO:
12348		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12349			free_io = 0;
12350			ctl_done(io);
12351		} else {
12352			free_io = 1;
12353			mtx_lock(&lun->lun_lock);
12354			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12355				     ooa_links);
12356			ctl_check_blocked(lun);
12357			mtx_unlock(&lun->lun_lock);
12358		}
12359		break;
12360	case CTL_MSG_PERS_ACTION:
12361		ctl_hndl_per_res_out_on_other_sc(
12362			(union ctl_ha_msg *)&io->presio.pr_msg);
12363		free_io = 1;
12364		break;
12365	case CTL_MSG_BAD_JUJU:
12366		free_io = 0;
12367		ctl_done(io);
12368		break;
12369	case CTL_MSG_DATAMOVE:
12370		/* Only used in XFER mode */
12371		free_io = 0;
12372		ctl_datamove_remote(io);
12373		break;
12374	case CTL_MSG_DATAMOVE_DONE:
12375		/* Only used in XFER mode */
12376		free_io = 0;
12377		io->scsiio.be_move_done(io);
12378		break;
12379	default:
12380		free_io = 1;
12381		printf("%s: Invalid message type %d\n",
12382		       __func__, io->io_hdr.msg_type);
12383		break;
12384	}
12385	if (free_io)
12386		ctl_free_io(io);
12387
12388}
12389
12390
12391/*
12392 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12393 * there is no match.
12394 */
12395static ctl_lun_error_pattern
12396ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12397{
12398	const struct ctl_cmd_entry *entry;
12399	ctl_lun_error_pattern filtered_pattern, pattern;
12400
12401	pattern = desc->error_pattern;
12402
12403	/*
12404	 * XXX KDM we need more data passed into this function to match a
12405	 * custom pattern, and we actually need to implement custom pattern
12406	 * matching.
12407	 */
12408	if (pattern & CTL_LUN_PAT_CMD)
12409		return (CTL_LUN_PAT_CMD);
12410
12411	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12412		return (CTL_LUN_PAT_ANY);
12413
12414	entry = ctl_get_cmd_entry(ctsio, NULL);
12415
12416	filtered_pattern = entry->pattern & pattern;
12417
12418	/*
12419	 * If the user requested specific flags in the pattern (e.g.
12420	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12421	 * flags.
12422	 *
12423	 * If the user did not specify any flags, it doesn't matter whether
12424	 * or not the command supports the flags.
12425	 */
12426	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12427	     (pattern & ~CTL_LUN_PAT_MASK))
12428		return (CTL_LUN_PAT_NONE);
12429
12430	/*
12431	 * If the user asked for a range check, see if the requested LBA
12432	 * range overlaps with this command's LBA range.
12433	 */
12434	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12435		uint64_t lba1;
12436		uint64_t len1;
12437		ctl_action action;
12438		int retval;
12439
12440		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12441		if (retval != 0)
12442			return (CTL_LUN_PAT_NONE);
12443
12444		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12445					      desc->lba_range.len);
12446		/*
12447		 * A "pass" means that the LBA ranges don't overlap, so
12448		 * this doesn't match the user's range criteria.
12449		 */
12450		if (action == CTL_ACTION_PASS)
12451			return (CTL_LUN_PAT_NONE);
12452	}
12453
12454	return (filtered_pattern);
12455}
12456
12457static void
12458ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12459{
12460	struct ctl_error_desc *desc, *desc2;
12461
12462	mtx_assert(&lun->lun_lock, MA_OWNED);
12463
12464	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12465		ctl_lun_error_pattern pattern;
12466		/*
12467		 * Check to see whether this particular command matches
12468		 * the pattern in the descriptor.
12469		 */
12470		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12471		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12472			continue;
12473
12474		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12475		case CTL_LUN_INJ_ABORTED:
12476			ctl_set_aborted(&io->scsiio);
12477			break;
12478		case CTL_LUN_INJ_MEDIUM_ERR:
12479			ctl_set_medium_error(&io->scsiio);
12480			break;
12481		case CTL_LUN_INJ_UA:
12482			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12483			 * OCCURRED */
12484			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12485			break;
12486		case CTL_LUN_INJ_CUSTOM:
12487			/*
12488			 * We're assuming the user knows what he is doing.
12489			 * Just copy the sense information without doing
12490			 * checks.
12491			 */
12492			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12493			      ctl_min(sizeof(desc->custom_sense),
12494				      sizeof(io->scsiio.sense_data)));
12495			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12496			io->scsiio.sense_len = SSD_FULL_SIZE;
12497			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12498			break;
12499		case CTL_LUN_INJ_NONE:
12500		default:
12501			/*
12502			 * If this is an error injection type we don't know
12503			 * about, clear the continuous flag (if it is set)
12504			 * so it will get deleted below.
12505			 */
12506			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12507			break;
12508		}
12509		/*
12510		 * By default, each error injection action is a one-shot
12511		 */
12512		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12513			continue;
12514
12515		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12516
12517		free(desc, M_CTL);
12518	}
12519}
12520
12521#ifdef CTL_IO_DELAY
12522static void
12523ctl_datamove_timer_wakeup(void *arg)
12524{
12525	union ctl_io *io;
12526
12527	io = (union ctl_io *)arg;
12528
12529	ctl_datamove(io);
12530}
12531#endif /* CTL_IO_DELAY */
12532
12533void
12534ctl_datamove(union ctl_io *io)
12535{
12536	void (*fe_datamove)(union ctl_io *io);
12537
12538	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12539
12540	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12541
12542#ifdef CTL_TIME_IO
12543	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12544		char str[256];
12545		char path_str[64];
12546		struct sbuf sb;
12547
12548		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12549		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12550
12551		sbuf_cat(&sb, path_str);
12552		switch (io->io_hdr.io_type) {
12553		case CTL_IO_SCSI:
12554			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12555			sbuf_printf(&sb, "\n");
12556			sbuf_cat(&sb, path_str);
12557			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12558				    io->scsiio.tag_num, io->scsiio.tag_type);
12559			break;
12560		case CTL_IO_TASK:
12561			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12562				    "Tag Type: %d\n", io->taskio.task_action,
12563				    io->taskio.tag_num, io->taskio.tag_type);
12564			break;
12565		default:
12566			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12567			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12568			break;
12569		}
12570		sbuf_cat(&sb, path_str);
12571		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12572			    (intmax_t)time_uptime - io->io_hdr.start_time);
12573		sbuf_finish(&sb);
12574		printf("%s", sbuf_data(&sb));
12575	}
12576#endif /* CTL_TIME_IO */
12577
12578#ifdef CTL_IO_DELAY
12579	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12580		struct ctl_lun *lun;
12581
12582		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12583
12584		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12585	} else {
12586		struct ctl_lun *lun;
12587
12588		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12589		if ((lun != NULL)
12590		 && (lun->delay_info.datamove_delay > 0)) {
12591			struct callout *callout;
12592
12593			callout = (struct callout *)&io->io_hdr.timer_bytes;
12594			callout_init(callout, /*mpsafe*/ 1);
12595			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12596			callout_reset(callout,
12597				      lun->delay_info.datamove_delay * hz,
12598				      ctl_datamove_timer_wakeup, io);
12599			if (lun->delay_info.datamove_type ==
12600			    CTL_DELAY_TYPE_ONESHOT)
12601				lun->delay_info.datamove_delay = 0;
12602			return;
12603		}
12604	}
12605#endif
12606
12607	/*
12608	 * This command has been aborted.  Set the port status, so we fail
12609	 * the data move.
12610	 */
12611	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12612		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12613		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12614		       io->io_hdr.nexus.targ_port,
12615		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12616		       io->io_hdr.nexus.targ_lun);
12617		io->io_hdr.port_status = 31337;
12618		/*
12619		 * Note that the backend, in this case, will get the
12620		 * callback in its context.  In other cases it may get
12621		 * called in the frontend's interrupt thread context.
12622		 */
12623		io->scsiio.be_move_done(io);
12624		return;
12625	}
12626
12627	/* Don't confuse frontend with zero length data move. */
12628	if (io->scsiio.kern_data_len == 0) {
12629		io->scsiio.be_move_done(io);
12630		return;
12631	}
12632
12633	/*
12634	 * If we're in XFER mode and this I/O is from the other shelf
12635	 * controller, we need to send the DMA to the other side to
12636	 * actually transfer the data to/from the host.  In serialize only
12637	 * mode the transfer happens below CTL and ctl_datamove() is only
12638	 * called on the machine that originally received the I/O.
12639	 */
12640	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12641	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12642		union ctl_ha_msg msg;
12643		uint32_t sg_entries_sent;
12644		int do_sg_copy;
12645		int i;
12646
12647		memset(&msg, 0, sizeof(msg));
12648		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12649		msg.hdr.original_sc = io->io_hdr.original_sc;
12650		msg.hdr.serializing_sc = io;
12651		msg.hdr.nexus = io->io_hdr.nexus;
12652		msg.dt.flags = io->io_hdr.flags;
12653		/*
12654		 * We convert everything into a S/G list here.  We can't
12655		 * pass by reference, only by value between controllers.
12656		 * So we can't pass a pointer to the S/G list, only as many
12657		 * S/G entries as we can fit in here.  If it's possible for
12658		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12659		 * then we need to break this up into multiple transfers.
12660		 */
12661		if (io->scsiio.kern_sg_entries == 0) {
12662			msg.dt.kern_sg_entries = 1;
12663			/*
12664			 * If this is in cached memory, flush the cache
12665			 * before we send the DMA request to the other
12666			 * controller.  We want to do this in either the
12667			 * read or the write case.  The read case is
12668			 * straightforward.  In the write case, we want to
12669			 * make sure nothing is in the local cache that
12670			 * could overwrite the DMAed data.
12671			 */
12672			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12673				/*
12674				 * XXX KDM use bus_dmamap_sync() here.
12675				 */
12676			}
12677
12678			/*
12679			 * Convert to a physical address if this is a
12680			 * virtual address.
12681			 */
12682			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12683				msg.dt.sg_list[0].addr =
12684					io->scsiio.kern_data_ptr;
12685			} else {
12686				/*
12687				 * XXX KDM use busdma here!
12688				 */
12689#if 0
12690				msg.dt.sg_list[0].addr = (void *)
12691					vtophys(io->scsiio.kern_data_ptr);
12692#endif
12693			}
12694
12695			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12696			do_sg_copy = 0;
12697		} else {
12698			struct ctl_sg_entry *sgl;
12699
12700			do_sg_copy = 1;
12701			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12702			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12703			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12704				/*
12705				 * XXX KDM use bus_dmamap_sync() here.
12706				 */
12707			}
12708		}
12709
12710		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12711		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12712		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12713		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12714		msg.dt.sg_sequence = 0;
12715
12716		/*
12717		 * Loop until we've sent all of the S/G entries.  On the
12718		 * other end, we'll recompose these S/G entries into one
12719		 * contiguous list before passing it to the
12720		 */
12721		for (sg_entries_sent = 0; sg_entries_sent <
12722		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12723			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12724				sizeof(msg.dt.sg_list[0])),
12725				msg.dt.kern_sg_entries - sg_entries_sent);
12726
12727			if (do_sg_copy != 0) {
12728				struct ctl_sg_entry *sgl;
12729				int j;
12730
12731				sgl = (struct ctl_sg_entry *)
12732					io->scsiio.kern_data_ptr;
12733				/*
12734				 * If this is in cached memory, flush the cache
12735				 * before we send the DMA request to the other
12736				 * controller.  We want to do this in either
12737				 * the * read or the write case.  The read
12738				 * case is straightforward.  In the write
12739				 * case, we want to make sure nothing is
12740				 * in the local cache that could overwrite
12741				 * the DMAed data.
12742				 */
12743
12744				for (i = sg_entries_sent, j = 0;
12745				     i < msg.dt.cur_sg_entries; i++, j++) {
12746					if ((io->io_hdr.flags &
12747					     CTL_FLAG_NO_DATASYNC) == 0) {
12748						/*
12749						 * XXX KDM use bus_dmamap_sync()
12750						 */
12751					}
12752					if ((io->io_hdr.flags &
12753					     CTL_FLAG_BUS_ADDR) == 0) {
12754						/*
12755						 * XXX KDM use busdma.
12756						 */
12757#if 0
12758						msg.dt.sg_list[j].addr =(void *)
12759						       vtophys(sgl[i].addr);
12760#endif
12761					} else {
12762						msg.dt.sg_list[j].addr =
12763							sgl[i].addr;
12764					}
12765					msg.dt.sg_list[j].len = sgl[i].len;
12766				}
12767			}
12768
12769			sg_entries_sent += msg.dt.cur_sg_entries;
12770			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12771				msg.dt.sg_last = 1;
12772			else
12773				msg.dt.sg_last = 0;
12774
12775			/*
12776			 * XXX KDM drop and reacquire the lock here?
12777			 */
12778			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12779			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12780				/*
12781				 * XXX do something here.
12782				 */
12783			}
12784
12785			msg.dt.sent_sg_entries = sg_entries_sent;
12786		}
12787		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12788		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12789			ctl_failover_io(io, /*have_lock*/ 0);
12790
12791	} else {
12792
12793		/*
12794		 * Lookup the fe_datamove() function for this particular
12795		 * front end.
12796		 */
12797		fe_datamove =
12798		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12799
12800		fe_datamove(io);
12801	}
12802}
12803
12804static void
12805ctl_send_datamove_done(union ctl_io *io, int have_lock)
12806{
12807	union ctl_ha_msg msg;
12808	int isc_status;
12809
12810	memset(&msg, 0, sizeof(msg));
12811
12812	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12813	msg.hdr.original_sc = io;
12814	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12815	msg.hdr.nexus = io->io_hdr.nexus;
12816	msg.hdr.status = io->io_hdr.status;
12817	msg.scsi.tag_num = io->scsiio.tag_num;
12818	msg.scsi.tag_type = io->scsiio.tag_type;
12819	msg.scsi.scsi_status = io->scsiio.scsi_status;
12820	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12821	       sizeof(io->scsiio.sense_data));
12822	msg.scsi.sense_len = io->scsiio.sense_len;
12823	msg.scsi.sense_residual = io->scsiio.sense_residual;
12824	msg.scsi.fetd_status = io->io_hdr.port_status;
12825	msg.scsi.residual = io->scsiio.residual;
12826	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12827
12828	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12829		ctl_failover_io(io, /*have_lock*/ have_lock);
12830		return;
12831	}
12832
12833	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12834	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12835		/* XXX do something if this fails */
12836	}
12837
12838}
12839
12840/*
12841 * The DMA to the remote side is done, now we need to tell the other side
12842 * we're done so it can continue with its data movement.
12843 */
12844static void
12845ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12846{
12847	union ctl_io *io;
12848
12849	io = rq->context;
12850
12851	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12852		printf("%s: ISC DMA write failed with error %d", __func__,
12853		       rq->ret);
12854		ctl_set_internal_failure(&io->scsiio,
12855					 /*sks_valid*/ 1,
12856					 /*retry_count*/ rq->ret);
12857	}
12858
12859	ctl_dt_req_free(rq);
12860
12861	/*
12862	 * In this case, we had to malloc the memory locally.  Free it.
12863	 */
12864	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12865		int i;
12866		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12867			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12868	}
12869	/*
12870	 * The data is in local and remote memory, so now we need to send
12871	 * status (good or back) back to the other side.
12872	 */
12873	ctl_send_datamove_done(io, /*have_lock*/ 0);
12874}
12875
12876/*
12877 * We've moved the data from the host/controller into local memory.  Now we
12878 * need to push it over to the remote controller's memory.
12879 */
12880static int
12881ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12882{
12883	int retval;
12884
12885	retval = 0;
12886
12887	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12888					  ctl_datamove_remote_write_cb);
12889
12890	return (retval);
12891}
12892
12893static void
12894ctl_datamove_remote_write(union ctl_io *io)
12895{
12896	int retval;
12897	void (*fe_datamove)(union ctl_io *io);
12898
12899	/*
12900	 * - Get the data from the host/HBA into local memory.
12901	 * - DMA memory from the local controller to the remote controller.
12902	 * - Send status back to the remote controller.
12903	 */
12904
12905	retval = ctl_datamove_remote_sgl_setup(io);
12906	if (retval != 0)
12907		return;
12908
12909	/* Switch the pointer over so the FETD knows what to do */
12910	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12911
12912	/*
12913	 * Use a custom move done callback, since we need to send completion
12914	 * back to the other controller, not to the backend on this side.
12915	 */
12916	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12917
12918	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12919
12920	fe_datamove(io);
12921
12922	return;
12923
12924}
12925
12926static int
12927ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12928{
12929#if 0
12930	char str[256];
12931	char path_str[64];
12932	struct sbuf sb;
12933#endif
12934
12935	/*
12936	 * In this case, we had to malloc the memory locally.  Free it.
12937	 */
12938	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12939		int i;
12940		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12941			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12942	}
12943
12944#if 0
12945	scsi_path_string(io, path_str, sizeof(path_str));
12946	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12947	sbuf_cat(&sb, path_str);
12948	scsi_command_string(&io->scsiio, NULL, &sb);
12949	sbuf_printf(&sb, "\n");
12950	sbuf_cat(&sb, path_str);
12951	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12952		    io->scsiio.tag_num, io->scsiio.tag_type);
12953	sbuf_cat(&sb, path_str);
12954	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12955		    io->io_hdr.flags, io->io_hdr.status);
12956	sbuf_finish(&sb);
12957	printk("%s", sbuf_data(&sb));
12958#endif
12959
12960
12961	/*
12962	 * The read is done, now we need to send status (good or bad) back
12963	 * to the other side.
12964	 */
12965	ctl_send_datamove_done(io, /*have_lock*/ 0);
12966
12967	return (0);
12968}
12969
12970static void
12971ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12972{
12973	union ctl_io *io;
12974	void (*fe_datamove)(union ctl_io *io);
12975
12976	io = rq->context;
12977
12978	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12979		printf("%s: ISC DMA read failed with error %d", __func__,
12980		       rq->ret);
12981		ctl_set_internal_failure(&io->scsiio,
12982					 /*sks_valid*/ 1,
12983					 /*retry_count*/ rq->ret);
12984	}
12985
12986	ctl_dt_req_free(rq);
12987
12988	/* Switch the pointer over so the FETD knows what to do */
12989	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12990
12991	/*
12992	 * Use a custom move done callback, since we need to send completion
12993	 * back to the other controller, not to the backend on this side.
12994	 */
12995	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12996
12997	/* XXX KDM add checks like the ones in ctl_datamove? */
12998
12999	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13000
13001	fe_datamove(io);
13002}
13003
13004static int
13005ctl_datamove_remote_sgl_setup(union ctl_io *io)
13006{
13007	struct ctl_sg_entry *local_sglist, *remote_sglist;
13008	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13009	struct ctl_softc *softc;
13010	int retval;
13011	int i;
13012
13013	retval = 0;
13014	softc = control_softc;
13015
13016	local_sglist = io->io_hdr.local_sglist;
13017	local_dma_sglist = io->io_hdr.local_dma_sglist;
13018	remote_sglist = io->io_hdr.remote_sglist;
13019	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13020
13021	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13022		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13023			local_sglist[i].len = remote_sglist[i].len;
13024
13025			/*
13026			 * XXX Detect the situation where the RS-level I/O
13027			 * redirector on the other side has already read the
13028			 * data off of the AOR RS on this side, and
13029			 * transferred it to remote (mirror) memory on the
13030			 * other side.  Since we already have the data in
13031			 * memory here, we just need to use it.
13032			 *
13033			 * XXX KDM this can probably be removed once we
13034			 * get the cache device code in and take the
13035			 * current AOR implementation out.
13036			 */
13037#ifdef NEEDTOPORT
13038			if ((remote_sglist[i].addr >=
13039			     (void *)vtophys(softc->mirr->addr))
13040			 && (remote_sglist[i].addr <
13041			     ((void *)vtophys(softc->mirr->addr) +
13042			     CacheMirrorOffset))) {
13043				local_sglist[i].addr = remote_sglist[i].addr -
13044					CacheMirrorOffset;
13045				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13046				     CTL_FLAG_DATA_IN)
13047					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13048			} else {
13049				local_sglist[i].addr = remote_sglist[i].addr +
13050					CacheMirrorOffset;
13051			}
13052#endif
13053#if 0
13054			printf("%s: local %p, remote %p, len %d\n",
13055			       __func__, local_sglist[i].addr,
13056			       remote_sglist[i].addr, local_sglist[i].len);
13057#endif
13058		}
13059	} else {
13060		uint32_t len_to_go;
13061
13062		/*
13063		 * In this case, we don't have automatically allocated
13064		 * memory for this I/O on this controller.  This typically
13065		 * happens with internal CTL I/O -- e.g. inquiry, mode
13066		 * sense, etc.  Anything coming from RAIDCore will have
13067		 * a mirror area available.
13068		 */
13069		len_to_go = io->scsiio.kern_data_len;
13070
13071		/*
13072		 * Clear the no datasync flag, we have to use malloced
13073		 * buffers.
13074		 */
13075		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13076
13077		/*
13078		 * The difficult thing here is that the size of the various
13079		 * S/G segments may be different than the size from the
13080		 * remote controller.  That'll make it harder when DMAing
13081		 * the data back to the other side.
13082		 */
13083		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13084		     sizeof(io->io_hdr.remote_sglist[0])) &&
13085		     (len_to_go > 0); i++) {
13086			local_sglist[i].len = ctl_min(len_to_go, 131072);
13087			CTL_SIZE_8B(local_dma_sglist[i].len,
13088				    local_sglist[i].len);
13089			local_sglist[i].addr =
13090				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13091
13092			local_dma_sglist[i].addr = local_sglist[i].addr;
13093
13094			if (local_sglist[i].addr == NULL) {
13095				int j;
13096
13097				printf("malloc failed for %zd bytes!",
13098				       local_dma_sglist[i].len);
13099				for (j = 0; j < i; j++) {
13100					free(local_sglist[j].addr, M_CTL);
13101				}
13102				ctl_set_internal_failure(&io->scsiio,
13103							 /*sks_valid*/ 1,
13104							 /*retry_count*/ 4857);
13105				retval = 1;
13106				goto bailout_error;
13107
13108			}
13109			/* XXX KDM do we need a sync here? */
13110
13111			len_to_go -= local_sglist[i].len;
13112		}
13113		/*
13114		 * Reset the number of S/G entries accordingly.  The
13115		 * original number of S/G entries is available in
13116		 * rem_sg_entries.
13117		 */
13118		io->scsiio.kern_sg_entries = i;
13119
13120#if 0
13121		printf("%s: kern_sg_entries = %d\n", __func__,
13122		       io->scsiio.kern_sg_entries);
13123		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13124			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13125			       local_sglist[i].addr, local_sglist[i].len,
13126			       local_dma_sglist[i].len);
13127#endif
13128	}
13129
13130
13131	return (retval);
13132
13133bailout_error:
13134
13135	ctl_send_datamove_done(io, /*have_lock*/ 0);
13136
13137	return (retval);
13138}
13139
13140static int
13141ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13142			 ctl_ha_dt_cb callback)
13143{
13144	struct ctl_ha_dt_req *rq;
13145	struct ctl_sg_entry *remote_sglist, *local_sglist;
13146	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13147	uint32_t local_used, remote_used, total_used;
13148	int retval;
13149	int i, j;
13150
13151	retval = 0;
13152
13153	rq = ctl_dt_req_alloc();
13154
13155	/*
13156	 * If we failed to allocate the request, and if the DMA didn't fail
13157	 * anyway, set busy status.  This is just a resource allocation
13158	 * failure.
13159	 */
13160	if ((rq == NULL)
13161	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13162		ctl_set_busy(&io->scsiio);
13163
13164	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13165
13166		if (rq != NULL)
13167			ctl_dt_req_free(rq);
13168
13169		/*
13170		 * The data move failed.  We need to return status back
13171		 * to the other controller.  No point in trying to DMA
13172		 * data to the remote controller.
13173		 */
13174
13175		ctl_send_datamove_done(io, /*have_lock*/ 0);
13176
13177		retval = 1;
13178
13179		goto bailout;
13180	}
13181
13182	local_sglist = io->io_hdr.local_sglist;
13183	local_dma_sglist = io->io_hdr.local_dma_sglist;
13184	remote_sglist = io->io_hdr.remote_sglist;
13185	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13186	local_used = 0;
13187	remote_used = 0;
13188	total_used = 0;
13189
13190	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13191		rq->ret = CTL_HA_STATUS_SUCCESS;
13192		rq->context = io;
13193		callback(rq);
13194		goto bailout;
13195	}
13196
13197	/*
13198	 * Pull/push the data over the wire from/to the other controller.
13199	 * This takes into account the possibility that the local and
13200	 * remote sglists may not be identical in terms of the size of
13201	 * the elements and the number of elements.
13202	 *
13203	 * One fundamental assumption here is that the length allocated for
13204	 * both the local and remote sglists is identical.  Otherwise, we've
13205	 * essentially got a coding error of some sort.
13206	 */
13207	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13208		int isc_ret;
13209		uint32_t cur_len, dma_length;
13210		uint8_t *tmp_ptr;
13211
13212		rq->id = CTL_HA_DATA_CTL;
13213		rq->command = command;
13214		rq->context = io;
13215
13216		/*
13217		 * Both pointers should be aligned.  But it is possible
13218		 * that the allocation length is not.  They should both
13219		 * also have enough slack left over at the end, though,
13220		 * to round up to the next 8 byte boundary.
13221		 */
13222		cur_len = ctl_min(local_sglist[i].len - local_used,
13223				  remote_sglist[j].len - remote_used);
13224
13225		/*
13226		 * In this case, we have a size issue and need to decrease
13227		 * the size, except in the case where we actually have less
13228		 * than 8 bytes left.  In that case, we need to increase
13229		 * the DMA length to get the last bit.
13230		 */
13231		if ((cur_len & 0x7) != 0) {
13232			if (cur_len > 0x7) {
13233				cur_len = cur_len - (cur_len & 0x7);
13234				dma_length = cur_len;
13235			} else {
13236				CTL_SIZE_8B(dma_length, cur_len);
13237			}
13238
13239		} else
13240			dma_length = cur_len;
13241
13242		/*
13243		 * If we had to allocate memory for this I/O, instead of using
13244		 * the non-cached mirror memory, we'll need to flush the cache
13245		 * before trying to DMA to the other controller.
13246		 *
13247		 * We could end up doing this multiple times for the same
13248		 * segment if we have a larger local segment than remote
13249		 * segment.  That shouldn't be an issue.
13250		 */
13251		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13252			/*
13253			 * XXX KDM use bus_dmamap_sync() here.
13254			 */
13255		}
13256
13257		rq->size = dma_length;
13258
13259		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13260		tmp_ptr += local_used;
13261
13262		/* Use physical addresses when talking to ISC hardware */
13263		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13264			/* XXX KDM use busdma */
13265#if 0
13266			rq->local = vtophys(tmp_ptr);
13267#endif
13268		} else
13269			rq->local = tmp_ptr;
13270
13271		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13272		tmp_ptr += remote_used;
13273		rq->remote = tmp_ptr;
13274
13275		rq->callback = NULL;
13276
13277		local_used += cur_len;
13278		if (local_used >= local_sglist[i].len) {
13279			i++;
13280			local_used = 0;
13281		}
13282
13283		remote_used += cur_len;
13284		if (remote_used >= remote_sglist[j].len) {
13285			j++;
13286			remote_used = 0;
13287		}
13288		total_used += cur_len;
13289
13290		if (total_used >= io->scsiio.kern_data_len)
13291			rq->callback = callback;
13292
13293		if ((rq->size & 0x7) != 0) {
13294			printf("%s: warning: size %d is not on 8b boundary\n",
13295			       __func__, rq->size);
13296		}
13297		if (((uintptr_t)rq->local & 0x7) != 0) {
13298			printf("%s: warning: local %p not on 8b boundary\n",
13299			       __func__, rq->local);
13300		}
13301		if (((uintptr_t)rq->remote & 0x7) != 0) {
13302			printf("%s: warning: remote %p not on 8b boundary\n",
13303			       __func__, rq->local);
13304		}
13305#if 0
13306		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13307		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13308		       rq->local, rq->remote, rq->size);
13309#endif
13310
13311		isc_ret = ctl_dt_single(rq);
13312		if (isc_ret == CTL_HA_STATUS_WAIT)
13313			continue;
13314
13315		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13316			rq->ret = CTL_HA_STATUS_SUCCESS;
13317		} else {
13318			rq->ret = isc_ret;
13319		}
13320		callback(rq);
13321		goto bailout;
13322	}
13323
13324bailout:
13325	return (retval);
13326
13327}
13328
13329static void
13330ctl_datamove_remote_read(union ctl_io *io)
13331{
13332	int retval;
13333	int i;
13334
13335	/*
13336	 * This will send an error to the other controller in the case of a
13337	 * failure.
13338	 */
13339	retval = ctl_datamove_remote_sgl_setup(io);
13340	if (retval != 0)
13341		return;
13342
13343	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13344					  ctl_datamove_remote_read_cb);
13345	if ((retval != 0)
13346	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13347		/*
13348		 * Make sure we free memory if there was an error..  The
13349		 * ctl_datamove_remote_xfer() function will send the
13350		 * datamove done message, or call the callback with an
13351		 * error if there is a problem.
13352		 */
13353		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13354			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13355	}
13356
13357	return;
13358}
13359
13360/*
13361 * Process a datamove request from the other controller.  This is used for
13362 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13363 * first.  Once that is complete, the data gets DMAed into the remote
13364 * controller's memory.  For reads, we DMA from the remote controller's
13365 * memory into our memory first, and then move it out to the FETD.
13366 */
13367static void
13368ctl_datamove_remote(union ctl_io *io)
13369{
13370	struct ctl_softc *softc;
13371
13372	softc = control_softc;
13373
13374	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13375
13376	/*
13377	 * Note that we look for an aborted I/O here, but don't do some of
13378	 * the other checks that ctl_datamove() normally does.
13379	 * We don't need to run the datamove delay code, since that should
13380	 * have been done if need be on the other controller.
13381	 */
13382	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13383		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13384		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13385		       io->io_hdr.nexus.targ_port,
13386		       io->io_hdr.nexus.targ_target.id,
13387		       io->io_hdr.nexus.targ_lun);
13388		io->io_hdr.port_status = 31338;
13389		ctl_send_datamove_done(io, /*have_lock*/ 0);
13390		return;
13391	}
13392
13393	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13394		ctl_datamove_remote_write(io);
13395	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13396		ctl_datamove_remote_read(io);
13397	} else {
13398		union ctl_ha_msg msg;
13399		struct scsi_sense_data *sense;
13400		uint8_t sks[3];
13401		int retry_count;
13402
13403		memset(&msg, 0, sizeof(msg));
13404
13405		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13406		msg.hdr.status = CTL_SCSI_ERROR;
13407		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13408
13409		retry_count = 4243;
13410
13411		sense = &msg.scsi.sense_data;
13412		sks[0] = SSD_SCS_VALID;
13413		sks[1] = (retry_count >> 8) & 0xff;
13414		sks[2] = retry_count & 0xff;
13415
13416		/* "Internal target failure" */
13417		scsi_set_sense_data(sense,
13418				    /*sense_format*/ SSD_TYPE_NONE,
13419				    /*current_error*/ 1,
13420				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13421				    /*asc*/ 0x44,
13422				    /*ascq*/ 0x00,
13423				    /*type*/ SSD_ELEM_SKS,
13424				    /*size*/ sizeof(sks),
13425				    /*data*/ sks,
13426				    SSD_ELEM_NONE);
13427
13428		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13429		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13430			ctl_failover_io(io, /*have_lock*/ 1);
13431			return;
13432		}
13433
13434		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13435		    CTL_HA_STATUS_SUCCESS) {
13436			/* XXX KDM what to do if this fails? */
13437		}
13438		return;
13439	}
13440
13441}
13442
13443static int
13444ctl_process_done(union ctl_io *io)
13445{
13446	struct ctl_lun *lun;
13447	struct ctl_softc *ctl_softc = control_softc;
13448	void (*fe_done)(union ctl_io *io);
13449	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13450
13451	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13452
13453	fe_done =
13454	    control_softc->ctl_ports[targ_port]->fe_done;
13455
13456#ifdef CTL_TIME_IO
13457	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13458		char str[256];
13459		char path_str[64];
13460		struct sbuf sb;
13461
13462		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13463		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13464
13465		sbuf_cat(&sb, path_str);
13466		switch (io->io_hdr.io_type) {
13467		case CTL_IO_SCSI:
13468			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13469			sbuf_printf(&sb, "\n");
13470			sbuf_cat(&sb, path_str);
13471			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13472				    io->scsiio.tag_num, io->scsiio.tag_type);
13473			break;
13474		case CTL_IO_TASK:
13475			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13476				    "Tag Type: %d\n", io->taskio.task_action,
13477				    io->taskio.tag_num, io->taskio.tag_type);
13478			break;
13479		default:
13480			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13481			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13482			break;
13483		}
13484		sbuf_cat(&sb, path_str);
13485		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13486			    (intmax_t)time_uptime - io->io_hdr.start_time);
13487		sbuf_finish(&sb);
13488		printf("%s", sbuf_data(&sb));
13489	}
13490#endif /* CTL_TIME_IO */
13491
13492	switch (io->io_hdr.io_type) {
13493	case CTL_IO_SCSI:
13494		break;
13495	case CTL_IO_TASK:
13496		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13497			ctl_io_error_print(io, NULL);
13498		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13499			ctl_free_io(io);
13500		else
13501			fe_done(io);
13502		return (CTL_RETVAL_COMPLETE);
13503	default:
13504		panic("ctl_process_done: invalid io type %d\n",
13505		      io->io_hdr.io_type);
13506		break; /* NOTREACHED */
13507	}
13508
13509	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13510	if (lun == NULL) {
13511		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13512				 io->io_hdr.nexus.targ_mapped_lun));
13513		goto bailout;
13514	}
13515
13516	mtx_lock(&lun->lun_lock);
13517
13518	/*
13519	 * Check to see if we have any errors to inject here.  We only
13520	 * inject errors for commands that don't already have errors set.
13521	 */
13522	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13523	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13524	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13525		ctl_inject_error(lun, io);
13526
13527	/*
13528	 * XXX KDM how do we treat commands that aren't completed
13529	 * successfully?
13530	 *
13531	 * XXX KDM should we also track I/O latency?
13532	 */
13533	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13534	    io->io_hdr.io_type == CTL_IO_SCSI) {
13535#ifdef CTL_TIME_IO
13536		struct bintime cur_bt;
13537#endif
13538		int type;
13539
13540		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13541		    CTL_FLAG_DATA_IN)
13542			type = CTL_STATS_READ;
13543		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13544		    CTL_FLAG_DATA_OUT)
13545			type = CTL_STATS_WRITE;
13546		else
13547			type = CTL_STATS_NO_IO;
13548
13549		lun->stats.ports[targ_port].bytes[type] +=
13550		    io->scsiio.kern_total_len;
13551		lun->stats.ports[targ_port].operations[type]++;
13552#ifdef CTL_TIME_IO
13553		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13554		   &io->io_hdr.dma_bt);
13555		lun->stats.ports[targ_port].num_dmas[type] +=
13556		    io->io_hdr.num_dmas;
13557		getbintime(&cur_bt);
13558		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13559		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13560#endif
13561	}
13562
13563	/*
13564	 * Remove this from the OOA queue.
13565	 */
13566	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13567
13568	/*
13569	 * Run through the blocked queue on this LUN and see if anything
13570	 * has become unblocked, now that this transaction is done.
13571	 */
13572	ctl_check_blocked(lun);
13573
13574	/*
13575	 * If the LUN has been invalidated, free it if there is nothing
13576	 * left on its OOA queue.
13577	 */
13578	if ((lun->flags & CTL_LUN_INVALID)
13579	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13580		mtx_unlock(&lun->lun_lock);
13581		mtx_lock(&ctl_softc->ctl_lock);
13582		ctl_free_lun(lun);
13583		mtx_unlock(&ctl_softc->ctl_lock);
13584	} else
13585		mtx_unlock(&lun->lun_lock);
13586
13587bailout:
13588
13589	/*
13590	 * If this command has been aborted, make sure we set the status
13591	 * properly.  The FETD is responsible for freeing the I/O and doing
13592	 * whatever it needs to do to clean up its state.
13593	 */
13594	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13595		ctl_set_task_aborted(&io->scsiio);
13596
13597	/*
13598	 * If enabled, print command error status.
13599	 * We don't print UAs unless debugging was enabled explicitly.
13600	 */
13601	do {
13602		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13603			break;
13604		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13605			break;
13606		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13607		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13608		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13609			int error_code, sense_key, asc, ascq;
13610
13611			scsi_extract_sense_len(&io->scsiio.sense_data,
13612			    io->scsiio.sense_len, &error_code, &sense_key,
13613			    &asc, &ascq, /*show_errors*/ 0);
13614			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13615				break;
13616		}
13617
13618		ctl_io_error_print(io, NULL);
13619	} while (0);
13620
13621	/*
13622	 * Tell the FETD or the other shelf controller we're done with this
13623	 * command.  Note that only SCSI commands get to this point.  Task
13624	 * management commands are completed above.
13625	 *
13626	 * We only send status to the other controller if we're in XFER
13627	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13628	 * received the I/O (from CTL's perspective), and so the status is
13629	 * generated there.
13630	 *
13631	 * XXX KDM if we hold the lock here, we could cause a deadlock
13632	 * if the frontend comes back in in this context to queue
13633	 * something.
13634	 */
13635	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13636	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13637		union ctl_ha_msg msg;
13638
13639		memset(&msg, 0, sizeof(msg));
13640		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13641		msg.hdr.original_sc = io->io_hdr.original_sc;
13642		msg.hdr.nexus = io->io_hdr.nexus;
13643		msg.hdr.status = io->io_hdr.status;
13644		msg.scsi.scsi_status = io->scsiio.scsi_status;
13645		msg.scsi.tag_num = io->scsiio.tag_num;
13646		msg.scsi.tag_type = io->scsiio.tag_type;
13647		msg.scsi.sense_len = io->scsiio.sense_len;
13648		msg.scsi.sense_residual = io->scsiio.sense_residual;
13649		msg.scsi.residual = io->scsiio.residual;
13650		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13651		       sizeof(io->scsiio.sense_data));
13652		/*
13653		 * We copy this whether or not this is an I/O-related
13654		 * command.  Otherwise, we'd have to go and check to see
13655		 * whether it's a read/write command, and it really isn't
13656		 * worth it.
13657		 */
13658		memcpy(&msg.scsi.lbalen,
13659		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13660		       sizeof(msg.scsi.lbalen));
13661
13662		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13663				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13664			/* XXX do something here */
13665		}
13666
13667		ctl_free_io(io);
13668	} else
13669		fe_done(io);
13670
13671	return (CTL_RETVAL_COMPLETE);
13672}
13673
13674#ifdef CTL_WITH_CA
13675/*
13676 * Front end should call this if it doesn't do autosense.  When the request
13677 * sense comes back in from the initiator, we'll dequeue this and send it.
13678 */
13679int
13680ctl_queue_sense(union ctl_io *io)
13681{
13682	struct ctl_lun *lun;
13683	struct ctl_softc *ctl_softc;
13684	uint32_t initidx, targ_lun;
13685
13686	ctl_softc = control_softc;
13687
13688	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13689
13690	/*
13691	 * LUN lookup will likely move to the ctl_work_thread() once we
13692	 * have our new queueing infrastructure (that doesn't put things on
13693	 * a per-LUN queue initially).  That is so that we can handle
13694	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13695	 * can't deal with that right now.
13696	 */
13697	mtx_lock(&ctl_softc->ctl_lock);
13698
13699	/*
13700	 * If we don't have a LUN for this, just toss the sense
13701	 * information.
13702	 */
13703	targ_lun = io->io_hdr.nexus.targ_lun;
13704	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13705	if ((targ_lun < CTL_MAX_LUNS)
13706	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13707		lun = ctl_softc->ctl_luns[targ_lun];
13708	else
13709		goto bailout;
13710
13711	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13712
13713	mtx_lock(&lun->lun_lock);
13714	/*
13715	 * Already have CA set for this LUN...toss the sense information.
13716	 */
13717	if (ctl_is_set(lun->have_ca, initidx)) {
13718		mtx_unlock(&lun->lun_lock);
13719		goto bailout;
13720	}
13721
13722	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13723	       ctl_min(sizeof(lun->pending_sense[initidx]),
13724	       sizeof(io->scsiio.sense_data)));
13725	ctl_set_mask(lun->have_ca, initidx);
13726	mtx_unlock(&lun->lun_lock);
13727
13728bailout:
13729	mtx_unlock(&ctl_softc->ctl_lock);
13730
13731	ctl_free_io(io);
13732
13733	return (CTL_RETVAL_COMPLETE);
13734}
13735#endif
13736
13737/*
13738 * Primary command inlet from frontend ports.  All SCSI and task I/O
13739 * requests must go through this function.
13740 */
13741int
13742ctl_queue(union ctl_io *io)
13743{
13744	struct ctl_softc *ctl_softc;
13745
13746	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13747
13748	ctl_softc = control_softc;
13749
13750#ifdef CTL_TIME_IO
13751	io->io_hdr.start_time = time_uptime;
13752	getbintime(&io->io_hdr.start_bt);
13753#endif /* CTL_TIME_IO */
13754
13755	/* Map FE-specific LUN ID into global one. */
13756	io->io_hdr.nexus.targ_mapped_lun =
13757	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13758
13759	switch (io->io_hdr.io_type) {
13760	case CTL_IO_SCSI:
13761	case CTL_IO_TASK:
13762		if (ctl_debug & CTL_DEBUG_CDB)
13763			ctl_io_print(io);
13764		ctl_enqueue_incoming(io);
13765		break;
13766	default:
13767		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13768		return (EINVAL);
13769	}
13770
13771	return (CTL_RETVAL_COMPLETE);
13772}
13773
13774#ifdef CTL_IO_DELAY
13775static void
13776ctl_done_timer_wakeup(void *arg)
13777{
13778	union ctl_io *io;
13779
13780	io = (union ctl_io *)arg;
13781	ctl_done(io);
13782}
13783#endif /* CTL_IO_DELAY */
13784
13785void
13786ctl_done(union ctl_io *io)
13787{
13788	struct ctl_softc *ctl_softc;
13789
13790	ctl_softc = control_softc;
13791
13792	/*
13793	 * Enable this to catch duplicate completion issues.
13794	 */
13795#if 0
13796	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13797		printf("%s: type %d msg %d cdb %x iptl: "
13798		       "%d:%d:%d:%d tag 0x%04x "
13799		       "flag %#x status %x\n",
13800			__func__,
13801			io->io_hdr.io_type,
13802			io->io_hdr.msg_type,
13803			io->scsiio.cdb[0],
13804			io->io_hdr.nexus.initid.id,
13805			io->io_hdr.nexus.targ_port,
13806			io->io_hdr.nexus.targ_target.id,
13807			io->io_hdr.nexus.targ_lun,
13808			(io->io_hdr.io_type ==
13809			CTL_IO_TASK) ?
13810			io->taskio.tag_num :
13811			io->scsiio.tag_num,
13812		        io->io_hdr.flags,
13813			io->io_hdr.status);
13814	} else
13815		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13816#endif
13817
13818	/*
13819	 * This is an internal copy of an I/O, and should not go through
13820	 * the normal done processing logic.
13821	 */
13822	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13823		return;
13824
13825	/*
13826	 * We need to send a msg to the serializing shelf to finish the IO
13827	 * as well.  We don't send a finish message to the other shelf if
13828	 * this is a task management command.  Task management commands
13829	 * aren't serialized in the OOA queue, but rather just executed on
13830	 * both shelf controllers for commands that originated on that
13831	 * controller.
13832	 */
13833	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13834	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13835		union ctl_ha_msg msg_io;
13836
13837		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13838		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13839		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13840		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13841		}
13842		/* continue on to finish IO */
13843	}
13844#ifdef CTL_IO_DELAY
13845	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13846		struct ctl_lun *lun;
13847
13848		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13849
13850		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13851	} else {
13852		struct ctl_lun *lun;
13853
13854		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13855
13856		if ((lun != NULL)
13857		 && (lun->delay_info.done_delay > 0)) {
13858			struct callout *callout;
13859
13860			callout = (struct callout *)&io->io_hdr.timer_bytes;
13861			callout_init(callout, /*mpsafe*/ 1);
13862			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13863			callout_reset(callout,
13864				      lun->delay_info.done_delay * hz,
13865				      ctl_done_timer_wakeup, io);
13866			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13867				lun->delay_info.done_delay = 0;
13868			return;
13869		}
13870	}
13871#endif /* CTL_IO_DELAY */
13872
13873	ctl_enqueue_done(io);
13874}
13875
13876int
13877ctl_isc(struct ctl_scsiio *ctsio)
13878{
13879	struct ctl_lun *lun;
13880	int retval;
13881
13882	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13883
13884	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13885
13886	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13887
13888	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13889
13890	return (retval);
13891}
13892
13893
13894static void
13895ctl_work_thread(void *arg)
13896{
13897	struct ctl_thread *thr = (struct ctl_thread *)arg;
13898	struct ctl_softc *softc = thr->ctl_softc;
13899	union ctl_io *io;
13900	int retval;
13901
13902	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13903
13904	for (;;) {
13905		retval = 0;
13906
13907		/*
13908		 * We handle the queues in this order:
13909		 * - ISC
13910		 * - done queue (to free up resources, unblock other commands)
13911		 * - RtR queue
13912		 * - incoming queue
13913		 *
13914		 * If those queues are empty, we break out of the loop and
13915		 * go to sleep.
13916		 */
13917		mtx_lock(&thr->queue_lock);
13918		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13919		if (io != NULL) {
13920			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13921			mtx_unlock(&thr->queue_lock);
13922			ctl_handle_isc(io);
13923			continue;
13924		}
13925		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13926		if (io != NULL) {
13927			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13928			/* clear any blocked commands, call fe_done */
13929			mtx_unlock(&thr->queue_lock);
13930			retval = ctl_process_done(io);
13931			continue;
13932		}
13933		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13934		if (io != NULL) {
13935			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13936			mtx_unlock(&thr->queue_lock);
13937			if (io->io_hdr.io_type == CTL_IO_TASK)
13938				ctl_run_task(io);
13939			else
13940				ctl_scsiio_precheck(softc, &io->scsiio);
13941			continue;
13942		}
13943		if (!ctl_pause_rtr) {
13944			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13945			if (io != NULL) {
13946				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13947				mtx_unlock(&thr->queue_lock);
13948				retval = ctl_scsiio(&io->scsiio);
13949				if (retval != CTL_RETVAL_COMPLETE)
13950					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13951				continue;
13952			}
13953		}
13954
13955		/* Sleep until we have something to do. */
13956		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13957	}
13958}
13959
13960static void
13961ctl_lun_thread(void *arg)
13962{
13963	struct ctl_softc *softc = (struct ctl_softc *)arg;
13964	struct ctl_be_lun *be_lun;
13965	int retval;
13966
13967	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13968
13969	for (;;) {
13970		retval = 0;
13971		mtx_lock(&softc->ctl_lock);
13972		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13973		if (be_lun != NULL) {
13974			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13975			mtx_unlock(&softc->ctl_lock);
13976			ctl_create_lun(be_lun);
13977			continue;
13978		}
13979
13980		/* Sleep until we have something to do. */
13981		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13982		    PDROP | PRIBIO, "-", 0);
13983	}
13984}
13985
13986static void
13987ctl_thresh_thread(void *arg)
13988{
13989	struct ctl_softc *softc = (struct ctl_softc *)arg;
13990	struct ctl_lun *lun;
13991	struct ctl_be_lun *be_lun;
13992	struct scsi_da_rw_recovery_page *rwpage;
13993	struct ctl_logical_block_provisioning_page *page;
13994	const char *attr;
13995	uint64_t thres, val;
13996	int i, e;
13997
13998	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13999
14000	for (;;) {
14001		mtx_lock(&softc->ctl_lock);
14002		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14003			be_lun = lun->be_lun;
14004			if ((lun->flags & CTL_LUN_DISABLED) ||
14005			    (lun->flags & CTL_LUN_OFFLINE) ||
14006			    lun->backend->lun_attr == NULL)
14007				continue;
14008			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14009			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14010				continue;
14011			e = 0;
14012			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14013			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14014				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14015					continue;
14016				thres = scsi_4btoul(page->descr[i].count);
14017				thres <<= CTL_LBP_EXPONENT;
14018				switch (page->descr[i].resource) {
14019				case 0x01:
14020					attr = "blocksavail";
14021					break;
14022				case 0x02:
14023					attr = "blocksused";
14024					break;
14025				case 0xf1:
14026					attr = "poolblocksavail";
14027					break;
14028				case 0xf2:
14029					attr = "poolblocksused";
14030					break;
14031				default:
14032					continue;
14033				}
14034				mtx_unlock(&softc->ctl_lock); // XXX
14035				val = lun->backend->lun_attr(
14036				    lun->be_lun->be_lun, attr);
14037				mtx_lock(&softc->ctl_lock);
14038				if (val == UINT64_MAX)
14039					continue;
14040				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14041				    == SLBPPD_ARMING_INC)
14042					e |= (val >= thres);
14043				else
14044					e |= (val <= thres);
14045			}
14046			mtx_lock(&lun->lun_lock);
14047			if (e) {
14048				if (lun->lasttpt == 0 ||
14049				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14050					lun->lasttpt = time_uptime;
14051					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14052				}
14053			} else {
14054				lun->lasttpt = 0;
14055				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14056			}
14057			mtx_unlock(&lun->lun_lock);
14058		}
14059		mtx_unlock(&softc->ctl_lock);
14060		pause("-", CTL_LBP_PERIOD * hz);
14061	}
14062}
14063
14064static void
14065ctl_enqueue_incoming(union ctl_io *io)
14066{
14067	struct ctl_softc *softc = control_softc;
14068	struct ctl_thread *thr;
14069	u_int idx;
14070
14071	idx = (io->io_hdr.nexus.targ_port * 127 +
14072	       io->io_hdr.nexus.initid.id) % worker_threads;
14073	thr = &softc->threads[idx];
14074	mtx_lock(&thr->queue_lock);
14075	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14076	mtx_unlock(&thr->queue_lock);
14077	wakeup(thr);
14078}
14079
14080static void
14081ctl_enqueue_rtr(union ctl_io *io)
14082{
14083	struct ctl_softc *softc = control_softc;
14084	struct ctl_thread *thr;
14085
14086	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14087	mtx_lock(&thr->queue_lock);
14088	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14089	mtx_unlock(&thr->queue_lock);
14090	wakeup(thr);
14091}
14092
14093static void
14094ctl_enqueue_done(union ctl_io *io)
14095{
14096	struct ctl_softc *softc = control_softc;
14097	struct ctl_thread *thr;
14098
14099	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14100	mtx_lock(&thr->queue_lock);
14101	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14102	mtx_unlock(&thr->queue_lock);
14103	wakeup(thr);
14104}
14105
14106static void
14107ctl_enqueue_isc(union ctl_io *io)
14108{
14109	struct ctl_softc *softc = control_softc;
14110	struct ctl_thread *thr;
14111
14112	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14113	mtx_lock(&thr->queue_lock);
14114	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14115	mtx_unlock(&thr->queue_lock);
14116	wakeup(thr);
14117}
14118
14119/* Initialization and failover */
14120
14121void
14122ctl_init_isc_msg(void)
14123{
14124	printf("CTL: Still calling this thing\n");
14125}
14126
14127/*
14128 * Init component
14129 * 	Initializes component into configuration defined by bootMode
14130 *	(see hasc-sv.c)
14131 *  	returns hasc_Status:
14132 * 		OK
14133 *		ERROR - fatal error
14134 */
14135static ctl_ha_comp_status
14136ctl_isc_init(struct ctl_ha_component *c)
14137{
14138	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14139
14140	c->status = ret;
14141	return ret;
14142}
14143
14144/* Start component
14145 * 	Starts component in state requested. If component starts successfully,
14146 *	it must set its own state to the requestrd state
14147 *	When requested state is HASC_STATE_HA, the component may refine it
14148 * 	by adding _SLAVE or _MASTER flags.
14149 *	Currently allowed state transitions are:
14150 *	UNKNOWN->HA		- initial startup
14151 *	UNKNOWN->SINGLE - initial startup when no parter detected
14152 *	HA->SINGLE		- failover
14153 * returns ctl_ha_comp_status:
14154 * 		OK	- component successfully started in requested state
14155 *		FAILED  - could not start the requested state, failover may
14156 * 			  be possible
14157 *		ERROR	- fatal error detected, no future startup possible
14158 */
14159static ctl_ha_comp_status
14160ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14161{
14162	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14163
14164	printf("%s: go\n", __func__);
14165
14166	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14167	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14168		control_softc->is_single = 0;
14169		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14170		    != CTL_HA_STATUS_SUCCESS) {
14171			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14172			ret = CTL_HA_COMP_STATUS_ERROR;
14173		}
14174	} else if (CTL_HA_STATE_IS_HA(c->state)
14175		&& CTL_HA_STATE_IS_SINGLE(state)){
14176		// HA->SINGLE transition
14177	        ctl_failover();
14178		control_softc->is_single = 1;
14179	} else {
14180		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14181		       c->state, state);
14182		ret = CTL_HA_COMP_STATUS_ERROR;
14183	}
14184	if (CTL_HA_STATE_IS_SINGLE(state))
14185		control_softc->is_single = 1;
14186
14187	c->state = state;
14188	c->status = ret;
14189	return ret;
14190}
14191
14192/*
14193 * Quiesce component
14194 * The component must clear any error conditions (set status to OK) and
14195 * prepare itself to another Start call
14196 * returns ctl_ha_comp_status:
14197 * 	OK
14198 *	ERROR
14199 */
14200static ctl_ha_comp_status
14201ctl_isc_quiesce(struct ctl_ha_component *c)
14202{
14203	int ret = CTL_HA_COMP_STATUS_OK;
14204
14205	ctl_pause_rtr = 1;
14206	c->status = ret;
14207	return ret;
14208}
14209
14210struct ctl_ha_component ctl_ha_component_ctlisc =
14211{
14212	.name = "CTL ISC",
14213	.state = CTL_HA_STATE_UNKNOWN,
14214	.init = ctl_isc_init,
14215	.start = ctl_isc_start,
14216	.quiesce = ctl_isc_quiesce
14217};
14218
14219/*
14220 *  vim: ts=8
14221 */
14222