]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r288148: Synchronize mode pages between HA peers.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id$
36  */
37 /*
38  * CAM Target Layer, a SCSI device emulation subsystem.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42
43 #define _CTL_C
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ctype.h>
51 #include <sys/kernel.h>
52 #include <sys/types.h>
53 #include <sys/kthread.h>
54 #include <sys/bio.h>
55 #include <sys/fcntl.h>
56 #include <sys/lock.h>
57 #include <sys/module.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/malloc.h>
61 #include <sys/conf.h>
62 #include <sys/ioccom.h>
63 #include <sys/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/endian.h>
67 #include <sys/sysctl.h>
68 #include <vm/uma.h>
69
70 #include <cam/cam.h>
71 #include <cam/scsi/scsi_all.h>
72 #include <cam/scsi/scsi_da.h>
73 #include <cam/ctl/ctl_io.h>
74 #include <cam/ctl/ctl.h>
75 #include <cam/ctl/ctl_frontend.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
85 struct ctl_softc *control_softc = NULL;
86
87 /*
88  * Template mode pages.
89  */
90
91 /*
92  * Note that these are default values only.  The actual values will be
93  * filled in when the user does a mode sense.
94  */
95 const static struct copan_debugconf_subpage debugconf_page_default = {
96         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
97         DBGCNF_SUBPAGE_CODE,            /* subpage */
98         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
99          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
100         DBGCNF_VERSION,                 /* page_version */
101         {CTL_TIME_IO_DEFAULT_SECS>>8,
102          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
103 };
104
105 const static struct copan_debugconf_subpage debugconf_page_changeable = {
106         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
107         DBGCNF_SUBPAGE_CODE,            /* subpage */
108         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
109          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
110         0,                              /* page_version */
111         {0xff,0xff},                    /* ctl_time_io_secs */
112 };
113
114 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
115         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
118         /*read_retry_count*/0,
119         /*correction_span*/0,
120         /*head_offset_count*/0,
121         /*data_strobe_offset_cnt*/0,
122         /*byte8*/SMS_RWER_LBPERE,
123         /*write_retry_count*/0,
124         /*reserved2*/0,
125         /*recovery_time_limit*/{0, 0},
126 };
127
128 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
129         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
130         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
131         /*byte3*/0,
132         /*read_retry_count*/0,
133         /*correction_span*/0,
134         /*head_offset_count*/0,
135         /*data_strobe_offset_cnt*/0,
136         /*byte8*/0,
137         /*write_retry_count*/0,
138         /*reserved2*/0,
139         /*recovery_time_limit*/{0, 0},
140 };
141
142 const static struct scsi_format_page format_page_default = {
143         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
144         /*page_length*/sizeof(struct scsi_format_page) - 2,
145         /*tracks_per_zone*/ {0, 0},
146         /*alt_sectors_per_zone*/ {0, 0},
147         /*alt_tracks_per_zone*/ {0, 0},
148         /*alt_tracks_per_lun*/ {0, 0},
149         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
150                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
151         /*bytes_per_sector*/ {0, 0},
152         /*interleave*/ {0, 0},
153         /*track_skew*/ {0, 0},
154         /*cylinder_skew*/ {0, 0},
155         /*flags*/ SFP_HSEC,
156         /*reserved*/ {0, 0, 0}
157 };
158
159 const static struct scsi_format_page format_page_changeable = {
160         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
161         /*page_length*/sizeof(struct scsi_format_page) - 2,
162         /*tracks_per_zone*/ {0, 0},
163         /*alt_sectors_per_zone*/ {0, 0},
164         /*alt_tracks_per_zone*/ {0, 0},
165         /*alt_tracks_per_lun*/ {0, 0},
166         /*sectors_per_track*/ {0, 0},
167         /*bytes_per_sector*/ {0, 0},
168         /*interleave*/ {0, 0},
169         /*track_skew*/ {0, 0},
170         /*cylinder_skew*/ {0, 0},
171         /*flags*/ 0,
172         /*reserved*/ {0, 0, 0}
173 };
174
175 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
176         /*page_code*/SMS_RIGID_DISK_PAGE,
177         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
178         /*cylinders*/ {0, 0, 0},
179         /*heads*/ CTL_DEFAULT_HEADS,
180         /*start_write_precomp*/ {0, 0, 0},
181         /*start_reduced_current*/ {0, 0, 0},
182         /*step_rate*/ {0, 0},
183         /*landing_zone_cylinder*/ {0, 0, 0},
184         /*rpl*/ SRDP_RPL_DISABLED,
185         /*rotational_offset*/ 0,
186         /*reserved1*/ 0,
187         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
188                            CTL_DEFAULT_ROTATION_RATE & 0xff},
189         /*reserved2*/ {0, 0}
190 };
191
192 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
193         /*page_code*/SMS_RIGID_DISK_PAGE,
194         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
195         /*cylinders*/ {0, 0, 0},
196         /*heads*/ 0,
197         /*start_write_precomp*/ {0, 0, 0},
198         /*start_reduced_current*/ {0, 0, 0},
199         /*step_rate*/ {0, 0},
200         /*landing_zone_cylinder*/ {0, 0, 0},
201         /*rpl*/ 0,
202         /*rotational_offset*/ 0,
203         /*reserved1*/ 0,
204         /*rotation_rate*/ {0, 0},
205         /*reserved2*/ {0, 0}
206 };
207
208 const static struct scsi_caching_page caching_page_default = {
209         /*page_code*/SMS_CACHING_PAGE,
210         /*page_length*/sizeof(struct scsi_caching_page) - 2,
211         /*flags1*/ SCP_DISC | SCP_WCE,
212         /*ret_priority*/ 0,
213         /*disable_pf_transfer_len*/ {0xff, 0xff},
214         /*min_prefetch*/ {0, 0},
215         /*max_prefetch*/ {0xff, 0xff},
216         /*max_pf_ceiling*/ {0xff, 0xff},
217         /*flags2*/ 0,
218         /*cache_segments*/ 0,
219         /*cache_seg_size*/ {0, 0},
220         /*reserved*/ 0,
221         /*non_cache_seg_size*/ {0, 0, 0}
222 };
223
224 const static struct scsi_caching_page caching_page_changeable = {
225         /*page_code*/SMS_CACHING_PAGE,
226         /*page_length*/sizeof(struct scsi_caching_page) - 2,
227         /*flags1*/ SCP_WCE | SCP_RCD,
228         /*ret_priority*/ 0,
229         /*disable_pf_transfer_len*/ {0, 0},
230         /*min_prefetch*/ {0, 0},
231         /*max_prefetch*/ {0, 0},
232         /*max_pf_ceiling*/ {0, 0},
233         /*flags2*/ 0,
234         /*cache_segments*/ 0,
235         /*cache_seg_size*/ {0, 0},
236         /*reserved*/ 0,
237         /*non_cache_seg_size*/ {0, 0, 0}
238 };
239
240 const static struct scsi_control_page control_page_default = {
241         /*page_code*/SMS_CONTROL_MODE_PAGE,
242         /*page_length*/sizeof(struct scsi_control_page) - 2,
243         /*rlec*/0,
244         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245         /*eca_and_aen*/0,
246         /*flags4*/SCP_TAS,
247         /*aen_holdoff_period*/{0, 0},
248         /*busy_timeout_period*/{0, 0},
249         /*extended_selftest_completion_time*/{0, 0}
250 };
251
252 const static struct scsi_control_page control_page_changeable = {
253         /*page_code*/SMS_CONTROL_MODE_PAGE,
254         /*page_length*/sizeof(struct scsi_control_page) - 2,
255         /*rlec*/SCP_DSENSE,
256         /*queue_flags*/SCP_QUEUE_ALG_MASK,
257         /*eca_and_aen*/SCP_SWP,
258         /*flags4*/0,
259         /*aen_holdoff_period*/{0, 0},
260         /*busy_timeout_period*/{0, 0},
261         /*extended_selftest_completion_time*/{0, 0}
262 };
263
264 #define CTL_CEM_LEN     (sizeof(struct scsi_control_ext_page) - 4)
265
266 const static struct scsi_control_ext_page control_ext_page_default = {
267         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268         /*subpage_code*/0x01,
269         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270         /*flags*/0,
271         /*prio*/0,
272         /*max_sense*/0
273 };
274
275 const static struct scsi_control_ext_page control_ext_page_changeable = {
276         /*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277         /*subpage_code*/0x01,
278         /*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279         /*flags*/0,
280         /*prio*/0,
281         /*max_sense*/0
282 };
283
284 const static struct scsi_info_exceptions_page ie_page_default = {
285         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287         /*info_flags*/SIEP_FLAGS_DEXCPT,
288         /*mrie*/0,
289         /*interval_timer*/{0, 0, 0, 0},
290         /*report_count*/{0, 0, 0, 0}
291 };
292
293 const static struct scsi_info_exceptions_page ie_page_changeable = {
294         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296         /*info_flags*/0,
297         /*mrie*/0,
298         /*interval_timer*/{0, 0, 0, 0},
299         /*report_count*/{0, 0, 0, 0}
300 };
301
302 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
303
304 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
305         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
306         /*subpage_code*/0x02,
307         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
308         /*flags*/0,
309         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
310         /*descr*/{}},
311         {{/*flags*/0,
312           /*resource*/0x01,
313           /*reserved*/{0, 0},
314           /*count*/{0, 0, 0, 0}},
315          {/*flags*/0,
316           /*resource*/0x02,
317           /*reserved*/{0, 0},
318           /*count*/{0, 0, 0, 0}},
319          {/*flags*/0,
320           /*resource*/0xf1,
321           /*reserved*/{0, 0},
322           /*count*/{0, 0, 0, 0}},
323          {/*flags*/0,
324           /*resource*/0xf2,
325           /*reserved*/{0, 0},
326           /*count*/{0, 0, 0, 0}}
327         }
328 };
329
330 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
331         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
332         /*subpage_code*/0x02,
333         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
334         /*flags*/0,
335         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
336         /*descr*/{}},
337         {{/*flags*/0,
338           /*resource*/0,
339           /*reserved*/{0, 0},
340           /*count*/{0, 0, 0, 0}},
341          {/*flags*/0,
342           /*resource*/0,
343           /*reserved*/{0, 0},
344           /*count*/{0, 0, 0, 0}},
345          {/*flags*/0,
346           /*resource*/0,
347           /*reserved*/{0, 0},
348           /*count*/{0, 0, 0, 0}},
349          {/*flags*/0,
350           /*resource*/0,
351           /*reserved*/{0, 0},
352           /*count*/{0, 0, 0, 0}}
353         }
354 };
355
356 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
357 static int worker_threads = -1;
358 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
359 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
360     &worker_threads, 1, "Number of worker threads");
361 static int ctl_debug = CTL_DEBUG_NONE;
362 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
363 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
364     &ctl_debug, 0, "Enabled debug flags");
365
366 /*
367  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
368  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
369  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
370  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
371  */
372 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
373
374 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
375                                   int param);
376 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
377 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
378 static int ctl_init(void);
379 void ctl_shutdown(void);
380 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
381 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
382 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
383 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
384                               struct ctl_ooa *ooa_hdr,
385                               struct ctl_ooa_entry *kern_entries);
386 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
387                      struct thread *td);
388 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
389                          struct ctl_be_lun *be_lun);
390 static int ctl_free_lun(struct ctl_lun *lun);
391 static void ctl_create_lun(struct ctl_be_lun *be_lun);
392 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
393
394 static int ctl_do_mode_select(union ctl_io *io);
395 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
396                            uint64_t res_key, uint64_t sa_res_key,
397                            uint8_t type, uint32_t residx,
398                            struct ctl_scsiio *ctsio,
399                            struct scsi_per_res_out *cdb,
400                            struct scsi_per_res_out_parms* param);
401 static void ctl_pro_preempt_other(struct ctl_lun *lun,
402                                   union ctl_ha_msg *msg);
403 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
404 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
405 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
406 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
407 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
408 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
409 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
410                                          int alloc_len);
411 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
412                                          int alloc_len);
413 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
414 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
415 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
416 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
417 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
418 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
419     bool seq);
420 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
421 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
422     union ctl_io *pending_io, union ctl_io *ooa_io);
423 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
424                                 union ctl_io *starting_io);
425 static int ctl_check_blocked(struct ctl_lun *lun);
426 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
427                                 const struct ctl_cmd_entry *entry,
428                                 struct ctl_scsiio *ctsio);
429 static void ctl_failover_lun(struct ctl_lun *lun);
430 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
431                                struct ctl_scsiio *ctsio);
432 static int ctl_scsiio(struct ctl_scsiio *ctsio);
433
434 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
435 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
436                             ctl_ua_type ua_type);
437 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
438                          ctl_ua_type ua_type);
439 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
440 static int ctl_abort_task(union ctl_io *io);
441 static int ctl_abort_task_set(union ctl_io *io);
442 static int ctl_query_task(union ctl_io *io, int task_set);
443 static int ctl_i_t_nexus_reset(union ctl_io *io);
444 static int ctl_query_async_event(union ctl_io *io);
445 static void ctl_run_task(union ctl_io *io);
446 #ifdef CTL_IO_DELAY
447 static void ctl_datamove_timer_wakeup(void *arg);
448 static void ctl_done_timer_wakeup(void *arg);
449 #endif /* CTL_IO_DELAY */
450
451 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
452 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
453 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
454 static void ctl_datamove_remote_write(union ctl_io *io);
455 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
456 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
457 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
458 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
459                                     ctl_ha_dt_cb callback);
460 static void ctl_datamove_remote_read(union ctl_io *io);
461 static void ctl_datamove_remote(union ctl_io *io);
462 static int ctl_process_done(union ctl_io *io);
463 static void ctl_lun_thread(void *arg);
464 static void ctl_thresh_thread(void *arg);
465 static void ctl_work_thread(void *arg);
466 static void ctl_enqueue_incoming(union ctl_io *io);
467 static void ctl_enqueue_rtr(union ctl_io *io);
468 static void ctl_enqueue_done(union ctl_io *io);
469 static void ctl_enqueue_isc(union ctl_io *io);
470 static const struct ctl_cmd_entry *
471     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
472 static const struct ctl_cmd_entry *
473     ctl_validate_command(struct ctl_scsiio *ctsio);
474 static int ctl_cmd_applicable(uint8_t lun_type,
475     const struct ctl_cmd_entry *entry);
476
477 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
478 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
479 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
480 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
481
482 /*
483  * Load the serialization table.  This isn't very pretty, but is probably
484  * the easiest way to do it.
485  */
486 #include "ctl_ser_table.c"
487
488 /*
489  * We only need to define open, close and ioctl routines for this driver.
490  */
491 static struct cdevsw ctl_cdevsw = {
492         .d_version =    D_VERSION,
493         .d_flags =      0,
494         .d_open =       ctl_open,
495         .d_close =      ctl_close,
496         .d_ioctl =      ctl_ioctl,
497         .d_name =       "ctl",
498 };
499
500
501 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
502
503 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
504
505 static moduledata_t ctl_moduledata = {
506         "ctl",
507         ctl_module_event_handler,
508         NULL
509 };
510
511 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
512 MODULE_VERSION(ctl, 1);
513
514 static struct ctl_frontend ha_frontend =
515 {
516         .name = "ha",
517 };
518
519 static void
520 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
521                             union ctl_ha_msg *msg_info)
522 {
523         struct ctl_scsiio *ctsio;
524
525         if (msg_info->hdr.original_sc == NULL) {
526                 printf("%s: original_sc == NULL!\n", __func__);
527                 /* XXX KDM now what? */
528                 return;
529         }
530
531         ctsio = &msg_info->hdr.original_sc->scsiio;
532         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
533         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
534         ctsio->io_hdr.status = msg_info->hdr.status;
535         ctsio->scsi_status = msg_info->scsi.scsi_status;
536         ctsio->sense_len = msg_info->scsi.sense_len;
537         ctsio->sense_residual = msg_info->scsi.sense_residual;
538         ctsio->residual = msg_info->scsi.residual;
539         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
540                msg_info->scsi.sense_len);
541         ctl_enqueue_isc((union ctl_io *)ctsio);
542 }
543
544 static void
545 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
546                                 union ctl_ha_msg *msg_info)
547 {
548         struct ctl_scsiio *ctsio;
549
550         if (msg_info->hdr.serializing_sc == NULL) {
551                 printf("%s: serializing_sc == NULL!\n", __func__);
552                 /* XXX KDM now what? */
553                 return;
554         }
555
556         ctsio = &msg_info->hdr.serializing_sc->scsiio;
557         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
558         ctl_enqueue_isc((union ctl_io *)ctsio);
559 }
560
561 void
562 ctl_isc_announce_lun(struct ctl_lun *lun)
563 {
564         struct ctl_softc *softc = lun->ctl_softc;
565         union ctl_ha_msg *msg;
566         struct ctl_ha_msg_lun_pr_key pr_key;
567         int i, k;
568
569         if (softc->ha_link != CTL_HA_LINK_ONLINE)
570                 return;
571         mtx_lock(&lun->lun_lock);
572         i = sizeof(msg->lun);
573         if (lun->lun_devid)
574                 i += lun->lun_devid->len;
575         i += sizeof(pr_key) * lun->pr_key_count;
576 alloc:
577         mtx_unlock(&lun->lun_lock);
578         msg = malloc(i, M_CTL, M_WAITOK);
579         mtx_lock(&lun->lun_lock);
580         k = sizeof(msg->lun);
581         if (lun->lun_devid)
582                 k += lun->lun_devid->len;
583         k += sizeof(pr_key) * lun->pr_key_count;
584         if (i < k) {
585                 free(msg, M_CTL);
586                 i = k;
587                 goto alloc;
588         }
589         bzero(&msg->lun, sizeof(msg->lun));
590         msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
591         msg->hdr.nexus.targ_lun = lun->lun;
592         msg->hdr.nexus.targ_mapped_lun = lun->lun;
593         msg->lun.flags = lun->flags;
594         msg->lun.pr_generation = lun->PRGeneration;
595         msg->lun.pr_res_idx = lun->pr_res_idx;
596         msg->lun.pr_res_type = lun->res_type;
597         msg->lun.pr_key_count = lun->pr_key_count;
598         i = 0;
599         if (lun->lun_devid) {
600                 msg->lun.lun_devid_len = lun->lun_devid->len;
601                 memcpy(&msg->lun.data[i], lun->lun_devid->data,
602                     msg->lun.lun_devid_len);
603                 i += msg->lun.lun_devid_len;
604         }
605         for (k = 0; k < CTL_MAX_INITIATORS; k++) {
606                 if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
607                         continue;
608                 pr_key.pr_iid = k;
609                 memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
610                 i += sizeof(pr_key);
611         }
612         mtx_unlock(&lun->lun_lock);
613         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
614             M_WAITOK);
615         free(msg, M_CTL);
616
617         if (lun->flags & CTL_LUN_PRIMARY_SC) {
618                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
619                         ctl_isc_announce_mode(lun, -1,
620                             lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
621                             lun->mode_pages.index[i].subpage);
622                 }
623         }
624 }
625
626 void
627 ctl_isc_announce_port(struct ctl_port *port)
628 {
629         struct ctl_softc *softc = control_softc;
630         union ctl_ha_msg *msg;
631         int i;
632
633         if (port->targ_port < softc->port_min ||
634             port->targ_port >= softc->port_max ||
635             softc->ha_link != CTL_HA_LINK_ONLINE)
636                 return;
637         i = sizeof(msg->port) + strlen(port->port_name) + 1;
638         if (port->lun_map)
639                 i += sizeof(uint32_t) * CTL_MAX_LUNS;
640         if (port->port_devid)
641                 i += port->port_devid->len;
642         if (port->target_devid)
643                 i += port->target_devid->len;
644         if (port->init_devid)
645                 i += port->init_devid->len;
646         msg = malloc(i, M_CTL, M_WAITOK);
647         bzero(&msg->port, sizeof(msg->port));
648         msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
649         msg->hdr.nexus.targ_port = port->targ_port;
650         msg->port.port_type = port->port_type;
651         msg->port.physical_port = port->physical_port;
652         msg->port.virtual_port = port->virtual_port;
653         msg->port.status = port->status;
654         i = 0;
655         msg->port.name_len = sprintf(&msg->port.data[i],
656             "%d:%s", softc->ha_id, port->port_name) + 1;
657         i += msg->port.name_len;
658         if (port->lun_map) {
659                 msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
660                 memcpy(&msg->port.data[i], port->lun_map,
661                     msg->port.lun_map_len);
662                 i += msg->port.lun_map_len;
663         }
664         if (port->port_devid) {
665                 msg->port.port_devid_len = port->port_devid->len;
666                 memcpy(&msg->port.data[i], port->port_devid->data,
667                     msg->port.port_devid_len);
668                 i += msg->port.port_devid_len;
669         }
670         if (port->target_devid) {
671                 msg->port.target_devid_len = port->target_devid->len;
672                 memcpy(&msg->port.data[i], port->target_devid->data,
673                     msg->port.target_devid_len);
674                 i += msg->port.target_devid_len;
675         }
676         if (port->init_devid) {
677                 msg->port.init_devid_len = port->init_devid->len;
678                 memcpy(&msg->port.data[i], port->init_devid->data,
679                     msg->port.init_devid_len);
680                 i += msg->port.init_devid_len;
681         }
682         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
683             M_WAITOK);
684         free(msg, M_CTL);
685 }
686
687 void
688 ctl_isc_announce_iid(struct ctl_port *port, int iid)
689 {
690         struct ctl_softc *softc = control_softc;
691         union ctl_ha_msg *msg;
692         int i, l;
693
694         if (port->targ_port < softc->port_min ||
695             port->targ_port >= softc->port_max ||
696             softc->ha_link != CTL_HA_LINK_ONLINE)
697                 return;
698         mtx_lock(&softc->ctl_lock);
699         i = sizeof(msg->iid);
700         l = 0;
701         if (port->wwpn_iid[iid].name)
702                 l = strlen(port->wwpn_iid[iid].name) + 1;
703         i += l;
704         msg = malloc(i, M_CTL, M_NOWAIT);
705         if (msg == NULL) {
706                 mtx_unlock(&softc->ctl_lock);
707                 return;
708         }
709         bzero(&msg->iid, sizeof(msg->iid));
710         msg->hdr.msg_type = CTL_MSG_IID_SYNC;
711         msg->hdr.nexus.targ_port = port->targ_port;
712         msg->hdr.nexus.initid = iid;
713         msg->iid.in_use = port->wwpn_iid[iid].in_use;
714         msg->iid.name_len = l;
715         msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
716         if (port->wwpn_iid[iid].name)
717                 strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
718         mtx_unlock(&softc->ctl_lock);
719         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
720         free(msg, M_CTL);
721 }
722
723 void
724 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
725     uint8_t page, uint8_t subpage)
726 {
727         struct ctl_softc *softc = lun->ctl_softc;
728         union ctl_ha_msg msg;
729         int i;
730
731         if (softc->ha_link != CTL_HA_LINK_ONLINE)
732                 return;
733         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
734                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
735                     page && lun->mode_pages.index[i].subpage == subpage)
736                         break;
737         }
738         if (i == CTL_NUM_MODE_PAGES)
739                 return;
740         bzero(&msg.mode, sizeof(msg.mode));
741         msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
742         msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
743         msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
744         msg.hdr.nexus.targ_lun = lun->lun;
745         msg.hdr.nexus.targ_mapped_lun = lun->lun;
746         msg.mode.page_code = page;
747         msg.mode.subpage = subpage;
748         msg.mode.page_len = lun->mode_pages.index[i].page_len;
749         memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
750             msg.mode.page_len);
751         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
752             M_WAITOK);
753 }
754
755 static void
756 ctl_isc_ha_link_up(struct ctl_softc *softc)
757 {
758         struct ctl_port *port;
759         struct ctl_lun *lun;
760         union ctl_ha_msg msg;
761         int i;
762
763         /* Announce this node parameters to peer for validation. */
764         msg.login.msg_type = CTL_MSG_LOGIN;
765         msg.login.version = CTL_HA_VERSION;
766         msg.login.ha_mode = softc->ha_mode;
767         msg.login.ha_id = softc->ha_id;
768         msg.login.max_luns = CTL_MAX_LUNS;
769         msg.login.max_ports = CTL_MAX_PORTS;
770         msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
771         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
772             M_WAITOK);
773
774         STAILQ_FOREACH(port, &softc->port_list, links) {
775                 ctl_isc_announce_port(port);
776                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
777                         if (port->wwpn_iid[i].in_use)
778                                 ctl_isc_announce_iid(port, i);
779                 }
780         }
781         STAILQ_FOREACH(lun, &softc->lun_list, links)
782                 ctl_isc_announce_lun(lun);
783 }
784
785 static void
786 ctl_isc_ha_link_down(struct ctl_softc *softc)
787 {
788         struct ctl_port *port;
789         struct ctl_lun *lun;
790         union ctl_io *io;
791         int i;
792
793         mtx_lock(&softc->ctl_lock);
794         STAILQ_FOREACH(lun, &softc->lun_list, links) {
795                 mtx_lock(&lun->lun_lock);
796                 if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
797                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
798                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
799                 }
800                 mtx_unlock(&lun->lun_lock);
801
802                 mtx_unlock(&softc->ctl_lock);
803                 io = ctl_alloc_io(softc->othersc_pool);
804                 mtx_lock(&softc->ctl_lock);
805                 ctl_zero_io(io);
806                 io->io_hdr.msg_type = CTL_MSG_FAILOVER;
807                 io->io_hdr.nexus.targ_mapped_lun = lun->lun;
808                 ctl_enqueue_isc(io);
809         }
810
811         STAILQ_FOREACH(port, &softc->port_list, links) {
812                 if (port->targ_port >= softc->port_min &&
813                     port->targ_port < softc->port_max)
814                         continue;
815                 port->status &= ~CTL_PORT_STATUS_ONLINE;
816                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
817                         port->wwpn_iid[i].in_use = 0;
818                         free(port->wwpn_iid[i].name, M_CTL);
819                         port->wwpn_iid[i].name = NULL;
820                 }
821         }
822         mtx_unlock(&softc->ctl_lock);
823 }
824
825 static void
826 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
827 {
828         struct ctl_lun *lun;
829         uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
830
831         mtx_lock(&softc->ctl_lock);
832         if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
833             (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
834                 mtx_lock(&lun->lun_lock);
835                 mtx_unlock(&softc->ctl_lock);
836                 if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
837                     msg->ua.ua_set)
838                         memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
839                 if (msg->ua.ua_all) {
840                         if (msg->ua.ua_set)
841                                 ctl_est_ua_all(lun, iid, msg->ua.ua_type);
842                         else
843                                 ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
844                 } else {
845                         if (msg->ua.ua_set)
846                                 ctl_est_ua(lun, iid, msg->ua.ua_type);
847                         else
848                                 ctl_clr_ua(lun, iid, msg->ua.ua_type);
849                 }
850                 mtx_unlock(&lun->lun_lock);
851         } else
852                 mtx_unlock(&softc->ctl_lock);
853 }
854
855 static void
856 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
857 {
858         struct ctl_lun *lun;
859         struct ctl_ha_msg_lun_pr_key pr_key;
860         int i, k;
861         ctl_lun_flags oflags;
862         uint32_t targ_lun;
863
864         targ_lun = msg->hdr.nexus.targ_mapped_lun;
865         mtx_lock(&softc->ctl_lock);
866         if ((targ_lun >= CTL_MAX_LUNS) ||
867             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
868                 mtx_unlock(&softc->ctl_lock);
869                 return;
870         }
871         mtx_lock(&lun->lun_lock);
872         mtx_unlock(&softc->ctl_lock);
873         if (lun->flags & CTL_LUN_DISABLED) {
874                 mtx_unlock(&lun->lun_lock);
875                 return;
876         }
877         i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
878         if (msg->lun.lun_devid_len != i || (i > 0 &&
879             memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
880                 mtx_unlock(&lun->lun_lock);
881                 printf("%s: Received conflicting HA LUN %d\n",
882                     __func__, msg->hdr.nexus.targ_lun);
883                 return;
884         } else {
885                 /* Record whether peer is primary. */
886                 oflags = lun->flags;
887                 if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
888                     (msg->lun.flags & CTL_LUN_DISABLED) == 0)
889                         lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
890                 else
891                         lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
892                 if (oflags != lun->flags)
893                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
894
895                 /* If peer is primary and we are not -- use data */
896                 if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
897                     (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
898                         lun->PRGeneration = msg->lun.pr_generation;
899                         lun->pr_res_idx = msg->lun.pr_res_idx;
900                         lun->res_type = msg->lun.pr_res_type;
901                         lun->pr_key_count = msg->lun.pr_key_count;
902                         for (k = 0; k < CTL_MAX_INITIATORS; k++)
903                                 ctl_clr_prkey(lun, k);
904                         for (k = 0; k < msg->lun.pr_key_count; k++) {
905                                 memcpy(&pr_key, &msg->lun.data[i],
906                                     sizeof(pr_key));
907                                 ctl_alloc_prkey(lun, pr_key.pr_iid);
908                                 ctl_set_prkey(lun, pr_key.pr_iid,
909                                     pr_key.pr_key);
910                                 i += sizeof(pr_key);
911                         }
912                 }
913
914                 mtx_unlock(&lun->lun_lock);
915                 CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
916                     __func__, msg->hdr.nexus.targ_lun,
917                     (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
918                     "primary" : "secondary"));
919
920                 /* If we are primary but peer doesn't know -- notify */
921                 if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
922                     (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
923                         ctl_isc_announce_lun(lun);
924         }
925 }
926
927 static void
928 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
929 {
930         struct ctl_port *port;
931         struct ctl_lun *lun;
932         int i, new;
933
934         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
935         if (port == NULL) {
936                 CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
937                     msg->hdr.nexus.targ_port));
938                 new = 1;
939                 port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
940                 port->frontend = &ha_frontend;
941                 port->targ_port = msg->hdr.nexus.targ_port;
942         } else if (port->frontend == &ha_frontend) {
943                 CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
944                     msg->hdr.nexus.targ_port));
945                 new = 0;
946         } else {
947                 printf("%s: Received conflicting HA port %d\n",
948                     __func__, msg->hdr.nexus.targ_port);
949                 return;
950         }
951         port->port_type = msg->port.port_type;
952         port->physical_port = msg->port.physical_port;
953         port->virtual_port = msg->port.virtual_port;
954         port->status = msg->port.status;
955         i = 0;
956         free(port->port_name, M_CTL);
957         port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
958             M_CTL);
959         i += msg->port.name_len;
960         if (msg->port.lun_map_len != 0) {
961                 if (port->lun_map == NULL)
962                         port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
963                             M_CTL, M_WAITOK);
964                 memcpy(port->lun_map, &msg->port.data[i],
965                     sizeof(uint32_t) * CTL_MAX_LUNS);
966                 i += msg->port.lun_map_len;
967         } else {
968                 free(port->lun_map, M_CTL);
969                 port->lun_map = NULL;
970         }
971         if (msg->port.port_devid_len != 0) {
972                 if (port->port_devid == NULL ||
973                     port->port_devid->len != msg->port.port_devid_len) {
974                         free(port->port_devid, M_CTL);
975                         port->port_devid = malloc(sizeof(struct ctl_devid) +
976                             msg->port.port_devid_len, M_CTL, M_WAITOK);
977                 }
978                 memcpy(port->port_devid->data, &msg->port.data[i],
979                     msg->port.port_devid_len);
980                 port->port_devid->len = msg->port.port_devid_len;
981                 i += msg->port.port_devid_len;
982         } else {
983                 free(port->port_devid, M_CTL);
984                 port->port_devid = NULL;
985         }
986         if (msg->port.target_devid_len != 0) {
987                 if (port->target_devid == NULL ||
988                     port->target_devid->len != msg->port.target_devid_len) {
989                         free(port->target_devid, M_CTL);
990                         port->target_devid = malloc(sizeof(struct ctl_devid) +
991                             msg->port.target_devid_len, M_CTL, M_WAITOK);
992                 }
993                 memcpy(port->target_devid->data, &msg->port.data[i],
994                     msg->port.target_devid_len);
995                 port->target_devid->len = msg->port.target_devid_len;
996                 i += msg->port.target_devid_len;
997         } else {
998                 free(port->target_devid, M_CTL);
999                 port->target_devid = NULL;
1000         }
1001         if (msg->port.init_devid_len != 0) {
1002                 if (port->init_devid == NULL ||
1003                     port->init_devid->len != msg->port.init_devid_len) {
1004                         free(port->init_devid, M_CTL);
1005                         port->init_devid = malloc(sizeof(struct ctl_devid) +
1006                             msg->port.init_devid_len, M_CTL, M_WAITOK);
1007                 }
1008                 memcpy(port->init_devid->data, &msg->port.data[i],
1009                     msg->port.init_devid_len);
1010                 port->init_devid->len = msg->port.init_devid_len;
1011                 i += msg->port.init_devid_len;
1012         } else {
1013                 free(port->init_devid, M_CTL);
1014                 port->init_devid = NULL;
1015         }
1016         if (new) {
1017                 if (ctl_port_register(port) != 0) {
1018                         printf("%s: ctl_port_register() failed with error\n",
1019                             __func__);
1020                 }
1021         }
1022         mtx_lock(&softc->ctl_lock);
1023         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1024                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1025                         continue;
1026                 mtx_lock(&lun->lun_lock);
1027                 ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1028                 mtx_unlock(&lun->lun_lock);
1029         }
1030         mtx_unlock(&softc->ctl_lock);
1031 }
1032
1033 static void
1034 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1035 {
1036         struct ctl_port *port;
1037         int iid;
1038
1039         port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1040         if (port == NULL) {
1041                 printf("%s: Received IID for unknown port %d\n",
1042                     __func__, msg->hdr.nexus.targ_port);
1043                 return;
1044         }
1045         iid = msg->hdr.nexus.initid;
1046         port->wwpn_iid[iid].in_use = msg->iid.in_use;
1047         port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1048         free(port->wwpn_iid[iid].name, M_CTL);
1049         if (msg->iid.name_len) {
1050                 port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1051                     msg->iid.name_len, M_CTL);
1052         } else
1053                 port->wwpn_iid[iid].name = NULL;
1054 }
1055
1056 static void
1057 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1058 {
1059
1060         if (msg->login.version != CTL_HA_VERSION) {
1061                 printf("CTL HA peers have different versions %d != %d\n",
1062                     msg->login.version, CTL_HA_VERSION);
1063                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1064                 return;
1065         }
1066         if (msg->login.ha_mode != softc->ha_mode) {
1067                 printf("CTL HA peers have different ha_mode %d != %d\n",
1068                     msg->login.ha_mode, softc->ha_mode);
1069                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1070                 return;
1071         }
1072         if (msg->login.ha_id == softc->ha_id) {
1073                 printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1074                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1075                 return;
1076         }
1077         if (msg->login.max_luns != CTL_MAX_LUNS ||
1078             msg->login.max_ports != CTL_MAX_PORTS ||
1079             msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1080                 printf("CTL HA peers have different limits\n");
1081                 ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1082                 return;
1083         }
1084 }
1085
1086 static void
1087 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1088 {
1089         struct ctl_lun *lun;
1090         int i;
1091         uint32_t initidx, targ_lun;
1092
1093         targ_lun = msg->hdr.nexus.targ_mapped_lun;
1094         mtx_lock(&softc->ctl_lock);
1095         if ((targ_lun >= CTL_MAX_LUNS) ||
1096             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1097                 mtx_unlock(&softc->ctl_lock);
1098                 return;
1099         }
1100         mtx_lock(&lun->lun_lock);
1101         mtx_unlock(&softc->ctl_lock);
1102         if (lun->flags & CTL_LUN_DISABLED) {
1103                 mtx_unlock(&lun->lun_lock);
1104                 return;
1105         }
1106         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1107                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1108                     msg->mode.page_code &&
1109                     lun->mode_pages.index[i].subpage == msg->mode.subpage)
1110                         break;
1111         }
1112         if (i == CTL_NUM_MODE_PAGES) {
1113                 mtx_unlock(&lun->lun_lock);
1114                 return;
1115         }
1116         memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1117             lun->mode_pages.index[i].page_len);
1118         initidx = ctl_get_initindex(&msg->hdr.nexus);
1119         if (initidx != -1)
1120                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1121         mtx_unlock(&lun->lun_lock);
1122 }
1123
1124 /*
1125  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1126  * subsystem come in here.
1127  */
1128 static void
1129 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1130 {
1131         struct ctl_softc *softc;
1132         union ctl_io *io;
1133         struct ctl_prio *presio;
1134         ctl_ha_status isc_status;
1135
1136         softc = control_softc;
1137         CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1138         if (event == CTL_HA_EVT_MSG_RECV) {
1139                 union ctl_ha_msg *msg, msgbuf;
1140
1141                 if (param > sizeof(msgbuf))
1142                         msg = malloc(param, M_CTL, M_WAITOK);
1143                 else
1144                         msg = &msgbuf;
1145                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1146                     M_WAITOK);
1147                 if (isc_status != CTL_HA_STATUS_SUCCESS) {
1148                         printf("%s: Error receiving message: %d\n",
1149                             __func__, isc_status);
1150                         if (msg != &msgbuf)
1151                                 free(msg, M_CTL);
1152                         return;
1153                 }
1154
1155                 CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1156                 switch (msg->hdr.msg_type) {
1157                 case CTL_MSG_SERIALIZE:
1158                         io = ctl_alloc_io(softc->othersc_pool);
1159                         ctl_zero_io(io);
1160                         // populate ctsio from msg
1161                         io->io_hdr.io_type = CTL_IO_SCSI;
1162                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1163                         io->io_hdr.original_sc = msg->hdr.original_sc;
1164                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1165                                             CTL_FLAG_IO_ACTIVE;
1166                         /*
1167                          * If we're in serialization-only mode, we don't
1168                          * want to go through full done processing.  Thus
1169                          * the COPY flag.
1170                          *
1171                          * XXX KDM add another flag that is more specific.
1172                          */
1173                         if (softc->ha_mode != CTL_HA_MODE_XFER)
1174                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1175                         io->io_hdr.nexus = msg->hdr.nexus;
1176 #if 0
1177                         printf("port %u, iid %u, lun %u\n",
1178                                io->io_hdr.nexus.targ_port,
1179                                io->io_hdr.nexus.initid,
1180                                io->io_hdr.nexus.targ_lun);
1181 #endif
1182                         io->scsiio.tag_num = msg->scsi.tag_num;
1183                         io->scsiio.tag_type = msg->scsi.tag_type;
1184 #ifdef CTL_TIME_IO
1185                         io->io_hdr.start_time = time_uptime;
1186                         getbintime(&io->io_hdr.start_bt);
1187 #endif /* CTL_TIME_IO */
1188                         io->scsiio.cdb_len = msg->scsi.cdb_len;
1189                         memcpy(io->scsiio.cdb, msg->scsi.cdb,
1190                                CTL_MAX_CDBLEN);
1191                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
1192                                 const struct ctl_cmd_entry *entry;
1193
1194                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1195                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1196                                 io->io_hdr.flags |=
1197                                         entry->flags & CTL_FLAG_DATA_MASK;
1198                         }
1199                         ctl_enqueue_isc(io);
1200                         break;
1201
1202                 /* Performed on the Originating SC, XFER mode only */
1203                 case CTL_MSG_DATAMOVE: {
1204                         struct ctl_sg_entry *sgl;
1205                         int i, j;
1206
1207                         io = msg->hdr.original_sc;
1208                         if (io == NULL) {
1209                                 printf("%s: original_sc == NULL!\n", __func__);
1210                                 /* XXX KDM do something here */
1211                                 break;
1212                         }
1213                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1214                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1215                         /*
1216                          * Keep track of this, we need to send it back over
1217                          * when the datamove is complete.
1218                          */
1219                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1220                         if (msg->hdr.status == CTL_SUCCESS)
1221                                 io->io_hdr.status = msg->hdr.status;
1222
1223                         if (msg->dt.sg_sequence == 0) {
1224                                 i = msg->dt.kern_sg_entries +
1225                                     msg->dt.kern_data_len /
1226                                     CTL_HA_DATAMOVE_SEGMENT + 1;
1227                                 sgl = malloc(sizeof(*sgl) * i, M_CTL,
1228                                     M_WAITOK | M_ZERO);
1229                                 io->io_hdr.remote_sglist = sgl;
1230                                 io->io_hdr.local_sglist =
1231                                     &sgl[msg->dt.kern_sg_entries];
1232
1233                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1234
1235                                 io->scsiio.kern_sg_entries =
1236                                         msg->dt.kern_sg_entries;
1237                                 io->scsiio.rem_sg_entries =
1238                                         msg->dt.kern_sg_entries;
1239                                 io->scsiio.kern_data_len =
1240                                         msg->dt.kern_data_len;
1241                                 io->scsiio.kern_total_len =
1242                                         msg->dt.kern_total_len;
1243                                 io->scsiio.kern_data_resid =
1244                                         msg->dt.kern_data_resid;
1245                                 io->scsiio.kern_rel_offset =
1246                                         msg->dt.kern_rel_offset;
1247                                 io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1248                                 io->io_hdr.flags |= msg->dt.flags &
1249                                     CTL_FLAG_BUS_ADDR;
1250                         } else
1251                                 sgl = (struct ctl_sg_entry *)
1252                                         io->scsiio.kern_data_ptr;
1253
1254                         for (i = msg->dt.sent_sg_entries, j = 0;
1255                              i < (msg->dt.sent_sg_entries +
1256                              msg->dt.cur_sg_entries); i++, j++) {
1257                                 sgl[i].addr = msg->dt.sg_list[j].addr;
1258                                 sgl[i].len = msg->dt.sg_list[j].len;
1259
1260 #if 0
1261                                 printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1262                                     __func__, sgl[i].addr, sgl[i].len, j, i);
1263 #endif
1264                         }
1265
1266                         /*
1267                          * If this is the last piece of the I/O, we've got
1268                          * the full S/G list.  Queue processing in the thread.
1269                          * Otherwise wait for the next piece.
1270                          */
1271                         if (msg->dt.sg_last != 0)
1272                                 ctl_enqueue_isc(io);
1273                         break;
1274                 }
1275                 /* Performed on the Serializing (primary) SC, XFER mode only */
1276                 case CTL_MSG_DATAMOVE_DONE: {
1277                         if (msg->hdr.serializing_sc == NULL) {
1278                                 printf("%s: serializing_sc == NULL!\n",
1279                                        __func__);
1280                                 /* XXX KDM now what? */
1281                                 break;
1282                         }
1283                         /*
1284                          * We grab the sense information here in case
1285                          * there was a failure, so we can return status
1286                          * back to the initiator.
1287                          */
1288                         io = msg->hdr.serializing_sc;
1289                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1290                         io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1291                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1292                         io->io_hdr.port_status = msg->scsi.fetd_status;
1293                         io->scsiio.residual = msg->scsi.residual;
1294                         if (msg->hdr.status != CTL_STATUS_NONE) {
1295                                 io->io_hdr.status = msg->hdr.status;
1296                                 io->scsiio.scsi_status = msg->scsi.scsi_status;
1297                                 io->scsiio.sense_len = msg->scsi.sense_len;
1298                                 io->scsiio.sense_residual =msg->scsi.sense_residual;
1299                                 memcpy(&io->scsiio.sense_data,
1300                                     &msg->scsi.sense_data,
1301                                     msg->scsi.sense_len);
1302                                 if (msg->hdr.status == CTL_SUCCESS)
1303                                         io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1304                         }
1305                         ctl_enqueue_isc(io);
1306                         break;
1307                 }
1308
1309                 /* Preformed on Originating SC, SER_ONLY mode */
1310                 case CTL_MSG_R2R:
1311                         io = msg->hdr.original_sc;
1312                         if (io == NULL) {
1313                                 printf("%s: original_sc == NULL!\n",
1314                                     __func__);
1315                                 break;
1316                         }
1317                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1318                         io->io_hdr.msg_type = CTL_MSG_R2R;
1319                         io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1320                         ctl_enqueue_isc(io);
1321                         break;
1322
1323                 /*
1324                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1325                  * mode.
1326                  * Performed on the Originating (i.e. secondary) SC in XFER
1327                  * mode
1328                  */
1329                 case CTL_MSG_FINISH_IO:
1330                         if (softc->ha_mode == CTL_HA_MODE_XFER)
1331                                 ctl_isc_handler_finish_xfer(softc, msg);
1332                         else
1333                                 ctl_isc_handler_finish_ser_only(softc, msg);
1334                         break;
1335
1336                 /* Preformed on Originating SC */
1337                 case CTL_MSG_BAD_JUJU:
1338                         io = msg->hdr.original_sc;
1339                         if (io == NULL) {
1340                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
1341                                        __func__);
1342                                 break;
1343                         }
1344                         ctl_copy_sense_data(msg, io);
1345                         /*
1346                          * IO should have already been cleaned up on other
1347                          * SC so clear this flag so we won't send a message
1348                          * back to finish the IO there.
1349                          */
1350                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1351                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1352
1353                         /* io = msg->hdr.serializing_sc; */
1354                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1355                         ctl_enqueue_isc(io);
1356                         break;
1357
1358                 /* Handle resets sent from the other side */
1359                 case CTL_MSG_MANAGE_TASKS: {
1360                         struct ctl_taskio *taskio;
1361                         taskio = (struct ctl_taskio *)ctl_alloc_io(
1362                             softc->othersc_pool);
1363                         ctl_zero_io((union ctl_io *)taskio);
1364                         taskio->io_hdr.io_type = CTL_IO_TASK;
1365                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1366                         taskio->io_hdr.nexus = msg->hdr.nexus;
1367                         taskio->task_action = msg->task.task_action;
1368                         taskio->tag_num = msg->task.tag_num;
1369                         taskio->tag_type = msg->task.tag_type;
1370 #ifdef CTL_TIME_IO
1371                         taskio->io_hdr.start_time = time_uptime;
1372                         getbintime(&taskio->io_hdr.start_bt);
1373 #endif /* CTL_TIME_IO */
1374                         ctl_run_task((union ctl_io *)taskio);
1375                         break;
1376                 }
1377                 /* Persistent Reserve action which needs attention */
1378                 case CTL_MSG_PERS_ACTION:
1379                         presio = (struct ctl_prio *)ctl_alloc_io(
1380                             softc->othersc_pool);
1381                         ctl_zero_io((union ctl_io *)presio);
1382                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1383                         presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1384                         presio->io_hdr.nexus = msg->hdr.nexus;
1385                         presio->pr_msg = msg->pr;
1386                         ctl_enqueue_isc((union ctl_io *)presio);
1387                         break;
1388                 case CTL_MSG_UA:
1389                         ctl_isc_ua(softc, msg, param);
1390                         break;
1391                 case CTL_MSG_PORT_SYNC:
1392                         ctl_isc_port_sync(softc, msg, param);
1393                         break;
1394                 case CTL_MSG_LUN_SYNC:
1395                         ctl_isc_lun_sync(softc, msg, param);
1396                         break;
1397                 case CTL_MSG_IID_SYNC:
1398                         ctl_isc_iid_sync(softc, msg, param);
1399                         break;
1400                 case CTL_MSG_LOGIN:
1401                         ctl_isc_login(softc, msg, param);
1402                         break;
1403                 case CTL_MSG_MODE_SYNC:
1404                         ctl_isc_mode_sync(softc, msg, param);
1405                         break;
1406                 default:
1407                         printf("Received HA message of unknown type %d\n",
1408                             msg->hdr.msg_type);
1409                         ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1410                         break;
1411                 }
1412                 if (msg != &msgbuf)
1413                         free(msg, M_CTL);
1414         } else if (event == CTL_HA_EVT_LINK_CHANGE) {
1415                 printf("CTL: HA link status changed from %d to %d\n",
1416                     softc->ha_link, param);
1417                 if (param == softc->ha_link)
1418                         return;
1419                 if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1420                         softc->ha_link = param;
1421                         ctl_isc_ha_link_down(softc);
1422                 } else {
1423                         softc->ha_link = param;
1424                         if (softc->ha_link == CTL_HA_LINK_ONLINE)
1425                                 ctl_isc_ha_link_up(softc);
1426                 }
1427                 return;
1428         } else {
1429                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
1430                 return;
1431         }
1432 }
1433
1434 static void
1435 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1436 {
1437
1438         memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1439             src->scsi.sense_len);
1440         dest->scsiio.scsi_status = src->scsi.scsi_status;
1441         dest->scsiio.sense_len = src->scsi.sense_len;
1442         dest->io_hdr.status = src->hdr.status;
1443 }
1444
1445 static void
1446 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1447 {
1448
1449         memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1450             src->scsiio.sense_len);
1451         dest->scsi.scsi_status = src->scsiio.scsi_status;
1452         dest->scsi.sense_len = src->scsiio.sense_len;
1453         dest->hdr.status = src->io_hdr.status;
1454 }
1455
1456 void
1457 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1458 {
1459         struct ctl_softc *softc = lun->ctl_softc;
1460         ctl_ua_type *pu;
1461
1462         if (initidx < softc->init_min || initidx >= softc->init_max)
1463                 return;
1464         mtx_assert(&lun->lun_lock, MA_OWNED);
1465         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1466         if (pu == NULL)
1467                 return;
1468         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1469 }
1470
1471 void
1472 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1473 {
1474         int i;
1475
1476         mtx_assert(&lun->lun_lock, MA_OWNED);
1477         if (lun->pending_ua[port] == NULL)
1478                 return;
1479         for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1480                 if (port * CTL_MAX_INIT_PER_PORT + i == except)
1481                         continue;
1482                 lun->pending_ua[port][i] |= ua;
1483         }
1484 }
1485
1486 void
1487 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1488 {
1489         struct ctl_softc *softc = lun->ctl_softc;
1490         int i;
1491
1492         mtx_assert(&lun->lun_lock, MA_OWNED);
1493         for (i = softc->port_min; i < softc->port_max; i++)
1494                 ctl_est_ua_port(lun, i, except, ua);
1495 }
1496
1497 void
1498 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1499 {
1500         struct ctl_softc *softc = lun->ctl_softc;
1501         ctl_ua_type *pu;
1502
1503         if (initidx < softc->init_min || initidx >= softc->init_max)
1504                 return;
1505         mtx_assert(&lun->lun_lock, MA_OWNED);
1506         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1507         if (pu == NULL)
1508                 return;
1509         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1510 }
1511
1512 void
1513 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1514 {
1515         struct ctl_softc *softc = lun->ctl_softc;
1516         int i, j;
1517
1518         mtx_assert(&lun->lun_lock, MA_OWNED);
1519         for (i = softc->port_min; i < softc->port_max; i++) {
1520                 if (lun->pending_ua[i] == NULL)
1521                         continue;
1522                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1523                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1524                                 continue;
1525                         lun->pending_ua[i][j] &= ~ua;
1526                 }
1527         }
1528 }
1529
1530 void
1531 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1532     ctl_ua_type ua_type)
1533 {
1534         struct ctl_lun *lun;
1535
1536         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1537         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1538                 mtx_lock(&lun->lun_lock);
1539                 ctl_clr_ua(lun, initidx, ua_type);
1540                 mtx_unlock(&lun->lun_lock);
1541         }
1542 }
1543
1544 static int
1545 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1546 {
1547         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1548         struct ctl_lun *lun;
1549         struct ctl_lun_req ireq;
1550         int error, value;
1551
1552         value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1553         error = sysctl_handle_int(oidp, &value, 0, req);
1554         if ((error != 0) || (req->newptr == NULL))
1555                 return (error);
1556
1557         mtx_lock(&softc->ctl_lock);
1558         if (value == 0)
1559                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1560         else
1561                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1562         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1563                 mtx_unlock(&softc->ctl_lock);
1564                 bzero(&ireq, sizeof(ireq));
1565                 ireq.reqtype = CTL_LUNREQ_MODIFY;
1566                 ireq.reqdata.modify.lun_id = lun->lun;
1567                 lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1568                     curthread);
1569                 if (ireq.status != CTL_LUN_OK) {
1570                         printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1571                             __func__, ireq.status, ireq.error_str);
1572                 }
1573                 mtx_lock(&softc->ctl_lock);
1574         }
1575         mtx_unlock(&softc->ctl_lock);
1576         return (0);
1577 }
1578
1579 static int
1580 ctl_init(void)
1581 {
1582         struct ctl_softc *softc;
1583         void *other_pool;
1584         int i, error, retval;
1585
1586         retval = 0;
1587         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1588                                M_WAITOK | M_ZERO);
1589         softc = control_softc;
1590
1591         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1592                               "cam/ctl");
1593
1594         softc->dev->si_drv1 = softc;
1595
1596         sysctl_ctx_init(&softc->sysctl_ctx);
1597         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1598                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1599                 CTLFLAG_RD, 0, "CAM Target Layer");
1600
1601         if (softc->sysctl_tree == NULL) {
1602                 printf("%s: unable to allocate sysctl tree\n", __func__);
1603                 destroy_dev(softc->dev);
1604                 free(control_softc, M_DEVBUF);
1605                 control_softc = NULL;
1606                 return (ENOMEM);
1607         }
1608
1609         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1610         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1611             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1612         softc->open_count = 0;
1613
1614         /*
1615          * Default to actually sending a SYNCHRONIZE CACHE command down to
1616          * the drive.
1617          */
1618         softc->flags = CTL_FLAG_REAL_SYNC;
1619
1620         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1621             OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1622             "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1623
1624         /*
1625          * In Copan's HA scheme, the "master" and "slave" roles are
1626          * figured out through the slot the controller is in.  Although it
1627          * is an active/active system, someone has to be in charge.
1628          */
1629         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1630             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1631             "HA head ID (0 - no HA)");
1632         if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1633                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1634                 softc->is_single = 1;
1635                 softc->port_cnt = CTL_MAX_PORTS;
1636                 softc->port_min = 0;
1637         } else {
1638                 softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1639                 softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1640         }
1641         softc->port_max = softc->port_min + softc->port_cnt;
1642         softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1643         softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1644
1645         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1646             OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1647             "HA link state (0 - offline, 1 - unknown, 2 - online)");
1648
1649         STAILQ_INIT(&softc->lun_list);
1650         STAILQ_INIT(&softc->pending_lun_queue);
1651         STAILQ_INIT(&softc->fe_list);
1652         STAILQ_INIT(&softc->port_list);
1653         STAILQ_INIT(&softc->be_list);
1654         ctl_tpc_init(softc);
1655
1656         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1657                             &other_pool) != 0)
1658         {
1659                 printf("ctl: can't allocate %d entry other SC pool, "
1660                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1661                 return (ENOMEM);
1662         }
1663         softc->othersc_pool = other_pool;
1664
1665         if (worker_threads <= 0)
1666                 worker_threads = max(1, mp_ncpus / 4);
1667         if (worker_threads > CTL_MAX_THREADS)
1668                 worker_threads = CTL_MAX_THREADS;
1669
1670         for (i = 0; i < worker_threads; i++) {
1671                 struct ctl_thread *thr = &softc->threads[i];
1672
1673                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1674                 thr->ctl_softc = softc;
1675                 STAILQ_INIT(&thr->incoming_queue);
1676                 STAILQ_INIT(&thr->rtr_queue);
1677                 STAILQ_INIT(&thr->done_queue);
1678                 STAILQ_INIT(&thr->isc_queue);
1679
1680                 error = kproc_kthread_add(ctl_work_thread, thr,
1681                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1682                 if (error != 0) {
1683                         printf("error creating CTL work thread!\n");
1684                         ctl_pool_free(other_pool);
1685                         return (error);
1686                 }
1687         }
1688         error = kproc_kthread_add(ctl_lun_thread, softc,
1689             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1690         if (error != 0) {
1691                 printf("error creating CTL lun thread!\n");
1692                 ctl_pool_free(other_pool);
1693                 return (error);
1694         }
1695         error = kproc_kthread_add(ctl_thresh_thread, softc,
1696             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1697         if (error != 0) {
1698                 printf("error creating CTL threshold thread!\n");
1699                 ctl_pool_free(other_pool);
1700                 return (error);
1701         }
1702
1703         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1704             OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1705             softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1706
1707         if (softc->is_single == 0) {
1708                 ctl_frontend_register(&ha_frontend);
1709                 if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1710                         printf("ctl_init: ctl_ha_msg_init failed.\n");
1711                         softc->is_single = 1;
1712                 } else
1713                 if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1714                     != CTL_HA_STATUS_SUCCESS) {
1715                         printf("ctl_init: ctl_ha_msg_register failed.\n");
1716                         softc->is_single = 1;
1717                 }
1718         }
1719         return (0);
1720 }
1721
1722 void
1723 ctl_shutdown(void)
1724 {
1725         struct ctl_softc *softc;
1726         struct ctl_lun *lun, *next_lun;
1727
1728         softc = (struct ctl_softc *)control_softc;
1729
1730         if (softc->is_single == 0) {
1731                 ctl_ha_msg_shutdown(softc);
1732                 if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1733                     != CTL_HA_STATUS_SUCCESS)
1734                         printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1735                 if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1736                         printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1737                 ctl_frontend_deregister(&ha_frontend);
1738         }
1739
1740         mtx_lock(&softc->ctl_lock);
1741
1742         /*
1743          * Free up each LUN.
1744          */
1745         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1746                 next_lun = STAILQ_NEXT(lun, links);
1747                 ctl_free_lun(lun);
1748         }
1749
1750         mtx_unlock(&softc->ctl_lock);
1751
1752 #if 0
1753         ctl_shutdown_thread(softc->work_thread);
1754         mtx_destroy(&softc->queue_lock);
1755 #endif
1756
1757         ctl_tpc_shutdown(softc);
1758         uma_zdestroy(softc->io_zone);
1759         mtx_destroy(&softc->ctl_lock);
1760
1761         destroy_dev(softc->dev);
1762
1763         sysctl_ctx_free(&softc->sysctl_ctx);
1764
1765         free(control_softc, M_DEVBUF);
1766         control_softc = NULL;
1767 }
1768
1769 static int
1770 ctl_module_event_handler(module_t mod, int what, void *arg)
1771 {
1772
1773         switch (what) {
1774         case MOD_LOAD:
1775                 return (ctl_init());
1776         case MOD_UNLOAD:
1777                 return (EBUSY);
1778         default:
1779                 return (EOPNOTSUPP);
1780         }
1781 }
1782
1783 /*
1784  * XXX KDM should we do some access checks here?  Bump a reference count to
1785  * prevent a CTL module from being unloaded while someone has it open?
1786  */
1787 static int
1788 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1789 {
1790         return (0);
1791 }
1792
1793 static int
1794 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1795 {
1796         return (0);
1797 }
1798
1799 /*
1800  * Remove an initiator by port number and initiator ID.
1801  * Returns 0 for success, -1 for failure.
1802  */
1803 int
1804 ctl_remove_initiator(struct ctl_port *port, int iid)
1805 {
1806         struct ctl_softc *softc = control_softc;
1807
1808         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1809
1810         if (iid > CTL_MAX_INIT_PER_PORT) {
1811                 printf("%s: initiator ID %u > maximun %u!\n",
1812                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1813                 return (-1);
1814         }
1815
1816         mtx_lock(&softc->ctl_lock);
1817         port->wwpn_iid[iid].in_use--;
1818         port->wwpn_iid[iid].last_use = time_uptime;
1819         mtx_unlock(&softc->ctl_lock);
1820         ctl_isc_announce_iid(port, iid);
1821
1822         return (0);
1823 }
1824
1825 /*
1826  * Add an initiator to the initiator map.
1827  * Returns iid for success, < 0 for failure.
1828  */
1829 int
1830 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1831 {
1832         struct ctl_softc *softc = control_softc;
1833         time_t best_time;
1834         int i, best;
1835
1836         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1837
1838         if (iid >= CTL_MAX_INIT_PER_PORT) {
1839                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1840                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1841                 free(name, M_CTL);
1842                 return (-1);
1843         }
1844
1845         mtx_lock(&softc->ctl_lock);
1846
1847         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1848                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1849                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1850                                 iid = i;
1851                                 break;
1852                         }
1853                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1854                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1855                                 iid = i;
1856                                 break;
1857                         }
1858                 }
1859         }
1860
1861         if (iid < 0) {
1862                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1863                         if (port->wwpn_iid[i].in_use == 0 &&
1864                             port->wwpn_iid[i].wwpn == 0 &&
1865                             port->wwpn_iid[i].name == NULL) {
1866                                 iid = i;
1867                                 break;
1868                         }
1869                 }
1870         }
1871
1872         if (iid < 0) {
1873                 best = -1;
1874                 best_time = INT32_MAX;
1875                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1876                         if (port->wwpn_iid[i].in_use == 0) {
1877                                 if (port->wwpn_iid[i].last_use < best_time) {
1878                                         best = i;
1879                                         best_time = port->wwpn_iid[i].last_use;
1880                                 }
1881                         }
1882                 }
1883                 iid = best;
1884         }
1885
1886         if (iid < 0) {
1887                 mtx_unlock(&softc->ctl_lock);
1888                 free(name, M_CTL);
1889                 return (-2);
1890         }
1891
1892         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1893                 /*
1894                  * This is not an error yet.
1895                  */
1896                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1897 #if 0
1898                         printf("%s: port %d iid %u WWPN %#jx arrived"
1899                             " again\n", __func__, port->targ_port,
1900                             iid, (uintmax_t)wwpn);
1901 #endif
1902                         goto take;
1903                 }
1904                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1905                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1906 #if 0
1907                         printf("%s: port %d iid %u name '%s' arrived"
1908                             " again\n", __func__, port->targ_port,
1909                             iid, name);
1910 #endif
1911                         goto take;
1912                 }
1913
1914                 /*
1915                  * This is an error, but what do we do about it?  The
1916                  * driver is telling us we have a new WWPN for this
1917                  * initiator ID, so we pretty much need to use it.
1918                  */
1919                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1920                     " but WWPN %#jx '%s' is still at that address\n",
1921                     __func__, port->targ_port, iid, wwpn, name,
1922                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1923                     port->wwpn_iid[iid].name);
1924
1925                 /*
1926                  * XXX KDM clear have_ca and ua_pending on each LUN for
1927                  * this initiator.
1928                  */
1929         }
1930 take:
1931         free(port->wwpn_iid[iid].name, M_CTL);
1932         port->wwpn_iid[iid].name = name;
1933         port->wwpn_iid[iid].wwpn = wwpn;
1934         port->wwpn_iid[iid].in_use++;
1935         mtx_unlock(&softc->ctl_lock);
1936         ctl_isc_announce_iid(port, iid);
1937
1938         return (iid);
1939 }
1940
1941 static int
1942 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1943 {
1944         int len;
1945
1946         switch (port->port_type) {
1947         case CTL_PORT_FC:
1948         {
1949                 struct scsi_transportid_fcp *id =
1950                     (struct scsi_transportid_fcp *)buf;
1951                 if (port->wwpn_iid[iid].wwpn == 0)
1952                         return (0);
1953                 memset(id, 0, sizeof(*id));
1954                 id->format_protocol = SCSI_PROTO_FC;
1955                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1956                 return (sizeof(*id));
1957         }
1958         case CTL_PORT_ISCSI:
1959         {
1960                 struct scsi_transportid_iscsi_port *id =
1961                     (struct scsi_transportid_iscsi_port *)buf;
1962                 if (port->wwpn_iid[iid].name == NULL)
1963                         return (0);
1964                 memset(id, 0, 256);
1965                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1966                     SCSI_PROTO_ISCSI;
1967                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1968                 len = roundup2(min(len, 252), 4);
1969                 scsi_ulto2b(len, id->additional_length);
1970                 return (sizeof(*id) + len);
1971         }
1972         case CTL_PORT_SAS:
1973         {
1974                 struct scsi_transportid_sas *id =
1975                     (struct scsi_transportid_sas *)buf;
1976                 if (port->wwpn_iid[iid].wwpn == 0)
1977                         return (0);
1978                 memset(id, 0, sizeof(*id));
1979                 id->format_protocol = SCSI_PROTO_SAS;
1980                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1981                 return (sizeof(*id));
1982         }
1983         default:
1984         {
1985                 struct scsi_transportid_spi *id =
1986                     (struct scsi_transportid_spi *)buf;
1987                 memset(id, 0, sizeof(*id));
1988                 id->format_protocol = SCSI_PROTO_SPI;
1989                 scsi_ulto2b(iid, id->scsi_addr);
1990                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1991                 return (sizeof(*id));
1992         }
1993         }
1994 }
1995
1996 /*
1997  * Serialize a command that went down the "wrong" side, and so was sent to
1998  * this controller for execution.  The logic is a little different than the
1999  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2000  * sent back to the other side, but in the success case, we execute the
2001  * command on this side (XFER mode) or tell the other side to execute it
2002  * (SER_ONLY mode).
2003  */
2004 static int
2005 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2006 {
2007         struct ctl_softc *softc;
2008         union ctl_ha_msg msg_info;
2009         struct ctl_lun *lun;
2010         const struct ctl_cmd_entry *entry;
2011         int retval = 0;
2012         uint32_t targ_lun;
2013
2014         softc = control_softc;
2015
2016         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2017         mtx_lock(&softc->ctl_lock);
2018         if ((targ_lun < CTL_MAX_LUNS) &&
2019             ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2020                 mtx_lock(&lun->lun_lock);
2021                 mtx_unlock(&softc->ctl_lock);
2022                 /*
2023                  * If the LUN is invalid, pretend that it doesn't exist.
2024                  * It will go away as soon as all pending I/O has been
2025                  * completed.
2026                  */
2027                 if (lun->flags & CTL_LUN_DISABLED) {
2028                         mtx_unlock(&lun->lun_lock);
2029                         lun = NULL;
2030                 }
2031         } else {
2032                 mtx_unlock(&softc->ctl_lock);
2033                 lun = NULL;
2034         }
2035         if (lun == NULL) {
2036                 /*
2037                  * The other node would not send this request to us unless
2038                  * received announce that we are primary node for this LUN.
2039                  * If this LUN does not exist now, it is probably result of
2040                  * a race, so respond to initiator in the most opaque way.
2041                  */
2042                 ctl_set_busy(ctsio);
2043                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2044                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2045                 msg_info.hdr.serializing_sc = NULL;
2046                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2047                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2048                     sizeof(msg_info.scsi), M_WAITOK);
2049                 return(1);
2050         }
2051
2052         entry = ctl_get_cmd_entry(ctsio, NULL);
2053         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2054                 mtx_unlock(&lun->lun_lock);
2055                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2056                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2057                 msg_info.hdr.serializing_sc = NULL;
2058                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2059                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2060                     sizeof(msg_info.scsi), M_WAITOK);
2061                 return(1);
2062         }
2063
2064         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2065         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2066
2067         /*
2068          * Every I/O goes into the OOA queue for a
2069          * particular LUN, and stays there until completion.
2070          */
2071 #ifdef CTL_TIME_IO
2072         if (TAILQ_EMPTY(&lun->ooa_queue))
2073                 lun->idle_time += getsbinuptime() - lun->last_busy;
2074 #endif
2075         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2076
2077         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2078                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2079                  ooa_links))) {
2080         case CTL_ACTION_BLOCK:
2081                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2082                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2083                                   blocked_links);
2084                 mtx_unlock(&lun->lun_lock);
2085                 break;
2086         case CTL_ACTION_PASS:
2087         case CTL_ACTION_SKIP:
2088                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
2089                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2090                         ctl_enqueue_rtr((union ctl_io *)ctsio);
2091                         mtx_unlock(&lun->lun_lock);
2092                 } else {
2093                         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2094                         mtx_unlock(&lun->lun_lock);
2095
2096                         /* send msg back to other side */
2097                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2098                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2099                         msg_info.hdr.msg_type = CTL_MSG_R2R;
2100                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2101                             sizeof(msg_info.hdr), M_WAITOK);
2102                 }
2103                 break;
2104         case CTL_ACTION_OVERLAP:
2105                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2106                 mtx_unlock(&lun->lun_lock);
2107                 retval = 1;
2108
2109                 ctl_set_overlapped_cmd(ctsio);
2110                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2111                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2112                 msg_info.hdr.serializing_sc = NULL;
2113                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2114                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2115                     sizeof(msg_info.scsi), M_WAITOK);
2116                 break;
2117         case CTL_ACTION_OVERLAP_TAG:
2118                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2119                 mtx_unlock(&lun->lun_lock);
2120                 retval = 1;
2121                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2122                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2123                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2124                 msg_info.hdr.serializing_sc = NULL;
2125                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2126                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2127                     sizeof(msg_info.scsi), M_WAITOK);
2128                 break;
2129         case CTL_ACTION_ERROR:
2130         default:
2131                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2132                 mtx_unlock(&lun->lun_lock);
2133                 retval = 1;
2134
2135                 ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2136                                          /*retry_count*/ 0);
2137                 ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2138                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2139                 msg_info.hdr.serializing_sc = NULL;
2140                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2141                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2142                     sizeof(msg_info.scsi), M_WAITOK);
2143                 break;
2144         }
2145         return (retval);
2146 }
2147
2148 /*
2149  * Returns 0 for success, errno for failure.
2150  */
2151 static int
2152 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2153                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2154 {
2155         union ctl_io *io;
2156         int retval;
2157
2158         retval = 0;
2159
2160         mtx_lock(&lun->lun_lock);
2161         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2162              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2163              ooa_links)) {
2164                 struct ctl_ooa_entry *entry;
2165
2166                 /*
2167                  * If we've got more than we can fit, just count the
2168                  * remaining entries.
2169                  */
2170                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2171                         continue;
2172
2173                 entry = &kern_entries[*cur_fill_num];
2174
2175                 entry->tag_num = io->scsiio.tag_num;
2176                 entry->lun_num = lun->lun;
2177 #ifdef CTL_TIME_IO
2178                 entry->start_bt = io->io_hdr.start_bt;
2179 #endif
2180                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2181                 entry->cdb_len = io->scsiio.cdb_len;
2182                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2183                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2184
2185                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2186                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2187
2188                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2189                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2190
2191                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2192                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2193
2194                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2195                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2196         }
2197         mtx_unlock(&lun->lun_lock);
2198
2199         return (retval);
2200 }
2201
2202 static void *
2203 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2204                  size_t error_str_len)
2205 {
2206         void *kptr;
2207
2208         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2209
2210         if (copyin(user_addr, kptr, len) != 0) {
2211                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2212                          "from user address %p to kernel address %p", len,
2213                          user_addr, kptr);
2214                 free(kptr, M_CTL);
2215                 return (NULL);
2216         }
2217
2218         return (kptr);
2219 }
2220
2221 static void
2222 ctl_free_args(int num_args, struct ctl_be_arg *args)
2223 {
2224         int i;
2225
2226         if (args == NULL)
2227                 return;
2228
2229         for (i = 0; i < num_args; i++) {
2230                 free(args[i].kname, M_CTL);
2231                 free(args[i].kvalue, M_CTL);
2232         }
2233
2234         free(args, M_CTL);
2235 }
2236
2237 static struct ctl_be_arg *
2238 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2239                 char *error_str, size_t error_str_len)
2240 {
2241         struct ctl_be_arg *args;
2242         int i;
2243
2244         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2245                                 error_str, error_str_len);
2246
2247         if (args == NULL)
2248                 goto bailout;
2249
2250         for (i = 0; i < num_args; i++) {
2251                 args[i].kname = NULL;
2252                 args[i].kvalue = NULL;
2253         }
2254
2255         for (i = 0; i < num_args; i++) {
2256                 uint8_t *tmpptr;
2257
2258                 args[i].kname = ctl_copyin_alloc(args[i].name,
2259                         args[i].namelen, error_str, error_str_len);
2260                 if (args[i].kname == NULL)
2261                         goto bailout;
2262
2263                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2264                         snprintf(error_str, error_str_len, "Argument %d "
2265                                  "name is not NUL-terminated", i);
2266                         goto bailout;
2267                 }
2268
2269                 if (args[i].flags & CTL_BEARG_RD) {
2270                         tmpptr = ctl_copyin_alloc(args[i].value,
2271                                 args[i].vallen, error_str, error_str_len);
2272                         if (tmpptr == NULL)
2273                                 goto bailout;
2274                         if ((args[i].flags & CTL_BEARG_ASCII)
2275                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2276                                 snprintf(error_str, error_str_len, "Argument "
2277                                     "%d value is not NUL-terminated", i);
2278                                 goto bailout;
2279                         }
2280                         args[i].kvalue = tmpptr;
2281                 } else {
2282                         args[i].kvalue = malloc(args[i].vallen,
2283                             M_CTL, M_WAITOK | M_ZERO);
2284                 }
2285         }
2286
2287         return (args);
2288 bailout:
2289
2290         ctl_free_args(num_args, args);
2291
2292         return (NULL);
2293 }
2294
2295 static void
2296 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2297 {
2298         int i;
2299
2300         for (i = 0; i < num_args; i++) {
2301                 if (args[i].flags & CTL_BEARG_WR)
2302                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2303         }
2304 }
2305
2306 /*
2307  * Escape characters that are illegal or not recommended in XML.
2308  */
2309 int
2310 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2311 {
2312         char *end = str + size;
2313         int retval;
2314
2315         retval = 0;
2316
2317         for (; *str && str < end; str++) {
2318                 switch (*str) {
2319                 case '&':
2320                         retval = sbuf_printf(sb, "&amp;");
2321                         break;
2322                 case '>':
2323                         retval = sbuf_printf(sb, "&gt;");
2324                         break;
2325                 case '<':
2326                         retval = sbuf_printf(sb, "&lt;");
2327                         break;
2328                 default:
2329                         retval = sbuf_putc(sb, *str);
2330                         break;
2331                 }
2332
2333                 if (retval != 0)
2334                         break;
2335
2336         }
2337
2338         return (retval);
2339 }
2340
2341 static void
2342 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2343 {
2344         struct scsi_vpd_id_descriptor *desc;
2345         int i;
2346
2347         if (id == NULL || id->len < 4)
2348                 return;
2349         desc = (struct scsi_vpd_id_descriptor *)id->data;
2350         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2351         case SVPD_ID_TYPE_T10:
2352                 sbuf_printf(sb, "t10.");
2353                 break;
2354         case SVPD_ID_TYPE_EUI64:
2355                 sbuf_printf(sb, "eui.");
2356                 break;
2357         case SVPD_ID_TYPE_NAA:
2358                 sbuf_printf(sb, "naa.");
2359                 break;
2360         case SVPD_ID_TYPE_SCSI_NAME:
2361                 break;
2362         }
2363         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2364         case SVPD_ID_CODESET_BINARY:
2365                 for (i = 0; i < desc->length; i++)
2366                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2367                 break;
2368         case SVPD_ID_CODESET_ASCII:
2369                 sbuf_printf(sb, "%.*s", (int)desc->length,
2370                     (char *)desc->identifier);
2371                 break;
2372         case SVPD_ID_CODESET_UTF8:
2373                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2374                 break;
2375         }
2376 }
2377
2378 static int
2379 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2380           struct thread *td)
2381 {
2382         struct ctl_softc *softc;
2383         struct ctl_lun *lun;
2384         int retval;
2385
2386         softc = control_softc;
2387
2388         retval = 0;
2389
2390         switch (cmd) {
2391         case CTL_IO:
2392                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2393                 break;
2394         case CTL_ENABLE_PORT:
2395         case CTL_DISABLE_PORT:
2396         case CTL_SET_PORT_WWNS: {
2397                 struct ctl_port *port;
2398                 struct ctl_port_entry *entry;
2399
2400                 entry = (struct ctl_port_entry *)addr;
2401                 
2402                 mtx_lock(&softc->ctl_lock);
2403                 STAILQ_FOREACH(port, &softc->port_list, links) {
2404                         int action, done;
2405
2406                         if (port->targ_port < softc->port_min ||
2407                             port->targ_port >= softc->port_max)
2408                                 continue;
2409
2410                         action = 0;
2411                         done = 0;
2412                         if ((entry->port_type == CTL_PORT_NONE)
2413                          && (entry->targ_port == port->targ_port)) {
2414                                 /*
2415                                  * If the user only wants to enable or
2416                                  * disable or set WWNs on a specific port,
2417                                  * do the operation and we're done.
2418                                  */
2419                                 action = 1;
2420                                 done = 1;
2421                         } else if (entry->port_type & port->port_type) {
2422                                 /*
2423                                  * Compare the user's type mask with the
2424                                  * particular frontend type to see if we
2425                                  * have a match.
2426                                  */
2427                                 action = 1;
2428                                 done = 0;
2429
2430                                 /*
2431                                  * Make sure the user isn't trying to set
2432                                  * WWNs on multiple ports at the same time.
2433                                  */
2434                                 if (cmd == CTL_SET_PORT_WWNS) {
2435                                         printf("%s: Can't set WWNs on "
2436                                                "multiple ports\n", __func__);
2437                                         retval = EINVAL;
2438                                         break;
2439                                 }
2440                         }
2441                         if (action == 0)
2442                                 continue;
2443
2444                         /*
2445                          * XXX KDM we have to drop the lock here, because
2446                          * the online/offline operations can potentially
2447                          * block.  We need to reference count the frontends
2448                          * so they can't go away,
2449                          */
2450                         if (cmd == CTL_ENABLE_PORT) {
2451                                 mtx_unlock(&softc->ctl_lock);
2452                                 ctl_port_online(port);
2453                                 mtx_lock(&softc->ctl_lock);
2454                         } else if (cmd == CTL_DISABLE_PORT) {
2455                                 mtx_unlock(&softc->ctl_lock);
2456                                 ctl_port_offline(port);
2457                                 mtx_lock(&softc->ctl_lock);
2458                         } else if (cmd == CTL_SET_PORT_WWNS) {
2459                                 ctl_port_set_wwns(port,
2460                                     (entry->flags & CTL_PORT_WWNN_VALID) ?
2461                                     1 : 0, entry->wwnn,
2462                                     (entry->flags & CTL_PORT_WWPN_VALID) ?
2463                                     1 : 0, entry->wwpn);
2464                         }
2465                         if (done != 0)
2466                                 break;
2467                 }
2468                 mtx_unlock(&softc->ctl_lock);
2469                 break;
2470         }
2471         case CTL_GET_PORT_LIST: {
2472                 struct ctl_port *port;
2473                 struct ctl_port_list *list;
2474                 int i;
2475
2476                 list = (struct ctl_port_list *)addr;
2477
2478                 if (list->alloc_len != (list->alloc_num *
2479                     sizeof(struct ctl_port_entry))) {
2480                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2481                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2482                                "%zu\n", __func__, list->alloc_len,
2483                                list->alloc_num, sizeof(struct ctl_port_entry));
2484                         retval = EINVAL;
2485                         break;
2486                 }
2487                 list->fill_len = 0;
2488                 list->fill_num = 0;
2489                 list->dropped_num = 0;
2490                 i = 0;
2491                 mtx_lock(&softc->ctl_lock);
2492                 STAILQ_FOREACH(port, &softc->port_list, links) {
2493                         struct ctl_port_entry entry, *list_entry;
2494
2495                         if (list->fill_num >= list->alloc_num) {
2496                                 list->dropped_num++;
2497                                 continue;
2498                         }
2499
2500                         entry.port_type = port->port_type;
2501                         strlcpy(entry.port_name, port->port_name,
2502                                 sizeof(entry.port_name));
2503                         entry.targ_port = port->targ_port;
2504                         entry.physical_port = port->physical_port;
2505                         entry.virtual_port = port->virtual_port;
2506                         entry.wwnn = port->wwnn;
2507                         entry.wwpn = port->wwpn;
2508                         if (port->status & CTL_PORT_STATUS_ONLINE)
2509                                 entry.online = 1;
2510                         else
2511                                 entry.online = 0;
2512
2513                         list_entry = &list->entries[i];
2514
2515                         retval = copyout(&entry, list_entry, sizeof(entry));
2516                         if (retval != 0) {
2517                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2518                                        "returned %d\n", __func__, retval);
2519                                 break;
2520                         }
2521                         i++;
2522                         list->fill_num++;
2523                         list->fill_len += sizeof(entry);
2524                 }
2525                 mtx_unlock(&softc->ctl_lock);
2526
2527                 /*
2528                  * If this is non-zero, we had a copyout fault, so there's
2529                  * probably no point in attempting to set the status inside
2530                  * the structure.
2531                  */
2532                 if (retval != 0)
2533                         break;
2534
2535                 if (list->dropped_num > 0)
2536                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2537                 else
2538                         list->status = CTL_PORT_LIST_OK;
2539                 break;
2540         }
2541         case CTL_DUMP_OOA: {
2542                 union ctl_io *io;
2543                 char printbuf[128];
2544                 struct sbuf sb;
2545
2546                 mtx_lock(&softc->ctl_lock);
2547                 printf("Dumping OOA queues:\n");
2548                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2549                         mtx_lock(&lun->lun_lock);
2550                         for (io = (union ctl_io *)TAILQ_FIRST(
2551                              &lun->ooa_queue); io != NULL;
2552                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2553                              ooa_links)) {
2554                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2555                                          SBUF_FIXEDLEN);
2556                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2557                                             (intmax_t)lun->lun,
2558                                             io->scsiio.tag_num,
2559                                             (io->io_hdr.flags &
2560                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2561                                             (io->io_hdr.flags &
2562                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2563                                             (io->io_hdr.flags &
2564                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2565                                             (io->io_hdr.flags &
2566                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2567                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2568                                 sbuf_finish(&sb);
2569                                 printf("%s\n", sbuf_data(&sb));
2570                         }
2571                         mtx_unlock(&lun->lun_lock);
2572                 }
2573                 printf("OOA queues dump done\n");
2574                 mtx_unlock(&softc->ctl_lock);
2575                 break;
2576         }
2577         case CTL_GET_OOA: {
2578                 struct ctl_ooa *ooa_hdr;
2579                 struct ctl_ooa_entry *entries;
2580                 uint32_t cur_fill_num;
2581
2582                 ooa_hdr = (struct ctl_ooa *)addr;
2583
2584                 if ((ooa_hdr->alloc_len == 0)
2585                  || (ooa_hdr->alloc_num == 0)) {
2586                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2587                                "must be non-zero\n", __func__,
2588                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2589                         retval = EINVAL;
2590                         break;
2591                 }
2592
2593                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2594                     sizeof(struct ctl_ooa_entry))) {
2595                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2596                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2597                                __func__, ooa_hdr->alloc_len,
2598                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2599                         retval = EINVAL;
2600                         break;
2601                 }
2602
2603                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2604                 if (entries == NULL) {
2605                         printf("%s: could not allocate %d bytes for OOA "
2606                                "dump\n", __func__, ooa_hdr->alloc_len);
2607                         retval = ENOMEM;
2608                         break;
2609                 }
2610
2611                 mtx_lock(&softc->ctl_lock);
2612                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2613                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2614                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2615                         mtx_unlock(&softc->ctl_lock);
2616                         free(entries, M_CTL);
2617                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2618                                __func__, (uintmax_t)ooa_hdr->lun_num);
2619                         retval = EINVAL;
2620                         break;
2621                 }
2622
2623                 cur_fill_num = 0;
2624
2625                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2626                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2627                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2628                                         ooa_hdr, entries);
2629                                 if (retval != 0)
2630                                         break;
2631                         }
2632                         if (retval != 0) {
2633                                 mtx_unlock(&softc->ctl_lock);
2634                                 free(entries, M_CTL);
2635                                 break;
2636                         }
2637                 } else {
2638                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2639
2640                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2641                                                     entries);
2642                 }
2643                 mtx_unlock(&softc->ctl_lock);
2644
2645                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2646                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2647                         sizeof(struct ctl_ooa_entry);
2648                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2649                 if (retval != 0) {
2650                         printf("%s: error copying out %d bytes for OOA dump\n", 
2651                                __func__, ooa_hdr->fill_len);
2652                 }
2653
2654                 getbintime(&ooa_hdr->cur_bt);
2655
2656                 if (cur_fill_num > ooa_hdr->alloc_num) {
2657                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2658                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2659                 } else {
2660                         ooa_hdr->dropped_num = 0;
2661                         ooa_hdr->status = CTL_OOA_OK;
2662                 }
2663
2664                 free(entries, M_CTL);
2665                 break;
2666         }
2667         case CTL_CHECK_OOA: {
2668                 union ctl_io *io;
2669                 struct ctl_ooa_info *ooa_info;
2670
2671
2672                 ooa_info = (struct ctl_ooa_info *)addr;
2673
2674                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2675                         ooa_info->status = CTL_OOA_INVALID_LUN;
2676                         break;
2677                 }
2678                 mtx_lock(&softc->ctl_lock);
2679                 lun = softc->ctl_luns[ooa_info->lun_id];
2680                 if (lun == NULL) {
2681                         mtx_unlock(&softc->ctl_lock);
2682                         ooa_info->status = CTL_OOA_INVALID_LUN;
2683                         break;
2684                 }
2685                 mtx_lock(&lun->lun_lock);
2686                 mtx_unlock(&softc->ctl_lock);
2687                 ooa_info->num_entries = 0;
2688                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2689                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2690                      &io->io_hdr, ooa_links)) {
2691                         ooa_info->num_entries++;
2692                 }
2693                 mtx_unlock(&lun->lun_lock);
2694
2695                 ooa_info->status = CTL_OOA_SUCCESS;
2696
2697                 break;
2698         }
2699         case CTL_DELAY_IO: {
2700                 struct ctl_io_delay_info *delay_info;
2701
2702                 delay_info = (struct ctl_io_delay_info *)addr;
2703
2704 #ifdef CTL_IO_DELAY
2705                 mtx_lock(&softc->ctl_lock);
2706
2707                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2708                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2709                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2710                 } else {
2711                         lun = softc->ctl_luns[delay_info->lun_id];
2712                         mtx_lock(&lun->lun_lock);
2713
2714                         delay_info->status = CTL_DELAY_STATUS_OK;
2715
2716                         switch (delay_info->delay_type) {
2717                         case CTL_DELAY_TYPE_CONT:
2718                                 break;
2719                         case CTL_DELAY_TYPE_ONESHOT:
2720                                 break;
2721                         default:
2722                                 delay_info->status =
2723                                         CTL_DELAY_STATUS_INVALID_TYPE;
2724                                 break;
2725                         }
2726
2727                         switch (delay_info->delay_loc) {
2728                         case CTL_DELAY_LOC_DATAMOVE:
2729                                 lun->delay_info.datamove_type =
2730                                         delay_info->delay_type;
2731                                 lun->delay_info.datamove_delay =
2732                                         delay_info->delay_secs;
2733                                 break;
2734                         case CTL_DELAY_LOC_DONE:
2735                                 lun->delay_info.done_type =
2736                                         delay_info->delay_type;
2737                                 lun->delay_info.done_delay =
2738                                         delay_info->delay_secs;
2739                                 break;
2740                         default:
2741                                 delay_info->status =
2742                                         CTL_DELAY_STATUS_INVALID_LOC;
2743                                 break;
2744                         }
2745                         mtx_unlock(&lun->lun_lock);
2746                 }
2747
2748                 mtx_unlock(&softc->ctl_lock);
2749 #else
2750                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2751 #endif /* CTL_IO_DELAY */
2752                 break;
2753         }
2754         case CTL_REALSYNC_SET: {
2755                 int *syncstate;
2756
2757                 syncstate = (int *)addr;
2758
2759                 mtx_lock(&softc->ctl_lock);
2760                 switch (*syncstate) {
2761                 case 0:
2762                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2763                         break;
2764                 case 1:
2765                         softc->flags |= CTL_FLAG_REAL_SYNC;
2766                         break;
2767                 default:
2768                         retval = EINVAL;
2769                         break;
2770                 }
2771                 mtx_unlock(&softc->ctl_lock);
2772                 break;
2773         }
2774         case CTL_REALSYNC_GET: {
2775                 int *syncstate;
2776
2777                 syncstate = (int*)addr;
2778
2779                 mtx_lock(&softc->ctl_lock);
2780                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2781                         *syncstate = 1;
2782                 else
2783                         *syncstate = 0;
2784                 mtx_unlock(&softc->ctl_lock);
2785
2786                 break;
2787         }
2788         case CTL_SETSYNC:
2789         case CTL_GETSYNC: {
2790                 struct ctl_sync_info *sync_info;
2791
2792                 sync_info = (struct ctl_sync_info *)addr;
2793
2794                 mtx_lock(&softc->ctl_lock);
2795                 lun = softc->ctl_luns[sync_info->lun_id];
2796                 if (lun == NULL) {
2797                         mtx_unlock(&softc->ctl_lock);
2798                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2799                         break;
2800                 }
2801                 /*
2802                  * Get or set the sync interval.  We're not bounds checking
2803                  * in the set case, hopefully the user won't do something
2804                  * silly.
2805                  */
2806                 mtx_lock(&lun->lun_lock);
2807                 mtx_unlock(&softc->ctl_lock);
2808                 if (cmd == CTL_GETSYNC)
2809                         sync_info->sync_interval = lun->sync_interval;
2810                 else
2811                         lun->sync_interval = sync_info->sync_interval;
2812                 mtx_unlock(&lun->lun_lock);
2813
2814                 sync_info->status = CTL_GS_SYNC_OK;
2815
2816                 break;
2817         }
2818         case CTL_GETSTATS: {
2819                 struct ctl_stats *stats;
2820                 int i;
2821
2822                 stats = (struct ctl_stats *)addr;
2823
2824                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2825                      stats->alloc_len) {
2826                         stats->status = CTL_SS_NEED_MORE_SPACE;
2827                         stats->num_luns = softc->num_luns;
2828                         break;
2829                 }
2830                 /*
2831                  * XXX KDM no locking here.  If the LUN list changes,
2832                  * things can blow up.
2833                  */
2834                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2835                      i++, lun = STAILQ_NEXT(lun, links)) {
2836                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2837                                          sizeof(lun->stats));
2838                         if (retval != 0)
2839                                 break;
2840                 }
2841                 stats->num_luns = softc->num_luns;
2842                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2843                                  softc->num_luns;
2844                 stats->status = CTL_SS_OK;
2845 #ifdef CTL_TIME_IO
2846                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2847 #else
2848                 stats->flags = CTL_STATS_FLAG_NONE;
2849 #endif
2850                 getnanouptime(&stats->timestamp);
2851                 break;
2852         }
2853         case CTL_ERROR_INJECT: {
2854                 struct ctl_error_desc *err_desc, *new_err_desc;
2855
2856                 err_desc = (struct ctl_error_desc *)addr;
2857
2858                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2859                                       M_WAITOK | M_ZERO);
2860                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2861
2862                 mtx_lock(&softc->ctl_lock);
2863                 lun = softc->ctl_luns[err_desc->lun_id];
2864                 if (lun == NULL) {
2865                         mtx_unlock(&softc->ctl_lock);
2866                         free(new_err_desc, M_CTL);
2867                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2868                                __func__, (uintmax_t)err_desc->lun_id);
2869                         retval = EINVAL;
2870                         break;
2871                 }
2872                 mtx_lock(&lun->lun_lock);
2873                 mtx_unlock(&softc->ctl_lock);
2874
2875                 /*
2876                  * We could do some checking here to verify the validity
2877                  * of the request, but given the complexity of error
2878                  * injection requests, the checking logic would be fairly
2879                  * complex.
2880                  *
2881                  * For now, if the request is invalid, it just won't get
2882                  * executed and might get deleted.
2883                  */
2884                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2885
2886                 /*
2887                  * XXX KDM check to make sure the serial number is unique,
2888                  * in case we somehow manage to wrap.  That shouldn't
2889                  * happen for a very long time, but it's the right thing to
2890                  * do.
2891                  */
2892                 new_err_desc->serial = lun->error_serial;
2893                 err_desc->serial = lun->error_serial;
2894                 lun->error_serial++;
2895
2896                 mtx_unlock(&lun->lun_lock);
2897                 break;
2898         }
2899         case CTL_ERROR_INJECT_DELETE: {
2900                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2901                 int delete_done;
2902
2903                 delete_desc = (struct ctl_error_desc *)addr;
2904                 delete_done = 0;
2905
2906                 mtx_lock(&softc->ctl_lock);
2907                 lun = softc->ctl_luns[delete_desc->lun_id];
2908                 if (lun == NULL) {
2909                         mtx_unlock(&softc->ctl_lock);
2910                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2911                                __func__, (uintmax_t)delete_desc->lun_id);
2912                         retval = EINVAL;
2913                         break;
2914                 }
2915                 mtx_lock(&lun->lun_lock);
2916                 mtx_unlock(&softc->ctl_lock);
2917                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2918                         if (desc->serial != delete_desc->serial)
2919                                 continue;
2920
2921                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2922                                       links);
2923                         free(desc, M_CTL);
2924                         delete_done = 1;
2925                 }
2926                 mtx_unlock(&lun->lun_lock);
2927                 if (delete_done == 0) {
2928                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2929                                "error serial %ju on LUN %u\n", __func__, 
2930                                delete_desc->serial, delete_desc->lun_id);
2931                         retval = EINVAL;
2932                         break;
2933                 }
2934                 break;
2935         }
2936         case CTL_DUMP_STRUCTS: {
2937                 int i, j, k;
2938                 struct ctl_port *port;
2939                 struct ctl_frontend *fe;
2940
2941                 mtx_lock(&softc->ctl_lock);
2942                 printf("CTL Persistent Reservation information start:\n");
2943                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2944                         lun = softc->ctl_luns[i];
2945
2946                         if ((lun == NULL)
2947                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2948                                 continue;
2949
2950                         for (j = 0; j < CTL_MAX_PORTS; j++) {
2951                                 if (lun->pr_keys[j] == NULL)
2952                                         continue;
2953                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2954                                         if (lun->pr_keys[j][k] == 0)
2955                                                 continue;
2956                                         printf("  LUN %d port %d iid %d key "
2957                                                "%#jx\n", i, j, k,
2958                                                (uintmax_t)lun->pr_keys[j][k]);
2959                                 }
2960                         }
2961                 }
2962                 printf("CTL Persistent Reservation information end\n");
2963                 printf("CTL Ports:\n");
2964                 STAILQ_FOREACH(port, &softc->port_list, links) {
2965                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2966                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2967                                port->frontend->name, port->port_type,
2968                                port->physical_port, port->virtual_port,
2969                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2970                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2971                                 if (port->wwpn_iid[j].in_use == 0 &&
2972                                     port->wwpn_iid[j].wwpn == 0 &&
2973                                     port->wwpn_iid[j].name == NULL)
2974                                         continue;
2975
2976                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2977                                     j, port->wwpn_iid[j].in_use,
2978                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2979                                     port->wwpn_iid[j].name);
2980                         }
2981                 }
2982                 printf("CTL Port information end\n");
2983                 mtx_unlock(&softc->ctl_lock);
2984                 /*
2985                  * XXX KDM calling this without a lock.  We'd likely want
2986                  * to drop the lock before calling the frontend's dump
2987                  * routine anyway.
2988                  */
2989                 printf("CTL Frontends:\n");
2990                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2991                         printf("  Frontend '%s'\n", fe->name);
2992                         if (fe->fe_dump != NULL)
2993                                 fe->fe_dump();
2994                 }
2995                 printf("CTL Frontend information end\n");
2996                 break;
2997         }
2998         case CTL_LUN_REQ: {
2999                 struct ctl_lun_req *lun_req;
3000                 struct ctl_backend_driver *backend;
3001
3002                 lun_req = (struct ctl_lun_req *)addr;
3003
3004                 backend = ctl_backend_find(lun_req->backend);
3005                 if (backend == NULL) {
3006                         lun_req->status = CTL_LUN_ERROR;
3007                         snprintf(lun_req->error_str,
3008                                  sizeof(lun_req->error_str),
3009                                  "Backend \"%s\" not found.",
3010                                  lun_req->backend);
3011                         break;
3012                 }
3013                 if (lun_req->num_be_args > 0) {
3014                         lun_req->kern_be_args = ctl_copyin_args(
3015                                 lun_req->num_be_args,
3016                                 lun_req->be_args,
3017                                 lun_req->error_str,
3018                                 sizeof(lun_req->error_str));
3019                         if (lun_req->kern_be_args == NULL) {
3020                                 lun_req->status = CTL_LUN_ERROR;
3021                                 break;
3022                         }
3023                 }
3024
3025                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3026
3027                 if (lun_req->num_be_args > 0) {
3028                         ctl_copyout_args(lun_req->num_be_args,
3029                                       lun_req->kern_be_args);
3030                         ctl_free_args(lun_req->num_be_args,
3031                                       lun_req->kern_be_args);
3032                 }
3033                 break;
3034         }
3035         case CTL_LUN_LIST: {
3036                 struct sbuf *sb;
3037                 struct ctl_lun_list *list;
3038                 struct ctl_option *opt;
3039
3040                 list = (struct ctl_lun_list *)addr;
3041
3042                 /*
3043                  * Allocate a fixed length sbuf here, based on the length
3044                  * of the user's buffer.  We could allocate an auto-extending
3045                  * buffer, and then tell the user how much larger our
3046                  * amount of data is than his buffer, but that presents
3047                  * some problems:
3048                  *
3049                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3050                  *     we can't hold a lock while calling them with an
3051                  *     auto-extending buffer.
3052                  *
3053                  * 2.  There is not currently a LUN reference counting
3054                  *     mechanism, outside of outstanding transactions on
3055                  *     the LUN's OOA queue.  So a LUN could go away on us
3056                  *     while we're getting the LUN number, backend-specific
3057                  *     information, etc.  Thus, given the way things
3058                  *     currently work, we need to hold the CTL lock while
3059                  *     grabbing LUN information.
3060                  *
3061                  * So, from the user's standpoint, the best thing to do is
3062                  * allocate what he thinks is a reasonable buffer length,
3063                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3064                  * double the buffer length and try again.  (And repeat
3065                  * that until he succeeds.)
3066                  */
3067                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3068                 if (sb == NULL) {
3069                         list->status = CTL_LUN_LIST_ERROR;
3070                         snprintf(list->error_str, sizeof(list->error_str),
3071                                  "Unable to allocate %d bytes for LUN list",
3072                                  list->alloc_len);
3073                         break;
3074                 }
3075
3076                 sbuf_printf(sb, "<ctllunlist>\n");
3077
3078                 mtx_lock(&softc->ctl_lock);
3079                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3080                         mtx_lock(&lun->lun_lock);
3081                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3082                                              (uintmax_t)lun->lun);
3083
3084                         /*
3085                          * Bail out as soon as we see that we've overfilled
3086                          * the buffer.
3087                          */
3088                         if (retval != 0)
3089                                 break;
3090
3091                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3092                                              "</backend_type>\n",
3093                                              (lun->backend == NULL) ?  "none" :
3094                                              lun->backend->name);
3095
3096                         if (retval != 0)
3097                                 break;
3098
3099                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3100                                              lun->be_lun->lun_type);
3101
3102                         if (retval != 0)
3103                                 break;
3104
3105                         if (lun->backend == NULL) {
3106                                 retval = sbuf_printf(sb, "</lun>\n");
3107                                 if (retval != 0)
3108                                         break;
3109                                 continue;
3110                         }
3111
3112                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3113                                              (lun->be_lun->maxlba > 0) ?
3114                                              lun->be_lun->maxlba + 1 : 0);
3115
3116                         if (retval != 0)
3117                                 break;
3118
3119                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3120                                              lun->be_lun->blocksize);
3121
3122                         if (retval != 0)
3123                                 break;
3124
3125                         retval = sbuf_printf(sb, "\t<serial_number>");
3126
3127                         if (retval != 0)
3128                                 break;
3129
3130                         retval = ctl_sbuf_printf_esc(sb,
3131                             lun->be_lun->serial_num,
3132                             sizeof(lun->be_lun->serial_num));
3133
3134                         if (retval != 0)
3135                                 break;
3136
3137                         retval = sbuf_printf(sb, "</serial_number>\n");
3138                 
3139                         if (retval != 0)
3140                                 break;
3141
3142                         retval = sbuf_printf(sb, "\t<device_id>");
3143
3144                         if (retval != 0)
3145                                 break;
3146
3147                         retval = ctl_sbuf_printf_esc(sb,
3148                             lun->be_lun->device_id,
3149                             sizeof(lun->be_lun->device_id));
3150
3151                         if (retval != 0)
3152                                 break;
3153
3154                         retval = sbuf_printf(sb, "</device_id>\n");
3155
3156                         if (retval != 0)
3157                                 break;
3158
3159                         if (lun->backend->lun_info != NULL) {
3160                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3161                                 if (retval != 0)
3162                                         break;
3163                         }
3164                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3165                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3166                                     opt->name, opt->value, opt->name);
3167                                 if (retval != 0)
3168                                         break;
3169                         }
3170
3171                         retval = sbuf_printf(sb, "</lun>\n");
3172
3173                         if (retval != 0)
3174                                 break;
3175                         mtx_unlock(&lun->lun_lock);
3176                 }
3177                 if (lun != NULL)
3178                         mtx_unlock(&lun->lun_lock);
3179                 mtx_unlock(&softc->ctl_lock);
3180
3181                 if ((retval != 0)
3182                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3183                         retval = 0;
3184                         sbuf_delete(sb);
3185                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3186                         snprintf(list->error_str, sizeof(list->error_str),
3187                                  "Out of space, %d bytes is too small",
3188                                  list->alloc_len);
3189                         break;
3190                 }
3191
3192                 sbuf_finish(sb);
3193
3194                 retval = copyout(sbuf_data(sb), list->lun_xml,
3195                                  sbuf_len(sb) + 1);
3196
3197                 list->fill_len = sbuf_len(sb) + 1;
3198                 list->status = CTL_LUN_LIST_OK;
3199                 sbuf_delete(sb);
3200                 break;
3201         }
3202         case CTL_ISCSI: {
3203                 struct ctl_iscsi *ci;
3204                 struct ctl_frontend *fe;
3205
3206                 ci = (struct ctl_iscsi *)addr;
3207
3208                 fe = ctl_frontend_find("iscsi");
3209                 if (fe == NULL) {
3210                         ci->status = CTL_ISCSI_ERROR;
3211                         snprintf(ci->error_str, sizeof(ci->error_str),
3212                             "Frontend \"iscsi\" not found.");
3213                         break;
3214                 }
3215
3216                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3217                 break;
3218         }
3219         case CTL_PORT_REQ: {
3220                 struct ctl_req *req;
3221                 struct ctl_frontend *fe;
3222
3223                 req = (struct ctl_req *)addr;
3224
3225                 fe = ctl_frontend_find(req->driver);
3226                 if (fe == NULL) {
3227                         req->status = CTL_LUN_ERROR;
3228                         snprintf(req->error_str, sizeof(req->error_str),
3229                             "Frontend \"%s\" not found.", req->driver);
3230                         break;
3231                 }
3232                 if (req->num_args > 0) {
3233                         req->kern_args = ctl_copyin_args(req->num_args,
3234                             req->args, req->error_str, sizeof(req->error_str));
3235                         if (req->kern_args == NULL) {
3236                                 req->status = CTL_LUN_ERROR;
3237                                 break;
3238                         }
3239                 }
3240
3241                 if (fe->ioctl)
3242                         retval = fe->ioctl(dev, cmd, addr, flag, td);
3243                 else
3244                         retval = ENODEV;
3245
3246                 if (req->num_args > 0) {
3247                         ctl_copyout_args(req->num_args, req->kern_args);
3248                         ctl_free_args(req->num_args, req->kern_args);
3249                 }
3250                 break;
3251         }
3252         case CTL_PORT_LIST: {
3253                 struct sbuf *sb;
3254                 struct ctl_port *port;
3255                 struct ctl_lun_list *list;
3256                 struct ctl_option *opt;
3257                 int j;
3258                 uint32_t plun;
3259
3260                 list = (struct ctl_lun_list *)addr;
3261
3262                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3263                 if (sb == NULL) {
3264                         list->status = CTL_LUN_LIST_ERROR;
3265                         snprintf(list->error_str, sizeof(list->error_str),
3266                                  "Unable to allocate %d bytes for LUN list",
3267                                  list->alloc_len);
3268                         break;
3269                 }
3270
3271                 sbuf_printf(sb, "<ctlportlist>\n");
3272
3273                 mtx_lock(&softc->ctl_lock);
3274                 STAILQ_FOREACH(port, &softc->port_list, links) {
3275                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3276                                              (uintmax_t)port->targ_port);
3277
3278                         /*
3279                          * Bail out as soon as we see that we've overfilled
3280                          * the buffer.
3281                          */
3282                         if (retval != 0)
3283                                 break;
3284
3285                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3286                             "</frontend_type>\n", port->frontend->name);
3287                         if (retval != 0)
3288                                 break;
3289
3290                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3291                                              port->port_type);
3292                         if (retval != 0)
3293                                 break;
3294
3295                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3296                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3297                         if (retval != 0)
3298                                 break;
3299
3300                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3301                             port->port_name);
3302                         if (retval != 0)
3303                                 break;
3304
3305                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3306                             port->physical_port);
3307                         if (retval != 0)
3308                                 break;
3309
3310                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3311                             port->virtual_port);
3312                         if (retval != 0)
3313                                 break;
3314
3315                         if (port->target_devid != NULL) {
3316                                 sbuf_printf(sb, "\t<target>");
3317                                 ctl_id_sbuf(port->target_devid, sb);
3318                                 sbuf_printf(sb, "</target>\n");
3319                         }
3320
3321                         if (port->port_devid != NULL) {
3322                                 sbuf_printf(sb, "\t<port>");
3323                                 ctl_id_sbuf(port->port_devid, sb);
3324                                 sbuf_printf(sb, "</port>\n");
3325                         }
3326
3327                         if (port->port_info != NULL) {
3328                                 retval = port->port_info(port->onoff_arg, sb);
3329                                 if (retval != 0)
3330                                         break;
3331                         }
3332                         STAILQ_FOREACH(opt, &port->options, links) {
3333                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3334                                     opt->name, opt->value, opt->name);
3335                                 if (retval != 0)
3336                                         break;
3337                         }
3338
3339                         if (port->lun_map != NULL) {
3340                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3341                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3342                                         plun = ctl_lun_map_from_port(port, j);
3343                                         if (plun >= CTL_MAX_LUNS)
3344                                                 continue;
3345                                         sbuf_printf(sb,
3346                                             "\t<lun id=\"%u\">%u</lun>\n",
3347                                             j, plun);
3348                                 }
3349                         }
3350
3351                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3352                                 if (port->wwpn_iid[j].in_use == 0 ||
3353                                     (port->wwpn_iid[j].wwpn == 0 &&
3354                                      port->wwpn_iid[j].name == NULL))
3355                                         continue;
3356
3357                                 if (port->wwpn_iid[j].name != NULL)
3358                                         retval = sbuf_printf(sb,
3359                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3360                                             j, port->wwpn_iid[j].name);
3361                                 else
3362                                         retval = sbuf_printf(sb,
3363                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3364                                             j, port->wwpn_iid[j].wwpn);
3365                                 if (retval != 0)
3366                                         break;
3367                         }
3368                         if (retval != 0)
3369                                 break;
3370
3371                         retval = sbuf_printf(sb, "</targ_port>\n");
3372                         if (retval != 0)
3373                                 break;
3374                 }
3375                 mtx_unlock(&softc->ctl_lock);
3376
3377                 if ((retval != 0)
3378                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3379                         retval = 0;
3380                         sbuf_delete(sb);
3381                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3382                         snprintf(list->error_str, sizeof(list->error_str),
3383                                  "Out of space, %d bytes is too small",
3384                                  list->alloc_len);
3385                         break;
3386                 }
3387
3388                 sbuf_finish(sb);
3389
3390                 retval = copyout(sbuf_data(sb), list->lun_xml,
3391                                  sbuf_len(sb) + 1);
3392
3393                 list->fill_len = sbuf_len(sb) + 1;
3394                 list->status = CTL_LUN_LIST_OK;
3395                 sbuf_delete(sb);
3396                 break;
3397         }
3398         case CTL_LUN_MAP: {
3399                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3400                 struct ctl_port *port;
3401
3402                 mtx_lock(&softc->ctl_lock);
3403                 if (lm->port < softc->port_min ||
3404                     lm->port >= softc->port_max ||
3405                     (port = softc->ctl_ports[lm->port]) == NULL) {
3406                         mtx_unlock(&softc->ctl_lock);
3407                         return (ENXIO);
3408                 }
3409                 if (port->status & CTL_PORT_STATUS_ONLINE) {
3410                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
3411                                 if (ctl_lun_map_to_port(port, lun->lun) >=
3412                                     CTL_MAX_LUNS)
3413                                         continue;
3414                                 mtx_lock(&lun->lun_lock);
3415                                 ctl_est_ua_port(lun, lm->port, -1,
3416                                     CTL_UA_LUN_CHANGE);
3417                                 mtx_unlock(&lun->lun_lock);
3418                         }
3419                 }
3420                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3421                 if (lm->plun < CTL_MAX_LUNS) {
3422                         if (lm->lun == UINT32_MAX)
3423                                 retval = ctl_lun_map_unset(port, lm->plun);
3424                         else if (lm->lun < CTL_MAX_LUNS &&
3425                             softc->ctl_luns[lm->lun] != NULL)
3426                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3427                         else
3428                                 return (ENXIO);
3429                 } else if (lm->plun == UINT32_MAX) {
3430                         if (lm->lun == UINT32_MAX)
3431                                 retval = ctl_lun_map_deinit(port);
3432                         else
3433                                 retval = ctl_lun_map_init(port);
3434                 } else
3435                         return (ENXIO);
3436                 if (port->status & CTL_PORT_STATUS_ONLINE)
3437                         ctl_isc_announce_port(port);
3438                 break;
3439         }
3440         default: {
3441                 /* XXX KDM should we fix this? */
3442 #if 0
3443                 struct ctl_backend_driver *backend;
3444                 unsigned int type;
3445                 int found;
3446
3447                 found = 0;
3448
3449                 /*
3450                  * We encode the backend type as the ioctl type for backend
3451                  * ioctls.  So parse it out here, and then search for a
3452                  * backend of this type.
3453                  */
3454                 type = _IOC_TYPE(cmd);
3455
3456                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3457                         if (backend->type == type) {
3458                                 found = 1;
3459                                 break;
3460                         }
3461                 }
3462                 if (found == 0) {
3463                         printf("ctl: unknown ioctl command %#lx or backend "
3464                                "%d\n", cmd, type);
3465                         retval = EINVAL;
3466                         break;
3467                 }
3468                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3469 #endif
3470                 retval = ENOTTY;
3471                 break;
3472         }
3473         }
3474         return (retval);
3475 }
3476
3477 uint32_t
3478 ctl_get_initindex(struct ctl_nexus *nexus)
3479 {
3480         return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3481 }
3482
3483 int
3484 ctl_lun_map_init(struct ctl_port *port)
3485 {
3486         struct ctl_softc *softc = control_softc;
3487         struct ctl_lun *lun;
3488         uint32_t i;
3489
3490         if (port->lun_map == NULL)
3491                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3492                     M_CTL, M_NOWAIT);
3493         if (port->lun_map == NULL)
3494                 return (ENOMEM);
3495         for (i = 0; i < CTL_MAX_LUNS; i++)
3496                 port->lun_map[i] = UINT32_MAX;
3497         if (port->status & CTL_PORT_STATUS_ONLINE) {
3498                 if (port->lun_disable != NULL) {
3499                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3500                                 port->lun_disable(port->targ_lun_arg, lun->lun);
3501                 }
3502                 ctl_isc_announce_port(port);
3503         }
3504         return (0);
3505 }
3506
3507 int
3508 ctl_lun_map_deinit(struct ctl_port *port)
3509 {
3510         struct ctl_softc *softc = control_softc;
3511         struct ctl_lun *lun;
3512
3513         if (port->lun_map == NULL)
3514                 return (0);
3515         free(port->lun_map, M_CTL);
3516         port->lun_map = NULL;
3517         if (port->status & CTL_PORT_STATUS_ONLINE) {
3518                 if (port->lun_enable != NULL) {
3519                         STAILQ_FOREACH(lun, &softc->lun_list, links)
3520                                 port->lun_enable(port->targ_lun_arg, lun->lun);
3521                 }
3522                 ctl_isc_announce_port(port);
3523         }
3524         return (0);
3525 }
3526
3527 int
3528 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3529 {
3530         int status;
3531         uint32_t old;
3532
3533         if (port->lun_map == NULL) {
3534                 status = ctl_lun_map_init(port);
3535                 if (status != 0)
3536                         return (status);
3537         }
3538         old = port->lun_map[plun];
3539         port->lun_map[plun] = glun;
3540         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3541                 if (port->lun_enable != NULL)
3542                         port->lun_enable(port->targ_lun_arg, plun);
3543                 ctl_isc_announce_port(port);
3544         }
3545         return (0);
3546 }
3547
3548 int
3549 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3550 {
3551         uint32_t old;
3552
3553         if (port->lun_map == NULL)
3554                 return (0);
3555         old = port->lun_map[plun];
3556         port->lun_map[plun] = UINT32_MAX;
3557         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3558                 if (port->lun_disable != NULL)
3559                         port->lun_disable(port->targ_lun_arg, plun);
3560                 ctl_isc_announce_port(port);
3561         }
3562         return (0);
3563 }
3564
3565 uint32_t
3566 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3567 {
3568
3569         if (port == NULL)
3570                 return (UINT32_MAX);
3571         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3572                 return (lun_id);
3573         return (port->lun_map[lun_id]);
3574 }
3575
3576 uint32_t
3577 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3578 {
3579         uint32_t i;
3580
3581         if (port == NULL)
3582                 return (UINT32_MAX);
3583         if (port->lun_map == NULL)
3584                 return (lun_id);
3585         for (i = 0; i < CTL_MAX_LUNS; i++) {
3586                 if (port->lun_map[i] == lun_id)
3587                         return (i);
3588         }
3589         return (UINT32_MAX);
3590 }
3591
3592 static struct ctl_port *
3593 ctl_io_port(struct ctl_io_hdr *io_hdr)
3594 {
3595
3596         return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3597 }
3598
3599 int
3600 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3601 {
3602         int i;
3603
3604         for (i = first; i < last; i++) {
3605                 if ((mask[i / 32] & (1 << (i % 32))) == 0)
3606                         return (i);
3607         }
3608         return (-1);
3609 }
3610
3611 int
3612 ctl_set_mask(uint32_t *mask, uint32_t bit)
3613 {
3614         uint32_t chunk, piece;
3615
3616         chunk = bit >> 5;
3617         piece = bit % (sizeof(uint32_t) * 8);
3618
3619         if ((mask[chunk] & (1 << piece)) != 0)
3620                 return (-1);
3621         else
3622                 mask[chunk] |= (1 << piece);
3623
3624         return (0);
3625 }
3626
3627 int
3628 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3629 {
3630         uint32_t chunk, piece;
3631
3632         chunk = bit >> 5;
3633         piece = bit % (sizeof(uint32_t) * 8);
3634
3635         if ((mask[chunk] & (1 << piece)) == 0)
3636                 return (-1);
3637         else
3638                 mask[chunk] &= ~(1 << piece);
3639
3640         return (0);
3641 }
3642
3643 int
3644 ctl_is_set(uint32_t *mask, uint32_t bit)
3645 {
3646         uint32_t chunk, piece;
3647
3648         chunk = bit >> 5;
3649         piece = bit % (sizeof(uint32_t) * 8);
3650
3651         if ((mask[chunk] & (1 << piece)) == 0)
3652                 return (0);
3653         else
3654                 return (1);
3655 }
3656
3657 static uint64_t
3658 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3659 {
3660         uint64_t *t;
3661
3662         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3663         if (t == NULL)
3664                 return (0);
3665         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3666 }
3667
3668 static void
3669 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3670 {
3671         uint64_t *t;
3672
3673         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3674         if (t == NULL)
3675                 return;
3676         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3677 }
3678
3679 static void
3680 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3681 {
3682         uint64_t *p;
3683         u_int i;
3684
3685         i = residx/CTL_MAX_INIT_PER_PORT;
3686         if (lun->pr_keys[i] != NULL)
3687                 return;
3688         mtx_unlock(&lun->lun_lock);
3689         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3690             M_WAITOK | M_ZERO);
3691         mtx_lock(&lun->lun_lock);
3692         if (lun->pr_keys[i] == NULL)
3693                 lun->pr_keys[i] = p;
3694         else
3695                 free(p, M_CTL);
3696 }
3697
3698 static void
3699 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3700 {
3701         uint64_t *t;
3702
3703         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3704         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3705         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3706 }
3707
3708 /*
3709  * ctl_softc, pool_name, total_ctl_io are passed in.
3710  * npool is passed out.
3711  */
3712 int
3713 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3714                 uint32_t total_ctl_io, void **npool)
3715 {
3716 #ifdef IO_POOLS
3717         struct ctl_io_pool *pool;
3718
3719         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3720                                             M_NOWAIT | M_ZERO);
3721         if (pool == NULL)
3722                 return (ENOMEM);
3723
3724         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3725         pool->ctl_softc = ctl_softc;
3726         pool->zone = uma_zsecond_create(pool->name, NULL,
3727             NULL, NULL, NULL, ctl_softc->io_zone);
3728         /* uma_prealloc(pool->zone, total_ctl_io); */
3729
3730         *npool = pool;
3731 #else
3732         *npool = ctl_softc->io_zone;
3733 #endif
3734         return (0);
3735 }
3736
3737 void
3738 ctl_pool_free(struct ctl_io_pool *pool)
3739 {
3740
3741         if (pool == NULL)
3742                 return;
3743
3744 #ifdef IO_POOLS
3745         uma_zdestroy(pool->zone);
3746         free(pool, M_CTL);
3747 #endif
3748 }
3749
3750 union ctl_io *
3751 ctl_alloc_io(void *pool_ref)
3752 {
3753         union ctl_io *io;
3754 #ifdef IO_POOLS
3755         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3756
3757         io = uma_zalloc(pool->zone, M_WAITOK);
3758 #else
3759         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3760 #endif
3761         if (io != NULL)
3762                 io->io_hdr.pool = pool_ref;
3763         return (io);
3764 }
3765
3766 union ctl_io *
3767 ctl_alloc_io_nowait(void *pool_ref)
3768 {
3769         union ctl_io *io;
3770 #ifdef IO_POOLS
3771         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3772
3773         io = uma_zalloc(pool->zone, M_NOWAIT);
3774 #else
3775         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3776 #endif
3777         if (io != NULL)
3778                 io->io_hdr.pool = pool_ref;
3779         return (io);
3780 }
3781
3782 void
3783 ctl_free_io(union ctl_io *io)
3784 {
3785 #ifdef IO_POOLS
3786         struct ctl_io_pool *pool;
3787 #endif
3788
3789         if (io == NULL)
3790                 return;
3791
3792 #ifdef IO_POOLS
3793         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3794         uma_zfree(pool->zone, io);
3795 #else
3796         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3797 #endif
3798 }
3799
3800 void
3801 ctl_zero_io(union ctl_io *io)
3802 {
3803         void *pool_ref;
3804
3805         if (io == NULL)
3806                 return;
3807
3808         /*
3809          * May need to preserve linked list pointers at some point too.
3810          */
3811         pool_ref = io->io_hdr.pool;
3812         memset(io, 0, sizeof(*io));
3813         io->io_hdr.pool = pool_ref;
3814 }
3815
3816 /*
3817  * This routine is currently used for internal copies of ctl_ios that need
3818  * to persist for some reason after we've already returned status to the
3819  * FETD.  (Thus the flag set.)
3820  *
3821  * XXX XXX
3822  * Note that this makes a blind copy of all fields in the ctl_io, except
3823  * for the pool reference.  This includes any memory that has been
3824  * allocated!  That memory will no longer be valid after done has been
3825  * called, so this would be VERY DANGEROUS for command that actually does
3826  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3827  * start and stop commands, which don't transfer any data, so this is not a
3828  * problem.  If it is used for anything else, the caller would also need to
3829  * allocate data buffer space and this routine would need to be modified to
3830  * copy the data buffer(s) as well.
3831  */
3832 void
3833 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3834 {
3835         void *pool_ref;
3836
3837         if ((src == NULL)
3838          || (dest == NULL))
3839                 return;
3840
3841         /*
3842          * May need to preserve linked list pointers at some point too.
3843          */
3844         pool_ref = dest->io_hdr.pool;
3845
3846         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3847
3848         dest->io_hdr.pool = pool_ref;
3849         /*
3850          * We need to know that this is an internal copy, and doesn't need
3851          * to get passed back to the FETD that allocated it.
3852          */
3853         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3854 }
3855
3856 int
3857 ctl_expand_number(const char *buf, uint64_t *num)
3858 {
3859         char *endptr;
3860         uint64_t number;
3861         unsigned shift;
3862
3863         number = strtoq(buf, &endptr, 0);
3864
3865         switch (tolower((unsigned char)*endptr)) {
3866         case 'e':
3867                 shift = 60;
3868                 break;
3869         case 'p':
3870                 shift = 50;
3871                 break;
3872         case 't':
3873                 shift = 40;
3874                 break;
3875         case 'g':
3876                 shift = 30;
3877                 break;
3878         case 'm':
3879                 shift = 20;
3880                 break;
3881         case 'k':
3882                 shift = 10;
3883                 break;
3884         case 'b':
3885         case '\0': /* No unit. */
3886                 *num = number;
3887                 return (0);
3888         default:
3889                 /* Unrecognized unit. */
3890                 return (-1);
3891         }
3892
3893         if ((number << shift) >> shift != number) {
3894                 /* Overflow */
3895                 return (-1);
3896         }
3897         *num = number << shift;
3898         return (0);
3899 }
3900
3901
3902 /*
3903  * This routine could be used in the future to load default and/or saved
3904  * mode page parameters for a particuar lun.
3905  */
3906 static int
3907 ctl_init_page_index(struct ctl_lun *lun)
3908 {
3909         int i;
3910         struct ctl_page_index *page_index;
3911         const char *value;
3912         uint64_t ival;
3913
3914         memcpy(&lun->mode_pages.index, page_index_template,
3915                sizeof(page_index_template));
3916
3917         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3918
3919                 page_index = &lun->mode_pages.index[i];
3920                 /*
3921                  * If this is a disk-only mode page, there's no point in
3922                  * setting it up.  For some pages, we have to have some
3923                  * basic information about the disk in order to calculate the
3924                  * mode page data.
3925                  */
3926                 if ((lun->be_lun->lun_type != T_DIRECT)
3927                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3928                         continue;
3929
3930                 switch (page_index->page_code & SMPH_PC_MASK) {
3931                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3932                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3933                                 panic("subpage is incorrect!");
3934                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3935                                &rw_er_page_default,
3936                                sizeof(rw_er_page_default));
3937                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3938                                &rw_er_page_changeable,
3939                                sizeof(rw_er_page_changeable));
3940                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3941                                &rw_er_page_default,
3942                                sizeof(rw_er_page_default));
3943                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3944                                &rw_er_page_default,
3945                                sizeof(rw_er_page_default));
3946                         page_index->page_data =
3947                                 (uint8_t *)lun->mode_pages.rw_er_page;
3948                         break;
3949                 }
3950                 case SMS_FORMAT_DEVICE_PAGE: {
3951                         struct scsi_format_page *format_page;
3952
3953                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3954                                 panic("subpage is incorrect!");
3955
3956                         /*
3957                          * Sectors per track are set above.  Bytes per
3958                          * sector need to be set here on a per-LUN basis.
3959                          */
3960                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3961                                &format_page_default,
3962                                sizeof(format_page_default));
3963                         memcpy(&lun->mode_pages.format_page[
3964                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3965                                sizeof(format_page_changeable));
3966                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3967                                &format_page_default,
3968                                sizeof(format_page_default));
3969                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3970                                &format_page_default,
3971                                sizeof(format_page_default));
3972
3973                         format_page = &lun->mode_pages.format_page[
3974                                 CTL_PAGE_CURRENT];
3975                         scsi_ulto2b(lun->be_lun->blocksize,
3976                                     format_page->bytes_per_sector);
3977
3978                         format_page = &lun->mode_pages.format_page[
3979                                 CTL_PAGE_DEFAULT];
3980                         scsi_ulto2b(lun->be_lun->blocksize,
3981                                     format_page->bytes_per_sector);
3982
3983                         format_page = &lun->mode_pages.format_page[
3984                                 CTL_PAGE_SAVED];
3985                         scsi_ulto2b(lun->be_lun->blocksize,
3986                                     format_page->bytes_per_sector);
3987
3988                         page_index->page_data =
3989                                 (uint8_t *)lun->mode_pages.format_page;
3990                         break;
3991                 }
3992                 case SMS_RIGID_DISK_PAGE: {
3993                         struct scsi_rigid_disk_page *rigid_disk_page;
3994                         uint32_t sectors_per_cylinder;
3995                         uint64_t cylinders;
3996 #ifndef __XSCALE__
3997                         int shift;
3998 #endif /* !__XSCALE__ */
3999
4000                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4001                                 panic("invalid subpage value %d",
4002                                       page_index->subpage);
4003
4004                         /*
4005                          * Rotation rate and sectors per track are set
4006                          * above.  We calculate the cylinders here based on
4007                          * capacity.  Due to the number of heads and
4008                          * sectors per track we're using, smaller arrays
4009                          * may turn out to have 0 cylinders.  Linux and
4010                          * FreeBSD don't pay attention to these mode pages
4011                          * to figure out capacity, but Solaris does.  It
4012                          * seems to deal with 0 cylinders just fine, and
4013                          * works out a fake geometry based on the capacity.
4014                          */
4015                         memcpy(&lun->mode_pages.rigid_disk_page[
4016                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4017                                sizeof(rigid_disk_page_default));
4018                         memcpy(&lun->mode_pages.rigid_disk_page[
4019                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4020                                sizeof(rigid_disk_page_changeable));
4021
4022                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4023                                 CTL_DEFAULT_HEADS;
4024
4025                         /*
4026                          * The divide method here will be more accurate,
4027                          * probably, but results in floating point being
4028                          * used in the kernel on i386 (__udivdi3()).  On the
4029                          * XScale, though, __udivdi3() is implemented in
4030                          * software.
4031                          *
4032                          * The shift method for cylinder calculation is
4033                          * accurate if sectors_per_cylinder is a power of
4034                          * 2.  Otherwise it might be slightly off -- you
4035                          * might have a bit of a truncation problem.
4036                          */
4037 #ifdef  __XSCALE__
4038                         cylinders = (lun->be_lun->maxlba + 1) /
4039                                 sectors_per_cylinder;
4040 #else
4041                         for (shift = 31; shift > 0; shift--) {
4042                                 if (sectors_per_cylinder & (1 << shift))
4043                                         break;
4044                         }
4045                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4046 #endif
4047
4048                         /*
4049                          * We've basically got 3 bytes, or 24 bits for the
4050                          * cylinder size in the mode page.  If we're over,
4051                          * just round down to 2^24.
4052                          */
4053                         if (cylinders > 0xffffff)
4054                                 cylinders = 0xffffff;
4055
4056                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4057                                 CTL_PAGE_DEFAULT];
4058                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4059
4060                         if ((value = ctl_get_opt(&lun->be_lun->options,
4061                             "rpm")) != NULL) {
4062                                 scsi_ulto2b(strtol(value, NULL, 0),
4063                                      rigid_disk_page->rotation_rate);
4064                         }
4065
4066                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4067                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4068                                sizeof(rigid_disk_page_default));
4069                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4070                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4071                                sizeof(rigid_disk_page_default));
4072
4073                         page_index->page_data =
4074                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4075                         break;
4076                 }
4077                 case SMS_CACHING_PAGE: {
4078                         struct scsi_caching_page *caching_page;
4079
4080                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4081                                 panic("invalid subpage value %d",
4082                                       page_index->subpage);
4083                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4084                                &caching_page_default,
4085                                sizeof(caching_page_default));
4086                         memcpy(&lun->mode_pages.caching_page[
4087                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4088                                sizeof(caching_page_changeable));
4089                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4090                                &caching_page_default,
4091                                sizeof(caching_page_default));
4092                         caching_page = &lun->mode_pages.caching_page[
4093                             CTL_PAGE_SAVED];
4094                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4095                         if (value != NULL && strcmp(value, "off") == 0)
4096                                 caching_page->flags1 &= ~SCP_WCE;
4097                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4098                         if (value != NULL && strcmp(value, "off") == 0)
4099                                 caching_page->flags1 |= SCP_RCD;
4100                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4101                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4102                                sizeof(caching_page_default));
4103                         page_index->page_data =
4104                                 (uint8_t *)lun->mode_pages.caching_page;
4105                         break;
4106                 }
4107                 case SMS_CONTROL_MODE_PAGE: {
4108                         switch (page_index->subpage) {
4109                         case SMS_SUBPAGE_PAGE_0: {
4110                                 struct scsi_control_page *control_page;
4111
4112                                 memcpy(&lun->mode_pages.control_page[
4113                                     CTL_PAGE_DEFAULT],
4114                                        &control_page_default,
4115                                        sizeof(control_page_default));
4116                                 memcpy(&lun->mode_pages.control_page[
4117                                     CTL_PAGE_CHANGEABLE],
4118                                        &control_page_changeable,
4119                                        sizeof(control_page_changeable));
4120                                 memcpy(&lun->mode_pages.control_page[
4121                                     CTL_PAGE_SAVED],
4122                                        &control_page_default,
4123                                        sizeof(control_page_default));
4124                                 control_page = &lun->mode_pages.control_page[
4125                                     CTL_PAGE_SAVED];
4126                                 value = ctl_get_opt(&lun->be_lun->options,
4127                                     "reordering");
4128                                 if (value != NULL &&
4129                                     strcmp(value, "unrestricted") == 0) {
4130                                         control_page->queue_flags &=
4131                                             ~SCP_QUEUE_ALG_MASK;
4132                                         control_page->queue_flags |=
4133                                             SCP_QUEUE_ALG_UNRESTRICTED;
4134                                 }
4135                                 memcpy(&lun->mode_pages.control_page[
4136                                     CTL_PAGE_CURRENT],
4137                                        &lun->mode_pages.control_page[
4138                                     CTL_PAGE_SAVED],
4139                                        sizeof(control_page_default));
4140                                 page_index->page_data =
4141                                     (uint8_t *)lun->mode_pages.control_page;
4142                                 break;
4143                         }
4144                         case 0x01:
4145                                 memcpy(&lun->mode_pages.control_ext_page[
4146                                     CTL_PAGE_DEFAULT],
4147                                        &control_ext_page_default,
4148                                        sizeof(control_ext_page_default));
4149                                 memcpy(&lun->mode_pages.control_ext_page[
4150                                     CTL_PAGE_CHANGEABLE],
4151                                        &control_ext_page_changeable,
4152                                        sizeof(control_ext_page_changeable));
4153                                 memcpy(&lun->mode_pages.control_ext_page[
4154                                     CTL_PAGE_SAVED],
4155                                        &control_ext_page_default,
4156                                        sizeof(control_ext_page_default));
4157                                 memcpy(&lun->mode_pages.control_ext_page[
4158                                     CTL_PAGE_CURRENT],
4159                                        &lun->mode_pages.control_ext_page[
4160                                     CTL_PAGE_SAVED],
4161                                        sizeof(control_ext_page_default));
4162                                 page_index->page_data =
4163                                     (uint8_t *)lun->mode_pages.control_ext_page;
4164                                 break;
4165                         }
4166                         break;
4167                 }
4168                 case SMS_INFO_EXCEPTIONS_PAGE: {
4169                         switch (page_index->subpage) {
4170                         case SMS_SUBPAGE_PAGE_0:
4171                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4172                                        &ie_page_default,
4173                                        sizeof(ie_page_default));
4174                                 memcpy(&lun->mode_pages.ie_page[
4175                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4176                                        sizeof(ie_page_changeable));
4177                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4178                                        &ie_page_default,
4179                                        sizeof(ie_page_default));
4180                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4181                                        &ie_page_default,
4182                                        sizeof(ie_page_default));
4183                                 page_index->page_data =
4184                                         (uint8_t *)lun->mode_pages.ie_page;
4185                                 break;
4186                         case 0x02: {
4187                                 struct ctl_logical_block_provisioning_page *page;
4188
4189                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4190                                        &lbp_page_default,
4191                                        sizeof(lbp_page_default));
4192                                 memcpy(&lun->mode_pages.lbp_page[
4193                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4194                                        sizeof(lbp_page_changeable));
4195                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4196                                        &lbp_page_default,
4197                                        sizeof(lbp_page_default));
4198                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4199                                 value = ctl_get_opt(&lun->be_lun->options,
4200                                     "avail-threshold");
4201                                 if (value != NULL &&
4202                                     ctl_expand_number(value, &ival) == 0) {
4203                                         page->descr[0].flags |= SLBPPD_ENABLED |
4204                                             SLBPPD_ARMING_DEC;
4205                                         if (lun->be_lun->blocksize)
4206                                                 ival /= lun->be_lun->blocksize;
4207                                         else
4208                                                 ival /= 512;
4209                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4210                                             page->descr[0].count);
4211                                 }
4212                                 value = ctl_get_opt(&lun->be_lun->options,
4213                                     "used-threshold");
4214                                 if (value != NULL &&
4215                                     ctl_expand_number(value, &ival) == 0) {
4216                                         page->descr[1].flags |= SLBPPD_ENABLED |
4217                                             SLBPPD_ARMING_INC;
4218                                         if (lun->be_lun->blocksize)
4219                                                 ival /= lun->be_lun->blocksize;
4220                                         else
4221                                                 ival /= 512;
4222                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4223                                             page->descr[1].count);
4224                                 }
4225                                 value = ctl_get_opt(&lun->be_lun->options,
4226                                     "pool-avail-threshold");
4227                                 if (value != NULL &&
4228                                     ctl_expand_number(value, &ival) == 0) {
4229                                         page->descr[2].flags |= SLBPPD_ENABLED |
4230                                             SLBPPD_ARMING_DEC;
4231                                         if (lun->be_lun->blocksize)
4232                                                 ival /= lun->be_lun->blocksize;
4233                                         else
4234                                                 ival /= 512;
4235                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4236                                             page->descr[2].count);
4237                                 }
4238                                 value = ctl_get_opt(&lun->be_lun->options,
4239                                     "pool-used-threshold");
4240                                 if (value != NULL &&
4241                                     ctl_expand_number(value, &ival) == 0) {
4242                                         page->descr[3].flags |= SLBPPD_ENABLED |
4243                                             SLBPPD_ARMING_INC;
4244                                         if (lun->be_lun->blocksize)
4245                                                 ival /= lun->be_lun->blocksize;
4246                                         else
4247                                                 ival /= 512;
4248                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4249                                             page->descr[3].count);
4250                                 }
4251                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4252                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4253                                        sizeof(lbp_page_default));
4254                                 page_index->page_data =
4255                                         (uint8_t *)lun->mode_pages.lbp_page;
4256                         }}
4257                         break;
4258                 }
4259                 case SMS_VENDOR_SPECIFIC_PAGE:{
4260                         switch (page_index->subpage) {
4261                         case DBGCNF_SUBPAGE_CODE: {
4262                                 struct copan_debugconf_subpage *current_page,
4263                                                                *saved_page;
4264
4265                                 memcpy(&lun->mode_pages.debugconf_subpage[
4266                                        CTL_PAGE_CURRENT],
4267                                        &debugconf_page_default,
4268                                        sizeof(debugconf_page_default));
4269                                 memcpy(&lun->mode_pages.debugconf_subpage[
4270                                        CTL_PAGE_CHANGEABLE],
4271                                        &debugconf_page_changeable,
4272                                        sizeof(debugconf_page_changeable));
4273                                 memcpy(&lun->mode_pages.debugconf_subpage[
4274                                        CTL_PAGE_DEFAULT],
4275                                        &debugconf_page_default,
4276                                        sizeof(debugconf_page_default));
4277                                 memcpy(&lun->mode_pages.debugconf_subpage[
4278                                        CTL_PAGE_SAVED],
4279                                        &debugconf_page_default,
4280                                        sizeof(debugconf_page_default));
4281                                 page_index->page_data =
4282                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4283
4284                                 current_page = (struct copan_debugconf_subpage *)
4285                                         (page_index->page_data +
4286                                          (page_index->page_len *
4287                                           CTL_PAGE_CURRENT));
4288                                 saved_page = (struct copan_debugconf_subpage *)
4289                                         (page_index->page_data +
4290                                          (page_index->page_len *
4291                                           CTL_PAGE_SAVED));
4292                                 break;
4293                         }
4294                         default:
4295                                 panic("invalid subpage value %d",
4296                                       page_index->subpage);
4297                                 break;
4298                         }
4299                         break;
4300                 }
4301                 default:
4302                         panic("invalid page value %d",
4303                               page_index->page_code & SMPH_PC_MASK);
4304                         break;
4305         }
4306         }
4307
4308         return (CTL_RETVAL_COMPLETE);
4309 }
4310
4311 static int
4312 ctl_init_log_page_index(struct ctl_lun *lun)
4313 {
4314         struct ctl_page_index *page_index;
4315         int i, j, k, prev;
4316
4317         memcpy(&lun->log_pages.index, log_page_index_template,
4318                sizeof(log_page_index_template));
4319
4320         prev = -1;
4321         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4322
4323                 page_index = &lun->log_pages.index[i];
4324                 /*
4325                  * If this is a disk-only mode page, there's no point in
4326                  * setting it up.  For some pages, we have to have some
4327                  * basic information about the disk in order to calculate the
4328                  * mode page data.
4329                  */
4330                 if ((lun->be_lun->lun_type != T_DIRECT)
4331                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4332                         continue;
4333
4334                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4335                      lun->backend->lun_attr == NULL)
4336                         continue;
4337
4338                 if (page_index->page_code != prev) {
4339                         lun->log_pages.pages_page[j] = page_index->page_code;
4340                         prev = page_index->page_code;
4341                         j++;
4342                 }
4343                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4344                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4345                 k++;
4346         }
4347         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4348         lun->log_pages.index[0].page_len = j;
4349         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4350         lun->log_pages.index[1].page_len = k * 2;
4351         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4352         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4353         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4354         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4355
4356         return (CTL_RETVAL_COMPLETE);
4357 }
4358
4359 static int
4360 hex2bin(const char *str, uint8_t *buf, int buf_size)
4361 {
4362         int i;
4363         u_char c;
4364
4365         memset(buf, 0, buf_size);
4366         while (isspace(str[0]))
4367                 str++;
4368         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4369                 str += 2;
4370         buf_size *= 2;
4371         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4372                 c = str[i];
4373                 if (isdigit(c))
4374                         c -= '0';
4375                 else if (isalpha(c))
4376                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4377                 else
4378                         break;
4379                 if (c >= 16)
4380                         break;
4381                 if ((i & 1) == 0)
4382                         buf[i / 2] |= (c << 4);
4383                 else
4384                         buf[i / 2] |= c;
4385         }
4386         return ((i + 1) / 2);
4387 }
4388
4389 /*
4390  * LUN allocation.
4391  *
4392  * Requirements:
4393  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4394  *   wants us to allocate the LUN and he can block.
4395  * - ctl_softc is always set
4396  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4397  *
4398  * Returns 0 for success, non-zero (errno) for failure.
4399  */
4400 static int
4401 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4402               struct ctl_be_lun *const be_lun)
4403 {
4404         struct ctl_lun *nlun, *lun;
4405         struct scsi_vpd_id_descriptor *desc;
4406         struct scsi_vpd_id_t10 *t10id;
4407         const char *eui, *naa, *scsiname, *vendor;
4408         int lun_number, i, lun_malloced;
4409         int devidlen, idlen1, idlen2 = 0, len;
4410
4411         if (be_lun == NULL)
4412                 return (EINVAL);
4413
4414         /*
4415          * We currently only support Direct Access or Processor LUN types.
4416          */
4417         switch (be_lun->lun_type) {
4418         case T_DIRECT:
4419                 break;
4420         case T_PROCESSOR:
4421                 break;
4422         case T_SEQUENTIAL:
4423         case T_CHANGER:
4424         default:
4425                 be_lun->lun_config_status(be_lun->be_lun,
4426                                           CTL_LUN_CONFIG_FAILURE);
4427                 break;
4428         }
4429         if (ctl_lun == NULL) {
4430                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4431                 lun_malloced = 1;
4432         } else {
4433                 lun_malloced = 0;
4434                 lun = ctl_lun;
4435         }
4436
4437         memset(lun, 0, sizeof(*lun));
4438         if (lun_malloced)
4439                 lun->flags = CTL_LUN_MALLOCED;
4440
4441         /* Generate LUN ID. */
4442         devidlen = max(CTL_DEVID_MIN_LEN,
4443             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4444         idlen1 = sizeof(*t10id) + devidlen;
4445         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4446         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4447         if (scsiname != NULL) {
4448                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4449                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4450         }
4451         eui = ctl_get_opt(&be_lun->options, "eui");
4452         if (eui != NULL) {
4453                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4454         }
4455         naa = ctl_get_opt(&be_lun->options, "naa");
4456         if (naa != NULL) {
4457                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4458         }
4459         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4460             M_CTL, M_WAITOK | M_ZERO);
4461         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4462         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4463         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4464         desc->length = idlen1;
4465         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4466         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4467         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4468                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4469         } else {
4470                 strncpy(t10id->vendor, vendor,
4471                     min(sizeof(t10id->vendor), strlen(vendor)));
4472         }
4473         strncpy((char *)t10id->vendor_spec_id,
4474             (char *)be_lun->device_id, devidlen);
4475         if (scsiname != NULL) {
4476                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4477                     desc->length);
4478                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4479                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4480                     SVPD_ID_TYPE_SCSI_NAME;
4481                 desc->length = idlen2;
4482                 strlcpy(desc->identifier, scsiname, idlen2);
4483         }
4484         if (eui != NULL) {
4485                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4486                     desc->length);
4487                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4488                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4489                     SVPD_ID_TYPE_EUI64;
4490                 desc->length = hex2bin(eui, desc->identifier, 16);
4491                 desc->length = desc->length > 12 ? 16 :
4492                     (desc->length > 8 ? 12 : 8);
4493                 len -= 16 - desc->length;
4494         }
4495         if (naa != NULL) {
4496                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4497                     desc->length);
4498                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4499                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4500                     SVPD_ID_TYPE_NAA;
4501                 desc->length = hex2bin(naa, desc->identifier, 16);
4502                 desc->length = desc->length > 8 ? 16 : 8;
4503                 len -= 16 - desc->length;
4504         }
4505         lun->lun_devid->len = len;
4506
4507         mtx_lock(&ctl_softc->ctl_lock);
4508         /*
4509          * See if the caller requested a particular LUN number.  If so, see
4510          * if it is available.  Otherwise, allocate the first available LUN.
4511          */
4512         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4513                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4514                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4515                         mtx_unlock(&ctl_softc->ctl_lock);
4516                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4517                                 printf("ctl: requested LUN ID %d is higher "
4518                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4519                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4520                         } else {
4521                                 /*
4522                                  * XXX KDM return an error, or just assign
4523                                  * another LUN ID in this case??
4524                                  */
4525                                 printf("ctl: requested LUN ID %d is already "
4526                                        "in use\n", be_lun->req_lun_id);
4527                         }
4528                         if (lun->flags & CTL_LUN_MALLOCED)
4529                                 free(lun, M_CTL);
4530                         be_lun->lun_config_status(be_lun->be_lun,
4531                                                   CTL_LUN_CONFIG_FAILURE);
4532                         return (ENOSPC);
4533                 }
4534                 lun_number = be_lun->req_lun_id;
4535         } else {
4536                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4537                 if (lun_number == -1) {
4538                         mtx_unlock(&ctl_softc->ctl_lock);
4539                         printf("ctl: can't allocate LUN, out of LUNs\n");
4540                         if (lun->flags & CTL_LUN_MALLOCED)
4541                                 free(lun, M_CTL);
4542                         be_lun->lun_config_status(be_lun->be_lun,
4543                                                   CTL_LUN_CONFIG_FAILURE);
4544                         return (ENOSPC);
4545                 }
4546         }
4547         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4548
4549         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4550         lun->lun = lun_number;
4551         lun->be_lun = be_lun;
4552         /*
4553          * The processor LUN is always enabled.  Disk LUNs come on line
4554          * disabled, and must be enabled by the backend.
4555          */
4556         lun->flags |= CTL_LUN_DISABLED;
4557         lun->backend = be_lun->be;
4558         be_lun->ctl_lun = lun;
4559         be_lun->lun_id = lun_number;
4560         atomic_add_int(&be_lun->be->num_luns, 1);
4561         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4562                 lun->flags |= CTL_LUN_OFFLINE;
4563
4564         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4565                 lun->flags |= CTL_LUN_STOPPED;
4566
4567         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4568                 lun->flags |= CTL_LUN_INOPERABLE;
4569
4570         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4571                 lun->flags |= CTL_LUN_PRIMARY_SC;
4572
4573         lun->ctl_softc = ctl_softc;
4574 #ifdef CTL_TIME_IO
4575         lun->last_busy = getsbinuptime();
4576 #endif
4577         TAILQ_INIT(&lun->ooa_queue);
4578         TAILQ_INIT(&lun->blocked_queue);
4579         STAILQ_INIT(&lun->error_list);
4580         ctl_tpc_lun_init(lun);
4581
4582         /*
4583          * Initialize the mode and log page index.
4584          */
4585         ctl_init_page_index(lun);
4586         ctl_init_log_page_index(lun);
4587
4588         /*
4589          * Now, before we insert this lun on the lun list, set the lun
4590          * inventory changed UA for all other luns.
4591          */
4592         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4593                 mtx_lock(&nlun->lun_lock);
4594                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4595                 mtx_unlock(&nlun->lun_lock);
4596         }
4597
4598         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4599
4600         ctl_softc->ctl_luns[lun_number] = lun;
4601
4602         ctl_softc->num_luns++;
4603
4604         /* Setup statistics gathering */
4605         lun->stats.device_type = be_lun->lun_type;
4606         lun->stats.lun_number = lun_number;
4607         if (lun->stats.device_type == T_DIRECT)
4608                 lun->stats.blocksize = be_lun->blocksize;
4609         else
4610                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4611         for (i = 0;i < CTL_MAX_PORTS;i++)
4612                 lun->stats.ports[i].targ_port = i;
4613
4614         mtx_unlock(&ctl_softc->ctl_lock);
4615
4616         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4617         return (0);
4618 }
4619
4620 /*
4621  * Delete a LUN.
4622  * Assumptions:
4623  * - LUN has already been marked invalid and any pending I/O has been taken
4624  *   care of.
4625  */
4626 static int
4627 ctl_free_lun(struct ctl_lun *lun)
4628 {
4629         struct ctl_softc *softc;
4630         struct ctl_lun *nlun;
4631         int i;
4632
4633         softc = lun->ctl_softc;
4634
4635         mtx_assert(&softc->ctl_lock, MA_OWNED);
4636
4637         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4638
4639         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4640
4641         softc->ctl_luns[lun->lun] = NULL;
4642
4643         if (!TAILQ_EMPTY(&lun->ooa_queue))
4644                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4645
4646         softc->num_luns--;
4647
4648         /*
4649          * Tell the backend to free resources, if this LUN has a backend.
4650          */
4651         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4652         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4653
4654         ctl_tpc_lun_shutdown(lun);
4655         mtx_destroy(&lun->lun_lock);
4656         free(lun->lun_devid, M_CTL);
4657         for (i = 0; i < CTL_MAX_PORTS; i++)
4658                 free(lun->pending_ua[i], M_CTL);
4659         for (i = 0; i < CTL_MAX_PORTS; i++)
4660                 free(lun->pr_keys[i], M_CTL);
4661         free(lun->write_buffer, M_CTL);
4662         if (lun->flags & CTL_LUN_MALLOCED)
4663                 free(lun, M_CTL);
4664
4665         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4666                 mtx_lock(&nlun->lun_lock);
4667                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4668                 mtx_unlock(&nlun->lun_lock);
4669         }
4670
4671         return (0);
4672 }
4673
4674 static void
4675 ctl_create_lun(struct ctl_be_lun *be_lun)
4676 {
4677         struct ctl_softc *softc;
4678
4679         softc = control_softc;
4680
4681         /*
4682          * ctl_alloc_lun() should handle all potential failure cases.
4683          */
4684         ctl_alloc_lun(softc, NULL, be_lun);
4685 }
4686
4687 int
4688 ctl_add_lun(struct ctl_be_lun *be_lun)
4689 {
4690         struct ctl_softc *softc = control_softc;
4691
4692         mtx_lock(&softc->ctl_lock);
4693         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4694         mtx_unlock(&softc->ctl_lock);
4695         wakeup(&softc->pending_lun_queue);
4696
4697         return (0);
4698 }
4699
4700 int
4701 ctl_enable_lun(struct ctl_be_lun *be_lun)
4702 {
4703         struct ctl_softc *softc;
4704         struct ctl_port *port, *nport;
4705         struct ctl_lun *lun;
4706         int retval;
4707
4708         lun = (struct ctl_lun *)be_lun->ctl_lun;
4709         softc = lun->ctl_softc;
4710
4711         mtx_lock(&softc->ctl_lock);
4712         mtx_lock(&lun->lun_lock);
4713         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4714                 /*
4715                  * eh?  Why did we get called if the LUN is already
4716                  * enabled?
4717                  */
4718                 mtx_unlock(&lun->lun_lock);
4719                 mtx_unlock(&softc->ctl_lock);
4720                 return (0);
4721         }
4722         lun->flags &= ~CTL_LUN_DISABLED;
4723         mtx_unlock(&lun->lun_lock);
4724
4725         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4726                 nport = STAILQ_NEXT(port, links);
4727                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4728                     port->lun_map != NULL || port->lun_enable == NULL)
4729                         continue;
4730
4731                 /*
4732                  * Drop the lock while we call the FETD's enable routine.
4733                  * This can lead to a callback into CTL (at least in the
4734                  * case of the internal initiator frontend.
4735                  */
4736                 mtx_unlock(&softc->ctl_lock);
4737                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4738                 mtx_lock(&softc->ctl_lock);
4739                 if (retval != 0) {
4740                         printf("%s: FETD %s port %d returned error "
4741                                "%d for lun_enable on lun %jd\n",
4742                                __func__, port->port_name, port->targ_port,
4743                                retval, (intmax_t)lun->lun);
4744                 }
4745         }
4746
4747         mtx_unlock(&softc->ctl_lock);
4748         ctl_isc_announce_lun(lun);
4749
4750         return (0);
4751 }
4752
4753 int
4754 ctl_disable_lun(struct ctl_be_lun *be_lun)
4755 {
4756         struct ctl_softc *softc;
4757         struct ctl_port *port;
4758         struct ctl_lun *lun;
4759         int retval;
4760
4761         lun = (struct ctl_lun *)be_lun->ctl_lun;
4762         softc = lun->ctl_softc;
4763
4764         mtx_lock(&softc->ctl_lock);
4765         mtx_lock(&lun->lun_lock);
4766         if (lun->flags & CTL_LUN_DISABLED) {
4767                 mtx_unlock(&lun->lun_lock);
4768                 mtx_unlock(&softc->ctl_lock);
4769                 return (0);
4770         }
4771         lun->flags |= CTL_LUN_DISABLED;
4772         mtx_unlock(&lun->lun_lock);
4773
4774         STAILQ_FOREACH(port, &softc->port_list, links) {
4775                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4776                     port->lun_map != NULL || port->lun_disable == NULL)
4777                         continue;
4778
4779                 /*
4780                  * Drop the lock before we call the frontend's disable
4781                  * routine, to avoid lock order reversals.
4782                  *
4783                  * XXX KDM what happens if the frontend list changes while
4784                  * we're traversing it?  It's unlikely, but should be handled.
4785                  */
4786                 mtx_unlock(&softc->ctl_lock);
4787                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4788                 mtx_lock(&softc->ctl_lock);
4789                 if (retval != 0) {
4790                         printf("%s: FETD %s port %d returned error "
4791                                "%d for lun_disable on lun %jd\n",
4792                                __func__, port->port_name, port->targ_port,
4793                                retval, (intmax_t)lun->lun);
4794                 }
4795         }
4796
4797         mtx_unlock(&softc->ctl_lock);
4798         ctl_isc_announce_lun(lun);
4799
4800         return (0);
4801 }
4802
4803 int
4804 ctl_start_lun(struct ctl_be_lun *be_lun)
4805 {
4806         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4807
4808         mtx_lock(&lun->lun_lock);
4809         lun->flags &= ~CTL_LUN_STOPPED;
4810         mtx_unlock(&lun->lun_lock);
4811         return (0);
4812 }
4813
4814 int
4815 ctl_stop_lun(struct ctl_be_lun *be_lun)
4816 {
4817         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4818
4819         mtx_lock(&lun->lun_lock);
4820         lun->flags |= CTL_LUN_STOPPED;
4821         mtx_unlock(&lun->lun_lock);
4822         return (0);
4823 }
4824
4825 int
4826 ctl_lun_offline(struct ctl_be_lun *be_lun)
4827 {
4828         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4829
4830         mtx_lock(&lun->lun_lock);
4831         lun->flags |= CTL_LUN_OFFLINE;
4832         mtx_unlock(&lun->lun_lock);
4833         return (0);
4834 }
4835
4836 int
4837 ctl_lun_online(struct ctl_be_lun *be_lun)
4838 {
4839         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4840
4841         mtx_lock(&lun->lun_lock);
4842         lun->flags &= ~CTL_LUN_OFFLINE;
4843         mtx_unlock(&lun->lun_lock);
4844         return (0);
4845 }
4846
4847 int
4848 ctl_lun_primary(struct ctl_be_lun *be_lun)
4849 {
4850         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4851
4852         mtx_lock(&lun->lun_lock);
4853         lun->flags |= CTL_LUN_PRIMARY_SC;
4854         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4855         mtx_unlock(&lun->lun_lock);
4856         ctl_isc_announce_lun(lun);
4857         return (0);
4858 }
4859
4860 int
4861 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4862 {
4863         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4864
4865         mtx_lock(&lun->lun_lock);
4866         lun->flags &= ~CTL_LUN_PRIMARY_SC;
4867         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4868         mtx_unlock(&lun->lun_lock);
4869         ctl_isc_announce_lun(lun);
4870         return (0);
4871 }
4872
4873 int
4874 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4875 {
4876         struct ctl_softc *softc;
4877         struct ctl_lun *lun;
4878
4879         lun = (struct ctl_lun *)be_lun->ctl_lun;
4880         softc = lun->ctl_softc;
4881
4882         mtx_lock(&lun->lun_lock);
4883
4884         /*
4885          * The LUN needs to be disabled before it can be marked invalid.
4886          */
4887         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4888                 mtx_unlock(&lun->lun_lock);
4889                 return (-1);
4890         }
4891         /*
4892          * Mark the LUN invalid.
4893          */
4894         lun->flags |= CTL_LUN_INVALID;
4895
4896         /*
4897          * If there is nothing in the OOA queue, go ahead and free the LUN.
4898          * If we have something in the OOA queue, we'll free it when the
4899          * last I/O completes.
4900          */
4901         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4902                 mtx_unlock(&lun->lun_lock);
4903                 mtx_lock(&softc->ctl_lock);
4904                 ctl_free_lun(lun);
4905                 mtx_unlock(&softc->ctl_lock);
4906         } else
4907                 mtx_unlock(&lun->lun_lock);
4908
4909         return (0);
4910 }
4911
4912 int
4913 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4914 {
4915         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4916
4917         mtx_lock(&lun->lun_lock);
4918         lun->flags |= CTL_LUN_INOPERABLE;
4919         mtx_unlock(&lun->lun_lock);
4920         return (0);
4921 }
4922
4923 int
4924 ctl_lun_operable(struct ctl_be_lun *be_lun)
4925 {
4926         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4927
4928         mtx_lock(&lun->lun_lock);
4929         lun->flags &= ~CTL_LUN_INOPERABLE;
4930         mtx_unlock(&lun->lun_lock);
4931         return (0);
4932 }
4933
4934 void
4935 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4936 {
4937         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4938         union ctl_ha_msg msg;
4939
4940         mtx_lock(&lun->lun_lock);
4941         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4942         mtx_unlock(&lun->lun_lock);
4943         if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4944                 /* Send msg to other side. */
4945                 bzero(&msg.ua, sizeof(msg.ua));
4946                 msg.hdr.msg_type = CTL_MSG_UA;
4947                 msg.hdr.nexus.initid = -1;
4948                 msg.hdr.nexus.targ_port = -1;
4949                 msg.hdr.nexus.targ_lun = lun->lun;
4950                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
4951                 msg.ua.ua_all = 1;
4952                 msg.ua.ua_set = 1;
4953                 msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4954                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4955                     M_WAITOK);
4956         }
4957 }
4958
4959 /*
4960  * Backend "memory move is complete" callback for requests that never
4961  * make it down to say RAIDCore's configuration code.
4962  */
4963 int
4964 ctl_config_move_done(union ctl_io *io)
4965 {
4966         int retval;
4967
4968         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4969         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4970             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4971
4972         if ((io->io_hdr.port_status != 0) &&
4973             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4974              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4975                 /*
4976                  * For hardware error sense keys, the sense key
4977                  * specific value is defined to be a retry count,
4978                  * but we use it to pass back an internal FETD
4979                  * error code.  XXX KDM  Hopefully the FETD is only
4980                  * using 16 bits for an error code, since that's
4981                  * all the space we have in the sks field.
4982                  */
4983                 ctl_set_internal_failure(&io->scsiio,
4984                                          /*sks_valid*/ 1,
4985                                          /*retry_count*/
4986                                          io->io_hdr.port_status);
4987         }
4988
4989         if (ctl_debug & CTL_DEBUG_CDB_DATA)
4990                 ctl_data_print(io);
4991         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4992             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4993              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4994             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4995                 /*
4996                  * XXX KDM just assuming a single pointer here, and not a
4997                  * S/G list.  If we start using S/G lists for config data,
4998                  * we'll need to know how to clean them up here as well.
4999                  */
5000                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5001                         free(io->scsiio.kern_data_ptr, M_CTL);
5002                 ctl_done(io);
5003                 retval = CTL_RETVAL_COMPLETE;
5004         } else {
5005                 /*
5006                  * XXX KDM now we need to continue data movement.  Some
5007                  * options:
5008                  * - call ctl_scsiio() again?  We don't do this for data
5009                  *   writes, because for those at least we know ahead of
5010                  *   time where the write will go and how long it is.  For
5011                  *   config writes, though, that information is largely
5012                  *   contained within the write itself, thus we need to
5013                  *   parse out the data again.
5014                  *
5015                  * - Call some other function once the data is in?
5016                  */
5017
5018                 /*
5019                  * XXX KDM call ctl_scsiio() again for now, and check flag
5020                  * bits to see whether we're allocated or not.
5021                  */
5022                 retval = ctl_scsiio(&io->scsiio);
5023         }
5024         return (retval);
5025 }
5026
5027 /*
5028  * This gets called by a backend driver when it is done with a
5029  * data_submit method.
5030  */
5031 void
5032 ctl_data_submit_done(union ctl_io *io)
5033 {
5034         /*
5035          * If the IO_CONT flag is set, we need to call the supplied
5036          * function to continue processing the I/O, instead of completing
5037          * the I/O just yet.
5038          *
5039          * If there is an error, though, we don't want to keep processing.
5040          * Instead, just send status back to the initiator.
5041          */
5042         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5043             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5044             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5045              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5046                 io->scsiio.io_cont(io);
5047                 return;
5048         }
5049         ctl_done(io);
5050 }
5051
5052 /*
5053  * This gets called by a backend driver when it is done with a
5054  * configuration write.
5055  */
5056 void
5057 ctl_config_write_done(union ctl_io *io)
5058 {
5059         uint8_t *buf;
5060
5061         /*
5062          * If the IO_CONT flag is set, we need to call the supplied
5063          * function to continue processing the I/O, instead of completing
5064          * the I/O just yet.
5065          *
5066          * If there is an error, though, we don't want to keep processing.
5067          * Instead, just send status back to the initiator.
5068          */
5069         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5070             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5071             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5072              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5073                 io->scsiio.io_cont(io);
5074                 return;
5075         }
5076         /*
5077          * Since a configuration write can be done for commands that actually
5078          * have data allocated, like write buffer, and commands that have
5079          * no data, like start/stop unit, we need to check here.
5080          */
5081         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5082                 buf = io->scsiio.kern_data_ptr;
5083         else
5084                 buf = NULL;
5085         ctl_done(io);
5086         if (buf)
5087                 free(buf, M_CTL);
5088 }
5089
5090 void
5091 ctl_config_read_done(union ctl_io *io)
5092 {
5093         uint8_t *buf;
5094
5095         /*
5096          * If there is some error -- we are done, skip data transfer.
5097          */
5098         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5099             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5100              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5101                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5102                         buf = io->scsiio.kern_data_ptr;
5103                 else
5104                         buf = NULL;
5105                 ctl_done(io);
5106                 if (buf)
5107                         free(buf, M_CTL);
5108                 return;
5109         }
5110
5111         /*
5112          * If the IO_CONT flag is set, we need to call the supplied
5113          * function to continue processing the I/O, instead of completing
5114          * the I/O just yet.
5115          */
5116         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5117                 io->scsiio.io_cont(io);
5118                 return;
5119         }
5120
5121         ctl_datamove(io);
5122 }
5123
5124 /*
5125  * SCSI release command.
5126  */
5127 int
5128 ctl_scsi_release(struct ctl_scsiio *ctsio)
5129 {
5130         int length, longid, thirdparty_id, resv_id;
5131         struct ctl_lun *lun;
5132         uint32_t residx;
5133
5134         length = 0;
5135         resv_id = 0;
5136
5137         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5138
5139         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5140         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5141
5142         switch (ctsio->cdb[0]) {
5143         case RELEASE_10: {
5144                 struct scsi_release_10 *cdb;
5145
5146                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5147
5148                 if (cdb->byte2 & SR10_LONGID)
5149                         longid = 1;
5150                 else
5151                         thirdparty_id = cdb->thirdparty_id;
5152
5153                 resv_id = cdb->resv_id;
5154                 length = scsi_2btoul(cdb->length);
5155                 break;
5156         }
5157         }
5158
5159
5160         /*
5161          * XXX KDM right now, we only support LUN reservation.  We don't
5162          * support 3rd party reservations, or extent reservations, which
5163          * might actually need the parameter list.  If we've gotten this
5164          * far, we've got a LUN reservation.  Anything else got kicked out
5165          * above.  So, according to SPC, ignore the length.
5166          */
5167         length = 0;
5168
5169         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5170          && (length > 0)) {
5171                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5172                 ctsio->kern_data_len = length;
5173                 ctsio->kern_total_len = length;
5174                 ctsio->kern_data_resid = 0;
5175                 ctsio->kern_rel_offset = 0;
5176                 ctsio->kern_sg_entries = 0;
5177                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5178                 ctsio->be_move_done = ctl_config_move_done;
5179                 ctl_datamove((union ctl_io *)ctsio);
5180
5181                 return (CTL_RETVAL_COMPLETE);
5182         }
5183
5184         if (length > 0)
5185                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5186
5187         mtx_lock(&lun->lun_lock);
5188
5189         /*
5190          * According to SPC, it is not an error for an intiator to attempt
5191          * to release a reservation on a LUN that isn't reserved, or that
5192          * is reserved by another initiator.  The reservation can only be
5193          * released, though, by the initiator who made it or by one of
5194          * several reset type events.
5195          */
5196         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5197                         lun->flags &= ~CTL_LUN_RESERVED;
5198
5199         mtx_unlock(&lun->lun_lock);
5200
5201         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5202                 free(ctsio->kern_data_ptr, M_CTL);
5203                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5204         }
5205
5206         ctl_set_success(ctsio);
5207         ctl_done((union ctl_io *)ctsio);
5208         return (CTL_RETVAL_COMPLETE);
5209 }
5210
5211 int
5212 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5213 {
5214         int extent, thirdparty, longid;
5215         int resv_id, length;
5216         uint64_t thirdparty_id;
5217         struct ctl_lun *lun;
5218         uint32_t residx;
5219
5220         extent = 0;
5221         thirdparty = 0;
5222         longid = 0;
5223         resv_id = 0;
5224         length = 0;
5225         thirdparty_id = 0;
5226
5227         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5228
5229         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5230         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5231
5232         switch (ctsio->cdb[0]) {
5233         case RESERVE_10: {
5234                 struct scsi_reserve_10 *cdb;
5235
5236                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5237
5238                 if (cdb->byte2 & SR10_LONGID)
5239                         longid = 1;
5240                 else
5241                         thirdparty_id = cdb->thirdparty_id;
5242
5243                 resv_id = cdb->resv_id;
5244                 length = scsi_2btoul(cdb->length);
5245                 break;
5246         }
5247         }
5248
5249         /*
5250          * XXX KDM right now, we only support LUN reservation.  We don't
5251          * support 3rd party reservations, or extent reservations, which
5252          * might actually need the parameter list.  If we've gotten this
5253          * far, we've got a LUN reservation.  Anything else got kicked out
5254          * above.  So, according to SPC, ignore the length.
5255          */
5256         length = 0;
5257
5258         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5259          && (length > 0)) {
5260                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5261                 ctsio->kern_data_len = length;
5262                 ctsio->kern_total_len = length;
5263                 ctsio->kern_data_resid = 0;
5264                 ctsio->kern_rel_offset = 0;
5265                 ctsio->kern_sg_entries = 0;
5266                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5267                 ctsio->be_move_done = ctl_config_move_done;
5268                 ctl_datamove((union ctl_io *)ctsio);
5269
5270                 return (CTL_RETVAL_COMPLETE);
5271         }
5272
5273         if (length > 0)
5274                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5275
5276         mtx_lock(&lun->lun_lock);
5277         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5278                 ctl_set_reservation_conflict(ctsio);
5279                 goto bailout;
5280         }
5281
5282         lun->flags |= CTL_LUN_RESERVED;
5283         lun->res_idx = residx;
5284
5285         ctl_set_success(ctsio);
5286
5287 bailout:
5288         mtx_unlock(&lun->lun_lock);
5289
5290         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5291                 free(ctsio->kern_data_ptr, M_CTL);
5292                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5293         }
5294
5295         ctl_done((union ctl_io *)ctsio);
5296         return (CTL_RETVAL_COMPLETE);
5297 }
5298
5299 int
5300 ctl_start_stop(struct ctl_scsiio *ctsio)
5301 {
5302         struct scsi_start_stop_unit *cdb;
5303         struct ctl_lun *lun;
5304         int retval;
5305
5306         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5307
5308         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5309         retval = 0;
5310
5311         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5312
5313         /*
5314          * XXX KDM
5315          * We don't support the immediate bit on a stop unit.  In order to
5316          * do that, we would need to code up a way to know that a stop is
5317          * pending, and hold off any new commands until it completes, one
5318          * way or another.  Then we could accept or reject those commands
5319          * depending on its status.  We would almost need to do the reverse
5320          * of what we do below for an immediate start -- return the copy of
5321          * the ctl_io to the FETD with status to send to the host (and to
5322          * free the copy!) and then free the original I/O once the stop
5323          * actually completes.  That way, the OOA queue mechanism can work
5324          * to block commands that shouldn't proceed.  Another alternative
5325          * would be to put the copy in the queue in place of the original,
5326          * and return the original back to the caller.  That could be
5327          * slightly safer..
5328          */
5329         if ((cdb->byte2 & SSS_IMMED)
5330          && ((cdb->how & SSS_START) == 0)) {
5331                 ctl_set_invalid_field(ctsio,
5332                                       /*sks_valid*/ 1,
5333                                       /*command*/ 1,
5334                                       /*field*/ 1,
5335                                       /*bit_valid*/ 1,
5336                                       /*bit*/ 0);
5337                 ctl_done((union ctl_io *)ctsio);
5338                 return (CTL_RETVAL_COMPLETE);
5339         }
5340
5341         if ((lun->flags & CTL_LUN_PR_RESERVED)
5342          && ((cdb->how & SSS_START)==0)) {
5343                 uint32_t residx;
5344
5345                 residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5346                 if (ctl_get_prkey(lun, residx) == 0
5347                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5348
5349                         ctl_set_reservation_conflict(ctsio);
5350                         ctl_done((union ctl_io *)ctsio);
5351                         return (CTL_RETVAL_COMPLETE);
5352                 }
5353         }
5354
5355         /*
5356          * If there is no backend on this device, we can't start or stop
5357          * it.  In theory we shouldn't get any start/stop commands in the
5358          * first place at this level if the LUN doesn't have a backend.
5359          * That should get stopped by the command decode code.
5360          */
5361         if (lun->backend == NULL) {
5362                 ctl_set_invalid_opcode(ctsio);
5363                 ctl_done((union ctl_io *)ctsio);
5364                 return (CTL_RETVAL_COMPLETE);
5365         }
5366
5367         /*
5368          * XXX KDM Copan-specific offline behavior.
5369          * Figure out a reasonable way to port this?
5370          */
5371 #ifdef NEEDTOPORT
5372         mtx_lock(&lun->lun_lock);
5373
5374         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5375          && (lun->flags & CTL_LUN_OFFLINE)) {
5376                 /*
5377                  * If the LUN is offline, and the on/offline bit isn't set,
5378                  * reject the start or stop.  Otherwise, let it through.
5379                  */
5380                 mtx_unlock(&lun->lun_lock);
5381                 ctl_set_lun_not_ready(ctsio);
5382                 ctl_done((union ctl_io *)ctsio);
5383         } else {
5384                 mtx_unlock(&lun->lun_lock);
5385 #endif /* NEEDTOPORT */
5386                 /*
5387                  * This could be a start or a stop when we're online,
5388                  * or a stop/offline or start/online.  A start or stop when
5389                  * we're offline is covered in the case above.
5390                  */
5391                 /*
5392                  * In the non-immediate case, we send the request to
5393                  * the backend and return status to the user when
5394                  * it is done.
5395                  *
5396                  * In the immediate case, we allocate a new ctl_io
5397                  * to hold a copy of the request, and send that to
5398                  * the backend.  We then set good status on the
5399                  * user's request and return it immediately.
5400                  */
5401                 if (cdb->byte2 & SSS_IMMED) {
5402                         union ctl_io *new_io;
5403
5404                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5405                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5406                         retval = lun->backend->config_write(new_io);
5407                         ctl_set_success(ctsio);
5408                         ctl_done((union ctl_io *)ctsio);
5409                 } else {
5410                         retval = lun->backend->config_write(
5411                                 (union ctl_io *)ctsio);
5412                 }
5413 #ifdef NEEDTOPORT
5414         }
5415 #endif
5416         return (retval);
5417 }
5418
5419 /*
5420  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5421  * we don't really do anything with the LBA and length fields if the user
5422  * passes them in.  Instead we'll just flush out the cache for the entire
5423  * LUN.
5424  */
5425 int
5426 ctl_sync_cache(struct ctl_scsiio *ctsio)
5427 {
5428         struct ctl_lun *lun;
5429         struct ctl_softc *softc;
5430         struct ctl_lba_len_flags *lbalen;
5431         uint64_t starting_lba;
5432         uint32_t block_count;
5433         int retval;
5434         uint8_t byte2;
5435
5436         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5437
5438         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5439         softc = lun->ctl_softc;
5440         retval = 0;
5441
5442         switch (ctsio->cdb[0]) {
5443         case SYNCHRONIZE_CACHE: {
5444                 struct scsi_sync_cache *cdb;
5445                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5446
5447                 starting_lba = scsi_4btoul(cdb->begin_lba);
5448                 block_count = scsi_2btoul(cdb->lb_count);
5449                 byte2 = cdb->byte2;
5450                 break;
5451         }
5452         case SYNCHRONIZE_CACHE_16: {
5453                 struct scsi_sync_cache_16 *cdb;
5454                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5455
5456                 starting_lba = scsi_8btou64(cdb->begin_lba);
5457                 block_count = scsi_4btoul(cdb->lb_count);
5458                 byte2 = cdb->byte2;
5459                 break;
5460         }
5461         default:
5462                 ctl_set_invalid_opcode(ctsio);
5463                 ctl_done((union ctl_io *)ctsio);
5464                 goto bailout;
5465                 break; /* NOTREACHED */
5466         }
5467
5468         /*
5469          * We check the LBA and length, but don't do anything with them.
5470          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5471          * get flushed.  This check will just help satisfy anyone who wants
5472          * to see an error for an out of range LBA.
5473          */
5474         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5475                 ctl_set_lba_out_of_range(ctsio);
5476                 ctl_done((union ctl_io *)ctsio);
5477                 goto bailout;
5478         }
5479
5480         /*
5481          * If this LUN has no backend, we can't flush the cache anyway.
5482          */
5483         if (lun->backend == NULL) {
5484                 ctl_set_invalid_opcode(ctsio);
5485                 ctl_done((union ctl_io *)ctsio);
5486                 goto bailout;
5487         }
5488
5489         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5490         lbalen->lba = starting_lba;
5491         lbalen->len = block_count;
5492         lbalen->flags = byte2;
5493
5494         /*
5495          * Check to see whether we're configured to send the SYNCHRONIZE
5496          * CACHE command directly to the back end.
5497          */
5498         mtx_lock(&lun->lun_lock);
5499         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5500          && (++(lun->sync_count) >= lun->sync_interval)) {
5501                 lun->sync_count = 0;
5502                 mtx_unlock(&lun->lun_lock);
5503                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5504         } else {
5505                 mtx_unlock(&lun->lun_lock);
5506                 ctl_set_success(ctsio);
5507                 ctl_done((union ctl_io *)ctsio);
5508         }
5509
5510 bailout:
5511
5512         return (retval);
5513 }
5514
5515 int
5516 ctl_format(struct ctl_scsiio *ctsio)
5517 {
5518         struct scsi_format *cdb;
5519         struct ctl_lun *lun;
5520         int length, defect_list_len;
5521
5522         CTL_DEBUG_PRINT(("ctl_format\n"));
5523
5524         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5525
5526         cdb = (struct scsi_format *)ctsio->cdb;
5527
5528         length = 0;
5529         if (cdb->byte2 & SF_FMTDATA) {
5530                 if (cdb->byte2 & SF_LONGLIST)
5531                         length = sizeof(struct scsi_format_header_long);
5532                 else
5533                         length = sizeof(struct scsi_format_header_short);
5534         }
5535
5536         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5537          && (length > 0)) {
5538                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5539                 ctsio->kern_data_len = length;
5540                 ctsio->kern_total_len = length;
5541                 ctsio->kern_data_resid = 0;
5542                 ctsio->kern_rel_offset = 0;
5543                 ctsio->kern_sg_entries = 0;
5544                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5545                 ctsio->be_move_done = ctl_config_move_done;
5546                 ctl_datamove((union ctl_io *)ctsio);
5547
5548                 return (CTL_RETVAL_COMPLETE);
5549         }
5550
5551         defect_list_len = 0;
5552
5553         if (cdb->byte2 & SF_FMTDATA) {
5554                 if (cdb->byte2 & SF_LONGLIST) {
5555                         struct scsi_format_header_long *header;
5556
5557                         header = (struct scsi_format_header_long *)
5558                                 ctsio->kern_data_ptr;
5559
5560                         defect_list_len = scsi_4btoul(header->defect_list_len);
5561                         if (defect_list_len != 0) {
5562                                 ctl_set_invalid_field(ctsio,
5563                                                       /*sks_valid*/ 1,
5564                                                       /*command*/ 0,
5565                                                       /*field*/ 2,
5566                                                       /*bit_valid*/ 0,
5567                                                       /*bit*/ 0);
5568                                 goto bailout;
5569                         }
5570                 } else {
5571                         struct scsi_format_header_short *header;
5572
5573                         header = (struct scsi_format_header_short *)
5574                                 ctsio->kern_data_ptr;
5575
5576                         defect_list_len = scsi_2btoul(header->defect_list_len);
5577                         if (defect_list_len != 0) {
5578                                 ctl_set_invalid_field(ctsio,
5579                                                       /*sks_valid*/ 1,
5580                                                       /*command*/ 0,
5581                                                       /*field*/ 2,
5582                                                       /*bit_valid*/ 0,
5583                                                       /*bit*/ 0);
5584                                 goto bailout;
5585                         }
5586                 }
5587         }
5588
5589         /*
5590          * The format command will clear out the "Medium format corrupted"
5591          * status if set by the configuration code.  That status is really
5592          * just a way to notify the host that we have lost the media, and
5593          * get them to issue a command that will basically make them think
5594          * they're blowing away the media.
5595          */
5596         mtx_lock(&lun->lun_lock);
5597         lun->flags &= ~CTL_LUN_INOPERABLE;
5598         mtx_unlock(&lun->lun_lock);
5599
5600         ctl_set_success(ctsio);
5601 bailout:
5602
5603         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5604                 free(ctsio->kern_data_ptr, M_CTL);
5605                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5606         }
5607
5608         ctl_done((union ctl_io *)ctsio);
5609         return (CTL_RETVAL_COMPLETE);
5610 }
5611
5612 int
5613 ctl_read_buffer(struct ctl_scsiio *ctsio)
5614 {
5615         struct scsi_read_buffer *cdb;
5616         struct ctl_lun *lun;
5617         int buffer_offset, len;
5618         static uint8_t descr[4];
5619         static uint8_t echo_descr[4] = { 0 };
5620
5621         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5622
5623         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5624         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5625
5626         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5627             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5628             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5629                 ctl_set_invalid_field(ctsio,
5630                                       /*sks_valid*/ 1,
5631                                       /*command*/ 1,
5632                                       /*field*/ 1,
5633                                       /*bit_valid*/ 1,
5634                                       /*bit*/ 4);
5635                 ctl_done((union ctl_io *)ctsio);
5636                 return (CTL_RETVAL_COMPLETE);
5637         }
5638
5639         len = scsi_3btoul(cdb->length);
5640         buffer_offset = scsi_3btoul(cdb->offset);
5641
5642         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5643                 ctl_set_invalid_field(ctsio,
5644                                       /*sks_valid*/ 1,
5645                                       /*command*/ 1,
5646                                       /*field*/ 6,
5647                                       /*bit_valid*/ 0,
5648                                       /*bit*/ 0);
5649                 ctl_done((union ctl_io *)ctsio);
5650                 return (CTL_RETVAL_COMPLETE);
5651         }
5652
5653         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5654                 descr[0] = 0;
5655                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5656                 ctsio->kern_data_ptr = descr;
5657                 len = min(len, sizeof(descr));
5658         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5659                 ctsio->kern_data_ptr = echo_descr;
5660                 len = min(len, sizeof(echo_descr));
5661         } else {
5662                 if (lun->write_buffer == NULL) {
5663                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5664                             M_CTL, M_WAITOK);
5665                 }
5666                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5667         }
5668         ctsio->kern_data_len = len;
5669         ctsio->kern_total_len = len;
5670         ctsio->kern_data_resid = 0;
5671         ctsio->kern_rel_offset = 0;
5672         ctsio->kern_sg_entries = 0;
5673         ctl_set_success(ctsio);
5674         ctsio->be_move_done = ctl_config_move_done;
5675         ctl_datamove((union ctl_io *)ctsio);
5676         return (CTL_RETVAL_COMPLETE);
5677 }
5678
5679 int
5680 ctl_write_buffer(struct ctl_scsiio *ctsio)
5681 {
5682         struct scsi_write_buffer *cdb;
5683         struct ctl_lun *lun;
5684         int buffer_offset, len;
5685
5686         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5687
5688         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5689         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5690
5691         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5692                 ctl_set_invalid_field(ctsio,
5693                                       /*sks_valid*/ 1,
5694                                       /*command*/ 1,
5695                                       /*field*/ 1,
5696                                       /*bit_valid*/ 1,
5697                                       /*bit*/ 4);
5698                 ctl_done((union ctl_io *)ctsio);
5699                 return (CTL_RETVAL_COMPLETE);
5700         }
5701
5702         len = scsi_3btoul(cdb->length);
5703         buffer_offset = scsi_3btoul(cdb->offset);
5704
5705         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5706                 ctl_set_invalid_field(ctsio,
5707                                       /*sks_valid*/ 1,
5708                                       /*command*/ 1,
5709                                       /*field*/ 6,
5710                                       /*bit_valid*/ 0,
5711                                       /*bit*/ 0);
5712                 ctl_done((union ctl_io *)ctsio);
5713                 return (CTL_RETVAL_COMPLETE);
5714         }
5715
5716         /*
5717          * If we've got a kernel request that hasn't been malloced yet,
5718          * malloc it and tell the caller the data buffer is here.
5719          */
5720         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5721                 if (lun->write_buffer == NULL) {
5722                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5723                             M_CTL, M_WAITOK);
5724                 }
5725                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5726                 ctsio->kern_data_len = len;
5727                 ctsio->kern_total_len = len;
5728                 ctsio->kern_data_resid = 0;
5729                 ctsio->kern_rel_offset = 0;
5730                 ctsio->kern_sg_entries = 0;
5731                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5732                 ctsio->be_move_done = ctl_config_move_done;
5733                 ctl_datamove((union ctl_io *)ctsio);
5734
5735                 return (CTL_RETVAL_COMPLETE);
5736         }
5737
5738         ctl_set_success(ctsio);
5739         ctl_done((union ctl_io *)ctsio);
5740         return (CTL_RETVAL_COMPLETE);
5741 }
5742
5743 int
5744 ctl_write_same(struct ctl_scsiio *ctsio)
5745 {
5746         struct ctl_lun *lun;
5747         struct ctl_lba_len_flags *lbalen;
5748         uint64_t lba;
5749         uint32_t num_blocks;
5750         int len, retval;
5751         uint8_t byte2;
5752
5753         retval = CTL_RETVAL_COMPLETE;
5754
5755         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5756
5757         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5758
5759         switch (ctsio->cdb[0]) {
5760         case WRITE_SAME_10: {
5761                 struct scsi_write_same_10 *cdb;
5762
5763                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5764
5765                 lba = scsi_4btoul(cdb->addr);
5766                 num_blocks = scsi_2btoul(cdb->length);
5767                 byte2 = cdb->byte2;
5768                 break;
5769         }
5770         case WRITE_SAME_16: {
5771                 struct scsi_write_same_16 *cdb;
5772
5773                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5774
5775                 lba = scsi_8btou64(cdb->addr);
5776                 num_blocks = scsi_4btoul(cdb->length);
5777                 byte2 = cdb->byte2;
5778                 break;
5779         }
5780         default:
5781                 /*
5782                  * We got a command we don't support.  This shouldn't
5783                  * happen, commands should be filtered out above us.
5784                  */
5785                 ctl_set_invalid_opcode(ctsio);
5786                 ctl_done((union ctl_io *)ctsio);
5787
5788                 return (CTL_RETVAL_COMPLETE);
5789                 break; /* NOTREACHED */
5790         }
5791
5792         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5793         if ((byte2 & SWS_UNMAP) == 0 &&
5794             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5795                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5796                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5797                 ctl_done((union ctl_io *)ctsio);
5798                 return (CTL_RETVAL_COMPLETE);
5799         }
5800
5801         /*
5802          * The first check is to make sure we're in bounds, the second
5803          * check is to catch wrap-around problems.  If the lba + num blocks
5804          * is less than the lba, then we've wrapped around and the block
5805          * range is invalid anyway.
5806          */
5807         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5808          || ((lba + num_blocks) < lba)) {
5809                 ctl_set_lba_out_of_range(ctsio);
5810                 ctl_done((union ctl_io *)ctsio);
5811                 return (CTL_RETVAL_COMPLETE);
5812         }
5813
5814         /* Zero number of blocks means "to the last logical block" */
5815         if (num_blocks == 0) {
5816                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5817                         ctl_set_invalid_field(ctsio,
5818                                               /*sks_valid*/ 0,
5819                                               /*command*/ 1,
5820                                               /*field*/ 0,
5821                                               /*bit_valid*/ 0,
5822                                               /*bit*/ 0);
5823                         ctl_done((union ctl_io *)ctsio);
5824                         return (CTL_RETVAL_COMPLETE);
5825                 }
5826                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5827         }
5828
5829         len = lun->be_lun->blocksize;
5830
5831         /*
5832          * If we've got a kernel request that hasn't been malloced yet,
5833          * malloc it and tell the caller the data buffer is here.
5834          */
5835         if ((byte2 & SWS_NDOB) == 0 &&
5836             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5837                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5838                 ctsio->kern_data_len = len;
5839                 ctsio->kern_total_len = len;
5840                 ctsio->kern_data_resid = 0;
5841                 ctsio->kern_rel_offset = 0;
5842                 ctsio->kern_sg_entries = 0;
5843                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5844                 ctsio->be_move_done = ctl_config_move_done;
5845                 ctl_datamove((union ctl_io *)ctsio);
5846
5847                 return (CTL_RETVAL_COMPLETE);
5848         }
5849
5850         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5851         lbalen->lba = lba;
5852         lbalen->len = num_blocks;
5853         lbalen->flags = byte2;
5854         retval = lun->backend->config_write((union ctl_io *)ctsio);
5855
5856         return (retval);
5857 }
5858
5859 int
5860 ctl_unmap(struct ctl_scsiio *ctsio)
5861 {
5862         struct ctl_lun *lun;
5863         struct scsi_unmap *cdb;
5864         struct ctl_ptr_len_flags *ptrlen;
5865         struct scsi_unmap_header *hdr;
5866         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5867         uint64_t lba;
5868         uint32_t num_blocks;
5869         int len, retval;
5870         uint8_t byte2;
5871
5872         retval = CTL_RETVAL_COMPLETE;
5873
5874         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5875
5876         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5877         cdb = (struct scsi_unmap *)ctsio->cdb;
5878
5879         len = scsi_2btoul(cdb->length);
5880         byte2 = cdb->byte2;
5881
5882         /*
5883          * If we've got a kernel request that hasn't been malloced yet,
5884          * malloc it and tell the caller the data buffer is here.
5885          */
5886         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5887                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5888                 ctsio->kern_data_len = len;
5889                 ctsio->kern_total_len = len;
5890                 ctsio->kern_data_resid = 0;
5891                 ctsio->kern_rel_offset = 0;
5892                 ctsio->kern_sg_entries = 0;
5893                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5894                 ctsio->be_move_done = ctl_config_move_done;
5895                 ctl_datamove((union ctl_io *)ctsio);
5896
5897                 return (CTL_RETVAL_COMPLETE);
5898         }
5899
5900         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5901         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5902         if (len < sizeof (*hdr) ||
5903             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5904             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5905             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5906                 ctl_set_invalid_field(ctsio,
5907                                       /*sks_valid*/ 0,
5908                                       /*command*/ 0,
5909                                       /*field*/ 0,
5910                                       /*bit_valid*/ 0,
5911                                       /*bit*/ 0);
5912                 goto done;
5913         }
5914         len = scsi_2btoul(hdr->desc_length);
5915         buf = (struct scsi_unmap_desc *)(hdr + 1);
5916         end = buf + len / sizeof(*buf);
5917
5918         endnz = buf;
5919         for (range = buf; range < end; range++) {
5920                 lba = scsi_8btou64(range->lba);
5921                 num_blocks = scsi_4btoul(range->length);
5922                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5923                  || ((lba + num_blocks) < lba)) {
5924                         ctl_set_lba_out_of_range(ctsio);
5925                         ctl_done((union ctl_io *)ctsio);
5926                         return (CTL_RETVAL_COMPLETE);
5927                 }
5928                 if (num_blocks != 0)
5929                         endnz = range + 1;
5930         }
5931
5932         /*
5933          * Block backend can not handle zero last range.
5934          * Filter it out and return if there is nothing left.
5935          */
5936         len = (uint8_t *)endnz - (uint8_t *)buf;
5937         if (len == 0) {
5938                 ctl_set_success(ctsio);
5939                 goto done;
5940         }
5941
5942         mtx_lock(&lun->lun_lock);
5943         ptrlen = (struct ctl_ptr_len_flags *)
5944             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5945         ptrlen->ptr = (void *)buf;
5946         ptrlen->len = len;
5947         ptrlen->flags = byte2;
5948         ctl_check_blocked(lun);
5949         mtx_unlock(&lun->lun_lock);
5950
5951         retval = lun->backend->config_write((union ctl_io *)ctsio);
5952         return (retval);
5953
5954 done:
5955         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5956                 free(ctsio->kern_data_ptr, M_CTL);
5957                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5958         }
5959         ctl_done((union ctl_io *)ctsio);
5960         return (CTL_RETVAL_COMPLETE);
5961 }
5962
5963 /*
5964  * Note that this function currently doesn't actually do anything inside
5965  * CTL to enforce things if the DQue bit is turned on.
5966  *
5967  * Also note that this function can't be used in the default case, because
5968  * the DQue bit isn't set in the changeable mask for the control mode page
5969  * anyway.  This is just here as an example for how to implement a page
5970  * handler, and a placeholder in case we want to allow the user to turn
5971  * tagged queueing on and off.
5972  *
5973  * The D_SENSE bit handling is functional, however, and will turn
5974  * descriptor sense on and off for a given LUN.
5975  */
5976 int
5977 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5978                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5979 {
5980         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5981         struct ctl_lun *lun;
5982         int set_ua;
5983         uint32_t initidx;
5984
5985         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5986         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5987         set_ua = 0;
5988
5989         user_cp = (struct scsi_control_page *)page_ptr;
5990         current_cp = (struct scsi_control_page *)
5991                 (page_index->page_data + (page_index->page_len *
5992                 CTL_PAGE_CURRENT));
5993         saved_cp = (struct scsi_control_page *)
5994                 (page_index->page_data + (page_index->page_len *
5995                 CTL_PAGE_SAVED));
5996
5997         mtx_lock(&lun->lun_lock);
5998         if (((current_cp->rlec & SCP_DSENSE) == 0)
5999          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6000                 /*
6001                  * Descriptor sense is currently turned off and the user
6002                  * wants to turn it on.
6003                  */
6004                 current_cp->rlec |= SCP_DSENSE;
6005                 saved_cp->rlec |= SCP_DSENSE;
6006                 lun->flags |= CTL_LUN_SENSE_DESC;
6007                 set_ua = 1;
6008         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6009                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6010                 /*
6011                  * Descriptor sense is currently turned on, and the user
6012                  * wants to turn it off.
6013                  */
6014                 current_cp->rlec &= ~SCP_DSENSE;
6015                 saved_cp->rlec &= ~SCP_DSENSE;
6016                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6017                 set_ua = 1;
6018         }
6019         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6020             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6021                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6022                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6023                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6024                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6025                 set_ua = 1;
6026         }
6027         if ((current_cp->eca_and_aen & SCP_SWP) !=
6028             (user_cp->eca_and_aen & SCP_SWP)) {
6029                 current_cp->eca_and_aen &= ~SCP_SWP;
6030                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6031                 saved_cp->eca_and_aen &= ~SCP_SWP;
6032                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6033                 set_ua = 1;
6034         }
6035         if (set_ua != 0)
6036                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6037         mtx_unlock(&lun->lun_lock);
6038         if (set_ua) {
6039                 ctl_isc_announce_mode(lun,
6040                     ctl_get_initindex(&ctsio->io_hdr.nexus),
6041                     page_index->page_code, page_index->subpage);
6042         }
6043         return (0);
6044 }
6045
6046 int
6047 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6048                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6049 {
6050         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6051         struct ctl_lun *lun;
6052         int set_ua;
6053         uint32_t initidx;
6054
6055         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6056         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6057         set_ua = 0;
6058
6059         user_cp = (struct scsi_caching_page *)page_ptr;
6060         current_cp = (struct scsi_caching_page *)
6061                 (page_index->page_data + (page_index->page_len *
6062                 CTL_PAGE_CURRENT));
6063         saved_cp = (struct scsi_caching_page *)
6064                 (page_index->page_data + (page_index->page_len *
6065                 CTL_PAGE_SAVED));
6066
6067         mtx_lock(&lun->lun_lock);
6068         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6069             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6070                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6071                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6072                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6073                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6074                 set_ua = 1;
6075         }
6076         if (set_ua != 0)
6077                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6078         mtx_unlock(&lun->lun_lock);
6079         if (set_ua) {
6080                 ctl_isc_announce_mode(lun,
6081                     ctl_get_initindex(&ctsio->io_hdr.nexus),
6082                     page_index->page_code, page_index->subpage);
6083         }
6084         return (0);
6085 }
6086
6087 int
6088 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6089                                 struct ctl_page_index *page_index,
6090                                 uint8_t *page_ptr)
6091 {
6092         uint8_t *c;
6093         int i;
6094
6095         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6096         ctl_time_io_secs =
6097                 (c[0] << 8) |
6098                 (c[1] << 0) |
6099                 0;
6100         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6101         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6102         printf("page data:");
6103         for (i=0; i<8; i++)
6104                 printf(" %.2x",page_ptr[i]);
6105         printf("\n");
6106         return (0);
6107 }
6108
6109 int
6110 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6111                                struct ctl_page_index *page_index,
6112                                int pc)
6113 {
6114         struct copan_debugconf_subpage *page;
6115
6116         page = (struct copan_debugconf_subpage *)page_index->page_data +
6117                 (page_index->page_len * pc);
6118
6119         switch (pc) {
6120         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6121         case SMS_PAGE_CTRL_DEFAULT >> 6:
6122         case SMS_PAGE_CTRL_SAVED >> 6:
6123                 /*
6124                  * We don't update the changable or default bits for this page.
6125                  */
6126                 break;
6127         case SMS_PAGE_CTRL_CURRENT >> 6:
6128                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6129                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6130                 break;
6131         default:
6132 #ifdef NEEDTOPORT
6133                 EPRINT(0, "Invalid PC %d!!", pc);
6134 #endif /* NEEDTOPORT */
6135                 break;
6136         }
6137         return (0);
6138 }
6139
6140
6141 static int
6142 ctl_do_mode_select(union ctl_io *io)
6143 {
6144         struct scsi_mode_page_header *page_header;
6145         struct ctl_page_index *page_index;
6146         struct ctl_scsiio *ctsio;
6147         int control_dev, page_len;
6148         int page_len_offset, page_len_size;
6149         union ctl_modepage_info *modepage_info;
6150         struct ctl_lun *lun;
6151         int *len_left, *len_used;
6152         int retval, i;
6153
6154         ctsio = &io->scsiio;
6155         page_index = NULL;
6156         page_len = 0;
6157         retval = CTL_RETVAL_COMPLETE;
6158
6159         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6160
6161         if (lun->be_lun->lun_type != T_DIRECT)
6162                 control_dev = 1;
6163         else
6164                 control_dev = 0;
6165
6166         modepage_info = (union ctl_modepage_info *)
6167                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6168         len_left = &modepage_info->header.len_left;
6169         len_used = &modepage_info->header.len_used;
6170
6171 do_next_page:
6172
6173         page_header = (struct scsi_mode_page_header *)
6174                 (ctsio->kern_data_ptr + *len_used);
6175
6176         if (*len_left == 0) {
6177                 free(ctsio->kern_data_ptr, M_CTL);
6178                 ctl_set_success(ctsio);
6179                 ctl_done((union ctl_io *)ctsio);
6180                 return (CTL_RETVAL_COMPLETE);
6181         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6182
6183                 free(ctsio->kern_data_ptr, M_CTL);
6184                 ctl_set_param_len_error(ctsio);
6185                 ctl_done((union ctl_io *)ctsio);
6186                 return (CTL_RETVAL_COMPLETE);
6187
6188         } else if ((page_header->page_code & SMPH_SPF)
6189                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6190
6191                 free(ctsio->kern_data_ptr, M_CTL);
6192                 ctl_set_param_len_error(ctsio);
6193                 ctl_done((union ctl_io *)ctsio);
6194                 return (CTL_RETVAL_COMPLETE);
6195         }
6196
6197
6198         /*
6199          * XXX KDM should we do something with the block descriptor?
6200          */
6201         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6202
6203                 if ((control_dev != 0)
6204                  && (lun->mode_pages.index[i].page_flags &
6205                      CTL_PAGE_FLAG_DISK_ONLY))
6206                         continue;
6207
6208                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6209                     (page_header->page_code & SMPH_PC_MASK))
6210                         continue;
6211
6212                 /*
6213                  * If neither page has a subpage code, then we've got a
6214                  * match.
6215                  */
6216                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6217                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6218                         page_index = &lun->mode_pages.index[i];
6219                         page_len = page_header->page_length;
6220                         break;
6221                 }
6222
6223                 /*
6224                  * If both pages have subpages, then the subpage numbers
6225                  * have to match.
6226                  */
6227                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6228                   && (page_header->page_code & SMPH_SPF)) {
6229                         struct scsi_mode_page_header_sp *sph;
6230
6231                         sph = (struct scsi_mode_page_header_sp *)page_header;
6232
6233                         if (lun->mode_pages.index[i].subpage ==
6234                             sph->subpage) {
6235                                 page_index = &lun->mode_pages.index[i];
6236                                 page_len = scsi_2btoul(sph->page_length);
6237                                 break;
6238                         }
6239                 }
6240         }
6241
6242         /*
6243          * If we couldn't find the page, or if we don't have a mode select
6244          * handler for it, send back an error to the user.
6245          */
6246         if ((page_index == NULL)
6247          || (page_index->select_handler == NULL)) {
6248                 ctl_set_invalid_field(ctsio,
6249                                       /*sks_valid*/ 1,
6250                                       /*command*/ 0,
6251                                       /*field*/ *len_used,
6252                                       /*bit_valid*/ 0,
6253                                       /*bit*/ 0);
6254                 free(ctsio->kern_data_ptr, M_CTL);
6255                 ctl_done((union ctl_io *)ctsio);
6256                 return (CTL_RETVAL_COMPLETE);
6257         }
6258
6259         if (page_index->page_code & SMPH_SPF) {
6260                 page_len_offset = 2;
6261                 page_len_size = 2;
6262         } else {
6263                 page_len_size = 1;
6264                 page_len_offset = 1;
6265         }
6266
6267         /*
6268          * If the length the initiator gives us isn't the one we specify in
6269          * the mode page header, or if they didn't specify enough data in
6270          * the CDB to avoid truncating this page, kick out the request.
6271          */
6272         if ((page_len != (page_index->page_len - page_len_offset -
6273                           page_len_size))
6274          || (*len_left < page_index->page_len)) {
6275
6276
6277                 ctl_set_invalid_field(ctsio,
6278                                       /*sks_valid*/ 1,
6279                                       /*command*/ 0,
6280                                       /*field*/ *len_used + page_len_offset,
6281                                       /*bit_valid*/ 0,
6282                                       /*bit*/ 0);
6283                 free(ctsio->kern_data_ptr, M_CTL);
6284                 ctl_done((union ctl_io *)ctsio);
6285                 return (CTL_RETVAL_COMPLETE);
6286         }
6287
6288         /*
6289          * Run through the mode page, checking to make sure that the bits
6290          * the user changed are actually legal for him to change.
6291          */
6292         for (i = 0; i < page_index->page_len; i++) {
6293                 uint8_t *user_byte, *change_mask, *current_byte;
6294                 int bad_bit;
6295                 int j;
6296
6297                 user_byte = (uint8_t *)page_header + i;
6298                 change_mask = page_index->page_data +
6299                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6300                 current_byte = page_index->page_data +
6301                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6302
6303                 /*
6304                  * Check to see whether the user set any bits in this byte
6305                  * that he is not allowed to set.
6306                  */
6307                 if ((*user_byte & ~(*change_mask)) ==
6308                     (*current_byte & ~(*change_mask)))
6309                         continue;
6310
6311                 /*
6312                  * Go through bit by bit to determine which one is illegal.
6313                  */
6314                 bad_bit = 0;
6315                 for (j = 7; j >= 0; j--) {
6316                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6317                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6318                                 bad_bit = i;
6319                                 break;
6320                         }
6321                 }
6322                 ctl_set_invalid_field(ctsio,
6323                                       /*sks_valid*/ 1,
6324                                       /*command*/ 0,
6325                                       /*field*/ *len_used + i,
6326                                       /*bit_valid*/ 1,
6327                                       /*bit*/ bad_bit);
6328                 free(ctsio->kern_data_ptr, M_CTL);
6329                 ctl_done((union ctl_io *)ctsio);
6330                 return (CTL_RETVAL_COMPLETE);
6331         }
6332
6333         /*
6334          * Decrement these before we call the page handler, since we may
6335          * end up getting called back one way or another before the handler
6336          * returns to this context.
6337          */
6338         *len_left -= page_index->page_len;
6339         *len_used += page_index->page_len;
6340
6341         retval = page_index->select_handler(ctsio, page_index,
6342                                             (uint8_t *)page_header);
6343
6344         /*
6345          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6346          * wait until this queued command completes to finish processing
6347          * the mode page.  If it returns anything other than
6348          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6349          * already set the sense information, freed the data pointer, and
6350          * completed the io for us.
6351          */
6352         if (retval != CTL_RETVAL_COMPLETE)
6353                 goto bailout_no_done;
6354
6355         /*
6356          * If the initiator sent us more than one page, parse the next one.
6357          */
6358         if (*len_left > 0)
6359                 goto do_next_page;
6360
6361         ctl_set_success(ctsio);
6362         free(ctsio->kern_data_ptr, M_CTL);
6363         ctl_done((union ctl_io *)ctsio);
6364
6365 bailout_no_done:
6366
6367         return (CTL_RETVAL_COMPLETE);
6368
6369 }
6370
6371 int
6372 ctl_mode_select(struct ctl_scsiio *ctsio)
6373 {
6374         int param_len, pf, sp;
6375         int header_size, bd_len;
6376         int len_left, len_used;
6377         struct ctl_page_index *page_index;
6378         struct ctl_lun *lun;
6379         int control_dev, page_len;
6380         union ctl_modepage_info *modepage_info;
6381         int retval;
6382
6383         pf = 0;
6384         sp = 0;
6385         page_len = 0;
6386         len_used = 0;
6387         len_left = 0;
6388         retval = 0;
6389         bd_len = 0;
6390         page_index = NULL;
6391
6392         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6393
6394         if (lun->be_lun->lun_type != T_DIRECT)
6395                 control_dev = 1;
6396         else
6397                 control_dev = 0;
6398
6399         switch (ctsio->cdb[0]) {
6400         case MODE_SELECT_6: {
6401                 struct scsi_mode_select_6 *cdb;
6402
6403                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6404
6405                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6406                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6407
6408                 param_len = cdb->length;
6409                 header_size = sizeof(struct scsi_mode_header_6);
6410                 break;
6411         }
6412         case MODE_SELECT_10: {
6413                 struct scsi_mode_select_10 *cdb;
6414
6415                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6416
6417                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6418                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6419
6420                 param_len = scsi_2btoul(cdb->length);
6421                 header_size = sizeof(struct scsi_mode_header_10);
6422                 break;
6423         }
6424         default:
6425                 ctl_set_invalid_opcode(ctsio);
6426                 ctl_done((union ctl_io *)ctsio);
6427                 return (CTL_RETVAL_COMPLETE);
6428                 break; /* NOTREACHED */
6429         }
6430
6431         /*
6432          * From SPC-3:
6433          * "A parameter list length of zero indicates that the Data-Out Buffer
6434          * shall be empty. This condition shall not be considered as an error."
6435          */
6436         if (param_len == 0) {
6437                 ctl_set_success(ctsio);
6438                 ctl_done((union ctl_io *)ctsio);
6439                 return (CTL_RETVAL_COMPLETE);
6440         }
6441
6442         /*
6443          * Since we'll hit this the first time through, prior to
6444          * allocation, we don't need to free a data buffer here.
6445          */
6446         if (param_len < header_size) {
6447                 ctl_set_param_len_error(ctsio);
6448                 ctl_done((union ctl_io *)ctsio);
6449                 return (CTL_RETVAL_COMPLETE);
6450         }
6451
6452         /*
6453          * Allocate the data buffer and grab the user's data.  In theory,
6454          * we shouldn't have to sanity check the parameter list length here
6455          * because the maximum size is 64K.  We should be able to malloc
6456          * that much without too many problems.
6457          */
6458         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6459                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6460                 ctsio->kern_data_len = param_len;
6461                 ctsio->kern_total_len = param_len;
6462                 ctsio->kern_data_resid = 0;
6463                 ctsio->kern_rel_offset = 0;
6464                 ctsio->kern_sg_entries = 0;
6465                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6466                 ctsio->be_move_done = ctl_config_move_done;
6467                 ctl_datamove((union ctl_io *)ctsio);
6468
6469                 return (CTL_RETVAL_COMPLETE);
6470         }
6471
6472         switch (ctsio->cdb[0]) {
6473         case MODE_SELECT_6: {
6474                 struct scsi_mode_header_6 *mh6;
6475
6476                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6477                 bd_len = mh6->blk_desc_len;
6478                 break;
6479         }
6480         case MODE_SELECT_10: {
6481                 struct scsi_mode_header_10 *mh10;
6482
6483                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6484                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6485                 break;
6486         }
6487         default:
6488                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6489                 break;
6490         }
6491
6492         if (param_len < (header_size + bd_len)) {
6493                 free(ctsio->kern_data_ptr, M_CTL);
6494                 ctl_set_param_len_error(ctsio);
6495                 ctl_done((union ctl_io *)ctsio);
6496                 return (CTL_RETVAL_COMPLETE);
6497         }
6498
6499         /*
6500          * Set the IO_CONT flag, so that if this I/O gets passed to
6501          * ctl_config_write_done(), it'll get passed back to
6502          * ctl_do_mode_select() for further processing, or completion if
6503          * we're all done.
6504          */
6505         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6506         ctsio->io_cont = ctl_do_mode_select;
6507
6508         modepage_info = (union ctl_modepage_info *)
6509                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6510
6511         memset(modepage_info, 0, sizeof(*modepage_info));
6512
6513         len_left = param_len - header_size - bd_len;
6514         len_used = header_size + bd_len;
6515
6516         modepage_info->header.len_left = len_left;
6517         modepage_info->header.len_used = len_used;
6518
6519         return (ctl_do_mode_select((union ctl_io *)ctsio));
6520 }
6521
6522 int
6523 ctl_mode_sense(struct ctl_scsiio *ctsio)
6524 {
6525         struct ctl_lun *lun;
6526         int pc, page_code, dbd, llba, subpage;
6527         int alloc_len, page_len, header_len, total_len;
6528         struct scsi_mode_block_descr *block_desc;
6529         struct ctl_page_index *page_index;
6530         int control_dev;
6531
6532         dbd = 0;
6533         llba = 0;
6534         block_desc = NULL;
6535         page_index = NULL;
6536
6537         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6538
6539         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6540
6541         if (lun->be_lun->lun_type != T_DIRECT)
6542                 control_dev = 1;
6543         else
6544                 control_dev = 0;
6545
6546         switch (ctsio->cdb[0]) {
6547         case MODE_SENSE_6: {
6548                 struct scsi_mode_sense_6 *cdb;
6549
6550                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6551
6552                 header_len = sizeof(struct scsi_mode_hdr_6);
6553                 if (cdb->byte2 & SMS_DBD)
6554                         dbd = 1;
6555                 else
6556                         header_len += sizeof(struct scsi_mode_block_descr);
6557
6558                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6559                 page_code = cdb->page & SMS_PAGE_CODE;
6560                 subpage = cdb->subpage;
6561                 alloc_len = cdb->length;
6562                 break;
6563         }
6564         case MODE_SENSE_10: {
6565                 struct scsi_mode_sense_10 *cdb;
6566
6567                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6568
6569                 header_len = sizeof(struct scsi_mode_hdr_10);
6570
6571                 if (cdb->byte2 & SMS_DBD)
6572                         dbd = 1;
6573                 else
6574                         header_len += sizeof(struct scsi_mode_block_descr);
6575                 if (cdb->byte2 & SMS10_LLBAA)
6576                         llba = 1;
6577                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6578                 page_code = cdb->page & SMS_PAGE_CODE;
6579                 subpage = cdb->subpage;
6580                 alloc_len = scsi_2btoul(cdb->length);
6581                 break;
6582         }
6583         default:
6584                 ctl_set_invalid_opcode(ctsio);
6585                 ctl_done((union ctl_io *)ctsio);
6586                 return (CTL_RETVAL_COMPLETE);
6587                 break; /* NOTREACHED */
6588         }
6589
6590         /*
6591          * We have to make a first pass through to calculate the size of
6592          * the pages that match the user's query.  Then we allocate enough
6593          * memory to hold it, and actually copy the data into the buffer.
6594          */
6595         switch (page_code) {
6596         case SMS_ALL_PAGES_PAGE: {
6597                 int i;
6598
6599                 page_len = 0;
6600
6601                 /*
6602                  * At the moment, values other than 0 and 0xff here are
6603                  * reserved according to SPC-3.
6604                  */
6605                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6606                  && (subpage != SMS_SUBPAGE_ALL)) {
6607                         ctl_set_invalid_field(ctsio,
6608                                               /*sks_valid*/ 1,
6609                                               /*command*/ 1,
6610                                               /*field*/ 3,
6611                                               /*bit_valid*/ 0,
6612                                               /*bit*/ 0);
6613                         ctl_done((union ctl_io *)ctsio);
6614                         return (CTL_RETVAL_COMPLETE);
6615                 }
6616
6617                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6618                         if ((control_dev != 0)
6619                          && (lun->mode_pages.index[i].page_flags &
6620                              CTL_PAGE_FLAG_DISK_ONLY))
6621                                 continue;
6622
6623                         /*
6624                          * We don't use this subpage if the user didn't
6625                          * request all subpages.
6626                          */
6627                         if ((lun->mode_pages.index[i].subpage != 0)
6628                          && (subpage == SMS_SUBPAGE_PAGE_0))
6629                                 continue;
6630
6631 #if 0
6632                         printf("found page %#x len %d\n",
6633                                lun->mode_pages.index[i].page_code &
6634                                SMPH_PC_MASK,
6635                                lun->mode_pages.index[i].page_len);
6636 #endif
6637                         page_len += lun->mode_pages.index[i].page_len;
6638                 }
6639                 break;
6640         }
6641         default: {
6642                 int i;
6643
6644                 page_len = 0;
6645
6646                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6647                         /* Look for the right page code */
6648                         if ((lun->mode_pages.index[i].page_code &
6649                              SMPH_PC_MASK) != page_code)
6650                                 continue;
6651
6652                         /* Look for the right subpage or the subpage wildcard*/
6653                         if ((lun->mode_pages.index[i].subpage != subpage)
6654                          && (subpage != SMS_SUBPAGE_ALL))
6655                                 continue;
6656
6657                         /* Make sure the page is supported for this dev type */
6658                         if ((control_dev != 0)
6659                          && (lun->mode_pages.index[i].page_flags &
6660                              CTL_PAGE_FLAG_DISK_ONLY))
6661                                 continue;
6662
6663 #if 0
6664                         printf("found page %#x len %d\n",
6665                                lun->mode_pages.index[i].page_code &
6666                                SMPH_PC_MASK,
6667                                lun->mode_pages.index[i].page_len);
6668 #endif
6669
6670                         page_len += lun->mode_pages.index[i].page_len;
6671                 }
6672
6673                 if (page_len == 0) {
6674                         ctl_set_invalid_field(ctsio,
6675                                               /*sks_valid*/ 1,
6676                                               /*command*/ 1,
6677                                               /*field*/ 2,
6678                                               /*bit_valid*/ 1,
6679                                               /*bit*/ 5);
6680                         ctl_done((union ctl_io *)ctsio);
6681                         return (CTL_RETVAL_COMPLETE);
6682                 }
6683                 break;
6684         }
6685         }
6686
6687         total_len = header_len + page_len;
6688 #if 0
6689         printf("header_len = %d, page_len = %d, total_len = %d\n",
6690                header_len, page_len, total_len);
6691 #endif
6692
6693         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6694         ctsio->kern_sg_entries = 0;
6695         ctsio->kern_data_resid = 0;
6696         ctsio->kern_rel_offset = 0;
6697         if (total_len < alloc_len) {
6698                 ctsio->residual = alloc_len - total_len;
6699                 ctsio->kern_data_len = total_len;
6700                 ctsio->kern_total_len = total_len;
6701         } else {
6702                 ctsio->residual = 0;
6703                 ctsio->kern_data_len = alloc_len;
6704                 ctsio->kern_total_len = alloc_len;
6705         }
6706
6707         switch (ctsio->cdb[0]) {
6708         case MODE_SENSE_6: {
6709                 struct scsi_mode_hdr_6 *header;
6710
6711                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6712
6713                 header->datalen = MIN(total_len - 1, 254);
6714                 if (control_dev == 0) {
6715                         header->dev_specific = 0x10; /* DPOFUA */
6716                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6717                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6718                             .eca_and_aen & SCP_SWP) != 0)
6719                                     header->dev_specific |= 0x80; /* WP */
6720                 }
6721                 if (dbd)
6722                         header->block_descr_len = 0;
6723                 else
6724                         header->block_descr_len =
6725                                 sizeof(struct scsi_mode_block_descr);
6726                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6727                 break;
6728         }
6729         case MODE_SENSE_10: {
6730                 struct scsi_mode_hdr_10 *header;
6731                 int datalen;
6732
6733                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6734
6735                 datalen = MIN(total_len - 2, 65533);
6736                 scsi_ulto2b(datalen, header->datalen);
6737                 if (control_dev == 0) {
6738                         header->dev_specific = 0x10; /* DPOFUA */
6739                         if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6740                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6741                             .eca_and_aen & SCP_SWP) != 0)
6742                                     header->dev_specific |= 0x80; /* WP */
6743                 }
6744                 if (dbd)
6745                         scsi_ulto2b(0, header->block_descr_len);
6746                 else
6747                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6748                                     header->block_descr_len);
6749                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6750                 break;
6751         }
6752         default:
6753                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6754                 break; /* NOTREACHED */
6755         }
6756
6757         /*
6758          * If we've got a disk, use its blocksize in the block
6759          * descriptor.  Otherwise, just set it to 0.
6760          */
6761         if (dbd == 0) {
6762                 if (control_dev == 0)
6763                         scsi_ulto3b(lun->be_lun->blocksize,
6764                                     block_desc->block_len);
6765                 else
6766                         scsi_ulto3b(0, block_desc->block_len);
6767         }
6768
6769         switch (page_code) {
6770         case SMS_ALL_PAGES_PAGE: {
6771                 int i, data_used;
6772
6773                 data_used = header_len;
6774                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6775                         struct ctl_page_index *page_index;
6776
6777                         page_index = &lun->mode_pages.index[i];
6778
6779                         if ((control_dev != 0)
6780                          && (page_index->page_flags &
6781                             CTL_PAGE_FLAG_DISK_ONLY))
6782                                 continue;
6783
6784                         /*
6785                          * We don't use this subpage if the user didn't
6786                          * request all subpages.  We already checked (above)
6787                          * to make sure the user only specified a subpage
6788                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6789                          */
6790                         if ((page_index->subpage != 0)
6791                          && (subpage == SMS_SUBPAGE_PAGE_0))
6792                                 continue;
6793
6794                         /*
6795                          * Call the handler, if it exists, to update the
6796                          * page to the latest values.
6797                          */
6798                         if (page_index->sense_handler != NULL)
6799                                 page_index->sense_handler(ctsio, page_index,pc);
6800
6801                         memcpy(ctsio->kern_data_ptr + data_used,
6802                                page_index->page_data +
6803                                (page_index->page_len * pc),
6804                                page_index->page_len);
6805                         data_used += page_index->page_len;
6806                 }
6807                 break;
6808         }
6809         default: {
6810                 int i, data_used;
6811
6812                 data_used = header_len;
6813
6814                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6815                         struct ctl_page_index *page_index;
6816
6817                         page_index = &lun->mode_pages.index[i];
6818
6819                         /* Look for the right page code */
6820                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6821                                 continue;
6822
6823                         /* Look for the right subpage or the subpage wildcard*/
6824                         if ((page_index->subpage != subpage)
6825                          && (subpage != SMS_SUBPAGE_ALL))
6826                                 continue;
6827
6828                         /* Make sure the page is supported for this dev type */
6829                         if ((control_dev != 0)
6830                          && (page_index->page_flags &
6831                              CTL_PAGE_FLAG_DISK_ONLY))
6832                                 continue;
6833
6834                         /*
6835                          * Call the handler, if it exists, to update the
6836                          * page to the latest values.
6837                          */
6838                         if (page_index->sense_handler != NULL)
6839                                 page_index->sense_handler(ctsio, page_index,pc);
6840
6841                         memcpy(ctsio->kern_data_ptr + data_used,
6842                                page_index->page_data +
6843                                (page_index->page_len * pc),
6844                                page_index->page_len);
6845                         data_used += page_index->page_len;
6846                 }
6847                 break;
6848         }
6849         }
6850
6851         ctl_set_success(ctsio);
6852         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6853         ctsio->be_move_done = ctl_config_move_done;
6854         ctl_datamove((union ctl_io *)ctsio);
6855         return (CTL_RETVAL_COMPLETE);
6856 }
6857
6858 int
6859 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6860                                struct ctl_page_index *page_index,
6861                                int pc)
6862 {
6863         struct ctl_lun *lun;
6864         struct scsi_log_param_header *phdr;
6865         uint8_t *data;
6866         uint64_t val;
6867
6868         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6869         data = page_index->page_data;
6870
6871         if (lun->backend->lun_attr != NULL &&
6872             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6873              != UINT64_MAX) {
6874                 phdr = (struct scsi_log_param_header *)data;
6875                 scsi_ulto2b(0x0001, phdr->param_code);
6876                 phdr->param_control = SLP_LBIN | SLP_LP;
6877                 phdr->param_len = 8;
6878                 data = (uint8_t *)(phdr + 1);
6879                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6880                 data[4] = 0x02; /* per-pool */
6881                 data += phdr->param_len;
6882         }
6883
6884         if (lun->backend->lun_attr != NULL &&
6885             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6886              != UINT64_MAX) {
6887                 phdr = (struct scsi_log_param_header *)data;
6888                 scsi_ulto2b(0x0002, phdr->param_code);
6889                 phdr->param_control = SLP_LBIN | SLP_LP;
6890                 phdr->param_len = 8;
6891                 data = (uint8_t *)(phdr + 1);
6892                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6893                 data[4] = 0x01; /* per-LUN */
6894                 data += phdr->param_len;
6895         }
6896
6897         if (lun->backend->lun_attr != NULL &&
6898             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6899              != UINT64_MAX) {
6900                 phdr = (struct scsi_log_param_header *)data;
6901                 scsi_ulto2b(0x00f1, phdr->param_code);
6902                 phdr->param_control = SLP_LBIN | SLP_LP;
6903                 phdr->param_len = 8;
6904                 data = (uint8_t *)(phdr + 1);
6905                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6906                 data[4] = 0x02; /* per-pool */
6907                 data += phdr->param_len;
6908         }
6909
6910         if (lun->backend->lun_attr != NULL &&
6911             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6912              != UINT64_MAX) {
6913                 phdr = (struct scsi_log_param_header *)data;
6914                 scsi_ulto2b(0x00f2, phdr->param_code);
6915                 phdr->param_control = SLP_LBIN | SLP_LP;
6916                 phdr->param_len = 8;
6917                 data = (uint8_t *)(phdr + 1);
6918                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6919                 data[4] = 0x02; /* per-pool */
6920                 data += phdr->param_len;
6921         }
6922
6923         page_index->page_len = data - page_index->page_data;
6924         return (0);
6925 }
6926
6927 int
6928 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6929                                struct ctl_page_index *page_index,
6930                                int pc)
6931 {
6932         struct ctl_lun *lun;
6933         struct stat_page *data;
6934         uint64_t rn, wn, rb, wb;
6935         struct bintime rt, wt;
6936         int i;
6937
6938         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6939         data = (struct stat_page *)page_index->page_data;
6940
6941         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6942         data->sap.hdr.param_control = SLP_LBIN;
6943         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6944             sizeof(struct scsi_log_param_header);
6945         rn = wn = rb = wb = 0;
6946         bintime_clear(&rt);
6947         bintime_clear(&wt);
6948         for (i = 0; i < CTL_MAX_PORTS; i++) {
6949                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6950                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6951                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6952                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6953                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6954                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6955         }
6956         scsi_u64to8b(rn, data->sap.read_num);
6957         scsi_u64to8b(wn, data->sap.write_num);
6958         if (lun->stats.blocksize > 0) {
6959                 scsi_u64to8b(wb / lun->stats.blocksize,
6960                     data->sap.recvieved_lba);
6961                 scsi_u64to8b(rb / lun->stats.blocksize,
6962                     data->sap.transmitted_lba);
6963         }
6964         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6965             data->sap.read_int);
6966         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6967             data->sap.write_int);
6968         scsi_u64to8b(0, data->sap.weighted_num);
6969         scsi_u64to8b(0, data->sap.weighted_int);
6970         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6971         data->it.hdr.param_control = SLP_LBIN;
6972         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6973             sizeof(struct scsi_log_param_header);
6974 #ifdef CTL_TIME_IO
6975         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6976 #endif
6977         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6978         data->it.hdr.param_control = SLP_LBIN;
6979         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6980             sizeof(struct scsi_log_param_header);
6981         scsi_ulto4b(3, data->ti.exponent);
6982         scsi_ulto4b(1, data->ti.integer);
6983
6984         page_index->page_len = sizeof(*data);
6985         return (0);
6986 }
6987
6988 int
6989 ctl_log_sense(struct ctl_scsiio *ctsio)
6990 {
6991         struct ctl_lun *lun;
6992         int i, pc, page_code, subpage;
6993         int alloc_len, total_len;
6994         struct ctl_page_index *page_index;
6995         struct scsi_log_sense *cdb;
6996         struct scsi_log_header *header;
6997
6998         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6999
7000         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7001         cdb = (struct scsi_log_sense *)ctsio->cdb;
7002         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7003         page_code = cdb->page & SLS_PAGE_CODE;
7004         subpage = cdb->subpage;
7005         alloc_len = scsi_2btoul(cdb->length);
7006
7007         page_index = NULL;
7008         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7009                 page_index = &lun->log_pages.index[i];
7010
7011                 /* Look for the right page code */
7012                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7013                         continue;
7014
7015                 /* Look for the right subpage or the subpage wildcard*/
7016                 if (page_index->subpage != subpage)
7017                         continue;
7018
7019                 break;
7020         }
7021         if (i >= CTL_NUM_LOG_PAGES) {
7022                 ctl_set_invalid_field(ctsio,
7023                                       /*sks_valid*/ 1,
7024                                       /*command*/ 1,
7025                                       /*field*/ 2,
7026                                       /*bit_valid*/ 0,
7027                                       /*bit*/ 0);
7028                 ctl_done((union ctl_io *)ctsio);
7029                 return (CTL_RETVAL_COMPLETE);
7030         }
7031
7032         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7033
7034         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7035         ctsio->kern_sg_entries = 0;
7036         ctsio->kern_data_resid = 0;
7037         ctsio->kern_rel_offset = 0;
7038         if (total_len < alloc_len) {
7039                 ctsio->residual = alloc_len - total_len;
7040                 ctsio->kern_data_len = total_len;
7041                 ctsio->kern_total_len = total_len;
7042         } else {
7043                 ctsio->residual = 0;
7044                 ctsio->kern_data_len = alloc_len;
7045                 ctsio->kern_total_len = alloc_len;
7046         }
7047
7048         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7049         header->page = page_index->page_code;
7050         if (page_index->subpage) {
7051                 header->page |= SL_SPF;
7052                 header->subpage = page_index->subpage;
7053         }
7054         scsi_ulto2b(page_index->page_len, header->datalen);
7055
7056         /*
7057          * Call the handler, if it exists, to update the
7058          * page to the latest values.
7059          */
7060         if (page_index->sense_handler != NULL)
7061                 page_index->sense_handler(ctsio, page_index, pc);
7062
7063         memcpy(header + 1, page_index->page_data, page_index->page_len);
7064
7065         ctl_set_success(ctsio);
7066         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7067         ctsio->be_move_done = ctl_config_move_done;
7068         ctl_datamove((union ctl_io *)ctsio);
7069         return (CTL_RETVAL_COMPLETE);
7070 }
7071
7072 int
7073 ctl_read_capacity(struct ctl_scsiio *ctsio)
7074 {
7075         struct scsi_read_capacity *cdb;
7076         struct scsi_read_capacity_data *data;
7077         struct ctl_lun *lun;
7078         uint32_t lba;
7079
7080         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7081
7082         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7083
7084         lba = scsi_4btoul(cdb->addr);
7085         if (((cdb->pmi & SRC_PMI) == 0)
7086          && (lba != 0)) {
7087                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7088                                       /*sks_valid*/ 1,
7089                                       /*command*/ 1,
7090                                       /*field*/ 2,
7091                                       /*bit_valid*/ 0,
7092                                       /*bit*/ 0);
7093                 ctl_done((union ctl_io *)ctsio);
7094                 return (CTL_RETVAL_COMPLETE);
7095         }
7096
7097         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7098
7099         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7100         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7101         ctsio->residual = 0;
7102         ctsio->kern_data_len = sizeof(*data);
7103         ctsio->kern_total_len = sizeof(*data);
7104         ctsio->kern_data_resid = 0;
7105         ctsio->kern_rel_offset = 0;
7106         ctsio->kern_sg_entries = 0;
7107
7108         /*
7109          * If the maximum LBA is greater than 0xfffffffe, the user must
7110          * issue a SERVICE ACTION IN (16) command, with the read capacity
7111          * serivce action set.
7112          */
7113         if (lun->be_lun->maxlba > 0xfffffffe)
7114                 scsi_ulto4b(0xffffffff, data->addr);
7115         else
7116                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7117
7118         /*
7119          * XXX KDM this may not be 512 bytes...
7120          */
7121         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7122
7123         ctl_set_success(ctsio);
7124         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7125         ctsio->be_move_done = ctl_config_move_done;
7126         ctl_datamove((union ctl_io *)ctsio);
7127         return (CTL_RETVAL_COMPLETE);
7128 }
7129
7130 int
7131 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7132 {
7133         struct scsi_read_capacity_16 *cdb;
7134         struct scsi_read_capacity_data_long *data;
7135         struct ctl_lun *lun;
7136         uint64_t lba;
7137         uint32_t alloc_len;
7138
7139         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7140
7141         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7142
7143         alloc_len = scsi_4btoul(cdb->alloc_len);
7144         lba = scsi_8btou64(cdb->addr);
7145
7146         if ((cdb->reladr & SRC16_PMI)
7147          && (lba != 0)) {
7148                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7149                                       /*sks_valid*/ 1,
7150                                       /*command*/ 1,
7151                                       /*field*/ 2,
7152                                       /*bit_valid*/ 0,
7153                                       /*bit*/ 0);
7154                 ctl_done((union ctl_io *)ctsio);
7155                 return (CTL_RETVAL_COMPLETE);
7156         }
7157
7158         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7159
7160         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7161         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7162
7163         if (sizeof(*data) < alloc_len) {
7164                 ctsio->residual = alloc_len - sizeof(*data);
7165                 ctsio->kern_data_len = sizeof(*data);
7166                 ctsio->kern_total_len = sizeof(*data);
7167         } else {
7168                 ctsio->residual = 0;
7169                 ctsio->kern_data_len = alloc_len;
7170                 ctsio->kern_total_len = alloc_len;
7171         }
7172         ctsio->kern_data_resid = 0;
7173         ctsio->kern_rel_offset = 0;
7174         ctsio->kern_sg_entries = 0;
7175
7176         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7177         /* XXX KDM this may not be 512 bytes... */
7178         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7179         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7180         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7181         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7182                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7183
7184         ctl_set_success(ctsio);
7185         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7186         ctsio->be_move_done = ctl_config_move_done;
7187         ctl_datamove((union ctl_io *)ctsio);
7188         return (CTL_RETVAL_COMPLETE);
7189 }
7190
7191 int
7192 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7193 {
7194         struct scsi_get_lba_status *cdb;
7195         struct scsi_get_lba_status_data *data;
7196         struct ctl_lun *lun;
7197         struct ctl_lba_len_flags *lbalen;
7198         uint64_t lba;
7199         uint32_t alloc_len, total_len;
7200         int retval;
7201
7202         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7203
7204         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7205         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7206         lba = scsi_8btou64(cdb->addr);
7207         alloc_len = scsi_4btoul(cdb->alloc_len);
7208
7209         if (lba > lun->be_lun->maxlba) {
7210                 ctl_set_lba_out_of_range(ctsio);
7211                 ctl_done((union ctl_io *)ctsio);
7212                 return (CTL_RETVAL_COMPLETE);
7213         }
7214
7215         total_len = sizeof(*data) + sizeof(data->descr[0]);
7216         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7217         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7218
7219         if (total_len < alloc_len) {
7220                 ctsio->residual = alloc_len - total_len;
7221                 ctsio->kern_data_len = total_len;
7222                 ctsio->kern_total_len = total_len;
7223         } else {
7224                 ctsio->residual = 0;
7225                 ctsio->kern_data_len = alloc_len;
7226                 ctsio->kern_total_len = alloc_len;
7227         }
7228         ctsio->kern_data_resid = 0;
7229         ctsio->kern_rel_offset = 0;
7230         ctsio->kern_sg_entries = 0;
7231
7232         /* Fill dummy data in case backend can't tell anything. */
7233         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7234         scsi_u64to8b(lba, data->descr[0].addr);
7235         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7236             data->descr[0].length);
7237         data->descr[0].status = 0; /* Mapped or unknown. */
7238
7239         ctl_set_success(ctsio);
7240         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7241         ctsio->be_move_done = ctl_config_move_done;
7242
7243         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7244         lbalen->lba = lba;
7245         lbalen->len = total_len;
7246         lbalen->flags = 0;
7247         retval = lun->backend->config_read((union ctl_io *)ctsio);
7248         return (CTL_RETVAL_COMPLETE);
7249 }
7250
7251 int
7252 ctl_read_defect(struct ctl_scsiio *ctsio)
7253 {
7254         struct scsi_read_defect_data_10 *ccb10;
7255         struct scsi_read_defect_data_12 *ccb12;
7256         struct scsi_read_defect_data_hdr_10 *data10;
7257         struct scsi_read_defect_data_hdr_12 *data12;
7258         uint32_t alloc_len, data_len;
7259         uint8_t format;
7260
7261         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7262
7263         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7264                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7265                 format = ccb10->format;
7266                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7267                 data_len = sizeof(*data10);
7268         } else {
7269                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7270                 format = ccb12->format;
7271                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7272                 data_len = sizeof(*data12);
7273         }
7274         if (alloc_len == 0) {
7275                 ctl_set_success(ctsio);
7276                 ctl_done((union ctl_io *)ctsio);
7277                 return (CTL_RETVAL_COMPLETE);
7278         }
7279
7280         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7281         if (data_len < alloc_len) {
7282                 ctsio->residual = alloc_len - data_len;
7283                 ctsio->kern_data_len = data_len;
7284                 ctsio->kern_total_len = data_len;
7285         } else {
7286                 ctsio->residual = 0;
7287                 ctsio->kern_data_len = alloc_len;
7288                 ctsio->kern_total_len = alloc_len;
7289         }
7290         ctsio->kern_data_resid = 0;
7291         ctsio->kern_rel_offset = 0;
7292         ctsio->kern_sg_entries = 0;
7293
7294         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7295                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7296                     ctsio->kern_data_ptr;
7297                 data10->format = format;
7298                 scsi_ulto2b(0, data10->length);
7299         } else {
7300                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7301                     ctsio->kern_data_ptr;
7302                 data12->format = format;
7303                 scsi_ulto2b(0, data12->generation);
7304                 scsi_ulto4b(0, data12->length);
7305         }
7306
7307         ctl_set_success(ctsio);
7308         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7309         ctsio->be_move_done = ctl_config_move_done;
7310         ctl_datamove((union ctl_io *)ctsio);
7311         return (CTL_RETVAL_COMPLETE);
7312 }
7313
7314 int
7315 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7316 {
7317         struct scsi_maintenance_in *cdb;
7318         int retval;
7319         int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7320         int num_target_port_groups, num_target_ports;
7321         struct ctl_lun *lun;
7322         struct ctl_softc *softc;
7323         struct ctl_port *port;
7324         struct scsi_target_group_data *rtg_ptr;
7325         struct scsi_target_group_data_extended *rtg_ext_ptr;
7326         struct scsi_target_port_group_descriptor *tpg_desc;
7327
7328         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7329
7330         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7331         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7332         softc = lun->ctl_softc;
7333
7334         retval = CTL_RETVAL_COMPLETE;
7335
7336         switch (cdb->byte2 & STG_PDF_MASK) {
7337         case STG_PDF_LENGTH:
7338                 ext = 0;
7339                 break;
7340         case STG_PDF_EXTENDED:
7341                 ext = 1;
7342                 break;
7343         default:
7344                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7345                                       /*sks_valid*/ 1,
7346                                       /*command*/ 1,
7347                                       /*field*/ 2,
7348                                       /*bit_valid*/ 1,
7349                                       /*bit*/ 5);
7350                 ctl_done((union ctl_io *)ctsio);
7351                 return(retval);
7352         }
7353
7354         if (softc->is_single)
7355                 num_target_port_groups = 1;
7356         else
7357                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7358         num_target_ports = 0;
7359         mtx_lock(&softc->ctl_lock);
7360         STAILQ_FOREACH(port, &softc->port_list, links) {
7361                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7362                         continue;
7363                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7364                         continue;
7365                 num_target_ports++;
7366         }
7367         mtx_unlock(&softc->ctl_lock);
7368
7369         if (ext)
7370                 total_len = sizeof(struct scsi_target_group_data_extended);
7371         else
7372                 total_len = sizeof(struct scsi_target_group_data);
7373         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7374                 num_target_port_groups +
7375             sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7376
7377         alloc_len = scsi_4btoul(cdb->length);
7378
7379         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7380
7381         ctsio->kern_sg_entries = 0;
7382
7383         if (total_len < alloc_len) {
7384                 ctsio->residual = alloc_len - total_len;
7385                 ctsio->kern_data_len = total_len;
7386                 ctsio->kern_total_len = total_len;
7387         } else {
7388                 ctsio->residual = 0;
7389                 ctsio->kern_data_len = alloc_len;
7390                 ctsio->kern_total_len = alloc_len;
7391         }
7392         ctsio->kern_data_resid = 0;
7393         ctsio->kern_rel_offset = 0;
7394
7395         if (ext) {
7396                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7397                     ctsio->kern_data_ptr;
7398                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7399                 rtg_ext_ptr->format_type = 0x10;
7400                 rtg_ext_ptr->implicit_transition_time = 0;
7401                 tpg_desc = &rtg_ext_ptr->groups[0];
7402         } else {
7403                 rtg_ptr = (struct scsi_target_group_data *)
7404                     ctsio->kern_data_ptr;
7405                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7406                 tpg_desc = &rtg_ptr->groups[0];
7407         }
7408
7409         mtx_lock(&softc->ctl_lock);
7410         pg = softc->port_min / softc->port_cnt;
7411         if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7412                 gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7413         else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7414                 gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7415         else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7416                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7417         else
7418                 gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7419         if (lun->flags & CTL_LUN_PRIMARY_SC) {
7420                 os = gs;
7421                 gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7422         } else
7423                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7424         for (g = 0; g < num_target_port_groups; g++) {
7425                 tpg_desc->pref_state = (g == pg) ? gs : os;
7426                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7427                     TPG_U_SUP | TPG_T_SUP;
7428                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7429                 tpg_desc->status = TPG_IMPLICIT;
7430                 pc = 0;
7431                 STAILQ_FOREACH(port, &softc->port_list, links) {
7432                         if (port->targ_port < g * softc->port_cnt ||
7433                             port->targ_port >= (g + 1) * softc->port_cnt)
7434                                 continue;
7435                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7436                                 continue;
7437                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7438                                 continue;
7439                         scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7440                             relative_target_port_identifier);
7441                         pc++;
7442                 }
7443                 tpg_desc->target_port_count = pc;
7444                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7445                     &tpg_desc->descriptors[pc];
7446         }
7447         mtx_unlock(&softc->ctl_lock);
7448
7449         ctl_set_success(ctsio);
7450         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7451         ctsio->be_move_done = ctl_config_move_done;
7452         ctl_datamove((union ctl_io *)ctsio);
7453         return(retval);
7454 }
7455
7456 int
7457 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7458 {
7459         struct ctl_lun *lun;
7460         struct scsi_report_supported_opcodes *cdb;
7461         const struct ctl_cmd_entry *entry, *sentry;
7462         struct scsi_report_supported_opcodes_all *all;
7463         struct scsi_report_supported_opcodes_descr *descr;
7464         struct scsi_report_supported_opcodes_one *one;
7465         int retval;
7466         int alloc_len, total_len;
7467         int opcode, service_action, i, j, num;
7468
7469         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7470
7471         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7472         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7473
7474         retval = CTL_RETVAL_COMPLETE;
7475
7476         opcode = cdb->requested_opcode;
7477         service_action = scsi_2btoul(cdb->requested_service_action);
7478         switch (cdb->options & RSO_OPTIONS_MASK) {
7479         case RSO_OPTIONS_ALL:
7480                 num = 0;
7481                 for (i = 0; i < 256; i++) {
7482                         entry = &ctl_cmd_table[i];
7483                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7484                                 for (j = 0; j < 32; j++) {
7485                                         sentry = &((const struct ctl_cmd_entry *)
7486                                             entry->execute)[j];
7487                                         if (ctl_cmd_applicable(
7488                                             lun->be_lun->lun_type, sentry))
7489                                                 num++;
7490                                 }
7491                         } else {
7492                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7493                                     entry))
7494                                         num++;
7495                         }
7496                 }
7497                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7498                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7499                 break;
7500         case RSO_OPTIONS_OC:
7501                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7502                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7503                                               /*sks_valid*/ 1,
7504                                               /*command*/ 1,
7505                                               /*field*/ 2,
7506                                               /*bit_valid*/ 1,
7507                                               /*bit*/ 2);
7508                         ctl_done((union ctl_io *)ctsio);
7509                         return (CTL_RETVAL_COMPLETE);
7510                 }
7511                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7512                 break;
7513         case RSO_OPTIONS_OC_SA:
7514                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7515                     service_action >= 32) {
7516                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7517                                               /*sks_valid*/ 1,
7518                                               /*command*/ 1,
7519                                               /*field*/ 2,
7520                                               /*bit_valid*/ 1,
7521                                               /*bit*/ 2);
7522                         ctl_done((union ctl_io *)ctsio);
7523                         return (CTL_RETVAL_COMPLETE);
7524                 }
7525                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7526                 break;
7527         default:
7528                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7529                                       /*sks_valid*/ 1,
7530                                       /*command*/ 1,
7531                                       /*field*/ 2,
7532                                       /*bit_valid*/ 1,
7533                                       /*bit*/ 2);
7534                 ctl_done((union ctl_io *)ctsio);
7535                 return (CTL_RETVAL_COMPLETE);
7536         }
7537
7538         alloc_len = scsi_4btoul(cdb->length);
7539
7540         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7541
7542         ctsio->kern_sg_entries = 0;
7543
7544         if (total_len < alloc_len) {
7545                 ctsio->residual = alloc_len - total_len;
7546                 ctsio->kern_data_len = total_len;
7547                 ctsio->kern_total_len = total_len;
7548         } else {
7549                 ctsio->residual = 0;
7550                 ctsio->kern_data_len = alloc_len;
7551                 ctsio->kern_total_len = alloc_len;
7552         }
7553         ctsio->kern_data_resid = 0;
7554         ctsio->kern_rel_offset = 0;
7555
7556         switch (cdb->options & RSO_OPTIONS_MASK) {
7557         case RSO_OPTIONS_ALL:
7558                 all = (struct scsi_report_supported_opcodes_all *)
7559                     ctsio->kern_data_ptr;
7560                 num = 0;
7561                 for (i = 0; i < 256; i++) {
7562                         entry = &ctl_cmd_table[i];
7563                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7564                                 for (j = 0; j < 32; j++) {
7565                                         sentry = &((const struct ctl_cmd_entry *)
7566                                             entry->execute)[j];
7567                                         if (!ctl_cmd_applicable(
7568                                             lun->be_lun->lun_type, sentry))
7569                                                 continue;
7570                                         descr = &all->descr[num++];
7571                                         descr->opcode = i;
7572                                         scsi_ulto2b(j, descr->service_action);
7573                                         descr->flags = RSO_SERVACTV;
7574                                         scsi_ulto2b(sentry->length,
7575                                             descr->cdb_length);
7576                                 }
7577                         } else {
7578                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7579                                     entry))
7580                                         continue;
7581                                 descr = &all->descr[num++];
7582                                 descr->opcode = i;
7583                                 scsi_ulto2b(0, descr->service_action);
7584                                 descr->flags = 0;
7585                                 scsi_ulto2b(entry->length, descr->cdb_length);
7586                         }
7587                 }
7588                 scsi_ulto4b(
7589                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7590                     all->length);
7591                 break;
7592         case RSO_OPTIONS_OC:
7593                 one = (struct scsi_report_supported_opcodes_one *)
7594                     ctsio->kern_data_ptr;
7595                 entry = &ctl_cmd_table[opcode];
7596                 goto fill_one;
7597         case RSO_OPTIONS_OC_SA:
7598                 one = (struct scsi_report_supported_opcodes_one *)
7599                     ctsio->kern_data_ptr;
7600                 entry = &ctl_cmd_table[opcode];
7601                 entry = &((const struct ctl_cmd_entry *)
7602                     entry->execute)[service_action];
7603 fill_one:
7604                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7605                         one->support = 3;
7606                         scsi_ulto2b(entry->length, one->cdb_length);
7607                         one->cdb_usage[0] = opcode;
7608                         memcpy(&one->cdb_usage[1], entry->usage,
7609                             entry->length - 1);
7610                 } else
7611                         one->support = 1;
7612                 break;
7613         }
7614
7615         ctl_set_success(ctsio);
7616         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7617         ctsio->be_move_done = ctl_config_move_done;
7618         ctl_datamove((union ctl_io *)ctsio);
7619         return(retval);
7620 }
7621
7622 int
7623 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7624 {
7625         struct scsi_report_supported_tmf *cdb;
7626         struct scsi_report_supported_tmf_data *data;
7627         int retval;
7628         int alloc_len, total_len;
7629
7630         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7631
7632         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7633
7634         retval = CTL_RETVAL_COMPLETE;
7635
7636         total_len = sizeof(struct scsi_report_supported_tmf_data);
7637         alloc_len = scsi_4btoul(cdb->length);
7638
7639         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7640
7641         ctsio->kern_sg_entries = 0;
7642
7643         if (total_len < alloc_len) {
7644                 ctsio->residual = alloc_len - total_len;
7645                 ctsio->kern_data_len = total_len;
7646                 ctsio->kern_total_len = total_len;
7647         } else {
7648                 ctsio->residual = 0;
7649                 ctsio->kern_data_len = alloc_len;
7650                 ctsio->kern_total_len = alloc_len;
7651         }
7652         ctsio->kern_data_resid = 0;
7653         ctsio->kern_rel_offset = 0;
7654
7655         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7656         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7657             RST_TRS;
7658         data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7659
7660         ctl_set_success(ctsio);
7661         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7662         ctsio->be_move_done = ctl_config_move_done;
7663         ctl_datamove((union ctl_io *)ctsio);
7664         return (retval);
7665 }
7666
7667 int
7668 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7669 {
7670         struct scsi_report_timestamp *cdb;
7671         struct scsi_report_timestamp_data *data;
7672         struct timeval tv;
7673         int64_t timestamp;
7674         int retval;
7675         int alloc_len, total_len;
7676
7677         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7678
7679         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7680
7681         retval = CTL_RETVAL_COMPLETE;
7682
7683         total_len = sizeof(struct scsi_report_timestamp_data);
7684         alloc_len = scsi_4btoul(cdb->length);
7685
7686         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7687
7688         ctsio->kern_sg_entries = 0;
7689
7690         if (total_len < alloc_len) {
7691                 ctsio->residual = alloc_len - total_len;
7692                 ctsio->kern_data_len = total_len;
7693                 ctsio->kern_total_len = total_len;
7694         } else {
7695                 ctsio->residual = 0;
7696                 ctsio->kern_data_len = alloc_len;
7697                 ctsio->kern_total_len = alloc_len;
7698         }
7699         ctsio->kern_data_resid = 0;
7700         ctsio->kern_rel_offset = 0;
7701
7702         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7703         scsi_ulto2b(sizeof(*data) - 2, data->length);
7704         data->origin = RTS_ORIG_OUTSIDE;
7705         getmicrotime(&tv);
7706         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7707         scsi_ulto4b(timestamp >> 16, data->timestamp);
7708         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7709
7710         ctl_set_success(ctsio);
7711         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7712         ctsio->be_move_done = ctl_config_move_done;
7713         ctl_datamove((union ctl_io *)ctsio);
7714         return (retval);
7715 }
7716
7717 int
7718 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7719 {
7720         struct scsi_per_res_in *cdb;
7721         int alloc_len, total_len = 0;
7722         /* struct scsi_per_res_in_rsrv in_data; */
7723         struct ctl_lun *lun;
7724         struct ctl_softc *softc;
7725         uint64_t key;
7726
7727         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7728
7729         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7730
7731         alloc_len = scsi_2btoul(cdb->length);
7732
7733         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7734         softc = lun->ctl_softc;
7735
7736 retry:
7737         mtx_lock(&lun->lun_lock);
7738         switch (cdb->action) {
7739         case SPRI_RK: /* read keys */
7740                 total_len = sizeof(struct scsi_per_res_in_keys) +
7741                         lun->pr_key_count *
7742                         sizeof(struct scsi_per_res_key);
7743                 break;
7744         case SPRI_RR: /* read reservation */
7745                 if (lun->flags & CTL_LUN_PR_RESERVED)
7746                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7747                 else
7748                         total_len = sizeof(struct scsi_per_res_in_header);
7749                 break;
7750         case SPRI_RC: /* report capabilities */
7751                 total_len = sizeof(struct scsi_per_res_cap);
7752                 break;
7753         case SPRI_RS: /* read full status */
7754                 total_len = sizeof(struct scsi_per_res_in_header) +
7755                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7756                     lun->pr_key_count;
7757                 break;
7758         default:
7759                 panic("Invalid PR type %x", cdb->action);
7760         }
7761         mtx_unlock(&lun->lun_lock);
7762
7763         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7764
7765         if (total_len < alloc_len) {
7766                 ctsio->residual = alloc_len - total_len;
7767                 ctsio->kern_data_len = total_len;
7768                 ctsio->kern_total_len = total_len;
7769         } else {
7770                 ctsio->residual = 0;
7771                 ctsio->kern_data_len = alloc_len;
7772                 ctsio->kern_total_len = alloc_len;
7773         }
7774
7775         ctsio->kern_data_resid = 0;
7776         ctsio->kern_rel_offset = 0;
7777         ctsio->kern_sg_entries = 0;
7778
7779         mtx_lock(&lun->lun_lock);
7780         switch (cdb->action) {
7781         case SPRI_RK: { // read keys
7782         struct scsi_per_res_in_keys *res_keys;
7783                 int i, key_count;
7784
7785                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7786
7787                 /*
7788                  * We had to drop the lock to allocate our buffer, which
7789                  * leaves time for someone to come in with another
7790                  * persistent reservation.  (That is unlikely, though,
7791                  * since this should be the only persistent reservation
7792                  * command active right now.)
7793                  */
7794                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7795                     (lun->pr_key_count *
7796                      sizeof(struct scsi_per_res_key)))){
7797                         mtx_unlock(&lun->lun_lock);
7798                         free(ctsio->kern_data_ptr, M_CTL);
7799                         printf("%s: reservation length changed, retrying\n",
7800                                __func__);
7801                         goto retry;
7802                 }
7803
7804                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7805
7806                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7807                              lun->pr_key_count, res_keys->header.length);
7808
7809                 for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7810                         if ((key = ctl_get_prkey(lun, i)) == 0)
7811                                 continue;
7812
7813                         /*
7814                          * We used lun->pr_key_count to calculate the
7815                          * size to allocate.  If it turns out the number of
7816                          * initiators with the registered flag set is
7817                          * larger than that (i.e. they haven't been kept in
7818                          * sync), we've got a problem.
7819                          */
7820                         if (key_count >= lun->pr_key_count) {
7821 #ifdef NEEDTOPORT
7822                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7823                                             CTL_PR_ERROR,
7824                                             csevent_LogType_Fault,
7825                                             csevent_AlertLevel_Yellow,
7826                                             csevent_FRU_ShelfController,
7827                                             csevent_FRU_Firmware,
7828                                         csevent_FRU_Unknown,
7829                                             "registered keys %d >= key "
7830                                             "count %d", key_count,
7831                                             lun->pr_key_count);
7832 #endif
7833                                 key_count++;
7834                                 continue;
7835                         }
7836                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7837                         key_count++;
7838                 }
7839                 break;
7840         }
7841         case SPRI_RR: { // read reservation
7842                 struct scsi_per_res_in_rsrv *res;
7843                 int tmp_len, header_only;
7844
7845                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7846
7847                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7848
7849                 if (lun->flags & CTL_LUN_PR_RESERVED)
7850                 {
7851                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7852                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7853                                     res->header.length);
7854                         header_only = 0;
7855                 } else {
7856                         tmp_len = sizeof(struct scsi_per_res_in_header);
7857                         scsi_ulto4b(0, res->header.length);
7858                         header_only = 1;
7859                 }
7860
7861                 /*
7862                  * We had to drop the lock to allocate our buffer, which
7863                  * leaves time for someone to come in with another
7864                  * persistent reservation.  (That is unlikely, though,
7865                  * since this should be the only persistent reservation
7866                  * command active right now.)
7867                  */
7868                 if (tmp_len != total_len) {
7869                         mtx_unlock(&lun->lun_lock);
7870                         free(ctsio->kern_data_ptr, M_CTL);
7871                         printf("%s: reservation status changed, retrying\n",
7872                                __func__);
7873                         goto retry;
7874                 }
7875
7876                 /*
7877                  * No reservation held, so we're done.
7878                  */
7879                 if (header_only != 0)
7880                         break;
7881
7882                 /*
7883                  * If the registration is an All Registrants type, the key
7884                  * is 0, since it doesn't really matter.
7885                  */
7886                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7887                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7888                             res->data.reservation);
7889                 }
7890                 res->data.scopetype = lun->res_type;
7891                 break;
7892         }
7893         case SPRI_RC:     //report capabilities
7894         {
7895                 struct scsi_per_res_cap *res_cap;
7896                 uint16_t type_mask;
7897
7898                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7899                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7900                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7901                 type_mask = SPRI_TM_WR_EX_AR |
7902                             SPRI_TM_EX_AC_RO |
7903                             SPRI_TM_WR_EX_RO |
7904                             SPRI_TM_EX_AC |
7905                             SPRI_TM_WR_EX |
7906                             SPRI_TM_EX_AC_AR;
7907                 scsi_ulto2b(type_mask, res_cap->type_mask);
7908                 break;
7909         }
7910         case SPRI_RS: { // read full status
7911                 struct scsi_per_res_in_full *res_status;
7912                 struct scsi_per_res_in_full_desc *res_desc;
7913                 struct ctl_port *port;
7914                 int i, len;
7915
7916                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7917
7918                 /*
7919                  * We had to drop the lock to allocate our buffer, which
7920                  * leaves time for someone to come in with another
7921                  * persistent reservation.  (That is unlikely, though,
7922                  * since this should be the only persistent reservation
7923                  * command active right now.)
7924                  */
7925                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7926                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7927                      lun->pr_key_count)){
7928                         mtx_unlock(&lun->lun_lock);
7929                         free(ctsio->kern_data_ptr, M_CTL);
7930                         printf("%s: reservation length changed, retrying\n",
7931                                __func__);
7932                         goto retry;
7933                 }
7934
7935                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7936
7937                 res_desc = &res_status->desc[0];
7938                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7939                         if ((key = ctl_get_prkey(lun, i)) == 0)
7940                                 continue;
7941
7942                         scsi_u64to8b(key, res_desc->res_key.key);
7943                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7944                             (lun->pr_res_idx == i ||
7945                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7946                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7947                                 res_desc->scopetype = lun->res_type;
7948                         }
7949                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7950                             res_desc->rel_trgt_port_id);
7951                         len = 0;
7952                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7953                         if (port != NULL)
7954                                 len = ctl_create_iid(port,
7955                                     i % CTL_MAX_INIT_PER_PORT,
7956                                     res_desc->transport_id);
7957                         scsi_ulto4b(len, res_desc->additional_length);
7958                         res_desc = (struct scsi_per_res_in_full_desc *)
7959                             &res_desc->transport_id[len];
7960                 }
7961                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7962                     res_status->header.length);
7963                 break;
7964         }
7965         default:
7966                 /*
7967                  * This is a bug, because we just checked for this above,
7968                  * and should have returned an error.
7969                  */
7970                 panic("Invalid PR type %x", cdb->action);
7971                 break; /* NOTREACHED */
7972         }
7973         mtx_unlock(&lun->lun_lock);
7974
7975         ctl_set_success(ctsio);
7976         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7977         ctsio->be_move_done = ctl_config_move_done;
7978         ctl_datamove((union ctl_io *)ctsio);
7979         return (CTL_RETVAL_COMPLETE);
7980 }
7981
7982 /*
7983  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7984  * it should return.
7985  */
7986 static int
7987 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7988                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7989                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7990                 struct scsi_per_res_out_parms* param)
7991 {
7992         union ctl_ha_msg persis_io;
7993         int i;
7994
7995         mtx_lock(&lun->lun_lock);
7996         if (sa_res_key == 0) {
7997                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7998                         /* validate scope and type */
7999                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8000                              SPR_LU_SCOPE) {
8001                                 mtx_unlock(&lun->lun_lock);
8002                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8003                                                       /*sks_valid*/ 1,
8004                                                       /*command*/ 1,
8005                                                       /*field*/ 2,
8006                                                       /*bit_valid*/ 1,
8007                                                       /*bit*/ 4);
8008                                 ctl_done((union ctl_io *)ctsio);
8009                                 return (1);
8010                         }
8011
8012                         if (type>8 || type==2 || type==4 || type==0) {
8013                                 mtx_unlock(&lun->lun_lock);
8014                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8015                                                       /*sks_valid*/ 1,
8016                                                       /*command*/ 1,
8017                                                       /*field*/ 2,
8018                                                       /*bit_valid*/ 1,
8019                                                       /*bit*/ 0);
8020                                 ctl_done((union ctl_io *)ctsio);
8021                                 return (1);
8022                         }
8023
8024                         /*
8025                          * Unregister everybody else and build UA for
8026                          * them
8027                          */
8028                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8029                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8030                                         continue;
8031
8032                                 ctl_clr_prkey(lun, i);
8033                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8034                         }
8035                         lun->pr_key_count = 1;
8036                         lun->res_type = type;
8037                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8038                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8039                                 lun->pr_res_idx = residx;
8040                         lun->PRGeneration++;
8041                         mtx_unlock(&lun->lun_lock);
8042
8043                         /* send msg to other side */
8044                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8045                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8046                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8047                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8048                         persis_io.pr.pr_info.res_type = type;
8049                         memcpy(persis_io.pr.pr_info.sa_res_key,
8050                                param->serv_act_res_key,
8051                                sizeof(param->serv_act_res_key));
8052                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8053                             sizeof(persis_io.pr), M_WAITOK);
8054                 } else {
8055                         /* not all registrants */
8056                         mtx_unlock(&lun->lun_lock);
8057                         free(ctsio->kern_data_ptr, M_CTL);
8058                         ctl_set_invalid_field(ctsio,
8059                                               /*sks_valid*/ 1,
8060                                               /*command*/ 0,
8061                                               /*field*/ 8,
8062                                               /*bit_valid*/ 0,
8063                                               /*bit*/ 0);
8064                         ctl_done((union ctl_io *)ctsio);
8065                         return (1);
8066                 }
8067         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8068                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8069                 int found = 0;
8070
8071                 if (res_key == sa_res_key) {
8072                         /* special case */
8073                         /*
8074                          * The spec implies this is not good but doesn't
8075                          * say what to do. There are two choices either
8076                          * generate a res conflict or check condition
8077                          * with illegal field in parameter data. Since
8078                          * that is what is done when the sa_res_key is
8079                          * zero I'll take that approach since this has
8080                          * to do with the sa_res_key.
8081                          */
8082                         mtx_unlock(&lun->lun_lock);
8083                         free(ctsio->kern_data_ptr, M_CTL);
8084                         ctl_set_invalid_field(ctsio,
8085                                               /*sks_valid*/ 1,
8086                                               /*command*/ 0,
8087                                               /*field*/ 8,
8088                                               /*bit_valid*/ 0,
8089                                               /*bit*/ 0);
8090                         ctl_done((union ctl_io *)ctsio);
8091                         return (1);
8092                 }
8093
8094                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8095                         if (ctl_get_prkey(lun, i) != sa_res_key)
8096                                 continue;
8097
8098                         found = 1;
8099                         ctl_clr_prkey(lun, i);
8100                         lun->pr_key_count--;
8101                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8102                 }
8103                 if (!found) {
8104                         mtx_unlock(&lun->lun_lock);
8105                         free(ctsio->kern_data_ptr, M_CTL);
8106                         ctl_set_reservation_conflict(ctsio);
8107                         ctl_done((union ctl_io *)ctsio);
8108                         return (CTL_RETVAL_COMPLETE);
8109                 }
8110                 lun->PRGeneration++;
8111                 mtx_unlock(&lun->lun_lock);
8112
8113                 /* send msg to other side */
8114                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8115                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8116                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8117                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8118                 persis_io.pr.pr_info.res_type = type;
8119                 memcpy(persis_io.pr.pr_info.sa_res_key,
8120                        param->serv_act_res_key,
8121                        sizeof(param->serv_act_res_key));
8122                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8123                     sizeof(persis_io.pr), M_WAITOK);
8124         } else {
8125                 /* Reserved but not all registrants */
8126                 /* sa_res_key is res holder */
8127                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8128                         /* validate scope and type */
8129                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8130                              SPR_LU_SCOPE) {
8131                                 mtx_unlock(&lun->lun_lock);
8132                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8133                                                       /*sks_valid*/ 1,
8134                                                       /*command*/ 1,
8135                                                       /*field*/ 2,
8136                                                       /*bit_valid*/ 1,
8137                                                       /*bit*/ 4);
8138                                 ctl_done((union ctl_io *)ctsio);
8139                                 return (1);
8140                         }
8141
8142                         if (type>8 || type==2 || type==4 || type==0) {
8143                                 mtx_unlock(&lun->lun_lock);
8144                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8145                                                       /*sks_valid*/ 1,
8146                                                       /*command*/ 1,
8147                                                       /*field*/ 2,
8148                                                       /*bit_valid*/ 1,
8149                                                       /*bit*/ 0);
8150                                 ctl_done((union ctl_io *)ctsio);
8151                                 return (1);
8152                         }
8153
8154                         /*
8155                          * Do the following:
8156                          * if sa_res_key != res_key remove all
8157                          * registrants w/sa_res_key and generate UA
8158                          * for these registrants(Registrations
8159                          * Preempted) if it wasn't an exclusive
8160                          * reservation generate UA(Reservations
8161                          * Preempted) for all other registered nexuses
8162                          * if the type has changed. Establish the new
8163                          * reservation and holder. If res_key and
8164                          * sa_res_key are the same do the above
8165                          * except don't unregister the res holder.
8166                          */
8167
8168                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8169                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8170                                         continue;
8171
8172                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8173                                         ctl_clr_prkey(lun, i);
8174                                         lun->pr_key_count--;
8175                                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8176                                 } else if (type != lun->res_type
8177                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8178                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8179                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8180                                 }
8181                         }
8182                         lun->res_type = type;
8183                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8184                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8185                                 lun->pr_res_idx = residx;
8186                         else
8187                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8188                         lun->PRGeneration++;
8189                         mtx_unlock(&lun->lun_lock);
8190
8191                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8192                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8193                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8194                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8195                         persis_io.pr.pr_info.res_type = type;
8196                         memcpy(persis_io.pr.pr_info.sa_res_key,
8197                                param->serv_act_res_key,
8198                                sizeof(param->serv_act_res_key));
8199                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8200                             sizeof(persis_io.pr), M_WAITOK);
8201                 } else {
8202                         /*
8203                          * sa_res_key is not the res holder just
8204                          * remove registrants
8205                          */
8206                         int found=0;
8207
8208                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8209                                 if (sa_res_key != ctl_get_prkey(lun, i))
8210                                         continue;
8211
8212                                 found = 1;
8213                                 ctl_clr_prkey(lun, i);
8214                                 lun->pr_key_count--;
8215                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8216                         }
8217
8218                         if (!found) {
8219                                 mtx_unlock(&lun->lun_lock);
8220                                 free(ctsio->kern_data_ptr, M_CTL);
8221                                 ctl_set_reservation_conflict(ctsio);
8222                                 ctl_done((union ctl_io *)ctsio);
8223                                 return (1);
8224                         }
8225                         lun->PRGeneration++;
8226                         mtx_unlock(&lun->lun_lock);
8227
8228                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8229                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8230                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8231                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8232                         persis_io.pr.pr_info.res_type = type;
8233                         memcpy(persis_io.pr.pr_info.sa_res_key,
8234                                param->serv_act_res_key,
8235                                sizeof(param->serv_act_res_key));
8236                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8237                             sizeof(persis_io.pr), M_WAITOK);
8238                 }
8239         }
8240         return (0);
8241 }
8242
8243 static void
8244 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8245 {
8246         uint64_t sa_res_key;
8247         int i;
8248
8249         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8250
8251         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8252          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8253          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8254                 if (sa_res_key == 0) {
8255                         /*
8256                          * Unregister everybody else and build UA for
8257                          * them
8258                          */
8259                         for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8260                                 if (i == msg->pr.pr_info.residx ||
8261                                     ctl_get_prkey(lun, i) == 0)
8262                                         continue;
8263
8264                                 ctl_clr_prkey(lun, i);
8265                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8266                         }
8267
8268                         lun->pr_key_count = 1;
8269                         lun->res_type = msg->pr.pr_info.res_type;
8270                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8271                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8272                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8273                 } else {
8274                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8275                                 if (sa_res_key == ctl_get_prkey(lun, i))
8276                                         continue;
8277
8278                                 ctl_clr_prkey(lun, i);
8279                                 lun->pr_key_count--;
8280                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8281                         }
8282                 }
8283         } else {
8284                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8285                         if (i == msg->pr.pr_info.residx ||
8286                             ctl_get_prkey(lun, i) == 0)
8287                                 continue;
8288
8289                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8290                                 ctl_clr_prkey(lun, i);
8291                                 lun->pr_key_count--;
8292                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8293                         } else if (msg->pr.pr_info.res_type != lun->res_type
8294                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8295                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8296                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8297                         }
8298                 }
8299                 lun->res_type = msg->pr.pr_info.res_type;
8300                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8301                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8302                         lun->pr_res_idx = msg->pr.pr_info.residx;
8303                 else
8304                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8305         }
8306         lun->PRGeneration++;
8307
8308 }
8309
8310
8311 int
8312 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8313 {
8314         int retval;
8315         u_int32_t param_len;
8316         struct scsi_per_res_out *cdb;
8317         struct ctl_lun *lun;
8318         struct scsi_per_res_out_parms* param;
8319         struct ctl_softc *softc;
8320         uint32_t residx;
8321         uint64_t res_key, sa_res_key, key;
8322         uint8_t type;
8323         union ctl_ha_msg persis_io;
8324         int    i;
8325
8326         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8327
8328         retval = CTL_RETVAL_COMPLETE;
8329
8330         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8331         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8332         softc = lun->ctl_softc;
8333
8334         /*
8335          * We only support whole-LUN scope.  The scope & type are ignored for
8336          * register, register and ignore existing key and clear.
8337          * We sometimes ignore scope and type on preempts too!!
8338          * Verify reservation type here as well.
8339          */
8340         type = cdb->scope_type & SPR_TYPE_MASK;
8341         if ((cdb->action == SPRO_RESERVE)
8342          || (cdb->action == SPRO_RELEASE)) {
8343                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8344                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8345                                               /*sks_valid*/ 1,
8346                                               /*command*/ 1,
8347                                               /*field*/ 2,
8348                                               /*bit_valid*/ 1,
8349                                               /*bit*/ 4);
8350                         ctl_done((union ctl_io *)ctsio);
8351                         return (CTL_RETVAL_COMPLETE);
8352                 }
8353
8354                 if (type>8 || type==2 || type==4 || type==0) {
8355                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8356                                               /*sks_valid*/ 1,
8357                                               /*command*/ 1,
8358                                               /*field*/ 2,
8359                                               /*bit_valid*/ 1,
8360                                               /*bit*/ 0);
8361                         ctl_done((union ctl_io *)ctsio);
8362                         return (CTL_RETVAL_COMPLETE);
8363                 }
8364         }
8365
8366         param_len = scsi_4btoul(cdb->length);
8367
8368         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8369                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8370                 ctsio->kern_data_len = param_len;
8371                 ctsio->kern_total_len = param_len;
8372                 ctsio->kern_data_resid = 0;
8373                 ctsio->kern_rel_offset = 0;
8374                 ctsio->kern_sg_entries = 0;
8375                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8376                 ctsio->be_move_done = ctl_config_move_done;
8377                 ctl_datamove((union ctl_io *)ctsio);
8378
8379                 return (CTL_RETVAL_COMPLETE);
8380         }
8381
8382         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8383
8384         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8385         res_key = scsi_8btou64(param->res_key.key);
8386         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8387
8388         /*
8389          * Validate the reservation key here except for SPRO_REG_IGNO
8390          * This must be done for all other service actions
8391          */
8392         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8393                 mtx_lock(&lun->lun_lock);
8394                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8395                         if (res_key != key) {
8396                                 /*
8397                                  * The current key passed in doesn't match
8398                                  * the one the initiator previously
8399                                  * registered.
8400                                  */
8401                                 mtx_unlock(&lun->lun_lock);
8402                                 free(ctsio->kern_data_ptr, M_CTL);
8403                                 ctl_set_reservation_conflict(ctsio);
8404                                 ctl_done((union ctl_io *)ctsio);
8405                                 return (CTL_RETVAL_COMPLETE);
8406                         }
8407                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8408                         /*
8409                          * We are not registered
8410                          */
8411                         mtx_unlock(&lun->lun_lock);
8412                         free(ctsio->kern_data_ptr, M_CTL);
8413                         ctl_set_reservation_conflict(ctsio);
8414                         ctl_done((union ctl_io *)ctsio);
8415                         return (CTL_RETVAL_COMPLETE);
8416                 } else if (res_key != 0) {
8417                         /*
8418                          * We are not registered and trying to register but
8419                          * the register key isn't zero.
8420                          */
8421                         mtx_unlock(&lun->lun_lock);
8422                         free(ctsio->kern_data_ptr, M_CTL);
8423                         ctl_set_reservation_conflict(ctsio);
8424                         ctl_done((union ctl_io *)ctsio);
8425                         return (CTL_RETVAL_COMPLETE);
8426                 }
8427                 mtx_unlock(&lun->lun_lock);
8428         }
8429
8430         switch (cdb->action & SPRO_ACTION_MASK) {
8431         case SPRO_REGISTER:
8432         case SPRO_REG_IGNO: {
8433
8434 #if 0
8435                 printf("Registration received\n");
8436 #endif
8437
8438                 /*
8439                  * We don't support any of these options, as we report in
8440                  * the read capabilities request (see
8441                  * ctl_persistent_reserve_in(), above).
8442                  */
8443                 if ((param->flags & SPR_SPEC_I_PT)
8444                  || (param->flags & SPR_ALL_TG_PT)
8445                  || (param->flags & SPR_APTPL)) {
8446                         int bit_ptr;
8447
8448                         if (param->flags & SPR_APTPL)
8449                                 bit_ptr = 0;
8450                         else if (param->flags & SPR_ALL_TG_PT)
8451                                 bit_ptr = 2;
8452                         else /* SPR_SPEC_I_PT */
8453                                 bit_ptr = 3;
8454
8455                         free(ctsio->kern_data_ptr, M_CTL);
8456                         ctl_set_invalid_field(ctsio,
8457                                               /*sks_valid*/ 1,
8458                                               /*command*/ 0,
8459                                               /*field*/ 20,
8460                                               /*bit_valid*/ 1,
8461                                               /*bit*/ bit_ptr);
8462                         ctl_done((union ctl_io *)ctsio);
8463                         return (CTL_RETVAL_COMPLETE);
8464                 }
8465
8466                 mtx_lock(&lun->lun_lock);
8467
8468                 /*
8469                  * The initiator wants to clear the
8470                  * key/unregister.
8471                  */
8472                 if (sa_res_key == 0) {
8473                         if ((res_key == 0
8474                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8475                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8476                           && ctl_get_prkey(lun, residx) == 0)) {
8477                                 mtx_unlock(&lun->lun_lock);
8478                                 goto done;
8479                         }
8480
8481                         ctl_clr_prkey(lun, residx);
8482                         lun->pr_key_count--;
8483
8484                         if (residx == lun->pr_res_idx) {
8485                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8486                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8487
8488                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8489                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8490                                  && lun->pr_key_count) {
8491                                         /*
8492                                          * If the reservation is a registrants
8493                                          * only type we need to generate a UA
8494                                          * for other registered inits.  The
8495                                          * sense code should be RESERVATIONS
8496                                          * RELEASED
8497                                          */
8498
8499                                         for (i = softc->init_min; i < softc->init_max; i++){
8500                                                 if (ctl_get_prkey(lun, i) == 0)
8501                                                         continue;
8502                                                 ctl_est_ua(lun, i,
8503                                                     CTL_UA_RES_RELEASE);
8504                                         }
8505                                 }
8506                                 lun->res_type = 0;
8507                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8508                                 if (lun->pr_key_count==0) {
8509                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8510                                         lun->res_type = 0;
8511                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8512                                 }
8513                         }
8514                         lun->PRGeneration++;
8515                         mtx_unlock(&lun->lun_lock);
8516
8517                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8518                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8519                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8520                         persis_io.pr.pr_info.residx = residx;
8521                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8522                             sizeof(persis_io.pr), M_WAITOK);
8523                 } else /* sa_res_key != 0 */ {
8524
8525                         /*
8526                          * If we aren't registered currently then increment
8527                          * the key count and set the registered flag.
8528                          */
8529                         ctl_alloc_prkey(lun, residx);
8530                         if (ctl_get_prkey(lun, residx) == 0)
8531                                 lun->pr_key_count++;
8532                         ctl_set_prkey(lun, residx, sa_res_key);
8533                         lun->PRGeneration++;
8534                         mtx_unlock(&lun->lun_lock);
8535
8536                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8537                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8538                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8539                         persis_io.pr.pr_info.residx = residx;
8540                         memcpy(persis_io.pr.pr_info.sa_res_key,
8541                                param->serv_act_res_key,
8542                                sizeof(param->serv_act_res_key));
8543                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8544                             sizeof(persis_io.pr), M_WAITOK);
8545                 }
8546
8547                 break;
8548         }
8549         case SPRO_RESERVE:
8550 #if 0
8551                 printf("Reserve executed type %d\n", type);
8552 #endif
8553                 mtx_lock(&lun->lun_lock);
8554                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8555                         /*
8556                          * if this isn't the reservation holder and it's
8557                          * not a "all registrants" type or if the type is
8558                          * different then we have a conflict
8559                          */
8560                         if ((lun->pr_res_idx != residx
8561                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8562                          || lun->res_type != type) {
8563                                 mtx_unlock(&lun->lun_lock);
8564                                 free(ctsio->kern_data_ptr, M_CTL);
8565                                 ctl_set_reservation_conflict(ctsio);
8566                                 ctl_done((union ctl_io *)ctsio);
8567                                 return (CTL_RETVAL_COMPLETE);
8568                         }
8569                         mtx_unlock(&lun->lun_lock);
8570                 } else /* create a reservation */ {
8571                         /*
8572                          * If it's not an "all registrants" type record
8573                          * reservation holder
8574                          */
8575                         if (type != SPR_TYPE_WR_EX_AR
8576                          && type != SPR_TYPE_EX_AC_AR)
8577                                 lun->pr_res_idx = residx; /* Res holder */
8578                         else
8579                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8580
8581                         lun->flags |= CTL_LUN_PR_RESERVED;
8582                         lun->res_type = type;
8583
8584                         mtx_unlock(&lun->lun_lock);
8585
8586                         /* send msg to other side */
8587                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8588                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8589                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8590                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8591                         persis_io.pr.pr_info.res_type = type;
8592                         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8593                             sizeof(persis_io.pr), M_WAITOK);
8594                 }
8595                 break;
8596
8597         case SPRO_RELEASE:
8598                 mtx_lock(&lun->lun_lock);
8599                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8600                         /* No reservation exists return good status */
8601                         mtx_unlock(&lun->lun_lock);
8602                         goto done;
8603                 }
8604                 /*
8605                  * Is this nexus a reservation holder?
8606                  */
8607                 if (lun->pr_res_idx != residx
8608                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8609                         /*
8610                          * not a res holder return good status but
8611                          * do nothing
8612                          */
8613                         mtx_unlock(&lun->lun_lock);
8614                         goto done;
8615                 }
8616
8617                 if (lun->res_type != type) {
8618                         mtx_unlock(&lun->lun_lock);
8619                         free(ctsio->kern_data_ptr, M_CTL);
8620                         ctl_set_illegal_pr_release(ctsio);
8621                         ctl_done((union ctl_io *)ctsio);
8622                         return (CTL_RETVAL_COMPLETE);
8623                 }
8624
8625                 /* okay to release */
8626                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8627                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8628                 lun->res_type = 0;
8629
8630                 /*
8631                  * if this isn't an exclusive access
8632                  * res generate UA for all other
8633                  * registrants.
8634                  */
8635                 if (type != SPR_TYPE_EX_AC
8636                  && type != SPR_TYPE_WR_EX) {
8637                         for (i = softc->init_min; i < softc->init_max; i++) {
8638                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8639                                         continue;
8640                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8641                         }
8642                 }
8643                 mtx_unlock(&lun->lun_lock);
8644
8645                 /* Send msg to other side */
8646                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8647                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8648                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8649                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8650                      sizeof(persis_io.pr), M_WAITOK);
8651                 break;
8652
8653         case SPRO_CLEAR:
8654                 /* send msg to other side */
8655
8656                 mtx_lock(&lun->lun_lock);
8657                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8658                 lun->res_type = 0;
8659                 lun->pr_key_count = 0;
8660                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8661
8662                 ctl_clr_prkey(lun, residx);
8663                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
8664                         if (ctl_get_prkey(lun, i) != 0) {
8665                                 ctl_clr_prkey(lun, i);
8666                                 ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8667                         }
8668                 lun->PRGeneration++;
8669                 mtx_unlock(&lun->lun_lock);
8670
8671                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8672                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8673                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8674                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8675                      sizeof(persis_io.pr), M_WAITOK);
8676                 break;
8677
8678         case SPRO_PREEMPT:
8679         case SPRO_PRE_ABO: {
8680                 int nretval;
8681
8682                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8683                                           residx, ctsio, cdb, param);
8684                 if (nretval != 0)
8685                         return (CTL_RETVAL_COMPLETE);
8686                 break;
8687         }
8688         default:
8689                 panic("Invalid PR type %x", cdb->action);
8690         }
8691
8692 done:
8693         free(ctsio->kern_data_ptr, M_CTL);
8694         ctl_set_success(ctsio);
8695         ctl_done((union ctl_io *)ctsio);
8696
8697         return (retval);
8698 }
8699
8700 /*
8701  * This routine is for handling a message from the other SC pertaining to
8702  * persistent reserve out. All the error checking will have been done
8703  * so only perorming the action need be done here to keep the two
8704  * in sync.
8705  */
8706 static void
8707 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8708 {
8709         struct ctl_lun *lun;
8710         struct ctl_softc *softc;
8711         int i;
8712         uint32_t residx, targ_lun;
8713
8714         softc = control_softc;
8715         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8716         mtx_lock(&softc->ctl_lock);
8717         if ((targ_lun >= CTL_MAX_LUNS) ||
8718             ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8719                 mtx_unlock(&softc->ctl_lock);
8720                 return;
8721         }
8722         mtx_lock(&lun->lun_lock);
8723         mtx_unlock(&softc->ctl_lock);
8724         if (lun->flags & CTL_LUN_DISABLED) {
8725                 mtx_unlock(&lun->lun_lock);
8726                 return;
8727         }
8728         residx = ctl_get_initindex(&msg->hdr.nexus);
8729         switch(msg->pr.pr_info.action) {
8730         case CTL_PR_REG_KEY:
8731                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8732                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8733                         lun->pr_key_count++;
8734                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8735                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8736                 lun->PRGeneration++;
8737                 break;
8738
8739         case CTL_PR_UNREG_KEY:
8740                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8741                 lun->pr_key_count--;
8742
8743                 /* XXX Need to see if the reservation has been released */
8744                 /* if so do we need to generate UA? */
8745                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8746                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8747                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8748
8749                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8750                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8751                          && lun->pr_key_count) {
8752                                 /*
8753                                  * If the reservation is a registrants
8754                                  * only type we need to generate a UA
8755                                  * for other registered inits.  The
8756                                  * sense code should be RESERVATIONS
8757                                  * RELEASED
8758                                  */
8759
8760                                 for (i = softc->init_min; i < softc->init_max; i++) {
8761                                         if (ctl_get_prkey(lun, i) == 0)
8762                                                 continue;
8763
8764                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8765                                 }
8766                         }
8767                         lun->res_type = 0;
8768                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8769                         if (lun->pr_key_count==0) {
8770                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8771                                 lun->res_type = 0;
8772                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8773                         }
8774                 }
8775                 lun->PRGeneration++;
8776                 break;
8777
8778         case CTL_PR_RESERVE:
8779                 lun->flags |= CTL_LUN_PR_RESERVED;
8780                 lun->res_type = msg->pr.pr_info.res_type;
8781                 lun->pr_res_idx = msg->pr.pr_info.residx;
8782
8783                 break;
8784
8785         case CTL_PR_RELEASE:
8786                 /*
8787                  * if this isn't an exclusive access res generate UA for all
8788                  * other registrants.
8789                  */
8790                 if (lun->res_type != SPR_TYPE_EX_AC
8791                  && lun->res_type != SPR_TYPE_WR_EX) {
8792                         for (i = softc->init_min; i < softc->init_max; i++)
8793                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8794                                         continue;
8795                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8796                 }
8797
8798                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8799                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8800                 lun->res_type = 0;
8801                 break;
8802
8803         case CTL_PR_PREEMPT:
8804                 ctl_pro_preempt_other(lun, msg);
8805                 break;
8806         case CTL_PR_CLEAR:
8807                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8808                 lun->res_type = 0;
8809                 lun->pr_key_count = 0;
8810                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8811
8812                 for (i=0; i < CTL_MAX_INITIATORS; i++) {
8813                         if (ctl_get_prkey(lun, i) == 0)
8814                                 continue;
8815                         ctl_clr_prkey(lun, i);
8816                         ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8817                 }
8818                 lun->PRGeneration++;
8819                 break;
8820         }
8821
8822         mtx_unlock(&lun->lun_lock);
8823 }
8824
8825 int
8826 ctl_read_write(struct ctl_scsiio *ctsio)
8827 {
8828         struct ctl_lun *lun;
8829         struct ctl_lba_len_flags *lbalen;
8830         uint64_t lba;
8831         uint32_t num_blocks;
8832         int flags, retval;
8833         int isread;
8834
8835         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8836
8837         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8838
8839         flags = 0;
8840         retval = CTL_RETVAL_COMPLETE;
8841
8842         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8843               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8844         switch (ctsio->cdb[0]) {
8845         case READ_6:
8846         case WRITE_6: {
8847                 struct scsi_rw_6 *cdb;
8848
8849                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8850
8851                 lba = scsi_3btoul(cdb->addr);
8852                 /* only 5 bits are valid in the most significant address byte */
8853                 lba &= 0x1fffff;
8854                 num_blocks = cdb->length;
8855                 /*
8856                  * This is correct according to SBC-2.
8857                  */
8858                 if (num_blocks == 0)
8859                         num_blocks = 256;
8860                 break;
8861         }
8862         case READ_10:
8863         case WRITE_10: {
8864                 struct scsi_rw_10 *cdb;
8865
8866                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8867                 if (cdb->byte2 & SRW10_FUA)
8868                         flags |= CTL_LLF_FUA;
8869                 if (cdb->byte2 & SRW10_DPO)
8870                         flags |= CTL_LLF_DPO;
8871                 lba = scsi_4btoul(cdb->addr);
8872                 num_blocks = scsi_2btoul(cdb->length);
8873                 break;
8874         }
8875         case WRITE_VERIFY_10: {
8876                 struct scsi_write_verify_10 *cdb;
8877
8878                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8879                 flags |= CTL_LLF_FUA;
8880                 if (cdb->byte2 & SWV_DPO)
8881                         flags |= CTL_LLF_DPO;
8882                 lba = scsi_4btoul(cdb->addr);
8883                 num_blocks = scsi_2btoul(cdb->length);
8884                 break;
8885         }
8886         case READ_12:
8887         case WRITE_12: {
8888                 struct scsi_rw_12 *cdb;
8889
8890                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8891                 if (cdb->byte2 & SRW12_FUA)
8892                         flags |= CTL_LLF_FUA;
8893                 if (cdb->byte2 & SRW12_DPO)
8894                         flags |= CTL_LLF_DPO;
8895                 lba = scsi_4btoul(cdb->addr);
8896                 num_blocks = scsi_4btoul(cdb->length);
8897                 break;
8898         }
8899         case WRITE_VERIFY_12: {
8900                 struct scsi_write_verify_12 *cdb;
8901
8902                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8903                 flags |= CTL_LLF_FUA;
8904                 if (cdb->byte2 & SWV_DPO)
8905                         flags |= CTL_LLF_DPO;
8906                 lba = scsi_4btoul(cdb->addr);
8907                 num_blocks = scsi_4btoul(cdb->length);
8908                 break;
8909         }
8910         case READ_16:
8911         case WRITE_16: {
8912                 struct scsi_rw_16 *cdb;
8913
8914                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8915                 if (cdb->byte2 & SRW12_FUA)
8916                         flags |= CTL_LLF_FUA;
8917                 if (cdb->byte2 & SRW12_DPO)
8918                         flags |= CTL_LLF_DPO;
8919                 lba = scsi_8btou64(cdb->addr);
8920                 num_blocks = scsi_4btoul(cdb->length);
8921                 break;
8922         }
8923         case WRITE_ATOMIC_16: {
8924                 struct scsi_rw_16 *cdb;
8925
8926                 if (lun->be_lun->atomicblock == 0) {
8927                         ctl_set_invalid_opcode(ctsio);
8928                         ctl_done((union ctl_io *)ctsio);
8929                         return (CTL_RETVAL_COMPLETE);
8930                 }
8931
8932                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8933                 if (cdb->byte2 & SRW12_FUA)
8934                         flags |= CTL_LLF_FUA;
8935                 if (cdb->byte2 & SRW12_DPO)
8936                         flags |= CTL_LLF_DPO;
8937                 lba = scsi_8btou64(cdb->addr);
8938                 num_blocks = scsi_4btoul(cdb->length);
8939                 if (num_blocks > lun->be_lun->atomicblock) {
8940                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8941                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8942                             /*bit*/ 0);
8943                         ctl_done((union ctl_io *)ctsio);
8944                         return (CTL_RETVAL_COMPLETE);
8945                 }
8946                 break;
8947         }
8948         case WRITE_VERIFY_16: {
8949                 struct scsi_write_verify_16 *cdb;
8950
8951                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8952                 flags |= CTL_LLF_FUA;
8953                 if (cdb->byte2 & SWV_DPO)
8954                         flags |= CTL_LLF_DPO;
8955                 lba = scsi_8btou64(cdb->addr);
8956                 num_blocks = scsi_4btoul(cdb->length);
8957                 break;
8958         }
8959         default:
8960                 /*
8961                  * We got a command we don't support.  This shouldn't
8962                  * happen, commands should be filtered out above us.
8963                  */
8964                 ctl_set_invalid_opcode(ctsio);
8965                 ctl_done((union ctl_io *)ctsio);
8966
8967                 return (CTL_RETVAL_COMPLETE);
8968                 break; /* NOTREACHED */
8969         }
8970
8971         /*
8972          * The first check is to make sure we're in bounds, the second
8973          * check is to catch wrap-around problems.  If the lba + num blocks
8974          * is less than the lba, then we've wrapped around and the block
8975          * range is invalid anyway.
8976          */
8977         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8978          || ((lba + num_blocks) < lba)) {
8979                 ctl_set_lba_out_of_range(ctsio);
8980                 ctl_done((union ctl_io *)ctsio);
8981                 return (CTL_RETVAL_COMPLETE);
8982         }
8983
8984         /*
8985          * According to SBC-3, a transfer length of 0 is not an error.
8986          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8987          * translates to 256 blocks for those commands.
8988          */
8989         if (num_blocks == 0) {
8990                 ctl_set_success(ctsio);
8991                 ctl_done((union ctl_io *)ctsio);
8992                 return (CTL_RETVAL_COMPLETE);
8993         }
8994
8995         /* Set FUA and/or DPO if caches are disabled. */
8996         if (isread) {
8997                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8998                     SCP_RCD) != 0)
8999                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9000         } else {
9001                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9002                     SCP_WCE) == 0)
9003                         flags |= CTL_LLF_FUA;
9004         }
9005
9006         lbalen = (struct ctl_lba_len_flags *)
9007             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9008         lbalen->lba = lba;
9009         lbalen->len = num_blocks;
9010         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9011
9012         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9013         ctsio->kern_rel_offset = 0;
9014
9015         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9016
9017         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9018
9019         return (retval);
9020 }
9021
9022 static int
9023 ctl_cnw_cont(union ctl_io *io)
9024 {
9025         struct ctl_scsiio *ctsio;
9026         struct ctl_lun *lun;
9027         struct ctl_lba_len_flags *lbalen;
9028         int retval;
9029
9030         ctsio = &io->scsiio;
9031         ctsio->io_hdr.status = CTL_STATUS_NONE;
9032         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9033         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9034         lbalen = (struct ctl_lba_len_flags *)
9035             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9036         lbalen->flags &= ~CTL_LLF_COMPARE;
9037         lbalen->flags |= CTL_LLF_WRITE;
9038
9039         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9040         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9041         return (retval);
9042 }
9043
9044 int
9045 ctl_cnw(struct ctl_scsiio *ctsio)
9046 {
9047         struct ctl_lun *lun;
9048         struct ctl_lba_len_flags *lbalen;
9049         uint64_t lba;
9050         uint32_t num_blocks;
9051         int flags, retval;
9052
9053         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9054
9055         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9056
9057         flags = 0;
9058         retval = CTL_RETVAL_COMPLETE;
9059
9060         switch (ctsio->cdb[0]) {
9061         case COMPARE_AND_WRITE: {
9062                 struct scsi_compare_and_write *cdb;
9063
9064                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9065                 if (cdb->byte2 & SRW10_FUA)
9066                         flags |= CTL_LLF_FUA;
9067                 if (cdb->byte2 & SRW10_DPO)
9068                         flags |= CTL_LLF_DPO;
9069                 lba = scsi_8btou64(cdb->addr);
9070                 num_blocks = cdb->length;
9071                 break;
9072         }
9073         default:
9074                 /*
9075                  * We got a command we don't support.  This shouldn't
9076                  * happen, commands should be filtered out above us.
9077                  */
9078                 ctl_set_invalid_opcode(ctsio);
9079                 ctl_done((union ctl_io *)ctsio);
9080
9081                 return (CTL_RETVAL_COMPLETE);
9082                 break; /* NOTREACHED */
9083         }
9084
9085         /*
9086          * The first check is to make sure we're in bounds, the second
9087          * check is to catch wrap-around problems.  If the lba + num blocks
9088          * is less than the lba, then we've wrapped around and the block
9089          * range is invalid anyway.
9090          */
9091         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9092          || ((lba + num_blocks) < lba)) {
9093                 ctl_set_lba_out_of_range(ctsio);
9094                 ctl_done((union ctl_io *)ctsio);
9095                 return (CTL_RETVAL_COMPLETE);
9096         }
9097
9098         /*
9099          * According to SBC-3, a transfer length of 0 is not an error.
9100          */
9101         if (num_blocks == 0) {
9102                 ctl_set_success(ctsio);
9103                 ctl_done((union ctl_io *)ctsio);
9104                 return (CTL_RETVAL_COMPLETE);
9105         }
9106
9107         /* Set FUA if write cache is disabled. */
9108         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9109             SCP_WCE) == 0)
9110                 flags |= CTL_LLF_FUA;
9111
9112         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9113         ctsio->kern_rel_offset = 0;
9114
9115         /*
9116          * Set the IO_CONT flag, so that if this I/O gets passed to
9117          * ctl_data_submit_done(), it'll get passed back to
9118          * ctl_ctl_cnw_cont() for further processing.
9119          */
9120         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9121         ctsio->io_cont = ctl_cnw_cont;
9122
9123         lbalen = (struct ctl_lba_len_flags *)
9124             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9125         lbalen->lba = lba;
9126         lbalen->len = num_blocks;
9127         lbalen->flags = CTL_LLF_COMPARE | flags;
9128
9129         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9130         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9131         return (retval);
9132 }
9133
9134 int
9135 ctl_verify(struct ctl_scsiio *ctsio)
9136 {
9137         struct ctl_lun *lun;
9138         struct ctl_lba_len_flags *lbalen;
9139         uint64_t lba;
9140         uint32_t num_blocks;
9141         int bytchk, flags;
9142         int retval;
9143
9144         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9145
9146         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9147
9148         bytchk = 0;
9149         flags = CTL_LLF_FUA;
9150         retval = CTL_RETVAL_COMPLETE;
9151
9152         switch (ctsio->cdb[0]) {
9153         case VERIFY_10: {
9154                 struct scsi_verify_10 *cdb;
9155
9156                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9157                 if (cdb->byte2 & SVFY_BYTCHK)
9158                         bytchk = 1;
9159                 if (cdb->byte2 & SVFY_DPO)
9160                         flags |= CTL_LLF_DPO;
9161                 lba = scsi_4btoul(cdb->addr);
9162                 num_blocks = scsi_2btoul(cdb->length);
9163                 break;
9164         }
9165         case VERIFY_12: {
9166                 struct scsi_verify_12 *cdb;
9167
9168                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9169                 if (cdb->byte2 & SVFY_BYTCHK)
9170                         bytchk = 1;
9171                 if (cdb->byte2 & SVFY_DPO)
9172                         flags |= CTL_LLF_DPO;
9173                 lba = scsi_4btoul(cdb->addr);
9174                 num_blocks = scsi_4btoul(cdb->length);
9175                 break;
9176         }
9177         case VERIFY_16: {
9178                 struct scsi_rw_16 *cdb;
9179
9180                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9181                 if (cdb->byte2 & SVFY_BYTCHK)
9182                         bytchk = 1;
9183                 if (cdb->byte2 & SVFY_DPO)
9184                         flags |= CTL_LLF_DPO;
9185                 lba = scsi_8btou64(cdb->addr);
9186                 num_blocks = scsi_4btoul(cdb->length);
9187                 break;
9188         }
9189         default:
9190                 /*
9191                  * We got a command we don't support.  This shouldn't
9192                  * happen, commands should be filtered out above us.
9193                  */
9194                 ctl_set_invalid_opcode(ctsio);
9195                 ctl_done((union ctl_io *)ctsio);
9196                 return (CTL_RETVAL_COMPLETE);
9197         }
9198
9199         /*
9200          * The first check is to make sure we're in bounds, the second
9201          * check is to catch wrap-around problems.  If the lba + num blocks
9202          * is less than the lba, then we've wrapped around and the block
9203          * range is invalid anyway.
9204          */
9205         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9206          || ((lba + num_blocks) < lba)) {
9207                 ctl_set_lba_out_of_range(ctsio);
9208                 ctl_done((union ctl_io *)ctsio);
9209                 return (CTL_RETVAL_COMPLETE);
9210         }
9211
9212         /*
9213          * According to SBC-3, a transfer length of 0 is not an error.
9214          */
9215         if (num_blocks == 0) {
9216                 ctl_set_success(ctsio);
9217                 ctl_done((union ctl_io *)ctsio);
9218                 return (CTL_RETVAL_COMPLETE);
9219         }
9220
9221         lbalen = (struct ctl_lba_len_flags *)
9222             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9223         lbalen->lba = lba;
9224         lbalen->len = num_blocks;
9225         if (bytchk) {
9226                 lbalen->flags = CTL_LLF_COMPARE | flags;
9227                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9228         } else {
9229                 lbalen->flags = CTL_LLF_VERIFY | flags;
9230                 ctsio->kern_total_len = 0;
9231         }
9232         ctsio->kern_rel_offset = 0;
9233
9234         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9235         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9236         return (retval);
9237 }
9238
9239 int
9240 ctl_report_luns(struct ctl_scsiio *ctsio)
9241 {
9242         struct ctl_softc *softc = control_softc;
9243         struct scsi_report_luns *cdb;
9244         struct scsi_report_luns_data *lun_data;
9245         struct ctl_lun *lun, *request_lun;
9246         struct ctl_port *port;
9247         int num_luns, retval;
9248         uint32_t alloc_len, lun_datalen;
9249         int num_filled, well_known;
9250         uint32_t initidx, targ_lun_id, lun_id;
9251
9252         retval = CTL_RETVAL_COMPLETE;
9253         well_known = 0;
9254
9255         cdb = (struct scsi_report_luns *)ctsio->cdb;
9256         port = ctl_io_port(&ctsio->io_hdr);
9257
9258         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9259
9260         mtx_lock(&softc->ctl_lock);
9261         num_luns = 0;
9262         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9263                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9264                         num_luns++;
9265         }
9266         mtx_unlock(&softc->ctl_lock);
9267
9268         switch (cdb->select_report) {
9269         case RPL_REPORT_DEFAULT:
9270         case RPL_REPORT_ALL:
9271                 break;
9272         case RPL_REPORT_WELLKNOWN:
9273                 well_known = 1;
9274                 num_luns = 0;
9275                 break;
9276         default:
9277                 ctl_set_invalid_field(ctsio,
9278                                       /*sks_valid*/ 1,
9279                                       /*command*/ 1,
9280                                       /*field*/ 2,
9281                                       /*bit_valid*/ 0,
9282                                       /*bit*/ 0);
9283                 ctl_done((union ctl_io *)ctsio);
9284                 return (retval);
9285                 break; /* NOTREACHED */
9286         }
9287
9288         alloc_len = scsi_4btoul(cdb->length);
9289         /*
9290          * The initiator has to allocate at least 16 bytes for this request,
9291          * so he can at least get the header and the first LUN.  Otherwise
9292          * we reject the request (per SPC-3 rev 14, section 6.21).
9293          */
9294         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9295             sizeof(struct scsi_report_luns_lundata))) {
9296                 ctl_set_invalid_field(ctsio,
9297                                       /*sks_valid*/ 1,
9298                                       /*command*/ 1,
9299                                       /*field*/ 6,
9300                                       /*bit_valid*/ 0,
9301                                       /*bit*/ 0);
9302                 ctl_done((union ctl_io *)ctsio);
9303                 return (retval);
9304         }
9305
9306         request_lun = (struct ctl_lun *)
9307                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9308
9309         lun_datalen = sizeof(*lun_data) +
9310                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9311
9312         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9313         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9314         ctsio->kern_sg_entries = 0;
9315
9316         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9317
9318         mtx_lock(&softc->ctl_lock);
9319         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9320                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9321                 if (lun_id >= CTL_MAX_LUNS)
9322                         continue;
9323                 lun = softc->ctl_luns[lun_id];
9324                 if (lun == NULL)
9325                         continue;
9326
9327                 if (targ_lun_id <= 0xff) {
9328                         /*
9329                          * Peripheral addressing method, bus number 0.
9330                          */
9331                         lun_data->luns[num_filled].lundata[0] =
9332                                 RPL_LUNDATA_ATYP_PERIPH;
9333                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9334                         num_filled++;
9335                 } else if (targ_lun_id <= 0x3fff) {
9336                         /*
9337                          * Flat addressing method.
9338                          */
9339                         lun_data->luns[num_filled].lundata[0] =
9340                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9341                         lun_data->luns[num_filled].lundata[1] =
9342                                 (targ_lun_id & 0xff);
9343                         num_filled++;
9344                 } else if (targ_lun_id <= 0xffffff) {
9345                         /*
9346                          * Extended flat addressing method.
9347                          */
9348                         lun_data->luns[num_filled].lundata[0] =
9349                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9350                         scsi_ulto3b(targ_lun_id,
9351                             &lun_data->luns[num_filled].lundata[1]);
9352                         num_filled++;
9353                 } else {
9354                         printf("ctl_report_luns: bogus LUN number %jd, "
9355                                "skipping\n", (intmax_t)targ_lun_id);
9356                 }
9357                 /*
9358                  * According to SPC-3, rev 14 section 6.21:
9359                  *
9360                  * "The execution of a REPORT LUNS command to any valid and
9361                  * installed logical unit shall clear the REPORTED LUNS DATA
9362                  * HAS CHANGED unit attention condition for all logical
9363                  * units of that target with respect to the requesting
9364                  * initiator. A valid and installed logical unit is one
9365                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9366                  * INQUIRY data (see 6.4.2)."
9367                  *
9368                  * If request_lun is NULL, the LUN this report luns command
9369                  * was issued to is either disabled or doesn't exist. In that
9370                  * case, we shouldn't clear any pending lun change unit
9371                  * attention.
9372                  */
9373                 if (request_lun != NULL) {
9374                         mtx_lock(&lun->lun_lock);
9375                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9376                         mtx_unlock(&lun->lun_lock);
9377                 }
9378         }
9379         mtx_unlock(&softc->ctl_lock);
9380
9381         /*
9382          * It's quite possible that we've returned fewer LUNs than we allocated
9383          * space for.  Trim it.
9384          */
9385         lun_datalen = sizeof(*lun_data) +
9386                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9387
9388         if (lun_datalen < alloc_len) {
9389                 ctsio->residual = alloc_len - lun_datalen;
9390                 ctsio->kern_data_len = lun_datalen;
9391                 ctsio->kern_total_len = lun_datalen;
9392         } else {
9393                 ctsio->residual = 0;
9394                 ctsio->kern_data_len = alloc_len;
9395                 ctsio->kern_total_len = alloc_len;
9396         }
9397         ctsio->kern_data_resid = 0;
9398         ctsio->kern_rel_offset = 0;
9399         ctsio->kern_sg_entries = 0;
9400
9401         /*
9402          * We set this to the actual data length, regardless of how much
9403          * space we actually have to return results.  If the user looks at
9404          * this value, he'll know whether or not he allocated enough space
9405          * and reissue the command if necessary.  We don't support well
9406          * known logical units, so if the user asks for that, return none.
9407          */
9408         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9409
9410         /*
9411          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9412          * this request.
9413          */
9414         ctl_set_success(ctsio);
9415         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9416         ctsio->be_move_done = ctl_config_move_done;
9417         ctl_datamove((union ctl_io *)ctsio);
9418         return (retval);
9419 }
9420
9421 int
9422 ctl_request_sense(struct ctl_scsiio *ctsio)
9423 {
9424         struct scsi_request_sense *cdb;
9425         struct scsi_sense_data *sense_ptr;
9426         struct ctl_softc *ctl_softc;
9427         struct ctl_lun *lun;
9428         uint32_t initidx;
9429         int have_error;
9430         scsi_sense_data_type sense_format;
9431         ctl_ua_type ua_type;
9432
9433         cdb = (struct scsi_request_sense *)ctsio->cdb;
9434
9435         ctl_softc = control_softc;
9436         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9437
9438         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9439
9440         /*
9441          * Determine which sense format the user wants.
9442          */
9443         if (cdb->byte2 & SRS_DESC)
9444                 sense_format = SSD_TYPE_DESC;
9445         else
9446                 sense_format = SSD_TYPE_FIXED;
9447
9448         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9449         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9450         ctsio->kern_sg_entries = 0;
9451
9452         /*
9453          * struct scsi_sense_data, which is currently set to 256 bytes, is
9454          * larger than the largest allowed value for the length field in the
9455          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9456          */
9457         ctsio->residual = 0;
9458         ctsio->kern_data_len = cdb->length;
9459         ctsio->kern_total_len = cdb->length;
9460
9461         ctsio->kern_data_resid = 0;
9462         ctsio->kern_rel_offset = 0;
9463         ctsio->kern_sg_entries = 0;
9464
9465         /*
9466          * If we don't have a LUN, we don't have any pending sense.
9467          */
9468         if (lun == NULL)
9469                 goto no_sense;
9470
9471         have_error = 0;
9472         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9473         /*
9474          * Check for pending sense, and then for pending unit attentions.
9475          * Pending sense gets returned first, then pending unit attentions.
9476          */
9477         mtx_lock(&lun->lun_lock);
9478 #ifdef CTL_WITH_CA
9479         if (ctl_is_set(lun->have_ca, initidx)) {
9480                 scsi_sense_data_type stored_format;
9481
9482                 /*
9483                  * Check to see which sense format was used for the stored
9484                  * sense data.
9485                  */
9486                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9487
9488                 /*
9489                  * If the user requested a different sense format than the
9490                  * one we stored, then we need to convert it to the other
9491                  * format.  If we're going from descriptor to fixed format
9492                  * sense data, we may lose things in translation, depending
9493                  * on what options were used.
9494                  *
9495                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9496                  * for some reason we'll just copy it out as-is.
9497                  */
9498                 if ((stored_format == SSD_TYPE_FIXED)
9499                  && (sense_format == SSD_TYPE_DESC))
9500                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9501                             &lun->pending_sense[initidx],
9502                             (struct scsi_sense_data_desc *)sense_ptr);
9503                 else if ((stored_format == SSD_TYPE_DESC)
9504                       && (sense_format == SSD_TYPE_FIXED))
9505                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9506                             &lun->pending_sense[initidx],
9507                             (struct scsi_sense_data_fixed *)sense_ptr);
9508                 else
9509                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9510                                MIN(sizeof(*sense_ptr),
9511                                sizeof(lun->pending_sense[initidx])));
9512
9513                 ctl_clear_mask(lun->have_ca, initidx);
9514                 have_error = 1;
9515         } else
9516 #endif
9517         {
9518                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9519                 if (ua_type != CTL_UA_NONE)
9520                         have_error = 1;
9521                 if (ua_type == CTL_UA_LUN_CHANGE) {
9522                         mtx_unlock(&lun->lun_lock);
9523                         mtx_lock(&ctl_softc->ctl_lock);
9524                         ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9525                         mtx_unlock(&ctl_softc->ctl_lock);
9526                         mtx_lock(&lun->lun_lock);
9527                 }
9528
9529         }
9530         mtx_unlock(&lun->lun_lock);
9531
9532         /*
9533          * We already have a pending error, return it.
9534          */
9535         if (have_error != 0) {
9536                 /*
9537                  * We report the SCSI status as OK, since the status of the
9538                  * request sense command itself is OK.
9539                  * We report 0 for the sense length, because we aren't doing
9540                  * autosense in this case.  We're reporting sense as
9541                  * parameter data.
9542                  */
9543                 ctl_set_success(ctsio);
9544                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9545                 ctsio->be_move_done = ctl_config_move_done;
9546                 ctl_datamove((union ctl_io *)ctsio);
9547                 return (CTL_RETVAL_COMPLETE);
9548         }
9549
9550 no_sense:
9551
9552         /*
9553          * No sense information to report, so we report that everything is
9554          * okay.
9555          */
9556         ctl_set_sense_data(sense_ptr,
9557                            lun,
9558                            sense_format,
9559                            /*current_error*/ 1,
9560                            /*sense_key*/ SSD_KEY_NO_SENSE,
9561                            /*asc*/ 0x00,
9562                            /*ascq*/ 0x00,
9563                            SSD_ELEM_NONE);
9564
9565         /*
9566          * We report 0 for the sense length, because we aren't doing
9567          * autosense in this case.  We're reporting sense as parameter data.
9568          */
9569         ctl_set_success(ctsio);
9570         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9571         ctsio->be_move_done = ctl_config_move_done;
9572         ctl_datamove((union ctl_io *)ctsio);
9573         return (CTL_RETVAL_COMPLETE);
9574 }
9575
9576 int
9577 ctl_tur(struct ctl_scsiio *ctsio)
9578 {
9579
9580         CTL_DEBUG_PRINT(("ctl_tur\n"));
9581
9582         ctl_set_success(ctsio);
9583         ctl_done((union ctl_io *)ctsio);
9584
9585         return (CTL_RETVAL_COMPLETE);
9586 }
9587
9588 /*
9589  * SCSI VPD page 0x00, the Supported VPD Pages page.
9590  */
9591 static int
9592 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9593 {
9594         struct scsi_vpd_supported_pages *pages;
9595         int sup_page_size;
9596         struct ctl_lun *lun;
9597         int p;
9598
9599         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9600
9601         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9602             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9603         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9604         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9605         ctsio->kern_sg_entries = 0;
9606
9607         if (sup_page_size < alloc_len) {
9608                 ctsio->residual = alloc_len - sup_page_size;
9609                 ctsio->kern_data_len = sup_page_size;
9610                 ctsio->kern_total_len = sup_page_size;
9611         } else {
9612                 ctsio->residual = 0;
9613                 ctsio->kern_data_len = alloc_len;
9614                 ctsio->kern_total_len = alloc_len;
9615         }
9616         ctsio->kern_data_resid = 0;
9617         ctsio->kern_rel_offset = 0;
9618         ctsio->kern_sg_entries = 0;
9619
9620         /*
9621          * The control device is always connected.  The disk device, on the
9622          * other hand, may not be online all the time.  Need to change this
9623          * to figure out whether the disk device is actually online or not.
9624          */
9625         if (lun != NULL)
9626                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9627                                 lun->be_lun->lun_type;
9628         else
9629                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9630
9631         p = 0;
9632         /* Supported VPD pages */
9633         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9634         /* Serial Number */
9635         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9636         /* Device Identification */
9637         pages->page_list[p++] = SVPD_DEVICE_ID;
9638         /* Extended INQUIRY Data */
9639         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9640         /* Mode Page Policy */
9641         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9642         /* SCSI Ports */
9643         pages->page_list[p++] = SVPD_SCSI_PORTS;
9644         /* Third-party Copy */
9645         pages->page_list[p++] = SVPD_SCSI_TPC;
9646         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9647                 /* Block limits */
9648                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9649                 /* Block Device Characteristics */
9650                 pages->page_list[p++] = SVPD_BDC;
9651                 /* Logical Block Provisioning */
9652                 pages->page_list[p++] = SVPD_LBP;
9653         }
9654         pages->length = p;
9655
9656         ctl_set_success(ctsio);
9657         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9658         ctsio->be_move_done = ctl_config_move_done;
9659         ctl_datamove((union ctl_io *)ctsio);
9660         return (CTL_RETVAL_COMPLETE);
9661 }
9662
9663 /*
9664  * SCSI VPD page 0x80, the Unit Serial Number page.
9665  */
9666 static int
9667 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9668 {
9669         struct scsi_vpd_unit_serial_number *sn_ptr;
9670         struct ctl_lun *lun;
9671         int data_len;
9672
9673         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9674
9675         data_len = 4 + CTL_SN_LEN;
9676         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9677         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9678         if (data_len < alloc_len) {
9679                 ctsio->residual = alloc_len - data_len;
9680                 ctsio->kern_data_len = data_len;
9681                 ctsio->kern_total_len = data_len;
9682         } else {
9683                 ctsio->residual = 0;
9684                 ctsio->kern_data_len = alloc_len;
9685                 ctsio->kern_total_len = alloc_len;
9686         }
9687         ctsio->kern_data_resid = 0;
9688         ctsio->kern_rel_offset = 0;
9689         ctsio->kern_sg_entries = 0;
9690
9691         /*
9692          * The control device is always connected.  The disk device, on the
9693          * other hand, may not be online all the time.  Need to change this
9694          * to figure out whether the disk device is actually online or not.
9695          */
9696         if (lun != NULL)
9697                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9698                                   lun->be_lun->lun_type;
9699         else
9700                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9701
9702         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9703         sn_ptr->length = CTL_SN_LEN;
9704         /*
9705          * If we don't have a LUN, we just leave the serial number as
9706          * all spaces.
9707          */
9708         if (lun != NULL) {
9709                 strncpy((char *)sn_ptr->serial_num,
9710                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9711         } else
9712                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9713
9714         ctl_set_success(ctsio);
9715         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9716         ctsio->be_move_done = ctl_config_move_done;
9717         ctl_datamove((union ctl_io *)ctsio);
9718         return (CTL_RETVAL_COMPLETE);
9719 }
9720
9721
9722 /*
9723  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9724  */
9725 static int
9726 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9727 {
9728         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9729         struct ctl_lun *lun;
9730         int data_len;
9731
9732         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9733
9734         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9735         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9736         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9737         ctsio->kern_sg_entries = 0;
9738
9739         if (data_len < alloc_len) {
9740                 ctsio->residual = alloc_len - data_len;
9741                 ctsio->kern_data_len = data_len;
9742                 ctsio->kern_total_len = data_len;
9743         } else {
9744                 ctsio->residual = 0;
9745                 ctsio->kern_data_len = alloc_len;
9746                 ctsio->kern_total_len = alloc_len;
9747         }
9748         ctsio->kern_data_resid = 0;
9749         ctsio->kern_rel_offset = 0;
9750         ctsio->kern_sg_entries = 0;
9751
9752         /*
9753          * The control device is always connected.  The disk device, on the
9754          * other hand, may not be online all the time.
9755          */
9756         if (lun != NULL)
9757                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9758                                      lun->be_lun->lun_type;
9759         else
9760                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9761         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9762         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9763         /*
9764          * We support head of queue, ordered and simple tags.
9765          */
9766         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9767         /*
9768          * Volatile cache supported.
9769          */
9770         eid_ptr->flags3 = SVPD_EID_V_SUP;
9771
9772         /*
9773          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9774          * attention for a particular IT nexus on all LUNs once we report
9775          * it to that nexus once.  This bit is required as of SPC-4.
9776          */
9777         eid_ptr->flags4 = SVPD_EID_LUICLT;
9778
9779         /*
9780          * XXX KDM in order to correctly answer this, we would need
9781          * information from the SIM to determine how much sense data it
9782          * can send.  So this would really be a path inquiry field, most
9783          * likely.  This can be set to a maximum of 252 according to SPC-4,
9784          * but the hardware may or may not be able to support that much.
9785          * 0 just means that the maximum sense data length is not reported.
9786          */
9787         eid_ptr->max_sense_length = 0;
9788
9789         ctl_set_success(ctsio);
9790         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9791         ctsio->be_move_done = ctl_config_move_done;
9792         ctl_datamove((union ctl_io *)ctsio);
9793         return (CTL_RETVAL_COMPLETE);
9794 }
9795
9796 static int
9797 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9798 {
9799         struct scsi_vpd_mode_page_policy *mpp_ptr;
9800         struct ctl_lun *lun;
9801         int data_len;
9802
9803         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9804
9805         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9806             sizeof(struct scsi_vpd_mode_page_policy_descr);
9807
9808         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9809         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9810         ctsio->kern_sg_entries = 0;
9811
9812         if (data_len < alloc_len) {
9813                 ctsio->residual = alloc_len - data_len;
9814                 ctsio->kern_data_len = data_len;
9815                 ctsio->kern_total_len = data_len;
9816         } else {
9817                 ctsio->residual = 0;
9818                 ctsio->kern_data_len = alloc_len;
9819                 ctsio->kern_total_len = alloc_len;
9820         }
9821         ctsio->kern_data_resid = 0;
9822         ctsio->kern_rel_offset = 0;
9823         ctsio->kern_sg_entries = 0;
9824
9825         /*
9826          * The control device is always connected.  The disk device, on the
9827          * other hand, may not be online all the time.
9828          */
9829         if (lun != NULL)
9830                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9831                                      lun->be_lun->lun_type;
9832         else
9833                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9834         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9835         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9836         mpp_ptr->descr[0].page_code = 0x3f;
9837         mpp_ptr->descr[0].subpage_code = 0xff;
9838         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9839
9840         ctl_set_success(ctsio);
9841         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9842         ctsio->be_move_done = ctl_config_move_done;
9843         ctl_datamove((union ctl_io *)ctsio);
9844         return (CTL_RETVAL_COMPLETE);
9845 }
9846
9847 /*
9848  * SCSI VPD page 0x83, the Device Identification page.
9849  */
9850 static int
9851 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9852 {
9853         struct scsi_vpd_device_id *devid_ptr;
9854         struct scsi_vpd_id_descriptor *desc;
9855         struct ctl_softc *softc;
9856         struct ctl_lun *lun;
9857         struct ctl_port *port;
9858         int data_len;
9859         uint8_t proto;
9860
9861         softc = control_softc;
9862
9863         port = ctl_io_port(&ctsio->io_hdr);
9864         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9865
9866         data_len = sizeof(struct scsi_vpd_device_id) +
9867             sizeof(struct scsi_vpd_id_descriptor) +
9868                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9869             sizeof(struct scsi_vpd_id_descriptor) +
9870                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9871         if (lun && lun->lun_devid)
9872                 data_len += lun->lun_devid->len;
9873         if (port && port->port_devid)
9874                 data_len += port->port_devid->len;
9875         if (port && port->target_devid)
9876                 data_len += port->target_devid->len;
9877
9878         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9879         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9880         ctsio->kern_sg_entries = 0;
9881
9882         if (data_len < alloc_len) {
9883                 ctsio->residual = alloc_len - data_len;
9884                 ctsio->kern_data_len = data_len;
9885                 ctsio->kern_total_len = data_len;
9886         } else {
9887                 ctsio->residual = 0;
9888                 ctsio->kern_data_len = alloc_len;
9889                 ctsio->kern_total_len = alloc_len;
9890         }
9891         ctsio->kern_data_resid = 0;
9892         ctsio->kern_rel_offset = 0;
9893         ctsio->kern_sg_entries = 0;
9894
9895         /*
9896          * The control device is always connected.  The disk device, on the
9897          * other hand, may not be online all the time.
9898          */
9899         if (lun != NULL)
9900                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9901                                      lun->be_lun->lun_type;
9902         else
9903                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9904         devid_ptr->page_code = SVPD_DEVICE_ID;
9905         scsi_ulto2b(data_len - 4, devid_ptr->length);
9906
9907         if (port && port->port_type == CTL_PORT_FC)
9908                 proto = SCSI_PROTO_FC << 4;
9909         else if (port && port->port_type == CTL_PORT_ISCSI)
9910                 proto = SCSI_PROTO_ISCSI << 4;
9911         else
9912                 proto = SCSI_PROTO_SPI << 4;
9913         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9914
9915         /*
9916          * We're using a LUN association here.  i.e., this device ID is a
9917          * per-LUN identifier.
9918          */
9919         if (lun && lun->lun_devid) {
9920                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9921                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9922                     lun->lun_devid->len);
9923         }
9924
9925         /*
9926          * This is for the WWPN which is a port association.
9927          */
9928         if (port && port->port_devid) {
9929                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9930                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9931                     port->port_devid->len);
9932         }
9933
9934         /*
9935          * This is for the Relative Target Port(type 4h) identifier
9936          */
9937         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9938         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9939             SVPD_ID_TYPE_RELTARG;
9940         desc->length = 4;
9941         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9942         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9943             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9944
9945         /*
9946          * This is for the Target Port Group(type 5h) identifier
9947          */
9948         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9949         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9950             SVPD_ID_TYPE_TPORTGRP;
9951         desc->length = 4;
9952         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9953             &desc->identifier[2]);
9954         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9955             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9956
9957         /*
9958          * This is for the Target identifier
9959          */
9960         if (port && port->target_devid) {
9961                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9962         }
9963
9964         ctl_set_success(ctsio);
9965         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9966         ctsio->be_move_done = ctl_config_move_done;
9967         ctl_datamove((union ctl_io *)ctsio);
9968         return (CTL_RETVAL_COMPLETE);
9969 }
9970
9971 static int
9972 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9973 {
9974         struct ctl_softc *softc = control_softc;
9975         struct scsi_vpd_scsi_ports *sp;
9976         struct scsi_vpd_port_designation *pd;
9977         struct scsi_vpd_port_designation_cont *pdc;
9978         struct ctl_lun *lun;
9979         struct ctl_port *port;
9980         int data_len, num_target_ports, iid_len, id_len;
9981
9982         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9983
9984         num_target_ports = 0;
9985         iid_len = 0;
9986         id_len = 0;
9987         mtx_lock(&softc->ctl_lock);
9988         STAILQ_FOREACH(port, &softc->port_list, links) {
9989                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9990                         continue;
9991                 if (lun != NULL &&
9992                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9993                         continue;
9994                 num_target_ports++;
9995                 if (port->init_devid)
9996                         iid_len += port->init_devid->len;
9997                 if (port->port_devid)
9998                         id_len += port->port_devid->len;
9999         }
10000         mtx_unlock(&softc->ctl_lock);
10001
10002         data_len = sizeof(struct scsi_vpd_scsi_ports) +
10003             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10004              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10005         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10006         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10007         ctsio->kern_sg_entries = 0;
10008
10009         if (data_len < alloc_len) {
10010                 ctsio->residual = alloc_len - data_len;
10011                 ctsio->kern_data_len = data_len;
10012                 ctsio->kern_total_len = data_len;
10013         } else {
10014                 ctsio->residual = 0;
10015                 ctsio->kern_data_len = alloc_len;
10016                 ctsio->kern_total_len = alloc_len;
10017         }
10018         ctsio->kern_data_resid = 0;
10019         ctsio->kern_rel_offset = 0;
10020         ctsio->kern_sg_entries = 0;
10021
10022         /*
10023          * The control device is always connected.  The disk device, on the
10024          * other hand, may not be online all the time.  Need to change this
10025          * to figure out whether the disk device is actually online or not.
10026          */
10027         if (lun != NULL)
10028                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10029                                   lun->be_lun->lun_type;
10030         else
10031                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10032
10033         sp->page_code = SVPD_SCSI_PORTS;
10034         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10035             sp->page_length);
10036         pd = &sp->design[0];
10037
10038         mtx_lock(&softc->ctl_lock);
10039         STAILQ_FOREACH(port, &softc->port_list, links) {
10040                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10041                         continue;
10042                 if (lun != NULL &&
10043                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10044                         continue;
10045                 scsi_ulto2b(port->targ_port, pd->relative_port_id);
10046                 if (port->init_devid) {
10047                         iid_len = port->init_devid->len;
10048                         memcpy(pd->initiator_transportid,
10049                             port->init_devid->data, port->init_devid->len);
10050                 } else
10051                         iid_len = 0;
10052                 scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10053                 pdc = (struct scsi_vpd_port_designation_cont *)
10054                     (&pd->initiator_transportid[iid_len]);
10055                 if (port->port_devid) {
10056                         id_len = port->port_devid->len;
10057                         memcpy(pdc->target_port_descriptors,
10058                             port->port_devid->data, port->port_devid->len);
10059                 } else
10060                         id_len = 0;
10061                 scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10062                 pd = (struct scsi_vpd_port_designation *)
10063                     ((uint8_t *)pdc->target_port_descriptors + id_len);
10064         }
10065         mtx_unlock(&softc->ctl_lock);
10066
10067         ctl_set_success(ctsio);
10068         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10069         ctsio->be_move_done = ctl_config_move_done;
10070         ctl_datamove((union ctl_io *)ctsio);
10071         return (CTL_RETVAL_COMPLETE);
10072 }
10073
10074 static int
10075 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10076 {
10077         struct scsi_vpd_block_limits *bl_ptr;
10078         struct ctl_lun *lun;
10079         int bs;
10080
10081         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10082
10083         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10084         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10085         ctsio->kern_sg_entries = 0;
10086
10087         if (sizeof(*bl_ptr) < alloc_len) {
10088                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10089                 ctsio->kern_data_len = sizeof(*bl_ptr);
10090                 ctsio->kern_total_len = sizeof(*bl_ptr);
10091         } else {
10092                 ctsio->residual = 0;
10093                 ctsio->kern_data_len = alloc_len;
10094                 ctsio->kern_total_len = alloc_len;
10095         }
10096         ctsio->kern_data_resid = 0;
10097         ctsio->kern_rel_offset = 0;
10098         ctsio->kern_sg_entries = 0;
10099
10100         /*
10101          * The control device is always connected.  The disk device, on the
10102          * other hand, may not be online all the time.  Need to change this
10103          * to figure out whether the disk device is actually online or not.
10104          */
10105         if (lun != NULL)
10106                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10107                                   lun->be_lun->lun_type;
10108         else
10109                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10110
10111         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10112         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10113         bl_ptr->max_cmp_write_len = 0xff;
10114         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10115         if (lun != NULL) {
10116                 bs = lun->be_lun->blocksize;
10117                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10118                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10119                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10120                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10121                         if (lun->be_lun->ublockexp != 0) {
10122                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
10123                                     bl_ptr->opt_unmap_grain);
10124                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10125                                     bl_ptr->unmap_grain_align);
10126                         }
10127                 }
10128                 scsi_ulto4b(lun->be_lun->atomicblock,
10129                     bl_ptr->max_atomic_transfer_length);
10130                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10131                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10132         }
10133         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10134
10135         ctl_set_success(ctsio);
10136         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10137         ctsio->be_move_done = ctl_config_move_done;
10138         ctl_datamove((union ctl_io *)ctsio);
10139         return (CTL_RETVAL_COMPLETE);
10140 }
10141
10142 static int
10143 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10144 {
10145         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10146         struct ctl_lun *lun;
10147         const char *value;
10148         u_int i;
10149
10150         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10151
10152         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10153         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10154         ctsio->kern_sg_entries = 0;
10155
10156         if (sizeof(*bdc_ptr) < alloc_len) {
10157                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10158                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10159                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10160         } else {
10161                 ctsio->residual = 0;
10162                 ctsio->kern_data_len = alloc_len;
10163                 ctsio->kern_total_len = alloc_len;
10164         }
10165         ctsio->kern_data_resid = 0;
10166         ctsio->kern_rel_offset = 0;
10167         ctsio->kern_sg_entries = 0;
10168
10169         /*
10170          * The control device is always connected.  The disk device, on the
10171          * other hand, may not be online all the time.  Need to change this
10172          * to figure out whether the disk device is actually online or not.
10173          */
10174         if (lun != NULL)
10175                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10176                                   lun->be_lun->lun_type;
10177         else
10178                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10179         bdc_ptr->page_code = SVPD_BDC;
10180         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10181         if (lun != NULL &&
10182             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10183                 i = strtol(value, NULL, 0);
10184         else
10185                 i = CTL_DEFAULT_ROTATION_RATE;
10186         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10187         if (lun != NULL &&
10188             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10189                 i = strtol(value, NULL, 0);
10190         else
10191                 i = 0;
10192         bdc_ptr->wab_wac_ff = (i & 0x0f);
10193         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10194
10195         ctl_set_success(ctsio);
10196         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10197         ctsio->be_move_done = ctl_config_move_done;
10198         ctl_datamove((union ctl_io *)ctsio);
10199         return (CTL_RETVAL_COMPLETE);
10200 }
10201
10202 static int
10203 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10204 {
10205         struct scsi_vpd_logical_block_prov *lbp_ptr;
10206         struct ctl_lun *lun;
10207
10208         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10209
10210         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10211         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10212         ctsio->kern_sg_entries = 0;
10213
10214         if (sizeof(*lbp_ptr) < alloc_len) {
10215                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10216                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10217                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10218         } else {
10219                 ctsio->residual = 0;
10220                 ctsio->kern_data_len = alloc_len;
10221                 ctsio->kern_total_len = alloc_len;
10222         }
10223         ctsio->kern_data_resid = 0;
10224         ctsio->kern_rel_offset = 0;
10225         ctsio->kern_sg_entries = 0;
10226
10227         /*
10228          * The control device is always connected.  The disk device, on the
10229          * other hand, may not be online all the time.  Need to change this
10230          * to figure out whether the disk device is actually online or not.
10231          */
10232         if (lun != NULL)
10233                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10234                                   lun->be_lun->lun_type;
10235         else
10236                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10237
10238         lbp_ptr->page_code = SVPD_LBP;
10239         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10240         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10241         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10242                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10243                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10244                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10245         }
10246
10247         ctl_set_success(ctsio);
10248         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10249         ctsio->be_move_done = ctl_config_move_done;
10250         ctl_datamove((union ctl_io *)ctsio);
10251         return (CTL_RETVAL_COMPLETE);
10252 }
10253
10254 /*
10255  * INQUIRY with the EVPD bit set.
10256  */
10257 static int
10258 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10259 {
10260         struct ctl_lun *lun;
10261         struct scsi_inquiry *cdb;
10262         int alloc_len, retval;
10263
10264         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10265         cdb = (struct scsi_inquiry *)ctsio->cdb;
10266         alloc_len = scsi_2btoul(cdb->length);
10267
10268         switch (cdb->page_code) {
10269         case SVPD_SUPPORTED_PAGES:
10270                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10271                 break;
10272         case SVPD_UNIT_SERIAL_NUMBER:
10273                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10274                 break;
10275         case SVPD_DEVICE_ID:
10276                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10277                 break;
10278         case SVPD_EXTENDED_INQUIRY_DATA:
10279                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10280                 break;
10281         case SVPD_MODE_PAGE_POLICY:
10282                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10283                 break;
10284         case SVPD_SCSI_PORTS:
10285                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10286                 break;
10287         case SVPD_SCSI_TPC:
10288                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10289                 break;
10290         case SVPD_BLOCK_LIMITS:
10291                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10292                         goto err;
10293                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10294                 break;
10295         case SVPD_BDC:
10296                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10297                         goto err;
10298                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10299                 break;
10300         case SVPD_LBP:
10301                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10302                         goto err;
10303                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10304                 break;
10305         default:
10306 err:
10307                 ctl_set_invalid_field(ctsio,
10308                                       /*sks_valid*/ 1,
10309                                       /*command*/ 1,
10310                                       /*field*/ 2,
10311                                       /*bit_valid*/ 0,
10312                                       /*bit*/ 0);
10313                 ctl_done((union ctl_io *)ctsio);
10314                 retval = CTL_RETVAL_COMPLETE;
10315                 break;
10316         }
10317
10318         return (retval);
10319 }
10320
10321 /*
10322  * Standard INQUIRY data.
10323  */
10324 static int
10325 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10326 {
10327         struct scsi_inquiry_data *inq_ptr;
10328         struct scsi_inquiry *cdb;
10329         struct ctl_softc *softc;
10330         struct ctl_port *port;
10331         struct ctl_lun *lun;
10332         char *val;
10333         uint32_t alloc_len, data_len;
10334         ctl_port_type port_type;
10335
10336         softc = control_softc;
10337
10338         /*
10339          * Figure out whether we're talking to a Fibre Channel port or not.
10340          * We treat the ioctl front end, and any SCSI adapters, as packetized
10341          * SCSI front ends.
10342          */
10343         port = ctl_io_port(&ctsio->io_hdr);
10344         if (port != NULL)
10345                 port_type = port->port_type;
10346         else
10347                 port_type = CTL_PORT_SCSI;
10348         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10349                 port_type = CTL_PORT_SCSI;
10350
10351         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10352         cdb = (struct scsi_inquiry *)ctsio->cdb;
10353         alloc_len = scsi_2btoul(cdb->length);
10354
10355         /*
10356          * We malloc the full inquiry data size here and fill it
10357          * in.  If the user only asks for less, we'll give him
10358          * that much.
10359          */
10360         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10361         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10362         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10363         ctsio->kern_sg_entries = 0;
10364         ctsio->kern_data_resid = 0;
10365         ctsio->kern_rel_offset = 0;
10366
10367         if (data_len < alloc_len) {
10368                 ctsio->residual = alloc_len - data_len;
10369                 ctsio->kern_data_len = data_len;
10370                 ctsio->kern_total_len = data_len;
10371         } else {
10372                 ctsio->residual = 0;
10373                 ctsio->kern_data_len = alloc_len;
10374                 ctsio->kern_total_len = alloc_len;
10375         }
10376
10377         if (lun != NULL) {
10378                 if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10379                     softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10380                         inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10381                             lun->be_lun->lun_type;
10382                 } else {
10383                         inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10384                             lun->be_lun->lun_type;
10385                 }
10386         } else
10387                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10388
10389         /* RMB in byte 2 is 0 */
10390         inq_ptr->version = SCSI_REV_SPC4;
10391
10392         /*
10393          * According to SAM-3, even if a device only supports a single
10394          * level of LUN addressing, it should still set the HISUP bit:
10395          *
10396          * 4.9.1 Logical unit numbers overview
10397          *
10398          * All logical unit number formats described in this standard are
10399          * hierarchical in structure even when only a single level in that
10400          * hierarchy is used. The HISUP bit shall be set to one in the
10401          * standard INQUIRY data (see SPC-2) when any logical unit number
10402          * format described in this standard is used.  Non-hierarchical
10403          * formats are outside the scope of this standard.
10404          *
10405          * Therefore we set the HiSup bit here.
10406          *
10407          * The reponse format is 2, per SPC-3.
10408          */
10409         inq_ptr->response_format = SID_HiSup | 2;
10410
10411         inq_ptr->additional_length = data_len -
10412             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10413         CTL_DEBUG_PRINT(("additional_length = %d\n",
10414                          inq_ptr->additional_length));
10415
10416         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10417         /* 16 bit addressing */
10418         if (port_type == CTL_PORT_SCSI)
10419                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10420         /* XXX set the SID_MultiP bit here if we're actually going to
10421            respond on multiple ports */
10422         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10423
10424         /* 16 bit data bus, synchronous transfers */
10425         if (port_type == CTL_PORT_SCSI)
10426                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10427         /*
10428          * XXX KDM do we want to support tagged queueing on the control
10429          * device at all?
10430          */
10431         if ((lun == NULL)
10432          || (lun->be_lun->lun_type != T_PROCESSOR))
10433                 inq_ptr->flags |= SID_CmdQue;
10434         /*
10435          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10436          * We have 8 bytes for the vendor name, and 16 bytes for the device
10437          * name and 4 bytes for the revision.
10438          */
10439         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10440             "vendor")) == NULL) {
10441                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10442         } else {
10443                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10444                 strncpy(inq_ptr->vendor, val,
10445                     min(sizeof(inq_ptr->vendor), strlen(val)));
10446         }
10447         if (lun == NULL) {
10448                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10449                     sizeof(inq_ptr->product));
10450         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10451                 switch (lun->be_lun->lun_type) {
10452                 case T_DIRECT:
10453                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10454                             sizeof(inq_ptr->product));
10455                         break;
10456                 case T_PROCESSOR:
10457                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10458                             sizeof(inq_ptr->product));
10459                         break;
10460                 default:
10461                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10462                             sizeof(inq_ptr->product));
10463                         break;
10464                 }
10465         } else {
10466                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10467                 strncpy(inq_ptr->product, val,
10468                     min(sizeof(inq_ptr->product), strlen(val)));
10469         }
10470
10471         /*
10472          * XXX make this a macro somewhere so it automatically gets
10473          * incremented when we make changes.
10474          */
10475         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10476             "revision")) == NULL) {
10477                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10478         } else {
10479                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10480                 strncpy(inq_ptr->revision, val,
10481                     min(sizeof(inq_ptr->revision), strlen(val)));
10482         }
10483
10484         /*
10485          * For parallel SCSI, we support double transition and single
10486          * transition clocking.  We also support QAS (Quick Arbitration
10487          * and Selection) and Information Unit transfers on both the
10488          * control and array devices.
10489          */
10490         if (port_type == CTL_PORT_SCSI)
10491                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10492                                     SID_SPI_IUS;
10493
10494         /* SAM-5 (no version claimed) */
10495         scsi_ulto2b(0x00A0, inq_ptr->version1);
10496         /* SPC-4 (no version claimed) */
10497         scsi_ulto2b(0x0460, inq_ptr->version2);
10498         if (port_type == CTL_PORT_FC) {
10499                 /* FCP-2 ANSI INCITS.350:2003 */
10500                 scsi_ulto2b(0x0917, inq_ptr->version3);
10501         } else if (port_type == CTL_PORT_SCSI) {
10502                 /* SPI-4 ANSI INCITS.362:200x */
10503                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10504         } else if (port_type == CTL_PORT_ISCSI) {
10505                 /* iSCSI (no version claimed) */
10506                 scsi_ulto2b(0x0960, inq_ptr->version3);
10507         } else if (port_type == CTL_PORT_SAS) {
10508                 /* SAS (no version claimed) */
10509                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10510         }
10511
10512         if (lun == NULL) {
10513                 /* SBC-4 (no version claimed) */
10514                 scsi_ulto2b(0x0600, inq_ptr->version4);
10515         } else {
10516                 switch (lun->be_lun->lun_type) {
10517                 case T_DIRECT:
10518                         /* SBC-4 (no version claimed) */
10519                         scsi_ulto2b(0x0600, inq_ptr->version4);
10520                         break;
10521                 case T_PROCESSOR:
10522                 default:
10523                         break;
10524                 }
10525         }
10526
10527         ctl_set_success(ctsio);
10528         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10529         ctsio->be_move_done = ctl_config_move_done;
10530         ctl_datamove((union ctl_io *)ctsio);
10531         return (CTL_RETVAL_COMPLETE);
10532 }
10533
10534 int
10535 ctl_inquiry(struct ctl_scsiio *ctsio)
10536 {
10537         struct scsi_inquiry *cdb;
10538         int retval;
10539
10540         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10541
10542         cdb = (struct scsi_inquiry *)ctsio->cdb;
10543         if (cdb->byte2 & SI_EVPD)
10544                 retval = ctl_inquiry_evpd(ctsio);
10545         else if (cdb->page_code == 0)
10546                 retval = ctl_inquiry_std(ctsio);
10547         else {
10548                 ctl_set_invalid_field(ctsio,
10549                                       /*sks_valid*/ 1,
10550                                       /*command*/ 1,
10551                                       /*field*/ 2,
10552                                       /*bit_valid*/ 0,
10553                                       /*bit*/ 0);
10554                 ctl_done((union ctl_io *)ctsio);
10555                 return (CTL_RETVAL_COMPLETE);
10556         }
10557
10558         return (retval);
10559 }
10560
10561 /*
10562  * For known CDB types, parse the LBA and length.
10563  */
10564 static int
10565 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10566 {
10567         if (io->io_hdr.io_type != CTL_IO_SCSI)
10568                 return (1);
10569
10570         switch (io->scsiio.cdb[0]) {
10571         case COMPARE_AND_WRITE: {
10572                 struct scsi_compare_and_write *cdb;
10573
10574                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10575
10576                 *lba = scsi_8btou64(cdb->addr);
10577                 *len = cdb->length;
10578                 break;
10579         }
10580         case READ_6:
10581         case WRITE_6: {
10582                 struct scsi_rw_6 *cdb;
10583
10584                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10585
10586                 *lba = scsi_3btoul(cdb->addr);
10587                 /* only 5 bits are valid in the most significant address byte */
10588                 *lba &= 0x1fffff;
10589                 *len = cdb->length;
10590                 break;
10591         }
10592         case READ_10:
10593         case WRITE_10: {
10594                 struct scsi_rw_10 *cdb;
10595
10596                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10597
10598                 *lba = scsi_4btoul(cdb->addr);
10599                 *len = scsi_2btoul(cdb->length);
10600                 break;
10601         }
10602         case WRITE_VERIFY_10: {
10603                 struct scsi_write_verify_10 *cdb;
10604
10605                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10606
10607                 *lba = scsi_4btoul(cdb->addr);
10608                 *len = scsi_2btoul(cdb->length);
10609                 break;
10610         }
10611         case READ_12:
10612         case WRITE_12: {
10613                 struct scsi_rw_12 *cdb;
10614
10615                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10616
10617                 *lba = scsi_4btoul(cdb->addr);
10618                 *len = scsi_4btoul(cdb->length);
10619                 break;
10620         }
10621         case WRITE_VERIFY_12: {
10622                 struct scsi_write_verify_12 *cdb;
10623
10624                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10625
10626                 *lba = scsi_4btoul(cdb->addr);
10627                 *len = scsi_4btoul(cdb->length);
10628                 break;
10629         }
10630         case READ_16:
10631         case WRITE_16:
10632         case WRITE_ATOMIC_16: {
10633                 struct scsi_rw_16 *cdb;
10634
10635                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10636
10637                 *lba = scsi_8btou64(cdb->addr);
10638                 *len = scsi_4btoul(cdb->length);
10639                 break;
10640         }
10641         case WRITE_VERIFY_16: {
10642                 struct scsi_write_verify_16 *cdb;
10643
10644                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10645
10646                 *lba = scsi_8btou64(cdb->addr);
10647                 *len = scsi_4btoul(cdb->length);
10648                 break;
10649         }
10650         case WRITE_SAME_10: {
10651                 struct scsi_write_same_10 *cdb;
10652
10653                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10654
10655                 *lba = scsi_4btoul(cdb->addr);
10656                 *len = scsi_2btoul(cdb->length);
10657                 break;
10658         }
10659         case WRITE_SAME_16: {
10660                 struct scsi_write_same_16 *cdb;
10661
10662                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10663
10664                 *lba = scsi_8btou64(cdb->addr);
10665                 *len = scsi_4btoul(cdb->length);
10666                 break;
10667         }
10668         case VERIFY_10: {
10669                 struct scsi_verify_10 *cdb;
10670
10671                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10672
10673                 *lba = scsi_4btoul(cdb->addr);
10674                 *len = scsi_2btoul(cdb->length);
10675                 break;
10676         }
10677         case VERIFY_12: {
10678                 struct scsi_verify_12 *cdb;
10679
10680                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10681
10682                 *lba = scsi_4btoul(cdb->addr);
10683                 *len = scsi_4btoul(cdb->length);
10684                 break;
10685         }
10686         case VERIFY_16: {
10687                 struct scsi_verify_16 *cdb;
10688
10689                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10690
10691                 *lba = scsi_8btou64(cdb->addr);
10692                 *len = scsi_4btoul(cdb->length);
10693                 break;
10694         }
10695         case UNMAP: {
10696                 *lba = 0;
10697                 *len = UINT64_MAX;
10698                 break;
10699         }
10700         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10701                 struct scsi_get_lba_status *cdb;
10702
10703                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10704                 *lba = scsi_8btou64(cdb->addr);
10705                 *len = UINT32_MAX;
10706                 break;
10707         }
10708         default:
10709                 return (1);
10710                 break; /* NOTREACHED */
10711         }
10712
10713         return (0);
10714 }
10715
10716 static ctl_action
10717 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10718     bool seq)
10719 {
10720         uint64_t endlba1, endlba2;
10721
10722         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10723         endlba2 = lba2 + len2 - 1;
10724
10725         if ((endlba1 < lba2) || (endlba2 < lba1))
10726                 return (CTL_ACTION_PASS);
10727         else
10728                 return (CTL_ACTION_BLOCK);
10729 }
10730
10731 static int
10732 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10733 {
10734         struct ctl_ptr_len_flags *ptrlen;
10735         struct scsi_unmap_desc *buf, *end, *range;
10736         uint64_t lba;
10737         uint32_t len;
10738
10739         /* If not UNMAP -- go other way. */
10740         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10741             io->scsiio.cdb[0] != UNMAP)
10742                 return (CTL_ACTION_ERROR);
10743
10744         /* If UNMAP without data -- block and wait for data. */
10745         ptrlen = (struct ctl_ptr_len_flags *)
10746             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10747         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10748             ptrlen->ptr == NULL)
10749                 return (CTL_ACTION_BLOCK);
10750
10751         /* UNMAP with data -- check for collision. */
10752         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10753         end = buf + ptrlen->len / sizeof(*buf);
10754         for (range = buf; range < end; range++) {
10755                 lba = scsi_8btou64(range->lba);
10756                 len = scsi_4btoul(range->length);
10757                 if ((lba < lba2 + len2) && (lba + len > lba2))
10758                         return (CTL_ACTION_BLOCK);
10759         }
10760         return (CTL_ACTION_PASS);
10761 }
10762
10763 static ctl_action
10764 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10765 {
10766         uint64_t lba1, lba2;
10767         uint64_t len1, len2;
10768         int retval;
10769
10770         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10771                 return (CTL_ACTION_ERROR);
10772
10773         retval = ctl_extent_check_unmap(io1, lba2, len2);
10774         if (retval != CTL_ACTION_ERROR)
10775                 return (retval);
10776
10777         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10778                 return (CTL_ACTION_ERROR);
10779
10780         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10781                 seq = FALSE;
10782         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10783 }
10784
10785 static ctl_action
10786 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10787 {
10788         uint64_t lba1, lba2;
10789         uint64_t len1, len2;
10790
10791         if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10792                 return (CTL_ACTION_PASS);
10793         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10794                 return (CTL_ACTION_ERROR);
10795         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10796                 return (CTL_ACTION_ERROR);
10797
10798         if (lba1 + len1 == lba2)
10799                 return (CTL_ACTION_BLOCK);
10800         return (CTL_ACTION_PASS);
10801 }
10802
10803 static ctl_action
10804 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10805     union ctl_io *ooa_io)
10806 {
10807         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10808         ctl_serialize_action *serialize_row;
10809
10810         /*
10811          * The initiator attempted multiple untagged commands at the same
10812          * time.  Can't do that.
10813          */
10814         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10815          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10816          && ((pending_io->io_hdr.nexus.targ_port ==
10817               ooa_io->io_hdr.nexus.targ_port)
10818           && (pending_io->io_hdr.nexus.initid ==
10819               ooa_io->io_hdr.nexus.initid))
10820          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10821               CTL_FLAG_STATUS_SENT)) == 0))
10822                 return (CTL_ACTION_OVERLAP);
10823
10824         /*
10825          * The initiator attempted to send multiple tagged commands with
10826          * the same ID.  (It's fine if different initiators have the same
10827          * tag ID.)
10828          *
10829          * Even if all of those conditions are true, we don't kill the I/O
10830          * if the command ahead of us has been aborted.  We won't end up
10831          * sending it to the FETD, and it's perfectly legal to resend a
10832          * command with the same tag number as long as the previous
10833          * instance of this tag number has been aborted somehow.
10834          */
10835         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10836          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10837          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10838          && ((pending_io->io_hdr.nexus.targ_port ==
10839               ooa_io->io_hdr.nexus.targ_port)
10840           && (pending_io->io_hdr.nexus.initid ==
10841               ooa_io->io_hdr.nexus.initid))
10842          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10843               CTL_FLAG_STATUS_SENT)) == 0))
10844                 return (CTL_ACTION_OVERLAP_TAG);
10845
10846         /*
10847          * If we get a head of queue tag, SAM-3 says that we should
10848          * immediately execute it.
10849          *
10850          * What happens if this command would normally block for some other
10851          * reason?  e.g. a request sense with a head of queue tag
10852          * immediately after a write.  Normally that would block, but this
10853          * will result in its getting executed immediately...
10854          *
10855          * We currently return "pass" instead of "skip", so we'll end up
10856          * going through the rest of the queue to check for overlapped tags.
10857          *
10858          * XXX KDM check for other types of blockage first??
10859          */
10860         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10861                 return (CTL_ACTION_PASS);
10862
10863         /*
10864          * Ordered tags have to block until all items ahead of them
10865          * have completed.  If we get called with an ordered tag, we always
10866          * block, if something else is ahead of us in the queue.
10867          */
10868         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10869                 return (CTL_ACTION_BLOCK);
10870
10871         /*
10872          * Simple tags get blocked until all head of queue and ordered tags
10873          * ahead of them have completed.  I'm lumping untagged commands in
10874          * with simple tags here.  XXX KDM is that the right thing to do?
10875          */
10876         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10877           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10878          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10879           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10880                 return (CTL_ACTION_BLOCK);
10881
10882         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10883         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10884
10885         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10886
10887         switch (serialize_row[pending_entry->seridx]) {
10888         case CTL_SER_BLOCK:
10889                 return (CTL_ACTION_BLOCK);
10890         case CTL_SER_EXTENT:
10891                 return (ctl_extent_check(ooa_io, pending_io,
10892                     (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10893         case CTL_SER_EXTENTOPT:
10894                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10895                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10896                         return (ctl_extent_check(ooa_io, pending_io,
10897                             (lun->be_lun &&
10898                              lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10899                 return (CTL_ACTION_PASS);
10900         case CTL_SER_EXTENTSEQ:
10901                 if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10902                         return (ctl_extent_check_seq(ooa_io, pending_io));
10903                 return (CTL_ACTION_PASS);
10904         case CTL_SER_PASS:
10905                 return (CTL_ACTION_PASS);
10906         case CTL_SER_BLOCKOPT:
10907                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10908                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10909                         return (CTL_ACTION_BLOCK);
10910                 return (CTL_ACTION_PASS);
10911         case CTL_SER_SKIP:
10912                 return (CTL_ACTION_SKIP);
10913         default:
10914                 panic("invalid serialization value %d",
10915                       serialize_row[pending_entry->seridx]);
10916         }
10917
10918         return (CTL_ACTION_ERROR);
10919 }
10920
10921 /*
10922  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10923  * Assumptions:
10924  * - pending_io is generally either incoming, or on the blocked queue
10925  * - starting I/O is the I/O we want to start the check with.
10926  */
10927 static ctl_action
10928 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10929               union ctl_io *starting_io)
10930 {
10931         union ctl_io *ooa_io;
10932         ctl_action action;
10933
10934         mtx_assert(&lun->lun_lock, MA_OWNED);
10935
10936         /*
10937          * Run back along the OOA queue, starting with the current
10938          * blocked I/O and going through every I/O before it on the
10939          * queue.  If starting_io is NULL, we'll just end up returning
10940          * CTL_ACTION_PASS.
10941          */
10942         for (ooa_io = starting_io; ooa_io != NULL;
10943              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10944              ooa_links)){
10945
10946                 /*
10947                  * This routine just checks to see whether
10948                  * cur_blocked is blocked by ooa_io, which is ahead
10949                  * of it in the queue.  It doesn't queue/dequeue
10950                  * cur_blocked.
10951                  */
10952                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10953                 switch (action) {
10954                 case CTL_ACTION_BLOCK:
10955                 case CTL_ACTION_OVERLAP:
10956                 case CTL_ACTION_OVERLAP_TAG:
10957                 case CTL_ACTION_SKIP:
10958                 case CTL_ACTION_ERROR:
10959                         return (action);
10960                         break; /* NOTREACHED */
10961                 case CTL_ACTION_PASS:
10962                         break;
10963                 default:
10964                         panic("invalid action %d", action);
10965                         break;  /* NOTREACHED */
10966                 }
10967         }
10968
10969         return (CTL_ACTION_PASS);
10970 }
10971
10972 /*
10973  * Assumptions:
10974  * - An I/O has just completed, and has been removed from the per-LUN OOA
10975  *   queue, so some items on the blocked queue may now be unblocked.
10976  */
10977 static int
10978 ctl_check_blocked(struct ctl_lun *lun)
10979 {
10980         struct ctl_softc *softc = lun->ctl_softc;
10981         union ctl_io *cur_blocked, *next_blocked;
10982
10983         mtx_assert(&lun->lun_lock, MA_OWNED);
10984
10985         /*
10986          * Run forward from the head of the blocked queue, checking each
10987          * entry against the I/Os prior to it on the OOA queue to see if
10988          * there is still any blockage.
10989          *
10990          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10991          * with our removing a variable on it while it is traversing the
10992          * list.
10993          */
10994         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10995              cur_blocked != NULL; cur_blocked = next_blocked) {
10996                 union ctl_io *prev_ooa;
10997                 ctl_action action;
10998
10999                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11000                                                           blocked_links);
11001
11002                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11003                                                       ctl_ooaq, ooa_links);
11004
11005                 /*
11006                  * If cur_blocked happens to be the first item in the OOA
11007                  * queue now, prev_ooa will be NULL, and the action
11008                  * returned will just be CTL_ACTION_PASS.
11009                  */
11010                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11011
11012                 switch (action) {
11013                 case CTL_ACTION_BLOCK:
11014                         /* Nothing to do here, still blocked */
11015                         break;
11016                 case CTL_ACTION_OVERLAP:
11017                 case CTL_ACTION_OVERLAP_TAG:
11018                         /*
11019                          * This shouldn't happen!  In theory we've already
11020                          * checked this command for overlap...
11021                          */
11022                         break;
11023                 case CTL_ACTION_PASS:
11024                 case CTL_ACTION_SKIP: {
11025                         const struct ctl_cmd_entry *entry;
11026
11027                         /*
11028                          * The skip case shouldn't happen, this transaction
11029                          * should have never made it onto the blocked queue.
11030                          */
11031                         /*
11032                          * This I/O is no longer blocked, we can remove it
11033                          * from the blocked queue.  Since this is a TAILQ
11034                          * (doubly linked list), we can do O(1) removals
11035                          * from any place on the list.
11036                          */
11037                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11038                                      blocked_links);
11039                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11040
11041                         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11042                             (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11043                                 /*
11044                                  * Need to send IO back to original side to
11045                                  * run
11046                                  */
11047                                 union ctl_ha_msg msg_info;
11048
11049                                 cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11050                                 msg_info.hdr.original_sc =
11051                                         cur_blocked->io_hdr.original_sc;
11052                                 msg_info.hdr.serializing_sc = cur_blocked;
11053                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11054                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11055                                     sizeof(msg_info.hdr), M_NOWAIT);
11056                                 break;
11057                         }
11058                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11059
11060                         /*
11061                          * Check this I/O for LUN state changes that may
11062                          * have happened while this command was blocked.
11063                          * The LUN state may have been changed by a command
11064                          * ahead of us in the queue, so we need to re-check
11065                          * for any states that can be caused by SCSI
11066                          * commands.
11067                          */
11068                         if (ctl_scsiio_lun_check(lun, entry,
11069                                                  &cur_blocked->scsiio) == 0) {
11070                                 cur_blocked->io_hdr.flags |=
11071                                                       CTL_FLAG_IS_WAS_ON_RTR;
11072                                 ctl_enqueue_rtr(cur_blocked);
11073                         } else
11074                                 ctl_done(cur_blocked);
11075                         break;
11076                 }
11077                 default:
11078                         /*
11079                          * This probably shouldn't happen -- we shouldn't
11080                          * get CTL_ACTION_ERROR, or anything else.
11081                          */
11082                         break;
11083                 }
11084         }
11085
11086         return (CTL_RETVAL_COMPLETE);
11087 }
11088
11089 /*
11090  * This routine (with one exception) checks LUN flags that can be set by
11091  * commands ahead of us in the OOA queue.  These flags have to be checked
11092  * when a command initially comes in, and when we pull a command off the
11093  * blocked queue and are preparing to execute it.  The reason we have to
11094  * check these flags for commands on the blocked queue is that the LUN
11095  * state may have been changed by a command ahead of us while we're on the
11096  * blocked queue.
11097  *
11098  * Ordering is somewhat important with these checks, so please pay
11099  * careful attention to the placement of any new checks.
11100  */
11101 static int
11102 ctl_scsiio_lun_check(struct ctl_lun *lun,
11103     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11104 {
11105         struct ctl_softc *softc = lun->ctl_softc;
11106         int retval;
11107         uint32_t residx;
11108
11109         retval = 0;
11110
11111         mtx_assert(&lun->lun_lock, MA_OWNED);
11112
11113         /*
11114          * If this shelf is a secondary shelf controller, we may have to
11115          * reject some commands disallowed by HA mode and link state.
11116          */
11117         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11118                 if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11119                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11120                         ctl_set_lun_unavail(ctsio);
11121                         retval = 1;
11122                         goto bailout;
11123                 }
11124                 if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11125                     (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11126                         ctl_set_lun_transit(ctsio);
11127                         retval = 1;
11128                         goto bailout;
11129                 }
11130                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11131                     (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11132                         ctl_set_lun_standby(ctsio);
11133                         retval = 1;
11134                         goto bailout;
11135                 }
11136
11137                 /* The rest of checks are only done on executing side */
11138                 if (softc->ha_mode == CTL_HA_MODE_XFER)
11139                         goto bailout;
11140         }
11141
11142         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11143                 if (lun->be_lun &&
11144                     lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11145                         ctl_set_hw_write_protected(ctsio);
11146                         retval = 1;
11147                         goto bailout;
11148                 }
11149                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11150                     .eca_and_aen & SCP_SWP) != 0) {
11151                         ctl_set_sense(ctsio, /*current_error*/ 1,
11152                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11153                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11154                         retval = 1;
11155                         goto bailout;
11156                 }
11157         }
11158
11159         /*
11160          * Check for a reservation conflict.  If this command isn't allowed
11161          * even on reserved LUNs, and if this initiator isn't the one who
11162          * reserved us, reject the command with a reservation conflict.
11163          */
11164         residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11165         if ((lun->flags & CTL_LUN_RESERVED)
11166          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11167                 if (lun->res_idx != residx) {
11168                         ctl_set_reservation_conflict(ctsio);
11169                         retval = 1;
11170                         goto bailout;
11171                 }
11172         }
11173
11174         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11175             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11176                 /* No reservation or command is allowed. */;
11177         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11178             (lun->res_type == SPR_TYPE_WR_EX ||
11179              lun->res_type == SPR_TYPE_WR_EX_RO ||
11180              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11181                 /* The command is allowed for Write Exclusive resv. */;
11182         } else {
11183                 /*
11184                  * if we aren't registered or it's a res holder type
11185                  * reservation and this isn't the res holder then set a
11186                  * conflict.
11187                  */
11188                 if (ctl_get_prkey(lun, residx) == 0
11189                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11190                         ctl_set_reservation_conflict(ctsio);
11191                         retval = 1;
11192                         goto bailout;
11193                 }
11194         }
11195
11196         if ((lun->flags & CTL_LUN_OFFLINE)
11197          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
11198                 ctl_set_lun_not_ready(ctsio);
11199                 retval = 1;
11200                 goto bailout;
11201         }
11202
11203         if ((lun->flags & CTL_LUN_STOPPED)
11204          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11205                 /* "Logical unit not ready, initializing cmd. required" */
11206                 ctl_set_lun_stopped(ctsio);
11207                 retval = 1;
11208                 goto bailout;
11209         }
11210
11211         if ((lun->flags & CTL_LUN_INOPERABLE)
11212          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11213                 /* "Medium format corrupted" */
11214                 ctl_set_medium_format_corrupted(ctsio);
11215                 retval = 1;
11216                 goto bailout;
11217         }
11218
11219 bailout:
11220         return (retval);
11221 }
11222
11223 static void
11224 ctl_failover_io(union ctl_io *io, int have_lock)
11225 {
11226         ctl_set_busy(&io->scsiio);
11227         ctl_done(io);
11228 }
11229
11230 static void
11231 ctl_failover_lun(struct ctl_lun *lun)
11232 {
11233         struct ctl_softc *softc = lun->ctl_softc;
11234         struct ctl_io_hdr *io, *next_io;
11235
11236         CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
11237         if (softc->ha_mode == CTL_HA_MODE_XFER) {
11238                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11239                         /* We are master */
11240                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11241                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11242                                         io->flags |= CTL_FLAG_ABORT;
11243                                         io->flags |= CTL_FLAG_FAILOVER;
11244                                 } else { /* This can be only due to DATAMOVE */
11245                                         io->msg_type = CTL_MSG_DATAMOVE_DONE;
11246                                         io->flags &= ~CTL_FLAG_DMA_INPROG;
11247                                         io->flags |= CTL_FLAG_IO_ACTIVE;
11248                                         io->port_status = 31340;
11249                                         ctl_enqueue_isc((union ctl_io *)io);
11250                                 }
11251                         }
11252                         /* We are slave */
11253                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11254                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11255                                 if (io->flags & CTL_FLAG_IO_ACTIVE) {
11256                                         io->flags |= CTL_FLAG_FAILOVER;
11257                                 } else {
11258                                         ctl_set_busy(&((union ctl_io *)io)->
11259                                             scsiio);
11260                                         ctl_done((union ctl_io *)io);
11261                                 }
11262                         }
11263                 }
11264         } else { /* SERIALIZE modes */
11265                 TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11266                     next_io) {
11267                         /* We are master */
11268                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11269                                 TAILQ_REMOVE(&lun->blocked_queue, io,
11270                                     blocked_links);
11271                                 io->flags &= ~CTL_FLAG_BLOCKED;
11272                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11273                                 ctl_free_io((union ctl_io *)io);
11274                         }
11275                 }
11276                 TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11277                         /* We are master */
11278                         if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11279                                 TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11280                                 ctl_free_io((union ctl_io *)io);
11281                         }
11282                         /* We are slave */
11283                         if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11284                                 io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11285                                 if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11286                                         ctl_set_busy(&((union ctl_io *)io)->
11287                                             scsiio);
11288                                         ctl_done((union ctl_io *)io);
11289                                 }
11290                         }
11291                 }
11292                 ctl_check_blocked(lun);
11293         }
11294 }
11295
11296 static int
11297 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11298 {
11299         struct ctl_lun *lun;
11300         const struct ctl_cmd_entry *entry;
11301         uint32_t initidx, targ_lun;
11302         int retval;
11303
11304         retval = 0;
11305
11306         lun = NULL;
11307
11308         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11309         if ((targ_lun < CTL_MAX_LUNS)
11310          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11311                 /*
11312                  * If the LUN is invalid, pretend that it doesn't exist.
11313                  * It will go away as soon as all pending I/O has been
11314                  * completed.
11315                  */
11316                 mtx_lock(&lun->lun_lock);
11317                 if (lun->flags & CTL_LUN_DISABLED) {
11318                         mtx_unlock(&lun->lun_lock);
11319                         lun = NULL;
11320                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11321                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11322                 } else {
11323                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11324                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11325                                 lun->be_lun;
11326
11327                         /*
11328                          * Every I/O goes into the OOA queue for a
11329                          * particular LUN, and stays there until completion.
11330                          */
11331 #ifdef CTL_TIME_IO
11332                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11333                                 lun->idle_time += getsbinuptime() -
11334                                     lun->last_busy;
11335                         }
11336 #endif
11337                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11338                             ooa_links);
11339                 }
11340         } else {
11341                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11342                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11343         }
11344
11345         /* Get command entry and return error if it is unsuppotyed. */
11346         entry = ctl_validate_command(ctsio);
11347         if (entry == NULL) {
11348                 if (lun)
11349                         mtx_unlock(&lun->lun_lock);
11350                 return (retval);
11351         }
11352
11353         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11354         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11355
11356         /*
11357          * Check to see whether we can send this command to LUNs that don't
11358          * exist.  This should pretty much only be the case for inquiry
11359          * and request sense.  Further checks, below, really require having
11360          * a LUN, so we can't really check the command anymore.  Just put
11361          * it on the rtr queue.
11362          */
11363         if (lun == NULL) {
11364                 if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11365                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11366                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11367                         return (retval);
11368                 }
11369
11370                 ctl_set_unsupported_lun(ctsio);
11371                 ctl_done((union ctl_io *)ctsio);
11372                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11373                 return (retval);
11374         } else {
11375                 /*
11376                  * Make sure we support this particular command on this LUN.
11377                  * e.g., we don't support writes to the control LUN.
11378                  */
11379                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11380                         mtx_unlock(&lun->lun_lock);
11381                         ctl_set_invalid_opcode(ctsio);
11382                         ctl_done((union ctl_io *)ctsio);
11383                         return (retval);
11384                 }
11385         }
11386
11387         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11388
11389 #ifdef CTL_WITH_CA
11390         /*
11391          * If we've got a request sense, it'll clear the contingent
11392          * allegiance condition.  Otherwise, if we have a CA condition for
11393          * this initiator, clear it, because it sent down a command other
11394          * than request sense.
11395          */
11396         if ((ctsio->cdb[0] != REQUEST_SENSE)
11397          && (ctl_is_set(lun->have_ca, initidx)))
11398                 ctl_clear_mask(lun->have_ca, initidx);
11399 #endif
11400
11401         /*
11402          * If the command has this flag set, it handles its own unit
11403          * attention reporting, we shouldn't do anything.  Otherwise we
11404          * check for any pending unit attentions, and send them back to the
11405          * initiator.  We only do this when a command initially comes in,
11406          * not when we pull it off the blocked queue.
11407          *
11408          * According to SAM-3, section 5.3.2, the order that things get
11409          * presented back to the host is basically unit attentions caused
11410          * by some sort of reset event, busy status, reservation conflicts
11411          * or task set full, and finally any other status.
11412          *
11413          * One issue here is that some of the unit attentions we report
11414          * don't fall into the "reset" category (e.g. "reported luns data
11415          * has changed").  So reporting it here, before the reservation
11416          * check, may be technically wrong.  I guess the only thing to do
11417          * would be to check for and report the reset events here, and then
11418          * check for the other unit attention types after we check for a
11419          * reservation conflict.
11420          *
11421          * XXX KDM need to fix this
11422          */
11423         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11424                 ctl_ua_type ua_type;
11425
11426                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11427                     SSD_TYPE_NONE);
11428                 if (ua_type != CTL_UA_NONE) {
11429                         mtx_unlock(&lun->lun_lock);
11430                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11431                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11432                         ctsio->sense_len = SSD_FULL_SIZE;
11433                         ctl_done((union ctl_io *)ctsio);
11434                         return (retval);
11435                 }
11436         }
11437
11438
11439         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11440                 mtx_unlock(&lun->lun_lock);
11441                 ctl_done((union ctl_io *)ctsio);
11442                 return (retval);
11443         }
11444
11445         /*
11446          * XXX CHD this is where we want to send IO to other side if
11447          * this LUN is secondary on this SC. We will need to make a copy
11448          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11449          * the copy we send as FROM_OTHER.
11450          * We also need to stuff the address of the original IO so we can
11451          * find it easily. Something similar will need be done on the other
11452          * side so when we are done we can find the copy.
11453          */
11454         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11455             (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11456             (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11457                 union ctl_ha_msg msg_info;
11458                 int isc_retval;
11459
11460                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11461                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11462                 mtx_unlock(&lun->lun_lock);
11463
11464                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11465                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11466                 msg_info.hdr.serializing_sc = NULL;
11467                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11468                 msg_info.scsi.tag_num = ctsio->tag_num;
11469                 msg_info.scsi.tag_type = ctsio->tag_type;
11470                 msg_info.scsi.cdb_len = ctsio->cdb_len;
11471                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11472
11473                 if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11474                     sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11475                     M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11476                         ctl_set_busy(ctsio);
11477                         ctl_done((union ctl_io *)ctsio);
11478                         return (retval);
11479                 }
11480                 return (retval);
11481         }
11482
11483         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11484                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11485                               ctl_ooaq, ooa_links))) {
11486         case CTL_ACTION_BLOCK:
11487                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11488                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11489                                   blocked_links);
11490                 mtx_unlock(&lun->lun_lock);
11491                 return (retval);
11492         case CTL_ACTION_PASS:
11493         case CTL_ACTION_SKIP:
11494                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11495                 mtx_unlock(&lun->lun_lock);
11496                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11497                 break;
11498         case CTL_ACTION_OVERLAP:
11499                 mtx_unlock(&lun->lun_lock);
11500                 ctl_set_overlapped_cmd(ctsio);
11501                 ctl_done((union ctl_io *)ctsio);
11502                 break;
11503         case CTL_ACTION_OVERLAP_TAG:
11504                 mtx_unlock(&lun->lun_lock);
11505                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11506                 ctl_done((union ctl_io *)ctsio);
11507                 break;
11508         case CTL_ACTION_ERROR:
11509         default:
11510                 mtx_unlock(&lun->lun_lock);
11511                 ctl_set_internal_failure(ctsio,
11512                                          /*sks_valid*/ 0,
11513                                          /*retry_count*/ 0);
11514                 ctl_done((union ctl_io *)ctsio);
11515                 break;
11516         }
11517         return (retval);
11518 }
11519
11520 const struct ctl_cmd_entry *
11521 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11522 {
11523         const struct ctl_cmd_entry *entry;
11524         int service_action;
11525
11526         entry = &ctl_cmd_table[ctsio->cdb[0]];
11527         if (sa)
11528                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11529         if (entry->flags & CTL_CMD_FLAG_SA5) {
11530                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11531                 entry = &((const struct ctl_cmd_entry *)
11532                     entry->execute)[service_action];
11533         }
11534         return (entry);
11535 }
11536
11537 const struct ctl_cmd_entry *
11538 ctl_validate_command(struct ctl_scsiio *ctsio)
11539 {
11540         const struct ctl_cmd_entry *entry;
11541         int i, sa;
11542         uint8_t diff;
11543
11544         entry = ctl_get_cmd_entry(ctsio, &sa);
11545         if (entry->execute == NULL) {
11546                 if (sa)
11547                         ctl_set_invalid_field(ctsio,
11548                                               /*sks_valid*/ 1,
11549                                               /*command*/ 1,
11550                                               /*field*/ 1,
11551                                               /*bit_valid*/ 1,
11552                                               /*bit*/ 4);
11553                 else
11554                         ctl_set_invalid_opcode(ctsio);
11555                 ctl_done((union ctl_io *)ctsio);
11556                 return (NULL);
11557         }
11558         KASSERT(entry->length > 0,
11559             ("Not defined length for command 0x%02x/0x%02x",
11560              ctsio->cdb[0], ctsio->cdb[1]));
11561         for (i = 1; i < entry->length; i++) {
11562                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11563                 if (diff == 0)
11564                         continue;
11565                 ctl_set_invalid_field(ctsio,
11566                                       /*sks_valid*/ 1,
11567                                       /*command*/ 1,
11568                                       /*field*/ i,
11569                                       /*bit_valid*/ 1,
11570                                       /*bit*/ fls(diff) - 1);
11571                 ctl_done((union ctl_io *)ctsio);
11572                 return (NULL);
11573         }
11574         return (entry);
11575 }
11576
11577 static int
11578 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11579 {
11580
11581         switch (lun_type) {
11582         case T_PROCESSOR:
11583                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11584                         return (0);
11585                 break;
11586         case T_DIRECT:
11587                 if ((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
11588                         return (0);
11589                 break;
11590         default:
11591                 return (0);
11592         }
11593         return (1);
11594 }
11595
11596 static int
11597 ctl_scsiio(struct ctl_scsiio *ctsio)
11598 {
11599         int retval;
11600         const struct ctl_cmd_entry *entry;
11601
11602         retval = CTL_RETVAL_COMPLETE;
11603
11604         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11605
11606         entry = ctl_get_cmd_entry(ctsio, NULL);
11607
11608         /*
11609          * If this I/O has been aborted, just send it straight to
11610          * ctl_done() without executing it.
11611          */
11612         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11613                 ctl_done((union ctl_io *)ctsio);
11614                 goto bailout;
11615         }
11616
11617         /*
11618          * All the checks should have been handled by ctl_scsiio_precheck().
11619          * We should be clear now to just execute the I/O.
11620          */
11621         retval = entry->execute(ctsio);
11622
11623 bailout:
11624         return (retval);
11625 }
11626
11627 /*
11628  * Since we only implement one target right now, a bus reset simply resets
11629  * our single target.
11630  */
11631 static int
11632 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11633 {
11634         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11635 }
11636
11637 static int
11638 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11639                  ctl_ua_type ua_type)
11640 {
11641         struct ctl_port *port;
11642         struct ctl_lun *lun;
11643         int retval;
11644
11645         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11646                 union ctl_ha_msg msg_info;
11647
11648                 msg_info.hdr.nexus = io->io_hdr.nexus;
11649                 if (ua_type==CTL_UA_TARG_RESET)
11650                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11651                 else
11652                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11653                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11654                 msg_info.hdr.original_sc = NULL;
11655                 msg_info.hdr.serializing_sc = NULL;
11656                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11657                     sizeof(msg_info.task), M_WAITOK);
11658         }
11659         retval = 0;
11660
11661         mtx_lock(&softc->ctl_lock);
11662         port = softc->ctl_ports[io->io_hdr.nexus.targ_port];
11663         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11664                 if (port != NULL &&
11665                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11666                         continue;
11667                 retval += ctl_do_lun_reset(lun, io, ua_type);
11668         }
11669         mtx_unlock(&softc->ctl_lock);
11670         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11671         return (retval);
11672 }
11673
11674 /*
11675  * The LUN should always be set.  The I/O is optional, and is used to
11676  * distinguish between I/Os sent by this initiator, and by other
11677  * initiators.  We set unit attention for initiators other than this one.
11678  * SAM-3 is vague on this point.  It does say that a unit attention should
11679  * be established for other initiators when a LUN is reset (see section
11680  * 5.7.3), but it doesn't specifically say that the unit attention should
11681  * be established for this particular initiator when a LUN is reset.  Here
11682  * is the relevant text, from SAM-3 rev 8:
11683  *
11684  * 5.7.2 When a SCSI initiator port aborts its own tasks
11685  *
11686  * When a SCSI initiator port causes its own task(s) to be aborted, no
11687  * notification that the task(s) have been aborted shall be returned to
11688  * the SCSI initiator port other than the completion response for the
11689  * command or task management function action that caused the task(s) to
11690  * be aborted and notification(s) associated with related effects of the
11691  * action (e.g., a reset unit attention condition).
11692  *
11693  * XXX KDM for now, we're setting unit attention for all initiators.
11694  */
11695 static int
11696 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11697 {
11698         union ctl_io *xio;
11699 #if 0
11700         uint32_t initidx;
11701 #endif
11702 #ifdef CTL_WITH_CA
11703         int i;
11704 #endif
11705
11706         mtx_lock(&lun->lun_lock);
11707         /*
11708          * Run through the OOA queue and abort each I/O.
11709          */
11710         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11711              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11712                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11713         }
11714
11715         /*
11716          * This version sets unit attention for every
11717          */
11718 #if 0
11719         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11720         ctl_est_ua_all(lun, initidx, ua_type);
11721 #else
11722         ctl_est_ua_all(lun, -1, ua_type);
11723 #endif
11724
11725         /*
11726          * A reset (any kind, really) clears reservations established with
11727          * RESERVE/RELEASE.  It does not clear reservations established
11728          * with PERSISTENT RESERVE OUT, but we don't support that at the
11729          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11730          * reservations made with the RESERVE/RELEASE commands, because
11731          * those commands are obsolete in SPC-3.
11732          */
11733         lun->flags &= ~CTL_LUN_RESERVED;
11734
11735 #ifdef CTL_WITH_CA
11736         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11737                 ctl_clear_mask(lun->have_ca, i);
11738 #endif
11739         mtx_unlock(&lun->lun_lock);
11740
11741         return (0);
11742 }
11743
11744 static int
11745 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11746 {
11747         struct ctl_lun *lun;
11748         uint32_t targ_lun;
11749         int retval;
11750
11751         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11752         mtx_lock(&softc->ctl_lock);
11753         if ((targ_lun >= CTL_MAX_LUNS) ||
11754             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11755                 mtx_unlock(&softc->ctl_lock);
11756                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11757                 return (1);
11758         }
11759         retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11760         mtx_unlock(&softc->ctl_lock);
11761         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11762
11763         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11764                 union ctl_ha_msg msg_info;
11765
11766                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11767                 msg_info.hdr.nexus = io->io_hdr.nexus;
11768                 msg_info.task.task_action = CTL_TASK_LUN_RESET;
11769                 msg_info.hdr.original_sc = NULL;
11770                 msg_info.hdr.serializing_sc = NULL;
11771                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11772                     sizeof(msg_info.task), M_WAITOK);
11773         }
11774         return (retval);
11775 }
11776
11777 static void
11778 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11779     int other_sc)
11780 {
11781         union ctl_io *xio;
11782
11783         mtx_assert(&lun->lun_lock, MA_OWNED);
11784
11785         /*
11786          * Run through the OOA queue and attempt to find the given I/O.
11787          * The target port, initiator ID, tag type and tag number have to
11788          * match the values that we got from the initiator.  If we have an
11789          * untagged command to abort, simply abort the first untagged command
11790          * we come to.  We only allow one untagged command at a time of course.
11791          */
11792         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11793              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11794
11795                 if ((targ_port == UINT32_MAX ||
11796                      targ_port == xio->io_hdr.nexus.targ_port) &&
11797                     (init_id == UINT32_MAX ||
11798                      init_id == xio->io_hdr.nexus.initid)) {
11799                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11800                             init_id != xio->io_hdr.nexus.initid)
11801                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11802                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11803                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11804                                 union ctl_ha_msg msg_info;
11805
11806                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11807                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11808                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11809                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11810                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11811                                 msg_info.hdr.original_sc = NULL;
11812                                 msg_info.hdr.serializing_sc = NULL;
11813                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11814                                     sizeof(msg_info.task), M_NOWAIT);
11815                         }
11816                 }
11817         }
11818 }
11819
11820 static int
11821 ctl_abort_task_set(union ctl_io *io)
11822 {
11823         struct ctl_softc *softc = control_softc;
11824         struct ctl_lun *lun;
11825         uint32_t targ_lun;
11826
11827         /*
11828          * Look up the LUN.
11829          */
11830         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11831         mtx_lock(&softc->ctl_lock);
11832         if ((targ_lun >= CTL_MAX_LUNS) ||
11833             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11834                 mtx_unlock(&softc->ctl_lock);
11835                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11836                 return (1);
11837         }
11838
11839         mtx_lock(&lun->lun_lock);
11840         mtx_unlock(&softc->ctl_lock);
11841         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11842                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11843                     io->io_hdr.nexus.initid,
11844                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11845         } else { /* CTL_TASK_CLEAR_TASK_SET */
11846                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11847                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11848         }
11849         mtx_unlock(&lun->lun_lock);
11850         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11851         return (0);
11852 }
11853
11854 static int
11855 ctl_i_t_nexus_reset(union ctl_io *io)
11856 {
11857         struct ctl_softc *softc = control_softc;
11858         struct ctl_lun *lun;
11859         uint32_t initidx;
11860
11861         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11862                 union ctl_ha_msg msg_info;
11863
11864                 msg_info.hdr.nexus = io->io_hdr.nexus;
11865                 msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11866                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11867                 msg_info.hdr.original_sc = NULL;
11868                 msg_info.hdr.serializing_sc = NULL;
11869                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11870                     sizeof(msg_info.task), M_WAITOK);
11871         }
11872
11873         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11874         mtx_lock(&softc->ctl_lock);
11875         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11876                 mtx_lock(&lun->lun_lock);
11877                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11878                     io->io_hdr.nexus.initid, 1);
11879 #ifdef CTL_WITH_CA
11880                 ctl_clear_mask(lun->have_ca, initidx);
11881 #endif
11882                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11883                         lun->flags &= ~CTL_LUN_RESERVED;
11884                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11885                 mtx_unlock(&lun->lun_lock);
11886         }
11887         mtx_unlock(&softc->ctl_lock);
11888         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11889         return (0);
11890 }
11891
11892 static int
11893 ctl_abort_task(union ctl_io *io)
11894 {
11895         union ctl_io *xio;
11896         struct ctl_lun *lun;
11897         struct ctl_softc *softc;
11898 #if 0
11899         struct sbuf sb;
11900         char printbuf[128];
11901 #endif
11902         int found;
11903         uint32_t targ_lun;
11904
11905         softc = control_softc;
11906         found = 0;
11907
11908         /*
11909          * Look up the LUN.
11910          */
11911         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11912         mtx_lock(&softc->ctl_lock);
11913         if ((targ_lun >= CTL_MAX_LUNS) ||
11914             (lun = softc->ctl_luns[targ_lun]) == NULL) {
11915                 mtx_unlock(&softc->ctl_lock);
11916                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11917                 return (1);
11918         }
11919
11920 #if 0
11921         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11922                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11923 #endif
11924
11925         mtx_lock(&lun->lun_lock);
11926         mtx_unlock(&softc->ctl_lock);
11927         /*
11928          * Run through the OOA queue and attempt to find the given I/O.
11929          * The target port, initiator ID, tag type and tag number have to
11930          * match the values that we got from the initiator.  If we have an
11931          * untagged command to abort, simply abort the first untagged command
11932          * we come to.  We only allow one untagged command at a time of course.
11933          */
11934         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11935              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11936 #if 0
11937                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11938
11939                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11940                             lun->lun, xio->scsiio.tag_num,
11941                             xio->scsiio.tag_type,
11942                             (xio->io_hdr.blocked_links.tqe_prev
11943                             == NULL) ? "" : " BLOCKED",
11944                             (xio->io_hdr.flags &
11945                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11946                             (xio->io_hdr.flags &
11947                             CTL_FLAG_ABORT) ? " ABORT" : "",
11948                             (xio->io_hdr.flags &
11949                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11950                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11951                 sbuf_finish(&sb);
11952                 printf("%s\n", sbuf_data(&sb));
11953 #endif
11954
11955                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11956                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11957                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11958                         continue;
11959
11960                 /*
11961                  * If the abort says that the task is untagged, the
11962                  * task in the queue must be untagged.  Otherwise,
11963                  * we just check to see whether the tag numbers
11964                  * match.  This is because the QLogic firmware
11965                  * doesn't pass back the tag type in an abort
11966                  * request.
11967                  */
11968 #if 0
11969                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11970                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11971                  || (xio->scsiio.tag_num == io->taskio.tag_num))
11972 #endif
11973                 /*
11974                  * XXX KDM we've got problems with FC, because it
11975                  * doesn't send down a tag type with aborts.  So we
11976                  * can only really go by the tag number...
11977                  * This may cause problems with parallel SCSI.
11978                  * Need to figure that out!!
11979                  */
11980                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
11981                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11982                         found = 1;
11983                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11984                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11985                                 union ctl_ha_msg msg_info;
11986
11987                                 msg_info.hdr.nexus = io->io_hdr.nexus;
11988                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11989                                 msg_info.task.tag_num = io->taskio.tag_num;
11990                                 msg_info.task.tag_type = io->taskio.tag_type;
11991                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11992                                 msg_info.hdr.original_sc = NULL;
11993                                 msg_info.hdr.serializing_sc = NULL;
11994 #if 0
11995                                 printf("Sent Abort to other side\n");
11996 #endif
11997                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11998                                     sizeof(msg_info.task), M_NOWAIT);
11999                         }
12000 #if 0
12001                         printf("ctl_abort_task: found I/O to abort\n");
12002 #endif
12003                 }
12004         }
12005         mtx_unlock(&lun->lun_lock);
12006
12007         if (found == 0) {
12008                 /*
12009                  * This isn't really an error.  It's entirely possible for
12010                  * the abort and command completion to cross on the wire.
12011                  * This is more of an informative/diagnostic error.
12012                  */
12013 #if 0
12014                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12015                        "%u:%u:%u tag %d type %d\n",
12016                        io->io_hdr.nexus.initid,
12017                        io->io_hdr.nexus.targ_port,
12018                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12019                        io->taskio.tag_type);
12020 #endif
12021         }
12022         io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12023         return (0);
12024 }
12025
12026 static int
12027 ctl_query_task(union ctl_io *io, int task_set)
12028 {
12029         union ctl_io *xio;
12030         struct ctl_lun *lun;
12031         struct ctl_softc *softc;
12032         int found = 0;
12033         uint32_t targ_lun;
12034
12035         softc = control_softc;
12036         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12037         mtx_lock(&softc->ctl_lock);
12038         if ((targ_lun >= CTL_MAX_LUNS) ||
12039             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12040                 mtx_unlock(&softc->ctl_lock);
12041                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12042                 return (1);
12043         }
12044         mtx_lock(&lun->lun_lock);
12045         mtx_unlock(&softc->ctl_lock);
12046         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12047              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12048
12049                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12050                  || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12051                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12052                         continue;
12053
12054                 if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12055                         found = 1;
12056                         break;
12057                 }
12058         }
12059         mtx_unlock(&lun->lun_lock);
12060         if (found)
12061                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12062         else
12063                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12064         return (0);
12065 }
12066
12067 static int
12068 ctl_query_async_event(union ctl_io *io)
12069 {
12070         struct ctl_lun *lun;
12071         struct ctl_softc *softc;
12072         ctl_ua_type ua;
12073         uint32_t targ_lun, initidx;
12074
12075         softc = control_softc;
12076         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12077         mtx_lock(&softc->ctl_lock);
12078         if ((targ_lun >= CTL_MAX_LUNS) ||
12079             (lun = softc->ctl_luns[targ_lun]) == NULL) {
12080                 mtx_unlock(&softc->ctl_lock);
12081                 io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12082                 return (1);
12083         }
12084         mtx_lock(&lun->lun_lock);
12085         mtx_unlock(&softc->ctl_lock);
12086         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12087         ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12088         mtx_unlock(&lun->lun_lock);
12089         if (ua != CTL_UA_NONE)
12090                 io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12091         else
12092                 io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12093         return (0);
12094 }
12095
12096 static void
12097 ctl_run_task(union ctl_io *io)
12098 {
12099         struct ctl_softc *softc = control_softc;
12100         int retval = 1;
12101
12102         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12103         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12104             ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12105         io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12106         bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12107         switch (io->taskio.task_action) {
12108         case CTL_TASK_ABORT_TASK:
12109                 retval = ctl_abort_task(io);
12110                 break;
12111         case CTL_TASK_ABORT_TASK_SET:
12112         case CTL_TASK_CLEAR_TASK_SET:
12113                 retval = ctl_abort_task_set(io);
12114                 break;
12115         case CTL_TASK_CLEAR_ACA:
12116                 break;
12117         case CTL_TASK_I_T_NEXUS_RESET:
12118                 retval = ctl_i_t_nexus_reset(io);
12119                 break;
12120         case CTL_TASK_LUN_RESET:
12121                 retval = ctl_lun_reset(softc, io);
12122                 break;
12123         case CTL_TASK_TARGET_RESET:
12124                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12125                 break;
12126         case CTL_TASK_BUS_RESET:
12127                 retval = ctl_bus_reset(softc, io);
12128                 break;
12129         case CTL_TASK_PORT_LOGIN:
12130                 break;
12131         case CTL_TASK_PORT_LOGOUT:
12132                 break;
12133         case CTL_TASK_QUERY_TASK:
12134                 retval = ctl_query_task(io, 0);
12135                 break;
12136         case CTL_TASK_QUERY_TASK_SET:
12137                 retval = ctl_query_task(io, 1);
12138                 break;
12139         case CTL_TASK_QUERY_ASYNC_EVENT:
12140                 retval = ctl_query_async_event(io);
12141                 break;
12142         default:
12143                 printf("%s: got unknown task management event %d\n",
12144                        __func__, io->taskio.task_action);
12145                 break;
12146         }
12147         if (retval == 0)
12148                 io->io_hdr.status = CTL_SUCCESS;
12149         else
12150                 io->io_hdr.status = CTL_ERROR;
12151         ctl_done(io);
12152 }
12153
12154 /*
12155  * For HA operation.  Handle commands that come in from the other
12156  * controller.
12157  */
12158 static void
12159 ctl_handle_isc(union ctl_io *io)
12160 {
12161         int free_io;
12162         struct ctl_lun *lun;
12163         struct ctl_softc *softc;
12164         uint32_t targ_lun;
12165
12166         softc = control_softc;
12167
12168         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12169         lun = softc->ctl_luns[targ_lun];
12170
12171         switch (io->io_hdr.msg_type) {
12172         case CTL_MSG_SERIALIZE:
12173                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12174                 break;
12175         case CTL_MSG_R2R: {
12176                 const struct ctl_cmd_entry *entry;
12177
12178                 /*
12179                  * This is only used in SER_ONLY mode.
12180                  */
12181                 free_io = 0;
12182                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12183                 mtx_lock(&lun->lun_lock);
12184                 if (ctl_scsiio_lun_check(lun,
12185                     entry, (struct ctl_scsiio *)io) != 0) {
12186                         mtx_unlock(&lun->lun_lock);
12187                         ctl_done(io);
12188                         break;
12189                 }
12190                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12191                 mtx_unlock(&lun->lun_lock);
12192                 ctl_enqueue_rtr(io);
12193                 break;
12194         }
12195         case CTL_MSG_FINISH_IO:
12196                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12197                         free_io = 0;
12198                         ctl_done(io);
12199                 } else {
12200                         free_io = 1;
12201                         mtx_lock(&lun->lun_lock);
12202                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12203                                      ooa_links);
12204                         ctl_check_blocked(lun);
12205                         mtx_unlock(&lun->lun_lock);
12206                 }
12207                 break;
12208         case CTL_MSG_PERS_ACTION:
12209                 ctl_hndl_per_res_out_on_other_sc(
12210                         (union ctl_ha_msg *)&io->presio.pr_msg);
12211                 free_io = 1;
12212                 break;
12213         case CTL_MSG_BAD_JUJU:
12214                 free_io = 0;
12215                 ctl_done(io);
12216                 break;
12217         case CTL_MSG_DATAMOVE:
12218                 /* Only used in XFER mode */
12219                 free_io = 0;
12220                 ctl_datamove_remote(io);
12221                 break;
12222         case CTL_MSG_DATAMOVE_DONE:
12223                 /* Only used in XFER mode */
12224                 free_io = 0;
12225                 io->scsiio.be_move_done(io);
12226                 break;
12227         case CTL_MSG_FAILOVER:
12228                 mtx_lock(&lun->lun_lock);
12229                 ctl_failover_lun(lun);
12230                 mtx_unlock(&lun->lun_lock);
12231                 free_io = 1;
12232                 break;
12233         default:
12234                 free_io = 1;
12235                 printf("%s: Invalid message type %d\n",
12236                        __func__, io->io_hdr.msg_type);
12237                 break;
12238         }
12239         if (free_io)
12240                 ctl_free_io(io);
12241
12242 }
12243
12244
12245 /*
12246  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12247  * there is no match.
12248  */
12249 static ctl_lun_error_pattern
12250 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12251 {
12252         const struct ctl_cmd_entry *entry;
12253         ctl_lun_error_pattern filtered_pattern, pattern;
12254
12255         pattern = desc->error_pattern;
12256
12257         /*
12258          * XXX KDM we need more data passed into this function to match a
12259          * custom pattern, and we actually need to implement custom pattern
12260          * matching.
12261          */
12262         if (pattern & CTL_LUN_PAT_CMD)
12263                 return (CTL_LUN_PAT_CMD);
12264
12265         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12266                 return (CTL_LUN_PAT_ANY);
12267
12268         entry = ctl_get_cmd_entry(ctsio, NULL);
12269
12270         filtered_pattern = entry->pattern & pattern;
12271
12272         /*
12273          * If the user requested specific flags in the pattern (e.g.
12274          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12275          * flags.
12276          *
12277          * If the user did not specify any flags, it doesn't matter whether
12278          * or not the command supports the flags.
12279          */
12280         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12281              (pattern & ~CTL_LUN_PAT_MASK))
12282                 return (CTL_LUN_PAT_NONE);
12283
12284         /*
12285          * If the user asked for a range check, see if the requested LBA
12286          * range overlaps with this command's LBA range.
12287          */
12288         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12289                 uint64_t lba1;
12290                 uint64_t len1;
12291                 ctl_action action;
12292                 int retval;
12293
12294                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12295                 if (retval != 0)
12296                         return (CTL_LUN_PAT_NONE);
12297
12298                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12299                                               desc->lba_range.len, FALSE);
12300                 /*
12301                  * A "pass" means that the LBA ranges don't overlap, so
12302                  * this doesn't match the user's range criteria.
12303                  */
12304                 if (action == CTL_ACTION_PASS)
12305                         return (CTL_LUN_PAT_NONE);
12306         }
12307
12308         return (filtered_pattern);
12309 }
12310
12311 static void
12312 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12313 {
12314         struct ctl_error_desc *desc, *desc2;
12315
12316         mtx_assert(&lun->lun_lock, MA_OWNED);
12317
12318         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12319                 ctl_lun_error_pattern pattern;
12320                 /*
12321                  * Check to see whether this particular command matches
12322                  * the pattern in the descriptor.
12323                  */
12324                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12325                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12326                         continue;
12327
12328                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12329                 case CTL_LUN_INJ_ABORTED:
12330                         ctl_set_aborted(&io->scsiio);
12331                         break;
12332                 case CTL_LUN_INJ_MEDIUM_ERR:
12333                         ctl_set_medium_error(&io->scsiio,
12334                             (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12335                              CTL_FLAG_DATA_OUT);
12336                         break;
12337                 case CTL_LUN_INJ_UA:
12338                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12339                          * OCCURRED */
12340                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12341                         break;
12342                 case CTL_LUN_INJ_CUSTOM:
12343                         /*
12344                          * We're assuming the user knows what he is doing.
12345                          * Just copy the sense information without doing
12346                          * checks.
12347                          */
12348                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12349                               MIN(sizeof(desc->custom_sense),
12350                                   sizeof(io->scsiio.sense_data)));
12351                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12352                         io->scsiio.sense_len = SSD_FULL_SIZE;
12353                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12354                         break;
12355                 case CTL_LUN_INJ_NONE:
12356                 default:
12357                         /*
12358                          * If this is an error injection type we don't know
12359                          * about, clear the continuous flag (if it is set)
12360                          * so it will get deleted below.
12361                          */
12362                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12363                         break;
12364                 }
12365                 /*
12366                  * By default, each error injection action is a one-shot
12367                  */
12368                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12369                         continue;
12370
12371                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12372
12373                 free(desc, M_CTL);
12374         }
12375 }
12376
12377 #ifdef CTL_IO_DELAY
12378 static void
12379 ctl_datamove_timer_wakeup(void *arg)
12380 {
12381         union ctl_io *io;
12382
12383         io = (union ctl_io *)arg;
12384
12385         ctl_datamove(io);
12386 }
12387 #endif /* CTL_IO_DELAY */
12388
12389 void
12390 ctl_datamove(union ctl_io *io)
12391 {
12392         struct ctl_lun *lun;
12393         void (*fe_datamove)(union ctl_io *io);
12394
12395         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12396
12397         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12398
12399         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12400 #ifdef CTL_TIME_IO
12401         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12402                 char str[256];
12403                 char path_str[64];
12404                 struct sbuf sb;
12405
12406                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12407                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12408
12409                 sbuf_cat(&sb, path_str);
12410                 switch (io->io_hdr.io_type) {
12411                 case CTL_IO_SCSI:
12412                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12413                         sbuf_printf(&sb, "\n");
12414                         sbuf_cat(&sb, path_str);
12415                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12416                                     io->scsiio.tag_num, io->scsiio.tag_type);
12417                         break;
12418                 case CTL_IO_TASK:
12419                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12420                                     "Tag Type: %d\n", io->taskio.task_action,
12421                                     io->taskio.tag_num, io->taskio.tag_type);
12422                         break;
12423                 default:
12424                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12425                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12426                         break;
12427                 }
12428                 sbuf_cat(&sb, path_str);
12429                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12430                             (intmax_t)time_uptime - io->io_hdr.start_time);
12431                 sbuf_finish(&sb);
12432                 printf("%s", sbuf_data(&sb));
12433         }
12434 #endif /* CTL_TIME_IO */
12435
12436 #ifdef CTL_IO_DELAY
12437         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12438                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12439         } else {
12440                 if ((lun != NULL)
12441                  && (lun->delay_info.datamove_delay > 0)) {
12442
12443                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12444                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12445                         callout_reset(&io->io_hdr.delay_callout,
12446                                       lun->delay_info.datamove_delay * hz,
12447                                       ctl_datamove_timer_wakeup, io);
12448                         if (lun->delay_info.datamove_type ==
12449                             CTL_DELAY_TYPE_ONESHOT)
12450                                 lun->delay_info.datamove_delay = 0;
12451                         return;
12452                 }
12453         }
12454 #endif
12455
12456         /*
12457          * This command has been aborted.  Set the port status, so we fail
12458          * the data move.
12459          */
12460         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12461                 printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12462                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
12463                        io->io_hdr.nexus.targ_port,
12464                        io->io_hdr.nexus.targ_lun);
12465                 io->io_hdr.port_status = 31337;
12466                 /*
12467                  * Note that the backend, in this case, will get the
12468                  * callback in its context.  In other cases it may get
12469                  * called in the frontend's interrupt thread context.
12470                  */
12471                 io->scsiio.be_move_done(io);
12472                 return;
12473         }
12474
12475         /* Don't confuse frontend with zero length data move. */
12476         if (io->scsiio.kern_data_len == 0) {
12477                 io->scsiio.be_move_done(io);
12478                 return;
12479         }
12480
12481         /*
12482          * If we're in XFER mode and this I/O is from the other shelf
12483          * controller, we need to send the DMA to the other side to
12484          * actually transfer the data to/from the host.  In serialize only
12485          * mode the transfer happens below CTL and ctl_datamove() is only
12486          * called on the machine that originally received the I/O.
12487          */
12488         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12489          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12490                 union ctl_ha_msg msg;
12491                 uint32_t sg_entries_sent;
12492                 int do_sg_copy;
12493                 int i;
12494
12495                 memset(&msg, 0, sizeof(msg));
12496                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12497                 msg.hdr.original_sc = io->io_hdr.original_sc;
12498                 msg.hdr.serializing_sc = io;
12499                 msg.hdr.nexus = io->io_hdr.nexus;
12500                 msg.hdr.status = io->io_hdr.status;
12501                 msg.dt.flags = io->io_hdr.flags;
12502                 /*
12503                  * We convert everything into a S/G list here.  We can't
12504                  * pass by reference, only by value between controllers.
12505                  * So we can't pass a pointer to the S/G list, only as many
12506                  * S/G entries as we can fit in here.  If it's possible for
12507                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12508                  * then we need to break this up into multiple transfers.
12509                  */
12510                 if (io->scsiio.kern_sg_entries == 0) {
12511                         msg.dt.kern_sg_entries = 1;
12512 #if 0
12513                         /*
12514                          * Convert to a physical address if this is a
12515                          * virtual address.
12516                          */
12517                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12518                                 msg.dt.sg_list[0].addr =
12519                                         io->scsiio.kern_data_ptr;
12520                         } else {
12521                                 /*
12522                                  * XXX KDM use busdma here!
12523                                  */
12524                                 msg.dt.sg_list[0].addr = (void *)
12525                                         vtophys(io->scsiio.kern_data_ptr);
12526                         }
12527 #else
12528                         KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12529                             ("HA does not support BUS_ADDR"));
12530                         msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
12531 #endif
12532
12533                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12534                         do_sg_copy = 0;
12535                 } else {
12536                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12537                         do_sg_copy = 1;
12538                 }
12539
12540                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12541                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12542                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12543                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12544                 msg.dt.sg_sequence = 0;
12545
12546                 /*
12547                  * Loop until we've sent all of the S/G entries.  On the
12548                  * other end, we'll recompose these S/G entries into one
12549                  * contiguous list before passing it to the
12550                  */
12551                 for (sg_entries_sent = 0; sg_entries_sent <
12552                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12553                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12554                                 sizeof(msg.dt.sg_list[0])),
12555                                 msg.dt.kern_sg_entries - sg_entries_sent);
12556
12557                         if (do_sg_copy != 0) {
12558                                 struct ctl_sg_entry *sgl;
12559                                 int j;
12560
12561                                 sgl = (struct ctl_sg_entry *)
12562                                         io->scsiio.kern_data_ptr;
12563                                 /*
12564                                  * If this is in cached memory, flush the cache
12565                                  * before we send the DMA request to the other
12566                                  * controller.  We want to do this in either
12567                                  * the * read or the write case.  The read
12568                                  * case is straightforward.  In the write
12569                                  * case, we want to make sure nothing is
12570                                  * in the local cache that could overwrite
12571                                  * the DMAed data.
12572                                  */
12573
12574                                 for (i = sg_entries_sent, j = 0;
12575                                      i < msg.dt.cur_sg_entries; i++, j++) {
12576 #if 0
12577                                         if ((io->io_hdr.flags &
12578                                              CTL_FLAG_BUS_ADDR) == 0) {
12579                                                 /*
12580                                                  * XXX KDM use busdma.
12581                                                  */
12582                                                 msg.dt.sg_list[j].addr =(void *)
12583                                                        vtophys(sgl[i].addr);
12584                                         } else {
12585                                                 msg.dt.sg_list[j].addr =
12586                                                         sgl[i].addr;
12587                                         }
12588 #else
12589                                         KASSERT((io->io_hdr.flags &
12590                                             CTL_FLAG_BUS_ADDR) == 0,
12591                                             ("HA does not support BUS_ADDR"));
12592                                         msg.dt.sg_list[j].addr = sgl[i].addr;
12593 #endif
12594                                         msg.dt.sg_list[j].len = sgl[i].len;
12595                                 }
12596                         }
12597
12598                         sg_entries_sent += msg.dt.cur_sg_entries;
12599                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12600                                 msg.dt.sg_last = 1;
12601                         else
12602                                 msg.dt.sg_last = 0;
12603
12604                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12605                             sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
12606                             sizeof(struct ctl_sg_entry)*msg.dt.cur_sg_entries,
12607                             M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
12608                                 io->io_hdr.port_status = 31341;
12609                                 io->scsiio.be_move_done(io);
12610                                 return;
12611                         }
12612
12613                         msg.dt.sent_sg_entries = sg_entries_sent;
12614                 }
12615
12616                 /*
12617                  * Officially handover the request from us to peer.
12618                  * If failover has just happened, then we must return error.
12619                  * If failover happen just after, then it is not our problem.
12620                  */
12621                 if (lun)
12622                         mtx_lock(&lun->lun_lock);
12623                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12624                         if (lun)
12625                                 mtx_unlock(&lun->lun_lock);
12626                         io->io_hdr.port_status = 31342;
12627                         io->scsiio.be_move_done(io);
12628                         return;
12629                 }
12630                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12631                 io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
12632                 if (lun)
12633                         mtx_unlock(&lun->lun_lock);
12634         } else {
12635
12636                 /*
12637                  * Lookup the fe_datamove() function for this particular
12638                  * front end.
12639                  */
12640                 fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12641
12642                 fe_datamove(io);
12643         }
12644 }
12645
12646 static void
12647 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12648 {
12649         union ctl_ha_msg msg;
12650
12651         memset(&msg, 0, sizeof(msg));
12652
12653         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12654         msg.hdr.original_sc = io;
12655         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12656         msg.hdr.nexus = io->io_hdr.nexus;
12657         msg.hdr.status = io->io_hdr.status;
12658         msg.scsi.tag_num = io->scsiio.tag_num;
12659         msg.scsi.tag_type = io->scsiio.tag_type;
12660         msg.scsi.scsi_status = io->scsiio.scsi_status;
12661         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12662                io->scsiio.sense_len);
12663         msg.scsi.sense_len = io->scsiio.sense_len;
12664         msg.scsi.sense_residual = io->scsiio.sense_residual;
12665         msg.scsi.fetd_status = io->io_hdr.port_status;
12666         msg.scsi.residual = io->scsiio.residual;
12667         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12668
12669         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12670                 ctl_failover_io(io, /*have_lock*/ have_lock);
12671                 return;
12672         }
12673
12674         ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12675             sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12676             msg.scsi.sense_len, M_WAITOK);
12677 }
12678
12679 /*
12680  * The DMA to the remote side is done, now we need to tell the other side
12681  * we're done so it can continue with its data movement.
12682  */
12683 static void
12684 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12685 {
12686         union ctl_io *io;
12687         int i;
12688
12689         io = rq->context;
12690
12691         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12692                 printf("%s: ISC DMA write failed with error %d", __func__,
12693                        rq->ret);
12694                 ctl_set_internal_failure(&io->scsiio,
12695                                          /*sks_valid*/ 1,
12696                                          /*retry_count*/ rq->ret);
12697         }
12698
12699         ctl_dt_req_free(rq);
12700
12701         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12702                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12703         free(io->io_hdr.remote_sglist, M_CTL);
12704         io->io_hdr.remote_sglist = NULL;
12705         io->io_hdr.local_sglist = NULL;
12706
12707         /*
12708          * The data is in local and remote memory, so now we need to send
12709          * status (good or back) back to the other side.
12710          */
12711         ctl_send_datamove_done(io, /*have_lock*/ 0);
12712 }
12713
12714 /*
12715  * We've moved the data from the host/controller into local memory.  Now we
12716  * need to push it over to the remote controller's memory.
12717  */
12718 static int
12719 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12720 {
12721         int retval;
12722
12723         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12724                                           ctl_datamove_remote_write_cb);
12725         return (retval);
12726 }
12727
12728 static void
12729 ctl_datamove_remote_write(union ctl_io *io)
12730 {
12731         int retval;
12732         void (*fe_datamove)(union ctl_io *io);
12733
12734         /*
12735          * - Get the data from the host/HBA into local memory.
12736          * - DMA memory from the local controller to the remote controller.
12737          * - Send status back to the remote controller.
12738          */
12739
12740         retval = ctl_datamove_remote_sgl_setup(io);
12741         if (retval != 0)
12742                 return;
12743
12744         /* Switch the pointer over so the FETD knows what to do */
12745         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12746
12747         /*
12748          * Use a custom move done callback, since we need to send completion
12749          * back to the other controller, not to the backend on this side.
12750          */
12751         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12752
12753         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12754         fe_datamove(io);
12755 }
12756
12757 static int
12758 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12759 {
12760 #if 0
12761         char str[256];
12762         char path_str[64];
12763         struct sbuf sb;
12764 #endif
12765         int i;
12766
12767         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12768                 free(io->io_hdr.local_sglist[i].addr, M_CTL);
12769         free(io->io_hdr.remote_sglist, M_CTL);
12770         io->io_hdr.remote_sglist = NULL;
12771         io->io_hdr.local_sglist = NULL;
12772
12773 #if 0
12774         scsi_path_string(io, path_str, sizeof(path_str));
12775         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12776         sbuf_cat(&sb, path_str);
12777         scsi_command_string(&io->scsiio, NULL, &sb);
12778         sbuf_printf(&sb, "\n");
12779         sbuf_cat(&sb, path_str);
12780         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12781                     io->scsiio.tag_num, io->scsiio.tag_type);
12782         sbuf_cat(&sb, path_str);
12783         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12784                     io->io_hdr.flags, io->io_hdr.status);
12785         sbuf_finish(&sb);
12786         printk("%s", sbuf_data(&sb));
12787 #endif
12788
12789
12790         /*
12791          * The read is done, now we need to send status (good or bad) back
12792          * to the other side.
12793          */
12794         ctl_send_datamove_done(io, /*have_lock*/ 0);
12795
12796         return (0);
12797 }
12798
12799 static void
12800 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12801 {
12802         union ctl_io *io;
12803         void (*fe_datamove)(union ctl_io *io);
12804
12805         io = rq->context;
12806
12807         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12808                 printf("%s: ISC DMA read failed with error %d\n", __func__,
12809                        rq->ret);
12810                 ctl_set_internal_failure(&io->scsiio,
12811                                          /*sks_valid*/ 1,
12812                                          /*retry_count*/ rq->ret);
12813         }
12814
12815         ctl_dt_req_free(rq);
12816
12817         /* Switch the pointer over so the FETD knows what to do */
12818         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12819
12820         /*
12821          * Use a custom move done callback, since we need to send completion
12822          * back to the other controller, not to the backend on this side.
12823          */
12824         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12825
12826         /* XXX KDM add checks like the ones in ctl_datamove? */
12827
12828         fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12829         fe_datamove(io);
12830 }
12831
12832 static int
12833 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12834 {
12835         struct ctl_sg_entry *local_sglist;
12836         struct ctl_softc *softc;
12837         uint32_t len_to_go;
12838         int retval;
12839         int i;
12840
12841         retval = 0;
12842         softc = control_softc;
12843         local_sglist = io->io_hdr.local_sglist;
12844         len_to_go = io->scsiio.kern_data_len;
12845
12846         /*
12847          * The difficult thing here is that the size of the various
12848          * S/G segments may be different than the size from the
12849          * remote controller.  That'll make it harder when DMAing
12850          * the data back to the other side.
12851          */
12852         for (i = 0; len_to_go > 0; i++) {
12853                 local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12854                 local_sglist[i].addr =
12855                     malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12856
12857                 len_to_go -= local_sglist[i].len;
12858         }
12859         /*
12860          * Reset the number of S/G entries accordingly.  The original
12861          * number of S/G entries is available in rem_sg_entries.
12862          */
12863         io->scsiio.kern_sg_entries = i;
12864
12865 #if 0
12866         printf("%s: kern_sg_entries = %d\n", __func__,
12867                io->scsiio.kern_sg_entries);
12868         for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12869                 printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12870                        local_sglist[i].addr, local_sglist[i].len);
12871 #endif
12872
12873         return (retval);
12874 }
12875
12876 static int
12877 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12878                          ctl_ha_dt_cb callback)
12879 {
12880         struct ctl_ha_dt_req *rq;
12881         struct ctl_sg_entry *remote_sglist, *local_sglist;
12882         uint32_t local_used, remote_used, total_used;
12883         int i, j, isc_ret;
12884
12885         rq = ctl_dt_req_alloc();
12886
12887         /*
12888          * If we failed to allocate the request, and if the DMA didn't fail
12889          * anyway, set busy status.  This is just a resource allocation
12890          * failure.
12891          */
12892         if ((rq == NULL)
12893          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12894              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12895                 ctl_set_busy(&io->scsiio);
12896
12897         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12898             (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12899
12900                 if (rq != NULL)
12901                         ctl_dt_req_free(rq);
12902
12903                 /*
12904                  * The data move failed.  We need to return status back
12905                  * to the other controller.  No point in trying to DMA
12906                  * data to the remote controller.
12907                  */
12908
12909                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12910
12911                 return (1);
12912         }
12913
12914         local_sglist = io->io_hdr.local_sglist;
12915         remote_sglist = io->io_hdr.remote_sglist;
12916         local_used = 0;
12917         remote_used = 0;
12918         total_used = 0;
12919
12920         /*
12921          * Pull/push the data over the wire from/to the other controller.
12922          * This takes into account the possibility that the local and
12923          * remote sglists may not be identical in terms of the size of
12924          * the elements and the number of elements.
12925          *
12926          * One fundamental assumption here is that the length allocated for
12927          * both the local and remote sglists is identical.  Otherwise, we've
12928          * essentially got a coding error of some sort.
12929          */
12930         isc_ret = CTL_HA_STATUS_SUCCESS;
12931         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12932                 uint32_t cur_len;
12933                 uint8_t *tmp_ptr;
12934
12935                 rq->command = command;
12936                 rq->context = io;
12937
12938                 /*
12939                  * Both pointers should be aligned.  But it is possible
12940                  * that the allocation length is not.  They should both
12941                  * also have enough slack left over at the end, though,
12942                  * to round up to the next 8 byte boundary.
12943                  */
12944                 cur_len = MIN(local_sglist[i].len - local_used,
12945                               remote_sglist[j].len - remote_used);
12946                 rq->size = cur_len;
12947
12948                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12949                 tmp_ptr += local_used;
12950
12951 #if 0
12952                 /* Use physical addresses when talking to ISC hardware */
12953                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12954                         /* XXX KDM use busdma */
12955                         rq->local = vtophys(tmp_ptr);
12956                 } else
12957                         rq->local = tmp_ptr;
12958 #else
12959                 KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12960                     ("HA does not support BUS_ADDR"));
12961                 rq->local = tmp_ptr;
12962 #endif
12963
12964                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12965                 tmp_ptr += remote_used;
12966                 rq->remote = tmp_ptr;
12967
12968                 rq->callback = NULL;
12969
12970                 local_used += cur_len;
12971                 if (local_used >= local_sglist[i].len) {
12972                         i++;
12973                         local_used = 0;
12974                 }
12975
12976                 remote_used += cur_len;
12977                 if (remote_used >= remote_sglist[j].len) {
12978                         j++;
12979                         remote_used = 0;
12980                 }
12981                 total_used += cur_len;
12982
12983                 if (total_used >= io->scsiio.kern_data_len)
12984                         rq->callback = callback;
12985
12986 #if 0
12987                 printf("%s: %s: local %p remote %p size %d\n", __func__,
12988                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12989                        rq->local, rq->remote, rq->size);
12990 #endif
12991
12992                 isc_ret = ctl_dt_single(rq);
12993                 if (isc_ret > CTL_HA_STATUS_SUCCESS)
12994                         break;
12995         }
12996         if (isc_ret != CTL_HA_STATUS_WAIT) {
12997                 rq->ret = isc_ret;
12998                 callback(rq);
12999         }
13000
13001         return (0);
13002 }
13003
13004 static void
13005 ctl_datamove_remote_read(union ctl_io *io)
13006 {
13007         int retval;
13008         int i;
13009
13010         /*
13011          * This will send an error to the other controller in the case of a
13012          * failure.
13013          */
13014         retval = ctl_datamove_remote_sgl_setup(io);
13015         if (retval != 0)
13016                 return;
13017
13018         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13019                                           ctl_datamove_remote_read_cb);
13020         if (retval != 0) {
13021                 /*
13022                  * Make sure we free memory if there was an error..  The
13023                  * ctl_datamove_remote_xfer() function will send the
13024                  * datamove done message, or call the callback with an
13025                  * error if there is a problem.
13026                  */
13027                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13028                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13029                 free(io->io_hdr.remote_sglist, M_CTL);
13030                 io->io_hdr.remote_sglist = NULL;
13031                 io->io_hdr.local_sglist = NULL;
13032         }
13033 }
13034
13035 /*
13036  * Process a datamove request from the other controller.  This is used for
13037  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13038  * first.  Once that is complete, the data gets DMAed into the remote
13039  * controller's memory.  For reads, we DMA from the remote controller's
13040  * memory into our memory first, and then move it out to the FETD.
13041  */
13042 static void
13043 ctl_datamove_remote(union ctl_io *io)
13044 {
13045
13046         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13047
13048         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13049                 ctl_failover_io(io, /*have_lock*/ 0);
13050                 return;
13051         }
13052
13053         /*
13054          * Note that we look for an aborted I/O here, but don't do some of
13055          * the other checks that ctl_datamove() normally does.
13056          * We don't need to run the datamove delay code, since that should
13057          * have been done if need be on the other controller.
13058          */
13059         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13060                 printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13061                        io->scsiio.tag_num, io->io_hdr.nexus.initid,
13062                        io->io_hdr.nexus.targ_port,
13063                        io->io_hdr.nexus.targ_lun);
13064                 io->io_hdr.port_status = 31338;
13065                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13066                 return;
13067         }
13068
13069         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13070                 ctl_datamove_remote_write(io);
13071         else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13072                 ctl_datamove_remote_read(io);
13073         else {
13074                 io->io_hdr.port_status = 31339;
13075                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13076         }
13077 }
13078
13079 static int
13080 ctl_process_done(union ctl_io *io)
13081 {
13082         struct ctl_lun *lun;
13083         struct ctl_softc *softc = control_softc;
13084         void (*fe_done)(union ctl_io *io);
13085         union ctl_ha_msg msg;
13086         uint32_t targ_port = io->io_hdr.nexus.targ_port;
13087
13088         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13089
13090         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0)
13091                 fe_done = softc->ctl_ports[targ_port]->fe_done;
13092         else
13093                 fe_done = NULL;
13094
13095 #ifdef CTL_TIME_IO
13096         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13097                 char str[256];
13098                 char path_str[64];
13099                 struct sbuf sb;
13100
13101                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13102                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13103
13104                 sbuf_cat(&sb, path_str);
13105                 switch (io->io_hdr.io_type) {
13106                 case CTL_IO_SCSI:
13107                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13108                         sbuf_printf(&sb, "\n");
13109                         sbuf_cat(&sb, path_str);
13110                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13111                                     io->scsiio.tag_num, io->scsiio.tag_type);
13112                         break;
13113                 case CTL_IO_TASK:
13114                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13115                                     "Tag Type: %d\n", io->taskio.task_action,
13116                                     io->taskio.tag_num, io->taskio.tag_type);
13117                         break;
13118                 default:
13119                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13120                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13121                         break;
13122                 }
13123                 sbuf_cat(&sb, path_str);
13124                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13125                             (intmax_t)time_uptime - io->io_hdr.start_time);
13126                 sbuf_finish(&sb);
13127                 printf("%s", sbuf_data(&sb));
13128         }
13129 #endif /* CTL_TIME_IO */
13130
13131         switch (io->io_hdr.io_type) {
13132         case CTL_IO_SCSI:
13133                 break;
13134         case CTL_IO_TASK:
13135                 if (ctl_debug & CTL_DEBUG_INFO)
13136                         ctl_io_error_print(io, NULL);
13137                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13138                         ctl_free_io(io);
13139                 else
13140                         fe_done(io);
13141                 return (CTL_RETVAL_COMPLETE);
13142         default:
13143                 panic("ctl_process_done: invalid io type %d\n",
13144                       io->io_hdr.io_type);
13145                 break; /* NOTREACHED */
13146         }
13147
13148         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13149         if (lun == NULL) {
13150                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13151                                  io->io_hdr.nexus.targ_mapped_lun));
13152                 goto bailout;
13153         }
13154
13155         mtx_lock(&lun->lun_lock);
13156
13157         /*
13158          * Check to see if we have any errors to inject here.  We only
13159          * inject errors for commands that don't already have errors set.
13160          */
13161         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13162             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13163             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13164                 ctl_inject_error(lun, io);
13165
13166         /*
13167          * XXX KDM how do we treat commands that aren't completed
13168          * successfully?
13169          *
13170          * XXX KDM should we also track I/O latency?
13171          */
13172         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13173             io->io_hdr.io_type == CTL_IO_SCSI) {
13174 #ifdef CTL_TIME_IO
13175                 struct bintime cur_bt;
13176 #endif
13177                 int type;
13178
13179                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13180                     CTL_FLAG_DATA_IN)
13181                         type = CTL_STATS_READ;
13182                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13183                     CTL_FLAG_DATA_OUT)
13184                         type = CTL_STATS_WRITE;
13185                 else
13186                         type = CTL_STATS_NO_IO;
13187
13188                 lun->stats.ports[targ_port].bytes[type] +=
13189                     io->scsiio.kern_total_len;
13190                 lun->stats.ports[targ_port].operations[type]++;
13191 #ifdef CTL_TIME_IO
13192                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13193                    &io->io_hdr.dma_bt);
13194                 lun->stats.ports[targ_port].num_dmas[type] +=
13195                     io->io_hdr.num_dmas;
13196                 getbintime(&cur_bt);
13197                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13198                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13199 #endif
13200         }
13201
13202         /*
13203          * Remove this from the OOA queue.
13204          */
13205         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13206 #ifdef CTL_TIME_IO
13207         if (TAILQ_EMPTY(&lun->ooa_queue))
13208                 lun->last_busy = getsbinuptime();
13209 #endif
13210
13211         /*
13212          * Run through the blocked queue on this LUN and see if anything
13213          * has become unblocked, now that this transaction is done.
13214          */
13215         ctl_check_blocked(lun);
13216
13217         /*
13218          * If the LUN has been invalidated, free it if there is nothing
13219          * left on its OOA queue.
13220          */
13221         if ((lun->flags & CTL_LUN_INVALID)
13222          && TAILQ_EMPTY(&lun->ooa_queue)) {
13223                 mtx_unlock(&lun->lun_lock);
13224                 mtx_lock(&softc->ctl_lock);
13225                 ctl_free_lun(lun);
13226                 mtx_unlock(&softc->ctl_lock);
13227         } else
13228                 mtx_unlock(&lun->lun_lock);
13229
13230 bailout:
13231
13232         /*
13233          * If this command has been aborted, make sure we set the status
13234          * properly.  The FETD is responsible for freeing the I/O and doing
13235          * whatever it needs to do to clean up its state.
13236          */
13237         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13238                 ctl_set_task_aborted(&io->scsiio);
13239
13240         /*
13241          * If enabled, print command error status.
13242          */
13243         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13244             (ctl_debug & CTL_DEBUG_INFO) != 0)
13245                 ctl_io_error_print(io, NULL);
13246
13247         /*
13248          * Tell the FETD or the other shelf controller we're done with this
13249          * command.  Note that only SCSI commands get to this point.  Task
13250          * management commands are completed above.
13251          */
13252         if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13253             (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13254                 memset(&msg, 0, sizeof(msg));
13255                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13256                 msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13257                 msg.hdr.nexus = io->io_hdr.nexus;
13258                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13259                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13260                     M_WAITOK);
13261         }
13262         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13263          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13264                 memset(&msg, 0, sizeof(msg));
13265                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13266                 msg.hdr.original_sc = io->io_hdr.original_sc;
13267                 msg.hdr.nexus = io->io_hdr.nexus;
13268                 msg.hdr.status = io->io_hdr.status;
13269                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13270                 msg.scsi.tag_num = io->scsiio.tag_num;
13271                 msg.scsi.tag_type = io->scsiio.tag_type;
13272                 msg.scsi.sense_len = io->scsiio.sense_len;
13273                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13274                 msg.scsi.residual = io->scsiio.residual;
13275                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13276                        io->scsiio.sense_len);
13277
13278                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13279                     sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
13280                     msg.scsi.sense_len, M_WAITOK);
13281                 ctl_free_io(io);
13282         } else 
13283                 fe_done(io);
13284
13285         return (CTL_RETVAL_COMPLETE);
13286 }
13287
13288 #ifdef CTL_WITH_CA
13289 /*
13290  * Front end should call this if it doesn't do autosense.  When the request
13291  * sense comes back in from the initiator, we'll dequeue this and send it.
13292  */
13293 int
13294 ctl_queue_sense(union ctl_io *io)
13295 {
13296         struct ctl_lun *lun;
13297         struct ctl_port *port;
13298         struct ctl_softc *softc;
13299         uint32_t initidx, targ_lun;
13300
13301         softc = control_softc;
13302
13303         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13304
13305         /*
13306          * LUN lookup will likely move to the ctl_work_thread() once we
13307          * have our new queueing infrastructure (that doesn't put things on
13308          * a per-LUN queue initially).  That is so that we can handle
13309          * things like an INQUIRY to a LUN that we don't have enabled.  We
13310          * can't deal with that right now.
13311          */
13312         mtx_lock(&softc->ctl_lock);
13313
13314         /*
13315          * If we don't have a LUN for this, just toss the sense
13316          * information.
13317          */
13318         port = ctl_io_port(&ctsio->io_hdr);
13319         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13320         if ((targ_lun < CTL_MAX_LUNS)
13321          && (softc->ctl_luns[targ_lun] != NULL))
13322                 lun = softc->ctl_luns[targ_lun];
13323         else
13324                 goto bailout;
13325
13326         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13327
13328         mtx_lock(&lun->lun_lock);
13329         /*
13330          * Already have CA set for this LUN...toss the sense information.
13331          */
13332         if (ctl_is_set(lun->have_ca, initidx)) {
13333                 mtx_unlock(&lun->lun_lock);
13334                 goto bailout;
13335         }
13336
13337         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13338                MIN(sizeof(lun->pending_sense[initidx]),
13339                sizeof(io->scsiio.sense_data)));
13340         ctl_set_mask(lun->have_ca, initidx);
13341         mtx_unlock(&lun->lun_lock);
13342
13343 bailout:
13344         mtx_unlock(&softc->ctl_lock);
13345
13346         ctl_free_io(io);
13347
13348         return (CTL_RETVAL_COMPLETE);
13349 }
13350 #endif
13351
13352 /*
13353  * Primary command inlet from frontend ports.  All SCSI and task I/O
13354  * requests must go through this function.
13355  */
13356 int
13357 ctl_queue(union ctl_io *io)
13358 {
13359         struct ctl_port *port;
13360
13361         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13362
13363 #ifdef CTL_TIME_IO
13364         io->io_hdr.start_time = time_uptime;
13365         getbintime(&io->io_hdr.start_bt);
13366 #endif /* CTL_TIME_IO */
13367
13368         /* Map FE-specific LUN ID into global one. */
13369         port = ctl_io_port(&io->io_hdr);
13370         io->io_hdr.nexus.targ_mapped_lun =
13371             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13372
13373         switch (io->io_hdr.io_type) {
13374         case CTL_IO_SCSI:
13375         case CTL_IO_TASK:
13376                 if (ctl_debug & CTL_DEBUG_CDB)
13377                         ctl_io_print(io);
13378                 ctl_enqueue_incoming(io);
13379                 break;
13380         default:
13381                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13382                 return (EINVAL);
13383         }
13384
13385         return (CTL_RETVAL_COMPLETE);
13386 }
13387
13388 #ifdef CTL_IO_DELAY
13389 static void
13390 ctl_done_timer_wakeup(void *arg)
13391 {
13392         union ctl_io *io;
13393
13394         io = (union ctl_io *)arg;
13395         ctl_done(io);
13396 }
13397 #endif /* CTL_IO_DELAY */
13398
13399 void
13400 ctl_serseq_done(union ctl_io *io)
13401 {
13402         struct ctl_lun *lun;
13403
13404         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13405         if (lun->be_lun == NULL ||
13406             lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13407                 return;
13408         mtx_lock(&lun->lun_lock);
13409         io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13410         ctl_check_blocked(lun);
13411         mtx_unlock(&lun->lun_lock);
13412 }
13413
13414 void
13415 ctl_done(union ctl_io *io)
13416 {
13417
13418         /*
13419          * Enable this to catch duplicate completion issues.
13420          */
13421 #if 0
13422         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13423                 printf("%s: type %d msg %d cdb %x iptl: "
13424                        "%u:%u:%u tag 0x%04x "
13425                        "flag %#x status %x\n",
13426                         __func__,
13427                         io->io_hdr.io_type,
13428                         io->io_hdr.msg_type,
13429                         io->scsiio.cdb[0],
13430                         io->io_hdr.nexus.initid,
13431                         io->io_hdr.nexus.targ_port,
13432                         io->io_hdr.nexus.targ_lun,
13433                         (io->io_hdr.io_type ==
13434                         CTL_IO_TASK) ?
13435                         io->taskio.tag_num :
13436                         io->scsiio.tag_num,
13437                         io->io_hdr.flags,
13438                         io->io_hdr.status);
13439         } else
13440                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13441 #endif
13442
13443         /*
13444          * This is an internal copy of an I/O, and should not go through
13445          * the normal done processing logic.
13446          */
13447         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13448                 return;
13449
13450 #ifdef CTL_IO_DELAY
13451         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13452                 struct ctl_lun *lun;
13453
13454                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13455
13456                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13457         } else {
13458                 struct ctl_lun *lun;
13459
13460                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13461
13462                 if ((lun != NULL)
13463                  && (lun->delay_info.done_delay > 0)) {
13464
13465                         callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13466                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13467                         callout_reset(&io->io_hdr.delay_callout,
13468                                       lun->delay_info.done_delay * hz,
13469                                       ctl_done_timer_wakeup, io);
13470                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13471                                 lun->delay_info.done_delay = 0;
13472                         return;
13473                 }
13474         }
13475 #endif /* CTL_IO_DELAY */
13476
13477         ctl_enqueue_done(io);
13478 }
13479
13480 static void
13481 ctl_work_thread(void *arg)
13482 {
13483         struct ctl_thread *thr = (struct ctl_thread *)arg;
13484         struct ctl_softc *softc = thr->ctl_softc;
13485         union ctl_io *io;
13486         int retval;
13487
13488         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13489
13490         for (;;) {
13491                 retval = 0;
13492
13493                 /*
13494                  * We handle the queues in this order:
13495                  * - ISC
13496                  * - done queue (to free up resources, unblock other commands)
13497                  * - RtR queue
13498                  * - incoming queue
13499                  *
13500                  * If those queues are empty, we break out of the loop and
13501                  * go to sleep.
13502                  */
13503                 mtx_lock(&thr->queue_lock);
13504                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13505                 if (io != NULL) {
13506                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13507                         mtx_unlock(&thr->queue_lock);
13508                         ctl_handle_isc(io);
13509                         continue;
13510                 }
13511                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13512                 if (io != NULL) {
13513                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13514                         /* clear any blocked commands, call fe_done */
13515                         mtx_unlock(&thr->queue_lock);
13516                         retval = ctl_process_done(io);
13517                         continue;
13518                 }
13519                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13520                 if (io != NULL) {
13521                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13522                         mtx_unlock(&thr->queue_lock);
13523                         if (io->io_hdr.io_type == CTL_IO_TASK)
13524                                 ctl_run_task(io);
13525                         else
13526                                 ctl_scsiio_precheck(softc, &io->scsiio);
13527                         continue;
13528                 }
13529                 io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13530                 if (io != NULL) {
13531                         STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13532                         mtx_unlock(&thr->queue_lock);
13533                         retval = ctl_scsiio(&io->scsiio);
13534                         if (retval != CTL_RETVAL_COMPLETE)
13535                                 CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13536                         continue;
13537                 }
13538
13539                 /* Sleep until we have something to do. */
13540                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13541         }
13542 }
13543
13544 static void
13545 ctl_lun_thread(void *arg)
13546 {
13547         struct ctl_softc *softc = (struct ctl_softc *)arg;
13548         struct ctl_be_lun *be_lun;
13549         int retval;
13550
13551         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13552
13553         for (;;) {
13554                 retval = 0;
13555                 mtx_lock(&softc->ctl_lock);
13556                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13557                 if (be_lun != NULL) {
13558                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13559                         mtx_unlock(&softc->ctl_lock);
13560                         ctl_create_lun(be_lun);
13561                         continue;
13562                 }
13563
13564                 /* Sleep until we have something to do. */
13565                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13566                     PDROP | PRIBIO, "-", 0);
13567         }
13568 }
13569
13570 static void
13571 ctl_thresh_thread(void *arg)
13572 {
13573         struct ctl_softc *softc = (struct ctl_softc *)arg;
13574         struct ctl_lun *lun;
13575         struct ctl_be_lun *be_lun;
13576         struct scsi_da_rw_recovery_page *rwpage;
13577         struct ctl_logical_block_provisioning_page *page;
13578         const char *attr;
13579         union ctl_ha_msg msg;
13580         uint64_t thres, val;
13581         int i, e, set;
13582
13583         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13584
13585         for (;;) {
13586                 mtx_lock(&softc->ctl_lock);
13587                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13588                         be_lun = lun->be_lun;
13589                         if ((lun->flags & CTL_LUN_DISABLED) ||
13590                             (lun->flags & CTL_LUN_OFFLINE) ||
13591                             lun->backend->lun_attr == NULL)
13592                                 continue;
13593                         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13594                             softc->ha_mode == CTL_HA_MODE_XFER)
13595                                 continue;
13596                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13597                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13598                                 continue;
13599                         e = 0;
13600                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13601                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13602                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13603                                         continue;
13604                                 thres = scsi_4btoul(page->descr[i].count);
13605                                 thres <<= CTL_LBP_EXPONENT;
13606                                 switch (page->descr[i].resource) {
13607                                 case 0x01:
13608                                         attr = "blocksavail";
13609                                         break;
13610                                 case 0x02:
13611                                         attr = "blocksused";
13612                                         break;
13613                                 case 0xf1:
13614                                         attr = "poolblocksavail";
13615                                         break;
13616                                 case 0xf2:
13617                                         attr = "poolblocksused";
13618                                         break;
13619                                 default:
13620                                         continue;
13621                                 }
13622                                 mtx_unlock(&softc->ctl_lock); // XXX
13623                                 val = lun->backend->lun_attr(
13624                                     lun->be_lun->be_lun, attr);
13625                                 mtx_lock(&softc->ctl_lock);
13626                                 if (val == UINT64_MAX)
13627                                         continue;
13628                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13629                                     == SLBPPD_ARMING_INC)
13630                                         e = (val >= thres);
13631                                 else
13632                                         e = (val <= thres);
13633                                 if (e)
13634                                         break;
13635                         }
13636                         mtx_lock(&lun->lun_lock);
13637                         if (e) {
13638                                 scsi_u64to8b((uint8_t *)&page->descr[i] -
13639                                     (uint8_t *)page, lun->ua_tpt_info);
13640                                 if (lun->lasttpt == 0 ||
13641                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13642                                         lun->lasttpt = time_uptime;
13643                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13644                                         set = 1;
13645                                 } else
13646                                         set = 0;
13647                         } else {
13648                                 lun->lasttpt = 0;
13649                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13650                                 set = -1;
13651                         }
13652                         mtx_unlock(&lun->lun_lock);
13653                         if (set != 0 &&
13654                             lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13655                                 /* Send msg to other side. */
13656                                 bzero(&msg.ua, sizeof(msg.ua));
13657                                 msg.hdr.msg_type = CTL_MSG_UA;
13658                                 msg.hdr.nexus.initid = -1;
13659                                 msg.hdr.nexus.targ_port = -1;
13660                                 msg.hdr.nexus.targ_lun = lun->lun;
13661                                 msg.hdr.nexus.targ_mapped_lun = lun->lun;
13662                                 msg.ua.ua_all = 1;
13663                                 msg.ua.ua_set = (set > 0);
13664                                 msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13665                                 memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13666                                 mtx_unlock(&softc->ctl_lock); // XXX
13667                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13668                                     sizeof(msg.ua), M_WAITOK);
13669                                 mtx_lock(&softc->ctl_lock);
13670                         }
13671                 }
13672                 mtx_unlock(&softc->ctl_lock);
13673                 pause("-", CTL_LBP_PERIOD * hz);
13674         }
13675 }
13676
13677 static void
13678 ctl_enqueue_incoming(union ctl_io *io)
13679 {
13680         struct ctl_softc *softc = control_softc;
13681         struct ctl_thread *thr;
13682         u_int idx;
13683
13684         idx = (io->io_hdr.nexus.targ_port * 127 +
13685                io->io_hdr.nexus.initid) % worker_threads;
13686         thr = &softc->threads[idx];
13687         mtx_lock(&thr->queue_lock);
13688         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13689         mtx_unlock(&thr->queue_lock);
13690         wakeup(thr);
13691 }
13692
13693 static void
13694 ctl_enqueue_rtr(union ctl_io *io)
13695 {
13696         struct ctl_softc *softc = control_softc;
13697         struct ctl_thread *thr;
13698
13699         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13700         mtx_lock(&thr->queue_lock);
13701         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13702         mtx_unlock(&thr->queue_lock);
13703         wakeup(thr);
13704 }
13705
13706 static void
13707 ctl_enqueue_done(union ctl_io *io)
13708 {
13709         struct ctl_softc *softc = control_softc;
13710         struct ctl_thread *thr;
13711
13712         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13713         mtx_lock(&thr->queue_lock);
13714         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13715         mtx_unlock(&thr->queue_lock);
13716         wakeup(thr);
13717 }
13718
13719 static void
13720 ctl_enqueue_isc(union ctl_io *io)
13721 {
13722         struct ctl_softc *softc = control_softc;
13723         struct ctl_thread *thr;
13724
13725         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13726         mtx_lock(&thr->queue_lock);
13727         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13728         mtx_unlock(&thr->queue_lock);
13729         wakeup(thr);
13730 }
13731
13732 /*
13733  *  vim: ts=8
13734  */