]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r287372:
[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  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id$
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/ctype.h>
50 #include <sys/kernel.h>
51 #include <sys/types.h>
52 #include <sys/kthread.h>
53 #include <sys/bio.h>
54 #include <sys/fcntl.h>
55 #include <sys/lock.h>
56 #include <sys/module.h>
57 #include <sys/mutex.h>
58 #include <sys/condvar.h>
59 #include <sys/malloc.h>
60 #include <sys/conf.h>
61 #include <sys/ioccom.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/endian.h>
66 #include <sys/sysctl.h>
67 #include <vm/uma.h>
68
69 #include <cam/cam.h>
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_da.h>
72 #include <cam/ctl/ctl_io.h>
73 #include <cam/ctl/ctl.h>
74 #include <cam/ctl/ctl_frontend.h>
75 #include <cam/ctl/ctl_util.h>
76 #include <cam/ctl/ctl_backend.h>
77 #include <cam/ctl/ctl_ioctl.h>
78 #include <cam/ctl/ctl_ha.h>
79 #include <cam/ctl/ctl_private.h>
80 #include <cam/ctl/ctl_debug.h>
81 #include <cam/ctl/ctl_scsi_all.h>
82 #include <cam/ctl/ctl_error.h>
83
84 struct ctl_softc *control_softc = NULL;
85
86 /*
87  * Size and alignment macros needed for Copan-specific HA hardware.  These
88  * can go away when the HA code is re-written, and uses busdma for any
89  * hardware.
90  */
91 #define CTL_ALIGN_8B(target, source, type)                              \
92         if (((uint32_t)source & 0x7) != 0)                              \
93                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
94         else                                                            \
95                 target = (type)source;
96
97 #define CTL_SIZE_8B(target, size)                                       \
98         if ((size & 0x7) != 0)                                          \
99                 target = size + (0x8 - (size & 0x7));                   \
100         else                                                            \
101                 target = size;
102
103 #define CTL_ALIGN_8B_MARGIN     16
104
105 /*
106  * Template mode pages.
107  */
108
109 /*
110  * Note that these are default values only.  The actual values will be
111  * filled in when the user does a mode sense.
112  */
113 const static struct copan_debugconf_subpage debugconf_page_default = {
114         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
115         DBGCNF_SUBPAGE_CODE,            /* subpage */
116         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
117          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
118         DBGCNF_VERSION,                 /* page_version */
119         {CTL_TIME_IO_DEFAULT_SECS>>8,
120          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
121 };
122
123 const static struct copan_debugconf_subpage debugconf_page_changeable = {
124         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
125         DBGCNF_SUBPAGE_CODE,            /* subpage */
126         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
127          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
128         0,                              /* page_version */
129         {0xff,0xff},                    /* ctl_time_io_secs */
130 };
131
132 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
133         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
134         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
135         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
136         /*read_retry_count*/0,
137         /*correction_span*/0,
138         /*head_offset_count*/0,
139         /*data_strobe_offset_cnt*/0,
140         /*byte8*/SMS_RWER_LBPERE,
141         /*write_retry_count*/0,
142         /*reserved2*/0,
143         /*recovery_time_limit*/{0, 0},
144 };
145
146 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
147         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
148         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
149         /*byte3*/0,
150         /*read_retry_count*/0,
151         /*correction_span*/0,
152         /*head_offset_count*/0,
153         /*data_strobe_offset_cnt*/0,
154         /*byte8*/0,
155         /*write_retry_count*/0,
156         /*reserved2*/0,
157         /*recovery_time_limit*/{0, 0},
158 };
159
160 const static struct scsi_format_page format_page_default = {
161         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
162         /*page_length*/sizeof(struct scsi_format_page) - 2,
163         /*tracks_per_zone*/ {0, 0},
164         /*alt_sectors_per_zone*/ {0, 0},
165         /*alt_tracks_per_zone*/ {0, 0},
166         /*alt_tracks_per_lun*/ {0, 0},
167         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
168                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
169         /*bytes_per_sector*/ {0, 0},
170         /*interleave*/ {0, 0},
171         /*track_skew*/ {0, 0},
172         /*cylinder_skew*/ {0, 0},
173         /*flags*/ SFP_HSEC,
174         /*reserved*/ {0, 0, 0}
175 };
176
177 const static struct scsi_format_page format_page_changeable = {
178         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
179         /*page_length*/sizeof(struct scsi_format_page) - 2,
180         /*tracks_per_zone*/ {0, 0},
181         /*alt_sectors_per_zone*/ {0, 0},
182         /*alt_tracks_per_zone*/ {0, 0},
183         /*alt_tracks_per_lun*/ {0, 0},
184         /*sectors_per_track*/ {0, 0},
185         /*bytes_per_sector*/ {0, 0},
186         /*interleave*/ {0, 0},
187         /*track_skew*/ {0, 0},
188         /*cylinder_skew*/ {0, 0},
189         /*flags*/ 0,
190         /*reserved*/ {0, 0, 0}
191 };
192
193 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
194         /*page_code*/SMS_RIGID_DISK_PAGE,
195         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
196         /*cylinders*/ {0, 0, 0},
197         /*heads*/ CTL_DEFAULT_HEADS,
198         /*start_write_precomp*/ {0, 0, 0},
199         /*start_reduced_current*/ {0, 0, 0},
200         /*step_rate*/ {0, 0},
201         /*landing_zone_cylinder*/ {0, 0, 0},
202         /*rpl*/ SRDP_RPL_DISABLED,
203         /*rotational_offset*/ 0,
204         /*reserved1*/ 0,
205         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
206                            CTL_DEFAULT_ROTATION_RATE & 0xff},
207         /*reserved2*/ {0, 0}
208 };
209
210 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
211         /*page_code*/SMS_RIGID_DISK_PAGE,
212         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
213         /*cylinders*/ {0, 0, 0},
214         /*heads*/ 0,
215         /*start_write_precomp*/ {0, 0, 0},
216         /*start_reduced_current*/ {0, 0, 0},
217         /*step_rate*/ {0, 0},
218         /*landing_zone_cylinder*/ {0, 0, 0},
219         /*rpl*/ 0,
220         /*rotational_offset*/ 0,
221         /*reserved1*/ 0,
222         /*rotation_rate*/ {0, 0},
223         /*reserved2*/ {0, 0}
224 };
225
226 const static struct scsi_caching_page caching_page_default = {
227         /*page_code*/SMS_CACHING_PAGE,
228         /*page_length*/sizeof(struct scsi_caching_page) - 2,
229         /*flags1*/ SCP_DISC | SCP_WCE,
230         /*ret_priority*/ 0,
231         /*disable_pf_transfer_len*/ {0xff, 0xff},
232         /*min_prefetch*/ {0, 0},
233         /*max_prefetch*/ {0xff, 0xff},
234         /*max_pf_ceiling*/ {0xff, 0xff},
235         /*flags2*/ 0,
236         /*cache_segments*/ 0,
237         /*cache_seg_size*/ {0, 0},
238         /*reserved*/ 0,
239         /*non_cache_seg_size*/ {0, 0, 0}
240 };
241
242 const static struct scsi_caching_page caching_page_changeable = {
243         /*page_code*/SMS_CACHING_PAGE,
244         /*page_length*/sizeof(struct scsi_caching_page) - 2,
245         /*flags1*/ SCP_WCE | SCP_RCD,
246         /*ret_priority*/ 0,
247         /*disable_pf_transfer_len*/ {0, 0},
248         /*min_prefetch*/ {0, 0},
249         /*max_prefetch*/ {0, 0},
250         /*max_pf_ceiling*/ {0, 0},
251         /*flags2*/ 0,
252         /*cache_segments*/ 0,
253         /*cache_seg_size*/ {0, 0},
254         /*reserved*/ 0,
255         /*non_cache_seg_size*/ {0, 0, 0}
256 };
257
258 const static struct scsi_control_page control_page_default = {
259         /*page_code*/SMS_CONTROL_MODE_PAGE,
260         /*page_length*/sizeof(struct scsi_control_page) - 2,
261         /*rlec*/0,
262         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
263         /*eca_and_aen*/0,
264         /*flags4*/SCP_TAS,
265         /*aen_holdoff_period*/{0, 0},
266         /*busy_timeout_period*/{0, 0},
267         /*extended_selftest_completion_time*/{0, 0}
268 };
269
270 const static struct scsi_control_page control_page_changeable = {
271         /*page_code*/SMS_CONTROL_MODE_PAGE,
272         /*page_length*/sizeof(struct scsi_control_page) - 2,
273         /*rlec*/SCP_DSENSE,
274         /*queue_flags*/SCP_QUEUE_ALG_MASK,
275         /*eca_and_aen*/SCP_SWP,
276         /*flags4*/0,
277         /*aen_holdoff_period*/{0, 0},
278         /*busy_timeout_period*/{0, 0},
279         /*extended_selftest_completion_time*/{0, 0}
280 };
281
282 const static struct scsi_info_exceptions_page ie_page_default = {
283         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
284         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
285         /*info_flags*/SIEP_FLAGS_DEXCPT,
286         /*mrie*/0,
287         /*interval_timer*/{0, 0, 0, 0},
288         /*report_count*/{0, 0, 0, 0}
289 };
290
291 const static struct scsi_info_exceptions_page ie_page_changeable = {
292         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
293         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
294         /*info_flags*/0,
295         /*mrie*/0,
296         /*interval_timer*/{0, 0, 0, 0},
297         /*report_count*/{0, 0, 0, 0}
298 };
299
300 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
301
302 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
303         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
304         /*subpage_code*/0x02,
305         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
306         /*flags*/0,
307         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
308         /*descr*/{}},
309         {{/*flags*/0,
310           /*resource*/0x01,
311           /*reserved*/{0, 0},
312           /*count*/{0, 0, 0, 0}},
313          {/*flags*/0,
314           /*resource*/0x02,
315           /*reserved*/{0, 0},
316           /*count*/{0, 0, 0, 0}},
317          {/*flags*/0,
318           /*resource*/0xf1,
319           /*reserved*/{0, 0},
320           /*count*/{0, 0, 0, 0}},
321          {/*flags*/0,
322           /*resource*/0xf2,
323           /*reserved*/{0, 0},
324           /*count*/{0, 0, 0, 0}}
325         }
326 };
327
328 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
329         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
330         /*subpage_code*/0x02,
331         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
332         /*flags*/0,
333         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
334         /*descr*/{}},
335         {{/*flags*/0,
336           /*resource*/0,
337           /*reserved*/{0, 0},
338           /*count*/{0, 0, 0, 0}},
339          {/*flags*/0,
340           /*resource*/0,
341           /*reserved*/{0, 0},
342           /*count*/{0, 0, 0, 0}},
343          {/*flags*/0,
344           /*resource*/0,
345           /*reserved*/{0, 0},
346           /*count*/{0, 0, 0, 0}},
347          {/*flags*/0,
348           /*resource*/0,
349           /*reserved*/{0, 0},
350           /*count*/{0, 0, 0, 0}}
351         }
352 };
353
354 /*
355  * XXX KDM move these into the softc.
356  */
357 static int rcv_sync_msg;
358 static uint8_t ctl_pause_rtr;
359
360 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
361 static int worker_threads = -1;
362 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
363 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
364     &worker_threads, 1, "Number of worker threads");
365 static int ctl_debug = CTL_DEBUG_NONE;
366 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
367 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
368     &ctl_debug, 0, "Enabled debug flags");
369
370 /*
371  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
372  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
373  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
374  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
375  */
376 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
377
378 #ifdef notyet
379 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380                                   int param);
381 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382 #endif
383 static int ctl_init(void);
384 void ctl_shutdown(void);
385 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
386 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
387 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
388 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
389                               struct ctl_ooa *ooa_hdr,
390                               struct ctl_ooa_entry *kern_entries);
391 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
392                      struct thread *td);
393 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
394                          struct ctl_be_lun *be_lun);
395 static int ctl_free_lun(struct ctl_lun *lun);
396 static void ctl_create_lun(struct ctl_be_lun *be_lun);
397 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
398 /**
399 static void ctl_failover_change_pages(struct ctl_softc *softc,
400                                       struct ctl_scsiio *ctsio, int master);
401 **/
402
403 static int ctl_do_mode_select(union ctl_io *io);
404 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
405                            uint64_t res_key, uint64_t sa_res_key,
406                            uint8_t type, uint32_t residx,
407                            struct ctl_scsiio *ctsio,
408                            struct scsi_per_res_out *cdb,
409                            struct scsi_per_res_out_parms* param);
410 static void ctl_pro_preempt_other(struct ctl_lun *lun,
411                                   union ctl_ha_msg *msg);
412 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
413 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
414 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
415 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
416 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
417 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
418 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
419                                          int alloc_len);
420 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
421                                          int alloc_len);
422 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
423 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
424 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
425 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
426 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
427 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
428     bool seq);
429 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
430 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
431     union ctl_io *pending_io, union ctl_io *ooa_io);
432 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
433                                 union ctl_io *starting_io);
434 static int ctl_check_blocked(struct ctl_lun *lun);
435 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
436                                 const struct ctl_cmd_entry *entry,
437                                 struct ctl_scsiio *ctsio);
438 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
439 #ifdef notyet
440 static void ctl_failover(void);
441 #endif
442 static void ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
443                          ctl_ua_type ua_type);
444 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
445                                struct ctl_scsiio *ctsio);
446 static int ctl_scsiio(struct ctl_scsiio *ctsio);
447
448 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
449 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
450                             ctl_ua_type ua_type);
451 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
452                          ctl_ua_type ua_type);
453 static int ctl_abort_task(union ctl_io *io);
454 static int ctl_abort_task_set(union ctl_io *io);
455 static int ctl_i_t_nexus_reset(union ctl_io *io);
456 static void ctl_run_task(union ctl_io *io);
457 #ifdef CTL_IO_DELAY
458 static void ctl_datamove_timer_wakeup(void *arg);
459 static void ctl_done_timer_wakeup(void *arg);
460 #endif /* CTL_IO_DELAY */
461
462 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
463 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
464 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
465 static void ctl_datamove_remote_write(union ctl_io *io);
466 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
467 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
468 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
469 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
470                                     ctl_ha_dt_cb callback);
471 static void ctl_datamove_remote_read(union ctl_io *io);
472 static void ctl_datamove_remote(union ctl_io *io);
473 static int ctl_process_done(union ctl_io *io);
474 static void ctl_lun_thread(void *arg);
475 static void ctl_thresh_thread(void *arg);
476 static void ctl_work_thread(void *arg);
477 static void ctl_enqueue_incoming(union ctl_io *io);
478 static void ctl_enqueue_rtr(union ctl_io *io);
479 static void ctl_enqueue_done(union ctl_io *io);
480 #ifdef notyet
481 static void ctl_enqueue_isc(union ctl_io *io);
482 #endif
483 static const struct ctl_cmd_entry *
484     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
485 static const struct ctl_cmd_entry *
486     ctl_validate_command(struct ctl_scsiio *ctsio);
487 static int ctl_cmd_applicable(uint8_t lun_type,
488     const struct ctl_cmd_entry *entry);
489
490 /*
491  * Load the serialization table.  This isn't very pretty, but is probably
492  * the easiest way to do it.
493  */
494 #include "ctl_ser_table.c"
495
496 /*
497  * We only need to define open, close and ioctl routines for this driver.
498  */
499 static struct cdevsw ctl_cdevsw = {
500         .d_version =    D_VERSION,
501         .d_flags =      0,
502         .d_open =       ctl_open,
503         .d_close =      ctl_close,
504         .d_ioctl =      ctl_ioctl,
505         .d_name =       "ctl",
506 };
507
508
509 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
510
511 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
512
513 static moduledata_t ctl_moduledata = {
514         "ctl",
515         ctl_module_event_handler,
516         NULL
517 };
518
519 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
520 MODULE_VERSION(ctl, 1);
521
522 #ifdef notyet
523 static void
524 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
525                             union ctl_ha_msg *msg_info)
526 {
527         struct ctl_scsiio *ctsio;
528
529         if (msg_info->hdr.original_sc == NULL) {
530                 printf("%s: original_sc == NULL!\n", __func__);
531                 /* XXX KDM now what? */
532                 return;
533         }
534
535         ctsio = &msg_info->hdr.original_sc->scsiio;
536         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
537         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
538         ctsio->io_hdr.status = msg_info->hdr.status;
539         ctsio->scsi_status = msg_info->scsi.scsi_status;
540         ctsio->sense_len = msg_info->scsi.sense_len;
541         ctsio->sense_residual = msg_info->scsi.sense_residual;
542         ctsio->residual = msg_info->scsi.residual;
543         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
544                sizeof(ctsio->sense_data));
545         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
546                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
547         ctl_enqueue_isc((union ctl_io *)ctsio);
548 }
549
550 static void
551 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
552                                 union ctl_ha_msg *msg_info)
553 {
554         struct ctl_scsiio *ctsio;
555
556         if (msg_info->hdr.serializing_sc == NULL) {
557                 printf("%s: serializing_sc == NULL!\n", __func__);
558                 /* XXX KDM now what? */
559                 return;
560         }
561
562         ctsio = &msg_info->hdr.serializing_sc->scsiio;
563 #if 0
564         /*
565          * Attempt to catch the situation where an I/O has
566          * been freed, and we're using it again.
567          */
568         if (ctsio->io_hdr.io_type == 0xff) {
569                 union ctl_io *tmp_io;
570                 tmp_io = (union ctl_io *)ctsio;
571                 printf("%s: %p use after free!\n", __func__,
572                        ctsio);
573                 printf("%s: type %d msg %d cdb %x iptl: "
574                        "%d:%d:%d:%d tag 0x%04x "
575                        "flag %#x status %x\n",
576                         __func__,
577                         tmp_io->io_hdr.io_type,
578                         tmp_io->io_hdr.msg_type,
579                         tmp_io->scsiio.cdb[0],
580                         tmp_io->io_hdr.nexus.initid.id,
581                         tmp_io->io_hdr.nexus.targ_port,
582                         tmp_io->io_hdr.nexus.targ_target.id,
583                         tmp_io->io_hdr.nexus.targ_lun,
584                         (tmp_io->io_hdr.io_type ==
585                         CTL_IO_TASK) ?
586                         tmp_io->taskio.tag_num :
587                         tmp_io->scsiio.tag_num,
588                         tmp_io->io_hdr.flags,
589                         tmp_io->io_hdr.status);
590         }
591 #endif
592         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
593         ctl_enqueue_isc((union ctl_io *)ctsio);
594 }
595
596 /*
597  * ISC (Inter Shelf Communication) event handler.  Events from the HA
598  * subsystem come in here.
599  */
600 static void
601 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
602 {
603         struct ctl_softc *softc;
604         union ctl_io *io;
605         struct ctl_prio *presio;
606         ctl_ha_status isc_status;
607
608         softc = control_softc;
609         io = NULL;
610
611
612 #if 0
613         printf("CTL: Isc Msg event %d\n", event);
614 #endif
615         if (event == CTL_HA_EVT_MSG_RECV) {
616                 union ctl_ha_msg msg_info;
617
618                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
619                                              sizeof(msg_info), /*wait*/ 0);
620 #if 0
621                 printf("CTL: msg_type %d\n", msg_info.msg_type);
622 #endif
623                 if (isc_status != 0) {
624                         printf("Error receiving message, status = %d\n",
625                                isc_status);
626                         return;
627                 }
628
629                 switch (msg_info.hdr.msg_type) {
630                 case CTL_MSG_SERIALIZE:
631 #if 0
632                         printf("Serialize\n");
633 #endif
634                         io = ctl_alloc_io_nowait(softc->othersc_pool);
635                         if (io == NULL) {
636                                 printf("ctl_isc_event_handler: can't allocate "
637                                        "ctl_io!\n");
638                                 /* Bad Juju */
639                                 /* Need to set busy and send msg back */
640                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
641                                 msg_info.hdr.status = CTL_SCSI_ERROR;
642                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
643                                 msg_info.scsi.sense_len = 0;
644                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
645                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
646                                 }
647                                 goto bailout;
648                         }
649                         ctl_zero_io(io);
650                         // populate ctsio from msg_info
651                         io->io_hdr.io_type = CTL_IO_SCSI;
652                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
653                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
654 #if 0
655                         printf("pOrig %x\n", (int)msg_info.original_sc);
656 #endif
657                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
658                                             CTL_FLAG_IO_ACTIVE;
659                         /*
660                          * If we're in serialization-only mode, we don't
661                          * want to go through full done processing.  Thus
662                          * the COPY flag.
663                          *
664                          * XXX KDM add another flag that is more specific.
665                          */
666                         if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
667                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
668                         io->io_hdr.nexus = msg_info.hdr.nexus;
669 #if 0
670                         printf("targ %d, port %d, iid %d, lun %d\n",
671                                io->io_hdr.nexus.targ_target.id,
672                                io->io_hdr.nexus.targ_port,
673                                io->io_hdr.nexus.initid.id,
674                                io->io_hdr.nexus.targ_lun);
675 #endif
676                         io->scsiio.tag_num = msg_info.scsi.tag_num;
677                         io->scsiio.tag_type = msg_info.scsi.tag_type;
678                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
679                                CTL_MAX_CDBLEN);
680                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
681                                 const struct ctl_cmd_entry *entry;
682
683                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
684                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
685                                 io->io_hdr.flags |=
686                                         entry->flags & CTL_FLAG_DATA_MASK;
687                         }
688                         ctl_enqueue_isc(io);
689                         break;
690
691                 /* Performed on the Originating SC, XFER mode only */
692                 case CTL_MSG_DATAMOVE: {
693                         struct ctl_sg_entry *sgl;
694                         int i, j;
695
696                         io = msg_info.hdr.original_sc;
697                         if (io == NULL) {
698                                 printf("%s: original_sc == NULL!\n", __func__);
699                                 /* XXX KDM do something here */
700                                 break;
701                         }
702                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
703                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
704                         /*
705                          * Keep track of this, we need to send it back over
706                          * when the datamove is complete.
707                          */
708                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
709
710                         if (msg_info.dt.sg_sequence == 0) {
711                                 /*
712                                  * XXX KDM we use the preallocated S/G list
713                                  * here, but we'll need to change this to
714                                  * dynamic allocation if we need larger S/G
715                                  * lists.
716                                  */
717                                 if (msg_info.dt.kern_sg_entries >
718                                     sizeof(io->io_hdr.remote_sglist) /
719                                     sizeof(io->io_hdr.remote_sglist[0])) {
720                                         printf("%s: number of S/G entries "
721                                             "needed %u > allocated num %zd\n",
722                                             __func__,
723                                             msg_info.dt.kern_sg_entries,
724                                             sizeof(io->io_hdr.remote_sglist)/
725                                             sizeof(io->io_hdr.remote_sglist[0]));
726                                 
727                                         /*
728                                          * XXX KDM send a message back to
729                                          * the other side to shut down the
730                                          * DMA.  The error will come back
731                                          * through via the normal channel.
732                                          */
733                                         break;
734                                 }
735                                 sgl = io->io_hdr.remote_sglist;
736                                 memset(sgl, 0,
737                                        sizeof(io->io_hdr.remote_sglist));
738
739                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
740
741                                 io->scsiio.kern_sg_entries =
742                                         msg_info.dt.kern_sg_entries;
743                                 io->scsiio.rem_sg_entries =
744                                         msg_info.dt.kern_sg_entries;
745                                 io->scsiio.kern_data_len =
746                                         msg_info.dt.kern_data_len;
747                                 io->scsiio.kern_total_len =
748                                         msg_info.dt.kern_total_len;
749                                 io->scsiio.kern_data_resid =
750                                         msg_info.dt.kern_data_resid;
751                                 io->scsiio.kern_rel_offset =
752                                         msg_info.dt.kern_rel_offset;
753                                 /*
754                                  * Clear out per-DMA flags.
755                                  */
756                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
757                                 /*
758                                  * Add per-DMA flags that are set for this
759                                  * particular DMA request.
760                                  */
761                                 io->io_hdr.flags |= msg_info.dt.flags &
762                                                     CTL_FLAG_RDMA_MASK;
763                         } else
764                                 sgl = (struct ctl_sg_entry *)
765                                         io->scsiio.kern_data_ptr;
766
767                         for (i = msg_info.dt.sent_sg_entries, j = 0;
768                              i < (msg_info.dt.sent_sg_entries +
769                              msg_info.dt.cur_sg_entries); i++, j++) {
770                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
771                                 sgl[i].len = msg_info.dt.sg_list[j].len;
772
773 #if 0
774                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
775                                        __func__,
776                                        msg_info.dt.sg_list[j].addr,
777                                        msg_info.dt.sg_list[j].len,
778                                        sgl[i].addr, sgl[i].len, j, i);
779 #endif
780                         }
781 #if 0
782                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
783                                msg_info.dt.sg_list,
784                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
785 #endif
786
787                         /*
788                          * If this is the last piece of the I/O, we've got
789                          * the full S/G list.  Queue processing in the thread.
790                          * Otherwise wait for the next piece.
791                          */
792                         if (msg_info.dt.sg_last != 0)
793                                 ctl_enqueue_isc(io);
794                         break;
795                 }
796                 /* Performed on the Serializing (primary) SC, XFER mode only */
797                 case CTL_MSG_DATAMOVE_DONE: {
798                         if (msg_info.hdr.serializing_sc == NULL) {
799                                 printf("%s: serializing_sc == NULL!\n",
800                                        __func__);
801                                 /* XXX KDM now what? */
802                                 break;
803                         }
804                         /*
805                          * We grab the sense information here in case
806                          * there was a failure, so we can return status
807                          * back to the initiator.
808                          */
809                         io = msg_info.hdr.serializing_sc;
810                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
811                         io->io_hdr.status = msg_info.hdr.status;
812                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
813                         io->scsiio.sense_len = msg_info.scsi.sense_len;
814                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
815                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
816                         io->scsiio.residual = msg_info.scsi.residual;
817                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
818                                sizeof(io->scsiio.sense_data));
819                         ctl_enqueue_isc(io);
820                         break;
821                 }
822
823                 /* Preformed on Originating SC, SER_ONLY mode */
824                 case CTL_MSG_R2R:
825                         io = msg_info.hdr.original_sc;
826                         if (io == NULL) {
827                                 printf("%s: Major Bummer\n", __func__);
828                                 return;
829                         } else {
830 #if 0
831                                 printf("pOrig %x\n",(int) ctsio);
832 #endif
833                         }
834                         io->io_hdr.msg_type = CTL_MSG_R2R;
835                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
836                         ctl_enqueue_isc(io);
837                         break;
838
839                 /*
840                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
841                  * mode.
842                  * Performed on the Originating (i.e. secondary) SC in XFER
843                  * mode
844                  */
845                 case CTL_MSG_FINISH_IO:
846                         if (softc->ha_mode == CTL_HA_MODE_XFER)
847                                 ctl_isc_handler_finish_xfer(softc,
848                                                             &msg_info);
849                         else
850                                 ctl_isc_handler_finish_ser_only(softc,
851                                                                 &msg_info);
852                         break;
853
854                 /* Preformed on Originating SC */
855                 case CTL_MSG_BAD_JUJU:
856                         io = msg_info.hdr.original_sc;
857                         if (io == NULL) {
858                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
859                                        __func__);
860                                 break;
861                         }
862                         ctl_copy_sense_data(&msg_info, io);
863                         /*
864                          * IO should have already been cleaned up on other
865                          * SC so clear this flag so we won't send a message
866                          * back to finish the IO there.
867                          */
868                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
869                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
870
871                         /* io = msg_info.hdr.serializing_sc; */
872                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
873                         ctl_enqueue_isc(io);
874                         break;
875
876                 /* Handle resets sent from the other side */
877                 case CTL_MSG_MANAGE_TASKS: {
878                         struct ctl_taskio *taskio;
879                         taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
880                             softc->othersc_pool);
881                         if (taskio == NULL) {
882                                 printf("ctl_isc_event_handler: can't allocate "
883                                        "ctl_io!\n");
884                                 /* Bad Juju */
885                                 /* should I just call the proper reset func
886                                    here??? */
887                                 goto bailout;
888                         }
889                         ctl_zero_io((union ctl_io *)taskio);
890                         taskio->io_hdr.io_type = CTL_IO_TASK;
891                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
892                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
893                         taskio->task_action = msg_info.task.task_action;
894                         taskio->tag_num = msg_info.task.tag_num;
895                         taskio->tag_type = msg_info.task.tag_type;
896 #ifdef CTL_TIME_IO
897                         taskio->io_hdr.start_time = time_uptime;
898                         getbintime(&taskio->io_hdr.start_bt);
899 #if 0
900                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
901 #endif
902 #endif /* CTL_TIME_IO */
903                         ctl_run_task((union ctl_io *)taskio);
904                         break;
905                 }
906                 /* Persistent Reserve action which needs attention */
907                 case CTL_MSG_PERS_ACTION:
908                         presio = (struct ctl_prio *)ctl_alloc_io_nowait(
909                             softc->othersc_pool);
910                         if (presio == NULL) {
911                                 printf("ctl_isc_event_handler: can't allocate "
912                                        "ctl_io!\n");
913                                 /* Bad Juju */
914                                 /* Need to set busy and send msg back */
915                                 goto bailout;
916                         }
917                         ctl_zero_io((union ctl_io *)presio);
918                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
919                         presio->pr_msg = msg_info.pr;
920                         ctl_enqueue_isc((union ctl_io *)presio);
921                         break;
922                 case CTL_MSG_SYNC_FE:
923                         rcv_sync_msg = 1;
924                         break;
925                 default:
926                         printf("How did I get here?\n");
927                 }
928         } else if (event == CTL_HA_EVT_MSG_SENT) {
929                 if (param != CTL_HA_STATUS_SUCCESS) {
930                         printf("Bad status from ctl_ha_msg_send status %d\n",
931                                param);
932                 }
933                 return;
934         } else if (event == CTL_HA_EVT_DISCONNECT) {
935                 printf("CTL: Got a disconnect from Isc\n");
936                 return;
937         } else {
938                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
939                 return;
940         }
941
942 bailout:
943         return;
944 }
945
946 static void
947 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
948 {
949         struct scsi_sense_data *sense;
950
951         sense = &dest->scsiio.sense_data;
952         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
953         dest->scsiio.scsi_status = src->scsi.scsi_status;
954         dest->scsiio.sense_len = src->scsi.sense_len;
955         dest->io_hdr.status = src->hdr.status;
956 }
957 #endif
958
959 static void
960 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
961 {
962         ctl_ua_type *pu;
963
964         mtx_assert(&lun->lun_lock, MA_OWNED);
965         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
966         if (pu == NULL)
967                 return;
968         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
969 }
970
971 static void
972 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
973 {
974         int i, j;
975
976         mtx_assert(&lun->lun_lock, MA_OWNED);
977         for (i = 0; i < CTL_MAX_PORTS; i++) {
978                 if (lun->pending_ua[i] == NULL)
979                         continue;
980                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
981                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
982                                 continue;
983                         lun->pending_ua[i][j] |= ua;
984                 }
985         }
986 }
987
988 static void
989 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
990 {
991         ctl_ua_type *pu;
992
993         mtx_assert(&lun->lun_lock, MA_OWNED);
994         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
995         if (pu == NULL)
996                 return;
997         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
998 }
999
1000 static void
1001 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1002 {
1003         int i, j;
1004
1005         mtx_assert(&lun->lun_lock, MA_OWNED);
1006         for (i = 0; i < CTL_MAX_PORTS; i++) {
1007                 if (lun->pending_ua[i] == NULL)
1008                         continue;
1009                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1010                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1011                                 continue;
1012                         lun->pending_ua[i][j] &= ~ua;
1013                 }
1014         }
1015 }
1016
1017 static int
1018 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1019 {
1020         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1021         struct ctl_lun *lun;
1022         int error, value;
1023
1024         if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1025                 value = 0;
1026         else
1027                 value = 1;
1028
1029         error = sysctl_handle_int(oidp, &value, 0, req);
1030         if ((error != 0) || (req->newptr == NULL))
1031                 return (error);
1032
1033         mtx_lock(&softc->ctl_lock);
1034         if (value == 0)
1035                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1036         else
1037                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1038         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1039                 mtx_lock(&lun->lun_lock);
1040                 ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1041                 mtx_unlock(&lun->lun_lock);
1042         }
1043         mtx_unlock(&softc->ctl_lock);
1044         return (0);
1045 }
1046
1047 static int
1048 ctl_init(void)
1049 {
1050         struct ctl_softc *softc;
1051         void *other_pool;
1052         int i, error, retval;
1053         //int isc_retval;
1054
1055         retval = 0;
1056         ctl_pause_rtr = 0;
1057         rcv_sync_msg = 0;
1058
1059         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1060                                M_WAITOK | M_ZERO);
1061         softc = control_softc;
1062
1063         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1064                               "cam/ctl");
1065
1066         softc->dev->si_drv1 = softc;
1067
1068         /*
1069          * By default, return a "bad LUN" peripheral qualifier for unknown
1070          * LUNs.  The user can override this default using the tunable or
1071          * sysctl.  See the comment in ctl_inquiry_std() for more details.
1072          */
1073         softc->inquiry_pq_no_lun = 1;
1074         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1075                           &softc->inquiry_pq_no_lun);
1076         sysctl_ctx_init(&softc->sysctl_ctx);
1077         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1078                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1079                 CTLFLAG_RD, 0, "CAM Target Layer");
1080
1081         if (softc->sysctl_tree == NULL) {
1082                 printf("%s: unable to allocate sysctl tree\n", __func__);
1083                 destroy_dev(softc->dev);
1084                 free(control_softc, M_DEVBUF);
1085                 control_softc = NULL;
1086                 return (ENOMEM);
1087         }
1088
1089         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1090                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1091                        "inquiry_pq_no_lun", CTLFLAG_RW,
1092                        &softc->inquiry_pq_no_lun, 0,
1093                        "Report no lun possible for invalid LUNs");
1094
1095         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1096         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1097             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1098         softc->open_count = 0;
1099
1100         /*
1101          * Default to actually sending a SYNCHRONIZE CACHE command down to
1102          * the drive.
1103          */
1104         softc->flags = CTL_FLAG_REAL_SYNC;
1105
1106         /*
1107          * In Copan's HA scheme, the "master" and "slave" roles are
1108          * figured out through the slot the controller is in.  Although it
1109          * is an active/active system, someone has to be in charge.
1110          */
1111         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1112             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1113             "HA head ID (0 - no HA)");
1114         if (softc->ha_id == 0) {
1115                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1116                 softc->is_single = 1;
1117                 softc->port_offset = 0;
1118         } else
1119                 softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1120         softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1121
1122         STAILQ_INIT(&softc->lun_list);
1123         STAILQ_INIT(&softc->pending_lun_queue);
1124         STAILQ_INIT(&softc->fe_list);
1125         STAILQ_INIT(&softc->port_list);
1126         STAILQ_INIT(&softc->be_list);
1127         ctl_tpc_init(softc);
1128
1129         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1130                             &other_pool) != 0)
1131         {
1132                 printf("ctl: can't allocate %d entry other SC pool, "
1133                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1134                 return (ENOMEM);
1135         }
1136         softc->othersc_pool = other_pool;
1137
1138         if (worker_threads <= 0)
1139                 worker_threads = max(1, mp_ncpus / 4);
1140         if (worker_threads > CTL_MAX_THREADS)
1141                 worker_threads = CTL_MAX_THREADS;
1142
1143         for (i = 0; i < worker_threads; i++) {
1144                 struct ctl_thread *thr = &softc->threads[i];
1145
1146                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1147                 thr->ctl_softc = softc;
1148                 STAILQ_INIT(&thr->incoming_queue);
1149                 STAILQ_INIT(&thr->rtr_queue);
1150                 STAILQ_INIT(&thr->done_queue);
1151                 STAILQ_INIT(&thr->isc_queue);
1152
1153                 error = kproc_kthread_add(ctl_work_thread, thr,
1154                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1155                 if (error != 0) {
1156                         printf("error creating CTL work thread!\n");
1157                         ctl_pool_free(other_pool);
1158                         return (error);
1159                 }
1160         }
1161         error = kproc_kthread_add(ctl_lun_thread, softc,
1162             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1163         if (error != 0) {
1164                 printf("error creating CTL lun thread!\n");
1165                 ctl_pool_free(other_pool);
1166                 return (error);
1167         }
1168         error = kproc_kthread_add(ctl_thresh_thread, softc,
1169             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1170         if (error != 0) {
1171                 printf("error creating CTL threshold thread!\n");
1172                 ctl_pool_free(other_pool);
1173                 return (error);
1174         }
1175
1176         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1177             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1178             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1179
1180 #ifdef CTL_IO_DELAY
1181         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1182                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1183                        sizeof(struct callout), CTL_TIMER_BYTES);
1184                 return (EINVAL);
1185         }
1186 #endif /* CTL_IO_DELAY */
1187
1188         return (0);
1189 }
1190
1191 void
1192 ctl_shutdown(void)
1193 {
1194         struct ctl_softc *softc;
1195         struct ctl_lun *lun, *next_lun;
1196
1197         softc = (struct ctl_softc *)control_softc;
1198
1199         mtx_lock(&softc->ctl_lock);
1200
1201         /*
1202          * Free up each LUN.
1203          */
1204         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1205                 next_lun = STAILQ_NEXT(lun, links);
1206                 ctl_free_lun(lun);
1207         }
1208
1209         mtx_unlock(&softc->ctl_lock);
1210
1211 #if 0
1212         ctl_shutdown_thread(softc->work_thread);
1213         mtx_destroy(&softc->queue_lock);
1214 #endif
1215
1216         ctl_tpc_shutdown(softc);
1217         uma_zdestroy(softc->io_zone);
1218         mtx_destroy(&softc->ctl_lock);
1219
1220         destroy_dev(softc->dev);
1221
1222         sysctl_ctx_free(&softc->sysctl_ctx);
1223
1224         free(control_softc, M_DEVBUF);
1225         control_softc = NULL;
1226 }
1227
1228 static int
1229 ctl_module_event_handler(module_t mod, int what, void *arg)
1230 {
1231
1232         switch (what) {
1233         case MOD_LOAD:
1234                 return (ctl_init());
1235         case MOD_UNLOAD:
1236                 return (EBUSY);
1237         default:
1238                 return (EOPNOTSUPP);
1239         }
1240 }
1241
1242 /*
1243  * XXX KDM should we do some access checks here?  Bump a reference count to
1244  * prevent a CTL module from being unloaded while someone has it open?
1245  */
1246 static int
1247 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1248 {
1249         return (0);
1250 }
1251
1252 static int
1253 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1254 {
1255         return (0);
1256 }
1257
1258 int
1259 ctl_port_enable(ctl_port_type port_type)
1260 {
1261         struct ctl_softc *softc = control_softc;
1262         struct ctl_port *port;
1263
1264         if (softc->is_single == 0) {
1265                 union ctl_ha_msg msg_info;
1266                 int isc_retval;
1267
1268 #if 0
1269                 printf("%s: HA mode, synchronizing frontend enable\n",
1270                         __func__);
1271 #endif
1272                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1273                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1274                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1275                         printf("Sync msg send error retval %d\n", isc_retval);
1276                 }
1277                 if (!rcv_sync_msg) {
1278                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1279                                 sizeof(msg_info), 1);
1280                 }
1281 #if 0
1282                 printf("CTL:Frontend Enable\n");
1283         } else {
1284                 printf("%s: single mode, skipping frontend synchronization\n",
1285                         __func__);
1286 #endif
1287         }
1288
1289         STAILQ_FOREACH(port, &softc->port_list, links) {
1290                 if (port_type & port->port_type)
1291                 {
1292 #if 0
1293                         printf("port %d\n", port->targ_port);
1294 #endif
1295                         ctl_port_online(port);
1296                 }
1297         }
1298
1299         return (0);
1300 }
1301
1302 int
1303 ctl_port_disable(ctl_port_type port_type)
1304 {
1305         struct ctl_softc *softc;
1306         struct ctl_port *port;
1307
1308         softc = control_softc;
1309
1310         STAILQ_FOREACH(port, &softc->port_list, links) {
1311                 if (port_type & port->port_type)
1312                         ctl_port_offline(port);
1313         }
1314
1315         return (0);
1316 }
1317
1318 /*
1319  * Returns 0 for success, 1 for failure.
1320  * Currently the only failure mode is if there aren't enough entries
1321  * allocated.  So, in case of a failure, look at num_entries_dropped,
1322  * reallocate and try again.
1323  */
1324 int
1325 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1326               int *num_entries_filled, int *num_entries_dropped,
1327               ctl_port_type port_type, int no_virtual)
1328 {
1329         struct ctl_softc *softc;
1330         struct ctl_port *port;
1331         int entries_dropped, entries_filled;
1332         int retval;
1333         int i;
1334
1335         softc = control_softc;
1336
1337         retval = 0;
1338         entries_filled = 0;
1339         entries_dropped = 0;
1340
1341         i = 0;
1342         mtx_lock(&softc->ctl_lock);
1343         STAILQ_FOREACH(port, &softc->port_list, links) {
1344                 struct ctl_port_entry *entry;
1345
1346                 if ((port->port_type & port_type) == 0)
1347                         continue;
1348
1349                 if ((no_virtual != 0)
1350                  && (port->virtual_port != 0))
1351                         continue;
1352
1353                 if (entries_filled >= num_entries_alloced) {
1354                         entries_dropped++;
1355                         continue;
1356                 }
1357                 entry = &entries[i];
1358
1359                 entry->port_type = port->port_type;
1360                 strlcpy(entry->port_name, port->port_name,
1361                         sizeof(entry->port_name));
1362                 entry->physical_port = port->physical_port;
1363                 entry->virtual_port = port->virtual_port;
1364                 entry->wwnn = port->wwnn;
1365                 entry->wwpn = port->wwpn;
1366
1367                 i++;
1368                 entries_filled++;
1369         }
1370
1371         mtx_unlock(&softc->ctl_lock);
1372
1373         if (entries_dropped > 0)
1374                 retval = 1;
1375
1376         *num_entries_dropped = entries_dropped;
1377         *num_entries_filled = entries_filled;
1378
1379         return (retval);
1380 }
1381
1382 /*
1383  * Remove an initiator by port number and initiator ID.
1384  * Returns 0 for success, -1 for failure.
1385  */
1386 int
1387 ctl_remove_initiator(struct ctl_port *port, int iid)
1388 {
1389         struct ctl_softc *softc = control_softc;
1390
1391         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1392
1393         if (iid > CTL_MAX_INIT_PER_PORT) {
1394                 printf("%s: initiator ID %u > maximun %u!\n",
1395                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1396                 return (-1);
1397         }
1398
1399         mtx_lock(&softc->ctl_lock);
1400         port->wwpn_iid[iid].in_use--;
1401         port->wwpn_iid[iid].last_use = time_uptime;
1402         mtx_unlock(&softc->ctl_lock);
1403
1404         return (0);
1405 }
1406
1407 /*
1408  * Add an initiator to the initiator map.
1409  * Returns iid for success, < 0 for failure.
1410  */
1411 int
1412 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1413 {
1414         struct ctl_softc *softc = control_softc;
1415         time_t best_time;
1416         int i, best;
1417
1418         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1419
1420         if (iid >= CTL_MAX_INIT_PER_PORT) {
1421                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1422                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1423                 free(name, M_CTL);
1424                 return (-1);
1425         }
1426
1427         mtx_lock(&softc->ctl_lock);
1428
1429         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1430                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1431                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1432                                 iid = i;
1433                                 break;
1434                         }
1435                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1436                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1437                                 iid = i;
1438                                 break;
1439                         }
1440                 }
1441         }
1442
1443         if (iid < 0) {
1444                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1445                         if (port->wwpn_iid[i].in_use == 0 &&
1446                             port->wwpn_iid[i].wwpn == 0 &&
1447                             port->wwpn_iid[i].name == NULL) {
1448                                 iid = i;
1449                                 break;
1450                         }
1451                 }
1452         }
1453
1454         if (iid < 0) {
1455                 best = -1;
1456                 best_time = INT32_MAX;
1457                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1458                         if (port->wwpn_iid[i].in_use == 0) {
1459                                 if (port->wwpn_iid[i].last_use < best_time) {
1460                                         best = i;
1461                                         best_time = port->wwpn_iid[i].last_use;
1462                                 }
1463                         }
1464                 }
1465                 iid = best;
1466         }
1467
1468         if (iid < 0) {
1469                 mtx_unlock(&softc->ctl_lock);
1470                 free(name, M_CTL);
1471                 return (-2);
1472         }
1473
1474         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1475                 /*
1476                  * This is not an error yet.
1477                  */
1478                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1479 #if 0
1480                         printf("%s: port %d iid %u WWPN %#jx arrived"
1481                             " again\n", __func__, port->targ_port,
1482                             iid, (uintmax_t)wwpn);
1483 #endif
1484                         goto take;
1485                 }
1486                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1487                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1488 #if 0
1489                         printf("%s: port %d iid %u name '%s' arrived"
1490                             " again\n", __func__, port->targ_port,
1491                             iid, name);
1492 #endif
1493                         goto take;
1494                 }
1495
1496                 /*
1497                  * This is an error, but what do we do about it?  The
1498                  * driver is telling us we have a new WWPN for this
1499                  * initiator ID, so we pretty much need to use it.
1500                  */
1501                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1502                     " but WWPN %#jx '%s' is still at that address\n",
1503                     __func__, port->targ_port, iid, wwpn, name,
1504                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1505                     port->wwpn_iid[iid].name);
1506
1507                 /*
1508                  * XXX KDM clear have_ca and ua_pending on each LUN for
1509                  * this initiator.
1510                  */
1511         }
1512 take:
1513         free(port->wwpn_iid[iid].name, M_CTL);
1514         port->wwpn_iid[iid].name = name;
1515         port->wwpn_iid[iid].wwpn = wwpn;
1516         port->wwpn_iid[iid].in_use++;
1517         mtx_unlock(&softc->ctl_lock);
1518
1519         return (iid);
1520 }
1521
1522 static int
1523 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1524 {
1525         int len;
1526
1527         switch (port->port_type) {
1528         case CTL_PORT_FC:
1529         {
1530                 struct scsi_transportid_fcp *id =
1531                     (struct scsi_transportid_fcp *)buf;
1532                 if (port->wwpn_iid[iid].wwpn == 0)
1533                         return (0);
1534                 memset(id, 0, sizeof(*id));
1535                 id->format_protocol = SCSI_PROTO_FC;
1536                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1537                 return (sizeof(*id));
1538         }
1539         case CTL_PORT_ISCSI:
1540         {
1541                 struct scsi_transportid_iscsi_port *id =
1542                     (struct scsi_transportid_iscsi_port *)buf;
1543                 if (port->wwpn_iid[iid].name == NULL)
1544                         return (0);
1545                 memset(id, 0, 256);
1546                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1547                     SCSI_PROTO_ISCSI;
1548                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1549                 len = roundup2(min(len, 252), 4);
1550                 scsi_ulto2b(len, id->additional_length);
1551                 return (sizeof(*id) + len);
1552         }
1553         case CTL_PORT_SAS:
1554         {
1555                 struct scsi_transportid_sas *id =
1556                     (struct scsi_transportid_sas *)buf;
1557                 if (port->wwpn_iid[iid].wwpn == 0)
1558                         return (0);
1559                 memset(id, 0, sizeof(*id));
1560                 id->format_protocol = SCSI_PROTO_SAS;
1561                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1562                 return (sizeof(*id));
1563         }
1564         default:
1565         {
1566                 struct scsi_transportid_spi *id =
1567                     (struct scsi_transportid_spi *)buf;
1568                 memset(id, 0, sizeof(*id));
1569                 id->format_protocol = SCSI_PROTO_SPI;
1570                 scsi_ulto2b(iid, id->scsi_addr);
1571                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1572                 return (sizeof(*id));
1573         }
1574         }
1575 }
1576
1577 /*
1578  * Serialize a command that went down the "wrong" side, and so was sent to
1579  * this controller for execution.  The logic is a little different than the
1580  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1581  * sent back to the other side, but in the success case, we execute the
1582  * command on this side (XFER mode) or tell the other side to execute it
1583  * (SER_ONLY mode).
1584  */
1585 static int
1586 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1587 {
1588         struct ctl_softc *softc;
1589         union ctl_ha_msg msg_info;
1590         struct ctl_lun *lun;
1591         int retval = 0;
1592         uint32_t targ_lun;
1593
1594         softc = control_softc;
1595
1596         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1597         lun = softc->ctl_luns[targ_lun];
1598         if (lun==NULL)
1599         {
1600                 /*
1601                  * Why isn't LUN defined? The other side wouldn't
1602                  * send a cmd if the LUN is undefined.
1603                  */
1604                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1605
1606                 /* "Logical unit not supported" */
1607                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1608                                    lun,
1609                                    /*sense_format*/SSD_TYPE_NONE,
1610                                    /*current_error*/ 1,
1611                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1612                                    /*asc*/ 0x25,
1613                                    /*ascq*/ 0x00,
1614                                    SSD_ELEM_NONE);
1615
1616                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1617                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1618                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1619                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1620                 msg_info.hdr.serializing_sc = NULL;
1621                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1622                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1623                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1624                 }
1625                 return(1);
1626
1627         }
1628
1629         mtx_lock(&lun->lun_lock);
1630         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1631
1632         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1633                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1634                  ooa_links))) {
1635         case CTL_ACTION_BLOCK:
1636                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1637                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1638                                   blocked_links);
1639                 break;
1640         case CTL_ACTION_PASS:
1641         case CTL_ACTION_SKIP:
1642                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1643                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1644                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1645                 } else {
1646
1647                         /* send msg back to other side */
1648                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1649                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1650                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1651 #if 0
1652                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1653 #endif
1654                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1655                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1656                         }
1657                 }
1658                 break;
1659         case CTL_ACTION_OVERLAP:
1660                 /* OVERLAPPED COMMANDS ATTEMPTED */
1661                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1662                                    lun,
1663                                    /*sense_format*/SSD_TYPE_NONE,
1664                                    /*current_error*/ 1,
1665                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1666                                    /*asc*/ 0x4E,
1667                                    /*ascq*/ 0x00,
1668                                    SSD_ELEM_NONE);
1669
1670                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1671                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1672                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1673                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1674                 msg_info.hdr.serializing_sc = NULL;
1675                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1676 #if 0
1677                 printf("BAD JUJU:Major Bummer Overlap\n");
1678 #endif
1679                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1680                 retval = 1;
1681                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1682                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1683                 }
1684                 break;
1685         case CTL_ACTION_OVERLAP_TAG:
1686                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1687                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1688                                    lun,
1689                                    /*sense_format*/SSD_TYPE_NONE,
1690                                    /*current_error*/ 1,
1691                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1692                                    /*asc*/ 0x4D,
1693                                    /*ascq*/ ctsio->tag_num & 0xff,
1694                                    SSD_ELEM_NONE);
1695
1696                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1697                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1698                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1699                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1700                 msg_info.hdr.serializing_sc = NULL;
1701                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1702 #if 0
1703                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1704 #endif
1705                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1706                 retval = 1;
1707                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1708                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1709                 }
1710                 break;
1711         case CTL_ACTION_ERROR:
1712         default:
1713                 /* "Internal target failure" */
1714                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1715                                    lun,
1716                                    /*sense_format*/SSD_TYPE_NONE,
1717                                    /*current_error*/ 1,
1718                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1719                                    /*asc*/ 0x44,
1720                                    /*ascq*/ 0x00,
1721                                    SSD_ELEM_NONE);
1722
1723                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1724                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1725                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1726                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1727                 msg_info.hdr.serializing_sc = NULL;
1728                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1729 #if 0
1730                 printf("BAD JUJU:Major Bummer HW Error\n");
1731 #endif
1732                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1733                 retval = 1;
1734                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1735                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1736                 }
1737                 break;
1738         }
1739         mtx_unlock(&lun->lun_lock);
1740         return (retval);
1741 }
1742
1743 /*
1744  * Returns 0 for success, errno for failure.
1745  */
1746 static int
1747 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1748                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1749 {
1750         union ctl_io *io;
1751         int retval;
1752
1753         retval = 0;
1754
1755         mtx_lock(&lun->lun_lock);
1756         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1757              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1758              ooa_links)) {
1759                 struct ctl_ooa_entry *entry;
1760
1761                 /*
1762                  * If we've got more than we can fit, just count the
1763                  * remaining entries.
1764                  */
1765                 if (*cur_fill_num >= ooa_hdr->alloc_num)
1766                         continue;
1767
1768                 entry = &kern_entries[*cur_fill_num];
1769
1770                 entry->tag_num = io->scsiio.tag_num;
1771                 entry->lun_num = lun->lun;
1772 #ifdef CTL_TIME_IO
1773                 entry->start_bt = io->io_hdr.start_bt;
1774 #endif
1775                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
1776                 entry->cdb_len = io->scsiio.cdb_len;
1777                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
1778                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
1779
1780                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
1781                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
1782
1783                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
1784                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
1785
1786                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
1787                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
1788
1789                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
1790                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
1791         }
1792         mtx_unlock(&lun->lun_lock);
1793
1794         return (retval);
1795 }
1796
1797 static void *
1798 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
1799                  size_t error_str_len)
1800 {
1801         void *kptr;
1802
1803         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
1804
1805         if (copyin(user_addr, kptr, len) != 0) {
1806                 snprintf(error_str, error_str_len, "Error copying %d bytes "
1807                          "from user address %p to kernel address %p", len,
1808                          user_addr, kptr);
1809                 free(kptr, M_CTL);
1810                 return (NULL);
1811         }
1812
1813         return (kptr);
1814 }
1815
1816 static void
1817 ctl_free_args(int num_args, struct ctl_be_arg *args)
1818 {
1819         int i;
1820
1821         if (args == NULL)
1822                 return;
1823
1824         for (i = 0; i < num_args; i++) {
1825                 free(args[i].kname, M_CTL);
1826                 free(args[i].kvalue, M_CTL);
1827         }
1828
1829         free(args, M_CTL);
1830 }
1831
1832 static struct ctl_be_arg *
1833 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
1834                 char *error_str, size_t error_str_len)
1835 {
1836         struct ctl_be_arg *args;
1837         int i;
1838
1839         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
1840                                 error_str, error_str_len);
1841
1842         if (args == NULL)
1843                 goto bailout;
1844
1845         for (i = 0; i < num_args; i++) {
1846                 args[i].kname = NULL;
1847                 args[i].kvalue = NULL;
1848         }
1849
1850         for (i = 0; i < num_args; i++) {
1851                 uint8_t *tmpptr;
1852
1853                 args[i].kname = ctl_copyin_alloc(args[i].name,
1854                         args[i].namelen, error_str, error_str_len);
1855                 if (args[i].kname == NULL)
1856                         goto bailout;
1857
1858                 if (args[i].kname[args[i].namelen - 1] != '\0') {
1859                         snprintf(error_str, error_str_len, "Argument %d "
1860                                  "name is not NUL-terminated", i);
1861                         goto bailout;
1862                 }
1863
1864                 if (args[i].flags & CTL_BEARG_RD) {
1865                         tmpptr = ctl_copyin_alloc(args[i].value,
1866                                 args[i].vallen, error_str, error_str_len);
1867                         if (tmpptr == NULL)
1868                                 goto bailout;
1869                         if ((args[i].flags & CTL_BEARG_ASCII)
1870                          && (tmpptr[args[i].vallen - 1] != '\0')) {
1871                                 snprintf(error_str, error_str_len, "Argument "
1872                                     "%d value is not NUL-terminated", i);
1873                                 goto bailout;
1874                         }
1875                         args[i].kvalue = tmpptr;
1876                 } else {
1877                         args[i].kvalue = malloc(args[i].vallen,
1878                             M_CTL, M_WAITOK | M_ZERO);
1879                 }
1880         }
1881
1882         return (args);
1883 bailout:
1884
1885         ctl_free_args(num_args, args);
1886
1887         return (NULL);
1888 }
1889
1890 static void
1891 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
1892 {
1893         int i;
1894
1895         for (i = 0; i < num_args; i++) {
1896                 if (args[i].flags & CTL_BEARG_WR)
1897                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
1898         }
1899 }
1900
1901 /*
1902  * Escape characters that are illegal or not recommended in XML.
1903  */
1904 int
1905 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
1906 {
1907         char *end = str + size;
1908         int retval;
1909
1910         retval = 0;
1911
1912         for (; *str && str < end; str++) {
1913                 switch (*str) {
1914                 case '&':
1915                         retval = sbuf_printf(sb, "&amp;");
1916                         break;
1917                 case '>':
1918                         retval = sbuf_printf(sb, "&gt;");
1919                         break;
1920                 case '<':
1921                         retval = sbuf_printf(sb, "&lt;");
1922                         break;
1923                 default:
1924                         retval = sbuf_putc(sb, *str);
1925                         break;
1926                 }
1927
1928                 if (retval != 0)
1929                         break;
1930
1931         }
1932
1933         return (retval);
1934 }
1935
1936 static void
1937 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
1938 {
1939         struct scsi_vpd_id_descriptor *desc;
1940         int i;
1941
1942         if (id == NULL || id->len < 4)
1943                 return;
1944         desc = (struct scsi_vpd_id_descriptor *)id->data;
1945         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
1946         case SVPD_ID_TYPE_T10:
1947                 sbuf_printf(sb, "t10.");
1948                 break;
1949         case SVPD_ID_TYPE_EUI64:
1950                 sbuf_printf(sb, "eui.");
1951                 break;
1952         case SVPD_ID_TYPE_NAA:
1953                 sbuf_printf(sb, "naa.");
1954                 break;
1955         case SVPD_ID_TYPE_SCSI_NAME:
1956                 break;
1957         }
1958         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
1959         case SVPD_ID_CODESET_BINARY:
1960                 for (i = 0; i < desc->length; i++)
1961                         sbuf_printf(sb, "%02x", desc->identifier[i]);
1962                 break;
1963         case SVPD_ID_CODESET_ASCII:
1964                 sbuf_printf(sb, "%.*s", (int)desc->length,
1965                     (char *)desc->identifier);
1966                 break;
1967         case SVPD_ID_CODESET_UTF8:
1968                 sbuf_printf(sb, "%s", (char *)desc->identifier);
1969                 break;
1970         }
1971 }
1972
1973 static int
1974 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
1975           struct thread *td)
1976 {
1977         struct ctl_softc *softc;
1978         int retval;
1979
1980         softc = control_softc;
1981
1982         retval = 0;
1983
1984         switch (cmd) {
1985         case CTL_IO:
1986                 retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
1987                 break;
1988         case CTL_ENABLE_PORT:
1989         case CTL_DISABLE_PORT:
1990         case CTL_SET_PORT_WWNS: {
1991                 struct ctl_port *port;
1992                 struct ctl_port_entry *entry;
1993
1994                 entry = (struct ctl_port_entry *)addr;
1995                 
1996                 mtx_lock(&softc->ctl_lock);
1997                 STAILQ_FOREACH(port, &softc->port_list, links) {
1998                         int action, done;
1999
2000                         action = 0;
2001                         done = 0;
2002
2003                         if ((entry->port_type == CTL_PORT_NONE)
2004                          && (entry->targ_port == port->targ_port)) {
2005                                 /*
2006                                  * If the user only wants to enable or
2007                                  * disable or set WWNs on a specific port,
2008                                  * do the operation and we're done.
2009                                  */
2010                                 action = 1;
2011                                 done = 1;
2012                         } else if (entry->port_type & port->port_type) {
2013                                 /*
2014                                  * Compare the user's type mask with the
2015                                  * particular frontend type to see if we
2016                                  * have a match.
2017                                  */
2018                                 action = 1;
2019                                 done = 0;
2020
2021                                 /*
2022                                  * Make sure the user isn't trying to set
2023                                  * WWNs on multiple ports at the same time.
2024                                  */
2025                                 if (cmd == CTL_SET_PORT_WWNS) {
2026                                         printf("%s: Can't set WWNs on "
2027                                                "multiple ports\n", __func__);
2028                                         retval = EINVAL;
2029                                         break;
2030                                 }
2031                         }
2032                         if (action != 0) {
2033                                 /*
2034                                  * XXX KDM we have to drop the lock here,
2035                                  * because the online/offline operations
2036                                  * can potentially block.  We need to
2037                                  * reference count the frontends so they
2038                                  * can't go away,
2039                                  */
2040                                 mtx_unlock(&softc->ctl_lock);
2041
2042                                 if (cmd == CTL_ENABLE_PORT) {
2043                                         ctl_port_online(port);
2044                                 } else if (cmd == CTL_DISABLE_PORT) {
2045                                         ctl_port_offline(port);
2046                                 }
2047
2048                                 mtx_lock(&softc->ctl_lock);
2049
2050                                 if (cmd == CTL_SET_PORT_WWNS)
2051                                         ctl_port_set_wwns(port,
2052                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2053                                             1 : 0, entry->wwnn,
2054                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2055                                             1 : 0, entry->wwpn);
2056                         }
2057                         if (done != 0)
2058                                 break;
2059                 }
2060                 mtx_unlock(&softc->ctl_lock);
2061                 break;
2062         }
2063         case CTL_GET_PORT_LIST: {
2064                 struct ctl_port *port;
2065                 struct ctl_port_list *list;
2066                 int i;
2067
2068                 list = (struct ctl_port_list *)addr;
2069
2070                 if (list->alloc_len != (list->alloc_num *
2071                     sizeof(struct ctl_port_entry))) {
2072                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2073                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2074                                "%zu\n", __func__, list->alloc_len,
2075                                list->alloc_num, sizeof(struct ctl_port_entry));
2076                         retval = EINVAL;
2077                         break;
2078                 }
2079                 list->fill_len = 0;
2080                 list->fill_num = 0;
2081                 list->dropped_num = 0;
2082                 i = 0;
2083                 mtx_lock(&softc->ctl_lock);
2084                 STAILQ_FOREACH(port, &softc->port_list, links) {
2085                         struct ctl_port_entry entry, *list_entry;
2086
2087                         if (list->fill_num >= list->alloc_num) {
2088                                 list->dropped_num++;
2089                                 continue;
2090                         }
2091
2092                         entry.port_type = port->port_type;
2093                         strlcpy(entry.port_name, port->port_name,
2094                                 sizeof(entry.port_name));
2095                         entry.targ_port = port->targ_port;
2096                         entry.physical_port = port->physical_port;
2097                         entry.virtual_port = port->virtual_port;
2098                         entry.wwnn = port->wwnn;
2099                         entry.wwpn = port->wwpn;
2100                         if (port->status & CTL_PORT_STATUS_ONLINE)
2101                                 entry.online = 1;
2102                         else
2103                                 entry.online = 0;
2104
2105                         list_entry = &list->entries[i];
2106
2107                         retval = copyout(&entry, list_entry, sizeof(entry));
2108                         if (retval != 0) {
2109                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2110                                        "returned %d\n", __func__, retval);
2111                                 break;
2112                         }
2113                         i++;
2114                         list->fill_num++;
2115                         list->fill_len += sizeof(entry);
2116                 }
2117                 mtx_unlock(&softc->ctl_lock);
2118
2119                 /*
2120                  * If this is non-zero, we had a copyout fault, so there's
2121                  * probably no point in attempting to set the status inside
2122                  * the structure.
2123                  */
2124                 if (retval != 0)
2125                         break;
2126
2127                 if (list->dropped_num > 0)
2128                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2129                 else
2130                         list->status = CTL_PORT_LIST_OK;
2131                 break;
2132         }
2133         case CTL_DUMP_OOA: {
2134                 struct ctl_lun *lun;
2135                 union ctl_io *io;
2136                 char printbuf[128];
2137                 struct sbuf sb;
2138
2139                 mtx_lock(&softc->ctl_lock);
2140                 printf("Dumping OOA queues:\n");
2141                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2142                         mtx_lock(&lun->lun_lock);
2143                         for (io = (union ctl_io *)TAILQ_FIRST(
2144                              &lun->ooa_queue); io != NULL;
2145                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2146                              ooa_links)) {
2147                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2148                                          SBUF_FIXEDLEN);
2149                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2150                                             (intmax_t)lun->lun,
2151                                             io->scsiio.tag_num,
2152                                             (io->io_hdr.flags &
2153                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2154                                             (io->io_hdr.flags &
2155                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2156                                             (io->io_hdr.flags &
2157                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2158                                             (io->io_hdr.flags &
2159                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2160                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2161                                 sbuf_finish(&sb);
2162                                 printf("%s\n", sbuf_data(&sb));
2163                         }
2164                         mtx_unlock(&lun->lun_lock);
2165                 }
2166                 printf("OOA queues dump done\n");
2167                 mtx_unlock(&softc->ctl_lock);
2168                 break;
2169         }
2170         case CTL_GET_OOA: {
2171                 struct ctl_lun *lun;
2172                 struct ctl_ooa *ooa_hdr;
2173                 struct ctl_ooa_entry *entries;
2174                 uint32_t cur_fill_num;
2175
2176                 ooa_hdr = (struct ctl_ooa *)addr;
2177
2178                 if ((ooa_hdr->alloc_len == 0)
2179                  || (ooa_hdr->alloc_num == 0)) {
2180                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2181                                "must be non-zero\n", __func__,
2182                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2183                         retval = EINVAL;
2184                         break;
2185                 }
2186
2187                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2188                     sizeof(struct ctl_ooa_entry))) {
2189                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2190                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2191                                __func__, ooa_hdr->alloc_len,
2192                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2193                         retval = EINVAL;
2194                         break;
2195                 }
2196
2197                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2198                 if (entries == NULL) {
2199                         printf("%s: could not allocate %d bytes for OOA "
2200                                "dump\n", __func__, ooa_hdr->alloc_len);
2201                         retval = ENOMEM;
2202                         break;
2203                 }
2204
2205                 mtx_lock(&softc->ctl_lock);
2206                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2207                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2208                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2209                         mtx_unlock(&softc->ctl_lock);
2210                         free(entries, M_CTL);
2211                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2212                                __func__, (uintmax_t)ooa_hdr->lun_num);
2213                         retval = EINVAL;
2214                         break;
2215                 }
2216
2217                 cur_fill_num = 0;
2218
2219                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2220                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2221                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2222                                         ooa_hdr, entries);
2223                                 if (retval != 0)
2224                                         break;
2225                         }
2226                         if (retval != 0) {
2227                                 mtx_unlock(&softc->ctl_lock);
2228                                 free(entries, M_CTL);
2229                                 break;
2230                         }
2231                 } else {
2232                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2233
2234                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2235                                                     entries);
2236                 }
2237                 mtx_unlock(&softc->ctl_lock);
2238
2239                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2240                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2241                         sizeof(struct ctl_ooa_entry);
2242                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2243                 if (retval != 0) {
2244                         printf("%s: error copying out %d bytes for OOA dump\n", 
2245                                __func__, ooa_hdr->fill_len);
2246                 }
2247
2248                 getbintime(&ooa_hdr->cur_bt);
2249
2250                 if (cur_fill_num > ooa_hdr->alloc_num) {
2251                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2252                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2253                 } else {
2254                         ooa_hdr->dropped_num = 0;
2255                         ooa_hdr->status = CTL_OOA_OK;
2256                 }
2257
2258                 free(entries, M_CTL);
2259                 break;
2260         }
2261         case CTL_CHECK_OOA: {
2262                 union ctl_io *io;
2263                 struct ctl_lun *lun;
2264                 struct ctl_ooa_info *ooa_info;
2265
2266
2267                 ooa_info = (struct ctl_ooa_info *)addr;
2268
2269                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2270                         ooa_info->status = CTL_OOA_INVALID_LUN;
2271                         break;
2272                 }
2273                 mtx_lock(&softc->ctl_lock);
2274                 lun = softc->ctl_luns[ooa_info->lun_id];
2275                 if (lun == NULL) {
2276                         mtx_unlock(&softc->ctl_lock);
2277                         ooa_info->status = CTL_OOA_INVALID_LUN;
2278                         break;
2279                 }
2280                 mtx_lock(&lun->lun_lock);
2281                 mtx_unlock(&softc->ctl_lock);
2282                 ooa_info->num_entries = 0;
2283                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2284                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2285                      &io->io_hdr, ooa_links)) {
2286                         ooa_info->num_entries++;
2287                 }
2288                 mtx_unlock(&lun->lun_lock);
2289
2290                 ooa_info->status = CTL_OOA_SUCCESS;
2291
2292                 break;
2293         }
2294         case CTL_DELAY_IO: {
2295                 struct ctl_io_delay_info *delay_info;
2296 #ifdef CTL_IO_DELAY
2297                 struct ctl_lun *lun;
2298 #endif /* CTL_IO_DELAY */
2299
2300                 delay_info = (struct ctl_io_delay_info *)addr;
2301
2302 #ifdef CTL_IO_DELAY
2303                 mtx_lock(&softc->ctl_lock);
2304
2305                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2306                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2307                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2308                 } else {
2309                         lun = softc->ctl_luns[delay_info->lun_id];
2310                         mtx_lock(&lun->lun_lock);
2311
2312                         delay_info->status = CTL_DELAY_STATUS_OK;
2313
2314                         switch (delay_info->delay_type) {
2315                         case CTL_DELAY_TYPE_CONT:
2316                                 break;
2317                         case CTL_DELAY_TYPE_ONESHOT:
2318                                 break;
2319                         default:
2320                                 delay_info->status =
2321                                         CTL_DELAY_STATUS_INVALID_TYPE;
2322                                 break;
2323                         }
2324
2325                         switch (delay_info->delay_loc) {
2326                         case CTL_DELAY_LOC_DATAMOVE:
2327                                 lun->delay_info.datamove_type =
2328                                         delay_info->delay_type;
2329                                 lun->delay_info.datamove_delay =
2330                                         delay_info->delay_secs;
2331                                 break;
2332                         case CTL_DELAY_LOC_DONE:
2333                                 lun->delay_info.done_type =
2334                                         delay_info->delay_type;
2335                                 lun->delay_info.done_delay =
2336                                         delay_info->delay_secs;
2337                                 break;
2338                         default:
2339                                 delay_info->status =
2340                                         CTL_DELAY_STATUS_INVALID_LOC;
2341                                 break;
2342                         }
2343                         mtx_unlock(&lun->lun_lock);
2344                 }
2345
2346                 mtx_unlock(&softc->ctl_lock);
2347 #else
2348                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2349 #endif /* CTL_IO_DELAY */
2350                 break;
2351         }
2352         case CTL_REALSYNC_SET: {
2353                 int *syncstate;
2354
2355                 syncstate = (int *)addr;
2356
2357                 mtx_lock(&softc->ctl_lock);
2358                 switch (*syncstate) {
2359                 case 0:
2360                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2361                         break;
2362                 case 1:
2363                         softc->flags |= CTL_FLAG_REAL_SYNC;
2364                         break;
2365                 default:
2366                         retval = EINVAL;
2367                         break;
2368                 }
2369                 mtx_unlock(&softc->ctl_lock);
2370                 break;
2371         }
2372         case CTL_REALSYNC_GET: {
2373                 int *syncstate;
2374
2375                 syncstate = (int*)addr;
2376
2377                 mtx_lock(&softc->ctl_lock);
2378                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2379                         *syncstate = 1;
2380                 else
2381                         *syncstate = 0;
2382                 mtx_unlock(&softc->ctl_lock);
2383
2384                 break;
2385         }
2386         case CTL_SETSYNC:
2387         case CTL_GETSYNC: {
2388                 struct ctl_sync_info *sync_info;
2389                 struct ctl_lun *lun;
2390
2391                 sync_info = (struct ctl_sync_info *)addr;
2392
2393                 mtx_lock(&softc->ctl_lock);
2394                 lun = softc->ctl_luns[sync_info->lun_id];
2395                 if (lun == NULL) {
2396                         mtx_unlock(&softc->ctl_lock);
2397                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2398                 }
2399                 /*
2400                  * Get or set the sync interval.  We're not bounds checking
2401                  * in the set case, hopefully the user won't do something
2402                  * silly.
2403                  */
2404                 mtx_lock(&lun->lun_lock);
2405                 mtx_unlock(&softc->ctl_lock);
2406                 if (cmd == CTL_GETSYNC)
2407                         sync_info->sync_interval = lun->sync_interval;
2408                 else
2409                         lun->sync_interval = sync_info->sync_interval;
2410                 mtx_unlock(&lun->lun_lock);
2411
2412                 sync_info->status = CTL_GS_SYNC_OK;
2413
2414                 break;
2415         }
2416         case CTL_GETSTATS: {
2417                 struct ctl_stats *stats;
2418                 struct ctl_lun *lun;
2419                 int i;
2420
2421                 stats = (struct ctl_stats *)addr;
2422
2423                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2424                      stats->alloc_len) {
2425                         stats->status = CTL_SS_NEED_MORE_SPACE;
2426                         stats->num_luns = softc->num_luns;
2427                         break;
2428                 }
2429                 /*
2430                  * XXX KDM no locking here.  If the LUN list changes,
2431                  * things can blow up.
2432                  */
2433                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2434                      i++, lun = STAILQ_NEXT(lun, links)) {
2435                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2436                                          sizeof(lun->stats));
2437                         if (retval != 0)
2438                                 break;
2439                 }
2440                 stats->num_luns = softc->num_luns;
2441                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2442                                  softc->num_luns;
2443                 stats->status = CTL_SS_OK;
2444 #ifdef CTL_TIME_IO
2445                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2446 #else
2447                 stats->flags = CTL_STATS_FLAG_NONE;
2448 #endif
2449                 getnanouptime(&stats->timestamp);
2450                 break;
2451         }
2452         case CTL_ERROR_INJECT: {
2453                 struct ctl_error_desc *err_desc, *new_err_desc;
2454                 struct ctl_lun *lun;
2455
2456                 err_desc = (struct ctl_error_desc *)addr;
2457
2458                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2459                                       M_WAITOK | M_ZERO);
2460                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2461
2462                 mtx_lock(&softc->ctl_lock);
2463                 lun = softc->ctl_luns[err_desc->lun_id];
2464                 if (lun == NULL) {
2465                         mtx_unlock(&softc->ctl_lock);
2466                         free(new_err_desc, M_CTL);
2467                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2468                                __func__, (uintmax_t)err_desc->lun_id);
2469                         retval = EINVAL;
2470                         break;
2471                 }
2472                 mtx_lock(&lun->lun_lock);
2473                 mtx_unlock(&softc->ctl_lock);
2474
2475                 /*
2476                  * We could do some checking here to verify the validity
2477                  * of the request, but given the complexity of error
2478                  * injection requests, the checking logic would be fairly
2479                  * complex.
2480                  *
2481                  * For now, if the request is invalid, it just won't get
2482                  * executed and might get deleted.
2483                  */
2484                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2485
2486                 /*
2487                  * XXX KDM check to make sure the serial number is unique,
2488                  * in case we somehow manage to wrap.  That shouldn't
2489                  * happen for a very long time, but it's the right thing to
2490                  * do.
2491                  */
2492                 new_err_desc->serial = lun->error_serial;
2493                 err_desc->serial = lun->error_serial;
2494                 lun->error_serial++;
2495
2496                 mtx_unlock(&lun->lun_lock);
2497                 break;
2498         }
2499         case CTL_ERROR_INJECT_DELETE: {
2500                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2501                 struct ctl_lun *lun;
2502                 int delete_done;
2503
2504                 delete_desc = (struct ctl_error_desc *)addr;
2505                 delete_done = 0;
2506
2507                 mtx_lock(&softc->ctl_lock);
2508                 lun = softc->ctl_luns[delete_desc->lun_id];
2509                 if (lun == NULL) {
2510                         mtx_unlock(&softc->ctl_lock);
2511                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2512                                __func__, (uintmax_t)delete_desc->lun_id);
2513                         retval = EINVAL;
2514                         break;
2515                 }
2516                 mtx_lock(&lun->lun_lock);
2517                 mtx_unlock(&softc->ctl_lock);
2518                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2519                         if (desc->serial != delete_desc->serial)
2520                                 continue;
2521
2522                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2523                                       links);
2524                         free(desc, M_CTL);
2525                         delete_done = 1;
2526                 }
2527                 mtx_unlock(&lun->lun_lock);
2528                 if (delete_done == 0) {
2529                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2530                                "error serial %ju on LUN %u\n", __func__, 
2531                                delete_desc->serial, delete_desc->lun_id);
2532                         retval = EINVAL;
2533                         break;
2534                 }
2535                 break;
2536         }
2537         case CTL_DUMP_STRUCTS: {
2538                 int i, j, k;
2539                 struct ctl_port *port;
2540                 struct ctl_frontend *fe;
2541
2542                 mtx_lock(&softc->ctl_lock);
2543                 printf("CTL Persistent Reservation information start:\n");
2544                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2545                         struct ctl_lun *lun;
2546
2547                         lun = softc->ctl_luns[i];
2548
2549                         if ((lun == NULL)
2550                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2551                                 continue;
2552
2553                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2554                                 if (lun->pr_keys[j] == NULL)
2555                                         continue;
2556                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2557                                         if (lun->pr_keys[j][k] == 0)
2558                                                 continue;
2559                                         printf("  LUN %d port %d iid %d key "
2560                                                "%#jx\n", i, j, k,
2561                                                (uintmax_t)lun->pr_keys[j][k]);
2562                                 }
2563                         }
2564                 }
2565                 printf("CTL Persistent Reservation information end\n");
2566                 printf("CTL Ports:\n");
2567                 STAILQ_FOREACH(port, &softc->port_list, links) {
2568                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2569                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2570                                port->frontend->name, port->port_type,
2571                                port->physical_port, port->virtual_port,
2572                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2573                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2574                                 if (port->wwpn_iid[j].in_use == 0 &&
2575                                     port->wwpn_iid[j].wwpn == 0 &&
2576                                     port->wwpn_iid[j].name == NULL)
2577                                         continue;
2578
2579                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
2580                                     j, port->wwpn_iid[j].in_use,
2581                                     (uintmax_t)port->wwpn_iid[j].wwpn,
2582                                     port->wwpn_iid[j].name);
2583                         }
2584                 }
2585                 printf("CTL Port information end\n");
2586                 mtx_unlock(&softc->ctl_lock);
2587                 /*
2588                  * XXX KDM calling this without a lock.  We'd likely want
2589                  * to drop the lock before calling the frontend's dump
2590                  * routine anyway.
2591                  */
2592                 printf("CTL Frontends:\n");
2593                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
2594                         printf("  Frontend '%s'\n", fe->name);
2595                         if (fe->fe_dump != NULL)
2596                                 fe->fe_dump();
2597                 }
2598                 printf("CTL Frontend information end\n");
2599                 break;
2600         }
2601         case CTL_LUN_REQ: {
2602                 struct ctl_lun_req *lun_req;
2603                 struct ctl_backend_driver *backend;
2604
2605                 lun_req = (struct ctl_lun_req *)addr;
2606
2607                 backend = ctl_backend_find(lun_req->backend);
2608                 if (backend == NULL) {
2609                         lun_req->status = CTL_LUN_ERROR;
2610                         snprintf(lun_req->error_str,
2611                                  sizeof(lun_req->error_str),
2612                                  "Backend \"%s\" not found.",
2613                                  lun_req->backend);
2614                         break;
2615                 }
2616                 if (lun_req->num_be_args > 0) {
2617                         lun_req->kern_be_args = ctl_copyin_args(
2618                                 lun_req->num_be_args,
2619                                 lun_req->be_args,
2620                                 lun_req->error_str,
2621                                 sizeof(lun_req->error_str));
2622                         if (lun_req->kern_be_args == NULL) {
2623                                 lun_req->status = CTL_LUN_ERROR;
2624                                 break;
2625                         }
2626                 }
2627
2628                 retval = backend->ioctl(dev, cmd, addr, flag, td);
2629
2630                 if (lun_req->num_be_args > 0) {
2631                         ctl_copyout_args(lun_req->num_be_args,
2632                                       lun_req->kern_be_args);
2633                         ctl_free_args(lun_req->num_be_args,
2634                                       lun_req->kern_be_args);
2635                 }
2636                 break;
2637         }
2638         case CTL_LUN_LIST: {
2639                 struct sbuf *sb;
2640                 struct ctl_lun *lun;
2641                 struct ctl_lun_list *list;
2642                 struct ctl_option *opt;
2643
2644                 list = (struct ctl_lun_list *)addr;
2645
2646                 /*
2647                  * Allocate a fixed length sbuf here, based on the length
2648                  * of the user's buffer.  We could allocate an auto-extending
2649                  * buffer, and then tell the user how much larger our
2650                  * amount of data is than his buffer, but that presents
2651                  * some problems:
2652                  *
2653                  * 1.  The sbuf(9) routines use a blocking malloc, and so
2654                  *     we can't hold a lock while calling them with an
2655                  *     auto-extending buffer.
2656                  *
2657                  * 2.  There is not currently a LUN reference counting
2658                  *     mechanism, outside of outstanding transactions on
2659                  *     the LUN's OOA queue.  So a LUN could go away on us
2660                  *     while we're getting the LUN number, backend-specific
2661                  *     information, etc.  Thus, given the way things
2662                  *     currently work, we need to hold the CTL lock while
2663                  *     grabbing LUN information.
2664                  *
2665                  * So, from the user's standpoint, the best thing to do is
2666                  * allocate what he thinks is a reasonable buffer length,
2667                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2668                  * double the buffer length and try again.  (And repeat
2669                  * that until he succeeds.)
2670                  */
2671                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2672                 if (sb == NULL) {
2673                         list->status = CTL_LUN_LIST_ERROR;
2674                         snprintf(list->error_str, sizeof(list->error_str),
2675                                  "Unable to allocate %d bytes for LUN list",
2676                                  list->alloc_len);
2677                         break;
2678                 }
2679
2680                 sbuf_printf(sb, "<ctllunlist>\n");
2681
2682                 mtx_lock(&softc->ctl_lock);
2683                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2684                         mtx_lock(&lun->lun_lock);
2685                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2686                                              (uintmax_t)lun->lun);
2687
2688                         /*
2689                          * Bail out as soon as we see that we've overfilled
2690                          * the buffer.
2691                          */
2692                         if (retval != 0)
2693                                 break;
2694
2695                         retval = sbuf_printf(sb, "\t<backend_type>%s"
2696                                              "</backend_type>\n",
2697                                              (lun->backend == NULL) ?  "none" :
2698                                              lun->backend->name);
2699
2700                         if (retval != 0)
2701                                 break;
2702
2703                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
2704                                              lun->be_lun->lun_type);
2705
2706                         if (retval != 0)
2707                                 break;
2708
2709                         if (lun->backend == NULL) {
2710                                 retval = sbuf_printf(sb, "</lun>\n");
2711                                 if (retval != 0)
2712                                         break;
2713                                 continue;
2714                         }
2715
2716                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
2717                                              (lun->be_lun->maxlba > 0) ?
2718                                              lun->be_lun->maxlba + 1 : 0);
2719
2720                         if (retval != 0)
2721                                 break;
2722
2723                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
2724                                              lun->be_lun->blocksize);
2725
2726                         if (retval != 0)
2727                                 break;
2728
2729                         retval = sbuf_printf(sb, "\t<serial_number>");
2730
2731                         if (retval != 0)
2732                                 break;
2733
2734                         retval = ctl_sbuf_printf_esc(sb,
2735                             lun->be_lun->serial_num,
2736                             sizeof(lun->be_lun->serial_num));
2737
2738                         if (retval != 0)
2739                                 break;
2740
2741                         retval = sbuf_printf(sb, "</serial_number>\n");
2742                 
2743                         if (retval != 0)
2744                                 break;
2745
2746                         retval = sbuf_printf(sb, "\t<device_id>");
2747
2748                         if (retval != 0)
2749                                 break;
2750
2751                         retval = ctl_sbuf_printf_esc(sb,
2752                             lun->be_lun->device_id,
2753                             sizeof(lun->be_lun->device_id));
2754
2755                         if (retval != 0)
2756                                 break;
2757
2758                         retval = sbuf_printf(sb, "</device_id>\n");
2759
2760                         if (retval != 0)
2761                                 break;
2762
2763                         if (lun->backend->lun_info != NULL) {
2764                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
2765                                 if (retval != 0)
2766                                         break;
2767                         }
2768                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
2769                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
2770                                     opt->name, opt->value, opt->name);
2771                                 if (retval != 0)
2772                                         break;
2773                         }
2774
2775                         retval = sbuf_printf(sb, "</lun>\n");
2776
2777                         if (retval != 0)
2778                                 break;
2779                         mtx_unlock(&lun->lun_lock);
2780                 }
2781                 if (lun != NULL)
2782                         mtx_unlock(&lun->lun_lock);
2783                 mtx_unlock(&softc->ctl_lock);
2784
2785                 if ((retval != 0)
2786                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
2787                         retval = 0;
2788                         sbuf_delete(sb);
2789                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
2790                         snprintf(list->error_str, sizeof(list->error_str),
2791                                  "Out of space, %d bytes is too small",
2792                                  list->alloc_len);
2793                         break;
2794                 }
2795
2796                 sbuf_finish(sb);
2797
2798                 retval = copyout(sbuf_data(sb), list->lun_xml,
2799                                  sbuf_len(sb) + 1);
2800
2801                 list->fill_len = sbuf_len(sb) + 1;
2802                 list->status = CTL_LUN_LIST_OK;
2803                 sbuf_delete(sb);
2804                 break;
2805         }
2806         case CTL_ISCSI: {
2807                 struct ctl_iscsi *ci;
2808                 struct ctl_frontend *fe;
2809
2810                 ci = (struct ctl_iscsi *)addr;
2811
2812                 fe = ctl_frontend_find("iscsi");
2813                 if (fe == NULL) {
2814                         ci->status = CTL_ISCSI_ERROR;
2815                         snprintf(ci->error_str, sizeof(ci->error_str),
2816                             "Frontend \"iscsi\" not found.");
2817                         break;
2818                 }
2819
2820                 retval = fe->ioctl(dev, cmd, addr, flag, td);
2821                 break;
2822         }
2823         case CTL_PORT_REQ: {
2824                 struct ctl_req *req;
2825                 struct ctl_frontend *fe;
2826
2827                 req = (struct ctl_req *)addr;
2828
2829                 fe = ctl_frontend_find(req->driver);
2830                 if (fe == NULL) {
2831                         req->status = CTL_LUN_ERROR;
2832                         snprintf(req->error_str, sizeof(req->error_str),
2833                             "Frontend \"%s\" not found.", req->driver);
2834                         break;
2835                 }
2836                 if (req->num_args > 0) {
2837                         req->kern_args = ctl_copyin_args(req->num_args,
2838                             req->args, req->error_str, sizeof(req->error_str));
2839                         if (req->kern_args == NULL) {
2840                                 req->status = CTL_LUN_ERROR;
2841                                 break;
2842                         }
2843                 }
2844
2845                 retval = fe->ioctl(dev, cmd, addr, flag, td);
2846
2847                 if (req->num_args > 0) {
2848                         ctl_copyout_args(req->num_args, req->kern_args);
2849                         ctl_free_args(req->num_args, req->kern_args);
2850                 }
2851                 break;
2852         }
2853         case CTL_PORT_LIST: {
2854                 struct sbuf *sb;
2855                 struct ctl_port *port;
2856                 struct ctl_lun_list *list;
2857                 struct ctl_option *opt;
2858                 int j;
2859                 uint32_t plun;
2860
2861                 list = (struct ctl_lun_list *)addr;
2862
2863                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2864                 if (sb == NULL) {
2865                         list->status = CTL_LUN_LIST_ERROR;
2866                         snprintf(list->error_str, sizeof(list->error_str),
2867                                  "Unable to allocate %d bytes for LUN list",
2868                                  list->alloc_len);
2869                         break;
2870                 }
2871
2872                 sbuf_printf(sb, "<ctlportlist>\n");
2873
2874                 mtx_lock(&softc->ctl_lock);
2875                 STAILQ_FOREACH(port, &softc->port_list, links) {
2876                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
2877                                              (uintmax_t)port->targ_port);
2878
2879                         /*
2880                          * Bail out as soon as we see that we've overfilled
2881                          * the buffer.
2882                          */
2883                         if (retval != 0)
2884                                 break;
2885
2886                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
2887                             "</frontend_type>\n", port->frontend->name);
2888                         if (retval != 0)
2889                                 break;
2890
2891                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
2892                                              port->port_type);
2893                         if (retval != 0)
2894                                 break;
2895
2896                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
2897                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
2898                         if (retval != 0)
2899                                 break;
2900
2901                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
2902                             port->port_name);
2903                         if (retval != 0)
2904                                 break;
2905
2906                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
2907                             port->physical_port);
2908                         if (retval != 0)
2909                                 break;
2910
2911                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
2912                             port->virtual_port);
2913                         if (retval != 0)
2914                                 break;
2915
2916                         if (port->target_devid != NULL) {
2917                                 sbuf_printf(sb, "\t<target>");
2918                                 ctl_id_sbuf(port->target_devid, sb);
2919                                 sbuf_printf(sb, "</target>\n");
2920                         }
2921
2922                         if (port->port_devid != NULL) {
2923                                 sbuf_printf(sb, "\t<port>");
2924                                 ctl_id_sbuf(port->port_devid, sb);
2925                                 sbuf_printf(sb, "</port>\n");
2926                         }
2927
2928                         if (port->port_info != NULL) {
2929                                 retval = port->port_info(port->onoff_arg, sb);
2930                                 if (retval != 0)
2931                                         break;
2932                         }
2933                         STAILQ_FOREACH(opt, &port->options, links) {
2934                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
2935                                     opt->name, opt->value, opt->name);
2936                                 if (retval != 0)
2937                                         break;
2938                         }
2939
2940                         if (port->lun_map != NULL) {
2941                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
2942                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
2943                                         plun = ctl_lun_map_from_port(port, j);
2944                                         if (plun >= CTL_MAX_LUNS)
2945                                                 continue;
2946                                         sbuf_printf(sb,
2947                                             "\t<lun id=\"%u\">%u</lun>\n",
2948                                             j, plun);
2949                                 }
2950                         }
2951
2952                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2953                                 if (port->wwpn_iid[j].in_use == 0 ||
2954                                     (port->wwpn_iid[j].wwpn == 0 &&
2955                                      port->wwpn_iid[j].name == NULL))
2956                                         continue;
2957
2958                                 if (port->wwpn_iid[j].name != NULL)
2959                                         retval = sbuf_printf(sb,
2960                                             "\t<initiator id=\"%u\">%s</initiator>\n",
2961                                             j, port->wwpn_iid[j].name);
2962                                 else
2963                                         retval = sbuf_printf(sb,
2964                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
2965                                             j, port->wwpn_iid[j].wwpn);
2966                                 if (retval != 0)
2967                                         break;
2968                         }
2969                         if (retval != 0)
2970                                 break;
2971
2972                         retval = sbuf_printf(sb, "</targ_port>\n");
2973                         if (retval != 0)
2974                                 break;
2975                 }
2976                 mtx_unlock(&softc->ctl_lock);
2977
2978                 if ((retval != 0)
2979                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
2980                         retval = 0;
2981                         sbuf_delete(sb);
2982                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
2983                         snprintf(list->error_str, sizeof(list->error_str),
2984                                  "Out of space, %d bytes is too small",
2985                                  list->alloc_len);
2986                         break;
2987                 }
2988
2989                 sbuf_finish(sb);
2990
2991                 retval = copyout(sbuf_data(sb), list->lun_xml,
2992                                  sbuf_len(sb) + 1);
2993
2994                 list->fill_len = sbuf_len(sb) + 1;
2995                 list->status = CTL_LUN_LIST_OK;
2996                 sbuf_delete(sb);
2997                 break;
2998         }
2999         case CTL_LUN_MAP: {
3000                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3001                 struct ctl_port *port;
3002
3003                 mtx_lock(&softc->ctl_lock);
3004                 if (lm->port >= CTL_MAX_PORTS ||
3005                     (port = softc->ctl_ports[lm->port]) == NULL) {
3006                         mtx_unlock(&softc->ctl_lock);
3007                         return (ENXIO);
3008                 }
3009                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3010                 if (lm->plun < CTL_MAX_LUNS) {
3011                         if (lm->lun == UINT32_MAX)
3012                                 retval = ctl_lun_map_unset(port, lm->plun);
3013                         else if (lm->lun < CTL_MAX_LUNS &&
3014                             softc->ctl_luns[lm->lun] != NULL)
3015                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3016                         else
3017                                 return (ENXIO);
3018                 } else if (lm->plun == UINT32_MAX) {
3019                         if (lm->lun == UINT32_MAX)
3020                                 retval = ctl_lun_map_deinit(port);
3021                         else
3022                                 retval = ctl_lun_map_init(port);
3023                 } else
3024                         return (ENXIO);
3025                 break;
3026         }
3027         default: {
3028                 /* XXX KDM should we fix this? */
3029 #if 0
3030                 struct ctl_backend_driver *backend;
3031                 unsigned int type;
3032                 int found;
3033
3034                 found = 0;
3035
3036                 /*
3037                  * We encode the backend type as the ioctl type for backend
3038                  * ioctls.  So parse it out here, and then search for a
3039                  * backend of this type.
3040                  */
3041                 type = _IOC_TYPE(cmd);
3042
3043                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3044                         if (backend->type == type) {
3045                                 found = 1;
3046                                 break;
3047                         }
3048                 }
3049                 if (found == 0) {
3050                         printf("ctl: unknown ioctl command %#lx or backend "
3051                                "%d\n", cmd, type);
3052                         retval = EINVAL;
3053                         break;
3054                 }
3055                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3056 #endif
3057                 retval = ENOTTY;
3058                 break;
3059         }
3060         }
3061         return (retval);
3062 }
3063
3064 uint32_t
3065 ctl_get_initindex(struct ctl_nexus *nexus)
3066 {
3067         if (nexus->targ_port < CTL_MAX_PORTS)
3068                 return (nexus->initid.id +
3069                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3070         else
3071                 return (nexus->initid.id +
3072                        ((nexus->targ_port - CTL_MAX_PORTS) *
3073                         CTL_MAX_INIT_PER_PORT));
3074 }
3075
3076 uint32_t
3077 ctl_get_resindex(struct ctl_nexus *nexus)
3078 {
3079         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3080 }
3081
3082 uint32_t
3083 ctl_port_idx(int port_num)
3084 {
3085         if (port_num < CTL_MAX_PORTS)
3086                 return(port_num);
3087         else
3088                 return(port_num - CTL_MAX_PORTS);
3089 }
3090
3091 int
3092 ctl_lun_map_init(struct ctl_port *port)
3093 {
3094         struct ctl_softc *softc = control_softc;
3095         struct ctl_lun *lun;
3096         uint32_t i;
3097
3098         if (port->lun_map == NULL)
3099                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3100                     M_CTL, M_NOWAIT);
3101         if (port->lun_map == NULL)
3102                 return (ENOMEM);
3103         for (i = 0; i < CTL_MAX_LUNS; i++)
3104                 port->lun_map[i] = UINT32_MAX;
3105         if (port->status & CTL_PORT_STATUS_ONLINE &&
3106             port->lun_disable != NULL) {
3107                 STAILQ_FOREACH(lun, &softc->lun_list, links)
3108                         port->lun_disable(port->targ_lun_arg, lun->lun);
3109         }
3110         return (0);
3111 }
3112
3113 int
3114 ctl_lun_map_deinit(struct ctl_port *port)
3115 {
3116         struct ctl_softc *softc = control_softc;
3117         struct ctl_lun *lun;
3118
3119         if (port->lun_map == NULL)
3120                 return (0);
3121         free(port->lun_map, M_CTL);
3122         port->lun_map = NULL;
3123         if (port->status & CTL_PORT_STATUS_ONLINE &&
3124             port->lun_enable != NULL) {
3125                 STAILQ_FOREACH(lun, &softc->lun_list, links)
3126                         port->lun_enable(port->targ_lun_arg, lun->lun);
3127         }
3128         return (0);
3129 }
3130
3131 int
3132 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3133 {
3134         int status;
3135         uint32_t old;
3136
3137         if (port->lun_map == NULL) {
3138                 status = ctl_lun_map_init(port);
3139                 if (status != 0)
3140                         return (status);
3141         }
3142         old = port->lun_map[plun];
3143         port->lun_map[plun] = glun;
3144         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS &&
3145             port->lun_enable != NULL)
3146                 port->lun_enable(port->targ_lun_arg, plun);
3147         return (0);
3148 }
3149
3150 int
3151 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3152 {
3153         uint32_t old;
3154
3155         if (port->lun_map == NULL)
3156                 return (0);
3157         old = port->lun_map[plun];
3158         port->lun_map[plun] = UINT32_MAX;
3159         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS &&
3160             port->lun_disable != NULL)
3161                 port->lun_disable(port->targ_lun_arg, plun);
3162         return (0);
3163 }
3164
3165 uint32_t
3166 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3167 {
3168
3169         if (port == NULL)
3170                 return (UINT32_MAX);
3171         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3172                 return (lun_id);
3173         return (port->lun_map[lun_id]);
3174 }
3175
3176 uint32_t
3177 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3178 {
3179         uint32_t i;
3180
3181         if (port == NULL)
3182                 return (UINT32_MAX);
3183         if (port->lun_map == NULL)
3184                 return (lun_id);
3185         for (i = 0; i < CTL_MAX_LUNS; i++) {
3186                 if (port->lun_map[i] == lun_id)
3187                         return (i);
3188         }
3189         return (UINT32_MAX);
3190 }
3191
3192 static struct ctl_port *
3193 ctl_io_port(struct ctl_io_hdr *io_hdr)
3194 {
3195         int port_num;
3196
3197         port_num = io_hdr->nexus.targ_port;
3198         return (control_softc->ctl_ports[ctl_port_idx(port_num)]);
3199 }
3200
3201 /*
3202  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3203  * that are a power of 2.
3204  */
3205 int
3206 ctl_ffz(uint32_t *mask, uint32_t size)
3207 {
3208         uint32_t num_chunks, num_pieces;
3209         int i, j;
3210
3211         num_chunks = (size >> 5);
3212         if (num_chunks == 0)
3213                 num_chunks++;
3214         num_pieces = MIN((sizeof(uint32_t) * 8), size);
3215
3216         for (i = 0; i < num_chunks; i++) {
3217                 for (j = 0; j < num_pieces; j++) {
3218                         if ((mask[i] & (1 << j)) == 0)
3219                                 return ((i << 5) + j);
3220                 }
3221         }
3222
3223         return (-1);
3224 }
3225
3226 int
3227 ctl_set_mask(uint32_t *mask, uint32_t bit)
3228 {
3229         uint32_t chunk, piece;
3230
3231         chunk = bit >> 5;
3232         piece = bit % (sizeof(uint32_t) * 8);
3233
3234         if ((mask[chunk] & (1 << piece)) != 0)
3235                 return (-1);
3236         else
3237                 mask[chunk] |= (1 << piece);
3238
3239         return (0);
3240 }
3241
3242 int
3243 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3244 {
3245         uint32_t chunk, piece;
3246
3247         chunk = bit >> 5;
3248         piece = bit % (sizeof(uint32_t) * 8);
3249
3250         if ((mask[chunk] & (1 << piece)) == 0)
3251                 return (-1);
3252         else
3253                 mask[chunk] &= ~(1 << piece);
3254
3255         return (0);
3256 }
3257
3258 int
3259 ctl_is_set(uint32_t *mask, uint32_t bit)
3260 {
3261         uint32_t chunk, piece;
3262
3263         chunk = bit >> 5;
3264         piece = bit % (sizeof(uint32_t) * 8);
3265
3266         if ((mask[chunk] & (1 << piece)) == 0)
3267                 return (0);
3268         else
3269                 return (1);
3270 }
3271
3272 static uint64_t
3273 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3274 {
3275         uint64_t *t;
3276
3277         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3278         if (t == NULL)
3279                 return (0);
3280         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3281 }
3282
3283 static void
3284 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3285 {
3286         uint64_t *t;
3287
3288         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3289         if (t == NULL)
3290                 return;
3291         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3292 }
3293
3294 static void
3295 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3296 {
3297         uint64_t *p;
3298         u_int i;
3299
3300         i = residx/CTL_MAX_INIT_PER_PORT;
3301         if (lun->pr_keys[i] != NULL)
3302                 return;
3303         mtx_unlock(&lun->lun_lock);
3304         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3305             M_WAITOK | M_ZERO);
3306         mtx_lock(&lun->lun_lock);
3307         if (lun->pr_keys[i] == NULL)
3308                 lun->pr_keys[i] = p;
3309         else
3310                 free(p, M_CTL);
3311 }
3312
3313 static void
3314 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3315 {
3316         uint64_t *t;
3317
3318         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3319         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3320         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3321 }
3322
3323 /*
3324  * ctl_softc, pool_name, total_ctl_io are passed in.
3325  * npool is passed out.
3326  */
3327 int
3328 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3329                 uint32_t total_ctl_io, void **npool)
3330 {
3331 #ifdef IO_POOLS
3332         struct ctl_io_pool *pool;
3333
3334         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3335                                             M_NOWAIT | M_ZERO);
3336         if (pool == NULL)
3337                 return (ENOMEM);
3338
3339         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3340         pool->ctl_softc = ctl_softc;
3341         pool->zone = uma_zsecond_create(pool->name, NULL,
3342             NULL, NULL, NULL, ctl_softc->io_zone);
3343         /* uma_prealloc(pool->zone, total_ctl_io); */
3344
3345         *npool = pool;
3346 #else
3347         *npool = ctl_softc->io_zone;
3348 #endif
3349         return (0);
3350 }
3351
3352 void
3353 ctl_pool_free(struct ctl_io_pool *pool)
3354 {
3355
3356         if (pool == NULL)
3357                 return;
3358
3359 #ifdef IO_POOLS
3360         uma_zdestroy(pool->zone);
3361         free(pool, M_CTL);
3362 #endif
3363 }
3364
3365 union ctl_io *
3366 ctl_alloc_io(void *pool_ref)
3367 {
3368         union ctl_io *io;
3369 #ifdef IO_POOLS
3370         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3371
3372         io = uma_zalloc(pool->zone, M_WAITOK);
3373 #else
3374         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3375 #endif
3376         if (io != NULL)
3377                 io->io_hdr.pool = pool_ref;
3378         return (io);
3379 }
3380
3381 union ctl_io *
3382 ctl_alloc_io_nowait(void *pool_ref)
3383 {
3384         union ctl_io *io;
3385 #ifdef IO_POOLS
3386         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3387
3388         io = uma_zalloc(pool->zone, M_NOWAIT);
3389 #else
3390         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3391 #endif
3392         if (io != NULL)
3393                 io->io_hdr.pool = pool_ref;
3394         return (io);
3395 }
3396
3397 void
3398 ctl_free_io(union ctl_io *io)
3399 {
3400 #ifdef IO_POOLS
3401         struct ctl_io_pool *pool;
3402 #endif
3403
3404         if (io == NULL)
3405                 return;
3406
3407 #ifdef IO_POOLS
3408         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3409         uma_zfree(pool->zone, io);
3410 #else
3411         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3412 #endif
3413 }
3414
3415 void
3416 ctl_zero_io(union ctl_io *io)
3417 {
3418         void *pool_ref;
3419
3420         if (io == NULL)
3421                 return;
3422
3423         /*
3424          * May need to preserve linked list pointers at some point too.
3425          */
3426         pool_ref = io->io_hdr.pool;
3427         memset(io, 0, sizeof(*io));
3428         io->io_hdr.pool = pool_ref;
3429 }
3430
3431 /*
3432  * This routine is currently used for internal copies of ctl_ios that need
3433  * to persist for some reason after we've already returned status to the
3434  * FETD.  (Thus the flag set.)
3435  *
3436  * XXX XXX
3437  * Note that this makes a blind copy of all fields in the ctl_io, except
3438  * for the pool reference.  This includes any memory that has been
3439  * allocated!  That memory will no longer be valid after done has been
3440  * called, so this would be VERY DANGEROUS for command that actually does
3441  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3442  * start and stop commands, which don't transfer any data, so this is not a
3443  * problem.  If it is used for anything else, the caller would also need to
3444  * allocate data buffer space and this routine would need to be modified to
3445  * copy the data buffer(s) as well.
3446  */
3447 void
3448 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3449 {
3450         void *pool_ref;
3451
3452         if ((src == NULL)
3453          || (dest == NULL))
3454                 return;
3455
3456         /*
3457          * May need to preserve linked list pointers at some point too.
3458          */
3459         pool_ref = dest->io_hdr.pool;
3460
3461         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3462
3463         dest->io_hdr.pool = pool_ref;
3464         /*
3465          * We need to know that this is an internal copy, and doesn't need
3466          * to get passed back to the FETD that allocated it.
3467          */
3468         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3469 }
3470
3471 int
3472 ctl_expand_number(const char *buf, uint64_t *num)
3473 {
3474         char *endptr;
3475         uint64_t number;
3476         unsigned shift;
3477
3478         number = strtoq(buf, &endptr, 0);
3479
3480         switch (tolower((unsigned char)*endptr)) {
3481         case 'e':
3482                 shift = 60;
3483                 break;
3484         case 'p':
3485                 shift = 50;
3486                 break;
3487         case 't':
3488                 shift = 40;
3489                 break;
3490         case 'g':
3491                 shift = 30;
3492                 break;
3493         case 'm':
3494                 shift = 20;
3495                 break;
3496         case 'k':
3497                 shift = 10;
3498                 break;
3499         case 'b':
3500         case '\0': /* No unit. */
3501                 *num = number;
3502                 return (0);
3503         default:
3504                 /* Unrecognized unit. */
3505                 return (-1);
3506         }
3507
3508         if ((number << shift) >> shift != number) {
3509                 /* Overflow */
3510                 return (-1);
3511         }
3512         *num = number << shift;
3513         return (0);
3514 }
3515
3516
3517 /*
3518  * This routine could be used in the future to load default and/or saved
3519  * mode page parameters for a particuar lun.
3520  */
3521 static int
3522 ctl_init_page_index(struct ctl_lun *lun)
3523 {
3524         int i;
3525         struct ctl_page_index *page_index;
3526         const char *value;
3527         uint64_t ival;
3528
3529         memcpy(&lun->mode_pages.index, page_index_template,
3530                sizeof(page_index_template));
3531
3532         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3533
3534                 page_index = &lun->mode_pages.index[i];
3535                 /*
3536                  * If this is a disk-only mode page, there's no point in
3537                  * setting it up.  For some pages, we have to have some
3538                  * basic information about the disk in order to calculate the
3539                  * mode page data.
3540                  */
3541                 if ((lun->be_lun->lun_type != T_DIRECT)
3542                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3543                         continue;
3544
3545                 switch (page_index->page_code & SMPH_PC_MASK) {
3546                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3547                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3548                                 panic("subpage is incorrect!");
3549                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3550                                &rw_er_page_default,
3551                                sizeof(rw_er_page_default));
3552                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3553                                &rw_er_page_changeable,
3554                                sizeof(rw_er_page_changeable));
3555                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3556                                &rw_er_page_default,
3557                                sizeof(rw_er_page_default));
3558                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3559                                &rw_er_page_default,
3560                                sizeof(rw_er_page_default));
3561                         page_index->page_data =
3562                                 (uint8_t *)lun->mode_pages.rw_er_page;
3563                         break;
3564                 }
3565                 case SMS_FORMAT_DEVICE_PAGE: {
3566                         struct scsi_format_page *format_page;
3567
3568                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3569                                 panic("subpage is incorrect!");
3570
3571                         /*
3572                          * Sectors per track are set above.  Bytes per
3573                          * sector need to be set here on a per-LUN basis.
3574                          */
3575                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3576                                &format_page_default,
3577                                sizeof(format_page_default));
3578                         memcpy(&lun->mode_pages.format_page[
3579                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3580                                sizeof(format_page_changeable));
3581                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3582                                &format_page_default,
3583                                sizeof(format_page_default));
3584                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3585                                &format_page_default,
3586                                sizeof(format_page_default));
3587
3588                         format_page = &lun->mode_pages.format_page[
3589                                 CTL_PAGE_CURRENT];
3590                         scsi_ulto2b(lun->be_lun->blocksize,
3591                                     format_page->bytes_per_sector);
3592
3593                         format_page = &lun->mode_pages.format_page[
3594                                 CTL_PAGE_DEFAULT];
3595                         scsi_ulto2b(lun->be_lun->blocksize,
3596                                     format_page->bytes_per_sector);
3597
3598                         format_page = &lun->mode_pages.format_page[
3599                                 CTL_PAGE_SAVED];
3600                         scsi_ulto2b(lun->be_lun->blocksize,
3601                                     format_page->bytes_per_sector);
3602
3603                         page_index->page_data =
3604                                 (uint8_t *)lun->mode_pages.format_page;
3605                         break;
3606                 }
3607                 case SMS_RIGID_DISK_PAGE: {
3608                         struct scsi_rigid_disk_page *rigid_disk_page;
3609                         uint32_t sectors_per_cylinder;
3610                         uint64_t cylinders;
3611 #ifndef __XSCALE__
3612                         int shift;
3613 #endif /* !__XSCALE__ */
3614
3615                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3616                                 panic("invalid subpage value %d",
3617                                       page_index->subpage);
3618
3619                         /*
3620                          * Rotation rate and sectors per track are set
3621                          * above.  We calculate the cylinders here based on
3622                          * capacity.  Due to the number of heads and
3623                          * sectors per track we're using, smaller arrays
3624                          * may turn out to have 0 cylinders.  Linux and
3625                          * FreeBSD don't pay attention to these mode pages
3626                          * to figure out capacity, but Solaris does.  It
3627                          * seems to deal with 0 cylinders just fine, and
3628                          * works out a fake geometry based on the capacity.
3629                          */
3630                         memcpy(&lun->mode_pages.rigid_disk_page[
3631                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3632                                sizeof(rigid_disk_page_default));
3633                         memcpy(&lun->mode_pages.rigid_disk_page[
3634                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3635                                sizeof(rigid_disk_page_changeable));
3636
3637                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3638                                 CTL_DEFAULT_HEADS;
3639
3640                         /*
3641                          * The divide method here will be more accurate,
3642                          * probably, but results in floating point being
3643                          * used in the kernel on i386 (__udivdi3()).  On the
3644                          * XScale, though, __udivdi3() is implemented in
3645                          * software.
3646                          *
3647                          * The shift method for cylinder calculation is
3648                          * accurate if sectors_per_cylinder is a power of
3649                          * 2.  Otherwise it might be slightly off -- you
3650                          * might have a bit of a truncation problem.
3651                          */
3652 #ifdef  __XSCALE__
3653                         cylinders = (lun->be_lun->maxlba + 1) /
3654                                 sectors_per_cylinder;
3655 #else
3656                         for (shift = 31; shift > 0; shift--) {
3657                                 if (sectors_per_cylinder & (1 << shift))
3658                                         break;
3659                         }
3660                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
3661 #endif
3662
3663                         /*
3664                          * We've basically got 3 bytes, or 24 bits for the
3665                          * cylinder size in the mode page.  If we're over,
3666                          * just round down to 2^24.
3667                          */
3668                         if (cylinders > 0xffffff)
3669                                 cylinders = 0xffffff;
3670
3671                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3672                                 CTL_PAGE_DEFAULT];
3673                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3674
3675                         if ((value = ctl_get_opt(&lun->be_lun->options,
3676                             "rpm")) != NULL) {
3677                                 scsi_ulto2b(strtol(value, NULL, 0),
3678                                      rigid_disk_page->rotation_rate);
3679                         }
3680
3681                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3682                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3683                                sizeof(rigid_disk_page_default));
3684                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3685                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3686                                sizeof(rigid_disk_page_default));
3687
3688                         page_index->page_data =
3689                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
3690                         break;
3691                 }
3692                 case SMS_CACHING_PAGE: {
3693                         struct scsi_caching_page *caching_page;
3694
3695                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3696                                 panic("invalid subpage value %d",
3697                                       page_index->subpage);
3698                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3699                                &caching_page_default,
3700                                sizeof(caching_page_default));
3701                         memcpy(&lun->mode_pages.caching_page[
3702                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3703                                sizeof(caching_page_changeable));
3704                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3705                                &caching_page_default,
3706                                sizeof(caching_page_default));
3707                         caching_page = &lun->mode_pages.caching_page[
3708                             CTL_PAGE_SAVED];
3709                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
3710                         if (value != NULL && strcmp(value, "off") == 0)
3711                                 caching_page->flags1 &= ~SCP_WCE;
3712                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
3713                         if (value != NULL && strcmp(value, "off") == 0)
3714                                 caching_page->flags1 |= SCP_RCD;
3715                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3716                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3717                                sizeof(caching_page_default));
3718                         page_index->page_data =
3719                                 (uint8_t *)lun->mode_pages.caching_page;
3720                         break;
3721                 }
3722                 case SMS_CONTROL_MODE_PAGE: {
3723                         struct scsi_control_page *control_page;
3724
3725                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3726                                 panic("invalid subpage value %d",
3727                                       page_index->subpage);
3728
3729                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
3730                                &control_page_default,
3731                                sizeof(control_page_default));
3732                         memcpy(&lun->mode_pages.control_page[
3733                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
3734                                sizeof(control_page_changeable));
3735                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
3736                                &control_page_default,
3737                                sizeof(control_page_default));
3738                         control_page = &lun->mode_pages.control_page[
3739                             CTL_PAGE_SAVED];
3740                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
3741                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
3742                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
3743                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
3744                         }
3745                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
3746                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
3747                                sizeof(control_page_default));
3748                         page_index->page_data =
3749                                 (uint8_t *)lun->mode_pages.control_page;
3750                         break;
3751
3752                 }
3753                 case SMS_INFO_EXCEPTIONS_PAGE: {
3754                         switch (page_index->subpage) {
3755                         case SMS_SUBPAGE_PAGE_0:
3756                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
3757                                        &ie_page_default,
3758                                        sizeof(ie_page_default));
3759                                 memcpy(&lun->mode_pages.ie_page[
3760                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
3761                                        sizeof(ie_page_changeable));
3762                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
3763                                        &ie_page_default,
3764                                        sizeof(ie_page_default));
3765                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
3766                                        &ie_page_default,
3767                                        sizeof(ie_page_default));
3768                                 page_index->page_data =
3769                                         (uint8_t *)lun->mode_pages.ie_page;
3770                                 break;
3771                         case 0x02: {
3772                                 struct ctl_logical_block_provisioning_page *page;
3773
3774                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
3775                                        &lbp_page_default,
3776                                        sizeof(lbp_page_default));
3777                                 memcpy(&lun->mode_pages.lbp_page[
3778                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
3779                                        sizeof(lbp_page_changeable));
3780                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3781                                        &lbp_page_default,
3782                                        sizeof(lbp_page_default));
3783                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
3784                                 value = ctl_get_opt(&lun->be_lun->options,
3785                                     "avail-threshold");
3786                                 if (value != NULL &&
3787                                     ctl_expand_number(value, &ival) == 0) {
3788                                         page->descr[0].flags |= SLBPPD_ENABLED |
3789                                             SLBPPD_ARMING_DEC;
3790                                         if (lun->be_lun->blocksize)
3791                                                 ival /= lun->be_lun->blocksize;
3792                                         else
3793                                                 ival /= 512;
3794                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3795                                             page->descr[0].count);
3796                                 }
3797                                 value = ctl_get_opt(&lun->be_lun->options,
3798                                     "used-threshold");
3799                                 if (value != NULL &&
3800                                     ctl_expand_number(value, &ival) == 0) {
3801                                         page->descr[1].flags |= SLBPPD_ENABLED |
3802                                             SLBPPD_ARMING_INC;
3803                                         if (lun->be_lun->blocksize)
3804                                                 ival /= lun->be_lun->blocksize;
3805                                         else
3806                                                 ival /= 512;
3807                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3808                                             page->descr[1].count);
3809                                 }
3810                                 value = ctl_get_opt(&lun->be_lun->options,
3811                                     "pool-avail-threshold");
3812                                 if (value != NULL &&
3813                                     ctl_expand_number(value, &ival) == 0) {
3814                                         page->descr[2].flags |= SLBPPD_ENABLED |
3815                                             SLBPPD_ARMING_DEC;
3816                                         if (lun->be_lun->blocksize)
3817                                                 ival /= lun->be_lun->blocksize;
3818                                         else
3819                                                 ival /= 512;
3820                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3821                                             page->descr[2].count);
3822                                 }
3823                                 value = ctl_get_opt(&lun->be_lun->options,
3824                                     "pool-used-threshold");
3825                                 if (value != NULL &&
3826                                     ctl_expand_number(value, &ival) == 0) {
3827                                         page->descr[3].flags |= SLBPPD_ENABLED |
3828                                             SLBPPD_ARMING_INC;
3829                                         if (lun->be_lun->blocksize)
3830                                                 ival /= lun->be_lun->blocksize;
3831                                         else
3832                                                 ival /= 512;
3833                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3834                                             page->descr[3].count);
3835                                 }
3836                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
3837                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3838                                        sizeof(lbp_page_default));
3839                                 page_index->page_data =
3840                                         (uint8_t *)lun->mode_pages.lbp_page;
3841                         }}
3842                         break;
3843                 }
3844                 case SMS_VENDOR_SPECIFIC_PAGE:{
3845                         switch (page_index->subpage) {
3846                         case DBGCNF_SUBPAGE_CODE: {
3847                                 struct copan_debugconf_subpage *current_page,
3848                                                                *saved_page;
3849
3850                                 memcpy(&lun->mode_pages.debugconf_subpage[
3851                                        CTL_PAGE_CURRENT],
3852                                        &debugconf_page_default,
3853                                        sizeof(debugconf_page_default));
3854                                 memcpy(&lun->mode_pages.debugconf_subpage[
3855                                        CTL_PAGE_CHANGEABLE],
3856                                        &debugconf_page_changeable,
3857                                        sizeof(debugconf_page_changeable));
3858                                 memcpy(&lun->mode_pages.debugconf_subpage[
3859                                        CTL_PAGE_DEFAULT],
3860                                        &debugconf_page_default,
3861                                        sizeof(debugconf_page_default));
3862                                 memcpy(&lun->mode_pages.debugconf_subpage[
3863                                        CTL_PAGE_SAVED],
3864                                        &debugconf_page_default,
3865                                        sizeof(debugconf_page_default));
3866                                 page_index->page_data =
3867                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
3868
3869                                 current_page = (struct copan_debugconf_subpage *)
3870                                         (page_index->page_data +
3871                                          (page_index->page_len *
3872                                           CTL_PAGE_CURRENT));
3873                                 saved_page = (struct copan_debugconf_subpage *)
3874                                         (page_index->page_data +
3875                                          (page_index->page_len *
3876                                           CTL_PAGE_SAVED));
3877                                 break;
3878                         }
3879                         default:
3880                                 panic("invalid subpage value %d",
3881                                       page_index->subpage);
3882                                 break;
3883                         }
3884                         break;
3885                 }
3886                 default:
3887                         panic("invalid page value %d",
3888                               page_index->page_code & SMPH_PC_MASK);
3889                         break;
3890         }
3891         }
3892
3893         return (CTL_RETVAL_COMPLETE);
3894 }
3895
3896 static int
3897 ctl_init_log_page_index(struct ctl_lun *lun)
3898 {
3899         struct ctl_page_index *page_index;
3900         int i, j, k, prev;
3901
3902         memcpy(&lun->log_pages.index, log_page_index_template,
3903                sizeof(log_page_index_template));
3904
3905         prev = -1;
3906         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
3907
3908                 page_index = &lun->log_pages.index[i];
3909                 /*
3910                  * If this is a disk-only mode page, there's no point in
3911                  * setting it up.  For some pages, we have to have some
3912                  * basic information about the disk in order to calculate the
3913                  * mode page data.
3914                  */
3915                 if ((lun->be_lun->lun_type != T_DIRECT)
3916                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3917                         continue;
3918
3919                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
3920                      lun->backend->lun_attr == NULL)
3921                         continue;
3922
3923                 if (page_index->page_code != prev) {
3924                         lun->log_pages.pages_page[j] = page_index->page_code;
3925                         prev = page_index->page_code;
3926                         j++;
3927                 }
3928                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
3929                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
3930                 k++;
3931         }
3932         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
3933         lun->log_pages.index[0].page_len = j;
3934         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
3935         lun->log_pages.index[1].page_len = k * 2;
3936         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
3937         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
3938         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
3939         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
3940
3941         return (CTL_RETVAL_COMPLETE);
3942 }
3943
3944 static int
3945 hex2bin(const char *str, uint8_t *buf, int buf_size)
3946 {
3947         int i;
3948         u_char c;
3949
3950         memset(buf, 0, buf_size);
3951         while (isspace(str[0]))
3952                 str++;
3953         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
3954                 str += 2;
3955         buf_size *= 2;
3956         for (i = 0; str[i] != 0 && i < buf_size; i++) {
3957                 c = str[i];
3958                 if (isdigit(c))
3959                         c -= '0';
3960                 else if (isalpha(c))
3961                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
3962                 else
3963                         break;
3964                 if (c >= 16)
3965                         break;
3966                 if ((i & 1) == 0)
3967                         buf[i / 2] |= (c << 4);
3968                 else
3969                         buf[i / 2] |= c;
3970         }
3971         return ((i + 1) / 2);
3972 }
3973
3974 /*
3975  * LUN allocation.
3976  *
3977  * Requirements:
3978  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
3979  *   wants us to allocate the LUN and he can block.
3980  * - ctl_softc is always set
3981  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
3982  *
3983  * Returns 0 for success, non-zero (errno) for failure.
3984  */
3985 static int
3986 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
3987               struct ctl_be_lun *const be_lun)
3988 {
3989         struct ctl_lun *nlun, *lun;
3990         struct scsi_vpd_id_descriptor *desc;
3991         struct scsi_vpd_id_t10 *t10id;
3992         const char *eui, *naa, *scsiname, *vendor, *value;
3993         int lun_number, i, lun_malloced;
3994         int devidlen, idlen1, idlen2 = 0, len;
3995
3996         if (be_lun == NULL)
3997                 return (EINVAL);
3998
3999         /*
4000          * We currently only support Direct Access or Processor LUN types.
4001          */
4002         switch (be_lun->lun_type) {
4003         case T_DIRECT:
4004                 break;
4005         case T_PROCESSOR:
4006                 break;
4007         case T_SEQUENTIAL:
4008         case T_CHANGER:
4009         default:
4010                 be_lun->lun_config_status(be_lun->be_lun,
4011                                           CTL_LUN_CONFIG_FAILURE);
4012                 break;
4013         }
4014         if (ctl_lun == NULL) {
4015                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4016                 lun_malloced = 1;
4017         } else {
4018                 lun_malloced = 0;
4019                 lun = ctl_lun;
4020         }
4021
4022         memset(lun, 0, sizeof(*lun));
4023         if (lun_malloced)
4024                 lun->flags = CTL_LUN_MALLOCED;
4025
4026         /* Generate LUN ID. */
4027         devidlen = max(CTL_DEVID_MIN_LEN,
4028             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4029         idlen1 = sizeof(*t10id) + devidlen;
4030         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4031         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4032         if (scsiname != NULL) {
4033                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4034                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4035         }
4036         eui = ctl_get_opt(&be_lun->options, "eui");
4037         if (eui != NULL) {
4038                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4039         }
4040         naa = ctl_get_opt(&be_lun->options, "naa");
4041         if (naa != NULL) {
4042                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4043         }
4044         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4045             M_CTL, M_WAITOK | M_ZERO);
4046         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4047         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4048         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4049         desc->length = idlen1;
4050         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4051         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4052         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4053                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4054         } else {
4055                 strncpy(t10id->vendor, vendor,
4056                     min(sizeof(t10id->vendor), strlen(vendor)));
4057         }
4058         strncpy((char *)t10id->vendor_spec_id,
4059             (char *)be_lun->device_id, devidlen);
4060         if (scsiname != NULL) {
4061                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4062                     desc->length);
4063                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4064                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4065                     SVPD_ID_TYPE_SCSI_NAME;
4066                 desc->length = idlen2;
4067                 strlcpy(desc->identifier, scsiname, idlen2);
4068         }
4069         if (eui != NULL) {
4070                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4071                     desc->length);
4072                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4073                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4074                     SVPD_ID_TYPE_EUI64;
4075                 desc->length = hex2bin(eui, desc->identifier, 16);
4076                 desc->length = desc->length > 12 ? 16 :
4077                     (desc->length > 8 ? 12 : 8);
4078                 len -= 16 - desc->length;
4079         }
4080         if (naa != NULL) {
4081                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4082                     desc->length);
4083                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4084                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4085                     SVPD_ID_TYPE_NAA;
4086                 desc->length = hex2bin(naa, desc->identifier, 16);
4087                 desc->length = desc->length > 8 ? 16 : 8;
4088                 len -= 16 - desc->length;
4089         }
4090         lun->lun_devid->len = len;
4091
4092         mtx_lock(&ctl_softc->ctl_lock);
4093         /*
4094          * See if the caller requested a particular LUN number.  If so, see
4095          * if it is available.  Otherwise, allocate the first available LUN.
4096          */
4097         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4098                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4099                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4100                         mtx_unlock(&ctl_softc->ctl_lock);
4101                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4102                                 printf("ctl: requested LUN ID %d is higher "
4103                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4104                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4105                         } else {
4106                                 /*
4107                                  * XXX KDM return an error, or just assign
4108                                  * another LUN ID in this case??
4109                                  */
4110                                 printf("ctl: requested LUN ID %d is already "
4111                                        "in use\n", be_lun->req_lun_id);
4112                         }
4113                         if (lun->flags & CTL_LUN_MALLOCED)
4114                                 free(lun, M_CTL);
4115                         be_lun->lun_config_status(be_lun->be_lun,
4116                                                   CTL_LUN_CONFIG_FAILURE);
4117                         return (ENOSPC);
4118                 }
4119                 lun_number = be_lun->req_lun_id;
4120         } else {
4121                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4122                 if (lun_number == -1) {
4123                         mtx_unlock(&ctl_softc->ctl_lock);
4124                         printf("ctl: can't allocate LUN, out of LUNs\n");
4125                         if (lun->flags & CTL_LUN_MALLOCED)
4126                                 free(lun, M_CTL);
4127                         be_lun->lun_config_status(be_lun->be_lun,
4128                                                   CTL_LUN_CONFIG_FAILURE);
4129                         return (ENOSPC);
4130                 }
4131         }
4132         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4133
4134         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4135         lun->lun = lun_number;
4136         lun->be_lun = be_lun;
4137         /*
4138          * The processor LUN is always enabled.  Disk LUNs come on line
4139          * disabled, and must be enabled by the backend.
4140          */
4141         lun->flags |= CTL_LUN_DISABLED;
4142         lun->backend = be_lun->be;
4143         be_lun->ctl_lun = lun;
4144         be_lun->lun_id = lun_number;
4145         atomic_add_int(&be_lun->be->num_luns, 1);
4146         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4147                 lun->flags |= CTL_LUN_OFFLINE;
4148
4149         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4150                 lun->flags |= CTL_LUN_STOPPED;
4151
4152         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4153                 lun->flags |= CTL_LUN_INOPERABLE;
4154
4155         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4156                 lun->flags |= CTL_LUN_PRIMARY_SC;
4157
4158         value = ctl_get_opt(&be_lun->options, "readonly");
4159         if (value != NULL && strcmp(value, "on") == 0)
4160                 lun->flags |= CTL_LUN_READONLY;
4161
4162         lun->serseq = CTL_LUN_SERSEQ_OFF;
4163         if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4164                 lun->serseq = CTL_LUN_SERSEQ_READ;
4165         value = ctl_get_opt(&be_lun->options, "serseq");
4166         if (value != NULL && strcmp(value, "on") == 0)
4167                 lun->serseq = CTL_LUN_SERSEQ_ON;
4168         else if (value != NULL && strcmp(value, "read") == 0)
4169                 lun->serseq = CTL_LUN_SERSEQ_READ;
4170         else if (value != NULL && strcmp(value, "off") == 0)
4171                 lun->serseq = CTL_LUN_SERSEQ_OFF;
4172
4173         lun->ctl_softc = ctl_softc;
4174 #ifdef CTL_TIME_IO
4175         lun->last_busy = getsbinuptime();
4176 #endif
4177         TAILQ_INIT(&lun->ooa_queue);
4178         TAILQ_INIT(&lun->blocked_queue);
4179         STAILQ_INIT(&lun->error_list);
4180         ctl_tpc_lun_init(lun);
4181
4182         /*
4183          * Initialize the mode and log page index.
4184          */
4185         ctl_init_page_index(lun);
4186         ctl_init_log_page_index(lun);
4187
4188         /*
4189          * Now, before we insert this lun on the lun list, set the lun
4190          * inventory changed UA for all other luns.
4191          */
4192         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4193                 mtx_lock(&nlun->lun_lock);
4194                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4195                 mtx_unlock(&nlun->lun_lock);
4196         }
4197
4198         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4199
4200         ctl_softc->ctl_luns[lun_number] = lun;
4201
4202         ctl_softc->num_luns++;
4203
4204         /* Setup statistics gathering */
4205         lun->stats.device_type = be_lun->lun_type;
4206         lun->stats.lun_number = lun_number;
4207         if (lun->stats.device_type == T_DIRECT)
4208                 lun->stats.blocksize = be_lun->blocksize;
4209         else
4210                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4211         for (i = 0;i < CTL_MAX_PORTS;i++)
4212                 lun->stats.ports[i].targ_port = i;
4213
4214         mtx_unlock(&ctl_softc->ctl_lock);
4215
4216         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4217         return (0);
4218 }
4219
4220 /*
4221  * Delete a LUN.
4222  * Assumptions:
4223  * - LUN has already been marked invalid and any pending I/O has been taken
4224  *   care of.
4225  */
4226 static int
4227 ctl_free_lun(struct ctl_lun *lun)
4228 {
4229         struct ctl_softc *softc;
4230         struct ctl_lun *nlun;
4231         int i;
4232
4233         softc = lun->ctl_softc;
4234
4235         mtx_assert(&softc->ctl_lock, MA_OWNED);
4236
4237         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4238
4239         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4240
4241         softc->ctl_luns[lun->lun] = NULL;
4242
4243         if (!TAILQ_EMPTY(&lun->ooa_queue))
4244                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4245
4246         softc->num_luns--;
4247
4248         /*
4249          * Tell the backend to free resources, if this LUN has a backend.
4250          */
4251         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4252         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4253
4254         ctl_tpc_lun_shutdown(lun);
4255         mtx_destroy(&lun->lun_lock);
4256         free(lun->lun_devid, M_CTL);
4257         for (i = 0; i < CTL_MAX_PORTS; i++)
4258                 free(lun->pending_ua[i], M_CTL);
4259         for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4260                 free(lun->pr_keys[i], M_CTL);
4261         free(lun->write_buffer, M_CTL);
4262         if (lun->flags & CTL_LUN_MALLOCED)
4263                 free(lun, M_CTL);
4264
4265         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4266                 mtx_lock(&nlun->lun_lock);
4267                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4268                 mtx_unlock(&nlun->lun_lock);
4269         }
4270
4271         return (0);
4272 }
4273
4274 static void
4275 ctl_create_lun(struct ctl_be_lun *be_lun)
4276 {
4277         struct ctl_softc *softc;
4278
4279         softc = control_softc;
4280
4281         /*
4282          * ctl_alloc_lun() should handle all potential failure cases.
4283          */
4284         ctl_alloc_lun(softc, NULL, be_lun);
4285 }
4286
4287 int
4288 ctl_add_lun(struct ctl_be_lun *be_lun)
4289 {
4290         struct ctl_softc *softc = control_softc;
4291
4292         mtx_lock(&softc->ctl_lock);
4293         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4294         mtx_unlock(&softc->ctl_lock);
4295         wakeup(&softc->pending_lun_queue);
4296
4297         return (0);
4298 }
4299
4300 int
4301 ctl_enable_lun(struct ctl_be_lun *be_lun)
4302 {
4303         struct ctl_softc *softc;
4304         struct ctl_port *port, *nport;
4305         struct ctl_lun *lun;
4306         int retval;
4307
4308         lun = (struct ctl_lun *)be_lun->ctl_lun;
4309         softc = lun->ctl_softc;
4310
4311         mtx_lock(&softc->ctl_lock);
4312         mtx_lock(&lun->lun_lock);
4313         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4314                 /*
4315                  * eh?  Why did we get called if the LUN is already
4316                  * enabled?
4317                  */
4318                 mtx_unlock(&lun->lun_lock);
4319                 mtx_unlock(&softc->ctl_lock);
4320                 return (0);
4321         }
4322         lun->flags &= ~CTL_LUN_DISABLED;
4323         mtx_unlock(&lun->lun_lock);
4324
4325         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4326                 nport = STAILQ_NEXT(port, links);
4327                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4328                     port->lun_map != NULL || port->lun_enable == NULL)
4329                         continue;
4330
4331                 /*
4332                  * Drop the lock while we call the FETD's enable routine.
4333                  * This can lead to a callback into CTL (at least in the
4334                  * case of the internal initiator frontend.
4335                  */
4336                 mtx_unlock(&softc->ctl_lock);
4337                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4338                 mtx_lock(&softc->ctl_lock);
4339                 if (retval != 0) {
4340                         printf("%s: FETD %s port %d returned error "
4341                                "%d for lun_enable on lun %jd\n",
4342                                __func__, port->port_name, port->targ_port,
4343                                retval, (intmax_t)lun->lun);
4344                 }
4345         }
4346
4347         mtx_unlock(&softc->ctl_lock);
4348
4349         return (0);
4350 }
4351
4352 int
4353 ctl_disable_lun(struct ctl_be_lun *be_lun)
4354 {
4355         struct ctl_softc *softc;
4356         struct ctl_port *port;
4357         struct ctl_lun *lun;
4358         int retval;
4359
4360         lun = (struct ctl_lun *)be_lun->ctl_lun;
4361         softc = lun->ctl_softc;
4362
4363         mtx_lock(&softc->ctl_lock);
4364         mtx_lock(&lun->lun_lock);
4365         if (lun->flags & CTL_LUN_DISABLED) {
4366                 mtx_unlock(&lun->lun_lock);
4367                 mtx_unlock(&softc->ctl_lock);
4368                 return (0);
4369         }
4370         lun->flags |= CTL_LUN_DISABLED;
4371         mtx_unlock(&lun->lun_lock);
4372
4373         STAILQ_FOREACH(port, &softc->port_list, links) {
4374                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4375                     port->lun_map != NULL || port->lun_disable == NULL)
4376                         continue;
4377
4378                 /*
4379                  * Drop the lock before we call the frontend's disable
4380                  * routine, to avoid lock order reversals.
4381                  *
4382                  * XXX KDM what happens if the frontend list changes while
4383                  * we're traversing it?  It's unlikely, but should be handled.
4384                  */
4385                 mtx_unlock(&softc->ctl_lock);
4386                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4387                 mtx_lock(&softc->ctl_lock);
4388                 if (retval != 0) {
4389                         printf("%s: FETD %s port %d returned error "
4390                                "%d for lun_disable on lun %jd\n",
4391                                __func__, port->port_name, port->targ_port,
4392                                retval, (intmax_t)lun->lun);
4393                 }
4394         }
4395
4396         mtx_unlock(&softc->ctl_lock);
4397
4398         return (0);
4399 }
4400
4401 int
4402 ctl_start_lun(struct ctl_be_lun *be_lun)
4403 {
4404         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4405
4406         mtx_lock(&lun->lun_lock);
4407         lun->flags &= ~CTL_LUN_STOPPED;
4408         mtx_unlock(&lun->lun_lock);
4409         return (0);
4410 }
4411
4412 int
4413 ctl_stop_lun(struct ctl_be_lun *be_lun)
4414 {
4415         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4416
4417         mtx_lock(&lun->lun_lock);
4418         lun->flags |= CTL_LUN_STOPPED;
4419         mtx_unlock(&lun->lun_lock);
4420         return (0);
4421 }
4422
4423 int
4424 ctl_lun_offline(struct ctl_be_lun *be_lun)
4425 {
4426         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4427
4428         mtx_lock(&lun->lun_lock);
4429         lun->flags |= CTL_LUN_OFFLINE;
4430         mtx_unlock(&lun->lun_lock);
4431         return (0);
4432 }
4433
4434 int
4435 ctl_lun_online(struct ctl_be_lun *be_lun)
4436 {
4437         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4438
4439         mtx_lock(&lun->lun_lock);
4440         lun->flags &= ~CTL_LUN_OFFLINE;
4441         mtx_unlock(&lun->lun_lock);
4442         return (0);
4443 }
4444
4445 int
4446 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4447 {
4448         struct ctl_softc *softc;
4449         struct ctl_lun *lun;
4450
4451         lun = (struct ctl_lun *)be_lun->ctl_lun;
4452         softc = lun->ctl_softc;
4453
4454         mtx_lock(&lun->lun_lock);
4455
4456         /*
4457          * The LUN needs to be disabled before it can be marked invalid.
4458          */
4459         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4460                 mtx_unlock(&lun->lun_lock);
4461                 return (-1);
4462         }
4463         /*
4464          * Mark the LUN invalid.
4465          */
4466         lun->flags |= CTL_LUN_INVALID;
4467
4468         /*
4469          * If there is nothing in the OOA queue, go ahead and free the LUN.
4470          * If we have something in the OOA queue, we'll free it when the
4471          * last I/O completes.
4472          */
4473         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4474                 mtx_unlock(&lun->lun_lock);
4475                 mtx_lock(&softc->ctl_lock);
4476                 ctl_free_lun(lun);
4477                 mtx_unlock(&softc->ctl_lock);
4478         } else
4479                 mtx_unlock(&lun->lun_lock);
4480
4481         return (0);
4482 }
4483
4484 int
4485 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4486 {
4487         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4488
4489         mtx_lock(&lun->lun_lock);
4490         lun->flags |= CTL_LUN_INOPERABLE;
4491         mtx_unlock(&lun->lun_lock);
4492         return (0);
4493 }
4494
4495 int
4496 ctl_lun_operable(struct ctl_be_lun *be_lun)
4497 {
4498         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4499
4500         mtx_lock(&lun->lun_lock);
4501         lun->flags &= ~CTL_LUN_INOPERABLE;
4502         mtx_unlock(&lun->lun_lock);
4503         return (0);
4504 }
4505
4506 void
4507 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4508 {
4509         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4510
4511         mtx_lock(&lun->lun_lock);
4512         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4513         mtx_unlock(&lun->lun_lock);
4514 }
4515
4516 /*
4517  * Backend "memory move is complete" callback for requests that never
4518  * make it down to say RAIDCore's configuration code.
4519  */
4520 int
4521 ctl_config_move_done(union ctl_io *io)
4522 {
4523         int retval;
4524
4525         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4526         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4527             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4528
4529         if ((io->io_hdr.port_status != 0) &&
4530             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4531              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4532                 /*
4533                  * For hardware error sense keys, the sense key
4534                  * specific value is defined to be a retry count,
4535                  * but we use it to pass back an internal FETD
4536                  * error code.  XXX KDM  Hopefully the FETD is only
4537                  * using 16 bits for an error code, since that's
4538                  * all the space we have in the sks field.
4539                  */
4540                 ctl_set_internal_failure(&io->scsiio,
4541                                          /*sks_valid*/ 1,
4542                                          /*retry_count*/
4543                                          io->io_hdr.port_status);
4544         }
4545
4546         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4547             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4548              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4549             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4550                 /*
4551                  * XXX KDM just assuming a single pointer here, and not a
4552                  * S/G list.  If we start using S/G lists for config data,
4553                  * we'll need to know how to clean them up here as well.
4554                  */
4555                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4556                         free(io->scsiio.kern_data_ptr, M_CTL);
4557                 ctl_done(io);
4558                 retval = CTL_RETVAL_COMPLETE;
4559         } else {
4560                 /*
4561                  * XXX KDM now we need to continue data movement.  Some
4562                  * options:
4563                  * - call ctl_scsiio() again?  We don't do this for data
4564                  *   writes, because for those at least we know ahead of
4565                  *   time where the write will go and how long it is.  For
4566                  *   config writes, though, that information is largely
4567                  *   contained within the write itself, thus we need to
4568                  *   parse out the data again.
4569                  *
4570                  * - Call some other function once the data is in?
4571                  */
4572                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
4573                         ctl_data_print(io);
4574
4575                 /*
4576                  * XXX KDM call ctl_scsiio() again for now, and check flag
4577                  * bits to see whether we're allocated or not.
4578                  */
4579                 retval = ctl_scsiio(&io->scsiio);
4580         }
4581         return (retval);
4582 }
4583
4584 /*
4585  * This gets called by a backend driver when it is done with a
4586  * data_submit method.
4587  */
4588 void
4589 ctl_data_submit_done(union ctl_io *io)
4590 {
4591         /*
4592          * If the IO_CONT flag is set, we need to call the supplied
4593          * function to continue processing the I/O, instead of completing
4594          * the I/O just yet.
4595          *
4596          * If there is an error, though, we don't want to keep processing.
4597          * Instead, just send status back to the initiator.
4598          */
4599         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4600             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4601             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4602              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4603                 io->scsiio.io_cont(io);
4604                 return;
4605         }
4606         ctl_done(io);
4607 }
4608
4609 /*
4610  * This gets called by a backend driver when it is done with a
4611  * configuration write.
4612  */
4613 void
4614 ctl_config_write_done(union ctl_io *io)
4615 {
4616         uint8_t *buf;
4617
4618         /*
4619          * If the IO_CONT flag is set, we need to call the supplied
4620          * function to continue processing the I/O, instead of completing
4621          * the I/O just yet.
4622          *
4623          * If there is an error, though, we don't want to keep processing.
4624          * Instead, just send status back to the initiator.
4625          */
4626         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4627             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4628             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4629              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4630                 io->scsiio.io_cont(io);
4631                 return;
4632         }
4633         /*
4634          * Since a configuration write can be done for commands that actually
4635          * have data allocated, like write buffer, and commands that have
4636          * no data, like start/stop unit, we need to check here.
4637          */
4638         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4639                 buf = io->scsiio.kern_data_ptr;
4640         else
4641                 buf = NULL;
4642         ctl_done(io);
4643         if (buf)
4644                 free(buf, M_CTL);
4645 }
4646
4647 void
4648 ctl_config_read_done(union ctl_io *io)
4649 {
4650         uint8_t *buf;
4651
4652         /*
4653          * If there is some error -- we are done, skip data transfer.
4654          */
4655         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
4656             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4657              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
4658                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4659                         buf = io->scsiio.kern_data_ptr;
4660                 else
4661                         buf = NULL;
4662                 ctl_done(io);
4663                 if (buf)
4664                         free(buf, M_CTL);
4665                 return;
4666         }
4667
4668         /*
4669          * If the IO_CONT flag is set, we need to call the supplied
4670          * function to continue processing the I/O, instead of completing
4671          * the I/O just yet.
4672          */
4673         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
4674                 io->scsiio.io_cont(io);
4675                 return;
4676         }
4677
4678         ctl_datamove(io);
4679 }
4680
4681 /*
4682  * SCSI release command.
4683  */
4684 int
4685 ctl_scsi_release(struct ctl_scsiio *ctsio)
4686 {
4687         int length, longid, thirdparty_id, resv_id;
4688         struct ctl_lun *lun;
4689         uint32_t residx;
4690
4691         length = 0;
4692         resv_id = 0;
4693
4694         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
4695
4696         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
4697         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4698
4699         switch (ctsio->cdb[0]) {
4700         case RELEASE_10: {
4701                 struct scsi_release_10 *cdb;
4702
4703                 cdb = (struct scsi_release_10 *)ctsio->cdb;
4704
4705                 if (cdb->byte2 & SR10_LONGID)
4706                         longid = 1;
4707                 else
4708                         thirdparty_id = cdb->thirdparty_id;
4709
4710                 resv_id = cdb->resv_id;
4711                 length = scsi_2btoul(cdb->length);
4712                 break;
4713         }
4714         }
4715
4716
4717         /*
4718          * XXX KDM right now, we only support LUN reservation.  We don't
4719          * support 3rd party reservations, or extent reservations, which
4720          * might actually need the parameter list.  If we've gotten this
4721          * far, we've got a LUN reservation.  Anything else got kicked out
4722          * above.  So, according to SPC, ignore the length.
4723          */
4724         length = 0;
4725
4726         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4727          && (length > 0)) {
4728                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4729                 ctsio->kern_data_len = length;
4730                 ctsio->kern_total_len = length;
4731                 ctsio->kern_data_resid = 0;
4732                 ctsio->kern_rel_offset = 0;
4733                 ctsio->kern_sg_entries = 0;
4734                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4735                 ctsio->be_move_done = ctl_config_move_done;
4736                 ctl_datamove((union ctl_io *)ctsio);
4737
4738                 return (CTL_RETVAL_COMPLETE);
4739         }
4740
4741         if (length > 0)
4742                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4743
4744         mtx_lock(&lun->lun_lock);
4745
4746         /*
4747          * According to SPC, it is not an error for an intiator to attempt
4748          * to release a reservation on a LUN that isn't reserved, or that
4749          * is reserved by another initiator.  The reservation can only be
4750          * released, though, by the initiator who made it or by one of
4751          * several reset type events.
4752          */
4753         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
4754                         lun->flags &= ~CTL_LUN_RESERVED;
4755
4756         mtx_unlock(&lun->lun_lock);
4757
4758         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
4759                 free(ctsio->kern_data_ptr, M_CTL);
4760                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
4761         }
4762
4763         ctl_set_success(ctsio);
4764         ctl_done((union ctl_io *)ctsio);
4765         return (CTL_RETVAL_COMPLETE);
4766 }
4767
4768 int
4769 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
4770 {
4771         int extent, thirdparty, longid;
4772         int resv_id, length;
4773         uint64_t thirdparty_id;
4774         struct ctl_lun *lun;
4775         uint32_t residx;
4776
4777         extent = 0;
4778         thirdparty = 0;
4779         longid = 0;
4780         resv_id = 0;
4781         length = 0;
4782         thirdparty_id = 0;
4783
4784         CTL_DEBUG_PRINT(("ctl_reserve\n"));
4785
4786         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
4787         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4788
4789         switch (ctsio->cdb[0]) {
4790         case RESERVE_10: {
4791                 struct scsi_reserve_10 *cdb;
4792
4793                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
4794
4795                 if (cdb->byte2 & SR10_LONGID)
4796                         longid = 1;
4797                 else
4798                         thirdparty_id = cdb->thirdparty_id;
4799
4800                 resv_id = cdb->resv_id;
4801                 length = scsi_2btoul(cdb->length);
4802                 break;
4803         }
4804         }
4805
4806         /*
4807          * XXX KDM right now, we only support LUN reservation.  We don't
4808          * support 3rd party reservations, or extent reservations, which
4809          * might actually need the parameter list.  If we've gotten this
4810          * far, we've got a LUN reservation.  Anything else got kicked out
4811          * above.  So, according to SPC, ignore the length.
4812          */
4813         length = 0;
4814
4815         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4816          && (length > 0)) {
4817                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4818                 ctsio->kern_data_len = length;
4819                 ctsio->kern_total_len = length;
4820                 ctsio->kern_data_resid = 0;
4821                 ctsio->kern_rel_offset = 0;
4822                 ctsio->kern_sg_entries = 0;
4823                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4824                 ctsio->be_move_done = ctl_config_move_done;
4825                 ctl_datamove((union ctl_io *)ctsio);
4826
4827                 return (CTL_RETVAL_COMPLETE);
4828         }
4829
4830         if (length > 0)
4831                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4832
4833         mtx_lock(&lun->lun_lock);
4834         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
4835                 ctl_set_reservation_conflict(ctsio);
4836                 goto bailout;
4837         }
4838
4839         lun->flags |= CTL_LUN_RESERVED;
4840         lun->res_idx = residx;
4841
4842         ctl_set_success(ctsio);
4843
4844 bailout:
4845         mtx_unlock(&lun->lun_lock);
4846
4847         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
4848                 free(ctsio->kern_data_ptr, M_CTL);
4849                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
4850         }
4851
4852         ctl_done((union ctl_io *)ctsio);
4853         return (CTL_RETVAL_COMPLETE);
4854 }
4855
4856 int
4857 ctl_start_stop(struct ctl_scsiio *ctsio)
4858 {
4859         struct scsi_start_stop_unit *cdb;
4860         struct ctl_lun *lun;
4861         int retval;
4862
4863         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
4864
4865         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4866         retval = 0;
4867
4868         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
4869
4870         /*
4871          * XXX KDM
4872          * We don't support the immediate bit on a stop unit.  In order to
4873          * do that, we would need to code up a way to know that a stop is
4874          * pending, and hold off any new commands until it completes, one
4875          * way or another.  Then we could accept or reject those commands
4876          * depending on its status.  We would almost need to do the reverse
4877          * of what we do below for an immediate start -- return the copy of
4878          * the ctl_io to the FETD with status to send to the host (and to
4879          * free the copy!) and then free the original I/O once the stop
4880          * actually completes.  That way, the OOA queue mechanism can work
4881          * to block commands that shouldn't proceed.  Another alternative
4882          * would be to put the copy in the queue in place of the original,
4883          * and return the original back to the caller.  That could be
4884          * slightly safer..
4885          */
4886         if ((cdb->byte2 & SSS_IMMED)
4887          && ((cdb->how & SSS_START) == 0)) {
4888                 ctl_set_invalid_field(ctsio,
4889                                       /*sks_valid*/ 1,
4890                                       /*command*/ 1,
4891                                       /*field*/ 1,
4892                                       /*bit_valid*/ 1,
4893                                       /*bit*/ 0);
4894                 ctl_done((union ctl_io *)ctsio);
4895                 return (CTL_RETVAL_COMPLETE);
4896         }
4897
4898         if ((lun->flags & CTL_LUN_PR_RESERVED)
4899          && ((cdb->how & SSS_START)==0)) {
4900                 uint32_t residx;
4901
4902                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
4903                 if (ctl_get_prkey(lun, residx) == 0
4904                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
4905
4906                         ctl_set_reservation_conflict(ctsio);
4907                         ctl_done((union ctl_io *)ctsio);
4908                         return (CTL_RETVAL_COMPLETE);
4909                 }
4910         }
4911
4912         /*
4913          * If there is no backend on this device, we can't start or stop
4914          * it.  In theory we shouldn't get any start/stop commands in the
4915          * first place at this level if the LUN doesn't have a backend.
4916          * That should get stopped by the command decode code.
4917          */
4918         if (lun->backend == NULL) {
4919                 ctl_set_invalid_opcode(ctsio);
4920                 ctl_done((union ctl_io *)ctsio);
4921                 return (CTL_RETVAL_COMPLETE);
4922         }
4923
4924         /*
4925          * XXX KDM Copan-specific offline behavior.
4926          * Figure out a reasonable way to port this?
4927          */
4928 #ifdef NEEDTOPORT
4929         mtx_lock(&lun->lun_lock);
4930
4931         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
4932          && (lun->flags & CTL_LUN_OFFLINE)) {
4933                 /*
4934                  * If the LUN is offline, and the on/offline bit isn't set,
4935                  * reject the start or stop.  Otherwise, let it through.
4936                  */
4937                 mtx_unlock(&lun->lun_lock);
4938                 ctl_set_lun_not_ready(ctsio);
4939                 ctl_done((union ctl_io *)ctsio);
4940         } else {
4941                 mtx_unlock(&lun->lun_lock);
4942 #endif /* NEEDTOPORT */
4943                 /*
4944                  * This could be a start or a stop when we're online,
4945                  * or a stop/offline or start/online.  A start or stop when
4946                  * we're offline is covered in the case above.
4947                  */
4948                 /*
4949                  * In the non-immediate case, we send the request to
4950                  * the backend and return status to the user when
4951                  * it is done.
4952                  *
4953                  * In the immediate case, we allocate a new ctl_io
4954                  * to hold a copy of the request, and send that to
4955                  * the backend.  We then set good status on the
4956                  * user's request and return it immediately.
4957                  */
4958                 if (cdb->byte2 & SSS_IMMED) {
4959                         union ctl_io *new_io;
4960
4961                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
4962                         ctl_copy_io((union ctl_io *)ctsio, new_io);
4963                         retval = lun->backend->config_write(new_io);
4964                         ctl_set_success(ctsio);
4965                         ctl_done((union ctl_io *)ctsio);
4966                 } else {
4967                         retval = lun->backend->config_write(
4968                                 (union ctl_io *)ctsio);
4969                 }
4970 #ifdef NEEDTOPORT
4971         }
4972 #endif
4973         return (retval);
4974 }
4975
4976 /*
4977  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
4978  * we don't really do anything with the LBA and length fields if the user
4979  * passes them in.  Instead we'll just flush out the cache for the entire
4980  * LUN.
4981  */
4982 int
4983 ctl_sync_cache(struct ctl_scsiio *ctsio)
4984 {
4985         struct ctl_lun *lun;
4986         struct ctl_softc *softc;
4987         struct ctl_lba_len_flags *lbalen;
4988         uint64_t starting_lba;
4989         uint32_t block_count;
4990         int retval;
4991         uint8_t byte2;
4992
4993         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
4994
4995         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4996         softc = lun->ctl_softc;
4997         retval = 0;
4998
4999         switch (ctsio->cdb[0]) {
5000         case SYNCHRONIZE_CACHE: {
5001                 struct scsi_sync_cache *cdb;
5002                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5003
5004                 starting_lba = scsi_4btoul(cdb->begin_lba);
5005                 block_count = scsi_2btoul(cdb->lb_count);
5006                 byte2 = cdb->byte2;
5007                 break;
5008         }
5009         case SYNCHRONIZE_CACHE_16: {
5010                 struct scsi_sync_cache_16 *cdb;
5011                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5012
5013                 starting_lba = scsi_8btou64(cdb->begin_lba);
5014                 block_count = scsi_4btoul(cdb->lb_count);
5015                 byte2 = cdb->byte2;
5016                 break;
5017         }
5018         default:
5019                 ctl_set_invalid_opcode(ctsio);
5020                 ctl_done((union ctl_io *)ctsio);
5021                 goto bailout;
5022                 break; /* NOTREACHED */
5023         }
5024
5025         /*
5026          * We check the LBA and length, but don't do anything with them.
5027          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5028          * get flushed.  This check will just help satisfy anyone who wants
5029          * to see an error for an out of range LBA.
5030          */
5031         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5032                 ctl_set_lba_out_of_range(ctsio);
5033                 ctl_done((union ctl_io *)ctsio);
5034                 goto bailout;
5035         }
5036
5037         /*
5038          * If this LUN has no backend, we can't flush the cache anyway.
5039          */
5040         if (lun->backend == NULL) {
5041                 ctl_set_invalid_opcode(ctsio);
5042                 ctl_done((union ctl_io *)ctsio);
5043                 goto bailout;
5044         }
5045
5046         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5047         lbalen->lba = starting_lba;
5048         lbalen->len = block_count;
5049         lbalen->flags = byte2;
5050
5051         /*
5052          * Check to see whether we're configured to send the SYNCHRONIZE
5053          * CACHE command directly to the back end.
5054          */
5055         mtx_lock(&lun->lun_lock);
5056         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5057          && (++(lun->sync_count) >= lun->sync_interval)) {
5058                 lun->sync_count = 0;
5059                 mtx_unlock(&lun->lun_lock);
5060                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5061         } else {
5062                 mtx_unlock(&lun->lun_lock);
5063                 ctl_set_success(ctsio);
5064                 ctl_done((union ctl_io *)ctsio);
5065         }
5066
5067 bailout:
5068
5069         return (retval);
5070 }
5071
5072 int
5073 ctl_format(struct ctl_scsiio *ctsio)
5074 {
5075         struct scsi_format *cdb;
5076         struct ctl_lun *lun;
5077         int length, defect_list_len;
5078
5079         CTL_DEBUG_PRINT(("ctl_format\n"));
5080
5081         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5082
5083         cdb = (struct scsi_format *)ctsio->cdb;
5084
5085         length = 0;
5086         if (cdb->byte2 & SF_FMTDATA) {
5087                 if (cdb->byte2 & SF_LONGLIST)
5088                         length = sizeof(struct scsi_format_header_long);
5089                 else
5090                         length = sizeof(struct scsi_format_header_short);
5091         }
5092
5093         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5094          && (length > 0)) {
5095                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5096                 ctsio->kern_data_len = length;
5097                 ctsio->kern_total_len = length;
5098                 ctsio->kern_data_resid = 0;
5099                 ctsio->kern_rel_offset = 0;
5100                 ctsio->kern_sg_entries = 0;
5101                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5102                 ctsio->be_move_done = ctl_config_move_done;
5103                 ctl_datamove((union ctl_io *)ctsio);
5104
5105                 return (CTL_RETVAL_COMPLETE);
5106         }
5107
5108         defect_list_len = 0;
5109
5110         if (cdb->byte2 & SF_FMTDATA) {
5111                 if (cdb->byte2 & SF_LONGLIST) {
5112                         struct scsi_format_header_long *header;
5113
5114                         header = (struct scsi_format_header_long *)
5115                                 ctsio->kern_data_ptr;
5116
5117                         defect_list_len = scsi_4btoul(header->defect_list_len);
5118                         if (defect_list_len != 0) {
5119                                 ctl_set_invalid_field(ctsio,
5120                                                       /*sks_valid*/ 1,
5121                                                       /*command*/ 0,
5122                                                       /*field*/ 2,
5123                                                       /*bit_valid*/ 0,
5124                                                       /*bit*/ 0);
5125                                 goto bailout;
5126                         }
5127                 } else {
5128                         struct scsi_format_header_short *header;
5129
5130                         header = (struct scsi_format_header_short *)
5131                                 ctsio->kern_data_ptr;
5132
5133                         defect_list_len = scsi_2btoul(header->defect_list_len);
5134                         if (defect_list_len != 0) {
5135                                 ctl_set_invalid_field(ctsio,
5136                                                       /*sks_valid*/ 1,
5137                                                       /*command*/ 0,
5138                                                       /*field*/ 2,
5139                                                       /*bit_valid*/ 0,
5140                                                       /*bit*/ 0);
5141                                 goto bailout;
5142                         }
5143                 }
5144         }
5145
5146         /*
5147          * The format command will clear out the "Medium format corrupted"
5148          * status if set by the configuration code.  That status is really
5149          * just a way to notify the host that we have lost the media, and
5150          * get them to issue a command that will basically make them think
5151          * they're blowing away the media.
5152          */
5153         mtx_lock(&lun->lun_lock);
5154         lun->flags &= ~CTL_LUN_INOPERABLE;
5155         mtx_unlock(&lun->lun_lock);
5156
5157         ctl_set_success(ctsio);
5158 bailout:
5159
5160         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5161                 free(ctsio->kern_data_ptr, M_CTL);
5162                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5163         }
5164
5165         ctl_done((union ctl_io *)ctsio);
5166         return (CTL_RETVAL_COMPLETE);
5167 }
5168
5169 int
5170 ctl_read_buffer(struct ctl_scsiio *ctsio)
5171 {
5172         struct scsi_read_buffer *cdb;
5173         struct ctl_lun *lun;
5174         int buffer_offset, len;
5175         static uint8_t descr[4];
5176         static uint8_t echo_descr[4] = { 0 };
5177
5178         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5179
5180         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5181         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5182
5183         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5184             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5185             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5186                 ctl_set_invalid_field(ctsio,
5187                                       /*sks_valid*/ 1,
5188                                       /*command*/ 1,
5189                                       /*field*/ 1,
5190                                       /*bit_valid*/ 1,
5191                                       /*bit*/ 4);
5192                 ctl_done((union ctl_io *)ctsio);
5193                 return (CTL_RETVAL_COMPLETE);
5194         }
5195
5196         len = scsi_3btoul(cdb->length);
5197         buffer_offset = scsi_3btoul(cdb->offset);
5198
5199         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5200                 ctl_set_invalid_field(ctsio,
5201                                       /*sks_valid*/ 1,
5202                                       /*command*/ 1,
5203                                       /*field*/ 6,
5204                                       /*bit_valid*/ 0,
5205                                       /*bit*/ 0);
5206                 ctl_done((union ctl_io *)ctsio);
5207                 return (CTL_RETVAL_COMPLETE);
5208         }
5209
5210         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5211                 descr[0] = 0;
5212                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5213                 ctsio->kern_data_ptr = descr;
5214                 len = min(len, sizeof(descr));
5215         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5216                 ctsio->kern_data_ptr = echo_descr;
5217                 len = min(len, sizeof(echo_descr));
5218         } else {
5219                 if (lun->write_buffer == NULL) {
5220                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5221                             M_CTL, M_WAITOK);
5222                 }
5223                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5224         }
5225         ctsio->kern_data_len = len;
5226         ctsio->kern_total_len = len;
5227         ctsio->kern_data_resid = 0;
5228         ctsio->kern_rel_offset = 0;
5229         ctsio->kern_sg_entries = 0;
5230         ctl_set_success(ctsio);
5231         ctsio->be_move_done = ctl_config_move_done;
5232         ctl_datamove((union ctl_io *)ctsio);
5233         return (CTL_RETVAL_COMPLETE);
5234 }
5235
5236 int
5237 ctl_write_buffer(struct ctl_scsiio *ctsio)
5238 {
5239         struct scsi_write_buffer *cdb;
5240         struct ctl_lun *lun;
5241         int buffer_offset, len;
5242
5243         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5244
5245         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5246         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5247
5248         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5249                 ctl_set_invalid_field(ctsio,
5250                                       /*sks_valid*/ 1,
5251                                       /*command*/ 1,
5252                                       /*field*/ 1,
5253                                       /*bit_valid*/ 1,
5254                                       /*bit*/ 4);
5255                 ctl_done((union ctl_io *)ctsio);
5256                 return (CTL_RETVAL_COMPLETE);
5257         }
5258
5259         len = scsi_3btoul(cdb->length);
5260         buffer_offset = scsi_3btoul(cdb->offset);
5261
5262         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5263                 ctl_set_invalid_field(ctsio,
5264                                       /*sks_valid*/ 1,
5265                                       /*command*/ 1,
5266                                       /*field*/ 6,
5267                                       /*bit_valid*/ 0,
5268                                       /*bit*/ 0);
5269                 ctl_done((union ctl_io *)ctsio);
5270                 return (CTL_RETVAL_COMPLETE);
5271         }
5272
5273         /*
5274          * If we've got a kernel request that hasn't been malloced yet,
5275          * malloc it and tell the caller the data buffer is here.
5276          */
5277         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5278                 if (lun->write_buffer == NULL) {
5279                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5280                             M_CTL, M_WAITOK);
5281                 }
5282                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5283                 ctsio->kern_data_len = len;
5284                 ctsio->kern_total_len = len;
5285                 ctsio->kern_data_resid = 0;
5286                 ctsio->kern_rel_offset = 0;
5287                 ctsio->kern_sg_entries = 0;
5288                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5289                 ctsio->be_move_done = ctl_config_move_done;
5290                 ctl_datamove((union ctl_io *)ctsio);
5291
5292                 return (CTL_RETVAL_COMPLETE);
5293         }
5294
5295         ctl_set_success(ctsio);
5296         ctl_done((union ctl_io *)ctsio);
5297         return (CTL_RETVAL_COMPLETE);
5298 }
5299
5300 int
5301 ctl_write_same(struct ctl_scsiio *ctsio)
5302 {
5303         struct ctl_lun *lun;
5304         struct ctl_lba_len_flags *lbalen;
5305         uint64_t lba;
5306         uint32_t num_blocks;
5307         int len, retval;
5308         uint8_t byte2;
5309
5310         retval = CTL_RETVAL_COMPLETE;
5311
5312         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5313
5314         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5315
5316         switch (ctsio->cdb[0]) {
5317         case WRITE_SAME_10: {
5318                 struct scsi_write_same_10 *cdb;
5319
5320                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5321
5322                 lba = scsi_4btoul(cdb->addr);
5323                 num_blocks = scsi_2btoul(cdb->length);
5324                 byte2 = cdb->byte2;
5325                 break;
5326         }
5327         case WRITE_SAME_16: {
5328                 struct scsi_write_same_16 *cdb;
5329
5330                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5331
5332                 lba = scsi_8btou64(cdb->addr);
5333                 num_blocks = scsi_4btoul(cdb->length);
5334                 byte2 = cdb->byte2;
5335                 break;
5336         }
5337         default:
5338                 /*
5339                  * We got a command we don't support.  This shouldn't
5340                  * happen, commands should be filtered out above us.
5341                  */
5342                 ctl_set_invalid_opcode(ctsio);
5343                 ctl_done((union ctl_io *)ctsio);
5344
5345                 return (CTL_RETVAL_COMPLETE);
5346                 break; /* NOTREACHED */
5347         }
5348
5349         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5350         if ((byte2 & SWS_UNMAP) == 0 &&
5351             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5352                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5353                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5354                 ctl_done((union ctl_io *)ctsio);
5355                 return (CTL_RETVAL_COMPLETE);
5356         }
5357
5358         /*
5359          * The first check is to make sure we're in bounds, the second
5360          * check is to catch wrap-around problems.  If the lba + num blocks
5361          * is less than the lba, then we've wrapped around and the block
5362          * range is invalid anyway.
5363          */
5364         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5365          || ((lba + num_blocks) < lba)) {
5366                 ctl_set_lba_out_of_range(ctsio);
5367                 ctl_done((union ctl_io *)ctsio);
5368                 return (CTL_RETVAL_COMPLETE);
5369         }
5370
5371         /* Zero number of blocks means "to the last logical block" */
5372         if (num_blocks == 0) {
5373                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5374                         ctl_set_invalid_field(ctsio,
5375                                               /*sks_valid*/ 0,
5376                                               /*command*/ 1,
5377                                               /*field*/ 0,
5378                                               /*bit_valid*/ 0,
5379                                               /*bit*/ 0);
5380                         ctl_done((union ctl_io *)ctsio);
5381                         return (CTL_RETVAL_COMPLETE);
5382                 }
5383                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5384         }
5385
5386         len = lun->be_lun->blocksize;
5387
5388         /*
5389          * If we've got a kernel request that hasn't been malloced yet,
5390          * malloc it and tell the caller the data buffer is here.
5391          */
5392         if ((byte2 & SWS_NDOB) == 0 &&
5393             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5394                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5395                 ctsio->kern_data_len = len;
5396                 ctsio->kern_total_len = len;
5397                 ctsio->kern_data_resid = 0;
5398                 ctsio->kern_rel_offset = 0;
5399                 ctsio->kern_sg_entries = 0;
5400                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5401                 ctsio->be_move_done = ctl_config_move_done;
5402                 ctl_datamove((union ctl_io *)ctsio);
5403
5404                 return (CTL_RETVAL_COMPLETE);
5405         }
5406
5407         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5408         lbalen->lba = lba;
5409         lbalen->len = num_blocks;
5410         lbalen->flags = byte2;
5411         retval = lun->backend->config_write((union ctl_io *)ctsio);
5412
5413         return (retval);
5414 }
5415
5416 int
5417 ctl_unmap(struct ctl_scsiio *ctsio)
5418 {
5419         struct ctl_lun *lun;
5420         struct scsi_unmap *cdb;
5421         struct ctl_ptr_len_flags *ptrlen;
5422         struct scsi_unmap_header *hdr;
5423         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5424         uint64_t lba;
5425         uint32_t num_blocks;
5426         int len, retval;
5427         uint8_t byte2;
5428
5429         retval = CTL_RETVAL_COMPLETE;
5430
5431         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5432
5433         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5434         cdb = (struct scsi_unmap *)ctsio->cdb;
5435
5436         len = scsi_2btoul(cdb->length);
5437         byte2 = cdb->byte2;
5438
5439         /*
5440          * If we've got a kernel request that hasn't been malloced yet,
5441          * malloc it and tell the caller the data buffer is here.
5442          */
5443         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5444                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5445                 ctsio->kern_data_len = len;
5446                 ctsio->kern_total_len = len;
5447                 ctsio->kern_data_resid = 0;
5448                 ctsio->kern_rel_offset = 0;
5449                 ctsio->kern_sg_entries = 0;
5450                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5451                 ctsio->be_move_done = ctl_config_move_done;
5452                 ctl_datamove((union ctl_io *)ctsio);
5453
5454                 return (CTL_RETVAL_COMPLETE);
5455         }
5456
5457         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5458         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5459         if (len < sizeof (*hdr) ||
5460             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5461             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5462             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5463                 ctl_set_invalid_field(ctsio,
5464                                       /*sks_valid*/ 0,
5465                                       /*command*/ 0,
5466                                       /*field*/ 0,
5467                                       /*bit_valid*/ 0,
5468                                       /*bit*/ 0);
5469                 goto done;
5470         }
5471         len = scsi_2btoul(hdr->desc_length);
5472         buf = (struct scsi_unmap_desc *)(hdr + 1);
5473         end = buf + len / sizeof(*buf);
5474
5475         endnz = buf;
5476         for (range = buf; range < end; range++) {
5477                 lba = scsi_8btou64(range->lba);
5478                 num_blocks = scsi_4btoul(range->length);
5479                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5480                  || ((lba + num_blocks) < lba)) {
5481                         ctl_set_lba_out_of_range(ctsio);
5482                         ctl_done((union ctl_io *)ctsio);
5483                         return (CTL_RETVAL_COMPLETE);
5484                 }
5485                 if (num_blocks != 0)
5486                         endnz = range + 1;
5487         }
5488
5489         /*
5490          * Block backend can not handle zero last range.
5491          * Filter it out and return if there is nothing left.
5492          */
5493         len = (uint8_t *)endnz - (uint8_t *)buf;
5494         if (len == 0) {
5495                 ctl_set_success(ctsio);
5496                 goto done;
5497         }
5498
5499         mtx_lock(&lun->lun_lock);
5500         ptrlen = (struct ctl_ptr_len_flags *)
5501             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5502         ptrlen->ptr = (void *)buf;
5503         ptrlen->len = len;
5504         ptrlen->flags = byte2;
5505         ctl_check_blocked(lun);
5506         mtx_unlock(&lun->lun_lock);
5507
5508         retval = lun->backend->config_write((union ctl_io *)ctsio);
5509         return (retval);
5510
5511 done:
5512         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5513                 free(ctsio->kern_data_ptr, M_CTL);
5514                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5515         }
5516         ctl_done((union ctl_io *)ctsio);
5517         return (CTL_RETVAL_COMPLETE);
5518 }
5519
5520 /*
5521  * Note that this function currently doesn't actually do anything inside
5522  * CTL to enforce things if the DQue bit is turned on.
5523  *
5524  * Also note that this function can't be used in the default case, because
5525  * the DQue bit isn't set in the changeable mask for the control mode page
5526  * anyway.  This is just here as an example for how to implement a page
5527  * handler, and a placeholder in case we want to allow the user to turn
5528  * tagged queueing on and off.
5529  *
5530  * The D_SENSE bit handling is functional, however, and will turn
5531  * descriptor sense on and off for a given LUN.
5532  */
5533 int
5534 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5535                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5536 {
5537         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5538         struct ctl_lun *lun;
5539         int set_ua;
5540         uint32_t initidx;
5541
5542         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5543         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5544         set_ua = 0;
5545
5546         user_cp = (struct scsi_control_page *)page_ptr;
5547         current_cp = (struct scsi_control_page *)
5548                 (page_index->page_data + (page_index->page_len *
5549                 CTL_PAGE_CURRENT));
5550         saved_cp = (struct scsi_control_page *)
5551                 (page_index->page_data + (page_index->page_len *
5552                 CTL_PAGE_SAVED));
5553
5554         mtx_lock(&lun->lun_lock);
5555         if (((current_cp->rlec & SCP_DSENSE) == 0)
5556          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5557                 /*
5558                  * Descriptor sense is currently turned off and the user
5559                  * wants to turn it on.
5560                  */
5561                 current_cp->rlec |= SCP_DSENSE;
5562                 saved_cp->rlec |= SCP_DSENSE;
5563                 lun->flags |= CTL_LUN_SENSE_DESC;
5564                 set_ua = 1;
5565         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
5566                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
5567                 /*
5568                  * Descriptor sense is currently turned on, and the user
5569                  * wants to turn it off.
5570                  */
5571                 current_cp->rlec &= ~SCP_DSENSE;
5572                 saved_cp->rlec &= ~SCP_DSENSE;
5573                 lun->flags &= ~CTL_LUN_SENSE_DESC;
5574                 set_ua = 1;
5575         }
5576         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5577             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5578                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5579                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5580                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5581                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5582                 set_ua = 1;
5583         }
5584         if ((current_cp->eca_and_aen & SCP_SWP) !=
5585             (user_cp->eca_and_aen & SCP_SWP)) {
5586                 current_cp->eca_and_aen &= ~SCP_SWP;
5587                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5588                 saved_cp->eca_and_aen &= ~SCP_SWP;
5589                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5590                 set_ua = 1;
5591         }
5592         if (set_ua != 0)
5593                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5594         mtx_unlock(&lun->lun_lock);
5595
5596         return (0);
5597 }
5598
5599 int
5600 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5601                      struct ctl_page_index *page_index, uint8_t *page_ptr)
5602 {
5603         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5604         struct ctl_lun *lun;
5605         int set_ua;
5606         uint32_t initidx;
5607
5608         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5609         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5610         set_ua = 0;
5611
5612         user_cp = (struct scsi_caching_page *)page_ptr;
5613         current_cp = (struct scsi_caching_page *)
5614                 (page_index->page_data + (page_index->page_len *
5615                 CTL_PAGE_CURRENT));
5616         saved_cp = (struct scsi_caching_page *)
5617                 (page_index->page_data + (page_index->page_len *
5618                 CTL_PAGE_SAVED));
5619
5620         mtx_lock(&lun->lun_lock);
5621         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5622             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5623                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5624                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5625                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5626                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5627                 set_ua = 1;
5628         }
5629         if (set_ua != 0)
5630                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5631         mtx_unlock(&lun->lun_lock);
5632
5633         return (0);
5634 }
5635
5636 int
5637 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5638                                 struct ctl_page_index *page_index,
5639                                 uint8_t *page_ptr)
5640 {
5641         uint8_t *c;
5642         int i;
5643
5644         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5645         ctl_time_io_secs =
5646                 (c[0] << 8) |
5647                 (c[1] << 0) |
5648                 0;
5649         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5650         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5651         printf("page data:");
5652         for (i=0; i<8; i++)
5653                 printf(" %.2x",page_ptr[i]);
5654         printf("\n");
5655         return (0);
5656 }
5657
5658 int
5659 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5660                                struct ctl_page_index *page_index,
5661                                int pc)
5662 {
5663         struct copan_debugconf_subpage *page;
5664
5665         page = (struct copan_debugconf_subpage *)page_index->page_data +
5666                 (page_index->page_len * pc);
5667
5668         switch (pc) {
5669         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5670         case SMS_PAGE_CTRL_DEFAULT >> 6:
5671         case SMS_PAGE_CTRL_SAVED >> 6:
5672                 /*
5673                  * We don't update the changable or default bits for this page.
5674                  */
5675                 break;
5676         case SMS_PAGE_CTRL_CURRENT >> 6:
5677                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5678                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5679                 break;
5680         default:
5681 #ifdef NEEDTOPORT
5682                 EPRINT(0, "Invalid PC %d!!", pc);
5683 #endif /* NEEDTOPORT */
5684                 break;
5685         }
5686         return (0);
5687 }
5688
5689
5690 static int
5691 ctl_do_mode_select(union ctl_io *io)
5692 {
5693         struct scsi_mode_page_header *page_header;
5694         struct ctl_page_index *page_index;
5695         struct ctl_scsiio *ctsio;
5696         int control_dev, page_len;
5697         int page_len_offset, page_len_size;
5698         union ctl_modepage_info *modepage_info;
5699         struct ctl_lun *lun;
5700         int *len_left, *len_used;
5701         int retval, i;
5702
5703         ctsio = &io->scsiio;
5704         page_index = NULL;
5705         page_len = 0;
5706         retval = CTL_RETVAL_COMPLETE;
5707
5708         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5709
5710         if (lun->be_lun->lun_type != T_DIRECT)
5711                 control_dev = 1;
5712         else
5713                 control_dev = 0;
5714
5715         modepage_info = (union ctl_modepage_info *)
5716                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5717         len_left = &modepage_info->header.len_left;
5718         len_used = &modepage_info->header.len_used;
5719
5720 do_next_page:
5721
5722         page_header = (struct scsi_mode_page_header *)
5723                 (ctsio->kern_data_ptr + *len_used);
5724
5725         if (*len_left == 0) {
5726                 free(ctsio->kern_data_ptr, M_CTL);
5727                 ctl_set_success(ctsio);
5728                 ctl_done((union ctl_io *)ctsio);
5729                 return (CTL_RETVAL_COMPLETE);
5730         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5731
5732                 free(ctsio->kern_data_ptr, M_CTL);
5733                 ctl_set_param_len_error(ctsio);
5734                 ctl_done((union ctl_io *)ctsio);
5735                 return (CTL_RETVAL_COMPLETE);
5736
5737         } else if ((page_header->page_code & SMPH_SPF)
5738                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5739
5740                 free(ctsio->kern_data_ptr, M_CTL);
5741                 ctl_set_param_len_error(ctsio);
5742                 ctl_done((union ctl_io *)ctsio);
5743                 return (CTL_RETVAL_COMPLETE);
5744         }
5745
5746
5747         /*
5748          * XXX KDM should we do something with the block descriptor?
5749          */
5750         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5751
5752                 if ((control_dev != 0)
5753                  && (lun->mode_pages.index[i].page_flags &
5754                      CTL_PAGE_FLAG_DISK_ONLY))
5755                         continue;
5756
5757                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5758                     (page_header->page_code & SMPH_PC_MASK))
5759                         continue;
5760
5761                 /*
5762                  * If neither page has a subpage code, then we've got a
5763                  * match.
5764                  */
5765                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
5766                  && ((page_header->page_code & SMPH_SPF) == 0)) {
5767                         page_index = &lun->mode_pages.index[i];
5768                         page_len = page_header->page_length;
5769                         break;
5770                 }
5771
5772                 /*
5773                  * If both pages have subpages, then the subpage numbers
5774                  * have to match.
5775                  */
5776                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
5777                   && (page_header->page_code & SMPH_SPF)) {
5778                         struct scsi_mode_page_header_sp *sph;
5779
5780                         sph = (struct scsi_mode_page_header_sp *)page_header;
5781
5782                         if (lun->mode_pages.index[i].subpage ==
5783                             sph->subpage) {
5784                                 page_index = &lun->mode_pages.index[i];
5785                                 page_len = scsi_2btoul(sph->page_length);
5786                                 break;
5787                         }
5788                 }
5789         }
5790
5791         /*
5792          * If we couldn't find the page, or if we don't have a mode select
5793          * handler for it, send back an error to the user.
5794          */
5795         if ((page_index == NULL)
5796          || (page_index->select_handler == NULL)) {
5797                 ctl_set_invalid_field(ctsio,
5798                                       /*sks_valid*/ 1,
5799                                       /*command*/ 0,
5800                                       /*field*/ *len_used,
5801                                       /*bit_valid*/ 0,
5802                                       /*bit*/ 0);
5803                 free(ctsio->kern_data_ptr, M_CTL);
5804                 ctl_done((union ctl_io *)ctsio);
5805                 return (CTL_RETVAL_COMPLETE);
5806         }
5807
5808         if (page_index->page_code & SMPH_SPF) {
5809                 page_len_offset = 2;
5810                 page_len_size = 2;
5811         } else {
5812                 page_len_size = 1;
5813                 page_len_offset = 1;
5814         }
5815
5816         /*
5817          * If the length the initiator gives us isn't the one we specify in
5818          * the mode page header, or if they didn't specify enough data in
5819          * the CDB to avoid truncating this page, kick out the request.
5820          */
5821         if ((page_len != (page_index->page_len - page_len_offset -
5822                           page_len_size))
5823          || (*len_left < page_index->page_len)) {
5824
5825
5826                 ctl_set_invalid_field(ctsio,
5827                                       /*sks_valid*/ 1,
5828                                       /*command*/ 0,
5829                                       /*field*/ *len_used + page_len_offset,
5830                                       /*bit_valid*/ 0,
5831                                       /*bit*/ 0);
5832                 free(ctsio->kern_data_ptr, M_CTL);
5833                 ctl_done((union ctl_io *)ctsio);
5834                 return (CTL_RETVAL_COMPLETE);
5835         }
5836
5837         /*
5838          * Run through the mode page, checking to make sure that the bits
5839          * the user changed are actually legal for him to change.
5840          */
5841         for (i = 0; i < page_index->page_len; i++) {
5842                 uint8_t *user_byte, *change_mask, *current_byte;
5843                 int bad_bit;
5844                 int j;
5845
5846                 user_byte = (uint8_t *)page_header + i;
5847                 change_mask = page_index->page_data +
5848                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
5849                 current_byte = page_index->page_data +
5850                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
5851
5852                 /*
5853                  * Check to see whether the user set any bits in this byte
5854                  * that he is not allowed to set.
5855                  */
5856                 if ((*user_byte & ~(*change_mask)) ==
5857                     (*current_byte & ~(*change_mask)))
5858                         continue;
5859
5860                 /*
5861                  * Go through bit by bit to determine which one is illegal.
5862                  */
5863                 bad_bit = 0;
5864                 for (j = 7; j >= 0; j--) {
5865                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
5866                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
5867                                 bad_bit = i;
5868                                 break;
5869                         }
5870                 }
5871                 ctl_set_invalid_field(ctsio,
5872                                       /*sks_valid*/ 1,
5873                                       /*command*/ 0,
5874                                       /*field*/ *len_used + i,
5875                                       /*bit_valid*/ 1,
5876                                       /*bit*/ bad_bit);
5877                 free(ctsio->kern_data_ptr, M_CTL);
5878                 ctl_done((union ctl_io *)ctsio);
5879                 return (CTL_RETVAL_COMPLETE);
5880         }
5881
5882         /*
5883          * Decrement these before we call the page handler, since we may
5884          * end up getting called back one way or another before the handler
5885          * returns to this context.
5886          */
5887         *len_left -= page_index->page_len;
5888         *len_used += page_index->page_len;
5889
5890         retval = page_index->select_handler(ctsio, page_index,
5891                                             (uint8_t *)page_header);
5892
5893         /*
5894          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
5895          * wait until this queued command completes to finish processing
5896          * the mode page.  If it returns anything other than
5897          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
5898          * already set the sense information, freed the data pointer, and
5899          * completed the io for us.
5900          */
5901         if (retval != CTL_RETVAL_COMPLETE)
5902                 goto bailout_no_done;
5903
5904         /*
5905          * If the initiator sent us more than one page, parse the next one.
5906          */
5907         if (*len_left > 0)
5908                 goto do_next_page;
5909
5910         ctl_set_success(ctsio);
5911         free(ctsio->kern_data_ptr, M_CTL);
5912         ctl_done((union ctl_io *)ctsio);
5913
5914 bailout_no_done:
5915
5916         return (CTL_RETVAL_COMPLETE);
5917
5918 }
5919
5920 int
5921 ctl_mode_select(struct ctl_scsiio *ctsio)
5922 {
5923         int param_len, pf, sp;
5924         int header_size, bd_len;
5925         int len_left, len_used;
5926         struct ctl_page_index *page_index;
5927         struct ctl_lun *lun;
5928         int control_dev, page_len;
5929         union ctl_modepage_info *modepage_info;
5930         int retval;
5931
5932         pf = 0;
5933         sp = 0;
5934         page_len = 0;
5935         len_used = 0;
5936         len_left = 0;
5937         retval = 0;
5938         bd_len = 0;
5939         page_index = NULL;
5940
5941         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5942
5943         if (lun->be_lun->lun_type != T_DIRECT)
5944                 control_dev = 1;
5945         else
5946                 control_dev = 0;
5947
5948         switch (ctsio->cdb[0]) {
5949         case MODE_SELECT_6: {
5950                 struct scsi_mode_select_6 *cdb;
5951
5952                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
5953
5954                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
5955                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
5956
5957                 param_len = cdb->length;
5958                 header_size = sizeof(struct scsi_mode_header_6);
5959                 break;
5960         }
5961         case MODE_SELECT_10: {
5962                 struct scsi_mode_select_10 *cdb;
5963
5964                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
5965
5966                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
5967                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
5968
5969                 param_len = scsi_2btoul(cdb->length);
5970                 header_size = sizeof(struct scsi_mode_header_10);
5971                 break;
5972         }
5973         default:
5974                 ctl_set_invalid_opcode(ctsio);
5975                 ctl_done((union ctl_io *)ctsio);
5976                 return (CTL_RETVAL_COMPLETE);
5977                 break; /* NOTREACHED */
5978         }
5979
5980         /*
5981          * From SPC-3:
5982          * "A parameter list length of zero indicates that the Data-Out Buffer
5983          * shall be empty. This condition shall not be considered as an error."
5984          */
5985         if (param_len == 0) {
5986                 ctl_set_success(ctsio);
5987                 ctl_done((union ctl_io *)ctsio);
5988                 return (CTL_RETVAL_COMPLETE);
5989         }
5990
5991         /*
5992          * Since we'll hit this the first time through, prior to
5993          * allocation, we don't need to free a data buffer here.
5994          */
5995         if (param_len < header_size) {
5996                 ctl_set_param_len_error(ctsio);
5997                 ctl_done((union ctl_io *)ctsio);
5998                 return (CTL_RETVAL_COMPLETE);
5999         }
6000
6001         /*
6002          * Allocate the data buffer and grab the user's data.  In theory,
6003          * we shouldn't have to sanity check the parameter list length here
6004          * because the maximum size is 64K.  We should be able to malloc
6005          * that much without too many problems.
6006          */
6007         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6008                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6009                 ctsio->kern_data_len = param_len;
6010                 ctsio->kern_total_len = param_len;
6011                 ctsio->kern_data_resid = 0;
6012                 ctsio->kern_rel_offset = 0;
6013                 ctsio->kern_sg_entries = 0;
6014                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6015                 ctsio->be_move_done = ctl_config_move_done;
6016                 ctl_datamove((union ctl_io *)ctsio);
6017
6018                 return (CTL_RETVAL_COMPLETE);
6019         }
6020
6021         switch (ctsio->cdb[0]) {
6022         case MODE_SELECT_6: {
6023                 struct scsi_mode_header_6 *mh6;
6024
6025                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6026                 bd_len = mh6->blk_desc_len;
6027                 break;
6028         }
6029         case MODE_SELECT_10: {
6030                 struct scsi_mode_header_10 *mh10;
6031
6032                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6033                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6034                 break;
6035         }
6036         default:
6037                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6038                 break;
6039         }
6040
6041         if (param_len < (header_size + bd_len)) {
6042                 free(ctsio->kern_data_ptr, M_CTL);
6043                 ctl_set_param_len_error(ctsio);
6044                 ctl_done((union ctl_io *)ctsio);
6045                 return (CTL_RETVAL_COMPLETE);
6046         }
6047
6048         /*
6049          * Set the IO_CONT flag, so that if this I/O gets passed to
6050          * ctl_config_write_done(), it'll get passed back to
6051          * ctl_do_mode_select() for further processing, or completion if
6052          * we're all done.
6053          */
6054         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6055         ctsio->io_cont = ctl_do_mode_select;
6056
6057         modepage_info = (union ctl_modepage_info *)
6058                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6059
6060         memset(modepage_info, 0, sizeof(*modepage_info));
6061
6062         len_left = param_len - header_size - bd_len;
6063         len_used = header_size + bd_len;
6064
6065         modepage_info->header.len_left = len_left;
6066         modepage_info->header.len_used = len_used;
6067
6068         return (ctl_do_mode_select((union ctl_io *)ctsio));
6069 }
6070
6071 int
6072 ctl_mode_sense(struct ctl_scsiio *ctsio)
6073 {
6074         struct ctl_lun *lun;
6075         int pc, page_code, dbd, llba, subpage;
6076         int alloc_len, page_len, header_len, total_len;
6077         struct scsi_mode_block_descr *block_desc;
6078         struct ctl_page_index *page_index;
6079         int control_dev;
6080
6081         dbd = 0;
6082         llba = 0;
6083         block_desc = NULL;
6084         page_index = NULL;
6085
6086         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6087
6088         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6089
6090         if (lun->be_lun->lun_type != T_DIRECT)
6091                 control_dev = 1;
6092         else
6093                 control_dev = 0;
6094
6095         switch (ctsio->cdb[0]) {
6096         case MODE_SENSE_6: {
6097                 struct scsi_mode_sense_6 *cdb;
6098
6099                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6100
6101                 header_len = sizeof(struct scsi_mode_hdr_6);
6102                 if (cdb->byte2 & SMS_DBD)
6103                         dbd = 1;
6104                 else
6105                         header_len += sizeof(struct scsi_mode_block_descr);
6106
6107                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6108                 page_code = cdb->page & SMS_PAGE_CODE;
6109                 subpage = cdb->subpage;
6110                 alloc_len = cdb->length;
6111                 break;
6112         }
6113         case MODE_SENSE_10: {
6114                 struct scsi_mode_sense_10 *cdb;
6115
6116                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6117
6118                 header_len = sizeof(struct scsi_mode_hdr_10);
6119
6120                 if (cdb->byte2 & SMS_DBD)
6121                         dbd = 1;
6122                 else
6123                         header_len += sizeof(struct scsi_mode_block_descr);
6124                 if (cdb->byte2 & SMS10_LLBAA)
6125                         llba = 1;
6126                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6127                 page_code = cdb->page & SMS_PAGE_CODE;
6128                 subpage = cdb->subpage;
6129                 alloc_len = scsi_2btoul(cdb->length);
6130                 break;
6131         }
6132         default:
6133                 ctl_set_invalid_opcode(ctsio);
6134                 ctl_done((union ctl_io *)ctsio);
6135                 return (CTL_RETVAL_COMPLETE);
6136                 break; /* NOTREACHED */
6137         }
6138
6139         /*
6140          * We have to make a first pass through to calculate the size of
6141          * the pages that match the user's query.  Then we allocate enough
6142          * memory to hold it, and actually copy the data into the buffer.
6143          */
6144         switch (page_code) {
6145         case SMS_ALL_PAGES_PAGE: {
6146                 int i;
6147
6148                 page_len = 0;
6149
6150                 /*
6151                  * At the moment, values other than 0 and 0xff here are
6152                  * reserved according to SPC-3.
6153                  */
6154                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6155                  && (subpage != SMS_SUBPAGE_ALL)) {
6156                         ctl_set_invalid_field(ctsio,
6157                                               /*sks_valid*/ 1,
6158                                               /*command*/ 1,
6159                                               /*field*/ 3,
6160                                               /*bit_valid*/ 0,
6161                                               /*bit*/ 0);
6162                         ctl_done((union ctl_io *)ctsio);
6163                         return (CTL_RETVAL_COMPLETE);
6164                 }
6165
6166                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6167                         if ((control_dev != 0)
6168                          && (lun->mode_pages.index[i].page_flags &
6169                              CTL_PAGE_FLAG_DISK_ONLY))
6170                                 continue;
6171
6172                         /*
6173                          * We don't use this subpage if the user didn't
6174                          * request all subpages.
6175                          */
6176                         if ((lun->mode_pages.index[i].subpage != 0)
6177                          && (subpage == SMS_SUBPAGE_PAGE_0))
6178                                 continue;
6179
6180 #if 0
6181                         printf("found page %#x len %d\n",
6182                                lun->mode_pages.index[i].page_code &
6183                                SMPH_PC_MASK,
6184                                lun->mode_pages.index[i].page_len);
6185 #endif
6186                         page_len += lun->mode_pages.index[i].page_len;
6187                 }
6188                 break;
6189         }
6190         default: {
6191                 int i;
6192
6193                 page_len = 0;
6194
6195                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6196                         /* Look for the right page code */
6197                         if ((lun->mode_pages.index[i].page_code &
6198                              SMPH_PC_MASK) != page_code)
6199                                 continue;
6200
6201                         /* Look for the right subpage or the subpage wildcard*/
6202                         if ((lun->mode_pages.index[i].subpage != subpage)
6203                          && (subpage != SMS_SUBPAGE_ALL))
6204                                 continue;
6205
6206                         /* Make sure the page is supported for this dev type */
6207                         if ((control_dev != 0)
6208                          && (lun->mode_pages.index[i].page_flags &
6209                              CTL_PAGE_FLAG_DISK_ONLY))
6210                                 continue;
6211
6212 #if 0
6213                         printf("found page %#x len %d\n",
6214                                lun->mode_pages.index[i].page_code &
6215                                SMPH_PC_MASK,
6216                                lun->mode_pages.index[i].page_len);
6217 #endif
6218
6219                         page_len += lun->mode_pages.index[i].page_len;
6220                 }
6221
6222                 if (page_len == 0) {
6223                         ctl_set_invalid_field(ctsio,
6224                                               /*sks_valid*/ 1,
6225                                               /*command*/ 1,
6226                                               /*field*/ 2,
6227                                               /*bit_valid*/ 1,
6228                                               /*bit*/ 5);
6229                         ctl_done((union ctl_io *)ctsio);
6230                         return (CTL_RETVAL_COMPLETE);
6231                 }
6232                 break;
6233         }
6234         }
6235
6236         total_len = header_len + page_len;
6237 #if 0
6238         printf("header_len = %d, page_len = %d, total_len = %d\n",
6239                header_len, page_len, total_len);
6240 #endif
6241
6242         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6243         ctsio->kern_sg_entries = 0;
6244         ctsio->kern_data_resid = 0;
6245         ctsio->kern_rel_offset = 0;
6246         if (total_len < alloc_len) {
6247                 ctsio->residual = alloc_len - total_len;
6248                 ctsio->kern_data_len = total_len;
6249                 ctsio->kern_total_len = total_len;
6250         } else {
6251                 ctsio->residual = 0;
6252                 ctsio->kern_data_len = alloc_len;
6253                 ctsio->kern_total_len = alloc_len;
6254         }
6255
6256         switch (ctsio->cdb[0]) {
6257         case MODE_SENSE_6: {
6258                 struct scsi_mode_hdr_6 *header;
6259
6260                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6261
6262                 header->datalen = MIN(total_len - 1, 254);
6263                 if (control_dev == 0) {
6264                         header->dev_specific = 0x10; /* DPOFUA */
6265                         if ((lun->flags & CTL_LUN_READONLY) ||
6266                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6267                             .eca_and_aen & SCP_SWP) != 0)
6268                                     header->dev_specific |= 0x80; /* WP */
6269                 }
6270                 if (dbd)
6271                         header->block_descr_len = 0;
6272                 else
6273                         header->block_descr_len =
6274                                 sizeof(struct scsi_mode_block_descr);
6275                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6276                 break;
6277         }
6278         case MODE_SENSE_10: {
6279                 struct scsi_mode_hdr_10 *header;
6280                 int datalen;
6281
6282                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6283
6284                 datalen = MIN(total_len - 2, 65533);
6285                 scsi_ulto2b(datalen, header->datalen);
6286                 if (control_dev == 0) {
6287                         header->dev_specific = 0x10; /* DPOFUA */
6288                         if ((lun->flags & CTL_LUN_READONLY) ||
6289                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6290                             .eca_and_aen & SCP_SWP) != 0)
6291                                     header->dev_specific |= 0x80; /* WP */
6292                 }
6293                 if (dbd)
6294                         scsi_ulto2b(0, header->block_descr_len);
6295                 else
6296                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6297                                     header->block_descr_len);
6298                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6299                 break;
6300         }
6301         default:
6302                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6303                 break; /* NOTREACHED */
6304         }
6305
6306         /*
6307          * If we've got a disk, use its blocksize in the block
6308          * descriptor.  Otherwise, just set it to 0.
6309          */
6310         if (dbd == 0) {
6311                 if (control_dev == 0)
6312                         scsi_ulto3b(lun->be_lun->blocksize,
6313                                     block_desc->block_len);
6314                 else
6315                         scsi_ulto3b(0, block_desc->block_len);
6316         }
6317
6318         switch (page_code) {
6319         case SMS_ALL_PAGES_PAGE: {
6320                 int i, data_used;
6321
6322                 data_used = header_len;
6323                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6324                         struct ctl_page_index *page_index;
6325
6326                         page_index = &lun->mode_pages.index[i];
6327
6328                         if ((control_dev != 0)
6329                          && (page_index->page_flags &
6330                             CTL_PAGE_FLAG_DISK_ONLY))
6331                                 continue;
6332
6333                         /*
6334                          * We don't use this subpage if the user didn't
6335                          * request all subpages.  We already checked (above)
6336                          * to make sure the user only specified a subpage
6337                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6338                          */
6339                         if ((page_index->subpage != 0)
6340                          && (subpage == SMS_SUBPAGE_PAGE_0))
6341                                 continue;
6342
6343                         /*
6344                          * Call the handler, if it exists, to update the
6345                          * page to the latest values.
6346                          */
6347                         if (page_index->sense_handler != NULL)
6348                                 page_index->sense_handler(ctsio, page_index,pc);
6349
6350                         memcpy(ctsio->kern_data_ptr + data_used,
6351                                page_index->page_data +
6352                                (page_index->page_len * pc),
6353                                page_index->page_len);
6354                         data_used += page_index->page_len;
6355                 }
6356                 break;
6357         }
6358         default: {
6359                 int i, data_used;
6360
6361                 data_used = header_len;
6362
6363                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6364                         struct ctl_page_index *page_index;
6365
6366                         page_index = &lun->mode_pages.index[i];
6367
6368                         /* Look for the right page code */
6369                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6370                                 continue;
6371
6372                         /* Look for the right subpage or the subpage wildcard*/
6373                         if ((page_index->subpage != subpage)
6374                          && (subpage != SMS_SUBPAGE_ALL))
6375                                 continue;
6376
6377                         /* Make sure the page is supported for this dev type */
6378                         if ((control_dev != 0)
6379                          && (page_index->page_flags &
6380                              CTL_PAGE_FLAG_DISK_ONLY))
6381                                 continue;
6382
6383                         /*
6384                          * Call the handler, if it exists, to update the
6385                          * page to the latest values.
6386                          */
6387                         if (page_index->sense_handler != NULL)
6388                                 page_index->sense_handler(ctsio, page_index,pc);
6389
6390                         memcpy(ctsio->kern_data_ptr + data_used,
6391                                page_index->page_data +
6392                                (page_index->page_len * pc),
6393                                page_index->page_len);
6394                         data_used += page_index->page_len;
6395                 }
6396                 break;
6397         }
6398         }
6399
6400         ctl_set_success(ctsio);
6401         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6402         ctsio->be_move_done = ctl_config_move_done;
6403         ctl_datamove((union ctl_io *)ctsio);
6404         return (CTL_RETVAL_COMPLETE);
6405 }
6406
6407 int
6408 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6409                                struct ctl_page_index *page_index,
6410                                int pc)
6411 {
6412         struct ctl_lun *lun;
6413         struct scsi_log_param_header *phdr;
6414         uint8_t *data;
6415         uint64_t val;
6416
6417         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6418         data = page_index->page_data;
6419
6420         if (lun->backend->lun_attr != NULL &&
6421             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6422              != UINT64_MAX) {
6423                 phdr = (struct scsi_log_param_header *)data;
6424                 scsi_ulto2b(0x0001, phdr->param_code);
6425                 phdr->param_control = SLP_LBIN | SLP_LP;
6426                 phdr->param_len = 8;
6427                 data = (uint8_t *)(phdr + 1);
6428                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6429                 data[4] = 0x02; /* per-pool */
6430                 data += phdr->param_len;
6431         }
6432
6433         if (lun->backend->lun_attr != NULL &&
6434             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6435              != UINT64_MAX) {
6436                 phdr = (struct scsi_log_param_header *)data;
6437                 scsi_ulto2b(0x0002, phdr->param_code);
6438                 phdr->param_control = SLP_LBIN | SLP_LP;
6439                 phdr->param_len = 8;
6440                 data = (uint8_t *)(phdr + 1);
6441                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6442                 data[4] = 0x01; /* per-LUN */
6443                 data += phdr->param_len;
6444         }
6445
6446         if (lun->backend->lun_attr != NULL &&
6447             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6448              != UINT64_MAX) {
6449                 phdr = (struct scsi_log_param_header *)data;
6450                 scsi_ulto2b(0x00f1, phdr->param_code);
6451                 phdr->param_control = SLP_LBIN | SLP_LP;
6452                 phdr->param_len = 8;
6453                 data = (uint8_t *)(phdr + 1);
6454                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6455                 data[4] = 0x02; /* per-pool */
6456                 data += phdr->param_len;
6457         }
6458
6459         if (lun->backend->lun_attr != NULL &&
6460             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6461              != UINT64_MAX) {
6462                 phdr = (struct scsi_log_param_header *)data;
6463                 scsi_ulto2b(0x00f2, phdr->param_code);
6464                 phdr->param_control = SLP_LBIN | SLP_LP;
6465                 phdr->param_len = 8;
6466                 data = (uint8_t *)(phdr + 1);
6467                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6468                 data[4] = 0x02; /* per-pool */
6469                 data += phdr->param_len;
6470         }
6471
6472         page_index->page_len = data - page_index->page_data;
6473         return (0);
6474 }
6475
6476 int
6477 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6478                                struct ctl_page_index *page_index,
6479                                int pc)
6480 {
6481         struct ctl_lun *lun;
6482         struct stat_page *data;
6483         uint64_t rn, wn, rb, wb;
6484         struct bintime rt, wt;
6485         int i;
6486
6487         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6488         data = (struct stat_page *)page_index->page_data;
6489
6490         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6491         data->sap.hdr.param_control = SLP_LBIN;
6492         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6493             sizeof(struct scsi_log_param_header);
6494         rn = wn = rb = wb = 0;
6495         bintime_clear(&rt);
6496         bintime_clear(&wt);
6497         for (i = 0; i < CTL_MAX_PORTS; i++) {
6498                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6499                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6500                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6501                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6502                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6503                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6504         }
6505         scsi_u64to8b(rn, data->sap.read_num);
6506         scsi_u64to8b(wn, data->sap.write_num);
6507         if (lun->stats.blocksize > 0) {
6508                 scsi_u64to8b(wb / lun->stats.blocksize,
6509                     data->sap.recvieved_lba);
6510                 scsi_u64to8b(rb / lun->stats.blocksize,
6511                     data->sap.transmitted_lba);
6512         }
6513         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6514             data->sap.read_int);
6515         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6516             data->sap.write_int);
6517         scsi_u64to8b(0, data->sap.weighted_num);
6518         scsi_u64to8b(0, data->sap.weighted_int);
6519         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6520         data->it.hdr.param_control = SLP_LBIN;
6521         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6522             sizeof(struct scsi_log_param_header);
6523 #ifdef CTL_TIME_IO
6524         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6525 #endif
6526         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6527         data->it.hdr.param_control = SLP_LBIN;
6528         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6529             sizeof(struct scsi_log_param_header);
6530         scsi_ulto4b(3, data->ti.exponent);
6531         scsi_ulto4b(1, data->ti.integer);
6532
6533         page_index->page_len = sizeof(*data);
6534         return (0);
6535 }
6536
6537 int
6538 ctl_log_sense(struct ctl_scsiio *ctsio)
6539 {
6540         struct ctl_lun *lun;
6541         int i, pc, page_code, subpage;
6542         int alloc_len, total_len;
6543         struct ctl_page_index *page_index;
6544         struct scsi_log_sense *cdb;
6545         struct scsi_log_header *header;
6546
6547         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6548
6549         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6550         cdb = (struct scsi_log_sense *)ctsio->cdb;
6551         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6552         page_code = cdb->page & SLS_PAGE_CODE;
6553         subpage = cdb->subpage;
6554         alloc_len = scsi_2btoul(cdb->length);
6555
6556         page_index = NULL;
6557         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6558                 page_index = &lun->log_pages.index[i];
6559
6560                 /* Look for the right page code */
6561                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6562                         continue;
6563
6564                 /* Look for the right subpage or the subpage wildcard*/
6565                 if (page_index->subpage != subpage)
6566                         continue;
6567
6568                 break;
6569         }
6570         if (i >= CTL_NUM_LOG_PAGES) {
6571                 ctl_set_invalid_field(ctsio,
6572                                       /*sks_valid*/ 1,
6573                                       /*command*/ 1,
6574                                       /*field*/ 2,
6575                                       /*bit_valid*/ 0,
6576                                       /*bit*/ 0);
6577                 ctl_done((union ctl_io *)ctsio);
6578                 return (CTL_RETVAL_COMPLETE);
6579         }
6580
6581         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6582
6583         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6584         ctsio->kern_sg_entries = 0;
6585         ctsio->kern_data_resid = 0;
6586         ctsio->kern_rel_offset = 0;
6587         if (total_len < alloc_len) {
6588                 ctsio->residual = alloc_len - total_len;
6589                 ctsio->kern_data_len = total_len;
6590                 ctsio->kern_total_len = total_len;
6591         } else {
6592                 ctsio->residual = 0;
6593                 ctsio->kern_data_len = alloc_len;
6594                 ctsio->kern_total_len = alloc_len;
6595         }
6596
6597         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6598         header->page = page_index->page_code;
6599         if (page_index->subpage) {
6600                 header->page |= SL_SPF;
6601                 header->subpage = page_index->subpage;
6602         }
6603         scsi_ulto2b(page_index->page_len, header->datalen);
6604
6605         /*
6606          * Call the handler, if it exists, to update the
6607          * page to the latest values.
6608          */
6609         if (page_index->sense_handler != NULL)
6610                 page_index->sense_handler(ctsio, page_index, pc);
6611
6612         memcpy(header + 1, page_index->page_data, page_index->page_len);
6613
6614         ctl_set_success(ctsio);
6615         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6616         ctsio->be_move_done = ctl_config_move_done;
6617         ctl_datamove((union ctl_io *)ctsio);
6618         return (CTL_RETVAL_COMPLETE);
6619 }
6620
6621 int
6622 ctl_read_capacity(struct ctl_scsiio *ctsio)
6623 {
6624         struct scsi_read_capacity *cdb;
6625         struct scsi_read_capacity_data *data;
6626         struct ctl_lun *lun;
6627         uint32_t lba;
6628
6629         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6630
6631         cdb = (struct scsi_read_capacity *)ctsio->cdb;
6632
6633         lba = scsi_4btoul(cdb->addr);
6634         if (((cdb->pmi & SRC_PMI) == 0)
6635          && (lba != 0)) {
6636                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6637                                       /*sks_valid*/ 1,
6638                                       /*command*/ 1,
6639                                       /*field*/ 2,
6640                                       /*bit_valid*/ 0,
6641                                       /*bit*/ 0);
6642                 ctl_done((union ctl_io *)ctsio);
6643                 return (CTL_RETVAL_COMPLETE);
6644         }
6645
6646         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6647
6648         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6649         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6650         ctsio->residual = 0;
6651         ctsio->kern_data_len = sizeof(*data);
6652         ctsio->kern_total_len = sizeof(*data);
6653         ctsio->kern_data_resid = 0;
6654         ctsio->kern_rel_offset = 0;
6655         ctsio->kern_sg_entries = 0;
6656
6657         /*
6658          * If the maximum LBA is greater than 0xfffffffe, the user must
6659          * issue a SERVICE ACTION IN (16) command, with the read capacity
6660          * serivce action set.
6661          */
6662         if (lun->be_lun->maxlba > 0xfffffffe)
6663                 scsi_ulto4b(0xffffffff, data->addr);
6664         else
6665                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6666
6667         /*
6668          * XXX KDM this may not be 512 bytes...
6669          */
6670         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6671
6672         ctl_set_success(ctsio);
6673         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6674         ctsio->be_move_done = ctl_config_move_done;
6675         ctl_datamove((union ctl_io *)ctsio);
6676         return (CTL_RETVAL_COMPLETE);
6677 }
6678
6679 int
6680 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6681 {
6682         struct scsi_read_capacity_16 *cdb;
6683         struct scsi_read_capacity_data_long *data;
6684         struct ctl_lun *lun;
6685         uint64_t lba;
6686         uint32_t alloc_len;
6687
6688         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6689
6690         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6691
6692         alloc_len = scsi_4btoul(cdb->alloc_len);
6693         lba = scsi_8btou64(cdb->addr);
6694
6695         if ((cdb->reladr & SRC16_PMI)
6696          && (lba != 0)) {
6697                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6698                                       /*sks_valid*/ 1,
6699                                       /*command*/ 1,
6700                                       /*field*/ 2,
6701                                       /*bit_valid*/ 0,
6702                                       /*bit*/ 0);
6703                 ctl_done((union ctl_io *)ctsio);
6704                 return (CTL_RETVAL_COMPLETE);
6705         }
6706
6707         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6708
6709         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6710         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6711
6712         if (sizeof(*data) < alloc_len) {
6713                 ctsio->residual = alloc_len - sizeof(*data);
6714                 ctsio->kern_data_len = sizeof(*data);
6715                 ctsio->kern_total_len = sizeof(*data);
6716         } else {
6717                 ctsio->residual = 0;
6718                 ctsio->kern_data_len = alloc_len;
6719                 ctsio->kern_total_len = alloc_len;
6720         }
6721         ctsio->kern_data_resid = 0;
6722         ctsio->kern_rel_offset = 0;
6723         ctsio->kern_sg_entries = 0;
6724
6725         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6726         /* XXX KDM this may not be 512 bytes... */
6727         scsi_ulto4b(lun->be_lun->blocksize, data->length);
6728         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6729         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6730         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6731                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6732
6733         ctl_set_success(ctsio);
6734         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6735         ctsio->be_move_done = ctl_config_move_done;
6736         ctl_datamove((union ctl_io *)ctsio);
6737         return (CTL_RETVAL_COMPLETE);
6738 }
6739
6740 int
6741 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6742 {
6743         struct scsi_get_lba_status *cdb;
6744         struct scsi_get_lba_status_data *data;
6745         struct ctl_lun *lun;
6746         struct ctl_lba_len_flags *lbalen;
6747         uint64_t lba;
6748         uint32_t alloc_len, total_len;
6749         int retval;
6750
6751         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6752
6753         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6754         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6755         lba = scsi_8btou64(cdb->addr);
6756         alloc_len = scsi_4btoul(cdb->alloc_len);
6757
6758         if (lba > lun->be_lun->maxlba) {
6759                 ctl_set_lba_out_of_range(ctsio);
6760                 ctl_done((union ctl_io *)ctsio);
6761                 return (CTL_RETVAL_COMPLETE);
6762         }
6763
6764         total_len = sizeof(*data) + sizeof(data->descr[0]);
6765         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6766         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6767
6768         if (total_len < alloc_len) {
6769                 ctsio->residual = alloc_len - total_len;
6770                 ctsio->kern_data_len = total_len;
6771                 ctsio->kern_total_len = total_len;
6772         } else {
6773                 ctsio->residual = 0;
6774                 ctsio->kern_data_len = alloc_len;
6775                 ctsio->kern_total_len = alloc_len;
6776         }
6777         ctsio->kern_data_resid = 0;
6778         ctsio->kern_rel_offset = 0;
6779         ctsio->kern_sg_entries = 0;
6780
6781         /* Fill dummy data in case backend can't tell anything. */
6782         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6783         scsi_u64to8b(lba, data->descr[0].addr);
6784         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6785             data->descr[0].length);
6786         data->descr[0].status = 0; /* Mapped or unknown. */
6787
6788         ctl_set_success(ctsio);
6789         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6790         ctsio->be_move_done = ctl_config_move_done;
6791
6792         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6793         lbalen->lba = lba;
6794         lbalen->len = total_len;
6795         lbalen->flags = 0;
6796         retval = lun->backend->config_read((union ctl_io *)ctsio);
6797         return (CTL_RETVAL_COMPLETE);
6798 }
6799
6800 int
6801 ctl_read_defect(struct ctl_scsiio *ctsio)
6802 {
6803         struct scsi_read_defect_data_10 *ccb10;
6804         struct scsi_read_defect_data_12 *ccb12;
6805         struct scsi_read_defect_data_hdr_10 *data10;
6806         struct scsi_read_defect_data_hdr_12 *data12;
6807         uint32_t alloc_len, data_len;
6808         uint8_t format;
6809
6810         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
6811
6812         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6813                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
6814                 format = ccb10->format;
6815                 alloc_len = scsi_2btoul(ccb10->alloc_length);
6816                 data_len = sizeof(*data10);
6817         } else {
6818                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
6819                 format = ccb12->format;
6820                 alloc_len = scsi_4btoul(ccb12->alloc_length);
6821                 data_len = sizeof(*data12);
6822         }
6823         if (alloc_len == 0) {
6824                 ctl_set_success(ctsio);
6825                 ctl_done((union ctl_io *)ctsio);
6826                 return (CTL_RETVAL_COMPLETE);
6827         }
6828
6829         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
6830         if (data_len < alloc_len) {
6831                 ctsio->residual = alloc_len - data_len;
6832                 ctsio->kern_data_len = data_len;
6833                 ctsio->kern_total_len = data_len;
6834         } else {
6835                 ctsio->residual = 0;
6836                 ctsio->kern_data_len = alloc_len;
6837                 ctsio->kern_total_len = alloc_len;
6838         }
6839         ctsio->kern_data_resid = 0;
6840         ctsio->kern_rel_offset = 0;
6841         ctsio->kern_sg_entries = 0;
6842
6843         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6844                 data10 = (struct scsi_read_defect_data_hdr_10 *)
6845                     ctsio->kern_data_ptr;
6846                 data10->format = format;
6847                 scsi_ulto2b(0, data10->length);
6848         } else {
6849                 data12 = (struct scsi_read_defect_data_hdr_12 *)
6850                     ctsio->kern_data_ptr;
6851                 data12->format = format;
6852                 scsi_ulto2b(0, data12->generation);
6853                 scsi_ulto4b(0, data12->length);
6854         }
6855
6856         ctl_set_success(ctsio);
6857         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6858         ctsio->be_move_done = ctl_config_move_done;
6859         ctl_datamove((union ctl_io *)ctsio);
6860         return (CTL_RETVAL_COMPLETE);
6861 }
6862
6863 int
6864 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
6865 {
6866         struct scsi_maintenance_in *cdb;
6867         int retval;
6868         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
6869         int num_target_port_groups, num_target_ports;
6870         struct ctl_lun *lun;
6871         struct ctl_softc *softc;
6872         struct ctl_port *port;
6873         struct scsi_target_group_data *rtg_ptr;
6874         struct scsi_target_group_data_extended *rtg_ext_ptr;
6875         struct scsi_target_port_group_descriptor *tpg_desc;
6876
6877         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
6878
6879         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
6880         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6881         softc = lun->ctl_softc;
6882
6883         retval = CTL_RETVAL_COMPLETE;
6884
6885         switch (cdb->byte2 & STG_PDF_MASK) {
6886         case STG_PDF_LENGTH:
6887                 ext = 0;
6888                 break;
6889         case STG_PDF_EXTENDED:
6890                 ext = 1;
6891                 break;
6892         default:
6893                 ctl_set_invalid_field(/*ctsio*/ ctsio,
6894                                       /*sks_valid*/ 1,
6895                                       /*command*/ 1,
6896                                       /*field*/ 2,
6897                                       /*bit_valid*/ 1,
6898                                       /*bit*/ 5);
6899                 ctl_done((union ctl_io *)ctsio);
6900                 return(retval);
6901         }
6902
6903         if (softc->is_single)
6904                 num_target_port_groups = 1;
6905         else
6906                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
6907         num_target_ports = 0;
6908         mtx_lock(&softc->ctl_lock);
6909         STAILQ_FOREACH(port, &softc->port_list, links) {
6910                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
6911                         continue;
6912                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
6913                         continue;
6914                 num_target_ports++;
6915         }
6916         mtx_unlock(&softc->ctl_lock);
6917
6918         if (ext)
6919                 total_len = sizeof(struct scsi_target_group_data_extended);
6920         else
6921                 total_len = sizeof(struct scsi_target_group_data);
6922         total_len += sizeof(struct scsi_target_port_group_descriptor) *
6923                 num_target_port_groups +
6924             sizeof(struct scsi_target_port_descriptor) *
6925                 num_target_ports * num_target_port_groups;
6926
6927         alloc_len = scsi_4btoul(cdb->length);
6928
6929         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6930
6931         ctsio->kern_sg_entries = 0;
6932
6933         if (total_len < alloc_len) {
6934                 ctsio->residual = alloc_len - total_len;
6935                 ctsio->kern_data_len = total_len;
6936                 ctsio->kern_total_len = total_len;
6937         } else {
6938                 ctsio->residual = 0;
6939                 ctsio->kern_data_len = alloc_len;
6940                 ctsio->kern_total_len = alloc_len;
6941         }
6942         ctsio->kern_data_resid = 0;
6943         ctsio->kern_rel_offset = 0;
6944
6945         if (ext) {
6946                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
6947                     ctsio->kern_data_ptr;
6948                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
6949                 rtg_ext_ptr->format_type = 0x10;
6950                 rtg_ext_ptr->implicit_transition_time = 0;
6951                 tpg_desc = &rtg_ext_ptr->groups[0];
6952         } else {
6953                 rtg_ptr = (struct scsi_target_group_data *)
6954                     ctsio->kern_data_ptr;
6955                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
6956                 tpg_desc = &rtg_ptr->groups[0];
6957         }
6958
6959         mtx_lock(&softc->ctl_lock);
6960         pg = softc->port_offset / CTL_MAX_PORTS;
6961         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
6962                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
6963                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
6964                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
6965                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
6966                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
6967                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
6968                 } else {
6969                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
6970                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
6971                 }
6972         } else {
6973                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
6974                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
6975         }
6976         for (g = 0; g < num_target_port_groups; g++) {
6977                 tpg_desc->pref_state = (g == pg) ? gs : os;
6978                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
6979                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
6980                 tpg_desc->status = TPG_IMPLICIT;
6981                 pc = 0;
6982                 STAILQ_FOREACH(port, &softc->port_list, links) {
6983                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
6984                                 continue;
6985                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
6986                                 continue;
6987                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
6988                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
6989                             relative_target_port_identifier);
6990                         pc++;
6991                 }
6992                 tpg_desc->target_port_count = pc;
6993                 tpg_desc = (struct scsi_target_port_group_descriptor *)
6994                     &tpg_desc->descriptors[pc];
6995         }
6996         mtx_unlock(&softc->ctl_lock);
6997
6998         ctl_set_success(ctsio);
6999         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7000         ctsio->be_move_done = ctl_config_move_done;
7001         ctl_datamove((union ctl_io *)ctsio);
7002         return(retval);
7003 }
7004
7005 int
7006 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7007 {
7008         struct ctl_lun *lun;
7009         struct scsi_report_supported_opcodes *cdb;
7010         const struct ctl_cmd_entry *entry, *sentry;
7011         struct scsi_report_supported_opcodes_all *all;
7012         struct scsi_report_supported_opcodes_descr *descr;
7013         struct scsi_report_supported_opcodes_one *one;
7014         int retval;
7015         int alloc_len, total_len;
7016         int opcode, service_action, i, j, num;
7017
7018         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7019
7020         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7021         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7022
7023         retval = CTL_RETVAL_COMPLETE;
7024
7025         opcode = cdb->requested_opcode;
7026         service_action = scsi_2btoul(cdb->requested_service_action);
7027         switch (cdb->options & RSO_OPTIONS_MASK) {
7028         case RSO_OPTIONS_ALL:
7029                 num = 0;
7030                 for (i = 0; i < 256; i++) {
7031                         entry = &ctl_cmd_table[i];
7032                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7033                                 for (j = 0; j < 32; j++) {
7034                                         sentry = &((const struct ctl_cmd_entry *)
7035                                             entry->execute)[j];
7036                                         if (ctl_cmd_applicable(
7037                                             lun->be_lun->lun_type, sentry))
7038                                                 num++;
7039                                 }
7040                         } else {
7041                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7042                                     entry))
7043                                         num++;
7044                         }
7045                 }
7046                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7047                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7048                 break;
7049         case RSO_OPTIONS_OC:
7050                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7051                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7052                                               /*sks_valid*/ 1,
7053                                               /*command*/ 1,
7054                                               /*field*/ 2,
7055                                               /*bit_valid*/ 1,
7056                                               /*bit*/ 2);
7057                         ctl_done((union ctl_io *)ctsio);
7058                         return (CTL_RETVAL_COMPLETE);
7059                 }
7060                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7061                 break;
7062         case RSO_OPTIONS_OC_SA:
7063                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7064                     service_action >= 32) {
7065                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7066                                               /*sks_valid*/ 1,
7067                                               /*command*/ 1,
7068                                               /*field*/ 2,
7069                                               /*bit_valid*/ 1,
7070                                               /*bit*/ 2);
7071                         ctl_done((union ctl_io *)ctsio);
7072                         return (CTL_RETVAL_COMPLETE);
7073                 }
7074                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7075                 break;
7076         default:
7077                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7078                                       /*sks_valid*/ 1,
7079                                       /*command*/ 1,
7080                                       /*field*/ 2,
7081                                       /*bit_valid*/ 1,
7082                                       /*bit*/ 2);
7083                 ctl_done((union ctl_io *)ctsio);
7084                 return (CTL_RETVAL_COMPLETE);
7085         }
7086
7087         alloc_len = scsi_4btoul(cdb->length);
7088
7089         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7090
7091         ctsio->kern_sg_entries = 0;
7092
7093         if (total_len < alloc_len) {
7094                 ctsio->residual = alloc_len - total_len;
7095                 ctsio->kern_data_len = total_len;
7096                 ctsio->kern_total_len = total_len;
7097         } else {
7098                 ctsio->residual = 0;
7099                 ctsio->kern_data_len = alloc_len;
7100                 ctsio->kern_total_len = alloc_len;
7101         }
7102         ctsio->kern_data_resid = 0;
7103         ctsio->kern_rel_offset = 0;
7104
7105         switch (cdb->options & RSO_OPTIONS_MASK) {
7106         case RSO_OPTIONS_ALL:
7107                 all = (struct scsi_report_supported_opcodes_all *)
7108                     ctsio->kern_data_ptr;
7109                 num = 0;
7110                 for (i = 0; i < 256; i++) {
7111                         entry = &ctl_cmd_table[i];
7112                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7113                                 for (j = 0; j < 32; j++) {
7114                                         sentry = &((const struct ctl_cmd_entry *)
7115                                             entry->execute)[j];
7116                                         if (!ctl_cmd_applicable(
7117                                             lun->be_lun->lun_type, sentry))
7118                                                 continue;
7119                                         descr = &all->descr[num++];
7120                                         descr->opcode = i;
7121                                         scsi_ulto2b(j, descr->service_action);
7122                                         descr->flags = RSO_SERVACTV;
7123                                         scsi_ulto2b(sentry->length,
7124                                             descr->cdb_length);
7125                                 }
7126                         } else {
7127                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7128                                     entry))
7129                                         continue;
7130                                 descr = &all->descr[num++];
7131                                 descr->opcode = i;
7132                                 scsi_ulto2b(0, descr->service_action);
7133                                 descr->flags = 0;
7134                                 scsi_ulto2b(entry->length, descr->cdb_length);
7135                         }
7136                 }
7137                 scsi_ulto4b(
7138                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7139                     all->length);
7140                 break;
7141         case RSO_OPTIONS_OC:
7142                 one = (struct scsi_report_supported_opcodes_one *)
7143                     ctsio->kern_data_ptr;
7144                 entry = &ctl_cmd_table[opcode];
7145                 goto fill_one;
7146         case RSO_OPTIONS_OC_SA:
7147                 one = (struct scsi_report_supported_opcodes_one *)
7148                     ctsio->kern_data_ptr;
7149                 entry = &ctl_cmd_table[opcode];
7150                 entry = &((const struct ctl_cmd_entry *)
7151                     entry->execute)[service_action];
7152 fill_one:
7153                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7154                         one->support = 3;
7155                         scsi_ulto2b(entry->length, one->cdb_length);
7156                         one->cdb_usage[0] = opcode;
7157                         memcpy(&one->cdb_usage[1], entry->usage,
7158                             entry->length - 1);
7159                 } else
7160                         one->support = 1;
7161                 break;
7162         }
7163
7164         ctl_set_success(ctsio);
7165         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7166         ctsio->be_move_done = ctl_config_move_done;
7167         ctl_datamove((union ctl_io *)ctsio);
7168         return(retval);
7169 }
7170
7171 int
7172 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7173 {
7174         struct scsi_report_supported_tmf *cdb;
7175         struct scsi_report_supported_tmf_data *data;
7176         int retval;
7177         int alloc_len, total_len;
7178
7179         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7180
7181         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7182
7183         retval = CTL_RETVAL_COMPLETE;
7184
7185         total_len = sizeof(struct scsi_report_supported_tmf_data);
7186         alloc_len = scsi_4btoul(cdb->length);
7187
7188         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7189
7190         ctsio->kern_sg_entries = 0;
7191
7192         if (total_len < alloc_len) {
7193                 ctsio->residual = alloc_len - total_len;
7194                 ctsio->kern_data_len = total_len;
7195                 ctsio->kern_total_len = total_len;
7196         } else {
7197                 ctsio->residual = 0;
7198                 ctsio->kern_data_len = alloc_len;
7199                 ctsio->kern_total_len = alloc_len;
7200         }
7201         ctsio->kern_data_resid = 0;
7202         ctsio->kern_rel_offset = 0;
7203
7204         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7205         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7206         data->byte2 |= RST_ITNRS;
7207
7208         ctl_set_success(ctsio);
7209         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7210         ctsio->be_move_done = ctl_config_move_done;
7211         ctl_datamove((union ctl_io *)ctsio);
7212         return (retval);
7213 }
7214
7215 int
7216 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7217 {
7218         struct scsi_report_timestamp *cdb;
7219         struct scsi_report_timestamp_data *data;
7220         struct timeval tv;
7221         int64_t timestamp;
7222         int retval;
7223         int alloc_len, total_len;
7224
7225         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7226
7227         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7228
7229         retval = CTL_RETVAL_COMPLETE;
7230
7231         total_len = sizeof(struct scsi_report_timestamp_data);
7232         alloc_len = scsi_4btoul(cdb->length);
7233
7234         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7235
7236         ctsio->kern_sg_entries = 0;
7237
7238         if (total_len < alloc_len) {
7239                 ctsio->residual = alloc_len - total_len;
7240                 ctsio->kern_data_len = total_len;
7241                 ctsio->kern_total_len = total_len;
7242         } else {
7243                 ctsio->residual = 0;
7244                 ctsio->kern_data_len = alloc_len;
7245                 ctsio->kern_total_len = alloc_len;
7246         }
7247         ctsio->kern_data_resid = 0;
7248         ctsio->kern_rel_offset = 0;
7249
7250         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7251         scsi_ulto2b(sizeof(*data) - 2, data->length);
7252         data->origin = RTS_ORIG_OUTSIDE;
7253         getmicrotime(&tv);
7254         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7255         scsi_ulto4b(timestamp >> 16, data->timestamp);
7256         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7257
7258         ctl_set_success(ctsio);
7259         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7260         ctsio->be_move_done = ctl_config_move_done;
7261         ctl_datamove((union ctl_io *)ctsio);
7262         return (retval);
7263 }
7264
7265 int
7266 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7267 {
7268         struct scsi_per_res_in *cdb;
7269         int alloc_len, total_len = 0;
7270         /* struct scsi_per_res_in_rsrv in_data; */
7271         struct ctl_lun *lun;
7272         struct ctl_softc *softc;
7273         uint64_t key;
7274
7275         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7276
7277         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7278
7279         alloc_len = scsi_2btoul(cdb->length);
7280
7281         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7282         softc = lun->ctl_softc;
7283
7284 retry:
7285         mtx_lock(&lun->lun_lock);
7286         switch (cdb->action) {
7287         case SPRI_RK: /* read keys */
7288                 total_len = sizeof(struct scsi_per_res_in_keys) +
7289                         lun->pr_key_count *
7290                         sizeof(struct scsi_per_res_key);
7291                 break;
7292         case SPRI_RR: /* read reservation */
7293                 if (lun->flags & CTL_LUN_PR_RESERVED)
7294                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7295                 else
7296                         total_len = sizeof(struct scsi_per_res_in_header);
7297                 break;
7298         case SPRI_RC: /* report capabilities */
7299                 total_len = sizeof(struct scsi_per_res_cap);
7300                 break;
7301         case SPRI_RS: /* read full status */
7302                 total_len = sizeof(struct scsi_per_res_in_header) +
7303                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7304                     lun->pr_key_count;
7305                 break;
7306         default:
7307                 panic("Invalid PR type %x", cdb->action);
7308         }
7309         mtx_unlock(&lun->lun_lock);
7310
7311         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7312
7313         if (total_len < alloc_len) {
7314                 ctsio->residual = alloc_len - total_len;
7315                 ctsio->kern_data_len = total_len;
7316                 ctsio->kern_total_len = total_len;
7317         } else {
7318                 ctsio->residual = 0;
7319                 ctsio->kern_data_len = alloc_len;
7320                 ctsio->kern_total_len = alloc_len;
7321         }
7322
7323         ctsio->kern_data_resid = 0;
7324         ctsio->kern_rel_offset = 0;
7325         ctsio->kern_sg_entries = 0;
7326
7327         mtx_lock(&lun->lun_lock);
7328         switch (cdb->action) {
7329         case SPRI_RK: { // read keys
7330         struct scsi_per_res_in_keys *res_keys;
7331                 int i, key_count;
7332
7333                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7334
7335                 /*
7336                  * We had to drop the lock to allocate our buffer, which
7337                  * leaves time for someone to come in with another
7338                  * persistent reservation.  (That is unlikely, though,
7339                  * since this should be the only persistent reservation
7340                  * command active right now.)
7341                  */
7342                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7343                     (lun->pr_key_count *
7344                      sizeof(struct scsi_per_res_key)))){
7345                         mtx_unlock(&lun->lun_lock);
7346                         free(ctsio->kern_data_ptr, M_CTL);
7347                         printf("%s: reservation length changed, retrying\n",
7348                                __func__);
7349                         goto retry;
7350                 }
7351
7352                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7353
7354                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7355                              lun->pr_key_count, res_keys->header.length);
7356
7357                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7358                         if ((key = ctl_get_prkey(lun, i)) == 0)
7359                                 continue;
7360
7361                         /*
7362                          * We used lun->pr_key_count to calculate the
7363                          * size to allocate.  If it turns out the number of
7364                          * initiators with the registered flag set is
7365                          * larger than that (i.e. they haven't been kept in
7366                          * sync), we've got a problem.
7367                          */
7368                         if (key_count >= lun->pr_key_count) {
7369 #ifdef NEEDTOPORT
7370                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7371                                             CTL_PR_ERROR,
7372                                             csevent_LogType_Fault,
7373                                             csevent_AlertLevel_Yellow,
7374                                             csevent_FRU_ShelfController,
7375                                             csevent_FRU_Firmware,
7376                                         csevent_FRU_Unknown,
7377                                             "registered keys %d >= key "
7378                                             "count %d", key_count,
7379                                             lun->pr_key_count);
7380 #endif
7381                                 key_count++;
7382                                 continue;
7383                         }
7384                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7385                         key_count++;
7386                 }
7387                 break;
7388         }
7389         case SPRI_RR: { // read reservation
7390                 struct scsi_per_res_in_rsrv *res;
7391                 int tmp_len, header_only;
7392
7393                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7394
7395                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7396
7397                 if (lun->flags & CTL_LUN_PR_RESERVED)
7398                 {
7399                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7400                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7401                                     res->header.length);
7402                         header_only = 0;
7403                 } else {
7404                         tmp_len = sizeof(struct scsi_per_res_in_header);
7405                         scsi_ulto4b(0, res->header.length);
7406                         header_only = 1;
7407                 }
7408
7409                 /*
7410                  * We had to drop the lock to allocate our buffer, which
7411                  * leaves time for someone to come in with another
7412                  * persistent reservation.  (That is unlikely, though,
7413                  * since this should be the only persistent reservation
7414                  * command active right now.)
7415                  */
7416                 if (tmp_len != total_len) {
7417                         mtx_unlock(&lun->lun_lock);
7418                         free(ctsio->kern_data_ptr, M_CTL);
7419                         printf("%s: reservation status changed, retrying\n",
7420                                __func__);
7421                         goto retry;
7422                 }
7423
7424                 /*
7425                  * No reservation held, so we're done.
7426                  */
7427                 if (header_only != 0)
7428                         break;
7429
7430                 /*
7431                  * If the registration is an All Registrants type, the key
7432                  * is 0, since it doesn't really matter.
7433                  */
7434                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7435                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7436                             res->data.reservation);
7437                 }
7438                 res->data.scopetype = lun->res_type;
7439                 break;
7440         }
7441         case SPRI_RC:     //report capabilities
7442         {
7443                 struct scsi_per_res_cap *res_cap;
7444                 uint16_t type_mask;
7445
7446                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7447                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7448                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7449                 type_mask = SPRI_TM_WR_EX_AR |
7450                             SPRI_TM_EX_AC_RO |
7451                             SPRI_TM_WR_EX_RO |
7452                             SPRI_TM_EX_AC |
7453                             SPRI_TM_WR_EX |
7454                             SPRI_TM_EX_AC_AR;
7455                 scsi_ulto2b(type_mask, res_cap->type_mask);
7456                 break;
7457         }
7458         case SPRI_RS: { // read full status
7459                 struct scsi_per_res_in_full *res_status;
7460                 struct scsi_per_res_in_full_desc *res_desc;
7461                 struct ctl_port *port;
7462                 int i, len;
7463
7464                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7465
7466                 /*
7467                  * We had to drop the lock to allocate our buffer, which
7468                  * leaves time for someone to come in with another
7469                  * persistent reservation.  (That is unlikely, though,
7470                  * since this should be the only persistent reservation
7471                  * command active right now.)
7472                  */
7473                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7474                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7475                      lun->pr_key_count)){
7476                         mtx_unlock(&lun->lun_lock);
7477                         free(ctsio->kern_data_ptr, M_CTL);
7478                         printf("%s: reservation length changed, retrying\n",
7479                                __func__);
7480                         goto retry;
7481                 }
7482
7483                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7484
7485                 res_desc = &res_status->desc[0];
7486                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7487                         if ((key = ctl_get_prkey(lun, i)) == 0)
7488                                 continue;
7489
7490                         scsi_u64to8b(key, res_desc->res_key.key);
7491                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7492                             (lun->pr_res_idx == i ||
7493                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7494                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7495                                 res_desc->scopetype = lun->res_type;
7496                         }
7497                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7498                             res_desc->rel_trgt_port_id);
7499                         len = 0;
7500                         port = softc->ctl_ports[
7501                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7502                         if (port != NULL)
7503                                 len = ctl_create_iid(port,
7504                                     i % CTL_MAX_INIT_PER_PORT,
7505                                     res_desc->transport_id);
7506                         scsi_ulto4b(len, res_desc->additional_length);
7507                         res_desc = (struct scsi_per_res_in_full_desc *)
7508                             &res_desc->transport_id[len];
7509                 }
7510                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7511                     res_status->header.length);
7512                 break;
7513         }
7514         default:
7515                 /*
7516                  * This is a bug, because we just checked for this above,
7517                  * and should have returned an error.
7518                  */
7519                 panic("Invalid PR type %x", cdb->action);
7520                 break; /* NOTREACHED */
7521         }
7522         mtx_unlock(&lun->lun_lock);
7523
7524         ctl_set_success(ctsio);
7525         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7526         ctsio->be_move_done = ctl_config_move_done;
7527         ctl_datamove((union ctl_io *)ctsio);
7528         return (CTL_RETVAL_COMPLETE);
7529 }
7530
7531 static void
7532 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7533 {
7534         int off = lun->ctl_softc->persis_offset;
7535
7536         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7537                 ctl_est_ua(lun, residx - off, ua);
7538 }
7539
7540 /*
7541  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7542  * it should return.
7543  */
7544 static int
7545 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7546                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7547                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7548                 struct scsi_per_res_out_parms* param)
7549 {
7550         union ctl_ha_msg persis_io;
7551         int retval, i;
7552         int isc_retval;
7553
7554         retval = 0;
7555
7556         mtx_lock(&lun->lun_lock);
7557         if (sa_res_key == 0) {
7558                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7559                         /* validate scope and type */
7560                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7561                              SPR_LU_SCOPE) {
7562                                 mtx_unlock(&lun->lun_lock);
7563                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7564                                                       /*sks_valid*/ 1,
7565                                                       /*command*/ 1,
7566                                                       /*field*/ 2,
7567                                                       /*bit_valid*/ 1,
7568                                                       /*bit*/ 4);
7569                                 ctl_done((union ctl_io *)ctsio);
7570                                 return (1);
7571                         }
7572
7573                         if (type>8 || type==2 || type==4 || type==0) {
7574                                 mtx_unlock(&lun->lun_lock);
7575                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7576                                                       /*sks_valid*/ 1,
7577                                                       /*command*/ 1,
7578                                                       /*field*/ 2,
7579                                                       /*bit_valid*/ 1,
7580                                                       /*bit*/ 0);
7581                                 ctl_done((union ctl_io *)ctsio);
7582                                 return (1);
7583                         }
7584
7585                         /*
7586                          * Unregister everybody else and build UA for
7587                          * them
7588                          */
7589                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7590                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7591                                         continue;
7592
7593                                 ctl_clr_prkey(lun, i);
7594                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7595                         }
7596                         lun->pr_key_count = 1;
7597                         lun->res_type = type;
7598                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7599                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7600                                 lun->pr_res_idx = residx;
7601
7602                         /* send msg to other side */
7603                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7604                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7605                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7606                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7607                         persis_io.pr.pr_info.res_type = type;
7608                         memcpy(persis_io.pr.pr_info.sa_res_key,
7609                                param->serv_act_res_key,
7610                                sizeof(param->serv_act_res_key));
7611                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7612                              &persis_io, sizeof(persis_io), 0)) >
7613                              CTL_HA_STATUS_SUCCESS) {
7614                                 printf("CTL:Persis Out error returned "
7615                                        "from ctl_ha_msg_send %d\n",
7616                                        isc_retval);
7617                         }
7618                 } else {
7619                         /* not all registrants */
7620                         mtx_unlock(&lun->lun_lock);
7621                         free(ctsio->kern_data_ptr, M_CTL);
7622                         ctl_set_invalid_field(ctsio,
7623                                               /*sks_valid*/ 1,
7624                                               /*command*/ 0,
7625                                               /*field*/ 8,
7626                                               /*bit_valid*/ 0,
7627                                               /*bit*/ 0);
7628                         ctl_done((union ctl_io *)ctsio);
7629                         return (1);
7630                 }
7631         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7632                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7633                 int found = 0;
7634
7635                 if (res_key == sa_res_key) {
7636                         /* special case */
7637                         /*
7638                          * The spec implies this is not good but doesn't
7639                          * say what to do. There are two choices either
7640                          * generate a res conflict or check condition
7641                          * with illegal field in parameter data. Since
7642                          * that is what is done when the sa_res_key is
7643                          * zero I'll take that approach since this has
7644                          * to do with the sa_res_key.
7645                          */
7646                         mtx_unlock(&lun->lun_lock);
7647                         free(ctsio->kern_data_ptr, M_CTL);
7648                         ctl_set_invalid_field(ctsio,
7649                                               /*sks_valid*/ 1,
7650                                               /*command*/ 0,
7651                                               /*field*/ 8,
7652                                               /*bit_valid*/ 0,
7653                                               /*bit*/ 0);
7654                         ctl_done((union ctl_io *)ctsio);
7655                         return (1);
7656                 }
7657
7658                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7659                         if (ctl_get_prkey(lun, i) != sa_res_key)
7660                                 continue;
7661
7662                         found = 1;
7663                         ctl_clr_prkey(lun, i);
7664                         lun->pr_key_count--;
7665                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7666                 }
7667                 if (!found) {
7668                         mtx_unlock(&lun->lun_lock);
7669                         free(ctsio->kern_data_ptr, M_CTL);
7670                         ctl_set_reservation_conflict(ctsio);
7671                         ctl_done((union ctl_io *)ctsio);
7672                         return (CTL_RETVAL_COMPLETE);
7673                 }
7674                 /* send msg to other side */
7675                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7676                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7677                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7678                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7679                 persis_io.pr.pr_info.res_type = type;
7680                 memcpy(persis_io.pr.pr_info.sa_res_key,
7681                        param->serv_act_res_key,
7682                        sizeof(param->serv_act_res_key));
7683                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7684                      &persis_io, sizeof(persis_io), 0)) >
7685                      CTL_HA_STATUS_SUCCESS) {
7686                         printf("CTL:Persis Out error returned from "
7687                                "ctl_ha_msg_send %d\n", isc_retval);
7688                 }
7689         } else {
7690                 /* Reserved but not all registrants */
7691                 /* sa_res_key is res holder */
7692                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7693                         /* validate scope and type */
7694                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7695                              SPR_LU_SCOPE) {
7696                                 mtx_unlock(&lun->lun_lock);
7697                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7698                                                       /*sks_valid*/ 1,
7699                                                       /*command*/ 1,
7700                                                       /*field*/ 2,
7701                                                       /*bit_valid*/ 1,
7702                                                       /*bit*/ 4);
7703                                 ctl_done((union ctl_io *)ctsio);
7704                                 return (1);
7705                         }
7706
7707                         if (type>8 || type==2 || type==4 || type==0) {
7708                                 mtx_unlock(&lun->lun_lock);
7709                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7710                                                       /*sks_valid*/ 1,
7711                                                       /*command*/ 1,
7712                                                       /*field*/ 2,
7713                                                       /*bit_valid*/ 1,
7714                                                       /*bit*/ 0);
7715                                 ctl_done((union ctl_io *)ctsio);
7716                                 return (1);
7717                         }
7718
7719                         /*
7720                          * Do the following:
7721                          * if sa_res_key != res_key remove all
7722                          * registrants w/sa_res_key and generate UA
7723                          * for these registrants(Registrations
7724                          * Preempted) if it wasn't an exclusive
7725                          * reservation generate UA(Reservations
7726                          * Preempted) for all other registered nexuses
7727                          * if the type has changed. Establish the new
7728                          * reservation and holder. If res_key and
7729                          * sa_res_key are the same do the above
7730                          * except don't unregister the res holder.
7731                          */
7732
7733                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7734                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7735                                         continue;
7736
7737                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
7738                                         ctl_clr_prkey(lun, i);
7739                                         lun->pr_key_count--;
7740                                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7741                                 } else if (type != lun->res_type
7742                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
7743                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7744                                         ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
7745                                 }
7746                         }
7747                         lun->res_type = type;
7748                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7749                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7750                                 lun->pr_res_idx = residx;
7751                         else
7752                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7753
7754                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7755                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7756                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7757                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7758                         persis_io.pr.pr_info.res_type = type;
7759                         memcpy(persis_io.pr.pr_info.sa_res_key,
7760                                param->serv_act_res_key,
7761                                sizeof(param->serv_act_res_key));
7762                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7763                              &persis_io, sizeof(persis_io), 0)) >
7764                              CTL_HA_STATUS_SUCCESS) {
7765                                 printf("CTL:Persis Out error returned "
7766                                        "from ctl_ha_msg_send %d\n",
7767                                        isc_retval);
7768                         }
7769                 } else {
7770                         /*
7771                          * sa_res_key is not the res holder just
7772                          * remove registrants
7773                          */
7774                         int found=0;
7775
7776                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7777                                 if (sa_res_key != ctl_get_prkey(lun, i))
7778                                         continue;
7779
7780                                 found = 1;
7781                                 ctl_clr_prkey(lun, i);
7782                                 lun->pr_key_count--;
7783                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7784                         }
7785
7786                         if (!found) {
7787                                 mtx_unlock(&lun->lun_lock);
7788                                 free(ctsio->kern_data_ptr, M_CTL);
7789                                 ctl_set_reservation_conflict(ctsio);
7790                                 ctl_done((union ctl_io *)ctsio);
7791                                 return (1);
7792                         }
7793                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7794                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7795                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7796                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7797                         persis_io.pr.pr_info.res_type = type;
7798                         memcpy(persis_io.pr.pr_info.sa_res_key,
7799                                param->serv_act_res_key,
7800                                sizeof(param->serv_act_res_key));
7801                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7802                              &persis_io, sizeof(persis_io), 0)) >
7803                              CTL_HA_STATUS_SUCCESS) {
7804                                 printf("CTL:Persis Out error returned "
7805                                        "from ctl_ha_msg_send %d\n",
7806                                 isc_retval);
7807                         }
7808                 }
7809         }
7810
7811         lun->PRGeneration++;
7812         mtx_unlock(&lun->lun_lock);
7813
7814         return (retval);
7815 }
7816
7817 static void
7818 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7819 {
7820         uint64_t sa_res_key;
7821         int i;
7822
7823         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7824
7825         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7826          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7827          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7828                 if (sa_res_key == 0) {
7829                         /*
7830                          * Unregister everybody else and build UA for
7831                          * them
7832                          */
7833                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7834                                 if (i == msg->pr.pr_info.residx ||
7835                                     ctl_get_prkey(lun, i) == 0)
7836                                         continue;
7837
7838                                 ctl_clr_prkey(lun, i);
7839                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7840                         }
7841
7842                         lun->pr_key_count = 1;
7843                         lun->res_type = msg->pr.pr_info.res_type;
7844                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7845                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7846                                 lun->pr_res_idx = msg->pr.pr_info.residx;
7847                 } else {
7848                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7849                                 if (sa_res_key == ctl_get_prkey(lun, i))
7850                                         continue;
7851
7852                                 ctl_clr_prkey(lun, i);
7853                                 lun->pr_key_count--;
7854                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7855                         }
7856                 }
7857         } else {
7858                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7859                         if (i == msg->pr.pr_info.residx ||
7860                             ctl_get_prkey(lun, i) == 0)
7861                                 continue;
7862
7863                         if (sa_res_key == ctl_get_prkey(lun, i)) {
7864                                 ctl_clr_prkey(lun, i);
7865                                 lun->pr_key_count--;
7866                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7867                         } else if (msg->pr.pr_info.res_type != lun->res_type
7868                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
7869                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
7870                                 ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
7871                         }
7872                 }
7873                 lun->res_type = msg->pr.pr_info.res_type;
7874                 if (lun->res_type != SPR_TYPE_WR_EX_AR
7875                  && lun->res_type != SPR_TYPE_EX_AC_AR)
7876                         lun->pr_res_idx = msg->pr.pr_info.residx;
7877                 else
7878                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7879         }
7880         lun->PRGeneration++;
7881
7882 }
7883
7884
7885 int
7886 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
7887 {
7888         int retval;
7889         int isc_retval;
7890         u_int32_t param_len;
7891         struct scsi_per_res_out *cdb;
7892         struct ctl_lun *lun;
7893         struct scsi_per_res_out_parms* param;
7894         struct ctl_softc *softc;
7895         uint32_t residx;
7896         uint64_t res_key, sa_res_key, key;
7897         uint8_t type;
7898         union ctl_ha_msg persis_io;
7899         int    i;
7900
7901         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
7902
7903         retval = CTL_RETVAL_COMPLETE;
7904
7905         cdb = (struct scsi_per_res_out *)ctsio->cdb;
7906         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7907         softc = lun->ctl_softc;
7908
7909         /*
7910          * We only support whole-LUN scope.  The scope & type are ignored for
7911          * register, register and ignore existing key and clear.
7912          * We sometimes ignore scope and type on preempts too!!
7913          * Verify reservation type here as well.
7914          */
7915         type = cdb->scope_type & SPR_TYPE_MASK;
7916         if ((cdb->action == SPRO_RESERVE)
7917          || (cdb->action == SPRO_RELEASE)) {
7918                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
7919                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7920                                               /*sks_valid*/ 1,
7921                                               /*command*/ 1,
7922                                               /*field*/ 2,
7923                                               /*bit_valid*/ 1,
7924                                               /*bit*/ 4);
7925                         ctl_done((union ctl_io *)ctsio);
7926                         return (CTL_RETVAL_COMPLETE);
7927                 }
7928
7929                 if (type>8 || type==2 || type==4 || type==0) {
7930                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7931                                               /*sks_valid*/ 1,
7932                                               /*command*/ 1,
7933                                               /*field*/ 2,
7934                                               /*bit_valid*/ 1,
7935                                               /*bit*/ 0);
7936                         ctl_done((union ctl_io *)ctsio);
7937                         return (CTL_RETVAL_COMPLETE);
7938                 }
7939         }
7940
7941         param_len = scsi_4btoul(cdb->length);
7942
7943         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
7944                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
7945                 ctsio->kern_data_len = param_len;
7946                 ctsio->kern_total_len = param_len;
7947                 ctsio->kern_data_resid = 0;
7948                 ctsio->kern_rel_offset = 0;
7949                 ctsio->kern_sg_entries = 0;
7950                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7951                 ctsio->be_move_done = ctl_config_move_done;
7952                 ctl_datamove((union ctl_io *)ctsio);
7953
7954                 return (CTL_RETVAL_COMPLETE);
7955         }
7956
7957         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
7958
7959         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
7960         res_key = scsi_8btou64(param->res_key.key);
7961         sa_res_key = scsi_8btou64(param->serv_act_res_key);
7962
7963         /*
7964          * Validate the reservation key here except for SPRO_REG_IGNO
7965          * This must be done for all other service actions
7966          */
7967         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
7968                 mtx_lock(&lun->lun_lock);
7969                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
7970                         if (res_key != key) {
7971                                 /*
7972                                  * The current key passed in doesn't match
7973                                  * the one the initiator previously
7974                                  * registered.
7975                                  */
7976                                 mtx_unlock(&lun->lun_lock);
7977                                 free(ctsio->kern_data_ptr, M_CTL);
7978                                 ctl_set_reservation_conflict(ctsio);
7979                                 ctl_done((union ctl_io *)ctsio);
7980                                 return (CTL_RETVAL_COMPLETE);
7981                         }
7982                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
7983                         /*
7984                          * We are not registered
7985                          */
7986                         mtx_unlock(&lun->lun_lock);
7987                         free(ctsio->kern_data_ptr, M_CTL);
7988                         ctl_set_reservation_conflict(ctsio);
7989                         ctl_done((union ctl_io *)ctsio);
7990                         return (CTL_RETVAL_COMPLETE);
7991                 } else if (res_key != 0) {
7992                         /*
7993                          * We are not registered and trying to register but
7994                          * the register key isn't zero.
7995                          */
7996                         mtx_unlock(&lun->lun_lock);
7997                         free(ctsio->kern_data_ptr, M_CTL);
7998                         ctl_set_reservation_conflict(ctsio);
7999                         ctl_done((union ctl_io *)ctsio);
8000                         return (CTL_RETVAL_COMPLETE);
8001                 }
8002                 mtx_unlock(&lun->lun_lock);
8003         }
8004
8005         switch (cdb->action & SPRO_ACTION_MASK) {
8006         case SPRO_REGISTER:
8007         case SPRO_REG_IGNO: {
8008
8009 #if 0
8010                 printf("Registration received\n");
8011 #endif
8012
8013                 /*
8014                  * We don't support any of these options, as we report in
8015                  * the read capabilities request (see
8016                  * ctl_persistent_reserve_in(), above).
8017                  */
8018                 if ((param->flags & SPR_SPEC_I_PT)
8019                  || (param->flags & SPR_ALL_TG_PT)
8020                  || (param->flags & SPR_APTPL)) {
8021                         int bit_ptr;
8022
8023                         if (param->flags & SPR_APTPL)
8024                                 bit_ptr = 0;
8025                         else if (param->flags & SPR_ALL_TG_PT)
8026                                 bit_ptr = 2;
8027                         else /* SPR_SPEC_I_PT */
8028                                 bit_ptr = 3;
8029
8030                         free(ctsio->kern_data_ptr, M_CTL);
8031                         ctl_set_invalid_field(ctsio,
8032                                               /*sks_valid*/ 1,
8033                                               /*command*/ 0,
8034                                               /*field*/ 20,
8035                                               /*bit_valid*/ 1,
8036                                               /*bit*/ bit_ptr);
8037                         ctl_done((union ctl_io *)ctsio);
8038                         return (CTL_RETVAL_COMPLETE);
8039                 }
8040
8041                 mtx_lock(&lun->lun_lock);
8042
8043                 /*
8044                  * The initiator wants to clear the
8045                  * key/unregister.
8046                  */
8047                 if (sa_res_key == 0) {
8048                         if ((res_key == 0
8049                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8050                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8051                           && ctl_get_prkey(lun, residx) == 0)) {
8052                                 mtx_unlock(&lun->lun_lock);
8053                                 goto done;
8054                         }
8055
8056                         ctl_clr_prkey(lun, residx);
8057                         lun->pr_key_count--;
8058
8059                         if (residx == lun->pr_res_idx) {
8060                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8061                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8062
8063                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8064                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8065                                  && lun->pr_key_count) {
8066                                         /*
8067                                          * If the reservation is a registrants
8068                                          * only type we need to generate a UA
8069                                          * for other registered inits.  The
8070                                          * sense code should be RESERVATIONS
8071                                          * RELEASED
8072                                          */
8073
8074                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8075                                                 if (ctl_get_prkey(lun, i +
8076                                                     softc->persis_offset) == 0)
8077                                                         continue;
8078                                                 ctl_est_ua(lun, i,
8079                                                     CTL_UA_RES_RELEASE);
8080                                         }
8081                                 }
8082                                 lun->res_type = 0;
8083                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8084                                 if (lun->pr_key_count==0) {
8085                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8086                                         lun->res_type = 0;
8087                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8088                                 }
8089                         }
8090                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8091                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8092                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8093                         persis_io.pr.pr_info.residx = residx;
8094                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8095                              &persis_io, sizeof(persis_io), 0 )) >
8096                              CTL_HA_STATUS_SUCCESS) {
8097                                 printf("CTL:Persis Out error returned from "
8098                                        "ctl_ha_msg_send %d\n", isc_retval);
8099                         }
8100                 } else /* sa_res_key != 0 */ {
8101
8102                         /*
8103                          * If we aren't registered currently then increment
8104                          * the key count and set the registered flag.
8105                          */
8106                         ctl_alloc_prkey(lun, residx);
8107                         if (ctl_get_prkey(lun, residx) == 0)
8108                                 lun->pr_key_count++;
8109                         ctl_set_prkey(lun, residx, sa_res_key);
8110
8111                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8112                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8113                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8114                         persis_io.pr.pr_info.residx = residx;
8115                         memcpy(persis_io.pr.pr_info.sa_res_key,
8116                                param->serv_act_res_key,
8117                                sizeof(param->serv_act_res_key));
8118                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8119                              &persis_io, sizeof(persis_io), 0)) >
8120                              CTL_HA_STATUS_SUCCESS) {
8121                                 printf("CTL:Persis Out error returned from "
8122                                        "ctl_ha_msg_send %d\n", isc_retval);
8123                         }
8124                 }
8125                 lun->PRGeneration++;
8126                 mtx_unlock(&lun->lun_lock);
8127
8128                 break;
8129         }
8130         case SPRO_RESERVE:
8131 #if 0
8132                 printf("Reserve executed type %d\n", type);
8133 #endif
8134                 mtx_lock(&lun->lun_lock);
8135                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8136                         /*
8137                          * if this isn't the reservation holder and it's
8138                          * not a "all registrants" type or if the type is
8139                          * different then we have a conflict
8140                          */
8141                         if ((lun->pr_res_idx != residx
8142                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8143                          || lun->res_type != type) {
8144                                 mtx_unlock(&lun->lun_lock);
8145                                 free(ctsio->kern_data_ptr, M_CTL);
8146                                 ctl_set_reservation_conflict(ctsio);
8147                                 ctl_done((union ctl_io *)ctsio);
8148                                 return (CTL_RETVAL_COMPLETE);
8149                         }
8150                         mtx_unlock(&lun->lun_lock);
8151                 } else /* create a reservation */ {
8152                         /*
8153                          * If it's not an "all registrants" type record
8154                          * reservation holder
8155                          */
8156                         if (type != SPR_TYPE_WR_EX_AR
8157                          && type != SPR_TYPE_EX_AC_AR)
8158                                 lun->pr_res_idx = residx; /* Res holder */
8159                         else
8160                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8161
8162                         lun->flags |= CTL_LUN_PR_RESERVED;
8163                         lun->res_type = type;
8164
8165                         mtx_unlock(&lun->lun_lock);
8166
8167                         /* send msg to other side */
8168                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8169                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8170                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8171                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8172                         persis_io.pr.pr_info.res_type = type;
8173                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8174                              &persis_io, sizeof(persis_io), 0)) >
8175                              CTL_HA_STATUS_SUCCESS) {
8176                                 printf("CTL:Persis Out error returned from "
8177                                        "ctl_ha_msg_send %d\n", isc_retval);
8178                         }
8179                 }
8180                 break;
8181
8182         case SPRO_RELEASE:
8183                 mtx_lock(&lun->lun_lock);
8184                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8185                         /* No reservation exists return good status */
8186                         mtx_unlock(&lun->lun_lock);
8187                         goto done;
8188                 }
8189                 /*
8190                  * Is this nexus a reservation holder?
8191                  */
8192                 if (lun->pr_res_idx != residx
8193                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8194                         /*
8195                          * not a res holder return good status but
8196                          * do nothing
8197                          */
8198                         mtx_unlock(&lun->lun_lock);
8199                         goto done;
8200                 }
8201
8202                 if (lun->res_type != type) {
8203                         mtx_unlock(&lun->lun_lock);
8204                         free(ctsio->kern_data_ptr, M_CTL);
8205                         ctl_set_illegal_pr_release(ctsio);
8206                         ctl_done((union ctl_io *)ctsio);
8207                         return (CTL_RETVAL_COMPLETE);
8208                 }
8209
8210                 /* okay to release */
8211                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8212                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8213                 lun->res_type = 0;
8214
8215                 /*
8216                  * if this isn't an exclusive access
8217                  * res generate UA for all other
8218                  * registrants.
8219                  */
8220                 if (type != SPR_TYPE_EX_AC
8221                  && type != SPR_TYPE_WR_EX) {
8222                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8223                                 if (i == residx ||
8224                                     ctl_get_prkey(lun,
8225                                      i + softc->persis_offset) == 0)
8226                                         continue;
8227                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8228                         }
8229                 }
8230                 mtx_unlock(&lun->lun_lock);
8231                 /* Send msg to other side */
8232                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8233                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8234                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8235                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8236                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8237                         printf("CTL:Persis Out error returned from "
8238                                "ctl_ha_msg_send %d\n", isc_retval);
8239                 }
8240                 break;
8241
8242         case SPRO_CLEAR:
8243                 /* send msg to other side */
8244
8245                 mtx_lock(&lun->lun_lock);
8246                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8247                 lun->res_type = 0;
8248                 lun->pr_key_count = 0;
8249                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8250
8251                 ctl_clr_prkey(lun, residx);
8252                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8253                         if (ctl_get_prkey(lun, i) != 0) {
8254                                 ctl_clr_prkey(lun, i);
8255                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8256                         }
8257                 lun->PRGeneration++;
8258                 mtx_unlock(&lun->lun_lock);
8259                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8260                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8261                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8262                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8263                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8264                         printf("CTL:Persis Out error returned from "
8265                                "ctl_ha_msg_send %d\n", isc_retval);
8266                 }
8267                 break;
8268
8269         case SPRO_PREEMPT:
8270         case SPRO_PRE_ABO: {
8271                 int nretval;
8272
8273                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8274                                           residx, ctsio, cdb, param);
8275                 if (nretval != 0)
8276                         return (CTL_RETVAL_COMPLETE);
8277                 break;
8278         }
8279         default:
8280                 panic("Invalid PR type %x", cdb->action);
8281         }
8282
8283 done:
8284         free(ctsio->kern_data_ptr, M_CTL);
8285         ctl_set_success(ctsio);
8286         ctl_done((union ctl_io *)ctsio);
8287
8288         return (retval);
8289 }
8290
8291 /*
8292  * This routine is for handling a message from the other SC pertaining to
8293  * persistent reserve out. All the error checking will have been done
8294  * so only perorming the action need be done here to keep the two
8295  * in sync.
8296  */
8297 static void
8298 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8299 {
8300         struct ctl_lun *lun;
8301         struct ctl_softc *softc;
8302         int i;
8303         uint32_t targ_lun;
8304
8305         softc = control_softc;
8306
8307         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8308         lun = softc->ctl_luns[targ_lun];
8309         mtx_lock(&lun->lun_lock);
8310         switch(msg->pr.pr_info.action) {
8311         case CTL_PR_REG_KEY:
8312                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8313                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8314                         lun->pr_key_count++;
8315                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8316                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8317                 lun->PRGeneration++;
8318                 break;
8319
8320         case CTL_PR_UNREG_KEY:
8321                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8322                 lun->pr_key_count--;
8323
8324                 /* XXX Need to see if the reservation has been released */
8325                 /* if so do we need to generate UA? */
8326                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8327                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8328                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8329
8330                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8331                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8332                          && lun->pr_key_count) {
8333                                 /*
8334                                  * If the reservation is a registrants
8335                                  * only type we need to generate a UA
8336                                  * for other registered inits.  The
8337                                  * sense code should be RESERVATIONS
8338                                  * RELEASED
8339                                  */
8340
8341                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8342                                         if (ctl_get_prkey(lun, i +
8343                                             softc->persis_offset) == 0)
8344                                                 continue;
8345
8346                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8347                                 }
8348                         }
8349                         lun->res_type = 0;
8350                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8351                         if (lun->pr_key_count==0) {
8352                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8353                                 lun->res_type = 0;
8354                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8355                         }
8356                 }
8357                 lun->PRGeneration++;
8358                 break;
8359
8360         case CTL_PR_RESERVE:
8361                 lun->flags |= CTL_LUN_PR_RESERVED;
8362                 lun->res_type = msg->pr.pr_info.res_type;
8363                 lun->pr_res_idx = msg->pr.pr_info.residx;
8364
8365                 break;
8366
8367         case CTL_PR_RELEASE:
8368                 /*
8369                  * if this isn't an exclusive access res generate UA for all
8370                  * other registrants.
8371                  */
8372                 if (lun->res_type != SPR_TYPE_EX_AC
8373                  && lun->res_type != SPR_TYPE_WR_EX) {
8374                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8375                                 if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8376                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8377                 }
8378
8379                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8380                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8381                 lun->res_type = 0;
8382                 break;
8383
8384         case CTL_PR_PREEMPT:
8385                 ctl_pro_preempt_other(lun, msg);
8386                 break;
8387         case CTL_PR_CLEAR:
8388                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8389                 lun->res_type = 0;
8390                 lun->pr_key_count = 0;
8391                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8392
8393                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8394                         if (ctl_get_prkey(lun, i) == 0)
8395                                 continue;
8396                         ctl_clr_prkey(lun, i);
8397                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8398                 }
8399                 lun->PRGeneration++;
8400                 break;
8401         }
8402
8403         mtx_unlock(&lun->lun_lock);
8404 }
8405
8406 int
8407 ctl_read_write(struct ctl_scsiio *ctsio)
8408 {
8409         struct ctl_lun *lun;
8410         struct ctl_lba_len_flags *lbalen;
8411         uint64_t lba;
8412         uint32_t num_blocks;
8413         int flags, retval;
8414         int isread;
8415
8416         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8417
8418         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8419
8420         flags = 0;
8421         retval = CTL_RETVAL_COMPLETE;
8422
8423         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8424               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8425         switch (ctsio->cdb[0]) {
8426         case READ_6:
8427         case WRITE_6: {
8428                 struct scsi_rw_6 *cdb;
8429
8430                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8431
8432                 lba = scsi_3btoul(cdb->addr);
8433                 /* only 5 bits are valid in the most significant address byte */
8434                 lba &= 0x1fffff;
8435                 num_blocks = cdb->length;
8436                 /*
8437                  * This is correct according to SBC-2.
8438                  */
8439                 if (num_blocks == 0)
8440                         num_blocks = 256;
8441                 break;
8442         }
8443         case READ_10:
8444         case WRITE_10: {
8445                 struct scsi_rw_10 *cdb;
8446
8447                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8448                 if (cdb->byte2 & SRW10_FUA)
8449                         flags |= CTL_LLF_FUA;
8450                 if (cdb->byte2 & SRW10_DPO)
8451                         flags |= CTL_LLF_DPO;
8452                 lba = scsi_4btoul(cdb->addr);
8453                 num_blocks = scsi_2btoul(cdb->length);
8454                 break;
8455         }
8456         case WRITE_VERIFY_10: {
8457                 struct scsi_write_verify_10 *cdb;
8458
8459                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8460                 flags |= CTL_LLF_FUA;
8461                 if (cdb->byte2 & SWV_DPO)
8462                         flags |= CTL_LLF_DPO;
8463                 lba = scsi_4btoul(cdb->addr);
8464                 num_blocks = scsi_2btoul(cdb->length);
8465                 break;
8466         }
8467         case READ_12:
8468         case WRITE_12: {
8469                 struct scsi_rw_12 *cdb;
8470
8471                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8472                 if (cdb->byte2 & SRW12_FUA)
8473                         flags |= CTL_LLF_FUA;
8474                 if (cdb->byte2 & SRW12_DPO)
8475                         flags |= CTL_LLF_DPO;
8476                 lba = scsi_4btoul(cdb->addr);
8477                 num_blocks = scsi_4btoul(cdb->length);
8478                 break;
8479         }
8480         case WRITE_VERIFY_12: {
8481                 struct scsi_write_verify_12 *cdb;
8482
8483                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8484                 flags |= CTL_LLF_FUA;
8485                 if (cdb->byte2 & SWV_DPO)
8486                         flags |= CTL_LLF_DPO;
8487                 lba = scsi_4btoul(cdb->addr);
8488                 num_blocks = scsi_4btoul(cdb->length);
8489                 break;
8490         }
8491         case READ_16:
8492         case WRITE_16: {
8493                 struct scsi_rw_16 *cdb;
8494
8495                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8496                 if (cdb->byte2 & SRW12_FUA)
8497                         flags |= CTL_LLF_FUA;
8498                 if (cdb->byte2 & SRW12_DPO)
8499                         flags |= CTL_LLF_DPO;
8500                 lba = scsi_8btou64(cdb->addr);
8501                 num_blocks = scsi_4btoul(cdb->length);
8502                 break;
8503         }
8504         case WRITE_ATOMIC_16: {
8505                 struct scsi_rw_16 *cdb;
8506
8507                 if (lun->be_lun->atomicblock == 0) {
8508                         ctl_set_invalid_opcode(ctsio);
8509                         ctl_done((union ctl_io *)ctsio);
8510                         return (CTL_RETVAL_COMPLETE);
8511                 }
8512
8513                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8514                 if (cdb->byte2 & SRW12_FUA)
8515                         flags |= CTL_LLF_FUA;
8516                 if (cdb->byte2 & SRW12_DPO)
8517                         flags |= CTL_LLF_DPO;
8518                 lba = scsi_8btou64(cdb->addr);
8519                 num_blocks = scsi_4btoul(cdb->length);
8520                 if (num_blocks > lun->be_lun->atomicblock) {
8521                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8522                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8523                             /*bit*/ 0);
8524                         ctl_done((union ctl_io *)ctsio);
8525                         return (CTL_RETVAL_COMPLETE);
8526                 }
8527                 break;
8528         }
8529         case WRITE_VERIFY_16: {
8530                 struct scsi_write_verify_16 *cdb;
8531
8532                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8533                 flags |= CTL_LLF_FUA;
8534                 if (cdb->byte2 & SWV_DPO)
8535                         flags |= CTL_LLF_DPO;
8536                 lba = scsi_8btou64(cdb->addr);
8537                 num_blocks = scsi_4btoul(cdb->length);
8538                 break;
8539         }
8540         default:
8541                 /*
8542                  * We got a command we don't support.  This shouldn't
8543                  * happen, commands should be filtered out above us.
8544                  */
8545                 ctl_set_invalid_opcode(ctsio);
8546                 ctl_done((union ctl_io *)ctsio);
8547
8548                 return (CTL_RETVAL_COMPLETE);
8549                 break; /* NOTREACHED */
8550         }
8551
8552         /*
8553          * The first check is to make sure we're in bounds, the second
8554          * check is to catch wrap-around problems.  If the lba + num blocks
8555          * is less than the lba, then we've wrapped around and the block
8556          * range is invalid anyway.
8557          */
8558         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8559          || ((lba + num_blocks) < lba)) {
8560                 ctl_set_lba_out_of_range(ctsio);
8561                 ctl_done((union ctl_io *)ctsio);
8562                 return (CTL_RETVAL_COMPLETE);
8563         }
8564
8565         /*
8566          * According to SBC-3, a transfer length of 0 is not an error.
8567          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8568          * translates to 256 blocks for those commands.
8569          */
8570         if (num_blocks == 0) {
8571                 ctl_set_success(ctsio);
8572                 ctl_done((union ctl_io *)ctsio);
8573                 return (CTL_RETVAL_COMPLETE);
8574         }
8575
8576         /* Set FUA and/or DPO if caches are disabled. */
8577         if (isread) {
8578                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8579                     SCP_RCD) != 0)
8580                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8581         } else {
8582                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8583                     SCP_WCE) == 0)
8584                         flags |= CTL_LLF_FUA;
8585         }
8586
8587         lbalen = (struct ctl_lba_len_flags *)
8588             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8589         lbalen->lba = lba;
8590         lbalen->len = num_blocks;
8591         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8592
8593         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8594         ctsio->kern_rel_offset = 0;
8595
8596         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8597
8598         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8599
8600         return (retval);
8601 }
8602
8603 static int
8604 ctl_cnw_cont(union ctl_io *io)
8605 {
8606         struct ctl_scsiio *ctsio;
8607         struct ctl_lun *lun;
8608         struct ctl_lba_len_flags *lbalen;
8609         int retval;
8610
8611         ctsio = &io->scsiio;
8612         ctsio->io_hdr.status = CTL_STATUS_NONE;
8613         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8614         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8615         lbalen = (struct ctl_lba_len_flags *)
8616             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8617         lbalen->flags &= ~CTL_LLF_COMPARE;
8618         lbalen->flags |= CTL_LLF_WRITE;
8619
8620         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8621         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8622         return (retval);
8623 }
8624
8625 int
8626 ctl_cnw(struct ctl_scsiio *ctsio)
8627 {
8628         struct ctl_lun *lun;
8629         struct ctl_lba_len_flags *lbalen;
8630         uint64_t lba;
8631         uint32_t num_blocks;
8632         int flags, retval;
8633
8634         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8635
8636         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8637
8638         flags = 0;
8639         retval = CTL_RETVAL_COMPLETE;
8640
8641         switch (ctsio->cdb[0]) {
8642         case COMPARE_AND_WRITE: {
8643                 struct scsi_compare_and_write *cdb;
8644
8645                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8646                 if (cdb->byte2 & SRW10_FUA)
8647                         flags |= CTL_LLF_FUA;
8648                 if (cdb->byte2 & SRW10_DPO)
8649                         flags |= CTL_LLF_DPO;
8650                 lba = scsi_8btou64(cdb->addr);
8651                 num_blocks = cdb->length;
8652                 break;
8653         }
8654         default:
8655                 /*
8656                  * We got a command we don't support.  This shouldn't
8657                  * happen, commands should be filtered out above us.
8658                  */
8659                 ctl_set_invalid_opcode(ctsio);
8660                 ctl_done((union ctl_io *)ctsio);
8661
8662                 return (CTL_RETVAL_COMPLETE);
8663                 break; /* NOTREACHED */
8664         }
8665
8666         /*
8667          * The first check is to make sure we're in bounds, the second
8668          * check is to catch wrap-around problems.  If the lba + num blocks
8669          * is less than the lba, then we've wrapped around and the block
8670          * range is invalid anyway.
8671          */
8672         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8673          || ((lba + num_blocks) < lba)) {
8674                 ctl_set_lba_out_of_range(ctsio);
8675                 ctl_done((union ctl_io *)ctsio);
8676                 return (CTL_RETVAL_COMPLETE);
8677         }
8678
8679         /*
8680          * According to SBC-3, a transfer length of 0 is not an error.
8681          */
8682         if (num_blocks == 0) {
8683                 ctl_set_success(ctsio);
8684                 ctl_done((union ctl_io *)ctsio);
8685                 return (CTL_RETVAL_COMPLETE);
8686         }
8687
8688         /* Set FUA if write cache is disabled. */
8689         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8690             SCP_WCE) == 0)
8691                 flags |= CTL_LLF_FUA;
8692
8693         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8694         ctsio->kern_rel_offset = 0;
8695
8696         /*
8697          * Set the IO_CONT flag, so that if this I/O gets passed to
8698          * ctl_data_submit_done(), it'll get passed back to
8699          * ctl_ctl_cnw_cont() for further processing.
8700          */
8701         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8702         ctsio->io_cont = ctl_cnw_cont;
8703
8704         lbalen = (struct ctl_lba_len_flags *)
8705             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8706         lbalen->lba = lba;
8707         lbalen->len = num_blocks;
8708         lbalen->flags = CTL_LLF_COMPARE | flags;
8709
8710         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8711         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8712         return (retval);
8713 }
8714
8715 int
8716 ctl_verify(struct ctl_scsiio *ctsio)
8717 {
8718         struct ctl_lun *lun;
8719         struct ctl_lba_len_flags *lbalen;
8720         uint64_t lba;
8721         uint32_t num_blocks;
8722         int bytchk, flags;
8723         int retval;
8724
8725         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8726
8727         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8728
8729         bytchk = 0;
8730         flags = CTL_LLF_FUA;
8731         retval = CTL_RETVAL_COMPLETE;
8732
8733         switch (ctsio->cdb[0]) {
8734         case VERIFY_10: {
8735                 struct scsi_verify_10 *cdb;
8736
8737                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
8738                 if (cdb->byte2 & SVFY_BYTCHK)
8739                         bytchk = 1;
8740                 if (cdb->byte2 & SVFY_DPO)
8741                         flags |= CTL_LLF_DPO;
8742                 lba = scsi_4btoul(cdb->addr);
8743                 num_blocks = scsi_2btoul(cdb->length);
8744                 break;
8745         }
8746         case VERIFY_12: {
8747                 struct scsi_verify_12 *cdb;
8748
8749                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
8750                 if (cdb->byte2 & SVFY_BYTCHK)
8751                         bytchk = 1;
8752                 if (cdb->byte2 & SVFY_DPO)
8753                         flags |= CTL_LLF_DPO;
8754                 lba = scsi_4btoul(cdb->addr);
8755                 num_blocks = scsi_4btoul(cdb->length);
8756                 break;
8757         }
8758         case VERIFY_16: {
8759                 struct scsi_rw_16 *cdb;
8760
8761                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8762                 if (cdb->byte2 & SVFY_BYTCHK)
8763                         bytchk = 1;
8764                 if (cdb->byte2 & SVFY_DPO)
8765                         flags |= CTL_LLF_DPO;
8766                 lba = scsi_8btou64(cdb->addr);
8767                 num_blocks = scsi_4btoul(cdb->length);
8768                 break;
8769         }
8770         default:
8771                 /*
8772                  * We got a command we don't support.  This shouldn't
8773                  * happen, commands should be filtered out above us.
8774                  */
8775                 ctl_set_invalid_opcode(ctsio);
8776                 ctl_done((union ctl_io *)ctsio);
8777                 return (CTL_RETVAL_COMPLETE);
8778         }
8779
8780         /*
8781          * The first check is to make sure we're in bounds, the second
8782          * check is to catch wrap-around problems.  If the lba + num blocks
8783          * is less than the lba, then we've wrapped around and the block
8784          * range is invalid anyway.
8785          */
8786         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8787          || ((lba + num_blocks) < lba)) {
8788                 ctl_set_lba_out_of_range(ctsio);
8789                 ctl_done((union ctl_io *)ctsio);
8790                 return (CTL_RETVAL_COMPLETE);
8791         }
8792
8793         /*
8794          * According to SBC-3, a transfer length of 0 is not an error.
8795          */
8796         if (num_blocks == 0) {
8797                 ctl_set_success(ctsio);
8798                 ctl_done((union ctl_io *)ctsio);
8799                 return (CTL_RETVAL_COMPLETE);
8800         }
8801
8802         lbalen = (struct ctl_lba_len_flags *)
8803             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8804         lbalen->lba = lba;
8805         lbalen->len = num_blocks;
8806         if (bytchk) {
8807                 lbalen->flags = CTL_LLF_COMPARE | flags;
8808                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8809         } else {
8810                 lbalen->flags = CTL_LLF_VERIFY | flags;
8811                 ctsio->kern_total_len = 0;
8812         }
8813         ctsio->kern_rel_offset = 0;
8814
8815         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8816         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8817         return (retval);
8818 }
8819
8820 int
8821 ctl_report_luns(struct ctl_scsiio *ctsio)
8822 {
8823         struct ctl_softc *softc = control_softc;
8824         struct scsi_report_luns *cdb;
8825         struct scsi_report_luns_data *lun_data;
8826         struct ctl_lun *lun, *request_lun;
8827         struct ctl_port *port;
8828         int num_luns, retval;
8829         uint32_t alloc_len, lun_datalen;
8830         int num_filled, well_known;
8831         uint32_t initidx, targ_lun_id, lun_id;
8832
8833         retval = CTL_RETVAL_COMPLETE;
8834         well_known = 0;
8835
8836         cdb = (struct scsi_report_luns *)ctsio->cdb;
8837         port = ctl_io_port(&ctsio->io_hdr);
8838
8839         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8840
8841         mtx_lock(&softc->ctl_lock);
8842         num_luns = 0;
8843         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8844                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8845                         num_luns++;
8846         }
8847         mtx_unlock(&softc->ctl_lock);
8848
8849         switch (cdb->select_report) {
8850         case RPL_REPORT_DEFAULT:
8851         case RPL_REPORT_ALL:
8852                 break;
8853         case RPL_REPORT_WELLKNOWN:
8854                 well_known = 1;
8855                 num_luns = 0;
8856                 break;
8857         default:
8858                 ctl_set_invalid_field(ctsio,
8859                                       /*sks_valid*/ 1,
8860                                       /*command*/ 1,
8861                                       /*field*/ 2,
8862                                       /*bit_valid*/ 0,
8863                                       /*bit*/ 0);
8864                 ctl_done((union ctl_io *)ctsio);
8865                 return (retval);
8866                 break; /* NOTREACHED */
8867         }
8868
8869         alloc_len = scsi_4btoul(cdb->length);
8870         /*
8871          * The initiator has to allocate at least 16 bytes for this request,
8872          * so he can at least get the header and the first LUN.  Otherwise
8873          * we reject the request (per SPC-3 rev 14, section 6.21).
8874          */
8875         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
8876             sizeof(struct scsi_report_luns_lundata))) {
8877                 ctl_set_invalid_field(ctsio,
8878                                       /*sks_valid*/ 1,
8879                                       /*command*/ 1,
8880                                       /*field*/ 6,
8881                                       /*bit_valid*/ 0,
8882                                       /*bit*/ 0);
8883                 ctl_done((union ctl_io *)ctsio);
8884                 return (retval);
8885         }
8886
8887         request_lun = (struct ctl_lun *)
8888                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8889
8890         lun_datalen = sizeof(*lun_data) +
8891                 (num_luns * sizeof(struct scsi_report_luns_lundata));
8892
8893         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
8894         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
8895         ctsio->kern_sg_entries = 0;
8896
8897         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8898
8899         mtx_lock(&softc->ctl_lock);
8900         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
8901                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
8902                 if (lun_id >= CTL_MAX_LUNS)
8903                         continue;
8904                 lun = softc->ctl_luns[lun_id];
8905                 if (lun == NULL)
8906                         continue;
8907
8908                 if (targ_lun_id <= 0xff) {
8909                         /*
8910                          * Peripheral addressing method, bus number 0.
8911                          */
8912                         lun_data->luns[num_filled].lundata[0] =
8913                                 RPL_LUNDATA_ATYP_PERIPH;
8914                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
8915                         num_filled++;
8916                 } else if (targ_lun_id <= 0x3fff) {
8917                         /*
8918                          * Flat addressing method.
8919                          */
8920                         lun_data->luns[num_filled].lundata[0] =
8921                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
8922                         lun_data->luns[num_filled].lundata[1] =
8923                                 (targ_lun_id & 0xff);
8924                         num_filled++;
8925                 } else if (targ_lun_id <= 0xffffff) {
8926                         /*
8927                          * Extended flat addressing method.
8928                          */
8929                         lun_data->luns[num_filled].lundata[0] =
8930                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
8931                         scsi_ulto3b(targ_lun_id,
8932                             &lun_data->luns[num_filled].lundata[1]);
8933                         num_filled++;
8934                 } else {
8935                         printf("ctl_report_luns: bogus LUN number %jd, "
8936                                "skipping\n", (intmax_t)targ_lun_id);
8937                 }
8938                 /*
8939                  * According to SPC-3, rev 14 section 6.21:
8940                  *
8941                  * "The execution of a REPORT LUNS command to any valid and
8942                  * installed logical unit shall clear the REPORTED LUNS DATA
8943                  * HAS CHANGED unit attention condition for all logical
8944                  * units of that target with respect to the requesting
8945                  * initiator. A valid and installed logical unit is one
8946                  * having a PERIPHERAL QUALIFIER of 000b in the standard
8947                  * INQUIRY data (see 6.4.2)."
8948                  *
8949                  * If request_lun is NULL, the LUN this report luns command
8950                  * was issued to is either disabled or doesn't exist. In that
8951                  * case, we shouldn't clear any pending lun change unit
8952                  * attention.
8953                  */
8954                 if (request_lun != NULL) {
8955                         mtx_lock(&lun->lun_lock);
8956                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
8957                         mtx_unlock(&lun->lun_lock);
8958                 }
8959         }
8960         mtx_unlock(&softc->ctl_lock);
8961
8962         /*
8963          * It's quite possible that we've returned fewer LUNs than we allocated
8964          * space for.  Trim it.
8965          */
8966         lun_datalen = sizeof(*lun_data) +
8967                 (num_filled * sizeof(struct scsi_report_luns_lundata));
8968
8969         if (lun_datalen < alloc_len) {
8970                 ctsio->residual = alloc_len - lun_datalen;
8971                 ctsio->kern_data_len = lun_datalen;
8972                 ctsio->kern_total_len = lun_datalen;
8973         } else {
8974                 ctsio->residual = 0;
8975                 ctsio->kern_data_len = alloc_len;
8976                 ctsio->kern_total_len = alloc_len;
8977         }
8978         ctsio->kern_data_resid = 0;
8979         ctsio->kern_rel_offset = 0;
8980         ctsio->kern_sg_entries = 0;
8981
8982         /*
8983          * We set this to the actual data length, regardless of how much
8984          * space we actually have to return results.  If the user looks at
8985          * this value, he'll know whether or not he allocated enough space
8986          * and reissue the command if necessary.  We don't support well
8987          * known logical units, so if the user asks for that, return none.
8988          */
8989         scsi_ulto4b(lun_datalen - 8, lun_data->length);
8990
8991         /*
8992          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
8993          * this request.
8994          */
8995         ctl_set_success(ctsio);
8996         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8997         ctsio->be_move_done = ctl_config_move_done;
8998         ctl_datamove((union ctl_io *)ctsio);
8999         return (retval);
9000 }
9001
9002 int
9003 ctl_request_sense(struct ctl_scsiio *ctsio)
9004 {
9005         struct scsi_request_sense *cdb;
9006         struct scsi_sense_data *sense_ptr;
9007         struct ctl_softc *ctl_softc;
9008         struct ctl_lun *lun;
9009         uint32_t initidx;
9010         int have_error;
9011         scsi_sense_data_type sense_format;
9012         ctl_ua_type ua_type;
9013
9014         cdb = (struct scsi_request_sense *)ctsio->cdb;
9015
9016         ctl_softc = control_softc;
9017         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9018
9019         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9020
9021         /*
9022          * Determine which sense format the user wants.
9023          */
9024         if (cdb->byte2 & SRS_DESC)
9025                 sense_format = SSD_TYPE_DESC;
9026         else
9027                 sense_format = SSD_TYPE_FIXED;
9028
9029         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9030         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9031         ctsio->kern_sg_entries = 0;
9032
9033         /*
9034          * struct scsi_sense_data, which is currently set to 256 bytes, is
9035          * larger than the largest allowed value for the length field in the
9036          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9037          */
9038         ctsio->residual = 0;
9039         ctsio->kern_data_len = cdb->length;
9040         ctsio->kern_total_len = cdb->length;
9041
9042         ctsio->kern_data_resid = 0;
9043         ctsio->kern_rel_offset = 0;
9044         ctsio->kern_sg_entries = 0;
9045
9046         /*
9047          * If we don't have a LUN, we don't have any pending sense.
9048          */
9049         if (lun == NULL)
9050                 goto no_sense;
9051
9052         have_error = 0;
9053         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9054         /*
9055          * Check for pending sense, and then for pending unit attentions.
9056          * Pending sense gets returned first, then pending unit attentions.
9057          */
9058         mtx_lock(&lun->lun_lock);
9059 #ifdef CTL_WITH_CA
9060         if (ctl_is_set(lun->have_ca, initidx)) {
9061                 scsi_sense_data_type stored_format;
9062
9063                 /*
9064                  * Check to see which sense format was used for the stored
9065                  * sense data.
9066                  */
9067                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9068
9069                 /*
9070                  * If the user requested a different sense format than the
9071                  * one we stored, then we need to convert it to the other
9072                  * format.  If we're going from descriptor to fixed format
9073                  * sense data, we may lose things in translation, depending
9074                  * on what options were used.
9075                  *
9076                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9077                  * for some reason we'll just copy it out as-is.
9078                  */
9079                 if ((stored_format == SSD_TYPE_FIXED)
9080                  && (sense_format == SSD_TYPE_DESC))
9081                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9082                             &lun->pending_sense[initidx],
9083                             (struct scsi_sense_data_desc *)sense_ptr);
9084                 else if ((stored_format == SSD_TYPE_DESC)
9085                       && (sense_format == SSD_TYPE_FIXED))
9086                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9087                             &lun->pending_sense[initidx],
9088                             (struct scsi_sense_data_fixed *)sense_ptr);
9089                 else
9090                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9091                                MIN(sizeof(*sense_ptr),
9092                                sizeof(lun->pending_sense[initidx])));
9093
9094                 ctl_clear_mask(lun->have_ca, initidx);
9095                 have_error = 1;
9096         } else
9097 #endif
9098         {
9099                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9100                 if (ua_type != CTL_UA_NONE)
9101                         have_error = 1;
9102                 if (ua_type == CTL_UA_LUN_CHANGE) {
9103                         mtx_unlock(&lun->lun_lock);
9104                         mtx_lock(&ctl_softc->ctl_lock);
9105                         ctl_clear_ua(ctl_softc, initidx, ua_type);
9106                         mtx_unlock(&ctl_softc->ctl_lock);
9107                         mtx_lock(&lun->lun_lock);
9108                 }
9109
9110         }
9111         mtx_unlock(&lun->lun_lock);
9112
9113         /*
9114          * We already have a pending error, return it.
9115          */
9116         if (have_error != 0) {
9117                 /*
9118                  * We report the SCSI status as OK, since the status of the
9119                  * request sense command itself is OK.
9120                  * We report 0 for the sense length, because we aren't doing
9121                  * autosense in this case.  We're reporting sense as
9122                  * parameter data.
9123                  */
9124                 ctl_set_success(ctsio);
9125                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9126                 ctsio->be_move_done = ctl_config_move_done;
9127                 ctl_datamove((union ctl_io *)ctsio);
9128                 return (CTL_RETVAL_COMPLETE);
9129         }
9130
9131 no_sense:
9132
9133         /*
9134          * No sense information to report, so we report that everything is
9135          * okay.
9136          */
9137         ctl_set_sense_data(sense_ptr,
9138                            lun,
9139                            sense_format,
9140                            /*current_error*/ 1,
9141                            /*sense_key*/ SSD_KEY_NO_SENSE,
9142                            /*asc*/ 0x00,
9143                            /*ascq*/ 0x00,
9144                            SSD_ELEM_NONE);
9145
9146         /*
9147          * We report 0 for the sense length, because we aren't doing
9148          * autosense in this case.  We're reporting sense as parameter data.
9149          */
9150         ctl_set_success(ctsio);
9151         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9152         ctsio->be_move_done = ctl_config_move_done;
9153         ctl_datamove((union ctl_io *)ctsio);
9154         return (CTL_RETVAL_COMPLETE);
9155 }
9156
9157 int
9158 ctl_tur(struct ctl_scsiio *ctsio)
9159 {
9160
9161         CTL_DEBUG_PRINT(("ctl_tur\n"));
9162
9163         ctl_set_success(ctsio);
9164         ctl_done((union ctl_io *)ctsio);
9165
9166         return (CTL_RETVAL_COMPLETE);
9167 }
9168
9169 #ifdef notyet
9170 static int
9171 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9172 {
9173
9174 }
9175 #endif
9176
9177 /*
9178  * SCSI VPD page 0x00, the Supported VPD Pages page.
9179  */
9180 static int
9181 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9182 {
9183         struct scsi_vpd_supported_pages *pages;
9184         int sup_page_size;
9185         struct ctl_lun *lun;
9186         int p;
9187
9188         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9189
9190         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9191             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9192         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9193         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9194         ctsio->kern_sg_entries = 0;
9195
9196         if (sup_page_size < alloc_len) {
9197                 ctsio->residual = alloc_len - sup_page_size;
9198                 ctsio->kern_data_len = sup_page_size;
9199                 ctsio->kern_total_len = sup_page_size;
9200         } else {
9201                 ctsio->residual = 0;
9202                 ctsio->kern_data_len = alloc_len;
9203                 ctsio->kern_total_len = alloc_len;
9204         }
9205         ctsio->kern_data_resid = 0;
9206         ctsio->kern_rel_offset = 0;
9207         ctsio->kern_sg_entries = 0;
9208
9209         /*
9210          * The control device is always connected.  The disk device, on the
9211          * other hand, may not be online all the time.  Need to change this
9212          * to figure out whether the disk device is actually online or not.
9213          */
9214         if (lun != NULL)
9215                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9216                                 lun->be_lun->lun_type;
9217         else
9218                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9219
9220         p = 0;
9221         /* Supported VPD pages */
9222         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9223         /* Serial Number */
9224         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9225         /* Device Identification */
9226         pages->page_list[p++] = SVPD_DEVICE_ID;
9227         /* Extended INQUIRY Data */
9228         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9229         /* Mode Page Policy */
9230         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9231         /* SCSI Ports */
9232         pages->page_list[p++] = SVPD_SCSI_PORTS;
9233         /* Third-party Copy */
9234         pages->page_list[p++] = SVPD_SCSI_TPC;
9235         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9236                 /* Block limits */
9237                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9238                 /* Block Device Characteristics */
9239                 pages->page_list[p++] = SVPD_BDC;
9240                 /* Logical Block Provisioning */
9241                 pages->page_list[p++] = SVPD_LBP;
9242         }
9243         pages->length = p;
9244
9245         ctl_set_success(ctsio);
9246         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9247         ctsio->be_move_done = ctl_config_move_done;
9248         ctl_datamove((union ctl_io *)ctsio);
9249         return (CTL_RETVAL_COMPLETE);
9250 }
9251
9252 /*
9253  * SCSI VPD page 0x80, the Unit Serial Number page.
9254  */
9255 static int
9256 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9257 {
9258         struct scsi_vpd_unit_serial_number *sn_ptr;
9259         struct ctl_lun *lun;
9260         int data_len;
9261
9262         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9263
9264         data_len = 4 + CTL_SN_LEN;
9265         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9266         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9267         if (data_len < alloc_len) {
9268                 ctsio->residual = alloc_len - data_len;
9269                 ctsio->kern_data_len = data_len;
9270                 ctsio->kern_total_len = data_len;
9271         } else {
9272                 ctsio->residual = 0;
9273                 ctsio->kern_data_len = alloc_len;
9274                 ctsio->kern_total_len = alloc_len;
9275         }
9276         ctsio->kern_data_resid = 0;
9277         ctsio->kern_rel_offset = 0;
9278         ctsio->kern_sg_entries = 0;
9279
9280         /*
9281          * The control device is always connected.  The disk device, on the
9282          * other hand, may not be online all the time.  Need to change this
9283          * to figure out whether the disk device is actually online or not.
9284          */
9285         if (lun != NULL)
9286                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9287                                   lun->be_lun->lun_type;
9288         else
9289                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9290
9291         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9292         sn_ptr->length = CTL_SN_LEN;
9293         /*
9294          * If we don't have a LUN, we just leave the serial number as
9295          * all spaces.
9296          */
9297         if (lun != NULL) {
9298                 strncpy((char *)sn_ptr->serial_num,
9299                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9300         } else
9301                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9302
9303         ctl_set_success(ctsio);
9304         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9305         ctsio->be_move_done = ctl_config_move_done;
9306         ctl_datamove((union ctl_io *)ctsio);
9307         return (CTL_RETVAL_COMPLETE);
9308 }
9309
9310
9311 /*
9312  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9313  */
9314 static int
9315 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9316 {
9317         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9318         struct ctl_lun *lun;
9319         int data_len;
9320
9321         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9322
9323         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9324         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9325         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9326         ctsio->kern_sg_entries = 0;
9327
9328         if (data_len < alloc_len) {
9329                 ctsio->residual = alloc_len - data_len;
9330                 ctsio->kern_data_len = data_len;
9331                 ctsio->kern_total_len = data_len;
9332         } else {
9333                 ctsio->residual = 0;
9334                 ctsio->kern_data_len = alloc_len;
9335                 ctsio->kern_total_len = alloc_len;
9336         }
9337         ctsio->kern_data_resid = 0;
9338         ctsio->kern_rel_offset = 0;
9339         ctsio->kern_sg_entries = 0;
9340
9341         /*
9342          * The control device is always connected.  The disk device, on the
9343          * other hand, may not be online all the time.
9344          */
9345         if (lun != NULL)
9346                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9347                                      lun->be_lun->lun_type;
9348         else
9349                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9350         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9351         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9352         /*
9353          * We support head of queue, ordered and simple tags.
9354          */
9355         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9356         /*
9357          * Volatile cache supported.
9358          */
9359         eid_ptr->flags3 = SVPD_EID_V_SUP;
9360
9361         /*
9362          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9363          * attention for a particular IT nexus on all LUNs once we report
9364          * it to that nexus once.  This bit is required as of SPC-4.
9365          */
9366         eid_ptr->flags4 = SVPD_EID_LUICLT;
9367
9368         /*
9369          * XXX KDM in order to correctly answer this, we would need
9370          * information from the SIM to determine how much sense data it
9371          * can send.  So this would really be a path inquiry field, most
9372          * likely.  This can be set to a maximum of 252 according to SPC-4,
9373          * but the hardware may or may not be able to support that much.
9374          * 0 just means that the maximum sense data length is not reported.
9375          */
9376         eid_ptr->max_sense_length = 0;
9377
9378         ctl_set_success(ctsio);
9379         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9380         ctsio->be_move_done = ctl_config_move_done;
9381         ctl_datamove((union ctl_io *)ctsio);
9382         return (CTL_RETVAL_COMPLETE);
9383 }
9384
9385 static int
9386 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9387 {
9388         struct scsi_vpd_mode_page_policy *mpp_ptr;
9389         struct ctl_lun *lun;
9390         int data_len;
9391
9392         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9393
9394         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9395             sizeof(struct scsi_vpd_mode_page_policy_descr);
9396
9397         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9398         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9399         ctsio->kern_sg_entries = 0;
9400
9401         if (data_len < alloc_len) {
9402                 ctsio->residual = alloc_len - data_len;
9403                 ctsio->kern_data_len = data_len;
9404                 ctsio->kern_total_len = data_len;
9405         } else {
9406                 ctsio->residual = 0;
9407                 ctsio->kern_data_len = alloc_len;
9408                 ctsio->kern_total_len = alloc_len;
9409         }
9410         ctsio->kern_data_resid = 0;
9411         ctsio->kern_rel_offset = 0;
9412         ctsio->kern_sg_entries = 0;
9413
9414         /*
9415          * The control device is always connected.  The disk device, on the
9416          * other hand, may not be online all the time.
9417          */
9418         if (lun != NULL)
9419                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9420                                      lun->be_lun->lun_type;
9421         else
9422                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9423         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9424         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9425         mpp_ptr->descr[0].page_code = 0x3f;
9426         mpp_ptr->descr[0].subpage_code = 0xff;
9427         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9428
9429         ctl_set_success(ctsio);
9430         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9431         ctsio->be_move_done = ctl_config_move_done;
9432         ctl_datamove((union ctl_io *)ctsio);
9433         return (CTL_RETVAL_COMPLETE);
9434 }
9435
9436 /*
9437  * SCSI VPD page 0x83, the Device Identification page.
9438  */
9439 static int
9440 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9441 {
9442         struct scsi_vpd_device_id *devid_ptr;
9443         struct scsi_vpd_id_descriptor *desc;
9444         struct ctl_softc *softc;
9445         struct ctl_lun *lun;
9446         struct ctl_port *port;
9447         int data_len;
9448         uint8_t proto;
9449
9450         softc = control_softc;
9451
9452         port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9453         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9454
9455         data_len = sizeof(struct scsi_vpd_device_id) +
9456             sizeof(struct scsi_vpd_id_descriptor) +
9457                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9458             sizeof(struct scsi_vpd_id_descriptor) +
9459                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9460         if (lun && lun->lun_devid)
9461                 data_len += lun->lun_devid->len;
9462         if (port->port_devid)
9463                 data_len += port->port_devid->len;
9464         if (port->target_devid)
9465                 data_len += port->target_devid->len;
9466
9467         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9468         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9469         ctsio->kern_sg_entries = 0;
9470
9471         if (data_len < alloc_len) {
9472                 ctsio->residual = alloc_len - data_len;
9473                 ctsio->kern_data_len = data_len;
9474                 ctsio->kern_total_len = data_len;
9475         } else {
9476                 ctsio->residual = 0;
9477                 ctsio->kern_data_len = alloc_len;
9478                 ctsio->kern_total_len = alloc_len;
9479         }
9480         ctsio->kern_data_resid = 0;
9481         ctsio->kern_rel_offset = 0;
9482         ctsio->kern_sg_entries = 0;
9483
9484         /*
9485          * The control device is always connected.  The disk device, on the
9486          * other hand, may not be online all the time.
9487          */
9488         if (lun != NULL)
9489                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9490                                      lun->be_lun->lun_type;
9491         else
9492                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9493         devid_ptr->page_code = SVPD_DEVICE_ID;
9494         scsi_ulto2b(data_len - 4, devid_ptr->length);
9495
9496         if (port->port_type == CTL_PORT_FC)
9497                 proto = SCSI_PROTO_FC << 4;
9498         else if (port->port_type == CTL_PORT_ISCSI)
9499                 proto = SCSI_PROTO_ISCSI << 4;
9500         else
9501                 proto = SCSI_PROTO_SPI << 4;
9502         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9503
9504         /*
9505          * We're using a LUN association here.  i.e., this device ID is a
9506          * per-LUN identifier.
9507          */
9508         if (lun && lun->lun_devid) {
9509                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9510                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9511                     lun->lun_devid->len);
9512         }
9513
9514         /*
9515          * This is for the WWPN which is a port association.
9516          */
9517         if (port->port_devid) {
9518                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9519                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9520                     port->port_devid->len);
9521         }
9522
9523         /*
9524          * This is for the Relative Target Port(type 4h) identifier
9525          */
9526         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9527         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9528             SVPD_ID_TYPE_RELTARG;
9529         desc->length = 4;
9530         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9531         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9532             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9533
9534         /*
9535          * This is for the Target Port Group(type 5h) identifier
9536          */
9537         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9538         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9539             SVPD_ID_TYPE_TPORTGRP;
9540         desc->length = 4;
9541         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9542             &desc->identifier[2]);
9543         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9544             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9545
9546         /*
9547          * This is for the Target identifier
9548          */
9549         if (port->target_devid) {
9550                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9551         }
9552
9553         ctl_set_success(ctsio);
9554         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9555         ctsio->be_move_done = ctl_config_move_done;
9556         ctl_datamove((union ctl_io *)ctsio);
9557         return (CTL_RETVAL_COMPLETE);
9558 }
9559
9560 static int
9561 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9562 {
9563         struct ctl_softc *softc = control_softc;
9564         struct scsi_vpd_scsi_ports *sp;
9565         struct scsi_vpd_port_designation *pd;
9566         struct scsi_vpd_port_designation_cont *pdc;
9567         struct ctl_lun *lun;
9568         struct ctl_port *port;
9569         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9570         int num_target_port_groups;
9571
9572         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9573
9574         if (softc->is_single)
9575                 num_target_port_groups = 1;
9576         else
9577                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9578         num_target_ports = 0;
9579         iid_len = 0;
9580         id_len = 0;
9581         mtx_lock(&softc->ctl_lock);
9582         STAILQ_FOREACH(port, &softc->port_list, links) {
9583                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9584                         continue;
9585                 if (lun != NULL &&
9586                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9587                         continue;
9588                 num_target_ports++;
9589                 if (port->init_devid)
9590                         iid_len += port->init_devid->len;
9591                 if (port->port_devid)
9592                         id_len += port->port_devid->len;
9593         }
9594         mtx_unlock(&softc->ctl_lock);
9595
9596         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9597             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9598              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9599         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9600         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9601         ctsio->kern_sg_entries = 0;
9602
9603         if (data_len < alloc_len) {
9604                 ctsio->residual = alloc_len - data_len;
9605                 ctsio->kern_data_len = data_len;
9606                 ctsio->kern_total_len = data_len;
9607         } else {
9608                 ctsio->residual = 0;
9609                 ctsio->kern_data_len = alloc_len;
9610                 ctsio->kern_total_len = alloc_len;
9611         }
9612         ctsio->kern_data_resid = 0;
9613         ctsio->kern_rel_offset = 0;
9614         ctsio->kern_sg_entries = 0;
9615
9616         /*
9617          * The control device is always connected.  The disk device, on the
9618          * other hand, may not be online all the time.  Need to change this
9619          * to figure out whether the disk device is actually online or not.
9620          */
9621         if (lun != NULL)
9622                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9623                                   lun->be_lun->lun_type;
9624         else
9625                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9626
9627         sp->page_code = SVPD_SCSI_PORTS;
9628         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9629             sp->page_length);
9630         pd = &sp->design[0];
9631
9632         mtx_lock(&softc->ctl_lock);
9633         pg = softc->port_offset / CTL_MAX_PORTS;
9634         for (g = 0; g < num_target_port_groups; g++) {
9635                 STAILQ_FOREACH(port, &softc->port_list, links) {
9636                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9637                                 continue;
9638                         if (lun != NULL &&
9639                             ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9640                                 continue;
9641                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9642                         scsi_ulto2b(p, pd->relative_port_id);
9643                         if (port->init_devid && g == pg) {
9644                                 iid_len = port->init_devid->len;
9645                                 memcpy(pd->initiator_transportid,
9646                                     port->init_devid->data, port->init_devid->len);
9647                         } else
9648                                 iid_len = 0;
9649                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9650                         pdc = (struct scsi_vpd_port_designation_cont *)
9651                             (&pd->initiator_transportid[iid_len]);
9652                         if (port->port_devid && g == pg) {
9653                                 id_len = port->port_devid->len;
9654                                 memcpy(pdc->target_port_descriptors,
9655                                     port->port_devid->data, port->port_devid->len);
9656                         } else
9657                                 id_len = 0;
9658                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9659                         pd = (struct scsi_vpd_port_designation *)
9660                             ((uint8_t *)pdc->target_port_descriptors + id_len);
9661                 }
9662         }
9663         mtx_unlock(&softc->ctl_lock);
9664
9665         ctl_set_success(ctsio);
9666         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9667         ctsio->be_move_done = ctl_config_move_done;
9668         ctl_datamove((union ctl_io *)ctsio);
9669         return (CTL_RETVAL_COMPLETE);
9670 }
9671
9672 static int
9673 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9674 {
9675         struct scsi_vpd_block_limits *bl_ptr;
9676         struct ctl_lun *lun;
9677         int bs;
9678
9679         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9680
9681         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9682         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9683         ctsio->kern_sg_entries = 0;
9684
9685         if (sizeof(*bl_ptr) < alloc_len) {
9686                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9687                 ctsio->kern_data_len = sizeof(*bl_ptr);
9688                 ctsio->kern_total_len = sizeof(*bl_ptr);
9689         } else {
9690                 ctsio->residual = 0;
9691                 ctsio->kern_data_len = alloc_len;
9692                 ctsio->kern_total_len = alloc_len;
9693         }
9694         ctsio->kern_data_resid = 0;
9695         ctsio->kern_rel_offset = 0;
9696         ctsio->kern_sg_entries = 0;
9697
9698         /*
9699          * The control device is always connected.  The disk device, on the
9700          * other hand, may not be online all the time.  Need to change this
9701          * to figure out whether the disk device is actually online or not.
9702          */
9703         if (lun != NULL)
9704                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9705                                   lun->be_lun->lun_type;
9706         else
9707                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9708
9709         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9710         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9711         bl_ptr->max_cmp_write_len = 0xff;
9712         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9713         if (lun != NULL) {
9714                 bs = lun->be_lun->blocksize;
9715                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9716                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9717                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9718                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9719                         if (lun->be_lun->ublockexp != 0) {
9720                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
9721                                     bl_ptr->opt_unmap_grain);
9722                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9723                                     bl_ptr->unmap_grain_align);
9724                         }
9725                 }
9726                 scsi_ulto4b(lun->be_lun->atomicblock,
9727                     bl_ptr->max_atomic_transfer_length);
9728                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
9729                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9730         }
9731         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9732
9733         ctl_set_success(ctsio);
9734         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9735         ctsio->be_move_done = ctl_config_move_done;
9736         ctl_datamove((union ctl_io *)ctsio);
9737         return (CTL_RETVAL_COMPLETE);
9738 }
9739
9740 static int
9741 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9742 {
9743         struct scsi_vpd_block_device_characteristics *bdc_ptr;
9744         struct ctl_lun *lun;
9745         const char *value;
9746         u_int i;
9747
9748         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9749
9750         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9751         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9752         ctsio->kern_sg_entries = 0;
9753
9754         if (sizeof(*bdc_ptr) < alloc_len) {
9755                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9756                 ctsio->kern_data_len = sizeof(*bdc_ptr);
9757                 ctsio->kern_total_len = sizeof(*bdc_ptr);
9758         } else {
9759                 ctsio->residual = 0;
9760                 ctsio->kern_data_len = alloc_len;
9761                 ctsio->kern_total_len = alloc_len;
9762         }
9763         ctsio->kern_data_resid = 0;
9764         ctsio->kern_rel_offset = 0;
9765         ctsio->kern_sg_entries = 0;
9766
9767         /*
9768          * The control device is always connected.  The disk device, on the
9769          * other hand, may not be online all the time.  Need to change this
9770          * to figure out whether the disk device is actually online or not.
9771          */
9772         if (lun != NULL)
9773                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9774                                   lun->be_lun->lun_type;
9775         else
9776                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9777         bdc_ptr->page_code = SVPD_BDC;
9778         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9779         if (lun != NULL &&
9780             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9781                 i = strtol(value, NULL, 0);
9782         else
9783                 i = CTL_DEFAULT_ROTATION_RATE;
9784         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9785         if (lun != NULL &&
9786             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9787                 i = strtol(value, NULL, 0);
9788         else
9789                 i = 0;
9790         bdc_ptr->wab_wac_ff = (i & 0x0f);
9791         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9792
9793         ctl_set_success(ctsio);
9794         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9795         ctsio->be_move_done = ctl_config_move_done;
9796         ctl_datamove((union ctl_io *)ctsio);
9797         return (CTL_RETVAL_COMPLETE);
9798 }
9799
9800 static int
9801 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9802 {
9803         struct scsi_vpd_logical_block_prov *lbp_ptr;
9804         struct ctl_lun *lun;
9805
9806         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9807
9808         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9809         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9810         ctsio->kern_sg_entries = 0;
9811
9812         if (sizeof(*lbp_ptr) < alloc_len) {
9813                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9814                 ctsio->kern_data_len = sizeof(*lbp_ptr);
9815                 ctsio->kern_total_len = sizeof(*lbp_ptr);
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.  Need to change this
9828          * to figure out whether the disk device is actually online or not.
9829          */
9830         if (lun != NULL)
9831                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9832                                   lun->be_lun->lun_type;
9833         else
9834                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9835
9836         lbp_ptr->page_code = SVPD_LBP;
9837         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9838         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9839         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9840                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9841                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9842                 lbp_ptr->prov_type = SVPD_LBP_THIN;
9843         }
9844
9845         ctl_set_success(ctsio);
9846         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9847         ctsio->be_move_done = ctl_config_move_done;
9848         ctl_datamove((union ctl_io *)ctsio);
9849         return (CTL_RETVAL_COMPLETE);
9850 }
9851
9852 /*
9853  * INQUIRY with the EVPD bit set.
9854  */
9855 static int
9856 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9857 {
9858         struct ctl_lun *lun;
9859         struct scsi_inquiry *cdb;
9860         int alloc_len, retval;
9861
9862         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9863         cdb = (struct scsi_inquiry *)ctsio->cdb;
9864         alloc_len = scsi_2btoul(cdb->length);
9865
9866         switch (cdb->page_code) {
9867         case SVPD_SUPPORTED_PAGES:
9868                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9869                 break;
9870         case SVPD_UNIT_SERIAL_NUMBER:
9871                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9872                 break;
9873         case SVPD_DEVICE_ID:
9874                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9875                 break;
9876         case SVPD_EXTENDED_INQUIRY_DATA:
9877                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9878                 break;
9879         case SVPD_MODE_PAGE_POLICY:
9880                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9881                 break;
9882         case SVPD_SCSI_PORTS:
9883                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9884                 break;
9885         case SVPD_SCSI_TPC:
9886                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9887                 break;
9888         case SVPD_BLOCK_LIMITS:
9889                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9890                         goto err;
9891                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9892                 break;
9893         case SVPD_BDC:
9894                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9895                         goto err;
9896                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9897                 break;
9898         case SVPD_LBP:
9899                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9900                         goto err;
9901                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9902                 break;
9903         default:
9904 err:
9905                 ctl_set_invalid_field(ctsio,
9906                                       /*sks_valid*/ 1,
9907                                       /*command*/ 1,
9908                                       /*field*/ 2,
9909                                       /*bit_valid*/ 0,
9910                                       /*bit*/ 0);
9911                 ctl_done((union ctl_io *)ctsio);
9912                 retval = CTL_RETVAL_COMPLETE;
9913                 break;
9914         }
9915
9916         return (retval);
9917 }
9918
9919 /*
9920  * Standard INQUIRY data.
9921  */
9922 static int
9923 ctl_inquiry_std(struct ctl_scsiio *ctsio)
9924 {
9925         struct scsi_inquiry_data *inq_ptr;
9926         struct scsi_inquiry *cdb;
9927         struct ctl_softc *softc;
9928         struct ctl_lun *lun;
9929         char *val;
9930         uint32_t alloc_len, data_len;
9931         ctl_port_type port_type;
9932
9933         softc = control_softc;
9934
9935         /*
9936          * Figure out whether we're talking to a Fibre Channel port or not.
9937          * We treat the ioctl front end, and any SCSI adapters, as packetized
9938          * SCSI front ends.
9939          */
9940         port_type = softc->ctl_ports[
9941             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
9942         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
9943                 port_type = CTL_PORT_SCSI;
9944
9945         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9946         cdb = (struct scsi_inquiry *)ctsio->cdb;
9947         alloc_len = scsi_2btoul(cdb->length);
9948
9949         /*
9950          * We malloc the full inquiry data size here and fill it
9951          * in.  If the user only asks for less, we'll give him
9952          * that much.
9953          */
9954         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
9955         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9956         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9957         ctsio->kern_sg_entries = 0;
9958         ctsio->kern_data_resid = 0;
9959         ctsio->kern_rel_offset = 0;
9960
9961         if (data_len < alloc_len) {
9962                 ctsio->residual = alloc_len - data_len;
9963                 ctsio->kern_data_len = data_len;
9964                 ctsio->kern_total_len = data_len;
9965         } else {
9966                 ctsio->residual = 0;
9967                 ctsio->kern_data_len = alloc_len;
9968                 ctsio->kern_total_len = alloc_len;
9969         }
9970
9971         /*
9972          * If we have a LUN configured, report it as connected.  Otherwise,
9973          * report that it is offline or no device is supported, depending 
9974          * on the value of inquiry_pq_no_lun.
9975          *
9976          * According to the spec (SPC-4 r34), the peripheral qualifier
9977          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
9978          *
9979          * "A peripheral device having the specified peripheral device type 
9980          * is not connected to this logical unit. However, the device
9981          * server is capable of supporting the specified peripheral device
9982          * type on this logical unit."
9983          *
9984          * According to the same spec, the peripheral qualifier
9985          * SID_QUAL_BAD_LU (011b) is used in this scenario:
9986          *
9987          * "The device server is not capable of supporting a peripheral
9988          * device on this logical unit. For this peripheral qualifier the
9989          * peripheral device type shall be set to 1Fh. All other peripheral
9990          * device type values are reserved for this peripheral qualifier."
9991          *
9992          * Given the text, it would seem that we probably want to report that
9993          * the LUN is offline here.  There is no LUN connected, but we can
9994          * support a LUN at the given LUN number.
9995          *
9996          * In the real world, though, it sounds like things are a little
9997          * different:
9998          *
9999          * - Linux, when presented with a LUN with the offline peripheral
10000          *   qualifier, will create an sg driver instance for it.  So when
10001          *   you attach it to CTL, you wind up with a ton of sg driver
10002          *   instances.  (One for every LUN that Linux bothered to probe.)
10003          *   Linux does this despite the fact that it issues a REPORT LUNs
10004          *   to LUN 0 to get the inventory of supported LUNs.
10005          *
10006          * - There is other anecdotal evidence (from Emulex folks) about
10007          *   arrays that use the offline peripheral qualifier for LUNs that
10008          *   are on the "passive" path in an active/passive array.
10009          *
10010          * So the solution is provide a hopefully reasonable default
10011          * (return bad/no LUN) and allow the user to change the behavior
10012          * with a tunable/sysctl variable.
10013          */
10014         if (lun != NULL)
10015                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10016                                   lun->be_lun->lun_type;
10017         else if (softc->inquiry_pq_no_lun == 0)
10018                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10019         else
10020                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10021
10022         /* RMB in byte 2 is 0 */
10023         inq_ptr->version = SCSI_REV_SPC4;
10024
10025         /*
10026          * According to SAM-3, even if a device only supports a single
10027          * level of LUN addressing, it should still set the HISUP bit:
10028          *
10029          * 4.9.1 Logical unit numbers overview
10030          *
10031          * All logical unit number formats described in this standard are
10032          * hierarchical in structure even when only a single level in that
10033          * hierarchy is used. The HISUP bit shall be set to one in the
10034          * standard INQUIRY data (see SPC-2) when any logical unit number
10035          * format described in this standard is used.  Non-hierarchical
10036          * formats are outside the scope of this standard.
10037          *
10038          * Therefore we set the HiSup bit here.
10039          *
10040          * The reponse format is 2, per SPC-3.
10041          */
10042         inq_ptr->response_format = SID_HiSup | 2;
10043
10044         inq_ptr->additional_length = data_len -
10045             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10046         CTL_DEBUG_PRINT(("additional_length = %d\n",
10047                          inq_ptr->additional_length));
10048
10049         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10050         /* 16 bit addressing */
10051         if (port_type == CTL_PORT_SCSI)
10052                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10053         /* XXX set the SID_MultiP bit here if we're actually going to
10054            respond on multiple ports */
10055         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10056
10057         /* 16 bit data bus, synchronous transfers */
10058         if (port_type == CTL_PORT_SCSI)
10059                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10060         /*
10061          * XXX KDM do we want to support tagged queueing on the control
10062          * device at all?
10063          */
10064         if ((lun == NULL)
10065          || (lun->be_lun->lun_type != T_PROCESSOR))
10066                 inq_ptr->flags |= SID_CmdQue;
10067         /*
10068          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10069          * We have 8 bytes for the vendor name, and 16 bytes for the device
10070          * name and 4 bytes for the revision.
10071          */
10072         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10073             "vendor")) == NULL) {
10074                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10075         } else {
10076                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10077                 strncpy(inq_ptr->vendor, val,
10078                     min(sizeof(inq_ptr->vendor), strlen(val)));
10079         }
10080         if (lun == NULL) {
10081                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10082                     sizeof(inq_ptr->product));
10083         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10084                 switch (lun->be_lun->lun_type) {
10085                 case T_DIRECT:
10086                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10087                             sizeof(inq_ptr->product));
10088                         break;
10089                 case T_PROCESSOR:
10090                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10091                             sizeof(inq_ptr->product));
10092                         break;
10093                 default:
10094                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10095                             sizeof(inq_ptr->product));
10096                         break;
10097                 }
10098         } else {
10099                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10100                 strncpy(inq_ptr->product, val,
10101                     min(sizeof(inq_ptr->product), strlen(val)));
10102         }
10103
10104         /*
10105          * XXX make this a macro somewhere so it automatically gets
10106          * incremented when we make changes.
10107          */
10108         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10109             "revision")) == NULL) {
10110                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10111         } else {
10112                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10113                 strncpy(inq_ptr->revision, val,
10114                     min(sizeof(inq_ptr->revision), strlen(val)));
10115         }
10116
10117         /*
10118          * For parallel SCSI, we support double transition and single
10119          * transition clocking.  We also support QAS (Quick Arbitration
10120          * and Selection) and Information Unit transfers on both the
10121          * control and array devices.
10122          */
10123         if (port_type == CTL_PORT_SCSI)
10124                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10125                                     SID_SPI_IUS;
10126
10127         /* SAM-5 (no version claimed) */
10128         scsi_ulto2b(0x00A0, inq_ptr->version1);
10129         /* SPC-4 (no version claimed) */
10130         scsi_ulto2b(0x0460, inq_ptr->version2);
10131         if (port_type == CTL_PORT_FC) {
10132                 /* FCP-2 ANSI INCITS.350:2003 */
10133                 scsi_ulto2b(0x0917, inq_ptr->version3);
10134         } else if (port_type == CTL_PORT_SCSI) {
10135                 /* SPI-4 ANSI INCITS.362:200x */
10136                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10137         } else if (port_type == CTL_PORT_ISCSI) {
10138                 /* iSCSI (no version claimed) */
10139                 scsi_ulto2b(0x0960, inq_ptr->version3);
10140         } else if (port_type == CTL_PORT_SAS) {
10141                 /* SAS (no version claimed) */
10142                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10143         }
10144
10145         if (lun == NULL) {
10146                 /* SBC-4 (no version claimed) */
10147                 scsi_ulto2b(0x0600, inq_ptr->version4);
10148         } else {
10149                 switch (lun->be_lun->lun_type) {
10150                 case T_DIRECT:
10151                         /* SBC-4 (no version claimed) */
10152                         scsi_ulto2b(0x0600, inq_ptr->version4);
10153                         break;
10154                 case T_PROCESSOR:
10155                 default:
10156                         break;
10157                 }
10158         }
10159
10160         ctl_set_success(ctsio);
10161         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10162         ctsio->be_move_done = ctl_config_move_done;
10163         ctl_datamove((union ctl_io *)ctsio);
10164         return (CTL_RETVAL_COMPLETE);
10165 }
10166
10167 int
10168 ctl_inquiry(struct ctl_scsiio *ctsio)
10169 {
10170         struct scsi_inquiry *cdb;
10171         int retval;
10172
10173         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10174
10175         cdb = (struct scsi_inquiry *)ctsio->cdb;
10176         if (cdb->byte2 & SI_EVPD)
10177                 retval = ctl_inquiry_evpd(ctsio);
10178         else if (cdb->page_code == 0)
10179                 retval = ctl_inquiry_std(ctsio);
10180         else {
10181                 ctl_set_invalid_field(ctsio,
10182                                       /*sks_valid*/ 1,
10183                                       /*command*/ 1,
10184                                       /*field*/ 2,
10185                                       /*bit_valid*/ 0,
10186                                       /*bit*/ 0);
10187                 ctl_done((union ctl_io *)ctsio);
10188                 return (CTL_RETVAL_COMPLETE);
10189         }
10190
10191         return (retval);
10192 }
10193
10194 /*
10195  * For known CDB types, parse the LBA and length.
10196  */
10197 static int
10198 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10199 {
10200         if (io->io_hdr.io_type != CTL_IO_SCSI)
10201                 return (1);
10202
10203         switch (io->scsiio.cdb[0]) {
10204         case COMPARE_AND_WRITE: {
10205                 struct scsi_compare_and_write *cdb;
10206
10207                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10208
10209                 *lba = scsi_8btou64(cdb->addr);
10210                 *len = cdb->length;
10211                 break;
10212         }
10213         case READ_6:
10214         case WRITE_6: {
10215                 struct scsi_rw_6 *cdb;
10216
10217                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10218
10219                 *lba = scsi_3btoul(cdb->addr);
10220                 /* only 5 bits are valid in the most significant address byte */
10221                 *lba &= 0x1fffff;
10222                 *len = cdb->length;
10223                 break;
10224         }
10225         case READ_10:
10226         case WRITE_10: {
10227                 struct scsi_rw_10 *cdb;
10228
10229                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10230
10231                 *lba = scsi_4btoul(cdb->addr);
10232                 *len = scsi_2btoul(cdb->length);
10233                 break;
10234         }
10235         case WRITE_VERIFY_10: {
10236                 struct scsi_write_verify_10 *cdb;
10237
10238                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10239
10240                 *lba = scsi_4btoul(cdb->addr);
10241                 *len = scsi_2btoul(cdb->length);
10242                 break;
10243         }
10244         case READ_12:
10245         case WRITE_12: {
10246                 struct scsi_rw_12 *cdb;
10247
10248                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10249
10250                 *lba = scsi_4btoul(cdb->addr);
10251                 *len = scsi_4btoul(cdb->length);
10252                 break;
10253         }
10254         case WRITE_VERIFY_12: {
10255                 struct scsi_write_verify_12 *cdb;
10256
10257                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10258
10259                 *lba = scsi_4btoul(cdb->addr);
10260                 *len = scsi_4btoul(cdb->length);
10261                 break;
10262         }
10263         case READ_16:
10264         case WRITE_16:
10265         case WRITE_ATOMIC_16: {
10266                 struct scsi_rw_16 *cdb;
10267
10268                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10269
10270                 *lba = scsi_8btou64(cdb->addr);
10271                 *len = scsi_4btoul(cdb->length);
10272                 break;
10273         }
10274         case WRITE_VERIFY_16: {
10275                 struct scsi_write_verify_16 *cdb;
10276
10277                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10278
10279                 *lba = scsi_8btou64(cdb->addr);
10280                 *len = scsi_4btoul(cdb->length);
10281                 break;
10282         }
10283         case WRITE_SAME_10: {
10284                 struct scsi_write_same_10 *cdb;
10285
10286                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10287
10288                 *lba = scsi_4btoul(cdb->addr);
10289                 *len = scsi_2btoul(cdb->length);
10290                 break;
10291         }
10292         case WRITE_SAME_16: {
10293                 struct scsi_write_same_16 *cdb;
10294
10295                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10296
10297                 *lba = scsi_8btou64(cdb->addr);
10298                 *len = scsi_4btoul(cdb->length);
10299                 break;
10300         }
10301         case VERIFY_10: {
10302                 struct scsi_verify_10 *cdb;
10303
10304                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10305
10306                 *lba = scsi_4btoul(cdb->addr);
10307                 *len = scsi_2btoul(cdb->length);
10308                 break;
10309         }
10310         case VERIFY_12: {
10311                 struct scsi_verify_12 *cdb;
10312
10313                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10314
10315                 *lba = scsi_4btoul(cdb->addr);
10316                 *len = scsi_4btoul(cdb->length);
10317                 break;
10318         }
10319         case VERIFY_16: {
10320                 struct scsi_verify_16 *cdb;
10321
10322                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10323
10324                 *lba = scsi_8btou64(cdb->addr);
10325                 *len = scsi_4btoul(cdb->length);
10326                 break;
10327         }
10328         case UNMAP: {
10329                 *lba = 0;
10330                 *len = UINT64_MAX;
10331                 break;
10332         }
10333         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10334                 struct scsi_get_lba_status *cdb;
10335
10336                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10337                 *lba = scsi_8btou64(cdb->addr);
10338                 *len = UINT32_MAX;
10339                 break;
10340         }
10341         default:
10342                 return (1);
10343                 break; /* NOTREACHED */
10344         }
10345
10346         return (0);
10347 }
10348
10349 static ctl_action
10350 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10351     bool seq)
10352 {
10353         uint64_t endlba1, endlba2;
10354
10355         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10356         endlba2 = lba2 + len2 - 1;
10357
10358         if ((endlba1 < lba2) || (endlba2 < lba1))
10359                 return (CTL_ACTION_PASS);
10360         else
10361                 return (CTL_ACTION_BLOCK);
10362 }
10363
10364 static int
10365 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10366 {
10367         struct ctl_ptr_len_flags *ptrlen;
10368         struct scsi_unmap_desc *buf, *end, *range;
10369         uint64_t lba;
10370         uint32_t len;
10371
10372         /* If not UNMAP -- go other way. */
10373         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10374             io->scsiio.cdb[0] != UNMAP)
10375                 return (CTL_ACTION_ERROR);
10376
10377         /* If UNMAP without data -- block and wait for data. */
10378         ptrlen = (struct ctl_ptr_len_flags *)
10379             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10380         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10381             ptrlen->ptr == NULL)
10382                 return (CTL_ACTION_BLOCK);
10383
10384         /* UNMAP with data -- check for collision. */
10385         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10386         end = buf + ptrlen->len / sizeof(*buf);
10387         for (range = buf; range < end; range++) {
10388                 lba = scsi_8btou64(range->lba);
10389                 len = scsi_4btoul(range->length);
10390                 if ((lba < lba2 + len2) && (lba + len > lba2))
10391                         return (CTL_ACTION_BLOCK);
10392         }
10393         return (CTL_ACTION_PASS);
10394 }
10395
10396 static ctl_action
10397 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10398 {
10399         uint64_t lba1, lba2;
10400         uint64_t len1, len2;
10401         int retval;
10402
10403         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10404                 return (CTL_ACTION_ERROR);
10405
10406         retval = ctl_extent_check_unmap(io1, lba2, len2);
10407         if (retval != CTL_ACTION_ERROR)
10408                 return (retval);
10409
10410         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10411                 return (CTL_ACTION_ERROR);
10412
10413         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10414 }
10415
10416 static ctl_action
10417 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10418 {
10419         uint64_t lba1, lba2;
10420         uint64_t len1, len2;
10421
10422         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10423                 return (CTL_ACTION_ERROR);
10424         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10425                 return (CTL_ACTION_ERROR);
10426
10427         if (lba1 + len1 == lba2)
10428                 return (CTL_ACTION_BLOCK);
10429         return (CTL_ACTION_PASS);
10430 }
10431
10432 static ctl_action
10433 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10434     union ctl_io *ooa_io)
10435 {
10436         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10437         ctl_serialize_action *serialize_row;
10438
10439         /*
10440          * The initiator attempted multiple untagged commands at the same
10441          * time.  Can't do that.
10442          */
10443         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10444          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10445          && ((pending_io->io_hdr.nexus.targ_port ==
10446               ooa_io->io_hdr.nexus.targ_port)
10447           && (pending_io->io_hdr.nexus.initid.id ==
10448               ooa_io->io_hdr.nexus.initid.id))
10449          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10450               CTL_FLAG_STATUS_SENT)) == 0))
10451                 return (CTL_ACTION_OVERLAP);
10452
10453         /*
10454          * The initiator attempted to send multiple tagged commands with
10455          * the same ID.  (It's fine if different initiators have the same
10456          * tag ID.)
10457          *
10458          * Even if all of those conditions are true, we don't kill the I/O
10459          * if the command ahead of us has been aborted.  We won't end up
10460          * sending it to the FETD, and it's perfectly legal to resend a
10461          * command with the same tag number as long as the previous
10462          * instance of this tag number has been aborted somehow.
10463          */
10464         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10465          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10466          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10467          && ((pending_io->io_hdr.nexus.targ_port ==
10468               ooa_io->io_hdr.nexus.targ_port)
10469           && (pending_io->io_hdr.nexus.initid.id ==
10470               ooa_io->io_hdr.nexus.initid.id))
10471          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10472               CTL_FLAG_STATUS_SENT)) == 0))
10473                 return (CTL_ACTION_OVERLAP_TAG);
10474
10475         /*
10476          * If we get a head of queue tag, SAM-3 says that we should
10477          * immediately execute it.
10478          *
10479          * What happens if this command would normally block for some other
10480          * reason?  e.g. a request sense with a head of queue tag
10481          * immediately after a write.  Normally that would block, but this
10482          * will result in its getting executed immediately...
10483          *
10484          * We currently return "pass" instead of "skip", so we'll end up
10485          * going through the rest of the queue to check for overlapped tags.
10486          *
10487          * XXX KDM check for other types of blockage first??
10488          */
10489         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10490                 return (CTL_ACTION_PASS);
10491
10492         /*
10493          * Ordered tags have to block until all items ahead of them
10494          * have completed.  If we get called with an ordered tag, we always
10495          * block, if something else is ahead of us in the queue.
10496          */
10497         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10498                 return (CTL_ACTION_BLOCK);
10499
10500         /*
10501          * Simple tags get blocked until all head of queue and ordered tags
10502          * ahead of them have completed.  I'm lumping untagged commands in
10503          * with simple tags here.  XXX KDM is that the right thing to do?
10504          */
10505         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10506           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10507          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10508           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10509                 return (CTL_ACTION_BLOCK);
10510
10511         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10512         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10513
10514         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10515
10516         switch (serialize_row[pending_entry->seridx]) {
10517         case CTL_SER_BLOCK:
10518                 return (CTL_ACTION_BLOCK);
10519         case CTL_SER_EXTENT:
10520                 return (ctl_extent_check(ooa_io, pending_io,
10521                     (lun->serseq == CTL_LUN_SERSEQ_ON)));
10522         case CTL_SER_EXTENTOPT:
10523                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10524                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10525                         return (ctl_extent_check(ooa_io, pending_io,
10526                             (lun->serseq == CTL_LUN_SERSEQ_ON)));
10527                 return (CTL_ACTION_PASS);
10528         case CTL_SER_EXTENTSEQ:
10529                 if (lun->serseq != CTL_LUN_SERSEQ_OFF)
10530                         return (ctl_extent_check_seq(ooa_io, pending_io));
10531                 return (CTL_ACTION_PASS);
10532         case CTL_SER_PASS:
10533                 return (CTL_ACTION_PASS);
10534         case CTL_SER_BLOCKOPT:
10535                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10536                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10537                         return (CTL_ACTION_BLOCK);
10538                 return (CTL_ACTION_PASS);
10539         case CTL_SER_SKIP:
10540                 return (CTL_ACTION_SKIP);
10541         default:
10542                 panic("invalid serialization value %d",
10543                       serialize_row[pending_entry->seridx]);
10544         }
10545
10546         return (CTL_ACTION_ERROR);
10547 }
10548
10549 /*
10550  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10551  * Assumptions:
10552  * - pending_io is generally either incoming, or on the blocked queue
10553  * - starting I/O is the I/O we want to start the check with.
10554  */
10555 static ctl_action
10556 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10557               union ctl_io *starting_io)
10558 {
10559         union ctl_io *ooa_io;
10560         ctl_action action;
10561
10562         mtx_assert(&lun->lun_lock, MA_OWNED);
10563
10564         /*
10565          * Run back along the OOA queue, starting with the current
10566          * blocked I/O and going through every I/O before it on the
10567          * queue.  If starting_io is NULL, we'll just end up returning
10568          * CTL_ACTION_PASS.
10569          */
10570         for (ooa_io = starting_io; ooa_io != NULL;
10571              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10572              ooa_links)){
10573
10574                 /*
10575                  * This routine just checks to see whether
10576                  * cur_blocked is blocked by ooa_io, which is ahead
10577                  * of it in the queue.  It doesn't queue/dequeue
10578                  * cur_blocked.
10579                  */
10580                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10581                 switch (action) {
10582                 case CTL_ACTION_BLOCK:
10583                 case CTL_ACTION_OVERLAP:
10584                 case CTL_ACTION_OVERLAP_TAG:
10585                 case CTL_ACTION_SKIP:
10586                 case CTL_ACTION_ERROR:
10587                         return (action);
10588                         break; /* NOTREACHED */
10589                 case CTL_ACTION_PASS:
10590                         break;
10591                 default:
10592                         panic("invalid action %d", action);
10593                         break;  /* NOTREACHED */
10594                 }
10595         }
10596
10597         return (CTL_ACTION_PASS);
10598 }
10599
10600 /*
10601  * Assumptions:
10602  * - An I/O has just completed, and has been removed from the per-LUN OOA
10603  *   queue, so some items on the blocked queue may now be unblocked.
10604  */
10605 static int
10606 ctl_check_blocked(struct ctl_lun *lun)
10607 {
10608         union ctl_io *cur_blocked, *next_blocked;
10609
10610         mtx_assert(&lun->lun_lock, MA_OWNED);
10611
10612         /*
10613          * Run forward from the head of the blocked queue, checking each
10614          * entry against the I/Os prior to it on the OOA queue to see if
10615          * there is still any blockage.
10616          *
10617          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10618          * with our removing a variable on it while it is traversing the
10619          * list.
10620          */
10621         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10622              cur_blocked != NULL; cur_blocked = next_blocked) {
10623                 union ctl_io *prev_ooa;
10624                 ctl_action action;
10625
10626                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10627                                                           blocked_links);
10628
10629                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10630                                                       ctl_ooaq, ooa_links);
10631
10632                 /*
10633                  * If cur_blocked happens to be the first item in the OOA
10634                  * queue now, prev_ooa will be NULL, and the action
10635                  * returned will just be CTL_ACTION_PASS.
10636                  */
10637                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10638
10639                 switch (action) {
10640                 case CTL_ACTION_BLOCK:
10641                         /* Nothing to do here, still blocked */
10642                         break;
10643                 case CTL_ACTION_OVERLAP:
10644                 case CTL_ACTION_OVERLAP_TAG:
10645                         /*
10646                          * This shouldn't happen!  In theory we've already
10647                          * checked this command for overlap...
10648                          */
10649                         break;
10650                 case CTL_ACTION_PASS:
10651                 case CTL_ACTION_SKIP: {
10652                         const struct ctl_cmd_entry *entry;
10653                         int isc_retval;
10654
10655                         /*
10656                          * The skip case shouldn't happen, this transaction
10657                          * should have never made it onto the blocked queue.
10658                          */
10659                         /*
10660                          * This I/O is no longer blocked, we can remove it
10661                          * from the blocked queue.  Since this is a TAILQ
10662                          * (doubly linked list), we can do O(1) removals
10663                          * from any place on the list.
10664                          */
10665                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10666                                      blocked_links);
10667                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10668
10669                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10670                                 /*
10671                                  * Need to send IO back to original side to
10672                                  * run
10673                                  */
10674                                 union ctl_ha_msg msg_info;
10675
10676                                 msg_info.hdr.original_sc =
10677                                         cur_blocked->io_hdr.original_sc;
10678                                 msg_info.hdr.serializing_sc = cur_blocked;
10679                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10680                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10681                                      &msg_info, sizeof(msg_info), 0)) >
10682                                      CTL_HA_STATUS_SUCCESS) {
10683                                         printf("CTL:Check Blocked error from "
10684                                                "ctl_ha_msg_send %d\n",
10685                                                isc_retval);
10686                                 }
10687                                 break;
10688                         }
10689                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10690
10691                         /*
10692                          * Check this I/O for LUN state changes that may
10693                          * have happened while this command was blocked.
10694                          * The LUN state may have been changed by a command
10695                          * ahead of us in the queue, so we need to re-check
10696                          * for any states that can be caused by SCSI
10697                          * commands.
10698                          */
10699                         if (ctl_scsiio_lun_check(lun, entry,
10700                                                  &cur_blocked->scsiio) == 0) {
10701                                 cur_blocked->io_hdr.flags |=
10702                                                       CTL_FLAG_IS_WAS_ON_RTR;
10703                                 ctl_enqueue_rtr(cur_blocked);
10704                         } else
10705                                 ctl_done(cur_blocked);
10706                         break;
10707                 }
10708                 default:
10709                         /*
10710                          * This probably shouldn't happen -- we shouldn't
10711                          * get CTL_ACTION_ERROR, or anything else.
10712                          */
10713                         break;
10714                 }
10715         }
10716
10717         return (CTL_RETVAL_COMPLETE);
10718 }
10719
10720 /*
10721  * This routine (with one exception) checks LUN flags that can be set by
10722  * commands ahead of us in the OOA queue.  These flags have to be checked
10723  * when a command initially comes in, and when we pull a command off the
10724  * blocked queue and are preparing to execute it.  The reason we have to
10725  * check these flags for commands on the blocked queue is that the LUN
10726  * state may have been changed by a command ahead of us while we're on the
10727  * blocked queue.
10728  *
10729  * Ordering is somewhat important with these checks, so please pay
10730  * careful attention to the placement of any new checks.
10731  */
10732 static int
10733 ctl_scsiio_lun_check(struct ctl_lun *lun,
10734     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10735 {
10736         struct ctl_softc *softc = lun->ctl_softc;
10737         int retval;
10738         uint32_t residx;
10739
10740         retval = 0;
10741
10742         mtx_assert(&lun->lun_lock, MA_OWNED);
10743
10744         /*
10745          * If this shelf is a secondary shelf controller, we have to reject
10746          * any media access commands.
10747          */
10748         if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
10749             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
10750                 ctl_set_lun_standby(ctsio);
10751                 retval = 1;
10752                 goto bailout;
10753         }
10754
10755         if (entry->pattern & CTL_LUN_PAT_WRITE) {
10756                 if (lun->flags & CTL_LUN_READONLY) {
10757                         ctl_set_sense(ctsio, /*current_error*/ 1,
10758                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
10759                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
10760                         retval = 1;
10761                         goto bailout;
10762                 }
10763                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
10764                     .eca_and_aen & SCP_SWP) != 0) {
10765                         ctl_set_sense(ctsio, /*current_error*/ 1,
10766                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
10767                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
10768                         retval = 1;
10769                         goto bailout;
10770                 }
10771         }
10772
10773         /*
10774          * Check for a reservation conflict.  If this command isn't allowed
10775          * even on reserved LUNs, and if this initiator isn't the one who
10776          * reserved us, reject the command with a reservation conflict.
10777          */
10778         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10779         if ((lun->flags & CTL_LUN_RESERVED)
10780          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10781                 if (lun->res_idx != residx) {
10782                         ctl_set_reservation_conflict(ctsio);
10783                         retval = 1;
10784                         goto bailout;
10785                 }
10786         }
10787
10788         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
10789             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
10790                 /* No reservation or command is allowed. */;
10791         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
10792             (lun->res_type == SPR_TYPE_WR_EX ||
10793              lun->res_type == SPR_TYPE_WR_EX_RO ||
10794              lun->res_type == SPR_TYPE_WR_EX_AR)) {
10795                 /* The command is allowed for Write Exclusive resv. */;
10796         } else {
10797                 /*
10798                  * if we aren't registered or it's a res holder type
10799                  * reservation and this isn't the res holder then set a
10800                  * conflict.
10801                  */
10802                 if (ctl_get_prkey(lun, residx) == 0
10803                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10804                         ctl_set_reservation_conflict(ctsio);
10805                         retval = 1;
10806                         goto bailout;
10807                 }
10808
10809         }
10810
10811         if ((lun->flags & CTL_LUN_OFFLINE)
10812          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10813                 ctl_set_lun_not_ready(ctsio);
10814                 retval = 1;
10815                 goto bailout;
10816         }
10817
10818         /*
10819          * If the LUN is stopped, see if this particular command is allowed
10820          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10821          */
10822         if ((lun->flags & CTL_LUN_STOPPED)
10823          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10824                 /* "Logical unit not ready, initializing cmd. required" */
10825                 ctl_set_lun_stopped(ctsio);
10826                 retval = 1;
10827                 goto bailout;
10828         }
10829
10830         if ((lun->flags & CTL_LUN_INOPERABLE)
10831          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10832                 /* "Medium format corrupted" */
10833                 ctl_set_medium_format_corrupted(ctsio);
10834                 retval = 1;
10835                 goto bailout;
10836         }
10837
10838 bailout:
10839         return (retval);
10840
10841 }
10842
10843 static void
10844 ctl_failover_io(union ctl_io *io, int have_lock)
10845 {
10846         ctl_set_busy(&io->scsiio);
10847         ctl_done(io);
10848 }
10849
10850 #ifdef notyet
10851 static void
10852 ctl_failover(void)
10853 {
10854         struct ctl_lun *lun;
10855         struct ctl_softc *softc;
10856         union ctl_io *next_io, *pending_io;
10857         union ctl_io *io;
10858         int lun_idx;
10859
10860         softc = control_softc;
10861
10862         mtx_lock(&softc->ctl_lock);
10863         /*
10864          * Remove any cmds from the other SC from the rtr queue.  These
10865          * will obviously only be for LUNs for which we're the primary.
10866          * We can't send status or get/send data for these commands.
10867          * Since they haven't been executed yet, we can just remove them.
10868          * We'll either abort them or delete them below, depending on
10869          * which HA mode we're in.
10870          */
10871 #ifdef notyet
10872         mtx_lock(&softc->queue_lock);
10873         for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
10874              io != NULL; io = next_io) {
10875                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10876                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10877                         STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
10878                                       ctl_io_hdr, links);
10879         }
10880         mtx_unlock(&softc->queue_lock);
10881 #endif
10882
10883         for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
10884                 lun = softc->ctl_luns[lun_idx];
10885                 if (lun==NULL)
10886                         continue;
10887
10888                 /*
10889                  * Processor LUNs are primary on both sides.
10890                  * XXX will this always be true?
10891                  */
10892                 if (lun->be_lun->lun_type == T_PROCESSOR)
10893                         continue;
10894
10895                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
10896                  && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10897                         printf("FAILOVER: primary lun %d\n", lun_idx);
10898                         /*
10899                          * Remove all commands from the other SC. First from the
10900                          * blocked queue then from the ooa queue. Once we have
10901                          * removed them. Call ctl_check_blocked to see if there
10902                          * is anything that can run.
10903                          */
10904                         for (io = (union ctl_io *)TAILQ_FIRST(
10905                              &lun->blocked_queue); io != NULL; io = next_io) {
10906
10907                                 next_io = (union ctl_io *)TAILQ_NEXT(
10908                                     &io->io_hdr, blocked_links);
10909
10910                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10911                                         TAILQ_REMOVE(&lun->blocked_queue,
10912                                                      &io->io_hdr,blocked_links);
10913                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10914                                         TAILQ_REMOVE(&lun->ooa_queue,
10915                                                      &io->io_hdr, ooa_links);
10916
10917                                         ctl_free_io(io);
10918                                 }
10919                         }
10920
10921                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10922                              io != NULL; io = next_io) {
10923
10924                                 next_io = (union ctl_io *)TAILQ_NEXT(
10925                                     &io->io_hdr, ooa_links);
10926
10927                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10928
10929                                         TAILQ_REMOVE(&lun->ooa_queue,
10930                                                 &io->io_hdr,
10931                                                 ooa_links);
10932
10933                                         ctl_free_io(io);
10934                                 }
10935                         }
10936                         ctl_check_blocked(lun);
10937                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
10938                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
10939
10940                         printf("FAILOVER: primary lun %d\n", lun_idx);
10941                         /*
10942                          * Abort all commands from the other SC.  We can't
10943                          * send status back for them now.  These should get
10944                          * cleaned up when they are completed or come out
10945                          * for a datamove operation.
10946                          */
10947                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10948                              io != NULL; io = next_io) {
10949                                 next_io = (union ctl_io *)TAILQ_NEXT(
10950                                         &io->io_hdr, ooa_links);
10951
10952                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10953                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
10954                         }
10955                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10956                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
10957
10958                         printf("FAILOVER: secondary lun %d\n", lun_idx);
10959
10960                         lun->flags |= CTL_LUN_PRIMARY_SC;
10961
10962                         /*
10963                          * We send all I/O that was sent to this controller
10964                          * and redirected to the other side back with
10965                          * busy status, and have the initiator retry it.
10966                          * Figuring out how much data has been transferred,
10967                          * etc. and picking up where we left off would be 
10968                          * very tricky.
10969                          *
10970                          * XXX KDM need to remove I/O from the blocked
10971                          * queue as well!
10972                          */
10973                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
10974                              &lun->ooa_queue); pending_io != NULL;
10975                              pending_io = next_io) {
10976
10977                                 next_io =  (union ctl_io *)TAILQ_NEXT(
10978                                         &pending_io->io_hdr, ooa_links);
10979
10980                                 pending_io->io_hdr.flags &=
10981                                         ~CTL_FLAG_SENT_2OTHER_SC;
10982
10983                                 if (pending_io->io_hdr.flags &
10984                                     CTL_FLAG_IO_ACTIVE) {
10985                                         pending_io->io_hdr.flags |=
10986                                                 CTL_FLAG_FAILOVER;
10987                                 } else {
10988                                         ctl_set_busy(&pending_io->scsiio);
10989                                         ctl_done(pending_io);
10990                                 }
10991                         }
10992
10993                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
10994                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10995                         && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10996                         printf("FAILOVER: secondary lun %d\n", lun_idx);
10997                         /*
10998                          * if the first io on the OOA is not on the RtR queue
10999                          * add it.
11000                          */
11001                         lun->flags |= CTL_LUN_PRIMARY_SC;
11002
11003                         pending_io = (union ctl_io *)TAILQ_FIRST(
11004                             &lun->ooa_queue);
11005                         if (pending_io==NULL) {
11006                                 printf("Nothing on OOA queue\n");
11007                                 continue;
11008                         }
11009
11010                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11011                         if ((pending_io->io_hdr.flags &
11012                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11013                                 pending_io->io_hdr.flags |=
11014                                     CTL_FLAG_IS_WAS_ON_RTR;
11015                                 ctl_enqueue_rtr(pending_io);
11016                         }
11017 #if 0
11018                         else
11019                         {
11020                                 printf("Tag 0x%04x is running\n",
11021                                       pending_io->scsiio.tag_num);
11022                         }
11023 #endif
11024
11025                         next_io = (union ctl_io *)TAILQ_NEXT(
11026                             &pending_io->io_hdr, ooa_links);
11027                         for (pending_io=next_io; pending_io != NULL;
11028                              pending_io = next_io) {
11029                                 pending_io->io_hdr.flags &=
11030                                     ~CTL_FLAG_SENT_2OTHER_SC;
11031                                 next_io = (union ctl_io *)TAILQ_NEXT(
11032                                         &pending_io->io_hdr, ooa_links);
11033                                 if (pending_io->io_hdr.flags &
11034                                     CTL_FLAG_IS_WAS_ON_RTR) {
11035 #if 0
11036                                         printf("Tag 0x%04x is running\n",
11037                                                 pending_io->scsiio.tag_num);
11038 #endif
11039                                         continue;
11040                                 }
11041
11042                                 switch (ctl_check_ooa(lun, pending_io,
11043                                     (union ctl_io *)TAILQ_PREV(
11044                                     &pending_io->io_hdr, ctl_ooaq,
11045                                     ooa_links))) {
11046
11047                                 case CTL_ACTION_BLOCK:
11048                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11049                                                           &pending_io->io_hdr,
11050                                                           blocked_links);
11051                                         pending_io->io_hdr.flags |=
11052                                             CTL_FLAG_BLOCKED;
11053                                         break;
11054                                 case CTL_ACTION_PASS:
11055                                 case CTL_ACTION_SKIP:
11056                                         pending_io->io_hdr.flags |=
11057                                             CTL_FLAG_IS_WAS_ON_RTR;
11058                                         ctl_enqueue_rtr(pending_io);
11059                                         break;
11060                                 case CTL_ACTION_OVERLAP:
11061                                         ctl_set_overlapped_cmd(
11062                                             (struct ctl_scsiio *)pending_io);
11063                                         ctl_done(pending_io);
11064                                         break;
11065                                 case CTL_ACTION_OVERLAP_TAG:
11066                                         ctl_set_overlapped_tag(
11067                                             (struct ctl_scsiio *)pending_io,
11068                                             pending_io->scsiio.tag_num & 0xff);
11069                                         ctl_done(pending_io);
11070                                         break;
11071                                 case CTL_ACTION_ERROR:
11072                                 default:
11073                                         ctl_set_internal_failure(
11074                                                 (struct ctl_scsiio *)pending_io,
11075                                                 0,  // sks_valid
11076                                                 0); //retry count
11077                                         ctl_done(pending_io);
11078                                         break;
11079                                 }
11080                         }
11081
11082                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11083                 } else {
11084                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11085                               "ha_mode = #%x", lun->flags, softc->ha_mode);
11086                 }
11087         }
11088         ctl_pause_rtr = 0;
11089         mtx_unlock(&softc->ctl_lock);
11090 }
11091 #endif
11092
11093 static void
11094 ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
11095              ctl_ua_type ua_type)
11096 {
11097         struct ctl_lun *lun;
11098         ctl_ua_type *pu;
11099
11100         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
11101
11102         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
11103                 mtx_lock(&lun->lun_lock);
11104                 pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
11105                 if (pu != NULL)
11106                         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua_type;
11107                 mtx_unlock(&lun->lun_lock);
11108         }
11109 }
11110
11111 static int
11112 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11113 {
11114         struct ctl_lun *lun;
11115         const struct ctl_cmd_entry *entry;
11116         uint32_t initidx, targ_lun;
11117         int retval;
11118
11119         retval = 0;
11120
11121         lun = NULL;
11122
11123         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11124         if ((targ_lun < CTL_MAX_LUNS)
11125          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11126                 /*
11127                  * If the LUN is invalid, pretend that it doesn't exist.
11128                  * It will go away as soon as all pending I/O has been
11129                  * completed.
11130                  */
11131                 mtx_lock(&lun->lun_lock);
11132                 if (lun->flags & CTL_LUN_DISABLED) {
11133                         mtx_unlock(&lun->lun_lock);
11134                         lun = NULL;
11135                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11136                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11137                 } else {
11138                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11139                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11140                                 lun->be_lun;
11141                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11142                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11143                         }
11144
11145                         /*
11146                          * Every I/O goes into the OOA queue for a
11147                          * particular LUN, and stays there until completion.
11148                          */
11149 #ifdef CTL_TIME_IO
11150                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11151                                 lun->idle_time += getsbinuptime() -
11152                                     lun->last_busy;
11153                         }
11154 #endif
11155                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11156                             ooa_links);
11157                 }
11158         } else {
11159                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11160                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11161         }
11162
11163         /* Get command entry and return error if it is unsuppotyed. */
11164         entry = ctl_validate_command(ctsio);
11165         if (entry == NULL) {
11166                 if (lun)
11167                         mtx_unlock(&lun->lun_lock);
11168                 return (retval);
11169         }
11170
11171         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11172         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11173
11174         /*
11175          * Check to see whether we can send this command to LUNs that don't
11176          * exist.  This should pretty much only be the case for inquiry
11177          * and request sense.  Further checks, below, really require having
11178          * a LUN, so we can't really check the command anymore.  Just put
11179          * it on the rtr queue.
11180          */
11181         if (lun == NULL) {
11182                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11183                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11184                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11185                         return (retval);
11186                 }
11187
11188                 ctl_set_unsupported_lun(ctsio);
11189                 ctl_done((union ctl_io *)ctsio);
11190                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11191                 return (retval);
11192         } else {
11193                 /*
11194                  * Make sure we support this particular command on this LUN.
11195                  * e.g., we don't support writes to the control LUN.
11196                  */
11197                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11198                         mtx_unlock(&lun->lun_lock);
11199                         ctl_set_invalid_opcode(ctsio);
11200                         ctl_done((union ctl_io *)ctsio);
11201                         return (retval);
11202                 }
11203         }
11204
11205         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11206
11207 #ifdef CTL_WITH_CA
11208         /*
11209          * If we've got a request sense, it'll clear the contingent
11210          * allegiance condition.  Otherwise, if we have a CA condition for
11211          * this initiator, clear it, because it sent down a command other
11212          * than request sense.
11213          */
11214         if ((ctsio->cdb[0] != REQUEST_SENSE)
11215          && (ctl_is_set(lun->have_ca, initidx)))
11216                 ctl_clear_mask(lun->have_ca, initidx);
11217 #endif
11218
11219         /*
11220          * If the command has this flag set, it handles its own unit
11221          * attention reporting, we shouldn't do anything.  Otherwise we
11222          * check for any pending unit attentions, and send them back to the
11223          * initiator.  We only do this when a command initially comes in,
11224          * not when we pull it off the blocked queue.
11225          *
11226          * According to SAM-3, section 5.3.2, the order that things get
11227          * presented back to the host is basically unit attentions caused
11228          * by some sort of reset event, busy status, reservation conflicts
11229          * or task set full, and finally any other status.
11230          *
11231          * One issue here is that some of the unit attentions we report
11232          * don't fall into the "reset" category (e.g. "reported luns data
11233          * has changed").  So reporting it here, before the reservation
11234          * check, may be technically wrong.  I guess the only thing to do
11235          * would be to check for and report the reset events here, and then
11236          * check for the other unit attention types after we check for a
11237          * reservation conflict.
11238          *
11239          * XXX KDM need to fix this
11240          */
11241         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11242                 ctl_ua_type ua_type;
11243                 scsi_sense_data_type sense_format;
11244
11245                 if (lun->flags & CTL_LUN_SENSE_DESC)
11246                         sense_format = SSD_TYPE_DESC;
11247                 else
11248                         sense_format = SSD_TYPE_FIXED;
11249
11250                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11251                     sense_format);
11252                 if (ua_type != CTL_UA_NONE) {
11253                         mtx_unlock(&lun->lun_lock);
11254                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11255                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11256                         ctsio->sense_len = SSD_FULL_SIZE;
11257                         ctl_done((union ctl_io *)ctsio);
11258                         return (retval);
11259                 }
11260         }
11261
11262
11263         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11264                 mtx_unlock(&lun->lun_lock);
11265                 ctl_done((union ctl_io *)ctsio);
11266                 return (retval);
11267         }
11268
11269         /*
11270          * XXX CHD this is where we want to send IO to other side if
11271          * this LUN is secondary on this SC. We will need to make a copy
11272          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11273          * the copy we send as FROM_OTHER.
11274          * We also need to stuff the address of the original IO so we can
11275          * find it easily. Something similar will need be done on the other
11276          * side so when we are done we can find the copy.
11277          */
11278         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11279                 union ctl_ha_msg msg_info;
11280                 int isc_retval;
11281
11282                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11283
11284                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11285                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11286 #if 0
11287                 printf("1. ctsio %p\n", ctsio);
11288 #endif
11289                 msg_info.hdr.serializing_sc = NULL;
11290                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11291                 msg_info.scsi.tag_num = ctsio->tag_num;
11292                 msg_info.scsi.tag_type = ctsio->tag_type;
11293                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11294
11295                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11296
11297                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11298                     (void *)&msg_info, sizeof(msg_info), 0)) >
11299                     CTL_HA_STATUS_SUCCESS) {
11300                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11301                                isc_retval);
11302                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11303                 } else {
11304 #if 0
11305                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11306 #endif
11307                 }
11308
11309                 /*
11310                  * XXX KDM this I/O is off the incoming queue, but hasn't
11311                  * been inserted on any other queue.  We may need to come
11312                  * up with a holding queue while we wait for serialization
11313                  * so that we have an idea of what we're waiting for from
11314                  * the other side.
11315                  */
11316                 mtx_unlock(&lun->lun_lock);
11317                 return (retval);
11318         }
11319
11320         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11321                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11322                               ctl_ooaq, ooa_links))) {
11323         case CTL_ACTION_BLOCK:
11324                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11325                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11326                                   blocked_links);
11327                 mtx_unlock(&lun->lun_lock);
11328                 return (retval);
11329         case CTL_ACTION_PASS:
11330         case CTL_ACTION_SKIP:
11331                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11332                 mtx_unlock(&lun->lun_lock);
11333                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11334                 break;
11335         case CTL_ACTION_OVERLAP:
11336                 mtx_unlock(&lun->lun_lock);
11337                 ctl_set_overlapped_cmd(ctsio);
11338                 ctl_done((union ctl_io *)ctsio);
11339                 break;
11340         case CTL_ACTION_OVERLAP_TAG:
11341                 mtx_unlock(&lun->lun_lock);
11342                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11343                 ctl_done((union ctl_io *)ctsio);
11344                 break;
11345         case CTL_ACTION_ERROR:
11346         default:
11347                 mtx_unlock(&lun->lun_lock);
11348                 ctl_set_internal_failure(ctsio,
11349                                          /*sks_valid*/ 0,
11350                                          /*retry_count*/ 0);
11351                 ctl_done((union ctl_io *)ctsio);
11352                 break;
11353         }
11354         return (retval);
11355 }
11356
11357 const struct ctl_cmd_entry *
11358 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11359 {
11360         const struct ctl_cmd_entry *entry;
11361         int service_action;
11362
11363         entry = &ctl_cmd_table[ctsio->cdb[0]];
11364         if (sa)
11365                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11366         if (entry->flags & CTL_CMD_FLAG_SA5) {
11367                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11368                 entry = &((const struct ctl_cmd_entry *)
11369                     entry->execute)[service_action];
11370         }
11371         return (entry);
11372 }
11373
11374 const struct ctl_cmd_entry *
11375 ctl_validate_command(struct ctl_scsiio *ctsio)
11376 {
11377         const struct ctl_cmd_entry *entry;
11378         int i, sa;
11379         uint8_t diff;
11380
11381         entry = ctl_get_cmd_entry(ctsio, &sa);
11382         if (entry->execute == NULL) {
11383                 if (sa)
11384                         ctl_set_invalid_field(ctsio,
11385                                               /*sks_valid*/ 1,
11386                                               /*command*/ 1,
11387                                               /*field*/ 1,
11388                                               /*bit_valid*/ 1,
11389                                               /*bit*/ 4);
11390                 else
11391                         ctl_set_invalid_opcode(ctsio);
11392                 ctl_done((union ctl_io *)ctsio);
11393                 return (NULL);
11394         }
11395         KASSERT(entry->length > 0,
11396             ("Not defined length for command 0x%02x/0x%02x",
11397              ctsio->cdb[0], ctsio->cdb[1]));
11398         for (i = 1; i < entry->length; i++) {
11399                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11400                 if (diff == 0)
11401                         continue;
11402                 ctl_set_invalid_field(ctsio,
11403                                       /*sks_valid*/ 1,
11404                                       /*command*/ 1,
11405                                       /*field*/ i,
11406                                       /*bit_valid*/ 1,
11407                                       /*bit*/ fls(diff) - 1);
11408                 ctl_done((union ctl_io *)ctsio);
11409                 return (NULL);
11410         }
11411         return (entry);
11412 }
11413
11414 static int
11415 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11416 {
11417
11418         switch (lun_type) {
11419         case T_PROCESSOR:
11420                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11421                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11422                         return (0);
11423                 break;
11424         case T_DIRECT:
11425                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11426                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11427                         return (0);
11428                 break;
11429         default:
11430                 return (0);
11431         }
11432         return (1);
11433 }
11434
11435 static int
11436 ctl_scsiio(struct ctl_scsiio *ctsio)
11437 {
11438         int retval;
11439         const struct ctl_cmd_entry *entry;
11440
11441         retval = CTL_RETVAL_COMPLETE;
11442
11443         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11444
11445         entry = ctl_get_cmd_entry(ctsio, NULL);
11446
11447         /*
11448          * If this I/O has been aborted, just send it straight to
11449          * ctl_done() without executing it.
11450          */
11451         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11452                 ctl_done((union ctl_io *)ctsio);
11453                 goto bailout;
11454         }
11455
11456         /*
11457          * All the checks should have been handled by ctl_scsiio_precheck().
11458          * We should be clear now to just execute the I/O.
11459          */
11460         retval = entry->execute(ctsio);
11461
11462 bailout:
11463         return (retval);
11464 }
11465
11466 /*
11467  * Since we only implement one target right now, a bus reset simply resets
11468  * our single target.
11469  */
11470 static int
11471 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11472 {
11473         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11474 }
11475
11476 static int
11477 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11478                  ctl_ua_type ua_type)
11479 {
11480         struct ctl_lun *lun;
11481         int retval;
11482
11483         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11484                 union ctl_ha_msg msg_info;
11485
11486                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11487                 msg_info.hdr.nexus = io->io_hdr.nexus;
11488                 if (ua_type==CTL_UA_TARG_RESET)
11489                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11490                 else
11491                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11492                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11493                 msg_info.hdr.original_sc = NULL;
11494                 msg_info.hdr.serializing_sc = NULL;
11495                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11496                     (void *)&msg_info, sizeof(msg_info), 0)) {
11497                 }
11498         }
11499         retval = 0;
11500
11501         mtx_lock(&softc->ctl_lock);
11502         STAILQ_FOREACH(lun, &softc->lun_list, links)
11503                 retval += ctl_lun_reset(lun, io, ua_type);
11504         mtx_unlock(&softc->ctl_lock);
11505
11506         return (retval);
11507 }
11508
11509 /*
11510  * The LUN should always be set.  The I/O is optional, and is used to
11511  * distinguish between I/Os sent by this initiator, and by other
11512  * initiators.  We set unit attention for initiators other than this one.
11513  * SAM-3 is vague on this point.  It does say that a unit attention should
11514  * be established for other initiators when a LUN is reset (see section
11515  * 5.7.3), but it doesn't specifically say that the unit attention should
11516  * be established for this particular initiator when a LUN is reset.  Here
11517  * is the relevant text, from SAM-3 rev 8:
11518  *
11519  * 5.7.2 When a SCSI initiator port aborts its own tasks
11520  *
11521  * When a SCSI initiator port causes its own task(s) to be aborted, no
11522  * notification that the task(s) have been aborted shall be returned to
11523  * the SCSI initiator port other than the completion response for the
11524  * command or task management function action that caused the task(s) to
11525  * be aborted and notification(s) associated with related effects of the
11526  * action (e.g., a reset unit attention condition).
11527  *
11528  * XXX KDM for now, we're setting unit attention for all initiators.
11529  */
11530 static int
11531 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11532 {
11533         union ctl_io *xio;
11534 #if 0
11535         uint32_t initidx;
11536 #endif
11537 #ifdef CTL_WITH_CA
11538         int i;
11539 #endif
11540
11541         mtx_lock(&lun->lun_lock);
11542         /*
11543          * Run through the OOA queue and abort each I/O.
11544          */
11545         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11546              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11547                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11548         }
11549
11550         /*
11551          * This version sets unit attention for every
11552          */
11553 #if 0
11554         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11555         ctl_est_ua_all(lun, initidx, ua_type);
11556 #else
11557         ctl_est_ua_all(lun, -1, ua_type);
11558 #endif
11559
11560         /*
11561          * A reset (any kind, really) clears reservations established with
11562          * RESERVE/RELEASE.  It does not clear reservations established
11563          * with PERSISTENT RESERVE OUT, but we don't support that at the
11564          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11565          * reservations made with the RESERVE/RELEASE commands, because
11566          * those commands are obsolete in SPC-3.
11567          */
11568         lun->flags &= ~CTL_LUN_RESERVED;
11569
11570 #ifdef CTL_WITH_CA
11571         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11572                 ctl_clear_mask(lun->have_ca, i);
11573 #endif
11574         mtx_unlock(&lun->lun_lock);
11575
11576         return (0);
11577 }
11578
11579 static void
11580 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11581     int other_sc)
11582 {
11583         union ctl_io *xio;
11584
11585         mtx_assert(&lun->lun_lock, MA_OWNED);
11586
11587         /*
11588          * Run through the OOA queue and attempt to find the given I/O.
11589          * The target port, initiator ID, tag type and tag number have to
11590          * match the values that we got from the initiator.  If we have an
11591          * untagged command to abort, simply abort the first untagged command
11592          * we come to.  We only allow one untagged command at a time of course.
11593          */
11594         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11595              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11596
11597                 if ((targ_port == UINT32_MAX ||
11598                      targ_port == xio->io_hdr.nexus.targ_port) &&
11599                     (init_id == UINT32_MAX ||
11600                      init_id == xio->io_hdr.nexus.initid.id)) {
11601                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11602                             init_id != xio->io_hdr.nexus.initid.id)
11603                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11604                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11605                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11606                                 union ctl_ha_msg msg_info;
11607
11608                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11609                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11610                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11611                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11612                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11613                                 msg_info.hdr.original_sc = NULL;
11614                                 msg_info.hdr.serializing_sc = NULL;
11615                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11616                                     (void *)&msg_info, sizeof(msg_info), 0);
11617                         }
11618                 }
11619         }
11620 }
11621
11622 static int
11623 ctl_abort_task_set(union ctl_io *io)
11624 {
11625         struct ctl_softc *softc = control_softc;
11626         struct ctl_lun *lun;
11627         uint32_t targ_lun;
11628
11629         /*
11630          * Look up the LUN.
11631          */
11632         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11633         mtx_lock(&softc->ctl_lock);
11634         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11635                 lun = softc->ctl_luns[targ_lun];
11636         else {
11637                 mtx_unlock(&softc->ctl_lock);
11638                 return (1);
11639         }
11640
11641         mtx_lock(&lun->lun_lock);
11642         mtx_unlock(&softc->ctl_lock);
11643         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11644                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11645                     io->io_hdr.nexus.initid.id,
11646                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11647         } else { /* CTL_TASK_CLEAR_TASK_SET */
11648                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11649                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11650         }
11651         mtx_unlock(&lun->lun_lock);
11652         return (0);
11653 }
11654
11655 static int
11656 ctl_i_t_nexus_reset(union ctl_io *io)
11657 {
11658         struct ctl_softc *softc = control_softc;
11659         struct ctl_lun *lun;
11660         uint32_t initidx, residx;
11661
11662         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11663         residx = ctl_get_resindex(&io->io_hdr.nexus);
11664         mtx_lock(&softc->ctl_lock);
11665         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11666                 mtx_lock(&lun->lun_lock);
11667                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11668                     io->io_hdr.nexus.initid.id,
11669                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11670 #ifdef CTL_WITH_CA
11671                 ctl_clear_mask(lun->have_ca, initidx);
11672 #endif
11673                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
11674                         lun->flags &= ~CTL_LUN_RESERVED;
11675                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11676                 mtx_unlock(&lun->lun_lock);
11677         }
11678         mtx_unlock(&softc->ctl_lock);
11679         return (0);
11680 }
11681
11682 static int
11683 ctl_abort_task(union ctl_io *io)
11684 {
11685         union ctl_io *xio;
11686         struct ctl_lun *lun;
11687         struct ctl_softc *softc;
11688 #if 0
11689         struct sbuf sb;
11690         char printbuf[128];
11691 #endif
11692         int found;
11693         uint32_t targ_lun;
11694
11695         softc = control_softc;
11696         found = 0;
11697
11698         /*
11699          * Look up the LUN.
11700          */
11701         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11702         mtx_lock(&softc->ctl_lock);
11703         if ((targ_lun < CTL_MAX_LUNS)
11704          && (softc->ctl_luns[targ_lun] != NULL))
11705                 lun = softc->ctl_luns[targ_lun];
11706         else {
11707                 mtx_unlock(&softc->ctl_lock);
11708                 return (1);
11709         }
11710
11711 #if 0
11712         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11713                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11714 #endif
11715
11716         mtx_lock(&lun->lun_lock);
11717         mtx_unlock(&softc->ctl_lock);
11718         /*
11719          * Run through the OOA queue and attempt to find the given I/O.
11720          * The target port, initiator ID, tag type and tag number have to
11721          * match the values that we got from the initiator.  If we have an
11722          * untagged command to abort, simply abort the first untagged command
11723          * we come to.  We only allow one untagged command at a time of course.
11724          */
11725         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11726              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11727 #if 0
11728                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11729
11730                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11731                             lun->lun, xio->scsiio.tag_num,
11732                             xio->scsiio.tag_type,
11733                             (xio->io_hdr.blocked_links.tqe_prev
11734                             == NULL) ? "" : " BLOCKED",
11735                             (xio->io_hdr.flags &
11736                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11737                             (xio->io_hdr.flags &
11738                             CTL_FLAG_ABORT) ? " ABORT" : "",
11739                             (xio->io_hdr.flags &
11740                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11741                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11742                 sbuf_finish(&sb);
11743                 printf("%s\n", sbuf_data(&sb));
11744 #endif
11745
11746                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11747                  || (xio->io_hdr.nexus.initid.id != io->io_hdr.nexus.initid.id)
11748                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11749                         continue;
11750
11751                 /*
11752                  * If the abort says that the task is untagged, the
11753                  * task in the queue must be untagged.  Otherwise,
11754                  * we just check to see whether the tag numbers
11755                  * match.  This is because the QLogic firmware
11756                  * doesn't pass back the tag type in an abort
11757                  * request.
11758                  */
11759 #if 0
11760                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11761                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11762                  || (xio->scsiio.tag_num == io->taskio.tag_num))
11763 #endif
11764                 /*
11765                  * XXX KDM we've got problems with FC, because it
11766                  * doesn't send down a tag type with aborts.  So we
11767                  * can only really go by the tag number...
11768                  * This may cause problems with parallel SCSI.
11769                  * Need to figure that out!!
11770                  */
11771                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
11772                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11773                         found = 1;
11774                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11775                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11776                                 union ctl_ha_msg msg_info;
11777
11778                                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11779                                 msg_info.hdr.nexus = io->io_hdr.nexus;
11780                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11781                                 msg_info.task.tag_num = io->taskio.tag_num;
11782                                 msg_info.task.tag_type = io->taskio.tag_type;
11783                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11784                                 msg_info.hdr.original_sc = NULL;
11785                                 msg_info.hdr.serializing_sc = NULL;
11786 #if 0
11787                                 printf("Sent Abort to other side\n");
11788 #endif
11789                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11790                                     (void *)&msg_info, sizeof(msg_info), 0) !=
11791                                     CTL_HA_STATUS_SUCCESS) {
11792                                 }
11793                         }
11794 #if 0
11795                         printf("ctl_abort_task: found I/O to abort\n");
11796 #endif
11797                 }
11798         }
11799         mtx_unlock(&lun->lun_lock);
11800
11801         if (found == 0) {
11802                 /*
11803                  * This isn't really an error.  It's entirely possible for
11804                  * the abort and command completion to cross on the wire.
11805                  * This is more of an informative/diagnostic error.
11806                  */
11807 #if 0
11808                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11809                        "%d:%d:%d:%d tag %d type %d\n",
11810                        io->io_hdr.nexus.initid.id,
11811                        io->io_hdr.nexus.targ_port,
11812                        io->io_hdr.nexus.targ_target.id,
11813                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11814                        io->taskio.tag_type);
11815 #endif
11816         }
11817         return (0);
11818 }
11819
11820 static void
11821 ctl_run_task(union ctl_io *io)
11822 {
11823         struct ctl_softc *softc = control_softc;
11824         int retval = 1;
11825         const char *task_desc;
11826
11827         CTL_DEBUG_PRINT(("ctl_run_task\n"));
11828
11829         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11830             ("ctl_run_task: Unextected io_type %d\n",
11831              io->io_hdr.io_type));
11832
11833         task_desc = ctl_scsi_task_string(&io->taskio);
11834         if (task_desc != NULL) {
11835 #ifdef NEEDTOPORT
11836                 csevent_log(CSC_CTL | CSC_SHELF_SW |
11837                             CTL_TASK_REPORT,
11838                             csevent_LogType_Trace,
11839                             csevent_Severity_Information,
11840                             csevent_AlertLevel_Green,
11841                             csevent_FRU_Firmware,
11842                             csevent_FRU_Unknown,
11843                             "CTL: received task: %s",task_desc);
11844 #endif
11845         } else {
11846 #ifdef NEEDTOPORT
11847                 csevent_log(CSC_CTL | CSC_SHELF_SW |
11848                             CTL_TASK_REPORT,
11849                             csevent_LogType_Trace,
11850                             csevent_Severity_Information,
11851                             csevent_AlertLevel_Green,
11852                             csevent_FRU_Firmware,
11853                             csevent_FRU_Unknown,
11854                             "CTL: received unknown task "
11855                             "type: %d (%#x)",
11856                             io->taskio.task_action,
11857                             io->taskio.task_action);
11858 #endif
11859         }
11860         switch (io->taskio.task_action) {
11861         case CTL_TASK_ABORT_TASK:
11862                 retval = ctl_abort_task(io);
11863                 break;
11864         case CTL_TASK_ABORT_TASK_SET:
11865         case CTL_TASK_CLEAR_TASK_SET:
11866                 retval = ctl_abort_task_set(io);
11867                 break;
11868         case CTL_TASK_CLEAR_ACA:
11869                 break;
11870         case CTL_TASK_I_T_NEXUS_RESET:
11871                 retval = ctl_i_t_nexus_reset(io);
11872                 break;
11873         case CTL_TASK_LUN_RESET: {
11874                 struct ctl_lun *lun;
11875                 uint32_t targ_lun;
11876
11877                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11878                 mtx_lock(&softc->ctl_lock);
11879                 if ((targ_lun < CTL_MAX_LUNS)
11880                  && (softc->ctl_luns[targ_lun] != NULL))
11881                         lun = softc->ctl_luns[targ_lun];
11882                 else {
11883                         mtx_unlock(&softc->ctl_lock);
11884                         retval = 1;
11885                         break;
11886                 }
11887
11888                 if (!(io->io_hdr.flags &
11889                     CTL_FLAG_FROM_OTHER_SC)) {
11890                         union ctl_ha_msg msg_info;
11891
11892                         io->io_hdr.flags |=
11893                                 CTL_FLAG_SENT_2OTHER_SC;
11894                         msg_info.hdr.msg_type =
11895                                 CTL_MSG_MANAGE_TASKS;
11896                         msg_info.hdr.nexus = io->io_hdr.nexus;
11897                         msg_info.task.task_action =
11898                                 CTL_TASK_LUN_RESET;
11899                         msg_info.hdr.original_sc = NULL;
11900                         msg_info.hdr.serializing_sc = NULL;
11901                         if (CTL_HA_STATUS_SUCCESS !=
11902                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11903                             (void *)&msg_info,
11904                             sizeof(msg_info), 0)) {
11905                         }
11906                 }
11907
11908                 retval = ctl_lun_reset(lun, io,
11909                                        CTL_UA_LUN_RESET);
11910                 mtx_unlock(&softc->ctl_lock);
11911                 break;
11912         }
11913         case CTL_TASK_TARGET_RESET:
11914                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
11915                 break;
11916         case CTL_TASK_BUS_RESET:
11917                 retval = ctl_bus_reset(softc, io);
11918                 break;
11919         case CTL_TASK_PORT_LOGIN:
11920                 break;
11921         case CTL_TASK_PORT_LOGOUT:
11922                 break;
11923         default:
11924                 printf("ctl_run_task: got unknown task management event %d\n",
11925                        io->taskio.task_action);
11926                 break;
11927         }
11928         if (retval == 0)
11929                 io->io_hdr.status = CTL_SUCCESS;
11930         else
11931                 io->io_hdr.status = CTL_ERROR;
11932         ctl_done(io);
11933 }
11934
11935 /*
11936  * For HA operation.  Handle commands that come in from the other
11937  * controller.
11938  */
11939 static void
11940 ctl_handle_isc(union ctl_io *io)
11941 {
11942         int free_io;
11943         struct ctl_lun *lun;
11944         struct ctl_softc *softc;
11945         uint32_t targ_lun;
11946
11947         softc = control_softc;
11948
11949         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11950         lun = softc->ctl_luns[targ_lun];
11951
11952         switch (io->io_hdr.msg_type) {
11953         case CTL_MSG_SERIALIZE:
11954                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11955                 break;
11956         case CTL_MSG_R2R: {
11957                 const struct ctl_cmd_entry *entry;
11958
11959                 /*
11960                  * This is only used in SER_ONLY mode.
11961                  */
11962                 free_io = 0;
11963                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11964                 mtx_lock(&lun->lun_lock);
11965                 if (ctl_scsiio_lun_check(lun,
11966                     entry, (struct ctl_scsiio *)io) != 0) {
11967                         mtx_unlock(&lun->lun_lock);
11968                         ctl_done(io);
11969                         break;
11970                 }
11971                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11972                 mtx_unlock(&lun->lun_lock);
11973                 ctl_enqueue_rtr(io);
11974                 break;
11975         }
11976         case CTL_MSG_FINISH_IO:
11977                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
11978                         free_io = 0;
11979                         ctl_done(io);
11980                 } else {
11981                         free_io = 1;
11982                         mtx_lock(&lun->lun_lock);
11983                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11984                                      ooa_links);
11985                         ctl_check_blocked(lun);
11986                         mtx_unlock(&lun->lun_lock);
11987                 }
11988                 break;
11989         case CTL_MSG_PERS_ACTION:
11990                 ctl_hndl_per_res_out_on_other_sc(
11991                         (union ctl_ha_msg *)&io->presio.pr_msg);
11992                 free_io = 1;
11993                 break;
11994         case CTL_MSG_BAD_JUJU:
11995                 free_io = 0;
11996                 ctl_done(io);
11997                 break;
11998         case CTL_MSG_DATAMOVE:
11999                 /* Only used in XFER mode */
12000                 free_io = 0;
12001                 ctl_datamove_remote(io);
12002                 break;
12003         case CTL_MSG_DATAMOVE_DONE:
12004                 /* Only used in XFER mode */
12005                 free_io = 0;
12006                 io->scsiio.be_move_done(io);
12007                 break;
12008         default:
12009                 free_io = 1;
12010                 printf("%s: Invalid message type %d\n",
12011                        __func__, io->io_hdr.msg_type);
12012                 break;
12013         }
12014         if (free_io)
12015                 ctl_free_io(io);
12016
12017 }
12018
12019
12020 /*
12021  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12022  * there is no match.
12023  */
12024 static ctl_lun_error_pattern
12025 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12026 {
12027         const struct ctl_cmd_entry *entry;
12028         ctl_lun_error_pattern filtered_pattern, pattern;
12029
12030         pattern = desc->error_pattern;
12031
12032         /*
12033          * XXX KDM we need more data passed into this function to match a
12034          * custom pattern, and we actually need to implement custom pattern
12035          * matching.
12036          */
12037         if (pattern & CTL_LUN_PAT_CMD)
12038                 return (CTL_LUN_PAT_CMD);
12039
12040         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12041                 return (CTL_LUN_PAT_ANY);
12042
12043         entry = ctl_get_cmd_entry(ctsio, NULL);
12044
12045         filtered_pattern = entry->pattern & pattern;
12046
12047         /*
12048          * If the user requested specific flags in the pattern (e.g.
12049          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12050          * flags.
12051          *
12052          * If the user did not specify any flags, it doesn't matter whether
12053          * or not the command supports the flags.
12054          */
12055         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12056              (pattern & ~CTL_LUN_PAT_MASK))
12057                 return (CTL_LUN_PAT_NONE);
12058
12059         /*
12060          * If the user asked for a range check, see if the requested LBA
12061          * range overlaps with this command's LBA range.
12062          */
12063         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12064                 uint64_t lba1;
12065                 uint64_t len1;
12066                 ctl_action action;
12067                 int retval;
12068
12069                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12070                 if (retval != 0)
12071                         return (CTL_LUN_PAT_NONE);
12072
12073                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12074                                               desc->lba_range.len, FALSE);
12075                 /*
12076                  * A "pass" means that the LBA ranges don't overlap, so
12077                  * this doesn't match the user's range criteria.
12078                  */
12079                 if (action == CTL_ACTION_PASS)
12080                         return (CTL_LUN_PAT_NONE);
12081         }
12082
12083         return (filtered_pattern);
12084 }
12085
12086 static void
12087 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12088 {
12089         struct ctl_error_desc *desc, *desc2;
12090
12091         mtx_assert(&lun->lun_lock, MA_OWNED);
12092
12093         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12094                 ctl_lun_error_pattern pattern;
12095                 /*
12096                  * Check to see whether this particular command matches
12097                  * the pattern in the descriptor.
12098                  */
12099                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12100                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12101                         continue;
12102
12103                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12104                 case CTL_LUN_INJ_ABORTED:
12105                         ctl_set_aborted(&io->scsiio);
12106                         break;
12107                 case CTL_LUN_INJ_MEDIUM_ERR:
12108                         ctl_set_medium_error(&io->scsiio);
12109                         break;
12110                 case CTL_LUN_INJ_UA:
12111                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12112                          * OCCURRED */
12113                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12114                         break;
12115                 case CTL_LUN_INJ_CUSTOM:
12116                         /*
12117                          * We're assuming the user knows what he is doing.
12118                          * Just copy the sense information without doing
12119                          * checks.
12120                          */
12121                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12122                               MIN(sizeof(desc->custom_sense),
12123                                   sizeof(io->scsiio.sense_data)));
12124                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12125                         io->scsiio.sense_len = SSD_FULL_SIZE;
12126                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12127                         break;
12128                 case CTL_LUN_INJ_NONE:
12129                 default:
12130                         /*
12131                          * If this is an error injection type we don't know
12132                          * about, clear the continuous flag (if it is set)
12133                          * so it will get deleted below.
12134                          */
12135                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12136                         break;
12137                 }
12138                 /*
12139                  * By default, each error injection action is a one-shot
12140                  */
12141                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12142                         continue;
12143
12144                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12145
12146                 free(desc, M_CTL);
12147         }
12148 }
12149
12150 #ifdef CTL_IO_DELAY
12151 static void
12152 ctl_datamove_timer_wakeup(void *arg)
12153 {
12154         union ctl_io *io;
12155
12156         io = (union ctl_io *)arg;
12157
12158         ctl_datamove(io);
12159 }
12160 #endif /* CTL_IO_DELAY */
12161
12162 void
12163 ctl_datamove(union ctl_io *io)
12164 {
12165         void (*fe_datamove)(union ctl_io *io);
12166
12167         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12168
12169         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12170
12171 #ifdef CTL_TIME_IO
12172         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12173                 char str[256];
12174                 char path_str[64];
12175                 struct sbuf sb;
12176
12177                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12178                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12179
12180                 sbuf_cat(&sb, path_str);
12181                 switch (io->io_hdr.io_type) {
12182                 case CTL_IO_SCSI:
12183                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12184                         sbuf_printf(&sb, "\n");
12185                         sbuf_cat(&sb, path_str);
12186                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12187                                     io->scsiio.tag_num, io->scsiio.tag_type);
12188                         break;
12189                 case CTL_IO_TASK:
12190                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12191                                     "Tag Type: %d\n", io->taskio.task_action,
12192                                     io->taskio.tag_num, io->taskio.tag_type);
12193                         break;
12194                 default:
12195                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12196                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12197                         break;
12198                 }
12199                 sbuf_cat(&sb, path_str);
12200                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12201                             (intmax_t)time_uptime - io->io_hdr.start_time);
12202                 sbuf_finish(&sb);
12203                 printf("%s", sbuf_data(&sb));
12204         }
12205 #endif /* CTL_TIME_IO */
12206
12207 #ifdef CTL_IO_DELAY
12208         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12209                 struct ctl_lun *lun;
12210
12211                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12212
12213                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12214         } else {
12215                 struct ctl_lun *lun;
12216
12217                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12218                 if ((lun != NULL)
12219                  && (lun->delay_info.datamove_delay > 0)) {
12220                         struct callout *callout;
12221
12222                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12223                         callout_init(callout, /*mpsafe*/ 1);
12224                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12225                         callout_reset(callout,
12226                                       lun->delay_info.datamove_delay * hz,
12227                                       ctl_datamove_timer_wakeup, io);
12228                         if (lun->delay_info.datamove_type ==
12229                             CTL_DELAY_TYPE_ONESHOT)
12230                                 lun->delay_info.datamove_delay = 0;
12231                         return;
12232                 }
12233         }
12234 #endif
12235
12236         /*
12237          * This command has been aborted.  Set the port status, so we fail
12238          * the data move.
12239          */
12240         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12241                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12242                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12243                        io->io_hdr.nexus.targ_port,
12244                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12245                        io->io_hdr.nexus.targ_lun);
12246                 io->io_hdr.port_status = 31337;
12247                 /*
12248                  * Note that the backend, in this case, will get the
12249                  * callback in its context.  In other cases it may get
12250                  * called in the frontend's interrupt thread context.
12251                  */
12252                 io->scsiio.be_move_done(io);
12253                 return;
12254         }
12255
12256         /* Don't confuse frontend with zero length data move. */
12257         if (io->scsiio.kern_data_len == 0) {
12258                 io->scsiio.be_move_done(io);
12259                 return;
12260         }
12261
12262         /*
12263          * If we're in XFER mode and this I/O is from the other shelf
12264          * controller, we need to send the DMA to the other side to
12265          * actually transfer the data to/from the host.  In serialize only
12266          * mode the transfer happens below CTL and ctl_datamove() is only
12267          * called on the machine that originally received the I/O.
12268          */
12269         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12270          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12271                 union ctl_ha_msg msg;
12272                 uint32_t sg_entries_sent;
12273                 int do_sg_copy;
12274                 int i;
12275
12276                 memset(&msg, 0, sizeof(msg));
12277                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12278                 msg.hdr.original_sc = io->io_hdr.original_sc;
12279                 msg.hdr.serializing_sc = io;
12280                 msg.hdr.nexus = io->io_hdr.nexus;
12281                 msg.dt.flags = io->io_hdr.flags;
12282                 /*
12283                  * We convert everything into a S/G list here.  We can't
12284                  * pass by reference, only by value between controllers.
12285                  * So we can't pass a pointer to the S/G list, only as many
12286                  * S/G entries as we can fit in here.  If it's possible for
12287                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12288                  * then we need to break this up into multiple transfers.
12289                  */
12290                 if (io->scsiio.kern_sg_entries == 0) {
12291                         msg.dt.kern_sg_entries = 1;
12292                         /*
12293                          * If this is in cached memory, flush the cache
12294                          * before we send the DMA request to the other
12295                          * controller.  We want to do this in either the
12296                          * read or the write case.  The read case is
12297                          * straightforward.  In the write case, we want to
12298                          * make sure nothing is in the local cache that
12299                          * could overwrite the DMAed data.
12300                          */
12301                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12302                                 /*
12303                                  * XXX KDM use bus_dmamap_sync() here.
12304                                  */
12305                         }
12306
12307                         /*
12308                          * Convert to a physical address if this is a
12309                          * virtual address.
12310                          */
12311                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12312                                 msg.dt.sg_list[0].addr =
12313                                         io->scsiio.kern_data_ptr;
12314                         } else {
12315                                 /*
12316                                  * XXX KDM use busdma here!
12317                                  */
12318 #if 0
12319                                 msg.dt.sg_list[0].addr = (void *)
12320                                         vtophys(io->scsiio.kern_data_ptr);
12321 #endif
12322                         }
12323
12324                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12325                         do_sg_copy = 0;
12326                 } else {
12327                         struct ctl_sg_entry *sgl;
12328
12329                         do_sg_copy = 1;
12330                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12331                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12332                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12333                                 /*
12334                                  * XXX KDM use bus_dmamap_sync() here.
12335                                  */
12336                         }
12337                 }
12338
12339                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12340                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12341                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12342                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12343                 msg.dt.sg_sequence = 0;
12344
12345                 /*
12346                  * Loop until we've sent all of the S/G entries.  On the
12347                  * other end, we'll recompose these S/G entries into one
12348                  * contiguous list before passing it to the
12349                  */
12350                 for (sg_entries_sent = 0; sg_entries_sent <
12351                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12352                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12353                                 sizeof(msg.dt.sg_list[0])),
12354                                 msg.dt.kern_sg_entries - sg_entries_sent);
12355
12356                         if (do_sg_copy != 0) {
12357                                 struct ctl_sg_entry *sgl;
12358                                 int j;
12359
12360                                 sgl = (struct ctl_sg_entry *)
12361                                         io->scsiio.kern_data_ptr;
12362                                 /*
12363                                  * If this is in cached memory, flush the cache
12364                                  * before we send the DMA request to the other
12365                                  * controller.  We want to do this in either
12366                                  * the * read or the write case.  The read
12367                                  * case is straightforward.  In the write
12368                                  * case, we want to make sure nothing is
12369                                  * in the local cache that could overwrite
12370                                  * the DMAed data.
12371                                  */
12372
12373                                 for (i = sg_entries_sent, j = 0;
12374                                      i < msg.dt.cur_sg_entries; i++, j++) {
12375                                         if ((io->io_hdr.flags &
12376                                              CTL_FLAG_NO_DATASYNC) == 0) {
12377                                                 /*
12378                                                  * XXX KDM use bus_dmamap_sync()
12379                                                  */
12380                                         }
12381                                         if ((io->io_hdr.flags &
12382                                              CTL_FLAG_BUS_ADDR) == 0) {
12383                                                 /*
12384                                                  * XXX KDM use busdma.
12385                                                  */
12386 #if 0
12387                                                 msg.dt.sg_list[j].addr =(void *)
12388                                                        vtophys(sgl[i].addr);
12389 #endif
12390                                         } else {
12391                                                 msg.dt.sg_list[j].addr =
12392                                                         sgl[i].addr;
12393                                         }
12394                                         msg.dt.sg_list[j].len = sgl[i].len;
12395                                 }
12396                         }
12397
12398                         sg_entries_sent += msg.dt.cur_sg_entries;
12399                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12400                                 msg.dt.sg_last = 1;
12401                         else
12402                                 msg.dt.sg_last = 0;
12403
12404                         /*
12405                          * XXX KDM drop and reacquire the lock here?
12406                          */
12407                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12408                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12409                                 /*
12410                                  * XXX do something here.
12411                                  */
12412                         }
12413
12414                         msg.dt.sent_sg_entries = sg_entries_sent;
12415                 }
12416                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12417                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12418                         ctl_failover_io(io, /*have_lock*/ 0);
12419
12420         } else {
12421
12422                 /*
12423                  * Lookup the fe_datamove() function for this particular
12424                  * front end.
12425                  */
12426                 fe_datamove =
12427                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12428
12429                 fe_datamove(io);
12430         }
12431 }
12432
12433 static void
12434 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12435 {
12436         union ctl_ha_msg msg;
12437         int isc_status;
12438
12439         memset(&msg, 0, sizeof(msg));
12440
12441         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12442         msg.hdr.original_sc = io;
12443         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12444         msg.hdr.nexus = io->io_hdr.nexus;
12445         msg.hdr.status = io->io_hdr.status;
12446         msg.scsi.tag_num = io->scsiio.tag_num;
12447         msg.scsi.tag_type = io->scsiio.tag_type;
12448         msg.scsi.scsi_status = io->scsiio.scsi_status;
12449         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12450                sizeof(io->scsiio.sense_data));
12451         msg.scsi.sense_len = io->scsiio.sense_len;
12452         msg.scsi.sense_residual = io->scsiio.sense_residual;
12453         msg.scsi.fetd_status = io->io_hdr.port_status;
12454         msg.scsi.residual = io->scsiio.residual;
12455         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12456
12457         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12458                 ctl_failover_io(io, /*have_lock*/ have_lock);
12459                 return;
12460         }
12461
12462         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12463         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12464                 /* XXX do something if this fails */
12465         }
12466
12467 }
12468
12469 /*
12470  * The DMA to the remote side is done, now we need to tell the other side
12471  * we're done so it can continue with its data movement.
12472  */
12473 static void
12474 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12475 {
12476         union ctl_io *io;
12477
12478         io = rq->context;
12479
12480         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12481                 printf("%s: ISC DMA write failed with error %d", __func__,
12482                        rq->ret);
12483                 ctl_set_internal_failure(&io->scsiio,
12484                                          /*sks_valid*/ 1,
12485                                          /*retry_count*/ rq->ret);
12486         }
12487
12488         ctl_dt_req_free(rq);
12489
12490         /*
12491          * In this case, we had to malloc the memory locally.  Free it.
12492          */
12493         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12494                 int i;
12495                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12496                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12497         }
12498         /*
12499          * The data is in local and remote memory, so now we need to send
12500          * status (good or back) back to the other side.
12501          */
12502         ctl_send_datamove_done(io, /*have_lock*/ 0);
12503 }
12504
12505 /*
12506  * We've moved the data from the host/controller into local memory.  Now we
12507  * need to push it over to the remote controller's memory.
12508  */
12509 static int
12510 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12511 {
12512         int retval;
12513
12514         retval = 0;
12515
12516         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12517                                           ctl_datamove_remote_write_cb);
12518
12519         return (retval);
12520 }
12521
12522 static void
12523 ctl_datamove_remote_write(union ctl_io *io)
12524 {
12525         int retval;
12526         void (*fe_datamove)(union ctl_io *io);
12527
12528         /*
12529          * - Get the data from the host/HBA into local memory.
12530          * - DMA memory from the local controller to the remote controller.
12531          * - Send status back to the remote controller.
12532          */
12533
12534         retval = ctl_datamove_remote_sgl_setup(io);
12535         if (retval != 0)
12536                 return;
12537
12538         /* Switch the pointer over so the FETD knows what to do */
12539         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12540
12541         /*
12542          * Use a custom move done callback, since we need to send completion
12543          * back to the other controller, not to the backend on this side.
12544          */
12545         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12546
12547         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12548
12549         fe_datamove(io);
12550
12551         return;
12552
12553 }
12554
12555 static int
12556 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12557 {
12558 #if 0
12559         char str[256];
12560         char path_str[64];
12561         struct sbuf sb;
12562 #endif
12563
12564         /*
12565          * In this case, we had to malloc the memory locally.  Free it.
12566          */
12567         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12568                 int i;
12569                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12570                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12571         }
12572
12573 #if 0
12574         scsi_path_string(io, path_str, sizeof(path_str));
12575         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12576         sbuf_cat(&sb, path_str);
12577         scsi_command_string(&io->scsiio, NULL, &sb);
12578         sbuf_printf(&sb, "\n");
12579         sbuf_cat(&sb, path_str);
12580         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12581                     io->scsiio.tag_num, io->scsiio.tag_type);
12582         sbuf_cat(&sb, path_str);
12583         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12584                     io->io_hdr.flags, io->io_hdr.status);
12585         sbuf_finish(&sb);
12586         printk("%s", sbuf_data(&sb));
12587 #endif
12588
12589
12590         /*
12591          * The read is done, now we need to send status (good or bad) back
12592          * to the other side.
12593          */
12594         ctl_send_datamove_done(io, /*have_lock*/ 0);
12595
12596         return (0);
12597 }
12598
12599 static void
12600 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12601 {
12602         union ctl_io *io;
12603         void (*fe_datamove)(union ctl_io *io);
12604
12605         io = rq->context;
12606
12607         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12608                 printf("%s: ISC DMA read failed with error %d", __func__,
12609                        rq->ret);
12610                 ctl_set_internal_failure(&io->scsiio,
12611                                          /*sks_valid*/ 1,
12612                                          /*retry_count*/ rq->ret);
12613         }
12614
12615         ctl_dt_req_free(rq);
12616
12617         /* Switch the pointer over so the FETD knows what to do */
12618         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12619
12620         /*
12621          * Use a custom move done callback, since we need to send completion
12622          * back to the other controller, not to the backend on this side.
12623          */
12624         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12625
12626         /* XXX KDM add checks like the ones in ctl_datamove? */
12627
12628         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12629
12630         fe_datamove(io);
12631 }
12632
12633 static int
12634 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12635 {
12636         struct ctl_sg_entry *local_sglist, *remote_sglist;
12637         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12638         struct ctl_softc *softc;
12639         int retval;
12640         int i;
12641
12642         retval = 0;
12643         softc = control_softc;
12644
12645         local_sglist = io->io_hdr.local_sglist;
12646         local_dma_sglist = io->io_hdr.local_dma_sglist;
12647         remote_sglist = io->io_hdr.remote_sglist;
12648         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12649
12650         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12651                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12652                         local_sglist[i].len = remote_sglist[i].len;
12653
12654                         /*
12655                          * XXX Detect the situation where the RS-level I/O
12656                          * redirector on the other side has already read the
12657                          * data off of the AOR RS on this side, and
12658                          * transferred it to remote (mirror) memory on the
12659                          * other side.  Since we already have the data in
12660                          * memory here, we just need to use it.
12661                          *
12662                          * XXX KDM this can probably be removed once we
12663                          * get the cache device code in and take the
12664                          * current AOR implementation out.
12665                          */
12666 #ifdef NEEDTOPORT
12667                         if ((remote_sglist[i].addr >=
12668                              (void *)vtophys(softc->mirr->addr))
12669                          && (remote_sglist[i].addr <
12670                              ((void *)vtophys(softc->mirr->addr) +
12671                              CacheMirrorOffset))) {
12672                                 local_sglist[i].addr = remote_sglist[i].addr -
12673                                         CacheMirrorOffset;
12674                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12675                                      CTL_FLAG_DATA_IN)
12676                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12677                         } else {
12678                                 local_sglist[i].addr = remote_sglist[i].addr +
12679                                         CacheMirrorOffset;
12680                         }
12681 #endif
12682 #if 0
12683                         printf("%s: local %p, remote %p, len %d\n",
12684                                __func__, local_sglist[i].addr,
12685                                remote_sglist[i].addr, local_sglist[i].len);
12686 #endif
12687                 }
12688         } else {
12689                 uint32_t len_to_go;
12690
12691                 /*
12692                  * In this case, we don't have automatically allocated
12693                  * memory for this I/O on this controller.  This typically
12694                  * happens with internal CTL I/O -- e.g. inquiry, mode
12695                  * sense, etc.  Anything coming from RAIDCore will have
12696                  * a mirror area available.
12697                  */
12698                 len_to_go = io->scsiio.kern_data_len;
12699
12700                 /*
12701                  * Clear the no datasync flag, we have to use malloced
12702                  * buffers.
12703                  */
12704                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12705
12706                 /*
12707                  * The difficult thing here is that the size of the various
12708                  * S/G segments may be different than the size from the
12709                  * remote controller.  That'll make it harder when DMAing
12710                  * the data back to the other side.
12711                  */
12712                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12713                      sizeof(io->io_hdr.remote_sglist[0])) &&
12714                      (len_to_go > 0); i++) {
12715                         local_sglist[i].len = MIN(len_to_go, 131072);
12716                         CTL_SIZE_8B(local_dma_sglist[i].len,
12717                                     local_sglist[i].len);
12718                         local_sglist[i].addr =
12719                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12720
12721                         local_dma_sglist[i].addr = local_sglist[i].addr;
12722
12723                         if (local_sglist[i].addr == NULL) {
12724                                 int j;
12725
12726                                 printf("malloc failed for %zd bytes!",
12727                                        local_dma_sglist[i].len);
12728                                 for (j = 0; j < i; j++) {
12729                                         free(local_sglist[j].addr, M_CTL);
12730                                 }
12731                                 ctl_set_internal_failure(&io->scsiio,
12732                                                          /*sks_valid*/ 1,
12733                                                          /*retry_count*/ 4857);
12734                                 retval = 1;
12735                                 goto bailout_error;
12736                                 
12737                         }
12738                         /* XXX KDM do we need a sync here? */
12739
12740                         len_to_go -= local_sglist[i].len;
12741                 }
12742                 /*
12743                  * Reset the number of S/G entries accordingly.  The
12744                  * original number of S/G entries is available in
12745                  * rem_sg_entries.
12746                  */
12747                 io->scsiio.kern_sg_entries = i;
12748
12749 #if 0
12750                 printf("%s: kern_sg_entries = %d\n", __func__,
12751                        io->scsiio.kern_sg_entries);
12752                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12753                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
12754                                local_sglist[i].addr, local_sglist[i].len,
12755                                local_dma_sglist[i].len);
12756 #endif
12757         }
12758
12759
12760         return (retval);
12761
12762 bailout_error:
12763
12764         ctl_send_datamove_done(io, /*have_lock*/ 0);
12765
12766         return (retval);
12767 }
12768
12769 static int
12770 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12771                          ctl_ha_dt_cb callback)
12772 {
12773         struct ctl_ha_dt_req *rq;
12774         struct ctl_sg_entry *remote_sglist, *local_sglist;
12775         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
12776         uint32_t local_used, remote_used, total_used;
12777         int retval;
12778         int i, j;
12779
12780         retval = 0;
12781
12782         rq = ctl_dt_req_alloc();
12783
12784         /*
12785          * If we failed to allocate the request, and if the DMA didn't fail
12786          * anyway, set busy status.  This is just a resource allocation
12787          * failure.
12788          */
12789         if ((rq == NULL)
12790          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12791                 ctl_set_busy(&io->scsiio);
12792
12793         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12794
12795                 if (rq != NULL)
12796                         ctl_dt_req_free(rq);
12797
12798                 /*
12799                  * The data move failed.  We need to return status back
12800                  * to the other controller.  No point in trying to DMA
12801                  * data to the remote controller.
12802                  */
12803
12804                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12805
12806                 retval = 1;
12807
12808                 goto bailout;
12809         }
12810
12811         local_sglist = io->io_hdr.local_sglist;
12812         local_dma_sglist = io->io_hdr.local_dma_sglist;
12813         remote_sglist = io->io_hdr.remote_sglist;
12814         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12815         local_used = 0;
12816         remote_used = 0;
12817         total_used = 0;
12818
12819         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12820                 rq->ret = CTL_HA_STATUS_SUCCESS;
12821                 rq->context = io;
12822                 callback(rq);
12823                 goto bailout;
12824         }
12825
12826         /*
12827          * Pull/push the data over the wire from/to the other controller.
12828          * This takes into account the possibility that the local and
12829          * remote sglists may not be identical in terms of the size of
12830          * the elements and the number of elements.
12831          *
12832          * One fundamental assumption here is that the length allocated for
12833          * both the local and remote sglists is identical.  Otherwise, we've
12834          * essentially got a coding error of some sort.
12835          */
12836         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12837                 int isc_ret;
12838                 uint32_t cur_len, dma_length;
12839                 uint8_t *tmp_ptr;
12840
12841                 rq->id = CTL_HA_DATA_CTL;
12842                 rq->command = command;
12843                 rq->context = io;
12844
12845                 /*
12846                  * Both pointers should be aligned.  But it is possible
12847                  * that the allocation length is not.  They should both
12848                  * also have enough slack left over at the end, though,
12849                  * to round up to the next 8 byte boundary.
12850                  */
12851                 cur_len = MIN(local_sglist[i].len - local_used,
12852                               remote_sglist[j].len - remote_used);
12853
12854                 /*
12855                  * In this case, we have a size issue and need to decrease
12856                  * the size, except in the case where we actually have less
12857                  * than 8 bytes left.  In that case, we need to increase
12858                  * the DMA length to get the last bit.
12859                  */
12860                 if ((cur_len & 0x7) != 0) {
12861                         if (cur_len > 0x7) {
12862                                 cur_len = cur_len - (cur_len & 0x7);
12863                                 dma_length = cur_len;
12864                         } else {
12865                                 CTL_SIZE_8B(dma_length, cur_len);
12866                         }
12867
12868                 } else
12869                         dma_length = cur_len;
12870
12871                 /*
12872                  * If we had to allocate memory for this I/O, instead of using
12873                  * the non-cached mirror memory, we'll need to flush the cache
12874                  * before trying to DMA to the other controller.
12875                  *
12876                  * We could end up doing this multiple times for the same
12877                  * segment if we have a larger local segment than remote
12878                  * segment.  That shouldn't be an issue.
12879                  */
12880                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12881                         /*
12882                          * XXX KDM use bus_dmamap_sync() here.
12883                          */
12884                 }
12885
12886                 rq->size = dma_length;
12887
12888                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12889                 tmp_ptr += local_used;
12890
12891                 /* Use physical addresses when talking to ISC hardware */
12892                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12893                         /* XXX KDM use busdma */
12894 #if 0
12895                         rq->local = vtophys(tmp_ptr);
12896 #endif
12897                 } else
12898                         rq->local = tmp_ptr;
12899
12900                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12901                 tmp_ptr += remote_used;
12902                 rq->remote = tmp_ptr;
12903
12904                 rq->callback = NULL;
12905
12906                 local_used += cur_len;
12907                 if (local_used >= local_sglist[i].len) {
12908                         i++;
12909                         local_used = 0;
12910                 }
12911
12912                 remote_used += cur_len;
12913                 if (remote_used >= remote_sglist[j].len) {
12914                         j++;
12915                         remote_used = 0;
12916                 }
12917                 total_used += cur_len;
12918
12919                 if (total_used >= io->scsiio.kern_data_len)
12920                         rq->callback = callback;
12921
12922                 if ((rq->size & 0x7) != 0) {
12923                         printf("%s: warning: size %d is not on 8b boundary\n",
12924                                __func__, rq->size);
12925                 }
12926                 if (((uintptr_t)rq->local & 0x7) != 0) {
12927                         printf("%s: warning: local %p not on 8b boundary\n",
12928                                __func__, rq->local);
12929                 }
12930                 if (((uintptr_t)rq->remote & 0x7) != 0) {
12931                         printf("%s: warning: remote %p not on 8b boundary\n",
12932                                __func__, rq->local);
12933                 }
12934 #if 0
12935                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12936                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12937                        rq->local, rq->remote, rq->size);
12938 #endif
12939
12940                 isc_ret = ctl_dt_single(rq);
12941                 if (isc_ret == CTL_HA_STATUS_WAIT)
12942                         continue;
12943
12944                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
12945                         rq->ret = CTL_HA_STATUS_SUCCESS;
12946                 } else {
12947                         rq->ret = isc_ret;
12948                 }
12949                 callback(rq);
12950                 goto bailout;
12951         }
12952
12953 bailout:
12954         return (retval);
12955
12956 }
12957
12958 static void
12959 ctl_datamove_remote_read(union ctl_io *io)
12960 {
12961         int retval;
12962         int i;
12963
12964         /*
12965          * This will send an error to the other controller in the case of a
12966          * failure.
12967          */
12968         retval = ctl_datamove_remote_sgl_setup(io);
12969         if (retval != 0)
12970                 return;
12971
12972         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12973                                           ctl_datamove_remote_read_cb);
12974         if ((retval != 0)
12975          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
12976                 /*
12977                  * Make sure we free memory if there was an error..  The
12978                  * ctl_datamove_remote_xfer() function will send the
12979                  * datamove done message, or call the callback with an
12980                  * error if there is a problem.
12981                  */
12982                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12983                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12984         }
12985
12986         return;
12987 }
12988
12989 /*
12990  * Process a datamove request from the other controller.  This is used for
12991  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12992  * first.  Once that is complete, the data gets DMAed into the remote
12993  * controller's memory.  For reads, we DMA from the remote controller's
12994  * memory into our memory first, and then move it out to the FETD.
12995  */
12996 static void
12997 ctl_datamove_remote(union ctl_io *io)
12998 {
12999         struct ctl_softc *softc;
13000
13001         softc = control_softc;
13002
13003         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13004
13005         /*
13006          * Note that we look for an aborted I/O here, but don't do some of
13007          * the other checks that ctl_datamove() normally does.
13008          * We don't need to run the datamove delay code, since that should
13009          * have been done if need be on the other controller.
13010          */
13011         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13012                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13013                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13014                        io->io_hdr.nexus.targ_port,
13015                        io->io_hdr.nexus.targ_target.id,
13016                        io->io_hdr.nexus.targ_lun);
13017                 io->io_hdr.port_status = 31338;
13018                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13019                 return;
13020         }
13021
13022         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13023                 ctl_datamove_remote_write(io);
13024         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13025                 ctl_datamove_remote_read(io);
13026         } else {
13027                 union ctl_ha_msg msg;
13028                 struct scsi_sense_data *sense;
13029                 uint8_t sks[3];
13030                 int retry_count;
13031
13032                 memset(&msg, 0, sizeof(msg));
13033
13034                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13035                 msg.hdr.status = CTL_SCSI_ERROR;
13036                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13037
13038                 retry_count = 4243;
13039
13040                 sense = &msg.scsi.sense_data;
13041                 sks[0] = SSD_SCS_VALID;
13042                 sks[1] = (retry_count >> 8) & 0xff;
13043                 sks[2] = retry_count & 0xff;
13044
13045                 /* "Internal target failure" */
13046                 scsi_set_sense_data(sense,
13047                                     /*sense_format*/ SSD_TYPE_NONE,
13048                                     /*current_error*/ 1,
13049                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13050                                     /*asc*/ 0x44,
13051                                     /*ascq*/ 0x00,
13052                                     /*type*/ SSD_ELEM_SKS,
13053                                     /*size*/ sizeof(sks),
13054                                     /*data*/ sks,
13055                                     SSD_ELEM_NONE);
13056
13057                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13058                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13059                         ctl_failover_io(io, /*have_lock*/ 1);
13060                         return;
13061                 }
13062
13063                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13064                     CTL_HA_STATUS_SUCCESS) {
13065                         /* XXX KDM what to do if this fails? */
13066                 }
13067                 return;
13068         }
13069         
13070 }
13071
13072 static int
13073 ctl_process_done(union ctl_io *io)
13074 {
13075         struct ctl_lun *lun;
13076         struct ctl_softc *softc = control_softc;
13077         void (*fe_done)(union ctl_io *io);
13078         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13079
13080         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13081
13082         fe_done = softc->ctl_ports[targ_port]->fe_done;
13083
13084 #ifdef CTL_TIME_IO
13085         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13086                 char str[256];
13087                 char path_str[64];
13088                 struct sbuf sb;
13089
13090                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13091                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13092
13093                 sbuf_cat(&sb, path_str);
13094                 switch (io->io_hdr.io_type) {
13095                 case CTL_IO_SCSI:
13096                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13097                         sbuf_printf(&sb, "\n");
13098                         sbuf_cat(&sb, path_str);
13099                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13100                                     io->scsiio.tag_num, io->scsiio.tag_type);
13101                         break;
13102                 case CTL_IO_TASK:
13103                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13104                                     "Tag Type: %d\n", io->taskio.task_action,
13105                                     io->taskio.tag_num, io->taskio.tag_type);
13106                         break;
13107                 default:
13108                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13109                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13110                         break;
13111                 }
13112                 sbuf_cat(&sb, path_str);
13113                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13114                             (intmax_t)time_uptime - io->io_hdr.start_time);
13115                 sbuf_finish(&sb);
13116                 printf("%s", sbuf_data(&sb));
13117         }
13118 #endif /* CTL_TIME_IO */
13119
13120         switch (io->io_hdr.io_type) {
13121         case CTL_IO_SCSI:
13122                 break;
13123         case CTL_IO_TASK:
13124                 if (ctl_debug & CTL_DEBUG_INFO)
13125                         ctl_io_error_print(io, NULL);
13126                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13127                         ctl_free_io(io);
13128                 else
13129                         fe_done(io);
13130                 return (CTL_RETVAL_COMPLETE);
13131         default:
13132                 panic("ctl_process_done: invalid io type %d\n",
13133                       io->io_hdr.io_type);
13134                 break; /* NOTREACHED */
13135         }
13136
13137         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13138         if (lun == NULL) {
13139                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13140                                  io->io_hdr.nexus.targ_mapped_lun));
13141                 goto bailout;
13142         }
13143
13144         mtx_lock(&lun->lun_lock);
13145
13146         /*
13147          * Check to see if we have any errors to inject here.  We only
13148          * inject errors for commands that don't already have errors set.
13149          */
13150         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13151             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13152             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13153                 ctl_inject_error(lun, io);
13154
13155         /*
13156          * XXX KDM how do we treat commands that aren't completed
13157          * successfully?
13158          *
13159          * XXX KDM should we also track I/O latency?
13160          */
13161         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13162             io->io_hdr.io_type == CTL_IO_SCSI) {
13163 #ifdef CTL_TIME_IO
13164                 struct bintime cur_bt;
13165 #endif
13166                 int type;
13167
13168                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13169                     CTL_FLAG_DATA_IN)
13170                         type = CTL_STATS_READ;
13171                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13172                     CTL_FLAG_DATA_OUT)
13173                         type = CTL_STATS_WRITE;
13174                 else
13175                         type = CTL_STATS_NO_IO;
13176
13177                 lun->stats.ports[targ_port].bytes[type] +=
13178                     io->scsiio.kern_total_len;
13179                 lun->stats.ports[targ_port].operations[type]++;
13180 #ifdef CTL_TIME_IO
13181                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13182                    &io->io_hdr.dma_bt);
13183                 lun->stats.ports[targ_port].num_dmas[type] +=
13184                     io->io_hdr.num_dmas;
13185                 getbintime(&cur_bt);
13186                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13187                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13188 #endif
13189         }
13190
13191         /*
13192          * Remove this from the OOA queue.
13193          */
13194         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13195 #ifdef CTL_TIME_IO
13196         if (TAILQ_EMPTY(&lun->ooa_queue))
13197                 lun->last_busy = getsbinuptime();
13198 #endif
13199
13200         /*
13201          * Run through the blocked queue on this LUN and see if anything
13202          * has become unblocked, now that this transaction is done.
13203          */
13204         ctl_check_blocked(lun);
13205
13206         /*
13207          * If the LUN has been invalidated, free it if there is nothing
13208          * left on its OOA queue.
13209          */
13210         if ((lun->flags & CTL_LUN_INVALID)
13211          && TAILQ_EMPTY(&lun->ooa_queue)) {
13212                 mtx_unlock(&lun->lun_lock);
13213                 mtx_lock(&softc->ctl_lock);
13214                 ctl_free_lun(lun);
13215                 mtx_unlock(&softc->ctl_lock);
13216         } else
13217                 mtx_unlock(&lun->lun_lock);
13218
13219 bailout:
13220
13221         /*
13222          * If this command has been aborted, make sure we set the status
13223          * properly.  The FETD is responsible for freeing the I/O and doing
13224          * whatever it needs to do to clean up its state.
13225          */
13226         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13227                 ctl_set_task_aborted(&io->scsiio);
13228
13229         /*
13230          * If enabled, print command error status.
13231          */
13232         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13233             (ctl_debug & CTL_DEBUG_INFO) != 0)
13234                 ctl_io_error_print(io, NULL);
13235
13236         /*
13237          * Tell the FETD or the other shelf controller we're done with this
13238          * command.  Note that only SCSI commands get to this point.  Task
13239          * management commands are completed above.
13240          *
13241          * We only send status to the other controller if we're in XFER
13242          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13243          * received the I/O (from CTL's perspective), and so the status is
13244          * generated there.
13245          * 
13246          * XXX KDM if we hold the lock here, we could cause a deadlock
13247          * if the frontend comes back in in this context to queue
13248          * something.
13249          */
13250         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13251          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13252                 union ctl_ha_msg msg;
13253
13254                 memset(&msg, 0, sizeof(msg));
13255                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13256                 msg.hdr.original_sc = io->io_hdr.original_sc;
13257                 msg.hdr.nexus = io->io_hdr.nexus;
13258                 msg.hdr.status = io->io_hdr.status;
13259                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13260                 msg.scsi.tag_num = io->scsiio.tag_num;
13261                 msg.scsi.tag_type = io->scsiio.tag_type;
13262                 msg.scsi.sense_len = io->scsiio.sense_len;
13263                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13264                 msg.scsi.residual = io->scsiio.residual;
13265                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13266                        sizeof(io->scsiio.sense_data));
13267                 /*
13268                  * We copy this whether or not this is an I/O-related
13269                  * command.  Otherwise, we'd have to go and check to see
13270                  * whether it's a read/write command, and it really isn't
13271                  * worth it.
13272                  */
13273                 memcpy(&msg.scsi.lbalen,
13274                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13275                        sizeof(msg.scsi.lbalen));
13276
13277                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13278                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13279                         /* XXX do something here */
13280                 }
13281
13282                 ctl_free_io(io);
13283         } else 
13284                 fe_done(io);
13285
13286         return (CTL_RETVAL_COMPLETE);
13287 }
13288
13289 #ifdef CTL_WITH_CA
13290 /*
13291  * Front end should call this if it doesn't do autosense.  When the request
13292  * sense comes back in from the initiator, we'll dequeue this and send it.
13293  */
13294 int
13295 ctl_queue_sense(union ctl_io *io)
13296 {
13297         struct ctl_lun *lun;
13298         struct ctl_port *port;
13299         struct ctl_softc *softc;
13300         uint32_t initidx, targ_lun;
13301
13302         softc = control_softc;
13303
13304         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13305
13306         /*
13307          * LUN lookup will likely move to the ctl_work_thread() once we
13308          * have our new queueing infrastructure (that doesn't put things on
13309          * a per-LUN queue initially).  That is so that we can handle
13310          * things like an INQUIRY to a LUN that we don't have enabled.  We
13311          * can't deal with that right now.
13312          */
13313         mtx_lock(&softc->ctl_lock);
13314
13315         /*
13316          * If we don't have a LUN for this, just toss the sense
13317          * information.
13318          */
13319         port = ctl_io_port(&ctsio->io_hdr);
13320         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13321         if ((targ_lun < CTL_MAX_LUNS)
13322          && (softc->ctl_luns[targ_lun] != NULL))
13323                 lun = softc->ctl_luns[targ_lun];
13324         else
13325                 goto bailout;
13326
13327         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13328
13329         mtx_lock(&lun->lun_lock);
13330         /*
13331          * Already have CA set for this LUN...toss the sense information.
13332          */
13333         if (ctl_is_set(lun->have_ca, initidx)) {
13334                 mtx_unlock(&lun->lun_lock);
13335                 goto bailout;
13336         }
13337
13338         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13339                MIN(sizeof(lun->pending_sense[initidx]),
13340                sizeof(io->scsiio.sense_data)));
13341         ctl_set_mask(lun->have_ca, initidx);
13342         mtx_unlock(&lun->lun_lock);
13343
13344 bailout:
13345         mtx_unlock(&softc->ctl_lock);
13346
13347         ctl_free_io(io);
13348
13349         return (CTL_RETVAL_COMPLETE);
13350 }
13351 #endif
13352
13353 /*
13354  * Primary command inlet from frontend ports.  All SCSI and task I/O
13355  * requests must go through this function.
13356  */
13357 int
13358 ctl_queue(union ctl_io *io)
13359 {
13360         struct ctl_port *port;
13361
13362         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13363
13364 #ifdef CTL_TIME_IO
13365         io->io_hdr.start_time = time_uptime;
13366         getbintime(&io->io_hdr.start_bt);
13367 #endif /* CTL_TIME_IO */
13368
13369         /* Map FE-specific LUN ID into global one. */
13370         port = ctl_io_port(&io->io_hdr);
13371         io->io_hdr.nexus.targ_mapped_lun =
13372             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13373
13374         switch (io->io_hdr.io_type) {
13375         case CTL_IO_SCSI:
13376         case CTL_IO_TASK:
13377                 if (ctl_debug & CTL_DEBUG_CDB)
13378                         ctl_io_print(io);
13379                 ctl_enqueue_incoming(io);
13380                 break;
13381         default:
13382                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13383                 return (EINVAL);
13384         }
13385
13386         return (CTL_RETVAL_COMPLETE);
13387 }
13388
13389 #ifdef CTL_IO_DELAY
13390 static void
13391 ctl_done_timer_wakeup(void *arg)
13392 {
13393         union ctl_io *io;
13394
13395         io = (union ctl_io *)arg;
13396         ctl_done(io);
13397 }
13398 #endif /* CTL_IO_DELAY */
13399
13400 void
13401 ctl_done(union ctl_io *io)
13402 {
13403
13404         /*
13405          * Enable this to catch duplicate completion issues.
13406          */
13407 #if 0
13408         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13409                 printf("%s: type %d msg %d cdb %x iptl: "
13410                        "%d:%d:%d:%d tag 0x%04x "
13411                        "flag %#x status %x\n",
13412                         __func__,
13413                         io->io_hdr.io_type,
13414                         io->io_hdr.msg_type,
13415                         io->scsiio.cdb[0],
13416                         io->io_hdr.nexus.initid.id,
13417                         io->io_hdr.nexus.targ_port,
13418                         io->io_hdr.nexus.targ_target.id,
13419                         io->io_hdr.nexus.targ_lun,
13420                         (io->io_hdr.io_type ==
13421                         CTL_IO_TASK) ?
13422                         io->taskio.tag_num :
13423                         io->scsiio.tag_num,
13424                         io->io_hdr.flags,
13425                         io->io_hdr.status);
13426         } else
13427                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13428 #endif
13429
13430         /*
13431          * This is an internal copy of an I/O, and should not go through
13432          * the normal done processing logic.
13433          */
13434         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13435                 return;
13436
13437         /*
13438          * We need to send a msg to the serializing shelf to finish the IO
13439          * as well.  We don't send a finish message to the other shelf if
13440          * this is a task management command.  Task management commands
13441          * aren't serialized in the OOA queue, but rather just executed on
13442          * both shelf controllers for commands that originated on that
13443          * controller.
13444          */
13445         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13446          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13447                 union ctl_ha_msg msg_io;
13448
13449                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13450                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13451                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13452                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13453                 }
13454                 /* continue on to finish IO */
13455         }
13456 #ifdef CTL_IO_DELAY
13457         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13458                 struct ctl_lun *lun;
13459
13460                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13461
13462                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13463         } else {
13464                 struct ctl_lun *lun;
13465
13466                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13467
13468                 if ((lun != NULL)
13469                  && (lun->delay_info.done_delay > 0)) {
13470                         struct callout *callout;
13471
13472                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13473                         callout_init(callout, /*mpsafe*/ 1);
13474                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13475                         callout_reset(callout,
13476                                       lun->delay_info.done_delay * hz,
13477                                       ctl_done_timer_wakeup, io);
13478                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13479                                 lun->delay_info.done_delay = 0;
13480                         return;
13481                 }
13482         }
13483 #endif /* CTL_IO_DELAY */
13484
13485         ctl_enqueue_done(io);
13486 }
13487
13488 int
13489 ctl_isc(struct ctl_scsiio *ctsio)
13490 {
13491         struct ctl_lun *lun;
13492         int retval;
13493
13494         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13495
13496         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13497
13498         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13499
13500         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13501
13502         return (retval);
13503 }
13504
13505
13506 static void
13507 ctl_work_thread(void *arg)
13508 {
13509         struct ctl_thread *thr = (struct ctl_thread *)arg;
13510         struct ctl_softc *softc = thr->ctl_softc;
13511         union ctl_io *io;
13512         int retval;
13513
13514         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13515
13516         for (;;) {
13517                 retval = 0;
13518
13519                 /*
13520                  * We handle the queues in this order:
13521                  * - ISC
13522                  * - done queue (to free up resources, unblock other commands)
13523                  * - RtR queue
13524                  * - incoming queue
13525                  *
13526                  * If those queues are empty, we break out of the loop and
13527                  * go to sleep.
13528                  */
13529                 mtx_lock(&thr->queue_lock);
13530                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13531                 if (io != NULL) {
13532                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13533                         mtx_unlock(&thr->queue_lock);
13534                         ctl_handle_isc(io);
13535                         continue;
13536                 }
13537                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13538                 if (io != NULL) {
13539                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13540                         /* clear any blocked commands, call fe_done */
13541                         mtx_unlock(&thr->queue_lock);
13542                         retval = ctl_process_done(io);
13543                         continue;
13544                 }
13545                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13546                 if (io != NULL) {
13547                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13548                         mtx_unlock(&thr->queue_lock);
13549                         if (io->io_hdr.io_type == CTL_IO_TASK)
13550                                 ctl_run_task(io);
13551                         else
13552                                 ctl_scsiio_precheck(softc, &io->scsiio);
13553                         continue;
13554                 }
13555                 if (!ctl_pause_rtr) {
13556                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13557                         if (io != NULL) {
13558                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13559                                 mtx_unlock(&thr->queue_lock);
13560                                 retval = ctl_scsiio(&io->scsiio);
13561                                 if (retval != CTL_RETVAL_COMPLETE)
13562                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13563                                 continue;
13564                         }
13565                 }
13566
13567                 /* Sleep until we have something to do. */
13568                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13569         }
13570 }
13571
13572 static void
13573 ctl_lun_thread(void *arg)
13574 {
13575         struct ctl_softc *softc = (struct ctl_softc *)arg;
13576         struct ctl_be_lun *be_lun;
13577         int retval;
13578
13579         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13580
13581         for (;;) {
13582                 retval = 0;
13583                 mtx_lock(&softc->ctl_lock);
13584                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13585                 if (be_lun != NULL) {
13586                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13587                         mtx_unlock(&softc->ctl_lock);
13588                         ctl_create_lun(be_lun);
13589                         continue;
13590                 }
13591
13592                 /* Sleep until we have something to do. */
13593                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13594                     PDROP | PRIBIO, "-", 0);
13595         }
13596 }
13597
13598 static void
13599 ctl_thresh_thread(void *arg)
13600 {
13601         struct ctl_softc *softc = (struct ctl_softc *)arg;
13602         struct ctl_lun *lun;
13603         struct ctl_be_lun *be_lun;
13604         struct scsi_da_rw_recovery_page *rwpage;
13605         struct ctl_logical_block_provisioning_page *page;
13606         const char *attr;
13607         uint64_t thres, val;
13608         int i, e;
13609
13610         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13611
13612         for (;;) {
13613                 mtx_lock(&softc->ctl_lock);
13614                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13615                         be_lun = lun->be_lun;
13616                         if ((lun->flags & CTL_LUN_DISABLED) ||
13617                             (lun->flags & CTL_LUN_OFFLINE) ||
13618                             lun->backend->lun_attr == NULL)
13619                                 continue;
13620                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13621                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13622                                 continue;
13623                         e = 0;
13624                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13625                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13626                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13627                                         continue;
13628                                 thres = scsi_4btoul(page->descr[i].count);
13629                                 thres <<= CTL_LBP_EXPONENT;
13630                                 switch (page->descr[i].resource) {
13631                                 case 0x01:
13632                                         attr = "blocksavail";
13633                                         break;
13634                                 case 0x02:
13635                                         attr = "blocksused";
13636                                         break;
13637                                 case 0xf1:
13638                                         attr = "poolblocksavail";
13639                                         break;
13640                                 case 0xf2:
13641                                         attr = "poolblocksused";
13642                                         break;
13643                                 default:
13644                                         continue;
13645                                 }
13646                                 mtx_unlock(&softc->ctl_lock); // XXX
13647                                 val = lun->backend->lun_attr(
13648                                     lun->be_lun->be_lun, attr);
13649                                 mtx_lock(&softc->ctl_lock);
13650                                 if (val == UINT64_MAX)
13651                                         continue;
13652                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13653                                     == SLBPPD_ARMING_INC)
13654                                         e |= (val >= thres);
13655                                 else
13656                                         e |= (val <= thres);
13657                         }
13658                         mtx_lock(&lun->lun_lock);
13659                         if (e) {
13660                                 if (lun->lasttpt == 0 ||
13661                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13662                                         lun->lasttpt = time_uptime;
13663                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13664                                 }
13665                         } else {
13666                                 lun->lasttpt = 0;
13667                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13668                         }
13669                         mtx_unlock(&lun->lun_lock);
13670                 }
13671                 mtx_unlock(&softc->ctl_lock);
13672                 pause("-", CTL_LBP_PERIOD * hz);
13673         }
13674 }
13675
13676 static void
13677 ctl_enqueue_incoming(union ctl_io *io)
13678 {
13679         struct ctl_softc *softc = control_softc;
13680         struct ctl_thread *thr;
13681         u_int idx;
13682
13683         idx = (io->io_hdr.nexus.targ_port * 127 +
13684                io->io_hdr.nexus.initid.id) % worker_threads;
13685         thr = &softc->threads[idx];
13686         mtx_lock(&thr->queue_lock);
13687         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13688         mtx_unlock(&thr->queue_lock);
13689         wakeup(thr);
13690 }
13691
13692 static void
13693 ctl_enqueue_rtr(union ctl_io *io)
13694 {
13695         struct ctl_softc *softc = control_softc;
13696         struct ctl_thread *thr;
13697
13698         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13699         mtx_lock(&thr->queue_lock);
13700         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13701         mtx_unlock(&thr->queue_lock);
13702         wakeup(thr);
13703 }
13704
13705 static void
13706 ctl_enqueue_done(union ctl_io *io)
13707 {
13708         struct ctl_softc *softc = control_softc;
13709         struct ctl_thread *thr;
13710
13711         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13712         mtx_lock(&thr->queue_lock);
13713         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13714         mtx_unlock(&thr->queue_lock);
13715         wakeup(thr);
13716 }
13717
13718 #ifdef notyet
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 /* Initialization and failover */
13733
13734 void
13735 ctl_init_isc_msg(void)
13736 {
13737         printf("CTL: Still calling this thing\n");
13738 }
13739
13740 /*
13741  * Init component
13742  *      Initializes component into configuration defined by bootMode
13743  *      (see hasc-sv.c)
13744  *      returns hasc_Status:
13745  *              OK
13746  *              ERROR - fatal error
13747  */
13748 static ctl_ha_comp_status
13749 ctl_isc_init(struct ctl_ha_component *c)
13750 {
13751         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13752
13753         c->status = ret;
13754         return ret;
13755 }
13756
13757 /* Start component
13758  *      Starts component in state requested. If component starts successfully,
13759  *      it must set its own state to the requestrd state
13760  *      When requested state is HASC_STATE_HA, the component may refine it
13761  *      by adding _SLAVE or _MASTER flags.
13762  *      Currently allowed state transitions are:
13763  *      UNKNOWN->HA             - initial startup
13764  *      UNKNOWN->SINGLE - initial startup when no parter detected
13765  *      HA->SINGLE              - failover
13766  * returns ctl_ha_comp_status:
13767  *              OK      - component successfully started in requested state
13768  *              FAILED  - could not start the requested state, failover may
13769  *                        be possible
13770  *              ERROR   - fatal error detected, no future startup possible
13771  */
13772 static ctl_ha_comp_status
13773 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13774 {
13775         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13776
13777         printf("%s: go\n", __func__);
13778
13779         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13780         if (c->state == CTL_HA_STATE_UNKNOWN ) {
13781                 control_softc->is_single = 0;
13782                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13783                     != CTL_HA_STATUS_SUCCESS) {
13784                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13785                         ret = CTL_HA_COMP_STATUS_ERROR;
13786                 }
13787         } else if (CTL_HA_STATE_IS_HA(c->state)
13788                 && CTL_HA_STATE_IS_SINGLE(state)){
13789                 // HA->SINGLE transition
13790                 ctl_failover();
13791                 control_softc->is_single = 1;
13792         } else {
13793                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
13794                        c->state, state);
13795                 ret = CTL_HA_COMP_STATUS_ERROR;
13796         }
13797         if (CTL_HA_STATE_IS_SINGLE(state))
13798                 control_softc->is_single = 1;
13799
13800         c->state = state;
13801         c->status = ret;
13802         return ret;
13803 }
13804
13805 /*
13806  * Quiesce component
13807  * The component must clear any error conditions (set status to OK) and
13808  * prepare itself to another Start call
13809  * returns ctl_ha_comp_status:
13810  *      OK
13811  *      ERROR
13812  */
13813 static ctl_ha_comp_status
13814 ctl_isc_quiesce(struct ctl_ha_component *c)
13815 {
13816         int ret = CTL_HA_COMP_STATUS_OK;
13817
13818         ctl_pause_rtr = 1;
13819         c->status = ret;
13820         return ret;
13821 }
13822
13823 struct ctl_ha_component ctl_ha_component_ctlisc =
13824 {
13825         .name = "CTL ISC",
13826         .state = CTL_HA_STATE_UNKNOWN,
13827         .init = ctl_isc_init,
13828         .start = ctl_isc_start,
13829         .quiesce = ctl_isc_quiesce
13830 };
13831 #endif
13832
13833 /*
13834  *  vim: ts=8
13835  */