]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/ctl/ctl.c
Remove some dead and duplicate LUN enabling code.
[FreeBSD/FreeBSD.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_frontend_internal.h>
76 #include <cam/ctl/ctl_util.h>
77 #include <cam/ctl/ctl_backend.h>
78 #include <cam/ctl/ctl_ioctl.h>
79 #include <cam/ctl/ctl_ha.h>
80 #include <cam/ctl/ctl_private.h>
81 #include <cam/ctl/ctl_debug.h>
82 #include <cam/ctl/ctl_scsi_all.h>
83 #include <cam/ctl/ctl_error.h>
84
85 struct ctl_softc *control_softc = NULL;
86
87 /*
88  * Size and alignment macros needed for Copan-specific HA hardware.  These
89  * can go away when the HA code is re-written, and uses busdma for any
90  * hardware.
91  */
92 #define CTL_ALIGN_8B(target, source, type)                              \
93         if (((uint32_t)source & 0x7) != 0)                              \
94                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95         else                                                            \
96                 target = (type)source;
97
98 #define CTL_SIZE_8B(target, size)                                       \
99         if ((size & 0x7) != 0)                                          \
100                 target = size + (0x8 - (size & 0x7));                   \
101         else                                                            \
102                 target = size;
103
104 #define CTL_ALIGN_8B_MARGIN     16
105
106 /*
107  * Template mode pages.
108  */
109
110 /*
111  * Note that these are default values only.  The actual values will be
112  * filled in when the user does a mode sense.
113  */
114 const static struct copan_debugconf_subpage debugconf_page_default = {
115         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
116         DBGCNF_SUBPAGE_CODE,            /* subpage */
117         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119         DBGCNF_VERSION,                 /* page_version */
120         {CTL_TIME_IO_DEFAULT_SECS>>8,
121          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
122 };
123
124 const static struct copan_debugconf_subpage debugconf_page_changeable = {
125         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
126         DBGCNF_SUBPAGE_CODE,            /* subpage */
127         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129         0,                              /* page_version */
130         {0xff,0xff},                    /* ctl_time_io_secs */
131 };
132
133 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
134         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137         /*read_retry_count*/0,
138         /*correction_span*/0,
139         /*head_offset_count*/0,
140         /*data_strobe_offset_cnt*/0,
141         /*byte8*/SMS_RWER_LBPERE,
142         /*write_retry_count*/0,
143         /*reserved2*/0,
144         /*recovery_time_limit*/{0, 0},
145 };
146
147 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150         /*byte3*/0,
151         /*read_retry_count*/0,
152         /*correction_span*/0,
153         /*head_offset_count*/0,
154         /*data_strobe_offset_cnt*/0,
155         /*byte8*/0,
156         /*write_retry_count*/0,
157         /*reserved2*/0,
158         /*recovery_time_limit*/{0, 0},
159 };
160
161 const static struct scsi_format_page format_page_default = {
162         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
163         /*page_length*/sizeof(struct scsi_format_page) - 2,
164         /*tracks_per_zone*/ {0, 0},
165         /*alt_sectors_per_zone*/ {0, 0},
166         /*alt_tracks_per_zone*/ {0, 0},
167         /*alt_tracks_per_lun*/ {0, 0},
168         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170         /*bytes_per_sector*/ {0, 0},
171         /*interleave*/ {0, 0},
172         /*track_skew*/ {0, 0},
173         /*cylinder_skew*/ {0, 0},
174         /*flags*/ SFP_HSEC,
175         /*reserved*/ {0, 0, 0}
176 };
177
178 const static struct scsi_format_page format_page_changeable = {
179         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
180         /*page_length*/sizeof(struct scsi_format_page) - 2,
181         /*tracks_per_zone*/ {0, 0},
182         /*alt_sectors_per_zone*/ {0, 0},
183         /*alt_tracks_per_zone*/ {0, 0},
184         /*alt_tracks_per_lun*/ {0, 0},
185         /*sectors_per_track*/ {0, 0},
186         /*bytes_per_sector*/ {0, 0},
187         /*interleave*/ {0, 0},
188         /*track_skew*/ {0, 0},
189         /*cylinder_skew*/ {0, 0},
190         /*flags*/ 0,
191         /*reserved*/ {0, 0, 0}
192 };
193
194 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
195         /*page_code*/SMS_RIGID_DISK_PAGE,
196         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197         /*cylinders*/ {0, 0, 0},
198         /*heads*/ CTL_DEFAULT_HEADS,
199         /*start_write_precomp*/ {0, 0, 0},
200         /*start_reduced_current*/ {0, 0, 0},
201         /*step_rate*/ {0, 0},
202         /*landing_zone_cylinder*/ {0, 0, 0},
203         /*rpl*/ SRDP_RPL_DISABLED,
204         /*rotational_offset*/ 0,
205         /*reserved1*/ 0,
206         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207                            CTL_DEFAULT_ROTATION_RATE & 0xff},
208         /*reserved2*/ {0, 0}
209 };
210
211 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212         /*page_code*/SMS_RIGID_DISK_PAGE,
213         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214         /*cylinders*/ {0, 0, 0},
215         /*heads*/ 0,
216         /*start_write_precomp*/ {0, 0, 0},
217         /*start_reduced_current*/ {0, 0, 0},
218         /*step_rate*/ {0, 0},
219         /*landing_zone_cylinder*/ {0, 0, 0},
220         /*rpl*/ 0,
221         /*rotational_offset*/ 0,
222         /*reserved1*/ 0,
223         /*rotation_rate*/ {0, 0},
224         /*reserved2*/ {0, 0}
225 };
226
227 const static struct scsi_caching_page caching_page_default = {
228         /*page_code*/SMS_CACHING_PAGE,
229         /*page_length*/sizeof(struct scsi_caching_page) - 2,
230         /*flags1*/ SCP_DISC | SCP_WCE,
231         /*ret_priority*/ 0,
232         /*disable_pf_transfer_len*/ {0xff, 0xff},
233         /*min_prefetch*/ {0, 0},
234         /*max_prefetch*/ {0xff, 0xff},
235         /*max_pf_ceiling*/ {0xff, 0xff},
236         /*flags2*/ 0,
237         /*cache_segments*/ 0,
238         /*cache_seg_size*/ {0, 0},
239         /*reserved*/ 0,
240         /*non_cache_seg_size*/ {0, 0, 0}
241 };
242
243 const static struct scsi_caching_page caching_page_changeable = {
244         /*page_code*/SMS_CACHING_PAGE,
245         /*page_length*/sizeof(struct scsi_caching_page) - 2,
246         /*flags1*/ SCP_WCE | SCP_RCD,
247         /*ret_priority*/ 0,
248         /*disable_pf_transfer_len*/ {0, 0},
249         /*min_prefetch*/ {0, 0},
250         /*max_prefetch*/ {0, 0},
251         /*max_pf_ceiling*/ {0, 0},
252         /*flags2*/ 0,
253         /*cache_segments*/ 0,
254         /*cache_seg_size*/ {0, 0},
255         /*reserved*/ 0,
256         /*non_cache_seg_size*/ {0, 0, 0}
257 };
258
259 const static struct scsi_control_page control_page_default = {
260         /*page_code*/SMS_CONTROL_MODE_PAGE,
261         /*page_length*/sizeof(struct scsi_control_page) - 2,
262         /*rlec*/0,
263         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264         /*eca_and_aen*/0,
265         /*flags4*/SCP_TAS,
266         /*aen_holdoff_period*/{0, 0},
267         /*busy_timeout_period*/{0, 0},
268         /*extended_selftest_completion_time*/{0, 0}
269 };
270
271 const static struct scsi_control_page control_page_changeable = {
272         /*page_code*/SMS_CONTROL_MODE_PAGE,
273         /*page_length*/sizeof(struct scsi_control_page) - 2,
274         /*rlec*/SCP_DSENSE,
275         /*queue_flags*/SCP_QUEUE_ALG_MASK,
276         /*eca_and_aen*/SCP_SWP,
277         /*flags4*/0,
278         /*aen_holdoff_period*/{0, 0},
279         /*busy_timeout_period*/{0, 0},
280         /*extended_selftest_completion_time*/{0, 0}
281 };
282
283 const static struct scsi_info_exceptions_page ie_page_default = {
284         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286         /*info_flags*/SIEP_FLAGS_DEXCPT,
287         /*mrie*/0,
288         /*interval_timer*/{0, 0, 0, 0},
289         /*report_count*/{0, 0, 0, 0}
290 };
291
292 const static struct scsi_info_exceptions_page ie_page_changeable = {
293         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295         /*info_flags*/0,
296         /*mrie*/0,
297         /*interval_timer*/{0, 0, 0, 0},
298         /*report_count*/{0, 0, 0, 0}
299 };
300
301 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305         /*subpage_code*/0x02,
306         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307         /*flags*/0,
308         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309         /*descr*/{}},
310         {{/*flags*/0,
311           /*resource*/0x01,
312           /*reserved*/{0, 0},
313           /*count*/{0, 0, 0, 0}},
314          {/*flags*/0,
315           /*resource*/0x02,
316           /*reserved*/{0, 0},
317           /*count*/{0, 0, 0, 0}},
318          {/*flags*/0,
319           /*resource*/0xf1,
320           /*reserved*/{0, 0},
321           /*count*/{0, 0, 0, 0}},
322          {/*flags*/0,
323           /*resource*/0xf2,
324           /*reserved*/{0, 0},
325           /*count*/{0, 0, 0, 0}}
326         }
327 };
328
329 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331         /*subpage_code*/0x02,
332         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333         /*flags*/0,
334         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335         /*descr*/{}},
336         {{/*flags*/0,
337           /*resource*/0,
338           /*reserved*/{0, 0},
339           /*count*/{0, 0, 0, 0}},
340          {/*flags*/0,
341           /*resource*/0,
342           /*reserved*/{0, 0},
343           /*count*/{0, 0, 0, 0}},
344          {/*flags*/0,
345           /*resource*/0,
346           /*reserved*/{0, 0},
347           /*count*/{0, 0, 0, 0}},
348          {/*flags*/0,
349           /*resource*/0,
350           /*reserved*/{0, 0},
351           /*count*/{0, 0, 0, 0}}
352         }
353 };
354
355 /*
356  * XXX KDM move these into the softc.
357  */
358 static int rcv_sync_msg;
359 static uint8_t ctl_pause_rtr;
360
361 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362 static int worker_threads = -1;
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 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
367     &ctl_debug, 0, "Enabled debug flags");
368
369 /*
370  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
371  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
372  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
373  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
374  */
375 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
376
377 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
378                                   int param);
379 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
380 static int ctl_init(void);
381 void ctl_shutdown(void);
382 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
383 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
384 static void ctl_ioctl_online(void *arg);
385 static void ctl_ioctl_offline(void *arg);
386 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
387 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
388 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
389 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
390 static int ctl_ioctl_submit_wait(union ctl_io *io);
391 static void ctl_ioctl_datamove(union ctl_io *io);
392 static void ctl_ioctl_done(union ctl_io *io);
393 static void ctl_ioctl_hard_startstop_callback(void *arg,
394                                               struct cfi_metatask *metatask);
395 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
396 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
397                               struct ctl_ooa *ooa_hdr,
398                               struct ctl_ooa_entry *kern_entries);
399 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
400                      struct thread *td);
401 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
402                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
403 static int ctl_free_lun(struct ctl_lun *lun);
404 static void ctl_create_lun(struct ctl_be_lun *be_lun);
405 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
406 /**
407 static void ctl_failover_change_pages(struct ctl_softc *softc,
408                                       struct ctl_scsiio *ctsio, int master);
409 **/
410
411 static int ctl_do_mode_select(union ctl_io *io);
412 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
413                            uint64_t res_key, uint64_t sa_res_key,
414                            uint8_t type, uint32_t residx,
415                            struct ctl_scsiio *ctsio,
416                            struct scsi_per_res_out *cdb,
417                            struct scsi_per_res_out_parms* param);
418 static void ctl_pro_preempt_other(struct ctl_lun *lun,
419                                   union ctl_ha_msg *msg);
420 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
421 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
422 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
423 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
424 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
425 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
426 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
427                                          int alloc_len);
428 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
429                                          int alloc_len);
430 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
431 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
432 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
433 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
434 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
435 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
436     bool seq);
437 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
438 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
439     union ctl_io *pending_io, union ctl_io *ooa_io);
440 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
441                                 union ctl_io *starting_io);
442 static int ctl_check_blocked(struct ctl_lun *lun);
443 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
444                                 const struct ctl_cmd_entry *entry,
445                                 struct ctl_scsiio *ctsio);
446 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
447 static void ctl_failover(void);
448 static void ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
449                          ctl_ua_type ua_type);
450 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
451                                struct ctl_scsiio *ctsio);
452 static int ctl_scsiio(struct ctl_scsiio *ctsio);
453
454 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
455 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
456                             ctl_ua_type ua_type);
457 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
458                          ctl_ua_type ua_type);
459 static int ctl_abort_task(union ctl_io *io);
460 static int ctl_abort_task_set(union ctl_io *io);
461 static int ctl_i_t_nexus_reset(union ctl_io *io);
462 static void ctl_run_task(union ctl_io *io);
463 #ifdef CTL_IO_DELAY
464 static void ctl_datamove_timer_wakeup(void *arg);
465 static void ctl_done_timer_wakeup(void *arg);
466 #endif /* CTL_IO_DELAY */
467
468 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
469 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
470 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
471 static void ctl_datamove_remote_write(union ctl_io *io);
472 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
473 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
474 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
475 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
476                                     ctl_ha_dt_cb callback);
477 static void ctl_datamove_remote_read(union ctl_io *io);
478 static void ctl_datamove_remote(union ctl_io *io);
479 static int ctl_process_done(union ctl_io *io);
480 static void ctl_lun_thread(void *arg);
481 static void ctl_thresh_thread(void *arg);
482 static void ctl_work_thread(void *arg);
483 static void ctl_enqueue_incoming(union ctl_io *io);
484 static void ctl_enqueue_rtr(union ctl_io *io);
485 static void ctl_enqueue_done(union ctl_io *io);
486 static void ctl_enqueue_isc(union ctl_io *io);
487 static const struct ctl_cmd_entry *
488     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
489 static const struct ctl_cmd_entry *
490     ctl_validate_command(struct ctl_scsiio *ctsio);
491 static int ctl_cmd_applicable(uint8_t lun_type,
492     const struct ctl_cmd_entry *entry);
493
494 /*
495  * Load the serialization table.  This isn't very pretty, but is probably
496  * the easiest way to do it.
497  */
498 #include "ctl_ser_table.c"
499
500 /*
501  * We only need to define open, close and ioctl routines for this driver.
502  */
503 static struct cdevsw ctl_cdevsw = {
504         .d_version =    D_VERSION,
505         .d_flags =      0,
506         .d_open =       ctl_open,
507         .d_close =      ctl_close,
508         .d_ioctl =      ctl_ioctl,
509         .d_name =       "ctl",
510 };
511
512
513 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
514 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
515
516 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
517
518 static moduledata_t ctl_moduledata = {
519         "ctl",
520         ctl_module_event_handler,
521         NULL
522 };
523
524 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
525 MODULE_VERSION(ctl, 1);
526
527 static struct ctl_frontend ioctl_frontend =
528 {
529         .name = "ioctl",
530 };
531
532 static void
533 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
534                             union ctl_ha_msg *msg_info)
535 {
536         struct ctl_scsiio *ctsio;
537
538         if (msg_info->hdr.original_sc == NULL) {
539                 printf("%s: original_sc == NULL!\n", __func__);
540                 /* XXX KDM now what? */
541                 return;
542         }
543
544         ctsio = &msg_info->hdr.original_sc->scsiio;
545         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
546         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
547         ctsio->io_hdr.status = msg_info->hdr.status;
548         ctsio->scsi_status = msg_info->scsi.scsi_status;
549         ctsio->sense_len = msg_info->scsi.sense_len;
550         ctsio->sense_residual = msg_info->scsi.sense_residual;
551         ctsio->residual = msg_info->scsi.residual;
552         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
553                sizeof(ctsio->sense_data));
554         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
555                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
556         ctl_enqueue_isc((union ctl_io *)ctsio);
557 }
558
559 static void
560 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
561                                 union ctl_ha_msg *msg_info)
562 {
563         struct ctl_scsiio *ctsio;
564
565         if (msg_info->hdr.serializing_sc == NULL) {
566                 printf("%s: serializing_sc == NULL!\n", __func__);
567                 /* XXX KDM now what? */
568                 return;
569         }
570
571         ctsio = &msg_info->hdr.serializing_sc->scsiio;
572 #if 0
573         /*
574          * Attempt to catch the situation where an I/O has
575          * been freed, and we're using it again.
576          */
577         if (ctsio->io_hdr.io_type == 0xff) {
578                 union ctl_io *tmp_io;
579                 tmp_io = (union ctl_io *)ctsio;
580                 printf("%s: %p use after free!\n", __func__,
581                        ctsio);
582                 printf("%s: type %d msg %d cdb %x iptl: "
583                        "%d:%d:%d:%d tag 0x%04x "
584                        "flag %#x status %x\n",
585                         __func__,
586                         tmp_io->io_hdr.io_type,
587                         tmp_io->io_hdr.msg_type,
588                         tmp_io->scsiio.cdb[0],
589                         tmp_io->io_hdr.nexus.initid.id,
590                         tmp_io->io_hdr.nexus.targ_port,
591                         tmp_io->io_hdr.nexus.targ_target.id,
592                         tmp_io->io_hdr.nexus.targ_lun,
593                         (tmp_io->io_hdr.io_type ==
594                         CTL_IO_TASK) ?
595                         tmp_io->taskio.tag_num :
596                         tmp_io->scsiio.tag_num,
597                         tmp_io->io_hdr.flags,
598                         tmp_io->io_hdr.status);
599         }
600 #endif
601         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
602         ctl_enqueue_isc((union ctl_io *)ctsio);
603 }
604
605 /*
606  * ISC (Inter Shelf Communication) event handler.  Events from the HA
607  * subsystem come in here.
608  */
609 static void
610 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
611 {
612         struct ctl_softc *softc;
613         union ctl_io *io;
614         struct ctl_prio *presio;
615         ctl_ha_status isc_status;
616
617         softc = control_softc;
618         io = NULL;
619
620
621 #if 0
622         printf("CTL: Isc Msg event %d\n", event);
623 #endif
624         if (event == CTL_HA_EVT_MSG_RECV) {
625                 union ctl_ha_msg msg_info;
626
627                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
628                                              sizeof(msg_info), /*wait*/ 0);
629 #if 0
630                 printf("CTL: msg_type %d\n", msg_info.msg_type);
631 #endif
632                 if (isc_status != 0) {
633                         printf("Error receiving message, status = %d\n",
634                                isc_status);
635                         return;
636                 }
637
638                 switch (msg_info.hdr.msg_type) {
639                 case CTL_MSG_SERIALIZE:
640 #if 0
641                         printf("Serialize\n");
642 #endif
643                         io = ctl_alloc_io_nowait(softc->othersc_pool);
644                         if (io == NULL) {
645                                 printf("ctl_isc_event_handler: can't allocate "
646                                        "ctl_io!\n");
647                                 /* Bad Juju */
648                                 /* Need to set busy and send msg back */
649                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
650                                 msg_info.hdr.status = CTL_SCSI_ERROR;
651                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
652                                 msg_info.scsi.sense_len = 0;
653                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
654                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
655                                 }
656                                 goto bailout;
657                         }
658                         ctl_zero_io(io);
659                         // populate ctsio from msg_info
660                         io->io_hdr.io_type = CTL_IO_SCSI;
661                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
662                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
663 #if 0
664                         printf("pOrig %x\n", (int)msg_info.original_sc);
665 #endif
666                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
667                                             CTL_FLAG_IO_ACTIVE;
668                         /*
669                          * If we're in serialization-only mode, we don't
670                          * want to go through full done processing.  Thus
671                          * the COPY flag.
672                          *
673                          * XXX KDM add another flag that is more specific.
674                          */
675                         if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
676                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
677                         io->io_hdr.nexus = msg_info.hdr.nexus;
678 #if 0
679                         printf("targ %d, port %d, iid %d, lun %d\n",
680                                io->io_hdr.nexus.targ_target.id,
681                                io->io_hdr.nexus.targ_port,
682                                io->io_hdr.nexus.initid.id,
683                                io->io_hdr.nexus.targ_lun);
684 #endif
685                         io->scsiio.tag_num = msg_info.scsi.tag_num;
686                         io->scsiio.tag_type = msg_info.scsi.tag_type;
687                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
688                                CTL_MAX_CDBLEN);
689                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
690                                 const struct ctl_cmd_entry *entry;
691
692                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
693                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
694                                 io->io_hdr.flags |=
695                                         entry->flags & CTL_FLAG_DATA_MASK;
696                         }
697                         ctl_enqueue_isc(io);
698                         break;
699
700                 /* Performed on the Originating SC, XFER mode only */
701                 case CTL_MSG_DATAMOVE: {
702                         struct ctl_sg_entry *sgl;
703                         int i, j;
704
705                         io = msg_info.hdr.original_sc;
706                         if (io == NULL) {
707                                 printf("%s: original_sc == NULL!\n", __func__);
708                                 /* XXX KDM do something here */
709                                 break;
710                         }
711                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
712                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
713                         /*
714                          * Keep track of this, we need to send it back over
715                          * when the datamove is complete.
716                          */
717                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
718
719                         if (msg_info.dt.sg_sequence == 0) {
720                                 /*
721                                  * XXX KDM we use the preallocated S/G list
722                                  * here, but we'll need to change this to
723                                  * dynamic allocation if we need larger S/G
724                                  * lists.
725                                  */
726                                 if (msg_info.dt.kern_sg_entries >
727                                     sizeof(io->io_hdr.remote_sglist) /
728                                     sizeof(io->io_hdr.remote_sglist[0])) {
729                                         printf("%s: number of S/G entries "
730                                             "needed %u > allocated num %zd\n",
731                                             __func__,
732                                             msg_info.dt.kern_sg_entries,
733                                             sizeof(io->io_hdr.remote_sglist)/
734                                             sizeof(io->io_hdr.remote_sglist[0]));
735                                 
736                                         /*
737                                          * XXX KDM send a message back to
738                                          * the other side to shut down the
739                                          * DMA.  The error will come back
740                                          * through via the normal channel.
741                                          */
742                                         break;
743                                 }
744                                 sgl = io->io_hdr.remote_sglist;
745                                 memset(sgl, 0,
746                                        sizeof(io->io_hdr.remote_sglist));
747
748                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
749
750                                 io->scsiio.kern_sg_entries =
751                                         msg_info.dt.kern_sg_entries;
752                                 io->scsiio.rem_sg_entries =
753                                         msg_info.dt.kern_sg_entries;
754                                 io->scsiio.kern_data_len =
755                                         msg_info.dt.kern_data_len;
756                                 io->scsiio.kern_total_len =
757                                         msg_info.dt.kern_total_len;
758                                 io->scsiio.kern_data_resid =
759                                         msg_info.dt.kern_data_resid;
760                                 io->scsiio.kern_rel_offset =
761                                         msg_info.dt.kern_rel_offset;
762                                 /*
763                                  * Clear out per-DMA flags.
764                                  */
765                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
766                                 /*
767                                  * Add per-DMA flags that are set for this
768                                  * particular DMA request.
769                                  */
770                                 io->io_hdr.flags |= msg_info.dt.flags &
771                                                     CTL_FLAG_RDMA_MASK;
772                         } else
773                                 sgl = (struct ctl_sg_entry *)
774                                         io->scsiio.kern_data_ptr;
775
776                         for (i = msg_info.dt.sent_sg_entries, j = 0;
777                              i < (msg_info.dt.sent_sg_entries +
778                              msg_info.dt.cur_sg_entries); i++, j++) {
779                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
780                                 sgl[i].len = msg_info.dt.sg_list[j].len;
781
782 #if 0
783                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
784                                        __func__,
785                                        msg_info.dt.sg_list[j].addr,
786                                        msg_info.dt.sg_list[j].len,
787                                        sgl[i].addr, sgl[i].len, j, i);
788 #endif
789                         }
790 #if 0
791                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
792                                msg_info.dt.sg_list,
793                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
794 #endif
795
796                         /*
797                          * If this is the last piece of the I/O, we've got
798                          * the full S/G list.  Queue processing in the thread.
799                          * Otherwise wait for the next piece.
800                          */
801                         if (msg_info.dt.sg_last != 0)
802                                 ctl_enqueue_isc(io);
803                         break;
804                 }
805                 /* Performed on the Serializing (primary) SC, XFER mode only */
806                 case CTL_MSG_DATAMOVE_DONE: {
807                         if (msg_info.hdr.serializing_sc == NULL) {
808                                 printf("%s: serializing_sc == NULL!\n",
809                                        __func__);
810                                 /* XXX KDM now what? */
811                                 break;
812                         }
813                         /*
814                          * We grab the sense information here in case
815                          * there was a failure, so we can return status
816                          * back to the initiator.
817                          */
818                         io = msg_info.hdr.serializing_sc;
819                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
820                         io->io_hdr.status = msg_info.hdr.status;
821                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
822                         io->scsiio.sense_len = msg_info.scsi.sense_len;
823                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
824                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
825                         io->scsiio.residual = msg_info.scsi.residual;
826                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
827                                sizeof(io->scsiio.sense_data));
828                         ctl_enqueue_isc(io);
829                         break;
830                 }
831
832                 /* Preformed on Originating SC, SER_ONLY mode */
833                 case CTL_MSG_R2R:
834                         io = msg_info.hdr.original_sc;
835                         if (io == NULL) {
836                                 printf("%s: Major Bummer\n", __func__);
837                                 return;
838                         } else {
839 #if 0
840                                 printf("pOrig %x\n",(int) ctsio);
841 #endif
842                         }
843                         io->io_hdr.msg_type = CTL_MSG_R2R;
844                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
845                         ctl_enqueue_isc(io);
846                         break;
847
848                 /*
849                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
850                  * mode.
851                  * Performed on the Originating (i.e. secondary) SC in XFER
852                  * mode
853                  */
854                 case CTL_MSG_FINISH_IO:
855                         if (softc->ha_mode == CTL_HA_MODE_XFER)
856                                 ctl_isc_handler_finish_xfer(softc,
857                                                             &msg_info);
858                         else
859                                 ctl_isc_handler_finish_ser_only(softc,
860                                                                 &msg_info);
861                         break;
862
863                 /* Preformed on Originating SC */
864                 case CTL_MSG_BAD_JUJU:
865                         io = msg_info.hdr.original_sc;
866                         if (io == NULL) {
867                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
868                                        __func__);
869                                 break;
870                         }
871                         ctl_copy_sense_data(&msg_info, io);
872                         /*
873                          * IO should have already been cleaned up on other
874                          * SC so clear this flag so we won't send a message
875                          * back to finish the IO there.
876                          */
877                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
878                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
879
880                         /* io = msg_info.hdr.serializing_sc; */
881                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
882                         ctl_enqueue_isc(io);
883                         break;
884
885                 /* Handle resets sent from the other side */
886                 case CTL_MSG_MANAGE_TASKS: {
887                         struct ctl_taskio *taskio;
888                         taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
889                             softc->othersc_pool);
890                         if (taskio == NULL) {
891                                 printf("ctl_isc_event_handler: can't allocate "
892                                        "ctl_io!\n");
893                                 /* Bad Juju */
894                                 /* should I just call the proper reset func
895                                    here??? */
896                                 goto bailout;
897                         }
898                         ctl_zero_io((union ctl_io *)taskio);
899                         taskio->io_hdr.io_type = CTL_IO_TASK;
900                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
901                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
902                         taskio->task_action = msg_info.task.task_action;
903                         taskio->tag_num = msg_info.task.tag_num;
904                         taskio->tag_type = msg_info.task.tag_type;
905 #ifdef CTL_TIME_IO
906                         taskio->io_hdr.start_time = time_uptime;
907                         getbintime(&taskio->io_hdr.start_bt);
908 #if 0
909                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
910 #endif
911 #endif /* CTL_TIME_IO */
912                         ctl_run_task((union ctl_io *)taskio);
913                         break;
914                 }
915                 /* Persistent Reserve action which needs attention */
916                 case CTL_MSG_PERS_ACTION:
917                         presio = (struct ctl_prio *)ctl_alloc_io_nowait(
918                             softc->othersc_pool);
919                         if (presio == NULL) {
920                                 printf("ctl_isc_event_handler: can't allocate "
921                                        "ctl_io!\n");
922                                 /* Bad Juju */
923                                 /* Need to set busy and send msg back */
924                                 goto bailout;
925                         }
926                         ctl_zero_io((union ctl_io *)presio);
927                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
928                         presio->pr_msg = msg_info.pr;
929                         ctl_enqueue_isc((union ctl_io *)presio);
930                         break;
931                 case CTL_MSG_SYNC_FE:
932                         rcv_sync_msg = 1;
933                         break;
934                 default:
935                         printf("How did I get here?\n");
936                 }
937         } else if (event == CTL_HA_EVT_MSG_SENT) {
938                 if (param != CTL_HA_STATUS_SUCCESS) {
939                         printf("Bad status from ctl_ha_msg_send status %d\n",
940                                param);
941                 }
942                 return;
943         } else if (event == CTL_HA_EVT_DISCONNECT) {
944                 printf("CTL: Got a disconnect from Isc\n");
945                 return;
946         } else {
947                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
948                 return;
949         }
950
951 bailout:
952         return;
953 }
954
955 static void
956 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
957 {
958         struct scsi_sense_data *sense;
959
960         sense = &dest->scsiio.sense_data;
961         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
962         dest->scsiio.scsi_status = src->scsi.scsi_status;
963         dest->scsiio.sense_len = src->scsi.sense_len;
964         dest->io_hdr.status = src->hdr.status;
965 }
966
967 static void
968 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
969 {
970         ctl_ua_type *pu;
971
972         mtx_assert(&lun->lun_lock, MA_OWNED);
973         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
974         if (pu == NULL)
975                 return;
976         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
977 }
978
979 static void
980 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
981 {
982         int i, j;
983
984         mtx_assert(&lun->lun_lock, MA_OWNED);
985         for (i = 0; i < CTL_MAX_PORTS; i++) {
986                 if (lun->pending_ua[i] == NULL)
987                         continue;
988                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
989                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
990                                 continue;
991                         lun->pending_ua[i][j] |= ua;
992                 }
993         }
994 }
995
996 static void
997 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
998 {
999         ctl_ua_type *pu;
1000
1001         mtx_assert(&lun->lun_lock, MA_OWNED);
1002         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1003         if (pu == NULL)
1004                 return;
1005         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1006 }
1007
1008 static void
1009 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1010 {
1011         int i, j;
1012
1013         mtx_assert(&lun->lun_lock, MA_OWNED);
1014         for (i = 0; i < CTL_MAX_PORTS; i++) {
1015                 if (lun->pending_ua[i] == NULL)
1016                         continue;
1017                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1018                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1019                                 continue;
1020                         lun->pending_ua[i][j] &= ~ua;
1021                 }
1022         }
1023 }
1024
1025 static int
1026 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1027 {
1028         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1029         struct ctl_lun *lun;
1030         int error, value;
1031
1032         if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1033                 value = 0;
1034         else
1035                 value = 1;
1036
1037         error = sysctl_handle_int(oidp, &value, 0, req);
1038         if ((error != 0) || (req->newptr == NULL))
1039                 return (error);
1040
1041         mtx_lock(&softc->ctl_lock);
1042         if (value == 0)
1043                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1044         else
1045                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1046         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1047                 mtx_lock(&lun->lun_lock);
1048                 ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1049                 mtx_unlock(&lun->lun_lock);
1050         }
1051         mtx_unlock(&softc->ctl_lock);
1052         return (0);
1053 }
1054
1055 static int
1056 ctl_init(void)
1057 {
1058         struct ctl_softc *softc;
1059         void *other_pool;
1060         struct ctl_port *port;
1061         int i, error, retval;
1062         //int isc_retval;
1063
1064         retval = 0;
1065         ctl_pause_rtr = 0;
1066         rcv_sync_msg = 0;
1067
1068         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1069                                M_WAITOK | M_ZERO);
1070         softc = control_softc;
1071
1072         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1073                               "cam/ctl");
1074
1075         softc->dev->si_drv1 = softc;
1076
1077         /*
1078          * By default, return a "bad LUN" peripheral qualifier for unknown
1079          * LUNs.  The user can override this default using the tunable or
1080          * sysctl.  See the comment in ctl_inquiry_std() for more details.
1081          */
1082         softc->inquiry_pq_no_lun = 1;
1083         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1084                           &softc->inquiry_pq_no_lun);
1085         sysctl_ctx_init(&softc->sysctl_ctx);
1086         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1087                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1088                 CTLFLAG_RD, 0, "CAM Target Layer");
1089
1090         if (softc->sysctl_tree == NULL) {
1091                 printf("%s: unable to allocate sysctl tree\n", __func__);
1092                 destroy_dev(softc->dev);
1093                 free(control_softc, M_DEVBUF);
1094                 control_softc = NULL;
1095                 return (ENOMEM);
1096         }
1097
1098         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1099                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1100                        "inquiry_pq_no_lun", CTLFLAG_RW,
1101                        &softc->inquiry_pq_no_lun, 0,
1102                        "Report no lun possible for invalid LUNs");
1103
1104         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1105         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1106             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1107         softc->open_count = 0;
1108
1109         /*
1110          * Default to actually sending a SYNCHRONIZE CACHE command down to
1111          * the drive.
1112          */
1113         softc->flags = CTL_FLAG_REAL_SYNC;
1114
1115         /*
1116          * In Copan's HA scheme, the "master" and "slave" roles are
1117          * figured out through the slot the controller is in.  Although it
1118          * is an active/active system, someone has to be in charge.
1119          */
1120         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1121             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1122             "HA head ID (0 - no HA)");
1123         if (softc->ha_id == 0) {
1124                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1125                 softc->is_single = 1;
1126                 softc->port_offset = 0;
1127         } else
1128                 softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1129         softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1130
1131         /*
1132          * XXX KDM need to figure out where we want to get our target ID
1133          * and WWID.  Is it different on each port?
1134          */
1135         softc->target.id = 0;
1136         softc->target.wwid[0] = 0x12345678;
1137         softc->target.wwid[1] = 0x87654321;
1138         STAILQ_INIT(&softc->lun_list);
1139         STAILQ_INIT(&softc->pending_lun_queue);
1140         STAILQ_INIT(&softc->fe_list);
1141         STAILQ_INIT(&softc->port_list);
1142         STAILQ_INIT(&softc->be_list);
1143         ctl_tpc_init(softc);
1144
1145         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1146                             &other_pool) != 0)
1147         {
1148                 printf("ctl: can't allocate %d entry other SC pool, "
1149                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1150                 return (ENOMEM);
1151         }
1152         softc->othersc_pool = other_pool;
1153
1154         if (worker_threads <= 0)
1155                 worker_threads = max(1, mp_ncpus / 4);
1156         if (worker_threads > CTL_MAX_THREADS)
1157                 worker_threads = CTL_MAX_THREADS;
1158
1159         for (i = 0; i < worker_threads; i++) {
1160                 struct ctl_thread *thr = &softc->threads[i];
1161
1162                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1163                 thr->ctl_softc = softc;
1164                 STAILQ_INIT(&thr->incoming_queue);
1165                 STAILQ_INIT(&thr->rtr_queue);
1166                 STAILQ_INIT(&thr->done_queue);
1167                 STAILQ_INIT(&thr->isc_queue);
1168
1169                 error = kproc_kthread_add(ctl_work_thread, thr,
1170                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1171                 if (error != 0) {
1172                         printf("error creating CTL work thread!\n");
1173                         ctl_pool_free(other_pool);
1174                         return (error);
1175                 }
1176         }
1177         error = kproc_kthread_add(ctl_lun_thread, softc,
1178             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1179         if (error != 0) {
1180                 printf("error creating CTL lun thread!\n");
1181                 ctl_pool_free(other_pool);
1182                 return (error);
1183         }
1184         error = kproc_kthread_add(ctl_thresh_thread, softc,
1185             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1186         if (error != 0) {
1187                 printf("error creating CTL threshold thread!\n");
1188                 ctl_pool_free(other_pool);
1189                 return (error);
1190         }
1191         if (bootverbose)
1192                 printf("ctl: CAM Target Layer loaded\n");
1193
1194         /*
1195          * Initialize the ioctl front end.
1196          */
1197         ctl_frontend_register(&ioctl_frontend);
1198         port = &softc->ioctl_info.port;
1199         port->frontend = &ioctl_frontend;
1200         sprintf(softc->ioctl_info.port_name, "ioctl");
1201         port->port_type = CTL_PORT_IOCTL;
1202         port->num_requested_ctl_io = 100;
1203         port->port_name = softc->ioctl_info.port_name;
1204         port->port_online = ctl_ioctl_online;
1205         port->port_offline = ctl_ioctl_offline;
1206         port->onoff_arg = &softc->ioctl_info;
1207         port->lun_enable = ctl_ioctl_lun_enable;
1208         port->lun_disable = ctl_ioctl_lun_disable;
1209         port->targ_lun_arg = &softc->ioctl_info;
1210         port->fe_datamove = ctl_ioctl_datamove;
1211         port->fe_done = ctl_ioctl_done;
1212         port->max_targets = 15;
1213         port->max_target_id = 15;
1214
1215         if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1216                 printf("ctl: ioctl front end registration failed, will "
1217                        "continue anyway\n");
1218         }
1219
1220         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1221             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1222             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1223
1224 #ifdef CTL_IO_DELAY
1225         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1226                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1227                        sizeof(struct callout), CTL_TIMER_BYTES);
1228                 return (EINVAL);
1229         }
1230 #endif /* CTL_IO_DELAY */
1231
1232         return (0);
1233 }
1234
1235 void
1236 ctl_shutdown(void)
1237 {
1238         struct ctl_softc *softc;
1239         struct ctl_lun *lun, *next_lun;
1240
1241         softc = (struct ctl_softc *)control_softc;
1242
1243         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1244                 printf("ctl: ioctl front end deregistration failed\n");
1245
1246         mtx_lock(&softc->ctl_lock);
1247
1248         /*
1249          * Free up each LUN.
1250          */
1251         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1252                 next_lun = STAILQ_NEXT(lun, links);
1253                 ctl_free_lun(lun);
1254         }
1255
1256         mtx_unlock(&softc->ctl_lock);
1257
1258         ctl_frontend_deregister(&ioctl_frontend);
1259
1260 #if 0
1261         ctl_shutdown_thread(softc->work_thread);
1262         mtx_destroy(&softc->queue_lock);
1263 #endif
1264
1265         ctl_tpc_shutdown(softc);
1266         uma_zdestroy(softc->io_zone);
1267         mtx_destroy(&softc->ctl_lock);
1268
1269         destroy_dev(softc->dev);
1270
1271         sysctl_ctx_free(&softc->sysctl_ctx);
1272
1273         free(control_softc, M_DEVBUF);
1274         control_softc = NULL;
1275
1276         if (bootverbose)
1277                 printf("ctl: CAM Target Layer unloaded\n");
1278 }
1279
1280 static int
1281 ctl_module_event_handler(module_t mod, int what, void *arg)
1282 {
1283
1284         switch (what) {
1285         case MOD_LOAD:
1286                 return (ctl_init());
1287         case MOD_UNLOAD:
1288                 return (EBUSY);
1289         default:
1290                 return (EOPNOTSUPP);
1291         }
1292 }
1293
1294 /*
1295  * XXX KDM should we do some access checks here?  Bump a reference count to
1296  * prevent a CTL module from being unloaded while someone has it open?
1297  */
1298 static int
1299 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1300 {
1301         return (0);
1302 }
1303
1304 static int
1305 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1306 {
1307         return (0);
1308 }
1309
1310 int
1311 ctl_port_enable(ctl_port_type port_type)
1312 {
1313         struct ctl_softc *softc = control_softc;
1314         struct ctl_port *port;
1315
1316         if (softc->is_single == 0) {
1317                 union ctl_ha_msg msg_info;
1318                 int isc_retval;
1319
1320 #if 0
1321                 printf("%s: HA mode, synchronizing frontend enable\n",
1322                         __func__);
1323 #endif
1324                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1325                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1326                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1327                         printf("Sync msg send error retval %d\n", isc_retval);
1328                 }
1329                 if (!rcv_sync_msg) {
1330                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1331                                 sizeof(msg_info), 1);
1332                 }
1333 #if 0
1334                 printf("CTL:Frontend Enable\n");
1335         } else {
1336                 printf("%s: single mode, skipping frontend synchronization\n",
1337                         __func__);
1338 #endif
1339         }
1340
1341         STAILQ_FOREACH(port, &softc->port_list, links) {
1342                 if (port_type & port->port_type)
1343                 {
1344 #if 0
1345                         printf("port %d\n", port->targ_port);
1346 #endif
1347                         ctl_port_online(port);
1348                 }
1349         }
1350
1351         return (0);
1352 }
1353
1354 int
1355 ctl_port_disable(ctl_port_type port_type)
1356 {
1357         struct ctl_softc *softc;
1358         struct ctl_port *port;
1359
1360         softc = control_softc;
1361
1362         STAILQ_FOREACH(port, &softc->port_list, links) {
1363                 if (port_type & port->port_type)
1364                         ctl_port_offline(port);
1365         }
1366
1367         return (0);
1368 }
1369
1370 /*
1371  * Returns 0 for success, 1 for failure.
1372  * Currently the only failure mode is if there aren't enough entries
1373  * allocated.  So, in case of a failure, look at num_entries_dropped,
1374  * reallocate and try again.
1375  */
1376 int
1377 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1378               int *num_entries_filled, int *num_entries_dropped,
1379               ctl_port_type port_type, int no_virtual)
1380 {
1381         struct ctl_softc *softc;
1382         struct ctl_port *port;
1383         int entries_dropped, entries_filled;
1384         int retval;
1385         int i;
1386
1387         softc = control_softc;
1388
1389         retval = 0;
1390         entries_filled = 0;
1391         entries_dropped = 0;
1392
1393         i = 0;
1394         mtx_lock(&softc->ctl_lock);
1395         STAILQ_FOREACH(port, &softc->port_list, links) {
1396                 struct ctl_port_entry *entry;
1397
1398                 if ((port->port_type & port_type) == 0)
1399                         continue;
1400
1401                 if ((no_virtual != 0)
1402                  && (port->virtual_port != 0))
1403                         continue;
1404
1405                 if (entries_filled >= num_entries_alloced) {
1406                         entries_dropped++;
1407                         continue;
1408                 }
1409                 entry = &entries[i];
1410
1411                 entry->port_type = port->port_type;
1412                 strlcpy(entry->port_name, port->port_name,
1413                         sizeof(entry->port_name));
1414                 entry->physical_port = port->physical_port;
1415                 entry->virtual_port = port->virtual_port;
1416                 entry->wwnn = port->wwnn;
1417                 entry->wwpn = port->wwpn;
1418
1419                 i++;
1420                 entries_filled++;
1421         }
1422
1423         mtx_unlock(&softc->ctl_lock);
1424
1425         if (entries_dropped > 0)
1426                 retval = 1;
1427
1428         *num_entries_dropped = entries_dropped;
1429         *num_entries_filled = entries_filled;
1430
1431         return (retval);
1432 }
1433
1434 static void
1435 ctl_ioctl_online(void *arg)
1436 {
1437         struct ctl_ioctl_info *ioctl_info;
1438
1439         ioctl_info = (struct ctl_ioctl_info *)arg;
1440
1441         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1442 }
1443
1444 static void
1445 ctl_ioctl_offline(void *arg)
1446 {
1447         struct ctl_ioctl_info *ioctl_info;
1448
1449         ioctl_info = (struct ctl_ioctl_info *)arg;
1450
1451         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1452 }
1453
1454 /*
1455  * Remove an initiator by port number and initiator ID.
1456  * Returns 0 for success, -1 for failure.
1457  */
1458 int
1459 ctl_remove_initiator(struct ctl_port *port, int iid)
1460 {
1461         struct ctl_softc *softc = control_softc;
1462
1463         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1464
1465         if (iid > CTL_MAX_INIT_PER_PORT) {
1466                 printf("%s: initiator ID %u > maximun %u!\n",
1467                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1468                 return (-1);
1469         }
1470
1471         mtx_lock(&softc->ctl_lock);
1472         port->wwpn_iid[iid].in_use--;
1473         port->wwpn_iid[iid].last_use = time_uptime;
1474         mtx_unlock(&softc->ctl_lock);
1475
1476         return (0);
1477 }
1478
1479 /*
1480  * Add an initiator to the initiator map.
1481  * Returns iid for success, < 0 for failure.
1482  */
1483 int
1484 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1485 {
1486         struct ctl_softc *softc = control_softc;
1487         time_t best_time;
1488         int i, best;
1489
1490         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1491
1492         if (iid >= CTL_MAX_INIT_PER_PORT) {
1493                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1494                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1495                 free(name, M_CTL);
1496                 return (-1);
1497         }
1498
1499         mtx_lock(&softc->ctl_lock);
1500
1501         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1502                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1503                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1504                                 iid = i;
1505                                 break;
1506                         }
1507                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1508                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1509                                 iid = i;
1510                                 break;
1511                         }
1512                 }
1513         }
1514
1515         if (iid < 0) {
1516                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1517                         if (port->wwpn_iid[i].in_use == 0 &&
1518                             port->wwpn_iid[i].wwpn == 0 &&
1519                             port->wwpn_iid[i].name == NULL) {
1520                                 iid = i;
1521                                 break;
1522                         }
1523                 }
1524         }
1525
1526         if (iid < 0) {
1527                 best = -1;
1528                 best_time = INT32_MAX;
1529                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1530                         if (port->wwpn_iid[i].in_use == 0) {
1531                                 if (port->wwpn_iid[i].last_use < best_time) {
1532                                         best = i;
1533                                         best_time = port->wwpn_iid[i].last_use;
1534                                 }
1535                         }
1536                 }
1537                 iid = best;
1538         }
1539
1540         if (iid < 0) {
1541                 mtx_unlock(&softc->ctl_lock);
1542                 free(name, M_CTL);
1543                 return (-2);
1544         }
1545
1546         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1547                 /*
1548                  * This is not an error yet.
1549                  */
1550                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1551 #if 0
1552                         printf("%s: port %d iid %u WWPN %#jx arrived"
1553                             " again\n", __func__, port->targ_port,
1554                             iid, (uintmax_t)wwpn);
1555 #endif
1556                         goto take;
1557                 }
1558                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1559                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1560 #if 0
1561                         printf("%s: port %d iid %u name '%s' arrived"
1562                             " again\n", __func__, port->targ_port,
1563                             iid, name);
1564 #endif
1565                         goto take;
1566                 }
1567
1568                 /*
1569                  * This is an error, but what do we do about it?  The
1570                  * driver is telling us we have a new WWPN for this
1571                  * initiator ID, so we pretty much need to use it.
1572                  */
1573                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1574                     " but WWPN %#jx '%s' is still at that address\n",
1575                     __func__, port->targ_port, iid, wwpn, name,
1576                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1577                     port->wwpn_iid[iid].name);
1578
1579                 /*
1580                  * XXX KDM clear have_ca and ua_pending on each LUN for
1581                  * this initiator.
1582                  */
1583         }
1584 take:
1585         free(port->wwpn_iid[iid].name, M_CTL);
1586         port->wwpn_iid[iid].name = name;
1587         port->wwpn_iid[iid].wwpn = wwpn;
1588         port->wwpn_iid[iid].in_use++;
1589         mtx_unlock(&softc->ctl_lock);
1590
1591         return (iid);
1592 }
1593
1594 static int
1595 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1596 {
1597         int len;
1598
1599         switch (port->port_type) {
1600         case CTL_PORT_FC:
1601         {
1602                 struct scsi_transportid_fcp *id =
1603                     (struct scsi_transportid_fcp *)buf;
1604                 if (port->wwpn_iid[iid].wwpn == 0)
1605                         return (0);
1606                 memset(id, 0, sizeof(*id));
1607                 id->format_protocol = SCSI_PROTO_FC;
1608                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1609                 return (sizeof(*id));
1610         }
1611         case CTL_PORT_ISCSI:
1612         {
1613                 struct scsi_transportid_iscsi_port *id =
1614                     (struct scsi_transportid_iscsi_port *)buf;
1615                 if (port->wwpn_iid[iid].name == NULL)
1616                         return (0);
1617                 memset(id, 0, 256);
1618                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1619                     SCSI_PROTO_ISCSI;
1620                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1621                 len = roundup2(min(len, 252), 4);
1622                 scsi_ulto2b(len, id->additional_length);
1623                 return (sizeof(*id) + len);
1624         }
1625         case CTL_PORT_SAS:
1626         {
1627                 struct scsi_transportid_sas *id =
1628                     (struct scsi_transportid_sas *)buf;
1629                 if (port->wwpn_iid[iid].wwpn == 0)
1630                         return (0);
1631                 memset(id, 0, sizeof(*id));
1632                 id->format_protocol = SCSI_PROTO_SAS;
1633                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1634                 return (sizeof(*id));
1635         }
1636         default:
1637         {
1638                 struct scsi_transportid_spi *id =
1639                     (struct scsi_transportid_spi *)buf;
1640                 memset(id, 0, sizeof(*id));
1641                 id->format_protocol = SCSI_PROTO_SPI;
1642                 scsi_ulto2b(iid, id->scsi_addr);
1643                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1644                 return (sizeof(*id));
1645         }
1646         }
1647 }
1648
1649 static int
1650 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1651 {
1652         return (0);
1653 }
1654
1655 static int
1656 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1657 {
1658         return (0);
1659 }
1660
1661 /*
1662  * Data movement routine for the CTL ioctl frontend port.
1663  */
1664 static int
1665 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1666 {
1667         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1668         struct ctl_sg_entry ext_entry, kern_entry;
1669         int ext_sglen, ext_sg_entries, kern_sg_entries;
1670         int ext_sg_start, ext_offset;
1671         int len_to_copy, len_copied;
1672         int kern_watermark, ext_watermark;
1673         int ext_sglist_malloced;
1674         int i, j;
1675
1676         ext_sglist_malloced = 0;
1677         ext_sg_start = 0;
1678         ext_offset = 0;
1679
1680         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1681
1682         /*
1683          * If this flag is set, fake the data transfer.
1684          */
1685         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1686                 ctsio->ext_data_filled = ctsio->ext_data_len;
1687                 goto bailout;
1688         }
1689
1690         /*
1691          * To simplify things here, if we have a single buffer, stick it in
1692          * a S/G entry and just make it a single entry S/G list.
1693          */
1694         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1695                 int len_seen;
1696
1697                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1698
1699                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1700                                                            M_WAITOK);
1701                 ext_sglist_malloced = 1;
1702                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1703                                    ext_sglen) != 0) {
1704                         ctl_set_internal_failure(ctsio,
1705                                                  /*sks_valid*/ 0,
1706                                                  /*retry_count*/ 0);
1707                         goto bailout;
1708                 }
1709                 ext_sg_entries = ctsio->ext_sg_entries;
1710                 len_seen = 0;
1711                 for (i = 0; i < ext_sg_entries; i++) {
1712                         if ((len_seen + ext_sglist[i].len) >=
1713                              ctsio->ext_data_filled) {
1714                                 ext_sg_start = i;
1715                                 ext_offset = ctsio->ext_data_filled - len_seen;
1716                                 break;
1717                         }
1718                         len_seen += ext_sglist[i].len;
1719                 }
1720         } else {
1721                 ext_sglist = &ext_entry;
1722                 ext_sglist->addr = ctsio->ext_data_ptr;
1723                 ext_sglist->len = ctsio->ext_data_len;
1724                 ext_sg_entries = 1;
1725                 ext_sg_start = 0;
1726                 ext_offset = ctsio->ext_data_filled;
1727         }
1728
1729         if (ctsio->kern_sg_entries > 0) {
1730                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1731                 kern_sg_entries = ctsio->kern_sg_entries;
1732         } else {
1733                 kern_sglist = &kern_entry;
1734                 kern_sglist->addr = ctsio->kern_data_ptr;
1735                 kern_sglist->len = ctsio->kern_data_len;
1736                 kern_sg_entries = 1;
1737         }
1738
1739
1740         kern_watermark = 0;
1741         ext_watermark = ext_offset;
1742         len_copied = 0;
1743         for (i = ext_sg_start, j = 0;
1744              i < ext_sg_entries && j < kern_sg_entries;) {
1745                 uint8_t *ext_ptr, *kern_ptr;
1746
1747                 len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1748                                   kern_sglist[j].len - kern_watermark);
1749
1750                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1751                 ext_ptr = ext_ptr + ext_watermark;
1752                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1753                         /*
1754                          * XXX KDM fix this!
1755                          */
1756                         panic("need to implement bus address support");
1757 #if 0
1758                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1759 #endif
1760                 } else
1761                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1762                 kern_ptr = kern_ptr + kern_watermark;
1763
1764                 kern_watermark += len_to_copy;
1765                 ext_watermark += len_to_copy;
1766
1767                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1768                      CTL_FLAG_DATA_IN) {
1769                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1770                                          "bytes to user\n", len_to_copy));
1771                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1772                                          "to %p\n", kern_ptr, ext_ptr));
1773                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1774                                 ctl_set_internal_failure(ctsio,
1775                                                          /*sks_valid*/ 0,
1776                                                          /*retry_count*/ 0);
1777                                 goto bailout;
1778                         }
1779                 } else {
1780                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1781                                          "bytes from user\n", len_to_copy));
1782                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1783                                          "to %p\n", ext_ptr, kern_ptr));
1784                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1785                                 ctl_set_internal_failure(ctsio,
1786                                                          /*sks_valid*/ 0,
1787                                                          /*retry_count*/0);
1788                                 goto bailout;
1789                         }
1790                 }
1791
1792                 len_copied += len_to_copy;
1793
1794                 if (ext_sglist[i].len == ext_watermark) {
1795                         i++;
1796                         ext_watermark = 0;
1797                 }
1798
1799                 if (kern_sglist[j].len == kern_watermark) {
1800                         j++;
1801                         kern_watermark = 0;
1802                 }
1803         }
1804
1805         ctsio->ext_data_filled += len_copied;
1806
1807         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1808                          "kern_sg_entries: %d\n", ext_sg_entries,
1809                          kern_sg_entries));
1810         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1811                          "kern_data_len = %d\n", ctsio->ext_data_len,
1812                          ctsio->kern_data_len));
1813
1814
1815         /* XXX KDM set residual?? */
1816 bailout:
1817
1818         if (ext_sglist_malloced != 0)
1819                 free(ext_sglist, M_CTL);
1820
1821         return (CTL_RETVAL_COMPLETE);
1822 }
1823
1824 /*
1825  * Serialize a command that went down the "wrong" side, and so was sent to
1826  * this controller for execution.  The logic is a little different than the
1827  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1828  * sent back to the other side, but in the success case, we execute the
1829  * command on this side (XFER mode) or tell the other side to execute it
1830  * (SER_ONLY mode).
1831  */
1832 static int
1833 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1834 {
1835         struct ctl_softc *softc;
1836         union ctl_ha_msg msg_info;
1837         struct ctl_lun *lun;
1838         int retval = 0;
1839         uint32_t targ_lun;
1840
1841         softc = control_softc;
1842
1843         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1844         lun = softc->ctl_luns[targ_lun];
1845         if (lun==NULL)
1846         {
1847                 /*
1848                  * Why isn't LUN defined? The other side wouldn't
1849                  * send a cmd if the LUN is undefined.
1850                  */
1851                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1852
1853                 /* "Logical unit not supported" */
1854                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1855                                    lun,
1856                                    /*sense_format*/SSD_TYPE_NONE,
1857                                    /*current_error*/ 1,
1858                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1859                                    /*asc*/ 0x25,
1860                                    /*ascq*/ 0x00,
1861                                    SSD_ELEM_NONE);
1862
1863                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1864                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1865                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1866                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1867                 msg_info.hdr.serializing_sc = NULL;
1868                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1869                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871                 }
1872                 return(1);
1873
1874         }
1875
1876         mtx_lock(&lun->lun_lock);
1877         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1878
1879         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1880                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1881                  ooa_links))) {
1882         case CTL_ACTION_BLOCK:
1883                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1884                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1885                                   blocked_links);
1886                 break;
1887         case CTL_ACTION_PASS:
1888         case CTL_ACTION_SKIP:
1889                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1890                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1891                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1892                 } else {
1893
1894                         /* send msg back to other side */
1895                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1896                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1897                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1898 #if 0
1899                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1900 #endif
1901                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1902                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1903                         }
1904                 }
1905                 break;
1906         case CTL_ACTION_OVERLAP:
1907                 /* OVERLAPPED COMMANDS ATTEMPTED */
1908                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1909                                    lun,
1910                                    /*sense_format*/SSD_TYPE_NONE,
1911                                    /*current_error*/ 1,
1912                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1913                                    /*asc*/ 0x4E,
1914                                    /*ascq*/ 0x00,
1915                                    SSD_ELEM_NONE);
1916
1917                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1918                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1919                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1920                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1921                 msg_info.hdr.serializing_sc = NULL;
1922                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1923 #if 0
1924                 printf("BAD JUJU:Major Bummer Overlap\n");
1925 #endif
1926                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1927                 retval = 1;
1928                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1929                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1930                 }
1931                 break;
1932         case CTL_ACTION_OVERLAP_TAG:
1933                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1934                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1935                                    lun,
1936                                    /*sense_format*/SSD_TYPE_NONE,
1937                                    /*current_error*/ 1,
1938                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1939                                    /*asc*/ 0x4D,
1940                                    /*ascq*/ ctsio->tag_num & 0xff,
1941                                    SSD_ELEM_NONE);
1942
1943                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1944                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1945                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1946                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1947                 msg_info.hdr.serializing_sc = NULL;
1948                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1949 #if 0
1950                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1951 #endif
1952                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1953                 retval = 1;
1954                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1955                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1956                 }
1957                 break;
1958         case CTL_ACTION_ERROR:
1959         default:
1960                 /* "Internal target failure" */
1961                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1962                                    lun,
1963                                    /*sense_format*/SSD_TYPE_NONE,
1964                                    /*current_error*/ 1,
1965                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1966                                    /*asc*/ 0x44,
1967                                    /*ascq*/ 0x00,
1968                                    SSD_ELEM_NONE);
1969
1970                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1971                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1972                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1973                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1974                 msg_info.hdr.serializing_sc = NULL;
1975                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1976 #if 0
1977                 printf("BAD JUJU:Major Bummer HW Error\n");
1978 #endif
1979                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1980                 retval = 1;
1981                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1982                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1983                 }
1984                 break;
1985         }
1986         mtx_unlock(&lun->lun_lock);
1987         return (retval);
1988 }
1989
1990 static int
1991 ctl_ioctl_submit_wait(union ctl_io *io)
1992 {
1993         struct ctl_fe_ioctl_params params;
1994         ctl_fe_ioctl_state last_state;
1995         int done, retval;
1996
1997         retval = 0;
1998
1999         bzero(&params, sizeof(params));
2000
2001         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2002         cv_init(&params.sem, "ctlioccv");
2003         params.state = CTL_IOCTL_INPROG;
2004         last_state = params.state;
2005
2006         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2007
2008         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2009
2010         /* This shouldn't happen */
2011         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2012                 return (retval);
2013
2014         done = 0;
2015
2016         do {
2017                 mtx_lock(&params.ioctl_mtx);
2018                 /*
2019                  * Check the state here, and don't sleep if the state has
2020                  * already changed (i.e. wakeup has already occured, but we
2021                  * weren't waiting yet).
2022                  */
2023                 if (params.state == last_state) {
2024                         /* XXX KDM cv_wait_sig instead? */
2025                         cv_wait(&params.sem, &params.ioctl_mtx);
2026                 }
2027                 last_state = params.state;
2028
2029                 switch (params.state) {
2030                 case CTL_IOCTL_INPROG:
2031                         /* Why did we wake up? */
2032                         /* XXX KDM error here? */
2033                         mtx_unlock(&params.ioctl_mtx);
2034                         break;
2035                 case CTL_IOCTL_DATAMOVE:
2036                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2037
2038                         /*
2039                          * change last_state back to INPROG to avoid
2040                          * deadlock on subsequent data moves.
2041                          */
2042                         params.state = last_state = CTL_IOCTL_INPROG;
2043
2044                         mtx_unlock(&params.ioctl_mtx);
2045                         ctl_ioctl_do_datamove(&io->scsiio);
2046                         /*
2047                          * Note that in some cases, most notably writes,
2048                          * this will queue the I/O and call us back later.
2049                          * In other cases, generally reads, this routine
2050                          * will immediately call back and wake us up,
2051                          * probably using our own context.
2052                          */
2053                         io->scsiio.be_move_done(io);
2054                         break;
2055                 case CTL_IOCTL_DONE:
2056                         mtx_unlock(&params.ioctl_mtx);
2057                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2058                         done = 1;
2059                         break;
2060                 default:
2061                         mtx_unlock(&params.ioctl_mtx);
2062                         /* XXX KDM error here? */
2063                         break;
2064                 }
2065         } while (done == 0);
2066
2067         mtx_destroy(&params.ioctl_mtx);
2068         cv_destroy(&params.sem);
2069
2070         return (CTL_RETVAL_COMPLETE);
2071 }
2072
2073 static void
2074 ctl_ioctl_datamove(union ctl_io *io)
2075 {
2076         struct ctl_fe_ioctl_params *params;
2077
2078         params = (struct ctl_fe_ioctl_params *)
2079                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2080
2081         mtx_lock(&params->ioctl_mtx);
2082         params->state = CTL_IOCTL_DATAMOVE;
2083         cv_broadcast(&params->sem);
2084         mtx_unlock(&params->ioctl_mtx);
2085 }
2086
2087 static void
2088 ctl_ioctl_done(union ctl_io *io)
2089 {
2090         struct ctl_fe_ioctl_params *params;
2091
2092         params = (struct ctl_fe_ioctl_params *)
2093                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2094
2095         mtx_lock(&params->ioctl_mtx);
2096         params->state = CTL_IOCTL_DONE;
2097         cv_broadcast(&params->sem);
2098         mtx_unlock(&params->ioctl_mtx);
2099 }
2100
2101 static void
2102 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2103 {
2104         struct ctl_fe_ioctl_startstop_info *sd_info;
2105
2106         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2107
2108         sd_info->hs_info.status = metatask->status;
2109         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2110         sd_info->hs_info.luns_complete =
2111                 metatask->taskinfo.startstop.luns_complete;
2112         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2113
2114         cv_broadcast(&sd_info->sem);
2115 }
2116
2117 static void
2118 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2119 {
2120         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2121
2122         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2123
2124         mtx_lock(fe_bbr_info->lock);
2125         fe_bbr_info->bbr_info->status = metatask->status;
2126         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2127         fe_bbr_info->wakeup_done = 1;
2128         mtx_unlock(fe_bbr_info->lock);
2129
2130         cv_broadcast(&fe_bbr_info->sem);
2131 }
2132
2133 /*
2134  * Returns 0 for success, errno for failure.
2135  */
2136 static int
2137 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2138                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2139 {
2140         union ctl_io *io;
2141         int retval;
2142
2143         retval = 0;
2144
2145         mtx_lock(&lun->lun_lock);
2146         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2147              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2148              ooa_links)) {
2149                 struct ctl_ooa_entry *entry;
2150
2151                 /*
2152                  * If we've got more than we can fit, just count the
2153                  * remaining entries.
2154                  */
2155                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2156                         continue;
2157
2158                 entry = &kern_entries[*cur_fill_num];
2159
2160                 entry->tag_num = io->scsiio.tag_num;
2161                 entry->lun_num = lun->lun;
2162 #ifdef CTL_TIME_IO
2163                 entry->start_bt = io->io_hdr.start_bt;
2164 #endif
2165                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2166                 entry->cdb_len = io->scsiio.cdb_len;
2167                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2168                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2169
2170                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2171                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2172
2173                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2174                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2175
2176                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2177                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2178
2179                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2180                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2181         }
2182         mtx_unlock(&lun->lun_lock);
2183
2184         return (retval);
2185 }
2186
2187 static void *
2188 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2189                  size_t error_str_len)
2190 {
2191         void *kptr;
2192
2193         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2194
2195         if (copyin(user_addr, kptr, len) != 0) {
2196                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2197                          "from user address %p to kernel address %p", len,
2198                          user_addr, kptr);
2199                 free(kptr, M_CTL);
2200                 return (NULL);
2201         }
2202
2203         return (kptr);
2204 }
2205
2206 static void
2207 ctl_free_args(int num_args, struct ctl_be_arg *args)
2208 {
2209         int i;
2210
2211         if (args == NULL)
2212                 return;
2213
2214         for (i = 0; i < num_args; i++) {
2215                 free(args[i].kname, M_CTL);
2216                 free(args[i].kvalue, M_CTL);
2217         }
2218
2219         free(args, M_CTL);
2220 }
2221
2222 static struct ctl_be_arg *
2223 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2224                 char *error_str, size_t error_str_len)
2225 {
2226         struct ctl_be_arg *args;
2227         int i;
2228
2229         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2230                                 error_str, error_str_len);
2231
2232         if (args == NULL)
2233                 goto bailout;
2234
2235         for (i = 0; i < num_args; i++) {
2236                 args[i].kname = NULL;
2237                 args[i].kvalue = NULL;
2238         }
2239
2240         for (i = 0; i < num_args; i++) {
2241                 uint8_t *tmpptr;
2242
2243                 args[i].kname = ctl_copyin_alloc(args[i].name,
2244                         args[i].namelen, error_str, error_str_len);
2245                 if (args[i].kname == NULL)
2246                         goto bailout;
2247
2248                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2249                         snprintf(error_str, error_str_len, "Argument %d "
2250                                  "name is not NUL-terminated", i);
2251                         goto bailout;
2252                 }
2253
2254                 if (args[i].flags & CTL_BEARG_RD) {
2255                         tmpptr = ctl_copyin_alloc(args[i].value,
2256                                 args[i].vallen, error_str, error_str_len);
2257                         if (tmpptr == NULL)
2258                                 goto bailout;
2259                         if ((args[i].flags & CTL_BEARG_ASCII)
2260                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2261                                 snprintf(error_str, error_str_len, "Argument "
2262                                     "%d value is not NUL-terminated", i);
2263                                 goto bailout;
2264                         }
2265                         args[i].kvalue = tmpptr;
2266                 } else {
2267                         args[i].kvalue = malloc(args[i].vallen,
2268                             M_CTL, M_WAITOK | M_ZERO);
2269                 }
2270         }
2271
2272         return (args);
2273 bailout:
2274
2275         ctl_free_args(num_args, args);
2276
2277         return (NULL);
2278 }
2279
2280 static void
2281 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2282 {
2283         int i;
2284
2285         for (i = 0; i < num_args; i++) {
2286                 if (args[i].flags & CTL_BEARG_WR)
2287                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2288         }
2289 }
2290
2291 /*
2292  * Escape characters that are illegal or not recommended in XML.
2293  */
2294 int
2295 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2296 {
2297         char *end = str + size;
2298         int retval;
2299
2300         retval = 0;
2301
2302         for (; *str && str < end; str++) {
2303                 switch (*str) {
2304                 case '&':
2305                         retval = sbuf_printf(sb, "&amp;");
2306                         break;
2307                 case '>':
2308                         retval = sbuf_printf(sb, "&gt;");
2309                         break;
2310                 case '<':
2311                         retval = sbuf_printf(sb, "&lt;");
2312                         break;
2313                 default:
2314                         retval = sbuf_putc(sb, *str);
2315                         break;
2316                 }
2317
2318                 if (retval != 0)
2319                         break;
2320
2321         }
2322
2323         return (retval);
2324 }
2325
2326 static void
2327 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2328 {
2329         struct scsi_vpd_id_descriptor *desc;
2330         int i;
2331
2332         if (id == NULL || id->len < 4)
2333                 return;
2334         desc = (struct scsi_vpd_id_descriptor *)id->data;
2335         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2336         case SVPD_ID_TYPE_T10:
2337                 sbuf_printf(sb, "t10.");
2338                 break;
2339         case SVPD_ID_TYPE_EUI64:
2340                 sbuf_printf(sb, "eui.");
2341                 break;
2342         case SVPD_ID_TYPE_NAA:
2343                 sbuf_printf(sb, "naa.");
2344                 break;
2345         case SVPD_ID_TYPE_SCSI_NAME:
2346                 break;
2347         }
2348         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2349         case SVPD_ID_CODESET_BINARY:
2350                 for (i = 0; i < desc->length; i++)
2351                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2352                 break;
2353         case SVPD_ID_CODESET_ASCII:
2354                 sbuf_printf(sb, "%.*s", (int)desc->length,
2355                     (char *)desc->identifier);
2356                 break;
2357         case SVPD_ID_CODESET_UTF8:
2358                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2359                 break;
2360         }
2361 }
2362
2363 static int
2364 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2365           struct thread *td)
2366 {
2367         struct ctl_softc *softc;
2368         int retval;
2369
2370         softc = control_softc;
2371
2372         retval = 0;
2373
2374         switch (cmd) {
2375         case CTL_IO: {
2376                 union ctl_io *io;
2377                 void *pool_tmp;
2378
2379                 /*
2380                  * If we haven't been "enabled", don't allow any SCSI I/O
2381                  * to this FETD.
2382                  */
2383                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2384                         retval = EPERM;
2385                         break;
2386                 }
2387
2388                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2389
2390                 /*
2391                  * Need to save the pool reference so it doesn't get
2392                  * spammed by the user's ctl_io.
2393                  */
2394                 pool_tmp = io->io_hdr.pool;
2395                 memcpy(io, (void *)addr, sizeof(*io));
2396                 io->io_hdr.pool = pool_tmp;
2397
2398                 /*
2399                  * No status yet, so make sure the status is set properly.
2400                  */
2401                 io->io_hdr.status = CTL_STATUS_NONE;
2402
2403                 /*
2404                  * The user sets the initiator ID, target and LUN IDs.
2405                  */
2406                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2407                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2408                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2409                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2410                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2411
2412                 retval = ctl_ioctl_submit_wait(io);
2413
2414                 if (retval != 0) {
2415                         ctl_free_io(io);
2416                         break;
2417                 }
2418
2419                 memcpy((void *)addr, io, sizeof(*io));
2420
2421                 /* return this to our pool */
2422                 ctl_free_io(io);
2423
2424                 break;
2425         }
2426         case CTL_ENABLE_PORT:
2427         case CTL_DISABLE_PORT:
2428         case CTL_SET_PORT_WWNS: {
2429                 struct ctl_port *port;
2430                 struct ctl_port_entry *entry;
2431
2432                 entry = (struct ctl_port_entry *)addr;
2433                 
2434                 mtx_lock(&softc->ctl_lock);
2435                 STAILQ_FOREACH(port, &softc->port_list, links) {
2436                         int action, done;
2437
2438                         action = 0;
2439                         done = 0;
2440
2441                         if ((entry->port_type == CTL_PORT_NONE)
2442                          && (entry->targ_port == port->targ_port)) {
2443                                 /*
2444                                  * If the user only wants to enable or
2445                                  * disable or set WWNs on a specific port,
2446                                  * do the operation and we're done.
2447                                  */
2448                                 action = 1;
2449                                 done = 1;
2450                         } else if (entry->port_type & port->port_type) {
2451                                 /*
2452                                  * Compare the user's type mask with the
2453                                  * particular frontend type to see if we
2454                                  * have a match.
2455                                  */
2456                                 action = 1;
2457                                 done = 0;
2458
2459                                 /*
2460                                  * Make sure the user isn't trying to set
2461                                  * WWNs on multiple ports at the same time.
2462                                  */
2463                                 if (cmd == CTL_SET_PORT_WWNS) {
2464                                         printf("%s: Can't set WWNs on "
2465                                                "multiple ports\n", __func__);
2466                                         retval = EINVAL;
2467                                         break;
2468                                 }
2469                         }
2470                         if (action != 0) {
2471                                 /*
2472                                  * XXX KDM we have to drop the lock here,
2473                                  * because the online/offline operations
2474                                  * can potentially block.  We need to
2475                                  * reference count the frontends so they
2476                                  * can't go away,
2477                                  */
2478                                 mtx_unlock(&softc->ctl_lock);
2479
2480                                 if (cmd == CTL_ENABLE_PORT) {
2481                                         struct ctl_lun *lun;
2482
2483                                         STAILQ_FOREACH(lun, &softc->lun_list,
2484                                                        links) {
2485                                                 port->lun_enable(port->targ_lun_arg,
2486                                                     lun->target,
2487                                                     lun->lun);
2488                                         }
2489
2490                                         ctl_port_online(port);
2491                                 } else if (cmd == CTL_DISABLE_PORT) {
2492                                         struct ctl_lun *lun;
2493
2494                                         ctl_port_offline(port);
2495
2496                                         STAILQ_FOREACH(lun, &softc->lun_list,
2497                                                        links) {
2498                                                 port->lun_disable(
2499                                                     port->targ_lun_arg,
2500                                                     lun->target,
2501                                                     lun->lun);
2502                                         }
2503                                 }
2504
2505                                 mtx_lock(&softc->ctl_lock);
2506
2507                                 if (cmd == CTL_SET_PORT_WWNS)
2508                                         ctl_port_set_wwns(port,
2509                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2510                                             1 : 0, entry->wwnn,
2511                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2512                                             1 : 0, entry->wwpn);
2513                         }
2514                         if (done != 0)
2515                                 break;
2516                 }
2517                 mtx_unlock(&softc->ctl_lock);
2518                 break;
2519         }
2520         case CTL_GET_PORT_LIST: {
2521                 struct ctl_port *port;
2522                 struct ctl_port_list *list;
2523                 int i;
2524
2525                 list = (struct ctl_port_list *)addr;
2526
2527                 if (list->alloc_len != (list->alloc_num *
2528                     sizeof(struct ctl_port_entry))) {
2529                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2530                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2531                                "%zu\n", __func__, list->alloc_len,
2532                                list->alloc_num, sizeof(struct ctl_port_entry));
2533                         retval = EINVAL;
2534                         break;
2535                 }
2536                 list->fill_len = 0;
2537                 list->fill_num = 0;
2538                 list->dropped_num = 0;
2539                 i = 0;
2540                 mtx_lock(&softc->ctl_lock);
2541                 STAILQ_FOREACH(port, &softc->port_list, links) {
2542                         struct ctl_port_entry entry, *list_entry;
2543
2544                         if (list->fill_num >= list->alloc_num) {
2545                                 list->dropped_num++;
2546                                 continue;
2547                         }
2548
2549                         entry.port_type = port->port_type;
2550                         strlcpy(entry.port_name, port->port_name,
2551                                 sizeof(entry.port_name));
2552                         entry.targ_port = port->targ_port;
2553                         entry.physical_port = port->physical_port;
2554                         entry.virtual_port = port->virtual_port;
2555                         entry.wwnn = port->wwnn;
2556                         entry.wwpn = port->wwpn;
2557                         if (port->status & CTL_PORT_STATUS_ONLINE)
2558                                 entry.online = 1;
2559                         else
2560                                 entry.online = 0;
2561
2562                         list_entry = &list->entries[i];
2563
2564                         retval = copyout(&entry, list_entry, sizeof(entry));
2565                         if (retval != 0) {
2566                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2567                                        "returned %d\n", __func__, retval);
2568                                 break;
2569                         }
2570                         i++;
2571                         list->fill_num++;
2572                         list->fill_len += sizeof(entry);
2573                 }
2574                 mtx_unlock(&softc->ctl_lock);
2575
2576                 /*
2577                  * If this is non-zero, we had a copyout fault, so there's
2578                  * probably no point in attempting to set the status inside
2579                  * the structure.
2580                  */
2581                 if (retval != 0)
2582                         break;
2583
2584                 if (list->dropped_num > 0)
2585                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2586                 else
2587                         list->status = CTL_PORT_LIST_OK;
2588                 break;
2589         }
2590         case CTL_DUMP_OOA: {
2591                 struct ctl_lun *lun;
2592                 union ctl_io *io;
2593                 char printbuf[128];
2594                 struct sbuf sb;
2595
2596                 mtx_lock(&softc->ctl_lock);
2597                 printf("Dumping OOA queues:\n");
2598                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2599                         mtx_lock(&lun->lun_lock);
2600                         for (io = (union ctl_io *)TAILQ_FIRST(
2601                              &lun->ooa_queue); io != NULL;
2602                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2603                              ooa_links)) {
2604                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2605                                          SBUF_FIXEDLEN);
2606                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2607                                             (intmax_t)lun->lun,
2608                                             io->scsiio.tag_num,
2609                                             (io->io_hdr.flags &
2610                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2611                                             (io->io_hdr.flags &
2612                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2613                                             (io->io_hdr.flags &
2614                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2615                                             (io->io_hdr.flags &
2616                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2617                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2618                                 sbuf_finish(&sb);
2619                                 printf("%s\n", sbuf_data(&sb));
2620                         }
2621                         mtx_unlock(&lun->lun_lock);
2622                 }
2623                 printf("OOA queues dump done\n");
2624                 mtx_unlock(&softc->ctl_lock);
2625                 break;
2626         }
2627         case CTL_GET_OOA: {
2628                 struct ctl_lun *lun;
2629                 struct ctl_ooa *ooa_hdr;
2630                 struct ctl_ooa_entry *entries;
2631                 uint32_t cur_fill_num;
2632
2633                 ooa_hdr = (struct ctl_ooa *)addr;
2634
2635                 if ((ooa_hdr->alloc_len == 0)
2636                  || (ooa_hdr->alloc_num == 0)) {
2637                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2638                                "must be non-zero\n", __func__,
2639                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2640                         retval = EINVAL;
2641                         break;
2642                 }
2643
2644                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2645                     sizeof(struct ctl_ooa_entry))) {
2646                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2647                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2648                                __func__, ooa_hdr->alloc_len,
2649                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2650                         retval = EINVAL;
2651                         break;
2652                 }
2653
2654                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2655                 if (entries == NULL) {
2656                         printf("%s: could not allocate %d bytes for OOA "
2657                                "dump\n", __func__, ooa_hdr->alloc_len);
2658                         retval = ENOMEM;
2659                         break;
2660                 }
2661
2662                 mtx_lock(&softc->ctl_lock);
2663                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2664                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2665                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2666                         mtx_unlock(&softc->ctl_lock);
2667                         free(entries, M_CTL);
2668                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2669                                __func__, (uintmax_t)ooa_hdr->lun_num);
2670                         retval = EINVAL;
2671                         break;
2672                 }
2673
2674                 cur_fill_num = 0;
2675
2676                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2677                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2678                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2679                                         ooa_hdr, entries);
2680                                 if (retval != 0)
2681                                         break;
2682                         }
2683                         if (retval != 0) {
2684                                 mtx_unlock(&softc->ctl_lock);
2685                                 free(entries, M_CTL);
2686                                 break;
2687                         }
2688                 } else {
2689                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2690
2691                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2692                                                     entries);
2693                 }
2694                 mtx_unlock(&softc->ctl_lock);
2695
2696                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2697                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2698                         sizeof(struct ctl_ooa_entry);
2699                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2700                 if (retval != 0) {
2701                         printf("%s: error copying out %d bytes for OOA dump\n", 
2702                                __func__, ooa_hdr->fill_len);
2703                 }
2704
2705                 getbintime(&ooa_hdr->cur_bt);
2706
2707                 if (cur_fill_num > ooa_hdr->alloc_num) {
2708                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2709                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2710                 } else {
2711                         ooa_hdr->dropped_num = 0;
2712                         ooa_hdr->status = CTL_OOA_OK;
2713                 }
2714
2715                 free(entries, M_CTL);
2716                 break;
2717         }
2718         case CTL_CHECK_OOA: {
2719                 union ctl_io *io;
2720                 struct ctl_lun *lun;
2721                 struct ctl_ooa_info *ooa_info;
2722
2723
2724                 ooa_info = (struct ctl_ooa_info *)addr;
2725
2726                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2727                         ooa_info->status = CTL_OOA_INVALID_LUN;
2728                         break;
2729                 }
2730                 mtx_lock(&softc->ctl_lock);
2731                 lun = softc->ctl_luns[ooa_info->lun_id];
2732                 if (lun == NULL) {
2733                         mtx_unlock(&softc->ctl_lock);
2734                         ooa_info->status = CTL_OOA_INVALID_LUN;
2735                         break;
2736                 }
2737                 mtx_lock(&lun->lun_lock);
2738                 mtx_unlock(&softc->ctl_lock);
2739                 ooa_info->num_entries = 0;
2740                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2741                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2742                      &io->io_hdr, ooa_links)) {
2743                         ooa_info->num_entries++;
2744                 }
2745                 mtx_unlock(&lun->lun_lock);
2746
2747                 ooa_info->status = CTL_OOA_SUCCESS;
2748
2749                 break;
2750         }
2751         case CTL_HARD_START:
2752         case CTL_HARD_STOP: {
2753                 struct ctl_fe_ioctl_startstop_info ss_info;
2754                 struct cfi_metatask *metatask;
2755                 struct mtx hs_mtx;
2756
2757                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2758
2759                 cv_init(&ss_info.sem, "hard start/stop cv" );
2760
2761                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2762                 if (metatask == NULL) {
2763                         retval = ENOMEM;
2764                         mtx_destroy(&hs_mtx);
2765                         break;
2766                 }
2767
2768                 if (cmd == CTL_HARD_START)
2769                         metatask->tasktype = CFI_TASK_STARTUP;
2770                 else
2771                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2772
2773                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2774                 metatask->callback_arg = &ss_info;
2775
2776                 cfi_action(metatask);
2777
2778                 /* Wait for the callback */
2779                 mtx_lock(&hs_mtx);
2780                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2781                 mtx_unlock(&hs_mtx);
2782
2783                 /*
2784                  * All information has been copied from the metatask by the
2785                  * time cv_broadcast() is called, so we free the metatask here.
2786                  */
2787                 cfi_free_metatask(metatask);
2788
2789                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2790
2791                 mtx_destroy(&hs_mtx);
2792                 break;
2793         }
2794         case CTL_BBRREAD: {
2795                 struct ctl_bbrread_info *bbr_info;
2796                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2797                 struct mtx bbr_mtx;
2798                 struct cfi_metatask *metatask;
2799
2800                 bbr_info = (struct ctl_bbrread_info *)addr;
2801
2802                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2803
2804                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2805                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2806
2807                 fe_bbr_info.bbr_info = bbr_info;
2808                 fe_bbr_info.lock = &bbr_mtx;
2809
2810                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2811                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2812
2813                 if (metatask == NULL) {
2814                         mtx_destroy(&bbr_mtx);
2815                         cv_destroy(&fe_bbr_info.sem);
2816                         retval = ENOMEM;
2817                         break;
2818                 }
2819                 metatask->tasktype = CFI_TASK_BBRREAD;
2820                 metatask->callback = ctl_ioctl_bbrread_callback;
2821                 metatask->callback_arg = &fe_bbr_info;
2822                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2823                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2824                 metatask->taskinfo.bbrread.len = bbr_info->len;
2825
2826                 cfi_action(metatask);
2827
2828                 mtx_lock(&bbr_mtx);
2829                 while (fe_bbr_info.wakeup_done == 0)
2830                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2831                 mtx_unlock(&bbr_mtx);
2832
2833                 bbr_info->status = metatask->status;
2834                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2835                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2836                 memcpy(&bbr_info->sense_data,
2837                        &metatask->taskinfo.bbrread.sense_data,
2838                        MIN(sizeof(bbr_info->sense_data),
2839                            sizeof(metatask->taskinfo.bbrread.sense_data)));
2840
2841                 cfi_free_metatask(metatask);
2842
2843                 mtx_destroy(&bbr_mtx);
2844                 cv_destroy(&fe_bbr_info.sem);
2845
2846                 break;
2847         }
2848         case CTL_DELAY_IO: {
2849                 struct ctl_io_delay_info *delay_info;
2850 #ifdef CTL_IO_DELAY
2851                 struct ctl_lun *lun;
2852 #endif /* CTL_IO_DELAY */
2853
2854                 delay_info = (struct ctl_io_delay_info *)addr;
2855
2856 #ifdef CTL_IO_DELAY
2857                 mtx_lock(&softc->ctl_lock);
2858
2859                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2860                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2861                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2862                 } else {
2863                         lun = softc->ctl_luns[delay_info->lun_id];
2864                         mtx_lock(&lun->lun_lock);
2865
2866                         delay_info->status = CTL_DELAY_STATUS_OK;
2867
2868                         switch (delay_info->delay_type) {
2869                         case CTL_DELAY_TYPE_CONT:
2870                                 break;
2871                         case CTL_DELAY_TYPE_ONESHOT:
2872                                 break;
2873                         default:
2874                                 delay_info->status =
2875                                         CTL_DELAY_STATUS_INVALID_TYPE;
2876                                 break;
2877                         }
2878
2879                         switch (delay_info->delay_loc) {
2880                         case CTL_DELAY_LOC_DATAMOVE:
2881                                 lun->delay_info.datamove_type =
2882                                         delay_info->delay_type;
2883                                 lun->delay_info.datamove_delay =
2884                                         delay_info->delay_secs;
2885                                 break;
2886                         case CTL_DELAY_LOC_DONE:
2887                                 lun->delay_info.done_type =
2888                                         delay_info->delay_type;
2889                                 lun->delay_info.done_delay =
2890                                         delay_info->delay_secs;
2891                                 break;
2892                         default:
2893                                 delay_info->status =
2894                                         CTL_DELAY_STATUS_INVALID_LOC;
2895                                 break;
2896                         }
2897                         mtx_unlock(&lun->lun_lock);
2898                 }
2899
2900                 mtx_unlock(&softc->ctl_lock);
2901 #else
2902                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2903 #endif /* CTL_IO_DELAY */
2904                 break;
2905         }
2906         case CTL_REALSYNC_SET: {
2907                 int *syncstate;
2908
2909                 syncstate = (int *)addr;
2910
2911                 mtx_lock(&softc->ctl_lock);
2912                 switch (*syncstate) {
2913                 case 0:
2914                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2915                         break;
2916                 case 1:
2917                         softc->flags |= CTL_FLAG_REAL_SYNC;
2918                         break;
2919                 default:
2920                         retval = EINVAL;
2921                         break;
2922                 }
2923                 mtx_unlock(&softc->ctl_lock);
2924                 break;
2925         }
2926         case CTL_REALSYNC_GET: {
2927                 int *syncstate;
2928
2929                 syncstate = (int*)addr;
2930
2931                 mtx_lock(&softc->ctl_lock);
2932                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2933                         *syncstate = 1;
2934                 else
2935                         *syncstate = 0;
2936                 mtx_unlock(&softc->ctl_lock);
2937
2938                 break;
2939         }
2940         case CTL_SETSYNC:
2941         case CTL_GETSYNC: {
2942                 struct ctl_sync_info *sync_info;
2943                 struct ctl_lun *lun;
2944
2945                 sync_info = (struct ctl_sync_info *)addr;
2946
2947                 mtx_lock(&softc->ctl_lock);
2948                 lun = softc->ctl_luns[sync_info->lun_id];
2949                 if (lun == NULL) {
2950                         mtx_unlock(&softc->ctl_lock);
2951                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2952                 }
2953                 /*
2954                  * Get or set the sync interval.  We're not bounds checking
2955                  * in the set case, hopefully the user won't do something
2956                  * silly.
2957                  */
2958                 mtx_lock(&lun->lun_lock);
2959                 mtx_unlock(&softc->ctl_lock);
2960                 if (cmd == CTL_GETSYNC)
2961                         sync_info->sync_interval = lun->sync_interval;
2962                 else
2963                         lun->sync_interval = sync_info->sync_interval;
2964                 mtx_unlock(&lun->lun_lock);
2965
2966                 sync_info->status = CTL_GS_SYNC_OK;
2967
2968                 break;
2969         }
2970         case CTL_GETSTATS: {
2971                 struct ctl_stats *stats;
2972                 struct ctl_lun *lun;
2973                 int i;
2974
2975                 stats = (struct ctl_stats *)addr;
2976
2977                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2978                      stats->alloc_len) {
2979                         stats->status = CTL_SS_NEED_MORE_SPACE;
2980                         stats->num_luns = softc->num_luns;
2981                         break;
2982                 }
2983                 /*
2984                  * XXX KDM no locking here.  If the LUN list changes,
2985                  * things can blow up.
2986                  */
2987                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2988                      i++, lun = STAILQ_NEXT(lun, links)) {
2989                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2990                                          sizeof(lun->stats));
2991                         if (retval != 0)
2992                                 break;
2993                 }
2994                 stats->num_luns = softc->num_luns;
2995                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2996                                  softc->num_luns;
2997                 stats->status = CTL_SS_OK;
2998 #ifdef CTL_TIME_IO
2999                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
3000 #else
3001                 stats->flags = CTL_STATS_FLAG_NONE;
3002 #endif
3003                 getnanouptime(&stats->timestamp);
3004                 break;
3005         }
3006         case CTL_ERROR_INJECT: {
3007                 struct ctl_error_desc *err_desc, *new_err_desc;
3008                 struct ctl_lun *lun;
3009
3010                 err_desc = (struct ctl_error_desc *)addr;
3011
3012                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3013                                       M_WAITOK | M_ZERO);
3014                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3015
3016                 mtx_lock(&softc->ctl_lock);
3017                 lun = softc->ctl_luns[err_desc->lun_id];
3018                 if (lun == NULL) {
3019                         mtx_unlock(&softc->ctl_lock);
3020                         free(new_err_desc, M_CTL);
3021                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3022                                __func__, (uintmax_t)err_desc->lun_id);
3023                         retval = EINVAL;
3024                         break;
3025                 }
3026                 mtx_lock(&lun->lun_lock);
3027                 mtx_unlock(&softc->ctl_lock);
3028
3029                 /*
3030                  * We could do some checking here to verify the validity
3031                  * of the request, but given the complexity of error
3032                  * injection requests, the checking logic would be fairly
3033                  * complex.
3034                  *
3035                  * For now, if the request is invalid, it just won't get
3036                  * executed and might get deleted.
3037                  */
3038                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3039
3040                 /*
3041                  * XXX KDM check to make sure the serial number is unique,
3042                  * in case we somehow manage to wrap.  That shouldn't
3043                  * happen for a very long time, but it's the right thing to
3044                  * do.
3045                  */
3046                 new_err_desc->serial = lun->error_serial;
3047                 err_desc->serial = lun->error_serial;
3048                 lun->error_serial++;
3049
3050                 mtx_unlock(&lun->lun_lock);
3051                 break;
3052         }
3053         case CTL_ERROR_INJECT_DELETE: {
3054                 struct ctl_error_desc *delete_desc, *desc, *desc2;
3055                 struct ctl_lun *lun;
3056                 int delete_done;
3057
3058                 delete_desc = (struct ctl_error_desc *)addr;
3059                 delete_done = 0;
3060
3061                 mtx_lock(&softc->ctl_lock);
3062                 lun = softc->ctl_luns[delete_desc->lun_id];
3063                 if (lun == NULL) {
3064                         mtx_unlock(&softc->ctl_lock);
3065                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3066                                __func__, (uintmax_t)delete_desc->lun_id);
3067                         retval = EINVAL;
3068                         break;
3069                 }
3070                 mtx_lock(&lun->lun_lock);
3071                 mtx_unlock(&softc->ctl_lock);
3072                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3073                         if (desc->serial != delete_desc->serial)
3074                                 continue;
3075
3076                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3077                                       links);
3078                         free(desc, M_CTL);
3079                         delete_done = 1;
3080                 }
3081                 mtx_unlock(&lun->lun_lock);
3082                 if (delete_done == 0) {
3083                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3084                                "error serial %ju on LUN %u\n", __func__, 
3085                                delete_desc->serial, delete_desc->lun_id);
3086                         retval = EINVAL;
3087                         break;
3088                 }
3089                 break;
3090         }
3091         case CTL_DUMP_STRUCTS: {
3092                 int i, j, k;
3093                 struct ctl_port *port;
3094                 struct ctl_frontend *fe;
3095
3096                 mtx_lock(&softc->ctl_lock);
3097                 printf("CTL Persistent Reservation information start:\n");
3098                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3099                         struct ctl_lun *lun;
3100
3101                         lun = softc->ctl_luns[i];
3102
3103                         if ((lun == NULL)
3104                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3105                                 continue;
3106
3107                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3108                                 if (lun->pr_keys[j] == NULL)
3109                                         continue;
3110                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3111                                         if (lun->pr_keys[j][k] == 0)
3112                                                 continue;
3113                                         printf("  LUN %d port %d iid %d key "
3114                                                "%#jx\n", i, j, k,
3115                                                (uintmax_t)lun->pr_keys[j][k]);
3116                                 }
3117                         }
3118                 }
3119                 printf("CTL Persistent Reservation information end\n");
3120                 printf("CTL Ports:\n");
3121                 STAILQ_FOREACH(port, &softc->port_list, links) {
3122                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3123                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3124                                port->frontend->name, port->port_type,
3125                                port->physical_port, port->virtual_port,
3126                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3127                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3128                                 if (port->wwpn_iid[j].in_use == 0 &&
3129                                     port->wwpn_iid[j].wwpn == 0 &&
3130                                     port->wwpn_iid[j].name == NULL)
3131                                         continue;
3132
3133                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3134                                     j, port->wwpn_iid[j].in_use,
3135                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3136                                     port->wwpn_iid[j].name);
3137                         }
3138                 }
3139                 printf("CTL Port information end\n");
3140                 mtx_unlock(&softc->ctl_lock);
3141                 /*
3142                  * XXX KDM calling this without a lock.  We'd likely want
3143                  * to drop the lock before calling the frontend's dump
3144                  * routine anyway.
3145                  */
3146                 printf("CTL Frontends:\n");
3147                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3148                         printf("  Frontend '%s'\n", fe->name);
3149                         if (fe->fe_dump != NULL)
3150                                 fe->fe_dump();
3151                 }
3152                 printf("CTL Frontend information end\n");
3153                 break;
3154         }
3155         case CTL_LUN_REQ: {
3156                 struct ctl_lun_req *lun_req;
3157                 struct ctl_backend_driver *backend;
3158
3159                 lun_req = (struct ctl_lun_req *)addr;
3160
3161                 backend = ctl_backend_find(lun_req->backend);
3162                 if (backend == NULL) {
3163                         lun_req->status = CTL_LUN_ERROR;
3164                         snprintf(lun_req->error_str,
3165                                  sizeof(lun_req->error_str),
3166                                  "Backend \"%s\" not found.",
3167                                  lun_req->backend);
3168                         break;
3169                 }
3170                 if (lun_req->num_be_args > 0) {
3171                         lun_req->kern_be_args = ctl_copyin_args(
3172                                 lun_req->num_be_args,
3173                                 lun_req->be_args,
3174                                 lun_req->error_str,
3175                                 sizeof(lun_req->error_str));
3176                         if (lun_req->kern_be_args == NULL) {
3177                                 lun_req->status = CTL_LUN_ERROR;
3178                                 break;
3179                         }
3180                 }
3181
3182                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3183
3184                 if (lun_req->num_be_args > 0) {
3185                         ctl_copyout_args(lun_req->num_be_args,
3186                                       lun_req->kern_be_args);
3187                         ctl_free_args(lun_req->num_be_args,
3188                                       lun_req->kern_be_args);
3189                 }
3190                 break;
3191         }
3192         case CTL_LUN_LIST: {
3193                 struct sbuf *sb;
3194                 struct ctl_lun *lun;
3195                 struct ctl_lun_list *list;
3196                 struct ctl_option *opt;
3197
3198                 list = (struct ctl_lun_list *)addr;
3199
3200                 /*
3201                  * Allocate a fixed length sbuf here, based on the length
3202                  * of the user's buffer.  We could allocate an auto-extending
3203                  * buffer, and then tell the user how much larger our
3204                  * amount of data is than his buffer, but that presents
3205                  * some problems:
3206                  *
3207                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3208                  *     we can't hold a lock while calling them with an
3209                  *     auto-extending buffer.
3210                  *
3211                  * 2.  There is not currently a LUN reference counting
3212                  *     mechanism, outside of outstanding transactions on
3213                  *     the LUN's OOA queue.  So a LUN could go away on us
3214                  *     while we're getting the LUN number, backend-specific
3215                  *     information, etc.  Thus, given the way things
3216                  *     currently work, we need to hold the CTL lock while
3217                  *     grabbing LUN information.
3218                  *
3219                  * So, from the user's standpoint, the best thing to do is
3220                  * allocate what he thinks is a reasonable buffer length,
3221                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3222                  * double the buffer length and try again.  (And repeat
3223                  * that until he succeeds.)
3224                  */
3225                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3226                 if (sb == NULL) {
3227                         list->status = CTL_LUN_LIST_ERROR;
3228                         snprintf(list->error_str, sizeof(list->error_str),
3229                                  "Unable to allocate %d bytes for LUN list",
3230                                  list->alloc_len);
3231                         break;
3232                 }
3233
3234                 sbuf_printf(sb, "<ctllunlist>\n");
3235
3236                 mtx_lock(&softc->ctl_lock);
3237                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3238                         mtx_lock(&lun->lun_lock);
3239                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3240                                              (uintmax_t)lun->lun);
3241
3242                         /*
3243                          * Bail out as soon as we see that we've overfilled
3244                          * the buffer.
3245                          */
3246                         if (retval != 0)
3247                                 break;
3248
3249                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3250                                              "</backend_type>\n",
3251                                              (lun->backend == NULL) ?  "none" :
3252                                              lun->backend->name);
3253
3254                         if (retval != 0)
3255                                 break;
3256
3257                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3258                                              lun->be_lun->lun_type);
3259
3260                         if (retval != 0)
3261                                 break;
3262
3263                         if (lun->backend == NULL) {
3264                                 retval = sbuf_printf(sb, "</lun>\n");
3265                                 if (retval != 0)
3266                                         break;
3267                                 continue;
3268                         }
3269
3270                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3271                                              (lun->be_lun->maxlba > 0) ?
3272                                              lun->be_lun->maxlba + 1 : 0);
3273
3274                         if (retval != 0)
3275                                 break;
3276
3277                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3278                                              lun->be_lun->blocksize);
3279
3280                         if (retval != 0)
3281                                 break;
3282
3283                         retval = sbuf_printf(sb, "\t<serial_number>");
3284
3285                         if (retval != 0)
3286                                 break;
3287
3288                         retval = ctl_sbuf_printf_esc(sb,
3289                             lun->be_lun->serial_num,
3290                             sizeof(lun->be_lun->serial_num));
3291
3292                         if (retval != 0)
3293                                 break;
3294
3295                         retval = sbuf_printf(sb, "</serial_number>\n");
3296                 
3297                         if (retval != 0)
3298                                 break;
3299
3300                         retval = sbuf_printf(sb, "\t<device_id>");
3301
3302                         if (retval != 0)
3303                                 break;
3304
3305                         retval = ctl_sbuf_printf_esc(sb,
3306                             lun->be_lun->device_id,
3307                             sizeof(lun->be_lun->device_id));
3308
3309                         if (retval != 0)
3310                                 break;
3311
3312                         retval = sbuf_printf(sb, "</device_id>\n");
3313
3314                         if (retval != 0)
3315                                 break;
3316
3317                         if (lun->backend->lun_info != NULL) {
3318                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3319                                 if (retval != 0)
3320                                         break;
3321                         }
3322                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3323                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3324                                     opt->name, opt->value, opt->name);
3325                                 if (retval != 0)
3326                                         break;
3327                         }
3328
3329                         retval = sbuf_printf(sb, "</lun>\n");
3330
3331                         if (retval != 0)
3332                                 break;
3333                         mtx_unlock(&lun->lun_lock);
3334                 }
3335                 if (lun != NULL)
3336                         mtx_unlock(&lun->lun_lock);
3337                 mtx_unlock(&softc->ctl_lock);
3338
3339                 if ((retval != 0)
3340                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3341                         retval = 0;
3342                         sbuf_delete(sb);
3343                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3344                         snprintf(list->error_str, sizeof(list->error_str),
3345                                  "Out of space, %d bytes is too small",
3346                                  list->alloc_len);
3347                         break;
3348                 }
3349
3350                 sbuf_finish(sb);
3351
3352                 retval = copyout(sbuf_data(sb), list->lun_xml,
3353                                  sbuf_len(sb) + 1);
3354
3355                 list->fill_len = sbuf_len(sb) + 1;
3356                 list->status = CTL_LUN_LIST_OK;
3357                 sbuf_delete(sb);
3358                 break;
3359         }
3360         case CTL_ISCSI: {
3361                 struct ctl_iscsi *ci;
3362                 struct ctl_frontend *fe;
3363
3364                 ci = (struct ctl_iscsi *)addr;
3365
3366                 fe = ctl_frontend_find("iscsi");
3367                 if (fe == NULL) {
3368                         ci->status = CTL_ISCSI_ERROR;
3369                         snprintf(ci->error_str, sizeof(ci->error_str),
3370                             "Frontend \"iscsi\" not found.");
3371                         break;
3372                 }
3373
3374                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3375                 break;
3376         }
3377         case CTL_PORT_REQ: {
3378                 struct ctl_req *req;
3379                 struct ctl_frontend *fe;
3380
3381                 req = (struct ctl_req *)addr;
3382
3383                 fe = ctl_frontend_find(req->driver);
3384                 if (fe == NULL) {
3385                         req->status = CTL_LUN_ERROR;
3386                         snprintf(req->error_str, sizeof(req->error_str),
3387                             "Frontend \"%s\" not found.", req->driver);
3388                         break;
3389                 }
3390                 if (req->num_args > 0) {
3391                         req->kern_args = ctl_copyin_args(req->num_args,
3392                             req->args, req->error_str, sizeof(req->error_str));
3393                         if (req->kern_args == NULL) {
3394                                 req->status = CTL_LUN_ERROR;
3395                                 break;
3396                         }
3397                 }
3398
3399                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3400
3401                 if (req->num_args > 0) {
3402                         ctl_copyout_args(req->num_args, req->kern_args);
3403                         ctl_free_args(req->num_args, req->kern_args);
3404                 }
3405                 break;
3406         }
3407         case CTL_PORT_LIST: {
3408                 struct sbuf *sb;
3409                 struct ctl_port *port;
3410                 struct ctl_lun_list *list;
3411                 struct ctl_option *opt;
3412                 int j;
3413                 uint32_t plun;
3414
3415                 list = (struct ctl_lun_list *)addr;
3416
3417                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3418                 if (sb == NULL) {
3419                         list->status = CTL_LUN_LIST_ERROR;
3420                         snprintf(list->error_str, sizeof(list->error_str),
3421                                  "Unable to allocate %d bytes for LUN list",
3422                                  list->alloc_len);
3423                         break;
3424                 }
3425
3426                 sbuf_printf(sb, "<ctlportlist>\n");
3427
3428                 mtx_lock(&softc->ctl_lock);
3429                 STAILQ_FOREACH(port, &softc->port_list, links) {
3430                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3431                                              (uintmax_t)port->targ_port);
3432
3433                         /*
3434                          * Bail out as soon as we see that we've overfilled
3435                          * the buffer.
3436                          */
3437                         if (retval != 0)
3438                                 break;
3439
3440                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3441                             "</frontend_type>\n", port->frontend->name);
3442                         if (retval != 0)
3443                                 break;
3444
3445                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3446                                              port->port_type);
3447                         if (retval != 0)
3448                                 break;
3449
3450                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3451                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3452                         if (retval != 0)
3453                                 break;
3454
3455                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3456                             port->port_name);
3457                         if (retval != 0)
3458                                 break;
3459
3460                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3461                             port->physical_port);
3462                         if (retval != 0)
3463                                 break;
3464
3465                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3466                             port->virtual_port);
3467                         if (retval != 0)
3468                                 break;
3469
3470                         if (port->target_devid != NULL) {
3471                                 sbuf_printf(sb, "\t<target>");
3472                                 ctl_id_sbuf(port->target_devid, sb);
3473                                 sbuf_printf(sb, "</target>\n");
3474                         }
3475
3476                         if (port->port_devid != NULL) {
3477                                 sbuf_printf(sb, "\t<port>");
3478                                 ctl_id_sbuf(port->port_devid, sb);
3479                                 sbuf_printf(sb, "</port>\n");
3480                         }
3481
3482                         if (port->port_info != NULL) {
3483                                 retval = port->port_info(port->onoff_arg, sb);
3484                                 if (retval != 0)
3485                                         break;
3486                         }
3487                         STAILQ_FOREACH(opt, &port->options, links) {
3488                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3489                                     opt->name, opt->value, opt->name);
3490                                 if (retval != 0)
3491                                         break;
3492                         }
3493
3494                         if (port->lun_map != NULL) {
3495                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3496                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3497                                         plun = ctl_lun_map_from_port(port, j);
3498                                         if (plun >= CTL_MAX_LUNS)
3499                                                 continue;
3500                                         sbuf_printf(sb,
3501                                             "\t<lun id=\"%u\">%u</lun>\n",
3502                                             j, plun);
3503                                 }
3504                         }
3505
3506                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3507                                 if (port->wwpn_iid[j].in_use == 0 ||
3508                                     (port->wwpn_iid[j].wwpn == 0 &&
3509                                      port->wwpn_iid[j].name == NULL))
3510                                         continue;
3511
3512                                 if (port->wwpn_iid[j].name != NULL)
3513                                         retval = sbuf_printf(sb,
3514                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3515                                             j, port->wwpn_iid[j].name);
3516                                 else
3517                                         retval = sbuf_printf(sb,
3518                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3519                                             j, port->wwpn_iid[j].wwpn);
3520                                 if (retval != 0)
3521                                         break;
3522                         }
3523                         if (retval != 0)
3524                                 break;
3525
3526                         retval = sbuf_printf(sb, "</targ_port>\n");
3527                         if (retval != 0)
3528                                 break;
3529                 }
3530                 mtx_unlock(&softc->ctl_lock);
3531
3532                 if ((retval != 0)
3533                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3534                         retval = 0;
3535                         sbuf_delete(sb);
3536                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3537                         snprintf(list->error_str, sizeof(list->error_str),
3538                                  "Out of space, %d bytes is too small",
3539                                  list->alloc_len);
3540                         break;
3541                 }
3542
3543                 sbuf_finish(sb);
3544
3545                 retval = copyout(sbuf_data(sb), list->lun_xml,
3546                                  sbuf_len(sb) + 1);
3547
3548                 list->fill_len = sbuf_len(sb) + 1;
3549                 list->status = CTL_LUN_LIST_OK;
3550                 sbuf_delete(sb);
3551                 break;
3552         }
3553         case CTL_LUN_MAP: {
3554                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3555                 struct ctl_port *port;
3556
3557                 mtx_lock(&softc->ctl_lock);
3558                 if (lm->port >= CTL_MAX_PORTS ||
3559                     (port = softc->ctl_ports[lm->port]) == NULL) {
3560                         mtx_unlock(&softc->ctl_lock);
3561                         return (ENXIO);
3562                 }
3563                 if (lm->plun < CTL_MAX_LUNS) {
3564                         if (lm->lun == UINT32_MAX)
3565                                 retval = ctl_lun_map_unset(port, lm->plun);
3566                         else if (lm->lun < CTL_MAX_LUNS &&
3567                             softc->ctl_luns[lm->lun] != NULL)
3568                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3569                         else {
3570                                 mtx_unlock(&softc->ctl_lock);
3571                                 return (ENXIO);
3572                         }
3573                 } else if (lm->plun == UINT32_MAX) {
3574                         if (lm->lun == UINT32_MAX)
3575                                 retval = ctl_lun_map_deinit(port);
3576                         else
3577                                 retval = ctl_lun_map_init(port);
3578                 } else {
3579                         mtx_unlock(&softc->ctl_lock);
3580                         return (ENXIO);
3581                 }
3582                 mtx_unlock(&softc->ctl_lock);
3583                 break;
3584         }
3585         default: {
3586                 /* XXX KDM should we fix this? */
3587 #if 0
3588                 struct ctl_backend_driver *backend;
3589                 unsigned int type;
3590                 int found;
3591
3592                 found = 0;
3593
3594                 /*
3595                  * We encode the backend type as the ioctl type for backend
3596                  * ioctls.  So parse it out here, and then search for a
3597                  * backend of this type.
3598                  */
3599                 type = _IOC_TYPE(cmd);
3600
3601                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3602                         if (backend->type == type) {
3603                                 found = 1;
3604                                 break;
3605                         }
3606                 }
3607                 if (found == 0) {
3608                         printf("ctl: unknown ioctl command %#lx or backend "
3609                                "%d\n", cmd, type);
3610                         retval = EINVAL;
3611                         break;
3612                 }
3613                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3614 #endif
3615                 retval = ENOTTY;
3616                 break;
3617         }
3618         }
3619         return (retval);
3620 }
3621
3622 uint32_t
3623 ctl_get_initindex(struct ctl_nexus *nexus)
3624 {
3625         if (nexus->targ_port < CTL_MAX_PORTS)
3626                 return (nexus->initid.id +
3627                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3628         else
3629                 return (nexus->initid.id +
3630                        ((nexus->targ_port - CTL_MAX_PORTS) *
3631                         CTL_MAX_INIT_PER_PORT));
3632 }
3633
3634 uint32_t
3635 ctl_get_resindex(struct ctl_nexus *nexus)
3636 {
3637         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3638 }
3639
3640 uint32_t
3641 ctl_port_idx(int port_num)
3642 {
3643         if (port_num < CTL_MAX_PORTS)
3644                 return(port_num);
3645         else
3646                 return(port_num - CTL_MAX_PORTS);
3647 }
3648
3649 int
3650 ctl_lun_map_init(struct ctl_port *port)
3651 {
3652         uint32_t i;
3653
3654         if (port->lun_map == NULL)
3655                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3656                     M_CTL, M_NOWAIT);
3657         if (port->lun_map == NULL)
3658                 return (ENOMEM);
3659         for (i = 0; i < CTL_MAX_LUNS; i++)
3660                 port->lun_map[i] = UINT32_MAX;
3661         return (0);
3662 }
3663
3664 int
3665 ctl_lun_map_deinit(struct ctl_port *port)
3666 {
3667
3668         if (port->lun_map == NULL)
3669                 return (0);
3670         free(port->lun_map, M_CTL);
3671         port->lun_map = NULL;
3672         return (0);
3673 }
3674
3675 int
3676 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3677 {
3678         int status;
3679
3680         if (port->lun_map == NULL) {
3681                 status = ctl_lun_map_init(port);
3682                 if (status != 0)
3683                         return (status);
3684         }
3685         port->lun_map[plun] = glun;
3686         return (0);
3687 }
3688
3689 int
3690 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3691 {
3692
3693         if (port->lun_map == NULL)
3694                 return (0);
3695         port->lun_map[plun] = UINT32_MAX;
3696         return (0);
3697 }
3698
3699 int
3700 ctl_lun_map_unsetg(struct ctl_port *port, uint32_t glun)
3701 {
3702         int i;
3703
3704         if (port->lun_map == NULL)
3705                 return (0);
3706         for (i = 0; i < CTL_MAX_LUNS; i++) {
3707                 if (port->lun_map[i] == glun)
3708                         port->lun_map[i] = UINT32_MAX;
3709         }
3710         return (0);
3711 }
3712
3713 uint32_t
3714 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3715 {
3716
3717         if (port == NULL)
3718                 return (UINT32_MAX);
3719         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3720                 return (lun_id);
3721         return (port->lun_map[lun_id]);
3722 }
3723
3724 uint32_t
3725 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3726 {
3727         uint32_t i;
3728
3729         if (port == NULL)
3730                 return (UINT32_MAX);
3731         if (port->lun_map == NULL)
3732                 return (lun_id);
3733         for (i = 0; i < CTL_MAX_LUNS; i++) {
3734                 if (port->lun_map[i] == lun_id)
3735                         return (i);
3736         }
3737         return (UINT32_MAX);
3738 }
3739
3740 static struct ctl_port *
3741 ctl_io_port(struct ctl_io_hdr *io_hdr)
3742 {
3743         int port_num;
3744
3745         port_num = io_hdr->nexus.targ_port;
3746         return (control_softc->ctl_ports[ctl_port_idx(port_num)]);
3747 }
3748
3749 /*
3750  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3751  * that are a power of 2.
3752  */
3753 int
3754 ctl_ffz(uint32_t *mask, uint32_t size)
3755 {
3756         uint32_t num_chunks, num_pieces;
3757         int i, j;
3758
3759         num_chunks = (size >> 5);
3760         if (num_chunks == 0)
3761                 num_chunks++;
3762         num_pieces = MIN((sizeof(uint32_t) * 8), size);
3763
3764         for (i = 0; i < num_chunks; i++) {
3765                 for (j = 0; j < num_pieces; j++) {
3766                         if ((mask[i] & (1 << j)) == 0)
3767                                 return ((i << 5) + j);
3768                 }
3769         }
3770
3771         return (-1);
3772 }
3773
3774 int
3775 ctl_set_mask(uint32_t *mask, uint32_t bit)
3776 {
3777         uint32_t chunk, piece;
3778
3779         chunk = bit >> 5;
3780         piece = bit % (sizeof(uint32_t) * 8);
3781
3782         if ((mask[chunk] & (1 << piece)) != 0)
3783                 return (-1);
3784         else
3785                 mask[chunk] |= (1 << piece);
3786
3787         return (0);
3788 }
3789
3790 int
3791 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3792 {
3793         uint32_t chunk, piece;
3794
3795         chunk = bit >> 5;
3796         piece = bit % (sizeof(uint32_t) * 8);
3797
3798         if ((mask[chunk] & (1 << piece)) == 0)
3799                 return (-1);
3800         else
3801                 mask[chunk] &= ~(1 << piece);
3802
3803         return (0);
3804 }
3805
3806 int
3807 ctl_is_set(uint32_t *mask, uint32_t bit)
3808 {
3809         uint32_t chunk, piece;
3810
3811         chunk = bit >> 5;
3812         piece = bit % (sizeof(uint32_t) * 8);
3813
3814         if ((mask[chunk] & (1 << piece)) == 0)
3815                 return (0);
3816         else
3817                 return (1);
3818 }
3819
3820 static uint64_t
3821 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3822 {
3823         uint64_t *t;
3824
3825         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3826         if (t == NULL)
3827                 return (0);
3828         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3829 }
3830
3831 static void
3832 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3833 {
3834         uint64_t *t;
3835
3836         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3837         if (t == NULL)
3838                 return;
3839         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3840 }
3841
3842 static void
3843 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3844 {
3845         uint64_t *p;
3846         u_int i;
3847
3848         i = residx/CTL_MAX_INIT_PER_PORT;
3849         if (lun->pr_keys[i] != NULL)
3850                 return;
3851         mtx_unlock(&lun->lun_lock);
3852         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3853             M_WAITOK | M_ZERO);
3854         mtx_lock(&lun->lun_lock);
3855         if (lun->pr_keys[i] == NULL)
3856                 lun->pr_keys[i] = p;
3857         else
3858                 free(p, M_CTL);
3859 }
3860
3861 static void
3862 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3863 {
3864         uint64_t *t;
3865
3866         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3867         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3868         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3869 }
3870
3871 /*
3872  * ctl_softc, pool_name, total_ctl_io are passed in.
3873  * npool is passed out.
3874  */
3875 int
3876 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3877                 uint32_t total_ctl_io, void **npool)
3878 {
3879 #ifdef IO_POOLS
3880         struct ctl_io_pool *pool;
3881
3882         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3883                                             M_NOWAIT | M_ZERO);
3884         if (pool == NULL)
3885                 return (ENOMEM);
3886
3887         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3888         pool->ctl_softc = ctl_softc;
3889         pool->zone = uma_zsecond_create(pool->name, NULL,
3890             NULL, NULL, NULL, ctl_softc->io_zone);
3891         /* uma_prealloc(pool->zone, total_ctl_io); */
3892
3893         *npool = pool;
3894 #else
3895         *npool = ctl_softc->io_zone;
3896 #endif
3897         return (0);
3898 }
3899
3900 void
3901 ctl_pool_free(struct ctl_io_pool *pool)
3902 {
3903
3904         if (pool == NULL)
3905                 return;
3906
3907 #ifdef IO_POOLS
3908         uma_zdestroy(pool->zone);
3909         free(pool, M_CTL);
3910 #endif
3911 }
3912
3913 union ctl_io *
3914 ctl_alloc_io(void *pool_ref)
3915 {
3916         union ctl_io *io;
3917 #ifdef IO_POOLS
3918         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3919
3920         io = uma_zalloc(pool->zone, M_WAITOK);
3921 #else
3922         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3923 #endif
3924         if (io != NULL)
3925                 io->io_hdr.pool = pool_ref;
3926         return (io);
3927 }
3928
3929 union ctl_io *
3930 ctl_alloc_io_nowait(void *pool_ref)
3931 {
3932         union ctl_io *io;
3933 #ifdef IO_POOLS
3934         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3935
3936         io = uma_zalloc(pool->zone, M_NOWAIT);
3937 #else
3938         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3939 #endif
3940         if (io != NULL)
3941                 io->io_hdr.pool = pool_ref;
3942         return (io);
3943 }
3944
3945 void
3946 ctl_free_io(union ctl_io *io)
3947 {
3948 #ifdef IO_POOLS
3949         struct ctl_io_pool *pool;
3950 #endif
3951
3952         if (io == NULL)
3953                 return;
3954
3955 #ifdef IO_POOLS
3956         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3957         uma_zfree(pool->zone, io);
3958 #else
3959         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3960 #endif
3961 }
3962
3963 void
3964 ctl_zero_io(union ctl_io *io)
3965 {
3966         void *pool_ref;
3967
3968         if (io == NULL)
3969                 return;
3970
3971         /*
3972          * May need to preserve linked list pointers at some point too.
3973          */
3974         pool_ref = io->io_hdr.pool;
3975         memset(io, 0, sizeof(*io));
3976         io->io_hdr.pool = pool_ref;
3977 }
3978
3979 /*
3980  * This routine is currently used for internal copies of ctl_ios that need
3981  * to persist for some reason after we've already returned status to the
3982  * FETD.  (Thus the flag set.)
3983  *
3984  * XXX XXX
3985  * Note that this makes a blind copy of all fields in the ctl_io, except
3986  * for the pool reference.  This includes any memory that has been
3987  * allocated!  That memory will no longer be valid after done has been
3988  * called, so this would be VERY DANGEROUS for command that actually does
3989  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3990  * start and stop commands, which don't transfer any data, so this is not a
3991  * problem.  If it is used for anything else, the caller would also need to
3992  * allocate data buffer space and this routine would need to be modified to
3993  * copy the data buffer(s) as well.
3994  */
3995 void
3996 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3997 {
3998         void *pool_ref;
3999
4000         if ((src == NULL)
4001          || (dest == NULL))
4002                 return;
4003
4004         /*
4005          * May need to preserve linked list pointers at some point too.
4006          */
4007         pool_ref = dest->io_hdr.pool;
4008
4009         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
4010
4011         dest->io_hdr.pool = pool_ref;
4012         /*
4013          * We need to know that this is an internal copy, and doesn't need
4014          * to get passed back to the FETD that allocated it.
4015          */
4016         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
4017 }
4018
4019 int
4020 ctl_expand_number(const char *buf, uint64_t *num)
4021 {
4022         char *endptr;
4023         uint64_t number;
4024         unsigned shift;
4025
4026         number = strtoq(buf, &endptr, 0);
4027
4028         switch (tolower((unsigned char)*endptr)) {
4029         case 'e':
4030                 shift = 60;
4031                 break;
4032         case 'p':
4033                 shift = 50;
4034                 break;
4035         case 't':
4036                 shift = 40;
4037                 break;
4038         case 'g':
4039                 shift = 30;
4040                 break;
4041         case 'm':
4042                 shift = 20;
4043                 break;
4044         case 'k':
4045                 shift = 10;
4046                 break;
4047         case 'b':
4048         case '\0': /* No unit. */
4049                 *num = number;
4050                 return (0);
4051         default:
4052                 /* Unrecognized unit. */
4053                 return (-1);
4054         }
4055
4056         if ((number << shift) >> shift != number) {
4057                 /* Overflow */
4058                 return (-1);
4059         }
4060         *num = number << shift;
4061         return (0);
4062 }
4063
4064
4065 /*
4066  * This routine could be used in the future to load default and/or saved
4067  * mode page parameters for a particuar lun.
4068  */
4069 static int
4070 ctl_init_page_index(struct ctl_lun *lun)
4071 {
4072         int i;
4073         struct ctl_page_index *page_index;
4074         const char *value;
4075         uint64_t ival;
4076
4077         memcpy(&lun->mode_pages.index, page_index_template,
4078                sizeof(page_index_template));
4079
4080         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4081
4082                 page_index = &lun->mode_pages.index[i];
4083                 /*
4084                  * If this is a disk-only mode page, there's no point in
4085                  * setting it up.  For some pages, we have to have some
4086                  * basic information about the disk in order to calculate the
4087                  * mode page data.
4088                  */
4089                 if ((lun->be_lun->lun_type != T_DIRECT)
4090                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4091                         continue;
4092
4093                 switch (page_index->page_code & SMPH_PC_MASK) {
4094                 case SMS_RW_ERROR_RECOVERY_PAGE: {
4095                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4096                                 panic("subpage is incorrect!");
4097                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4098                                &rw_er_page_default,
4099                                sizeof(rw_er_page_default));
4100                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4101                                &rw_er_page_changeable,
4102                                sizeof(rw_er_page_changeable));
4103                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4104                                &rw_er_page_default,
4105                                sizeof(rw_er_page_default));
4106                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4107                                &rw_er_page_default,
4108                                sizeof(rw_er_page_default));
4109                         page_index->page_data =
4110                                 (uint8_t *)lun->mode_pages.rw_er_page;
4111                         break;
4112                 }
4113                 case SMS_FORMAT_DEVICE_PAGE: {
4114                         struct scsi_format_page *format_page;
4115
4116                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4117                                 panic("subpage is incorrect!");
4118
4119                         /*
4120                          * Sectors per track are set above.  Bytes per
4121                          * sector need to be set here on a per-LUN basis.
4122                          */
4123                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4124                                &format_page_default,
4125                                sizeof(format_page_default));
4126                         memcpy(&lun->mode_pages.format_page[
4127                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4128                                sizeof(format_page_changeable));
4129                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4130                                &format_page_default,
4131                                sizeof(format_page_default));
4132                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4133                                &format_page_default,
4134                                sizeof(format_page_default));
4135
4136                         format_page = &lun->mode_pages.format_page[
4137                                 CTL_PAGE_CURRENT];
4138                         scsi_ulto2b(lun->be_lun->blocksize,
4139                                     format_page->bytes_per_sector);
4140
4141                         format_page = &lun->mode_pages.format_page[
4142                                 CTL_PAGE_DEFAULT];
4143                         scsi_ulto2b(lun->be_lun->blocksize,
4144                                     format_page->bytes_per_sector);
4145
4146                         format_page = &lun->mode_pages.format_page[
4147                                 CTL_PAGE_SAVED];
4148                         scsi_ulto2b(lun->be_lun->blocksize,
4149                                     format_page->bytes_per_sector);
4150
4151                         page_index->page_data =
4152                                 (uint8_t *)lun->mode_pages.format_page;
4153                         break;
4154                 }
4155                 case SMS_RIGID_DISK_PAGE: {
4156                         struct scsi_rigid_disk_page *rigid_disk_page;
4157                         uint32_t sectors_per_cylinder;
4158                         uint64_t cylinders;
4159 #ifndef __XSCALE__
4160                         int shift;
4161 #endif /* !__XSCALE__ */
4162
4163                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4164                                 panic("invalid subpage value %d",
4165                                       page_index->subpage);
4166
4167                         /*
4168                          * Rotation rate and sectors per track are set
4169                          * above.  We calculate the cylinders here based on
4170                          * capacity.  Due to the number of heads and
4171                          * sectors per track we're using, smaller arrays
4172                          * may turn out to have 0 cylinders.  Linux and
4173                          * FreeBSD don't pay attention to these mode pages
4174                          * to figure out capacity, but Solaris does.  It
4175                          * seems to deal with 0 cylinders just fine, and
4176                          * works out a fake geometry based on the capacity.
4177                          */
4178                         memcpy(&lun->mode_pages.rigid_disk_page[
4179                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4180                                sizeof(rigid_disk_page_default));
4181                         memcpy(&lun->mode_pages.rigid_disk_page[
4182                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4183                                sizeof(rigid_disk_page_changeable));
4184
4185                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4186                                 CTL_DEFAULT_HEADS;
4187
4188                         /*
4189                          * The divide method here will be more accurate,
4190                          * probably, but results in floating point being
4191                          * used in the kernel on i386 (__udivdi3()).  On the
4192                          * XScale, though, __udivdi3() is implemented in
4193                          * software.
4194                          *
4195                          * The shift method for cylinder calculation is
4196                          * accurate if sectors_per_cylinder is a power of
4197                          * 2.  Otherwise it might be slightly off -- you
4198                          * might have a bit of a truncation problem.
4199                          */
4200 #ifdef  __XSCALE__
4201                         cylinders = (lun->be_lun->maxlba + 1) /
4202                                 sectors_per_cylinder;
4203 #else
4204                         for (shift = 31; shift > 0; shift--) {
4205                                 if (sectors_per_cylinder & (1 << shift))
4206                                         break;
4207                         }
4208                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4209 #endif
4210
4211                         /*
4212                          * We've basically got 3 bytes, or 24 bits for the
4213                          * cylinder size in the mode page.  If we're over,
4214                          * just round down to 2^24.
4215                          */
4216                         if (cylinders > 0xffffff)
4217                                 cylinders = 0xffffff;
4218
4219                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4220                                 CTL_PAGE_DEFAULT];
4221                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4222
4223                         if ((value = ctl_get_opt(&lun->be_lun->options,
4224                             "rpm")) != NULL) {
4225                                 scsi_ulto2b(strtol(value, NULL, 0),
4226                                      rigid_disk_page->rotation_rate);
4227                         }
4228
4229                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4230                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4231                                sizeof(rigid_disk_page_default));
4232                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4233                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4234                                sizeof(rigid_disk_page_default));
4235
4236                         page_index->page_data =
4237                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4238                         break;
4239                 }
4240                 case SMS_CACHING_PAGE: {
4241                         struct scsi_caching_page *caching_page;
4242
4243                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4244                                 panic("invalid subpage value %d",
4245                                       page_index->subpage);
4246                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4247                                &caching_page_default,
4248                                sizeof(caching_page_default));
4249                         memcpy(&lun->mode_pages.caching_page[
4250                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4251                                sizeof(caching_page_changeable));
4252                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4253                                &caching_page_default,
4254                                sizeof(caching_page_default));
4255                         caching_page = &lun->mode_pages.caching_page[
4256                             CTL_PAGE_SAVED];
4257                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4258                         if (value != NULL && strcmp(value, "off") == 0)
4259                                 caching_page->flags1 &= ~SCP_WCE;
4260                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4261                         if (value != NULL && strcmp(value, "off") == 0)
4262                                 caching_page->flags1 |= SCP_RCD;
4263                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4264                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4265                                sizeof(caching_page_default));
4266                         page_index->page_data =
4267                                 (uint8_t *)lun->mode_pages.caching_page;
4268                         break;
4269                 }
4270                 case SMS_CONTROL_MODE_PAGE: {
4271                         struct scsi_control_page *control_page;
4272
4273                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4274                                 panic("invalid subpage value %d",
4275                                       page_index->subpage);
4276
4277                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4278                                &control_page_default,
4279                                sizeof(control_page_default));
4280                         memcpy(&lun->mode_pages.control_page[
4281                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4282                                sizeof(control_page_changeable));
4283                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4284                                &control_page_default,
4285                                sizeof(control_page_default));
4286                         control_page = &lun->mode_pages.control_page[
4287                             CTL_PAGE_SAVED];
4288                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4289                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4290                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4291                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4292                         }
4293                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4294                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4295                                sizeof(control_page_default));
4296                         page_index->page_data =
4297                                 (uint8_t *)lun->mode_pages.control_page;
4298                         break;
4299
4300                 }
4301                 case SMS_INFO_EXCEPTIONS_PAGE: {
4302                         switch (page_index->subpage) {
4303                         case SMS_SUBPAGE_PAGE_0:
4304                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4305                                        &ie_page_default,
4306                                        sizeof(ie_page_default));
4307                                 memcpy(&lun->mode_pages.ie_page[
4308                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4309                                        sizeof(ie_page_changeable));
4310                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4311                                        &ie_page_default,
4312                                        sizeof(ie_page_default));
4313                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4314                                        &ie_page_default,
4315                                        sizeof(ie_page_default));
4316                                 page_index->page_data =
4317                                         (uint8_t *)lun->mode_pages.ie_page;
4318                                 break;
4319                         case 0x02: {
4320                                 struct ctl_logical_block_provisioning_page *page;
4321
4322                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4323                                        &lbp_page_default,
4324                                        sizeof(lbp_page_default));
4325                                 memcpy(&lun->mode_pages.lbp_page[
4326                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4327                                        sizeof(lbp_page_changeable));
4328                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4329                                        &lbp_page_default,
4330                                        sizeof(lbp_page_default));
4331                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4332                                 value = ctl_get_opt(&lun->be_lun->options,
4333                                     "avail-threshold");
4334                                 if (value != NULL &&
4335                                     ctl_expand_number(value, &ival) == 0) {
4336                                         page->descr[0].flags |= SLBPPD_ENABLED |
4337                                             SLBPPD_ARMING_DEC;
4338                                         if (lun->be_lun->blocksize)
4339                                                 ival /= lun->be_lun->blocksize;
4340                                         else
4341                                                 ival /= 512;
4342                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4343                                             page->descr[0].count);
4344                                 }
4345                                 value = ctl_get_opt(&lun->be_lun->options,
4346                                     "used-threshold");
4347                                 if (value != NULL &&
4348                                     ctl_expand_number(value, &ival) == 0) {
4349                                         page->descr[1].flags |= SLBPPD_ENABLED |
4350                                             SLBPPD_ARMING_INC;
4351                                         if (lun->be_lun->blocksize)
4352                                                 ival /= lun->be_lun->blocksize;
4353                                         else
4354                                                 ival /= 512;
4355                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4356                                             page->descr[1].count);
4357                                 }
4358                                 value = ctl_get_opt(&lun->be_lun->options,
4359                                     "pool-avail-threshold");
4360                                 if (value != NULL &&
4361                                     ctl_expand_number(value, &ival) == 0) {
4362                                         page->descr[2].flags |= SLBPPD_ENABLED |
4363                                             SLBPPD_ARMING_DEC;
4364                                         if (lun->be_lun->blocksize)
4365                                                 ival /= lun->be_lun->blocksize;
4366                                         else
4367                                                 ival /= 512;
4368                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4369                                             page->descr[2].count);
4370                                 }
4371                                 value = ctl_get_opt(&lun->be_lun->options,
4372                                     "pool-used-threshold");
4373                                 if (value != NULL &&
4374                                     ctl_expand_number(value, &ival) == 0) {
4375                                         page->descr[3].flags |= SLBPPD_ENABLED |
4376                                             SLBPPD_ARMING_INC;
4377                                         if (lun->be_lun->blocksize)
4378                                                 ival /= lun->be_lun->blocksize;
4379                                         else
4380                                                 ival /= 512;
4381                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4382                                             page->descr[3].count);
4383                                 }
4384                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4385                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4386                                        sizeof(lbp_page_default));
4387                                 page_index->page_data =
4388                                         (uint8_t *)lun->mode_pages.lbp_page;
4389                         }}
4390                         break;
4391                 }
4392                 case SMS_VENDOR_SPECIFIC_PAGE:{
4393                         switch (page_index->subpage) {
4394                         case DBGCNF_SUBPAGE_CODE: {
4395                                 struct copan_debugconf_subpage *current_page,
4396                                                                *saved_page;
4397
4398                                 memcpy(&lun->mode_pages.debugconf_subpage[
4399                                        CTL_PAGE_CURRENT],
4400                                        &debugconf_page_default,
4401                                        sizeof(debugconf_page_default));
4402                                 memcpy(&lun->mode_pages.debugconf_subpage[
4403                                        CTL_PAGE_CHANGEABLE],
4404                                        &debugconf_page_changeable,
4405                                        sizeof(debugconf_page_changeable));
4406                                 memcpy(&lun->mode_pages.debugconf_subpage[
4407                                        CTL_PAGE_DEFAULT],
4408                                        &debugconf_page_default,
4409                                        sizeof(debugconf_page_default));
4410                                 memcpy(&lun->mode_pages.debugconf_subpage[
4411                                        CTL_PAGE_SAVED],
4412                                        &debugconf_page_default,
4413                                        sizeof(debugconf_page_default));
4414                                 page_index->page_data =
4415                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4416
4417                                 current_page = (struct copan_debugconf_subpage *)
4418                                         (page_index->page_data +
4419                                          (page_index->page_len *
4420                                           CTL_PAGE_CURRENT));
4421                                 saved_page = (struct copan_debugconf_subpage *)
4422                                         (page_index->page_data +
4423                                          (page_index->page_len *
4424                                           CTL_PAGE_SAVED));
4425                                 break;
4426                         }
4427                         default:
4428                                 panic("invalid subpage value %d",
4429                                       page_index->subpage);
4430                                 break;
4431                         }
4432                         break;
4433                 }
4434                 default:
4435                         panic("invalid page value %d",
4436                               page_index->page_code & SMPH_PC_MASK);
4437                         break;
4438         }
4439         }
4440
4441         return (CTL_RETVAL_COMPLETE);
4442 }
4443
4444 static int
4445 ctl_init_log_page_index(struct ctl_lun *lun)
4446 {
4447         struct ctl_page_index *page_index;
4448         int i, j, k, prev;
4449
4450         memcpy(&lun->log_pages.index, log_page_index_template,
4451                sizeof(log_page_index_template));
4452
4453         prev = -1;
4454         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4455
4456                 page_index = &lun->log_pages.index[i];
4457                 /*
4458                  * If this is a disk-only mode page, there's no point in
4459                  * setting it up.  For some pages, we have to have some
4460                  * basic information about the disk in order to calculate the
4461                  * mode page data.
4462                  */
4463                 if ((lun->be_lun->lun_type != T_DIRECT)
4464                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4465                         continue;
4466
4467                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4468                      lun->backend->lun_attr == NULL)
4469                         continue;
4470
4471                 if (page_index->page_code != prev) {
4472                         lun->log_pages.pages_page[j] = page_index->page_code;
4473                         prev = page_index->page_code;
4474                         j++;
4475                 }
4476                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4477                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4478                 k++;
4479         }
4480         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4481         lun->log_pages.index[0].page_len = j;
4482         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4483         lun->log_pages.index[1].page_len = k * 2;
4484         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4485         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4486         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4487         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4488
4489         return (CTL_RETVAL_COMPLETE);
4490 }
4491
4492 static int
4493 hex2bin(const char *str, uint8_t *buf, int buf_size)
4494 {
4495         int i;
4496         u_char c;
4497
4498         memset(buf, 0, buf_size);
4499         while (isspace(str[0]))
4500                 str++;
4501         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4502                 str += 2;
4503         buf_size *= 2;
4504         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4505                 c = str[i];
4506                 if (isdigit(c))
4507                         c -= '0';
4508                 else if (isalpha(c))
4509                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4510                 else
4511                         break;
4512                 if (c >= 16)
4513                         break;
4514                 if ((i & 1) == 0)
4515                         buf[i / 2] |= (c << 4);
4516                 else
4517                         buf[i / 2] |= c;
4518         }
4519         return ((i + 1) / 2);
4520 }
4521
4522 /*
4523  * LUN allocation.
4524  *
4525  * Requirements:
4526  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4527  *   wants us to allocate the LUN and he can block.
4528  * - ctl_softc is always set
4529  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4530  *
4531  * Returns 0 for success, non-zero (errno) for failure.
4532  */
4533 static int
4534 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4535               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4536 {
4537         struct ctl_lun *nlun, *lun;
4538         struct scsi_vpd_id_descriptor *desc;
4539         struct scsi_vpd_id_t10 *t10id;
4540         const char *eui, *naa, *scsiname, *vendor, *value;
4541         int lun_number, i, lun_malloced;
4542         int devidlen, idlen1, idlen2 = 0, len;
4543
4544         if (be_lun == NULL)
4545                 return (EINVAL);
4546
4547         /*
4548          * We currently only support Direct Access or Processor LUN types.
4549          */
4550         switch (be_lun->lun_type) {
4551         case T_DIRECT:
4552                 break;
4553         case T_PROCESSOR:
4554                 break;
4555         case T_SEQUENTIAL:
4556         case T_CHANGER:
4557         default:
4558                 be_lun->lun_config_status(be_lun->be_lun,
4559                                           CTL_LUN_CONFIG_FAILURE);
4560                 break;
4561         }
4562         if (ctl_lun == NULL) {
4563                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4564                 lun_malloced = 1;
4565         } else {
4566                 lun_malloced = 0;
4567                 lun = ctl_lun;
4568         }
4569
4570         memset(lun, 0, sizeof(*lun));
4571         if (lun_malloced)
4572                 lun->flags = CTL_LUN_MALLOCED;
4573
4574         /* Generate LUN ID. */
4575         devidlen = max(CTL_DEVID_MIN_LEN,
4576             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4577         idlen1 = sizeof(*t10id) + devidlen;
4578         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4579         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4580         if (scsiname != NULL) {
4581                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4582                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4583         }
4584         eui = ctl_get_opt(&be_lun->options, "eui");
4585         if (eui != NULL) {
4586                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4587         }
4588         naa = ctl_get_opt(&be_lun->options, "naa");
4589         if (naa != NULL) {
4590                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4591         }
4592         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4593             M_CTL, M_WAITOK | M_ZERO);
4594         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4595         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4596         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4597         desc->length = idlen1;
4598         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4599         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4600         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4601                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4602         } else {
4603                 strncpy(t10id->vendor, vendor,
4604                     min(sizeof(t10id->vendor), strlen(vendor)));
4605         }
4606         strncpy((char *)t10id->vendor_spec_id,
4607             (char *)be_lun->device_id, devidlen);
4608         if (scsiname != NULL) {
4609                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4610                     desc->length);
4611                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4612                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4613                     SVPD_ID_TYPE_SCSI_NAME;
4614                 desc->length = idlen2;
4615                 strlcpy(desc->identifier, scsiname, idlen2);
4616         }
4617         if (eui != NULL) {
4618                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4619                     desc->length);
4620                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4621                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4622                     SVPD_ID_TYPE_EUI64;
4623                 desc->length = hex2bin(eui, desc->identifier, 16);
4624                 desc->length = desc->length > 12 ? 16 :
4625                     (desc->length > 8 ? 12 : 8);
4626                 len -= 16 - desc->length;
4627         }
4628         if (naa != NULL) {
4629                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4630                     desc->length);
4631                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4632                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4633                     SVPD_ID_TYPE_NAA;
4634                 desc->length = hex2bin(naa, desc->identifier, 16);
4635                 desc->length = desc->length > 8 ? 16 : 8;
4636                 len -= 16 - desc->length;
4637         }
4638         lun->lun_devid->len = len;
4639
4640         mtx_lock(&ctl_softc->ctl_lock);
4641         /*
4642          * See if the caller requested a particular LUN number.  If so, see
4643          * if it is available.  Otherwise, allocate the first available LUN.
4644          */
4645         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4646                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4647                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4648                         mtx_unlock(&ctl_softc->ctl_lock);
4649                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4650                                 printf("ctl: requested LUN ID %d is higher "
4651                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4652                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4653                         } else {
4654                                 /*
4655                                  * XXX KDM return an error, or just assign
4656                                  * another LUN ID in this case??
4657                                  */
4658                                 printf("ctl: requested LUN ID %d is already "
4659                                        "in use\n", be_lun->req_lun_id);
4660                         }
4661                         if (lun->flags & CTL_LUN_MALLOCED)
4662                                 free(lun, M_CTL);
4663                         be_lun->lun_config_status(be_lun->be_lun,
4664                                                   CTL_LUN_CONFIG_FAILURE);
4665                         return (ENOSPC);
4666                 }
4667                 lun_number = be_lun->req_lun_id;
4668         } else {
4669                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4670                 if (lun_number == -1) {
4671                         mtx_unlock(&ctl_softc->ctl_lock);
4672                         printf("ctl: can't allocate LUN on target %ju, out of "
4673                                "LUNs\n", (uintmax_t)target_id.id);
4674                         if (lun->flags & CTL_LUN_MALLOCED)
4675                                 free(lun, M_CTL);
4676                         be_lun->lun_config_status(be_lun->be_lun,
4677                                                   CTL_LUN_CONFIG_FAILURE);
4678                         return (ENOSPC);
4679                 }
4680         }
4681         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4682
4683         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4684         lun->target = target_id;
4685         lun->lun = lun_number;
4686         lun->be_lun = be_lun;
4687         /*
4688          * The processor LUN is always enabled.  Disk LUNs come on line
4689          * disabled, and must be enabled by the backend.
4690          */
4691         lun->flags |= CTL_LUN_DISABLED;
4692         lun->backend = be_lun->be;
4693         be_lun->ctl_lun = lun;
4694         be_lun->lun_id = lun_number;
4695         atomic_add_int(&be_lun->be->num_luns, 1);
4696         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4697                 lun->flags |= CTL_LUN_OFFLINE;
4698
4699         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4700                 lun->flags |= CTL_LUN_STOPPED;
4701
4702         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4703                 lun->flags |= CTL_LUN_INOPERABLE;
4704
4705         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4706                 lun->flags |= CTL_LUN_PRIMARY_SC;
4707
4708         value = ctl_get_opt(&be_lun->options, "readonly");
4709         if (value != NULL && strcmp(value, "on") == 0)
4710                 lun->flags |= CTL_LUN_READONLY;
4711
4712         lun->serseq = CTL_LUN_SERSEQ_OFF;
4713         if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4714                 lun->serseq = CTL_LUN_SERSEQ_READ;
4715         value = ctl_get_opt(&be_lun->options, "serseq");
4716         if (value != NULL && strcmp(value, "on") == 0)
4717                 lun->serseq = CTL_LUN_SERSEQ_ON;
4718         else if (value != NULL && strcmp(value, "read") == 0)
4719                 lun->serseq = CTL_LUN_SERSEQ_READ;
4720         else if (value != NULL && strcmp(value, "off") == 0)
4721                 lun->serseq = CTL_LUN_SERSEQ_OFF;
4722
4723         lun->ctl_softc = ctl_softc;
4724 #ifdef CTL_TIME_IO
4725         lun->last_busy = getsbinuptime();
4726 #endif
4727         TAILQ_INIT(&lun->ooa_queue);
4728         TAILQ_INIT(&lun->blocked_queue);
4729         STAILQ_INIT(&lun->error_list);
4730         ctl_tpc_lun_init(lun);
4731
4732         /*
4733          * Initialize the mode and log page index.
4734          */
4735         ctl_init_page_index(lun);
4736         ctl_init_log_page_index(lun);
4737
4738         /*
4739          * Now, before we insert this lun on the lun list, set the lun
4740          * inventory changed UA for all other luns.
4741          */
4742         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4743                 mtx_lock(&nlun->lun_lock);
4744                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4745                 mtx_unlock(&nlun->lun_lock);
4746         }
4747
4748         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4749
4750         ctl_softc->ctl_luns[lun_number] = lun;
4751
4752         ctl_softc->num_luns++;
4753
4754         /* Setup statistics gathering */
4755         lun->stats.device_type = be_lun->lun_type;
4756         lun->stats.lun_number = lun_number;
4757         if (lun->stats.device_type == T_DIRECT)
4758                 lun->stats.blocksize = be_lun->blocksize;
4759         else
4760                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4761         for (i = 0;i < CTL_MAX_PORTS;i++)
4762                 lun->stats.ports[i].targ_port = i;
4763
4764         mtx_unlock(&ctl_softc->ctl_lock);
4765
4766         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4767         return (0);
4768 }
4769
4770 /*
4771  * Delete a LUN.
4772  * Assumptions:
4773  * - LUN has already been marked invalid and any pending I/O has been taken
4774  *   care of.
4775  */
4776 static int
4777 ctl_free_lun(struct ctl_lun *lun)
4778 {
4779         struct ctl_softc *softc;
4780         struct ctl_port *port;
4781         struct ctl_lun *nlun;
4782         int i;
4783
4784         softc = lun->ctl_softc;
4785
4786         mtx_assert(&softc->ctl_lock, MA_OWNED);
4787
4788         STAILQ_FOREACH(port, &softc->port_list, links)
4789                 ctl_lun_map_unsetg(port, lun->lun);
4790
4791         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4792
4793         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4794
4795         softc->ctl_luns[lun->lun] = NULL;
4796
4797         if (!TAILQ_EMPTY(&lun->ooa_queue))
4798                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4799
4800         softc->num_luns--;
4801
4802         /*
4803          * Tell the backend to free resources, if this LUN has a backend.
4804          */
4805         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4806         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4807
4808         ctl_tpc_lun_shutdown(lun);
4809         mtx_destroy(&lun->lun_lock);
4810         free(lun->lun_devid, M_CTL);
4811         for (i = 0; i < CTL_MAX_PORTS; i++)
4812                 free(lun->pending_ua[i], M_CTL);
4813         for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4814                 free(lun->pr_keys[i], M_CTL);
4815         free(lun->write_buffer, M_CTL);
4816         if (lun->flags & CTL_LUN_MALLOCED)
4817                 free(lun, M_CTL);
4818
4819         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4820                 mtx_lock(&nlun->lun_lock);
4821                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4822                 mtx_unlock(&nlun->lun_lock);
4823         }
4824
4825         return (0);
4826 }
4827
4828 static void
4829 ctl_create_lun(struct ctl_be_lun *be_lun)
4830 {
4831         struct ctl_softc *softc;
4832
4833         softc = control_softc;
4834
4835         /*
4836          * ctl_alloc_lun() should handle all potential failure cases.
4837          */
4838         ctl_alloc_lun(softc, NULL, be_lun, softc->target);
4839 }
4840
4841 int
4842 ctl_add_lun(struct ctl_be_lun *be_lun)
4843 {
4844         struct ctl_softc *softc = control_softc;
4845
4846         mtx_lock(&softc->ctl_lock);
4847         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4848         mtx_unlock(&softc->ctl_lock);
4849         wakeup(&softc->pending_lun_queue);
4850
4851         return (0);
4852 }
4853
4854 int
4855 ctl_enable_lun(struct ctl_be_lun *be_lun)
4856 {
4857         struct ctl_softc *softc;
4858         struct ctl_port *port, *nport;
4859         struct ctl_lun *lun;
4860         int retval;
4861
4862         lun = (struct ctl_lun *)be_lun->ctl_lun;
4863         softc = lun->ctl_softc;
4864
4865         mtx_lock(&softc->ctl_lock);
4866         mtx_lock(&lun->lun_lock);
4867         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4868                 /*
4869                  * eh?  Why did we get called if the LUN is already
4870                  * enabled?
4871                  */
4872                 mtx_unlock(&lun->lun_lock);
4873                 mtx_unlock(&softc->ctl_lock);
4874                 return (0);
4875         }
4876         lun->flags &= ~CTL_LUN_DISABLED;
4877         mtx_unlock(&lun->lun_lock);
4878
4879         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4880                 nport = STAILQ_NEXT(port, links);
4881
4882                 /*
4883                  * Drop the lock while we call the FETD's enable routine.
4884                  * This can lead to a callback into CTL (at least in the
4885                  * case of the internal initiator frontend.
4886                  */
4887                 mtx_unlock(&softc->ctl_lock);
4888                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4889                 mtx_lock(&softc->ctl_lock);
4890                 if (retval != 0) {
4891                         printf("%s: FETD %s port %d returned error "
4892                                "%d for lun_enable on target %ju lun %jd\n",
4893                                __func__, port->port_name, port->targ_port, retval,
4894                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4895                 }
4896         }
4897
4898         mtx_unlock(&softc->ctl_lock);
4899
4900         return (0);
4901 }
4902
4903 int
4904 ctl_disable_lun(struct ctl_be_lun *be_lun)
4905 {
4906         struct ctl_softc *softc;
4907         struct ctl_port *port;
4908         struct ctl_lun *lun;
4909         int retval;
4910
4911         lun = (struct ctl_lun *)be_lun->ctl_lun;
4912         softc = lun->ctl_softc;
4913
4914         mtx_lock(&softc->ctl_lock);
4915         mtx_lock(&lun->lun_lock);
4916         if (lun->flags & CTL_LUN_DISABLED) {
4917                 mtx_unlock(&lun->lun_lock);
4918                 mtx_unlock(&softc->ctl_lock);
4919                 return (0);
4920         }
4921         lun->flags |= CTL_LUN_DISABLED;
4922         mtx_unlock(&lun->lun_lock);
4923
4924         STAILQ_FOREACH(port, &softc->port_list, links) {
4925                 mtx_unlock(&softc->ctl_lock);
4926                 /*
4927                  * Drop the lock before we call the frontend's disable
4928                  * routine, to avoid lock order reversals.
4929                  *
4930                  * XXX KDM what happens if the frontend list changes while
4931                  * we're traversing it?  It's unlikely, but should be handled.
4932                  */
4933                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4934                                          lun->lun);
4935                 mtx_lock(&softc->ctl_lock);
4936                 if (retval != 0) {
4937                         printf("%s: FETD %s port %d returned error "
4938                                "%d for lun_disable on target %ju lun %jd\n",
4939                                __func__, port->port_name, port->targ_port, retval,
4940                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4941                 }
4942         }
4943
4944         mtx_unlock(&softc->ctl_lock);
4945
4946         return (0);
4947 }
4948
4949 int
4950 ctl_start_lun(struct ctl_be_lun *be_lun)
4951 {
4952         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4953
4954         mtx_lock(&lun->lun_lock);
4955         lun->flags &= ~CTL_LUN_STOPPED;
4956         mtx_unlock(&lun->lun_lock);
4957         return (0);
4958 }
4959
4960 int
4961 ctl_stop_lun(struct ctl_be_lun *be_lun)
4962 {
4963         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4964
4965         mtx_lock(&lun->lun_lock);
4966         lun->flags |= CTL_LUN_STOPPED;
4967         mtx_unlock(&lun->lun_lock);
4968         return (0);
4969 }
4970
4971 int
4972 ctl_lun_offline(struct ctl_be_lun *be_lun)
4973 {
4974         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4975
4976         mtx_lock(&lun->lun_lock);
4977         lun->flags |= CTL_LUN_OFFLINE;
4978         mtx_unlock(&lun->lun_lock);
4979         return (0);
4980 }
4981
4982 int
4983 ctl_lun_online(struct ctl_be_lun *be_lun)
4984 {
4985         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4986
4987         mtx_lock(&lun->lun_lock);
4988         lun->flags &= ~CTL_LUN_OFFLINE;
4989         mtx_unlock(&lun->lun_lock);
4990         return (0);
4991 }
4992
4993 int
4994 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4995 {
4996         struct ctl_softc *softc;
4997         struct ctl_lun *lun;
4998
4999         lun = (struct ctl_lun *)be_lun->ctl_lun;
5000         softc = lun->ctl_softc;
5001
5002         mtx_lock(&lun->lun_lock);
5003
5004         /*
5005          * The LUN needs to be disabled before it can be marked invalid.
5006          */
5007         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5008                 mtx_unlock(&lun->lun_lock);
5009                 return (-1);
5010         }
5011         /*
5012          * Mark the LUN invalid.
5013          */
5014         lun->flags |= CTL_LUN_INVALID;
5015
5016         /*
5017          * If there is nothing in the OOA queue, go ahead and free the LUN.
5018          * If we have something in the OOA queue, we'll free it when the
5019          * last I/O completes.
5020          */
5021         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5022                 mtx_unlock(&lun->lun_lock);
5023                 mtx_lock(&softc->ctl_lock);
5024                 ctl_free_lun(lun);
5025                 mtx_unlock(&softc->ctl_lock);
5026         } else
5027                 mtx_unlock(&lun->lun_lock);
5028
5029         return (0);
5030 }
5031
5032 int
5033 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5034 {
5035         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5036
5037         mtx_lock(&lun->lun_lock);
5038         lun->flags |= CTL_LUN_INOPERABLE;
5039         mtx_unlock(&lun->lun_lock);
5040         return (0);
5041 }
5042
5043 int
5044 ctl_lun_operable(struct ctl_be_lun *be_lun)
5045 {
5046         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5047
5048         mtx_lock(&lun->lun_lock);
5049         lun->flags &= ~CTL_LUN_INOPERABLE;
5050         mtx_unlock(&lun->lun_lock);
5051         return (0);
5052 }
5053
5054 void
5055 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5056 {
5057         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5058
5059         mtx_lock(&lun->lun_lock);
5060         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5061         mtx_unlock(&lun->lun_lock);
5062 }
5063
5064 /*
5065  * Backend "memory move is complete" callback for requests that never
5066  * make it down to say RAIDCore's configuration code.
5067  */
5068 int
5069 ctl_config_move_done(union ctl_io *io)
5070 {
5071         int retval;
5072
5073         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5074         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5075             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5076
5077         if ((io->io_hdr.port_status != 0) &&
5078             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5079              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5080                 /*
5081                  * For hardware error sense keys, the sense key
5082                  * specific value is defined to be a retry count,
5083                  * but we use it to pass back an internal FETD
5084                  * error code.  XXX KDM  Hopefully the FETD is only
5085                  * using 16 bits for an error code, since that's
5086                  * all the space we have in the sks field.
5087                  */
5088                 ctl_set_internal_failure(&io->scsiio,
5089                                          /*sks_valid*/ 1,
5090                                          /*retry_count*/
5091                                          io->io_hdr.port_status);
5092         }
5093
5094         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5095             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5096              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5097             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5098                 /*
5099                  * XXX KDM just assuming a single pointer here, and not a
5100                  * S/G list.  If we start using S/G lists for config data,
5101                  * we'll need to know how to clean them up here as well.
5102                  */
5103                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5104                         free(io->scsiio.kern_data_ptr, M_CTL);
5105                 ctl_done(io);
5106                 retval = CTL_RETVAL_COMPLETE;
5107         } else {
5108                 /*
5109                  * XXX KDM now we need to continue data movement.  Some
5110                  * options:
5111                  * - call ctl_scsiio() again?  We don't do this for data
5112                  *   writes, because for those at least we know ahead of
5113                  *   time where the write will go and how long it is.  For
5114                  *   config writes, though, that information is largely
5115                  *   contained within the write itself, thus we need to
5116                  *   parse out the data again.
5117                  *
5118                  * - Call some other function once the data is in?
5119                  */
5120                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5121                         ctl_data_print(io);
5122
5123                 /*
5124                  * XXX KDM call ctl_scsiio() again for now, and check flag
5125                  * bits to see whether we're allocated or not.
5126                  */
5127                 retval = ctl_scsiio(&io->scsiio);
5128         }
5129         return (retval);
5130 }
5131
5132 /*
5133  * This gets called by a backend driver when it is done with a
5134  * data_submit method.
5135  */
5136 void
5137 ctl_data_submit_done(union ctl_io *io)
5138 {
5139         /*
5140          * If the IO_CONT flag is set, we need to call the supplied
5141          * function to continue processing the I/O, instead of completing
5142          * the I/O just yet.
5143          *
5144          * If there is an error, though, we don't want to keep processing.
5145          * Instead, just send status back to the initiator.
5146          */
5147         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5148             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5149             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5150              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5151                 io->scsiio.io_cont(io);
5152                 return;
5153         }
5154         ctl_done(io);
5155 }
5156
5157 /*
5158  * This gets called by a backend driver when it is done with a
5159  * configuration write.
5160  */
5161 void
5162 ctl_config_write_done(union ctl_io *io)
5163 {
5164         uint8_t *buf;
5165
5166         /*
5167          * If the IO_CONT flag is set, we need to call the supplied
5168          * function to continue processing the I/O, instead of completing
5169          * the I/O just yet.
5170          *
5171          * If there is an error, though, we don't want to keep processing.
5172          * Instead, just send status back to the initiator.
5173          */
5174         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5175             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5176             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5177              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5178                 io->scsiio.io_cont(io);
5179                 return;
5180         }
5181         /*
5182          * Since a configuration write can be done for commands that actually
5183          * have data allocated, like write buffer, and commands that have
5184          * no data, like start/stop unit, we need to check here.
5185          */
5186         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5187                 buf = io->scsiio.kern_data_ptr;
5188         else
5189                 buf = NULL;
5190         ctl_done(io);
5191         if (buf)
5192                 free(buf, M_CTL);
5193 }
5194
5195 void
5196 ctl_config_read_done(union ctl_io *io)
5197 {
5198         uint8_t *buf;
5199
5200         /*
5201          * If there is some error -- we are done, skip data transfer.
5202          */
5203         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5204             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5205              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5206                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5207                         buf = io->scsiio.kern_data_ptr;
5208                 else
5209                         buf = NULL;
5210                 ctl_done(io);
5211                 if (buf)
5212                         free(buf, M_CTL);
5213                 return;
5214         }
5215
5216         /*
5217          * If the IO_CONT flag is set, we need to call the supplied
5218          * function to continue processing the I/O, instead of completing
5219          * the I/O just yet.
5220          */
5221         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5222                 io->scsiio.io_cont(io);
5223                 return;
5224         }
5225
5226         ctl_datamove(io);
5227 }
5228
5229 /*
5230  * SCSI release command.
5231  */
5232 int
5233 ctl_scsi_release(struct ctl_scsiio *ctsio)
5234 {
5235         int length, longid, thirdparty_id, resv_id;
5236         struct ctl_lun *lun;
5237         uint32_t residx;
5238
5239         length = 0;
5240         resv_id = 0;
5241
5242         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5243
5244         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5245         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5246
5247         switch (ctsio->cdb[0]) {
5248         case RELEASE_10: {
5249                 struct scsi_release_10 *cdb;
5250
5251                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5252
5253                 if (cdb->byte2 & SR10_LONGID)
5254                         longid = 1;
5255                 else
5256                         thirdparty_id = cdb->thirdparty_id;
5257
5258                 resv_id = cdb->resv_id;
5259                 length = scsi_2btoul(cdb->length);
5260                 break;
5261         }
5262         }
5263
5264
5265         /*
5266          * XXX KDM right now, we only support LUN reservation.  We don't
5267          * support 3rd party reservations, or extent reservations, which
5268          * might actually need the parameter list.  If we've gotten this
5269          * far, we've got a LUN reservation.  Anything else got kicked out
5270          * above.  So, according to SPC, ignore the length.
5271          */
5272         length = 0;
5273
5274         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5275          && (length > 0)) {
5276                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5277                 ctsio->kern_data_len = length;
5278                 ctsio->kern_total_len = length;
5279                 ctsio->kern_data_resid = 0;
5280                 ctsio->kern_rel_offset = 0;
5281                 ctsio->kern_sg_entries = 0;
5282                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5283                 ctsio->be_move_done = ctl_config_move_done;
5284                 ctl_datamove((union ctl_io *)ctsio);
5285
5286                 return (CTL_RETVAL_COMPLETE);
5287         }
5288
5289         if (length > 0)
5290                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5291
5292         mtx_lock(&lun->lun_lock);
5293
5294         /*
5295          * According to SPC, it is not an error for an intiator to attempt
5296          * to release a reservation on a LUN that isn't reserved, or that
5297          * is reserved by another initiator.  The reservation can only be
5298          * released, though, by the initiator who made it or by one of
5299          * several reset type events.
5300          */
5301         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5302                         lun->flags &= ~CTL_LUN_RESERVED;
5303
5304         mtx_unlock(&lun->lun_lock);
5305
5306         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5307                 free(ctsio->kern_data_ptr, M_CTL);
5308                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5309         }
5310
5311         ctl_set_success(ctsio);
5312         ctl_done((union ctl_io *)ctsio);
5313         return (CTL_RETVAL_COMPLETE);
5314 }
5315
5316 int
5317 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5318 {
5319         int extent, thirdparty, longid;
5320         int resv_id, length;
5321         uint64_t thirdparty_id;
5322         struct ctl_lun *lun;
5323         uint32_t residx;
5324
5325         extent = 0;
5326         thirdparty = 0;
5327         longid = 0;
5328         resv_id = 0;
5329         length = 0;
5330         thirdparty_id = 0;
5331
5332         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5333
5334         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5335         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5336
5337         switch (ctsio->cdb[0]) {
5338         case RESERVE_10: {
5339                 struct scsi_reserve_10 *cdb;
5340
5341                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5342
5343                 if (cdb->byte2 & SR10_LONGID)
5344                         longid = 1;
5345                 else
5346                         thirdparty_id = cdb->thirdparty_id;
5347
5348                 resv_id = cdb->resv_id;
5349                 length = scsi_2btoul(cdb->length);
5350                 break;
5351         }
5352         }
5353
5354         /*
5355          * XXX KDM right now, we only support LUN reservation.  We don't
5356          * support 3rd party reservations, or extent reservations, which
5357          * might actually need the parameter list.  If we've gotten this
5358          * far, we've got a LUN reservation.  Anything else got kicked out
5359          * above.  So, according to SPC, ignore the length.
5360          */
5361         length = 0;
5362
5363         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5364          && (length > 0)) {
5365                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5366                 ctsio->kern_data_len = length;
5367                 ctsio->kern_total_len = length;
5368                 ctsio->kern_data_resid = 0;
5369                 ctsio->kern_rel_offset = 0;
5370                 ctsio->kern_sg_entries = 0;
5371                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5372                 ctsio->be_move_done = ctl_config_move_done;
5373                 ctl_datamove((union ctl_io *)ctsio);
5374
5375                 return (CTL_RETVAL_COMPLETE);
5376         }
5377
5378         if (length > 0)
5379                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5380
5381         mtx_lock(&lun->lun_lock);
5382         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5383                 ctl_set_reservation_conflict(ctsio);
5384                 goto bailout;
5385         }
5386
5387         lun->flags |= CTL_LUN_RESERVED;
5388         lun->res_idx = residx;
5389
5390         ctl_set_success(ctsio);
5391
5392 bailout:
5393         mtx_unlock(&lun->lun_lock);
5394
5395         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5396                 free(ctsio->kern_data_ptr, M_CTL);
5397                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5398         }
5399
5400         ctl_done((union ctl_io *)ctsio);
5401         return (CTL_RETVAL_COMPLETE);
5402 }
5403
5404 int
5405 ctl_start_stop(struct ctl_scsiio *ctsio)
5406 {
5407         struct scsi_start_stop_unit *cdb;
5408         struct ctl_lun *lun;
5409         int retval;
5410
5411         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5412
5413         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5414         retval = 0;
5415
5416         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5417
5418         /*
5419          * XXX KDM
5420          * We don't support the immediate bit on a stop unit.  In order to
5421          * do that, we would need to code up a way to know that a stop is
5422          * pending, and hold off any new commands until it completes, one
5423          * way or another.  Then we could accept or reject those commands
5424          * depending on its status.  We would almost need to do the reverse
5425          * of what we do below for an immediate start -- return the copy of
5426          * the ctl_io to the FETD with status to send to the host (and to
5427          * free the copy!) and then free the original I/O once the stop
5428          * actually completes.  That way, the OOA queue mechanism can work
5429          * to block commands that shouldn't proceed.  Another alternative
5430          * would be to put the copy in the queue in place of the original,
5431          * and return the original back to the caller.  That could be
5432          * slightly safer..
5433          */
5434         if ((cdb->byte2 & SSS_IMMED)
5435          && ((cdb->how & SSS_START) == 0)) {
5436                 ctl_set_invalid_field(ctsio,
5437                                       /*sks_valid*/ 1,
5438                                       /*command*/ 1,
5439                                       /*field*/ 1,
5440                                       /*bit_valid*/ 1,
5441                                       /*bit*/ 0);
5442                 ctl_done((union ctl_io *)ctsio);
5443                 return (CTL_RETVAL_COMPLETE);
5444         }
5445
5446         if ((lun->flags & CTL_LUN_PR_RESERVED)
5447          && ((cdb->how & SSS_START)==0)) {
5448                 uint32_t residx;
5449
5450                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5451                 if (ctl_get_prkey(lun, residx) == 0
5452                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5453
5454                         ctl_set_reservation_conflict(ctsio);
5455                         ctl_done((union ctl_io *)ctsio);
5456                         return (CTL_RETVAL_COMPLETE);
5457                 }
5458         }
5459
5460         /*
5461          * If there is no backend on this device, we can't start or stop
5462          * it.  In theory we shouldn't get any start/stop commands in the
5463          * first place at this level if the LUN doesn't have a backend.
5464          * That should get stopped by the command decode code.
5465          */
5466         if (lun->backend == NULL) {
5467                 ctl_set_invalid_opcode(ctsio);
5468                 ctl_done((union ctl_io *)ctsio);
5469                 return (CTL_RETVAL_COMPLETE);
5470         }
5471
5472         /*
5473          * XXX KDM Copan-specific offline behavior.
5474          * Figure out a reasonable way to port this?
5475          */
5476 #ifdef NEEDTOPORT
5477         mtx_lock(&lun->lun_lock);
5478
5479         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5480          && (lun->flags & CTL_LUN_OFFLINE)) {
5481                 /*
5482                  * If the LUN is offline, and the on/offline bit isn't set,
5483                  * reject the start or stop.  Otherwise, let it through.
5484                  */
5485                 mtx_unlock(&lun->lun_lock);
5486                 ctl_set_lun_not_ready(ctsio);
5487                 ctl_done((union ctl_io *)ctsio);
5488         } else {
5489                 mtx_unlock(&lun->lun_lock);
5490 #endif /* NEEDTOPORT */
5491                 /*
5492                  * This could be a start or a stop when we're online,
5493                  * or a stop/offline or start/online.  A start or stop when
5494                  * we're offline is covered in the case above.
5495                  */
5496                 /*
5497                  * In the non-immediate case, we send the request to
5498                  * the backend and return status to the user when
5499                  * it is done.
5500                  *
5501                  * In the immediate case, we allocate a new ctl_io
5502                  * to hold a copy of the request, and send that to
5503                  * the backend.  We then set good status on the
5504                  * user's request and return it immediately.
5505                  */
5506                 if (cdb->byte2 & SSS_IMMED) {
5507                         union ctl_io *new_io;
5508
5509                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5510                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5511                         retval = lun->backend->config_write(new_io);
5512                         ctl_set_success(ctsio);
5513                         ctl_done((union ctl_io *)ctsio);
5514                 } else {
5515                         retval = lun->backend->config_write(
5516                                 (union ctl_io *)ctsio);
5517                 }
5518 #ifdef NEEDTOPORT
5519         }
5520 #endif
5521         return (retval);
5522 }
5523
5524 /*
5525  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5526  * we don't really do anything with the LBA and length fields if the user
5527  * passes them in.  Instead we'll just flush out the cache for the entire
5528  * LUN.
5529  */
5530 int
5531 ctl_sync_cache(struct ctl_scsiio *ctsio)
5532 {
5533         struct ctl_lun *lun;
5534         struct ctl_softc *softc;
5535         uint64_t starting_lba;
5536         uint32_t block_count;
5537         int retval;
5538
5539         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5540
5541         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5542         softc = lun->ctl_softc;
5543         retval = 0;
5544
5545         switch (ctsio->cdb[0]) {
5546         case SYNCHRONIZE_CACHE: {
5547                 struct scsi_sync_cache *cdb;
5548                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5549
5550                 starting_lba = scsi_4btoul(cdb->begin_lba);
5551                 block_count = scsi_2btoul(cdb->lb_count);
5552                 break;
5553         }
5554         case SYNCHRONIZE_CACHE_16: {
5555                 struct scsi_sync_cache_16 *cdb;
5556                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5557
5558                 starting_lba = scsi_8btou64(cdb->begin_lba);
5559                 block_count = scsi_4btoul(cdb->lb_count);
5560                 break;
5561         }
5562         default:
5563                 ctl_set_invalid_opcode(ctsio);
5564                 ctl_done((union ctl_io *)ctsio);
5565                 goto bailout;
5566                 break; /* NOTREACHED */
5567         }
5568
5569         /*
5570          * We check the LBA and length, but don't do anything with them.
5571          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5572          * get flushed.  This check will just help satisfy anyone who wants
5573          * to see an error for an out of range LBA.
5574          */
5575         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5576                 ctl_set_lba_out_of_range(ctsio);
5577                 ctl_done((union ctl_io *)ctsio);
5578                 goto bailout;
5579         }
5580
5581         /*
5582          * If this LUN has no backend, we can't flush the cache anyway.
5583          */
5584         if (lun->backend == NULL) {
5585                 ctl_set_invalid_opcode(ctsio);
5586                 ctl_done((union ctl_io *)ctsio);
5587                 goto bailout;
5588         }
5589
5590         /*
5591          * Check to see whether we're configured to send the SYNCHRONIZE
5592          * CACHE command directly to the back end.
5593          */
5594         mtx_lock(&lun->lun_lock);
5595         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5596          && (++(lun->sync_count) >= lun->sync_interval)) {
5597                 lun->sync_count = 0;
5598                 mtx_unlock(&lun->lun_lock);
5599                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5600         } else {
5601                 mtx_unlock(&lun->lun_lock);
5602                 ctl_set_success(ctsio);
5603                 ctl_done((union ctl_io *)ctsio);
5604         }
5605
5606 bailout:
5607
5608         return (retval);
5609 }
5610
5611 int
5612 ctl_format(struct ctl_scsiio *ctsio)
5613 {
5614         struct scsi_format *cdb;
5615         struct ctl_lun *lun;
5616         int length, defect_list_len;
5617
5618         CTL_DEBUG_PRINT(("ctl_format\n"));
5619
5620         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5621
5622         cdb = (struct scsi_format *)ctsio->cdb;
5623
5624         length = 0;
5625         if (cdb->byte2 & SF_FMTDATA) {
5626                 if (cdb->byte2 & SF_LONGLIST)
5627                         length = sizeof(struct scsi_format_header_long);
5628                 else
5629                         length = sizeof(struct scsi_format_header_short);
5630         }
5631
5632         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5633          && (length > 0)) {
5634                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5635                 ctsio->kern_data_len = length;
5636                 ctsio->kern_total_len = length;
5637                 ctsio->kern_data_resid = 0;
5638                 ctsio->kern_rel_offset = 0;
5639                 ctsio->kern_sg_entries = 0;
5640                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5641                 ctsio->be_move_done = ctl_config_move_done;
5642                 ctl_datamove((union ctl_io *)ctsio);
5643
5644                 return (CTL_RETVAL_COMPLETE);
5645         }
5646
5647         defect_list_len = 0;
5648
5649         if (cdb->byte2 & SF_FMTDATA) {
5650                 if (cdb->byte2 & SF_LONGLIST) {
5651                         struct scsi_format_header_long *header;
5652
5653                         header = (struct scsi_format_header_long *)
5654                                 ctsio->kern_data_ptr;
5655
5656                         defect_list_len = scsi_4btoul(header->defect_list_len);
5657                         if (defect_list_len != 0) {
5658                                 ctl_set_invalid_field(ctsio,
5659                                                       /*sks_valid*/ 1,
5660                                                       /*command*/ 0,
5661                                                       /*field*/ 2,
5662                                                       /*bit_valid*/ 0,
5663                                                       /*bit*/ 0);
5664                                 goto bailout;
5665                         }
5666                 } else {
5667                         struct scsi_format_header_short *header;
5668
5669                         header = (struct scsi_format_header_short *)
5670                                 ctsio->kern_data_ptr;
5671
5672                         defect_list_len = scsi_2btoul(header->defect_list_len);
5673                         if (defect_list_len != 0) {
5674                                 ctl_set_invalid_field(ctsio,
5675                                                       /*sks_valid*/ 1,
5676                                                       /*command*/ 0,
5677                                                       /*field*/ 2,
5678                                                       /*bit_valid*/ 0,
5679                                                       /*bit*/ 0);
5680                                 goto bailout;
5681                         }
5682                 }
5683         }
5684
5685         /*
5686          * The format command will clear out the "Medium format corrupted"
5687          * status if set by the configuration code.  That status is really
5688          * just a way to notify the host that we have lost the media, and
5689          * get them to issue a command that will basically make them think
5690          * they're blowing away the media.
5691          */
5692         mtx_lock(&lun->lun_lock);
5693         lun->flags &= ~CTL_LUN_INOPERABLE;
5694         mtx_unlock(&lun->lun_lock);
5695
5696         ctl_set_success(ctsio);
5697 bailout:
5698
5699         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5700                 free(ctsio->kern_data_ptr, M_CTL);
5701                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5702         }
5703
5704         ctl_done((union ctl_io *)ctsio);
5705         return (CTL_RETVAL_COMPLETE);
5706 }
5707
5708 int
5709 ctl_read_buffer(struct ctl_scsiio *ctsio)
5710 {
5711         struct scsi_read_buffer *cdb;
5712         struct ctl_lun *lun;
5713         int buffer_offset, len;
5714         static uint8_t descr[4];
5715         static uint8_t echo_descr[4] = { 0 };
5716
5717         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5718
5719         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5720         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5721
5722         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5723             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5724             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5725                 ctl_set_invalid_field(ctsio,
5726                                       /*sks_valid*/ 1,
5727                                       /*command*/ 1,
5728                                       /*field*/ 1,
5729                                       /*bit_valid*/ 1,
5730                                       /*bit*/ 4);
5731                 ctl_done((union ctl_io *)ctsio);
5732                 return (CTL_RETVAL_COMPLETE);
5733         }
5734
5735         len = scsi_3btoul(cdb->length);
5736         buffer_offset = scsi_3btoul(cdb->offset);
5737
5738         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5739                 ctl_set_invalid_field(ctsio,
5740                                       /*sks_valid*/ 1,
5741                                       /*command*/ 1,
5742                                       /*field*/ 6,
5743                                       /*bit_valid*/ 0,
5744                                       /*bit*/ 0);
5745                 ctl_done((union ctl_io *)ctsio);
5746                 return (CTL_RETVAL_COMPLETE);
5747         }
5748
5749         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5750                 descr[0] = 0;
5751                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5752                 ctsio->kern_data_ptr = descr;
5753                 len = min(len, sizeof(descr));
5754         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5755                 ctsio->kern_data_ptr = echo_descr;
5756                 len = min(len, sizeof(echo_descr));
5757         } else {
5758                 if (lun->write_buffer == NULL) {
5759                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5760                             M_CTL, M_WAITOK);
5761                 }
5762                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5763         }
5764         ctsio->kern_data_len = len;
5765         ctsio->kern_total_len = len;
5766         ctsio->kern_data_resid = 0;
5767         ctsio->kern_rel_offset = 0;
5768         ctsio->kern_sg_entries = 0;
5769         ctl_set_success(ctsio);
5770         ctsio->be_move_done = ctl_config_move_done;
5771         ctl_datamove((union ctl_io *)ctsio);
5772         return (CTL_RETVAL_COMPLETE);
5773 }
5774
5775 int
5776 ctl_write_buffer(struct ctl_scsiio *ctsio)
5777 {
5778         struct scsi_write_buffer *cdb;
5779         struct ctl_lun *lun;
5780         int buffer_offset, len;
5781
5782         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5783
5784         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5785         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5786
5787         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5788                 ctl_set_invalid_field(ctsio,
5789                                       /*sks_valid*/ 1,
5790                                       /*command*/ 1,
5791                                       /*field*/ 1,
5792                                       /*bit_valid*/ 1,
5793                                       /*bit*/ 4);
5794                 ctl_done((union ctl_io *)ctsio);
5795                 return (CTL_RETVAL_COMPLETE);
5796         }
5797
5798         len = scsi_3btoul(cdb->length);
5799         buffer_offset = scsi_3btoul(cdb->offset);
5800
5801         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5802                 ctl_set_invalid_field(ctsio,
5803                                       /*sks_valid*/ 1,
5804                                       /*command*/ 1,
5805                                       /*field*/ 6,
5806                                       /*bit_valid*/ 0,
5807                                       /*bit*/ 0);
5808                 ctl_done((union ctl_io *)ctsio);
5809                 return (CTL_RETVAL_COMPLETE);
5810         }
5811
5812         /*
5813          * If we've got a kernel request that hasn't been malloced yet,
5814          * malloc it and tell the caller the data buffer is here.
5815          */
5816         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5817                 if (lun->write_buffer == NULL) {
5818                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5819                             M_CTL, M_WAITOK);
5820                 }
5821                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5822                 ctsio->kern_data_len = len;
5823                 ctsio->kern_total_len = len;
5824                 ctsio->kern_data_resid = 0;
5825                 ctsio->kern_rel_offset = 0;
5826                 ctsio->kern_sg_entries = 0;
5827                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5828                 ctsio->be_move_done = ctl_config_move_done;
5829                 ctl_datamove((union ctl_io *)ctsio);
5830
5831                 return (CTL_RETVAL_COMPLETE);
5832         }
5833
5834         ctl_set_success(ctsio);
5835         ctl_done((union ctl_io *)ctsio);
5836         return (CTL_RETVAL_COMPLETE);
5837 }
5838
5839 int
5840 ctl_write_same(struct ctl_scsiio *ctsio)
5841 {
5842         struct ctl_lun *lun;
5843         struct ctl_lba_len_flags *lbalen;
5844         uint64_t lba;
5845         uint32_t num_blocks;
5846         int len, retval;
5847         uint8_t byte2;
5848
5849         retval = CTL_RETVAL_COMPLETE;
5850
5851         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5852
5853         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5854
5855         switch (ctsio->cdb[0]) {
5856         case WRITE_SAME_10: {
5857                 struct scsi_write_same_10 *cdb;
5858
5859                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5860
5861                 lba = scsi_4btoul(cdb->addr);
5862                 num_blocks = scsi_2btoul(cdb->length);
5863                 byte2 = cdb->byte2;
5864                 break;
5865         }
5866         case WRITE_SAME_16: {
5867                 struct scsi_write_same_16 *cdb;
5868
5869                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5870
5871                 lba = scsi_8btou64(cdb->addr);
5872                 num_blocks = scsi_4btoul(cdb->length);
5873                 byte2 = cdb->byte2;
5874                 break;
5875         }
5876         default:
5877                 /*
5878                  * We got a command we don't support.  This shouldn't
5879                  * happen, commands should be filtered out above us.
5880                  */
5881                 ctl_set_invalid_opcode(ctsio);
5882                 ctl_done((union ctl_io *)ctsio);
5883
5884                 return (CTL_RETVAL_COMPLETE);
5885                 break; /* NOTREACHED */
5886         }
5887
5888         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5889         if ((byte2 & SWS_UNMAP) == 0 &&
5890             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5891                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5892                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5893                 ctl_done((union ctl_io *)ctsio);
5894                 return (CTL_RETVAL_COMPLETE);
5895         }
5896
5897         /*
5898          * The first check is to make sure we're in bounds, the second
5899          * check is to catch wrap-around problems.  If the lba + num blocks
5900          * is less than the lba, then we've wrapped around and the block
5901          * range is invalid anyway.
5902          */
5903         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5904          || ((lba + num_blocks) < lba)) {
5905                 ctl_set_lba_out_of_range(ctsio);
5906                 ctl_done((union ctl_io *)ctsio);
5907                 return (CTL_RETVAL_COMPLETE);
5908         }
5909
5910         /* Zero number of blocks means "to the last logical block" */
5911         if (num_blocks == 0) {
5912                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5913                         ctl_set_invalid_field(ctsio,
5914                                               /*sks_valid*/ 0,
5915                                               /*command*/ 1,
5916                                               /*field*/ 0,
5917                                               /*bit_valid*/ 0,
5918                                               /*bit*/ 0);
5919                         ctl_done((union ctl_io *)ctsio);
5920                         return (CTL_RETVAL_COMPLETE);
5921                 }
5922                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5923         }
5924
5925         len = lun->be_lun->blocksize;
5926
5927         /*
5928          * If we've got a kernel request that hasn't been malloced yet,
5929          * malloc it and tell the caller the data buffer is here.
5930          */
5931         if ((byte2 & SWS_NDOB) == 0 &&
5932             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5933                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5934                 ctsio->kern_data_len = len;
5935                 ctsio->kern_total_len = len;
5936                 ctsio->kern_data_resid = 0;
5937                 ctsio->kern_rel_offset = 0;
5938                 ctsio->kern_sg_entries = 0;
5939                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5940                 ctsio->be_move_done = ctl_config_move_done;
5941                 ctl_datamove((union ctl_io *)ctsio);
5942
5943                 return (CTL_RETVAL_COMPLETE);
5944         }
5945
5946         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5947         lbalen->lba = lba;
5948         lbalen->len = num_blocks;
5949         lbalen->flags = byte2;
5950         retval = lun->backend->config_write((union ctl_io *)ctsio);
5951
5952         return (retval);
5953 }
5954
5955 int
5956 ctl_unmap(struct ctl_scsiio *ctsio)
5957 {
5958         struct ctl_lun *lun;
5959         struct scsi_unmap *cdb;
5960         struct ctl_ptr_len_flags *ptrlen;
5961         struct scsi_unmap_header *hdr;
5962         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5963         uint64_t lba;
5964         uint32_t num_blocks;
5965         int len, retval;
5966         uint8_t byte2;
5967
5968         retval = CTL_RETVAL_COMPLETE;
5969
5970         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5971
5972         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5973         cdb = (struct scsi_unmap *)ctsio->cdb;
5974
5975         len = scsi_2btoul(cdb->length);
5976         byte2 = cdb->byte2;
5977
5978         /*
5979          * If we've got a kernel request that hasn't been malloced yet,
5980          * malloc it and tell the caller the data buffer is here.
5981          */
5982         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5983                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5984                 ctsio->kern_data_len = len;
5985                 ctsio->kern_total_len = len;
5986                 ctsio->kern_data_resid = 0;
5987                 ctsio->kern_rel_offset = 0;
5988                 ctsio->kern_sg_entries = 0;
5989                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5990                 ctsio->be_move_done = ctl_config_move_done;
5991                 ctl_datamove((union ctl_io *)ctsio);
5992
5993                 return (CTL_RETVAL_COMPLETE);
5994         }
5995
5996         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5997         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5998         if (len < sizeof (*hdr) ||
5999             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6000             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6001             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6002                 ctl_set_invalid_field(ctsio,
6003                                       /*sks_valid*/ 0,
6004                                       /*command*/ 0,
6005                                       /*field*/ 0,
6006                                       /*bit_valid*/ 0,
6007                                       /*bit*/ 0);
6008                 goto done;
6009         }
6010         len = scsi_2btoul(hdr->desc_length);
6011         buf = (struct scsi_unmap_desc *)(hdr + 1);
6012         end = buf + len / sizeof(*buf);
6013
6014         endnz = buf;
6015         for (range = buf; range < end; range++) {
6016                 lba = scsi_8btou64(range->lba);
6017                 num_blocks = scsi_4btoul(range->length);
6018                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6019                  || ((lba + num_blocks) < lba)) {
6020                         ctl_set_lba_out_of_range(ctsio);
6021                         ctl_done((union ctl_io *)ctsio);
6022                         return (CTL_RETVAL_COMPLETE);
6023                 }
6024                 if (num_blocks != 0)
6025                         endnz = range + 1;
6026         }
6027
6028         /*
6029          * Block backend can not handle zero last range.
6030          * Filter it out and return if there is nothing left.
6031          */
6032         len = (uint8_t *)endnz - (uint8_t *)buf;
6033         if (len == 0) {
6034                 ctl_set_success(ctsio);
6035                 goto done;
6036         }
6037
6038         mtx_lock(&lun->lun_lock);
6039         ptrlen = (struct ctl_ptr_len_flags *)
6040             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6041         ptrlen->ptr = (void *)buf;
6042         ptrlen->len = len;
6043         ptrlen->flags = byte2;
6044         ctl_check_blocked(lun);
6045         mtx_unlock(&lun->lun_lock);
6046
6047         retval = lun->backend->config_write((union ctl_io *)ctsio);
6048         return (retval);
6049
6050 done:
6051         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6052                 free(ctsio->kern_data_ptr, M_CTL);
6053                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6054         }
6055         ctl_done((union ctl_io *)ctsio);
6056         return (CTL_RETVAL_COMPLETE);
6057 }
6058
6059 /*
6060  * Note that this function currently doesn't actually do anything inside
6061  * CTL to enforce things if the DQue bit is turned on.
6062  *
6063  * Also note that this function can't be used in the default case, because
6064  * the DQue bit isn't set in the changeable mask for the control mode page
6065  * anyway.  This is just here as an example for how to implement a page
6066  * handler, and a placeholder in case we want to allow the user to turn
6067  * tagged queueing on and off.
6068  *
6069  * The D_SENSE bit handling is functional, however, and will turn
6070  * descriptor sense on and off for a given LUN.
6071  */
6072 int
6073 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6074                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6075 {
6076         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6077         struct ctl_lun *lun;
6078         int set_ua;
6079         uint32_t initidx;
6080
6081         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6082         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6083         set_ua = 0;
6084
6085         user_cp = (struct scsi_control_page *)page_ptr;
6086         current_cp = (struct scsi_control_page *)
6087                 (page_index->page_data + (page_index->page_len *
6088                 CTL_PAGE_CURRENT));
6089         saved_cp = (struct scsi_control_page *)
6090                 (page_index->page_data + (page_index->page_len *
6091                 CTL_PAGE_SAVED));
6092
6093         mtx_lock(&lun->lun_lock);
6094         if (((current_cp->rlec & SCP_DSENSE) == 0)
6095          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6096                 /*
6097                  * Descriptor sense is currently turned off and the user
6098                  * wants to turn it on.
6099                  */
6100                 current_cp->rlec |= SCP_DSENSE;
6101                 saved_cp->rlec |= SCP_DSENSE;
6102                 lun->flags |= CTL_LUN_SENSE_DESC;
6103                 set_ua = 1;
6104         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6105                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6106                 /*
6107                  * Descriptor sense is currently turned on, and the user
6108                  * wants to turn it off.
6109                  */
6110                 current_cp->rlec &= ~SCP_DSENSE;
6111                 saved_cp->rlec &= ~SCP_DSENSE;
6112                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6113                 set_ua = 1;
6114         }
6115         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6116             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6117                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6118                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6119                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6120                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6121                 set_ua = 1;
6122         }
6123         if ((current_cp->eca_and_aen & SCP_SWP) !=
6124             (user_cp->eca_and_aen & SCP_SWP)) {
6125                 current_cp->eca_and_aen &= ~SCP_SWP;
6126                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6127                 saved_cp->eca_and_aen &= ~SCP_SWP;
6128                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6129                 set_ua = 1;
6130         }
6131         if (set_ua != 0)
6132                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6133         mtx_unlock(&lun->lun_lock);
6134
6135         return (0);
6136 }
6137
6138 int
6139 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6140                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6141 {
6142         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6143         struct ctl_lun *lun;
6144         int set_ua;
6145         uint32_t initidx;
6146
6147         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6148         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6149         set_ua = 0;
6150
6151         user_cp = (struct scsi_caching_page *)page_ptr;
6152         current_cp = (struct scsi_caching_page *)
6153                 (page_index->page_data + (page_index->page_len *
6154                 CTL_PAGE_CURRENT));
6155         saved_cp = (struct scsi_caching_page *)
6156                 (page_index->page_data + (page_index->page_len *
6157                 CTL_PAGE_SAVED));
6158
6159         mtx_lock(&lun->lun_lock);
6160         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6161             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6162                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6163                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6164                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6165                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6166                 set_ua = 1;
6167         }
6168         if (set_ua != 0)
6169                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6170         mtx_unlock(&lun->lun_lock);
6171
6172         return (0);
6173 }
6174
6175 int
6176 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6177                                 struct ctl_page_index *page_index,
6178                                 uint8_t *page_ptr)
6179 {
6180         uint8_t *c;
6181         int i;
6182
6183         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6184         ctl_time_io_secs =
6185                 (c[0] << 8) |
6186                 (c[1] << 0) |
6187                 0;
6188         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6189         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6190         printf("page data:");
6191         for (i=0; i<8; i++)
6192                 printf(" %.2x",page_ptr[i]);
6193         printf("\n");
6194         return (0);
6195 }
6196
6197 int
6198 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6199                                struct ctl_page_index *page_index,
6200                                int pc)
6201 {
6202         struct copan_debugconf_subpage *page;
6203
6204         page = (struct copan_debugconf_subpage *)page_index->page_data +
6205                 (page_index->page_len * pc);
6206
6207         switch (pc) {
6208         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6209         case SMS_PAGE_CTRL_DEFAULT >> 6:
6210         case SMS_PAGE_CTRL_SAVED >> 6:
6211                 /*
6212                  * We don't update the changable or default bits for this page.
6213                  */
6214                 break;
6215         case SMS_PAGE_CTRL_CURRENT >> 6:
6216                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6217                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6218                 break;
6219         default:
6220 #ifdef NEEDTOPORT
6221                 EPRINT(0, "Invalid PC %d!!", pc);
6222 #endif /* NEEDTOPORT */
6223                 break;
6224         }
6225         return (0);
6226 }
6227
6228
6229 static int
6230 ctl_do_mode_select(union ctl_io *io)
6231 {
6232         struct scsi_mode_page_header *page_header;
6233         struct ctl_page_index *page_index;
6234         struct ctl_scsiio *ctsio;
6235         int control_dev, page_len;
6236         int page_len_offset, page_len_size;
6237         union ctl_modepage_info *modepage_info;
6238         struct ctl_lun *lun;
6239         int *len_left, *len_used;
6240         int retval, i;
6241
6242         ctsio = &io->scsiio;
6243         page_index = NULL;
6244         page_len = 0;
6245         retval = CTL_RETVAL_COMPLETE;
6246
6247         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6248
6249         if (lun->be_lun->lun_type != T_DIRECT)
6250                 control_dev = 1;
6251         else
6252                 control_dev = 0;
6253
6254         modepage_info = (union ctl_modepage_info *)
6255                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6256         len_left = &modepage_info->header.len_left;
6257         len_used = &modepage_info->header.len_used;
6258
6259 do_next_page:
6260
6261         page_header = (struct scsi_mode_page_header *)
6262                 (ctsio->kern_data_ptr + *len_used);
6263
6264         if (*len_left == 0) {
6265                 free(ctsio->kern_data_ptr, M_CTL);
6266                 ctl_set_success(ctsio);
6267                 ctl_done((union ctl_io *)ctsio);
6268                 return (CTL_RETVAL_COMPLETE);
6269         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6270
6271                 free(ctsio->kern_data_ptr, M_CTL);
6272                 ctl_set_param_len_error(ctsio);
6273                 ctl_done((union ctl_io *)ctsio);
6274                 return (CTL_RETVAL_COMPLETE);
6275
6276         } else if ((page_header->page_code & SMPH_SPF)
6277                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6278
6279                 free(ctsio->kern_data_ptr, M_CTL);
6280                 ctl_set_param_len_error(ctsio);
6281                 ctl_done((union ctl_io *)ctsio);
6282                 return (CTL_RETVAL_COMPLETE);
6283         }
6284
6285
6286         /*
6287          * XXX KDM should we do something with the block descriptor?
6288          */
6289         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6290
6291                 if ((control_dev != 0)
6292                  && (lun->mode_pages.index[i].page_flags &
6293                      CTL_PAGE_FLAG_DISK_ONLY))
6294                         continue;
6295
6296                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6297                     (page_header->page_code & SMPH_PC_MASK))
6298                         continue;
6299
6300                 /*
6301                  * If neither page has a subpage code, then we've got a
6302                  * match.
6303                  */
6304                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6305                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6306                         page_index = &lun->mode_pages.index[i];
6307                         page_len = page_header->page_length;
6308                         break;
6309                 }
6310
6311                 /*
6312                  * If both pages have subpages, then the subpage numbers
6313                  * have to match.
6314                  */
6315                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6316                   && (page_header->page_code & SMPH_SPF)) {
6317                         struct scsi_mode_page_header_sp *sph;
6318
6319                         sph = (struct scsi_mode_page_header_sp *)page_header;
6320
6321                         if (lun->mode_pages.index[i].subpage ==
6322                             sph->subpage) {
6323                                 page_index = &lun->mode_pages.index[i];
6324                                 page_len = scsi_2btoul(sph->page_length);
6325                                 break;
6326                         }
6327                 }
6328         }
6329
6330         /*
6331          * If we couldn't find the page, or if we don't have a mode select
6332          * handler for it, send back an error to the user.
6333          */
6334         if ((page_index == NULL)
6335          || (page_index->select_handler == NULL)) {
6336                 ctl_set_invalid_field(ctsio,
6337                                       /*sks_valid*/ 1,
6338                                       /*command*/ 0,
6339                                       /*field*/ *len_used,
6340                                       /*bit_valid*/ 0,
6341                                       /*bit*/ 0);
6342                 free(ctsio->kern_data_ptr, M_CTL);
6343                 ctl_done((union ctl_io *)ctsio);
6344                 return (CTL_RETVAL_COMPLETE);
6345         }
6346
6347         if (page_index->page_code & SMPH_SPF) {
6348                 page_len_offset = 2;
6349                 page_len_size = 2;
6350         } else {
6351                 page_len_size = 1;
6352                 page_len_offset = 1;
6353         }
6354
6355         /*
6356          * If the length the initiator gives us isn't the one we specify in
6357          * the mode page header, or if they didn't specify enough data in
6358          * the CDB to avoid truncating this page, kick out the request.
6359          */
6360         if ((page_len != (page_index->page_len - page_len_offset -
6361                           page_len_size))
6362          || (*len_left < page_index->page_len)) {
6363
6364
6365                 ctl_set_invalid_field(ctsio,
6366                                       /*sks_valid*/ 1,
6367                                       /*command*/ 0,
6368                                       /*field*/ *len_used + page_len_offset,
6369                                       /*bit_valid*/ 0,
6370                                       /*bit*/ 0);
6371                 free(ctsio->kern_data_ptr, M_CTL);
6372                 ctl_done((union ctl_io *)ctsio);
6373                 return (CTL_RETVAL_COMPLETE);
6374         }
6375
6376         /*
6377          * Run through the mode page, checking to make sure that the bits
6378          * the user changed are actually legal for him to change.
6379          */
6380         for (i = 0; i < page_index->page_len; i++) {
6381                 uint8_t *user_byte, *change_mask, *current_byte;
6382                 int bad_bit;
6383                 int j;
6384
6385                 user_byte = (uint8_t *)page_header + i;
6386                 change_mask = page_index->page_data +
6387                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6388                 current_byte = page_index->page_data +
6389                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6390
6391                 /*
6392                  * Check to see whether the user set any bits in this byte
6393                  * that he is not allowed to set.
6394                  */
6395                 if ((*user_byte & ~(*change_mask)) ==
6396                     (*current_byte & ~(*change_mask)))
6397                         continue;
6398
6399                 /*
6400                  * Go through bit by bit to determine which one is illegal.
6401                  */
6402                 bad_bit = 0;
6403                 for (j = 7; j >= 0; j--) {
6404                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6405                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6406                                 bad_bit = i;
6407                                 break;
6408                         }
6409                 }
6410                 ctl_set_invalid_field(ctsio,
6411                                       /*sks_valid*/ 1,
6412                                       /*command*/ 0,
6413                                       /*field*/ *len_used + i,
6414                                       /*bit_valid*/ 1,
6415                                       /*bit*/ bad_bit);
6416                 free(ctsio->kern_data_ptr, M_CTL);
6417                 ctl_done((union ctl_io *)ctsio);
6418                 return (CTL_RETVAL_COMPLETE);
6419         }
6420
6421         /*
6422          * Decrement these before we call the page handler, since we may
6423          * end up getting called back one way or another before the handler
6424          * returns to this context.
6425          */
6426         *len_left -= page_index->page_len;
6427         *len_used += page_index->page_len;
6428
6429         retval = page_index->select_handler(ctsio, page_index,
6430                                             (uint8_t *)page_header);
6431
6432         /*
6433          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6434          * wait until this queued command completes to finish processing
6435          * the mode page.  If it returns anything other than
6436          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6437          * already set the sense information, freed the data pointer, and
6438          * completed the io for us.
6439          */
6440         if (retval != CTL_RETVAL_COMPLETE)
6441                 goto bailout_no_done;
6442
6443         /*
6444          * If the initiator sent us more than one page, parse the next one.
6445          */
6446         if (*len_left > 0)
6447                 goto do_next_page;
6448
6449         ctl_set_success(ctsio);
6450         free(ctsio->kern_data_ptr, M_CTL);
6451         ctl_done((union ctl_io *)ctsio);
6452
6453 bailout_no_done:
6454
6455         return (CTL_RETVAL_COMPLETE);
6456
6457 }
6458
6459 int
6460 ctl_mode_select(struct ctl_scsiio *ctsio)
6461 {
6462         int param_len, pf, sp;
6463         int header_size, bd_len;
6464         int len_left, len_used;
6465         struct ctl_page_index *page_index;
6466         struct ctl_lun *lun;
6467         int control_dev, page_len;
6468         union ctl_modepage_info *modepage_info;
6469         int retval;
6470
6471         pf = 0;
6472         sp = 0;
6473         page_len = 0;
6474         len_used = 0;
6475         len_left = 0;
6476         retval = 0;
6477         bd_len = 0;
6478         page_index = NULL;
6479
6480         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6481
6482         if (lun->be_lun->lun_type != T_DIRECT)
6483                 control_dev = 1;
6484         else
6485                 control_dev = 0;
6486
6487         switch (ctsio->cdb[0]) {
6488         case MODE_SELECT_6: {
6489                 struct scsi_mode_select_6 *cdb;
6490
6491                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6492
6493                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6494                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6495
6496                 param_len = cdb->length;
6497                 header_size = sizeof(struct scsi_mode_header_6);
6498                 break;
6499         }
6500         case MODE_SELECT_10: {
6501                 struct scsi_mode_select_10 *cdb;
6502
6503                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6504
6505                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6506                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6507
6508                 param_len = scsi_2btoul(cdb->length);
6509                 header_size = sizeof(struct scsi_mode_header_10);
6510                 break;
6511         }
6512         default:
6513                 ctl_set_invalid_opcode(ctsio);
6514                 ctl_done((union ctl_io *)ctsio);
6515                 return (CTL_RETVAL_COMPLETE);
6516                 break; /* NOTREACHED */
6517         }
6518
6519         /*
6520          * From SPC-3:
6521          * "A parameter list length of zero indicates that the Data-Out Buffer
6522          * shall be empty. This condition shall not be considered as an error."
6523          */
6524         if (param_len == 0) {
6525                 ctl_set_success(ctsio);
6526                 ctl_done((union ctl_io *)ctsio);
6527                 return (CTL_RETVAL_COMPLETE);
6528         }
6529
6530         /*
6531          * Since we'll hit this the first time through, prior to
6532          * allocation, we don't need to free a data buffer here.
6533          */
6534         if (param_len < header_size) {
6535                 ctl_set_param_len_error(ctsio);
6536                 ctl_done((union ctl_io *)ctsio);
6537                 return (CTL_RETVAL_COMPLETE);
6538         }
6539
6540         /*
6541          * Allocate the data buffer and grab the user's data.  In theory,
6542          * we shouldn't have to sanity check the parameter list length here
6543          * because the maximum size is 64K.  We should be able to malloc
6544          * that much without too many problems.
6545          */
6546         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6547                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6548                 ctsio->kern_data_len = param_len;
6549                 ctsio->kern_total_len = param_len;
6550                 ctsio->kern_data_resid = 0;
6551                 ctsio->kern_rel_offset = 0;
6552                 ctsio->kern_sg_entries = 0;
6553                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6554                 ctsio->be_move_done = ctl_config_move_done;
6555                 ctl_datamove((union ctl_io *)ctsio);
6556
6557                 return (CTL_RETVAL_COMPLETE);
6558         }
6559
6560         switch (ctsio->cdb[0]) {
6561         case MODE_SELECT_6: {
6562                 struct scsi_mode_header_6 *mh6;
6563
6564                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6565                 bd_len = mh6->blk_desc_len;
6566                 break;
6567         }
6568         case MODE_SELECT_10: {
6569                 struct scsi_mode_header_10 *mh10;
6570
6571                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6572                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6573                 break;
6574         }
6575         default:
6576                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6577                 break;
6578         }
6579
6580         if (param_len < (header_size + bd_len)) {
6581                 free(ctsio->kern_data_ptr, M_CTL);
6582                 ctl_set_param_len_error(ctsio);
6583                 ctl_done((union ctl_io *)ctsio);
6584                 return (CTL_RETVAL_COMPLETE);
6585         }
6586
6587         /*
6588          * Set the IO_CONT flag, so that if this I/O gets passed to
6589          * ctl_config_write_done(), it'll get passed back to
6590          * ctl_do_mode_select() for further processing, or completion if
6591          * we're all done.
6592          */
6593         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6594         ctsio->io_cont = ctl_do_mode_select;
6595
6596         modepage_info = (union ctl_modepage_info *)
6597                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6598
6599         memset(modepage_info, 0, sizeof(*modepage_info));
6600
6601         len_left = param_len - header_size - bd_len;
6602         len_used = header_size + bd_len;
6603
6604         modepage_info->header.len_left = len_left;
6605         modepage_info->header.len_used = len_used;
6606
6607         return (ctl_do_mode_select((union ctl_io *)ctsio));
6608 }
6609
6610 int
6611 ctl_mode_sense(struct ctl_scsiio *ctsio)
6612 {
6613         struct ctl_lun *lun;
6614         int pc, page_code, dbd, llba, subpage;
6615         int alloc_len, page_len, header_len, total_len;
6616         struct scsi_mode_block_descr *block_desc;
6617         struct ctl_page_index *page_index;
6618         int control_dev;
6619
6620         dbd = 0;
6621         llba = 0;
6622         block_desc = NULL;
6623         page_index = NULL;
6624
6625         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6626
6627         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6628
6629         if (lun->be_lun->lun_type != T_DIRECT)
6630                 control_dev = 1;
6631         else
6632                 control_dev = 0;
6633
6634         switch (ctsio->cdb[0]) {
6635         case MODE_SENSE_6: {
6636                 struct scsi_mode_sense_6 *cdb;
6637
6638                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6639
6640                 header_len = sizeof(struct scsi_mode_hdr_6);
6641                 if (cdb->byte2 & SMS_DBD)
6642                         dbd = 1;
6643                 else
6644                         header_len += sizeof(struct scsi_mode_block_descr);
6645
6646                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6647                 page_code = cdb->page & SMS_PAGE_CODE;
6648                 subpage = cdb->subpage;
6649                 alloc_len = cdb->length;
6650                 break;
6651         }
6652         case MODE_SENSE_10: {
6653                 struct scsi_mode_sense_10 *cdb;
6654
6655                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6656
6657                 header_len = sizeof(struct scsi_mode_hdr_10);
6658
6659                 if (cdb->byte2 & SMS_DBD)
6660                         dbd = 1;
6661                 else
6662                         header_len += sizeof(struct scsi_mode_block_descr);
6663                 if (cdb->byte2 & SMS10_LLBAA)
6664                         llba = 1;
6665                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6666                 page_code = cdb->page & SMS_PAGE_CODE;
6667                 subpage = cdb->subpage;
6668                 alloc_len = scsi_2btoul(cdb->length);
6669                 break;
6670         }
6671         default:
6672                 ctl_set_invalid_opcode(ctsio);
6673                 ctl_done((union ctl_io *)ctsio);
6674                 return (CTL_RETVAL_COMPLETE);
6675                 break; /* NOTREACHED */
6676         }
6677
6678         /*
6679          * We have to make a first pass through to calculate the size of
6680          * the pages that match the user's query.  Then we allocate enough
6681          * memory to hold it, and actually copy the data into the buffer.
6682          */
6683         switch (page_code) {
6684         case SMS_ALL_PAGES_PAGE: {
6685                 int i;
6686
6687                 page_len = 0;
6688
6689                 /*
6690                  * At the moment, values other than 0 and 0xff here are
6691                  * reserved according to SPC-3.
6692                  */
6693                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6694                  && (subpage != SMS_SUBPAGE_ALL)) {
6695                         ctl_set_invalid_field(ctsio,
6696                                               /*sks_valid*/ 1,
6697                                               /*command*/ 1,
6698                                               /*field*/ 3,
6699                                               /*bit_valid*/ 0,
6700                                               /*bit*/ 0);
6701                         ctl_done((union ctl_io *)ctsio);
6702                         return (CTL_RETVAL_COMPLETE);
6703                 }
6704
6705                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6706                         if ((control_dev != 0)
6707                          && (lun->mode_pages.index[i].page_flags &
6708                              CTL_PAGE_FLAG_DISK_ONLY))
6709                                 continue;
6710
6711                         /*
6712                          * We don't use this subpage if the user didn't
6713                          * request all subpages.
6714                          */
6715                         if ((lun->mode_pages.index[i].subpage != 0)
6716                          && (subpage == SMS_SUBPAGE_PAGE_0))
6717                                 continue;
6718
6719 #if 0
6720                         printf("found page %#x len %d\n",
6721                                lun->mode_pages.index[i].page_code &
6722                                SMPH_PC_MASK,
6723                                lun->mode_pages.index[i].page_len);
6724 #endif
6725                         page_len += lun->mode_pages.index[i].page_len;
6726                 }
6727                 break;
6728         }
6729         default: {
6730                 int i;
6731
6732                 page_len = 0;
6733
6734                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6735                         /* Look for the right page code */
6736                         if ((lun->mode_pages.index[i].page_code &
6737                              SMPH_PC_MASK) != page_code)
6738                                 continue;
6739
6740                         /* Look for the right subpage or the subpage wildcard*/
6741                         if ((lun->mode_pages.index[i].subpage != subpage)
6742                          && (subpage != SMS_SUBPAGE_ALL))
6743                                 continue;
6744
6745                         /* Make sure the page is supported for this dev type */
6746                         if ((control_dev != 0)
6747                          && (lun->mode_pages.index[i].page_flags &
6748                              CTL_PAGE_FLAG_DISK_ONLY))
6749                                 continue;
6750
6751 #if 0
6752                         printf("found page %#x len %d\n",
6753                                lun->mode_pages.index[i].page_code &
6754                                SMPH_PC_MASK,
6755                                lun->mode_pages.index[i].page_len);
6756 #endif
6757
6758                         page_len += lun->mode_pages.index[i].page_len;
6759                 }
6760
6761                 if (page_len == 0) {
6762                         ctl_set_invalid_field(ctsio,
6763                                               /*sks_valid*/ 1,
6764                                               /*command*/ 1,
6765                                               /*field*/ 2,
6766                                               /*bit_valid*/ 1,
6767                                               /*bit*/ 5);
6768                         ctl_done((union ctl_io *)ctsio);
6769                         return (CTL_RETVAL_COMPLETE);
6770                 }
6771                 break;
6772         }
6773         }
6774
6775         total_len = header_len + page_len;
6776 #if 0
6777         printf("header_len = %d, page_len = %d, total_len = %d\n",
6778                header_len, page_len, total_len);
6779 #endif
6780
6781         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6782         ctsio->kern_sg_entries = 0;
6783         ctsio->kern_data_resid = 0;
6784         ctsio->kern_rel_offset = 0;
6785         if (total_len < alloc_len) {
6786                 ctsio->residual = alloc_len - total_len;
6787                 ctsio->kern_data_len = total_len;
6788                 ctsio->kern_total_len = total_len;
6789         } else {
6790                 ctsio->residual = 0;
6791                 ctsio->kern_data_len = alloc_len;
6792                 ctsio->kern_total_len = alloc_len;
6793         }
6794
6795         switch (ctsio->cdb[0]) {
6796         case MODE_SENSE_6: {
6797                 struct scsi_mode_hdr_6 *header;
6798
6799                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6800
6801                 header->datalen = MIN(total_len - 1, 254);
6802                 if (control_dev == 0) {
6803                         header->dev_specific = 0x10; /* DPOFUA */
6804                         if ((lun->flags & CTL_LUN_READONLY) ||
6805                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6806                             .eca_and_aen & SCP_SWP) != 0)
6807                                     header->dev_specific |= 0x80; /* WP */
6808                 }
6809                 if (dbd)
6810                         header->block_descr_len = 0;
6811                 else
6812                         header->block_descr_len =
6813                                 sizeof(struct scsi_mode_block_descr);
6814                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6815                 break;
6816         }
6817         case MODE_SENSE_10: {
6818                 struct scsi_mode_hdr_10 *header;
6819                 int datalen;
6820
6821                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6822
6823                 datalen = MIN(total_len - 2, 65533);
6824                 scsi_ulto2b(datalen, header->datalen);
6825                 if (control_dev == 0) {
6826                         header->dev_specific = 0x10; /* DPOFUA */
6827                         if ((lun->flags & CTL_LUN_READONLY) ||
6828                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6829                             .eca_and_aen & SCP_SWP) != 0)
6830                                     header->dev_specific |= 0x80; /* WP */
6831                 }
6832                 if (dbd)
6833                         scsi_ulto2b(0, header->block_descr_len);
6834                 else
6835                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6836                                     header->block_descr_len);
6837                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6838                 break;
6839         }
6840         default:
6841                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6842                 break; /* NOTREACHED */
6843         }
6844
6845         /*
6846          * If we've got a disk, use its blocksize in the block
6847          * descriptor.  Otherwise, just set it to 0.
6848          */
6849         if (dbd == 0) {
6850                 if (control_dev == 0)
6851                         scsi_ulto3b(lun->be_lun->blocksize,
6852                                     block_desc->block_len);
6853                 else
6854                         scsi_ulto3b(0, block_desc->block_len);
6855         }
6856
6857         switch (page_code) {
6858         case SMS_ALL_PAGES_PAGE: {
6859                 int i, data_used;
6860
6861                 data_used = header_len;
6862                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6863                         struct ctl_page_index *page_index;
6864
6865                         page_index = &lun->mode_pages.index[i];
6866
6867                         if ((control_dev != 0)
6868                          && (page_index->page_flags &
6869                             CTL_PAGE_FLAG_DISK_ONLY))
6870                                 continue;
6871
6872                         /*
6873                          * We don't use this subpage if the user didn't
6874                          * request all subpages.  We already checked (above)
6875                          * to make sure the user only specified a subpage
6876                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6877                          */
6878                         if ((page_index->subpage != 0)
6879                          && (subpage == SMS_SUBPAGE_PAGE_0))
6880                                 continue;
6881
6882                         /*
6883                          * Call the handler, if it exists, to update the
6884                          * page to the latest values.
6885                          */
6886                         if (page_index->sense_handler != NULL)
6887                                 page_index->sense_handler(ctsio, page_index,pc);
6888
6889                         memcpy(ctsio->kern_data_ptr + data_used,
6890                                page_index->page_data +
6891                                (page_index->page_len * pc),
6892                                page_index->page_len);
6893                         data_used += page_index->page_len;
6894                 }
6895                 break;
6896         }
6897         default: {
6898                 int i, data_used;
6899
6900                 data_used = header_len;
6901
6902                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6903                         struct ctl_page_index *page_index;
6904
6905                         page_index = &lun->mode_pages.index[i];
6906
6907                         /* Look for the right page code */
6908                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6909                                 continue;
6910
6911                         /* Look for the right subpage or the subpage wildcard*/
6912                         if ((page_index->subpage != subpage)
6913                          && (subpage != SMS_SUBPAGE_ALL))
6914                                 continue;
6915
6916                         /* Make sure the page is supported for this dev type */
6917                         if ((control_dev != 0)
6918                          && (page_index->page_flags &
6919                              CTL_PAGE_FLAG_DISK_ONLY))
6920                                 continue;
6921
6922                         /*
6923                          * Call the handler, if it exists, to update the
6924                          * page to the latest values.
6925                          */
6926                         if (page_index->sense_handler != NULL)
6927                                 page_index->sense_handler(ctsio, page_index,pc);
6928
6929                         memcpy(ctsio->kern_data_ptr + data_used,
6930                                page_index->page_data +
6931                                (page_index->page_len * pc),
6932                                page_index->page_len);
6933                         data_used += page_index->page_len;
6934                 }
6935                 break;
6936         }
6937         }
6938
6939         ctl_set_success(ctsio);
6940         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6941         ctsio->be_move_done = ctl_config_move_done;
6942         ctl_datamove((union ctl_io *)ctsio);
6943         return (CTL_RETVAL_COMPLETE);
6944 }
6945
6946 int
6947 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6948                                struct ctl_page_index *page_index,
6949                                int pc)
6950 {
6951         struct ctl_lun *lun;
6952         struct scsi_log_param_header *phdr;
6953         uint8_t *data;
6954         uint64_t val;
6955
6956         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6957         data = page_index->page_data;
6958
6959         if (lun->backend->lun_attr != NULL &&
6960             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6961              != UINT64_MAX) {
6962                 phdr = (struct scsi_log_param_header *)data;
6963                 scsi_ulto2b(0x0001, phdr->param_code);
6964                 phdr->param_control = SLP_LBIN | SLP_LP;
6965                 phdr->param_len = 8;
6966                 data = (uint8_t *)(phdr + 1);
6967                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6968                 data[4] = 0x02; /* per-pool */
6969                 data += phdr->param_len;
6970         }
6971
6972         if (lun->backend->lun_attr != NULL &&
6973             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6974              != UINT64_MAX) {
6975                 phdr = (struct scsi_log_param_header *)data;
6976                 scsi_ulto2b(0x0002, phdr->param_code);
6977                 phdr->param_control = SLP_LBIN | SLP_LP;
6978                 phdr->param_len = 8;
6979                 data = (uint8_t *)(phdr + 1);
6980                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6981                 data[4] = 0x01; /* per-LUN */
6982                 data += phdr->param_len;
6983         }
6984
6985         if (lun->backend->lun_attr != NULL &&
6986             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6987              != UINT64_MAX) {
6988                 phdr = (struct scsi_log_param_header *)data;
6989                 scsi_ulto2b(0x00f1, phdr->param_code);
6990                 phdr->param_control = SLP_LBIN | SLP_LP;
6991                 phdr->param_len = 8;
6992                 data = (uint8_t *)(phdr + 1);
6993                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6994                 data[4] = 0x02; /* per-pool */
6995                 data += phdr->param_len;
6996         }
6997
6998         if (lun->backend->lun_attr != NULL &&
6999             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7000              != UINT64_MAX) {
7001                 phdr = (struct scsi_log_param_header *)data;
7002                 scsi_ulto2b(0x00f2, phdr->param_code);
7003                 phdr->param_control = SLP_LBIN | SLP_LP;
7004                 phdr->param_len = 8;
7005                 data = (uint8_t *)(phdr + 1);
7006                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7007                 data[4] = 0x02; /* per-pool */
7008                 data += phdr->param_len;
7009         }
7010
7011         page_index->page_len = data - page_index->page_data;
7012         return (0);
7013 }
7014
7015 int
7016 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
7017                                struct ctl_page_index *page_index,
7018                                int pc)
7019 {
7020         struct ctl_lun *lun;
7021         struct stat_page *data;
7022         uint64_t rn, wn, rb, wb;
7023         struct bintime rt, wt;
7024         int i;
7025
7026         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7027         data = (struct stat_page *)page_index->page_data;
7028
7029         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
7030         data->sap.hdr.param_control = SLP_LBIN;
7031         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
7032             sizeof(struct scsi_log_param_header);
7033         rn = wn = rb = wb = 0;
7034         bintime_clear(&rt);
7035         bintime_clear(&wt);
7036         for (i = 0; i < CTL_MAX_PORTS; i++) {
7037                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
7038                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
7039                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
7040                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
7041                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
7042                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
7043         }
7044         scsi_u64to8b(rn, data->sap.read_num);
7045         scsi_u64to8b(wn, data->sap.write_num);
7046         if (lun->stats.blocksize > 0) {
7047                 scsi_u64to8b(wb / lun->stats.blocksize,
7048                     data->sap.recvieved_lba);
7049                 scsi_u64to8b(rb / lun->stats.blocksize,
7050                     data->sap.transmitted_lba);
7051         }
7052         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
7053             data->sap.read_int);
7054         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
7055             data->sap.write_int);
7056         scsi_u64to8b(0, data->sap.weighted_num);
7057         scsi_u64to8b(0, data->sap.weighted_int);
7058         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
7059         data->it.hdr.param_control = SLP_LBIN;
7060         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
7061             sizeof(struct scsi_log_param_header);
7062 #ifdef CTL_TIME_IO
7063         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
7064 #endif
7065         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
7066         data->it.hdr.param_control = SLP_LBIN;
7067         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
7068             sizeof(struct scsi_log_param_header);
7069         scsi_ulto4b(3, data->ti.exponent);
7070         scsi_ulto4b(1, data->ti.integer);
7071
7072         page_index->page_len = sizeof(*data);
7073         return (0);
7074 }
7075
7076 int
7077 ctl_log_sense(struct ctl_scsiio *ctsio)
7078 {
7079         struct ctl_lun *lun;
7080         int i, pc, page_code, subpage;
7081         int alloc_len, total_len;
7082         struct ctl_page_index *page_index;
7083         struct scsi_log_sense *cdb;
7084         struct scsi_log_header *header;
7085
7086         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7087
7088         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7089         cdb = (struct scsi_log_sense *)ctsio->cdb;
7090         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7091         page_code = cdb->page & SLS_PAGE_CODE;
7092         subpage = cdb->subpage;
7093         alloc_len = scsi_2btoul(cdb->length);
7094
7095         page_index = NULL;
7096         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7097                 page_index = &lun->log_pages.index[i];
7098
7099                 /* Look for the right page code */
7100                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7101                         continue;
7102
7103                 /* Look for the right subpage or the subpage wildcard*/
7104                 if (page_index->subpage != subpage)
7105                         continue;
7106
7107                 break;
7108         }
7109         if (i >= CTL_NUM_LOG_PAGES) {
7110                 ctl_set_invalid_field(ctsio,
7111                                       /*sks_valid*/ 1,
7112                                       /*command*/ 1,
7113                                       /*field*/ 2,
7114                                       /*bit_valid*/ 0,
7115                                       /*bit*/ 0);
7116                 ctl_done((union ctl_io *)ctsio);
7117                 return (CTL_RETVAL_COMPLETE);
7118         }
7119
7120         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7121
7122         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7123         ctsio->kern_sg_entries = 0;
7124         ctsio->kern_data_resid = 0;
7125         ctsio->kern_rel_offset = 0;
7126         if (total_len < alloc_len) {
7127                 ctsio->residual = alloc_len - total_len;
7128                 ctsio->kern_data_len = total_len;
7129                 ctsio->kern_total_len = total_len;
7130         } else {
7131                 ctsio->residual = 0;
7132                 ctsio->kern_data_len = alloc_len;
7133                 ctsio->kern_total_len = alloc_len;
7134         }
7135
7136         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7137         header->page = page_index->page_code;
7138         if (page_index->subpage) {
7139                 header->page |= SL_SPF;
7140                 header->subpage = page_index->subpage;
7141         }
7142         scsi_ulto2b(page_index->page_len, header->datalen);
7143
7144         /*
7145          * Call the handler, if it exists, to update the
7146          * page to the latest values.
7147          */
7148         if (page_index->sense_handler != NULL)
7149                 page_index->sense_handler(ctsio, page_index, pc);
7150
7151         memcpy(header + 1, page_index->page_data, page_index->page_len);
7152
7153         ctl_set_success(ctsio);
7154         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7155         ctsio->be_move_done = ctl_config_move_done;
7156         ctl_datamove((union ctl_io *)ctsio);
7157         return (CTL_RETVAL_COMPLETE);
7158 }
7159
7160 int
7161 ctl_read_capacity(struct ctl_scsiio *ctsio)
7162 {
7163         struct scsi_read_capacity *cdb;
7164         struct scsi_read_capacity_data *data;
7165         struct ctl_lun *lun;
7166         uint32_t lba;
7167
7168         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7169
7170         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7171
7172         lba = scsi_4btoul(cdb->addr);
7173         if (((cdb->pmi & SRC_PMI) == 0)
7174          && (lba != 0)) {
7175                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7176                                       /*sks_valid*/ 1,
7177                                       /*command*/ 1,
7178                                       /*field*/ 2,
7179                                       /*bit_valid*/ 0,
7180                                       /*bit*/ 0);
7181                 ctl_done((union ctl_io *)ctsio);
7182                 return (CTL_RETVAL_COMPLETE);
7183         }
7184
7185         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7186
7187         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7188         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7189         ctsio->residual = 0;
7190         ctsio->kern_data_len = sizeof(*data);
7191         ctsio->kern_total_len = sizeof(*data);
7192         ctsio->kern_data_resid = 0;
7193         ctsio->kern_rel_offset = 0;
7194         ctsio->kern_sg_entries = 0;
7195
7196         /*
7197          * If the maximum LBA is greater than 0xfffffffe, the user must
7198          * issue a SERVICE ACTION IN (16) command, with the read capacity
7199          * serivce action set.
7200          */
7201         if (lun->be_lun->maxlba > 0xfffffffe)
7202                 scsi_ulto4b(0xffffffff, data->addr);
7203         else
7204                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7205
7206         /*
7207          * XXX KDM this may not be 512 bytes...
7208          */
7209         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7210
7211         ctl_set_success(ctsio);
7212         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7213         ctsio->be_move_done = ctl_config_move_done;
7214         ctl_datamove((union ctl_io *)ctsio);
7215         return (CTL_RETVAL_COMPLETE);
7216 }
7217
7218 int
7219 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7220 {
7221         struct scsi_read_capacity_16 *cdb;
7222         struct scsi_read_capacity_data_long *data;
7223         struct ctl_lun *lun;
7224         uint64_t lba;
7225         uint32_t alloc_len;
7226
7227         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7228
7229         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7230
7231         alloc_len = scsi_4btoul(cdb->alloc_len);
7232         lba = scsi_8btou64(cdb->addr);
7233
7234         if ((cdb->reladr & SRC16_PMI)
7235          && (lba != 0)) {
7236                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7237                                       /*sks_valid*/ 1,
7238                                       /*command*/ 1,
7239                                       /*field*/ 2,
7240                                       /*bit_valid*/ 0,
7241                                       /*bit*/ 0);
7242                 ctl_done((union ctl_io *)ctsio);
7243                 return (CTL_RETVAL_COMPLETE);
7244         }
7245
7246         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7247
7248         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7249         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7250
7251         if (sizeof(*data) < alloc_len) {
7252                 ctsio->residual = alloc_len - sizeof(*data);
7253                 ctsio->kern_data_len = sizeof(*data);
7254                 ctsio->kern_total_len = sizeof(*data);
7255         } else {
7256                 ctsio->residual = 0;
7257                 ctsio->kern_data_len = alloc_len;
7258                 ctsio->kern_total_len = alloc_len;
7259         }
7260         ctsio->kern_data_resid = 0;
7261         ctsio->kern_rel_offset = 0;
7262         ctsio->kern_sg_entries = 0;
7263
7264         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7265         /* XXX KDM this may not be 512 bytes... */
7266         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7267         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7268         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7269         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7270                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7271
7272         ctl_set_success(ctsio);
7273         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7274         ctsio->be_move_done = ctl_config_move_done;
7275         ctl_datamove((union ctl_io *)ctsio);
7276         return (CTL_RETVAL_COMPLETE);
7277 }
7278
7279 int
7280 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7281 {
7282         struct scsi_get_lba_status *cdb;
7283         struct scsi_get_lba_status_data *data;
7284         struct ctl_lun *lun;
7285         struct ctl_lba_len_flags *lbalen;
7286         uint64_t lba;
7287         uint32_t alloc_len, total_len;
7288         int retval;
7289
7290         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7291
7292         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7293         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7294         lba = scsi_8btou64(cdb->addr);
7295         alloc_len = scsi_4btoul(cdb->alloc_len);
7296
7297         if (lba > lun->be_lun->maxlba) {
7298                 ctl_set_lba_out_of_range(ctsio);
7299                 ctl_done((union ctl_io *)ctsio);
7300                 return (CTL_RETVAL_COMPLETE);
7301         }
7302
7303         total_len = sizeof(*data) + sizeof(data->descr[0]);
7304         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7305         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7306
7307         if (total_len < alloc_len) {
7308                 ctsio->residual = alloc_len - total_len;
7309                 ctsio->kern_data_len = total_len;
7310                 ctsio->kern_total_len = total_len;
7311         } else {
7312                 ctsio->residual = 0;
7313                 ctsio->kern_data_len = alloc_len;
7314                 ctsio->kern_total_len = alloc_len;
7315         }
7316         ctsio->kern_data_resid = 0;
7317         ctsio->kern_rel_offset = 0;
7318         ctsio->kern_sg_entries = 0;
7319
7320         /* Fill dummy data in case backend can't tell anything. */
7321         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7322         scsi_u64to8b(lba, data->descr[0].addr);
7323         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7324             data->descr[0].length);
7325         data->descr[0].status = 0; /* Mapped or unknown. */
7326
7327         ctl_set_success(ctsio);
7328         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7329         ctsio->be_move_done = ctl_config_move_done;
7330
7331         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7332         lbalen->lba = lba;
7333         lbalen->len = total_len;
7334         lbalen->flags = 0;
7335         retval = lun->backend->config_read((union ctl_io *)ctsio);
7336         return (CTL_RETVAL_COMPLETE);
7337 }
7338
7339 int
7340 ctl_read_defect(struct ctl_scsiio *ctsio)
7341 {
7342         struct scsi_read_defect_data_10 *ccb10;
7343         struct scsi_read_defect_data_12 *ccb12;
7344         struct scsi_read_defect_data_hdr_10 *data10;
7345         struct scsi_read_defect_data_hdr_12 *data12;
7346         uint32_t alloc_len, data_len;
7347         uint8_t format;
7348
7349         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7350
7351         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7352                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7353                 format = ccb10->format;
7354                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7355                 data_len = sizeof(*data10);
7356         } else {
7357                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7358                 format = ccb12->format;
7359                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7360                 data_len = sizeof(*data12);
7361         }
7362         if (alloc_len == 0) {
7363                 ctl_set_success(ctsio);
7364                 ctl_done((union ctl_io *)ctsio);
7365                 return (CTL_RETVAL_COMPLETE);
7366         }
7367
7368         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7369         if (data_len < alloc_len) {
7370                 ctsio->residual = alloc_len - data_len;
7371                 ctsio->kern_data_len = data_len;
7372                 ctsio->kern_total_len = data_len;
7373         } else {
7374                 ctsio->residual = 0;
7375                 ctsio->kern_data_len = alloc_len;
7376                 ctsio->kern_total_len = alloc_len;
7377         }
7378         ctsio->kern_data_resid = 0;
7379         ctsio->kern_rel_offset = 0;
7380         ctsio->kern_sg_entries = 0;
7381
7382         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7383                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7384                     ctsio->kern_data_ptr;
7385                 data10->format = format;
7386                 scsi_ulto2b(0, data10->length);
7387         } else {
7388                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7389                     ctsio->kern_data_ptr;
7390                 data12->format = format;
7391                 scsi_ulto2b(0, data12->generation);
7392                 scsi_ulto4b(0, data12->length);
7393         }
7394
7395         ctl_set_success(ctsio);
7396         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7397         ctsio->be_move_done = ctl_config_move_done;
7398         ctl_datamove((union ctl_io *)ctsio);
7399         return (CTL_RETVAL_COMPLETE);
7400 }
7401
7402 int
7403 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7404 {
7405         struct scsi_maintenance_in *cdb;
7406         int retval;
7407         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7408         int num_target_port_groups, num_target_ports;
7409         struct ctl_lun *lun;
7410         struct ctl_softc *softc;
7411         struct ctl_port *port;
7412         struct scsi_target_group_data *rtg_ptr;
7413         struct scsi_target_group_data_extended *rtg_ext_ptr;
7414         struct scsi_target_port_group_descriptor *tpg_desc;
7415
7416         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7417
7418         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7419         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7420         softc = lun->ctl_softc;
7421
7422         retval = CTL_RETVAL_COMPLETE;
7423
7424         switch (cdb->byte2 & STG_PDF_MASK) {
7425         case STG_PDF_LENGTH:
7426                 ext = 0;
7427                 break;
7428         case STG_PDF_EXTENDED:
7429                 ext = 1;
7430                 break;
7431         default:
7432                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7433                                       /*sks_valid*/ 1,
7434                                       /*command*/ 1,
7435                                       /*field*/ 2,
7436                                       /*bit_valid*/ 1,
7437                                       /*bit*/ 5);
7438                 ctl_done((union ctl_io *)ctsio);
7439                 return(retval);
7440         }
7441
7442         if (softc->is_single)
7443                 num_target_port_groups = 1;
7444         else
7445                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7446         num_target_ports = 0;
7447         mtx_lock(&softc->ctl_lock);
7448         STAILQ_FOREACH(port, &softc->port_list, links) {
7449                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7450                         continue;
7451                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7452                         continue;
7453                 num_target_ports++;
7454         }
7455         mtx_unlock(&softc->ctl_lock);
7456
7457         if (ext)
7458                 total_len = sizeof(struct scsi_target_group_data_extended);
7459         else
7460                 total_len = sizeof(struct scsi_target_group_data);
7461         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7462                 num_target_port_groups +
7463             sizeof(struct scsi_target_port_descriptor) *
7464                 num_target_ports * num_target_port_groups;
7465
7466         alloc_len = scsi_4btoul(cdb->length);
7467
7468         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7469
7470         ctsio->kern_sg_entries = 0;
7471
7472         if (total_len < alloc_len) {
7473                 ctsio->residual = alloc_len - total_len;
7474                 ctsio->kern_data_len = total_len;
7475                 ctsio->kern_total_len = total_len;
7476         } else {
7477                 ctsio->residual = 0;
7478                 ctsio->kern_data_len = alloc_len;
7479                 ctsio->kern_total_len = alloc_len;
7480         }
7481         ctsio->kern_data_resid = 0;
7482         ctsio->kern_rel_offset = 0;
7483
7484         if (ext) {
7485                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7486                     ctsio->kern_data_ptr;
7487                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7488                 rtg_ext_ptr->format_type = 0x10;
7489                 rtg_ext_ptr->implicit_transition_time = 0;
7490                 tpg_desc = &rtg_ext_ptr->groups[0];
7491         } else {
7492                 rtg_ptr = (struct scsi_target_group_data *)
7493                     ctsio->kern_data_ptr;
7494                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7495                 tpg_desc = &rtg_ptr->groups[0];
7496         }
7497
7498         mtx_lock(&softc->ctl_lock);
7499         pg = softc->port_offset / CTL_MAX_PORTS;
7500         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7501                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7502                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7503                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7504                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7505                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7506                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7507                 } else {
7508                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7509                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7510                 }
7511         } else {
7512                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7513                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7514         }
7515         for (g = 0; g < num_target_port_groups; g++) {
7516                 tpg_desc->pref_state = (g == pg) ? gs : os;
7517                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7518                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7519                 tpg_desc->status = TPG_IMPLICIT;
7520                 pc = 0;
7521                 STAILQ_FOREACH(port, &softc->port_list, links) {
7522                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7523                                 continue;
7524                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7525                                 continue;
7526                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7527                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7528                             relative_target_port_identifier);
7529                         pc++;
7530                 }
7531                 tpg_desc->target_port_count = pc;
7532                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7533                     &tpg_desc->descriptors[pc];
7534         }
7535         mtx_unlock(&softc->ctl_lock);
7536
7537         ctl_set_success(ctsio);
7538         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7539         ctsio->be_move_done = ctl_config_move_done;
7540         ctl_datamove((union ctl_io *)ctsio);
7541         return(retval);
7542 }
7543
7544 int
7545 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7546 {
7547         struct ctl_lun *lun;
7548         struct scsi_report_supported_opcodes *cdb;
7549         const struct ctl_cmd_entry *entry, *sentry;
7550         struct scsi_report_supported_opcodes_all *all;
7551         struct scsi_report_supported_opcodes_descr *descr;
7552         struct scsi_report_supported_opcodes_one *one;
7553         int retval;
7554         int alloc_len, total_len;
7555         int opcode, service_action, i, j, num;
7556
7557         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7558
7559         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7560         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7561
7562         retval = CTL_RETVAL_COMPLETE;
7563
7564         opcode = cdb->requested_opcode;
7565         service_action = scsi_2btoul(cdb->requested_service_action);
7566         switch (cdb->options & RSO_OPTIONS_MASK) {
7567         case RSO_OPTIONS_ALL:
7568                 num = 0;
7569                 for (i = 0; i < 256; i++) {
7570                         entry = &ctl_cmd_table[i];
7571                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7572                                 for (j = 0; j < 32; j++) {
7573                                         sentry = &((const struct ctl_cmd_entry *)
7574                                             entry->execute)[j];
7575                                         if (ctl_cmd_applicable(
7576                                             lun->be_lun->lun_type, sentry))
7577                                                 num++;
7578                                 }
7579                         } else {
7580                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7581                                     entry))
7582                                         num++;
7583                         }
7584                 }
7585                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7586                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7587                 break;
7588         case RSO_OPTIONS_OC:
7589                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7590                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7591                                               /*sks_valid*/ 1,
7592                                               /*command*/ 1,
7593                                               /*field*/ 2,
7594                                               /*bit_valid*/ 1,
7595                                               /*bit*/ 2);
7596                         ctl_done((union ctl_io *)ctsio);
7597                         return (CTL_RETVAL_COMPLETE);
7598                 }
7599                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7600                 break;
7601         case RSO_OPTIONS_OC_SA:
7602                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7603                     service_action >= 32) {
7604                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7605                                               /*sks_valid*/ 1,
7606                                               /*command*/ 1,
7607                                               /*field*/ 2,
7608                                               /*bit_valid*/ 1,
7609                                               /*bit*/ 2);
7610                         ctl_done((union ctl_io *)ctsio);
7611                         return (CTL_RETVAL_COMPLETE);
7612                 }
7613                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7614                 break;
7615         default:
7616                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7617                                       /*sks_valid*/ 1,
7618                                       /*command*/ 1,
7619                                       /*field*/ 2,
7620                                       /*bit_valid*/ 1,
7621                                       /*bit*/ 2);
7622                 ctl_done((union ctl_io *)ctsio);
7623                 return (CTL_RETVAL_COMPLETE);
7624         }
7625
7626         alloc_len = scsi_4btoul(cdb->length);
7627
7628         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7629
7630         ctsio->kern_sg_entries = 0;
7631
7632         if (total_len < alloc_len) {
7633                 ctsio->residual = alloc_len - total_len;
7634                 ctsio->kern_data_len = total_len;
7635                 ctsio->kern_total_len = total_len;
7636         } else {
7637                 ctsio->residual = 0;
7638                 ctsio->kern_data_len = alloc_len;
7639                 ctsio->kern_total_len = alloc_len;
7640         }
7641         ctsio->kern_data_resid = 0;
7642         ctsio->kern_rel_offset = 0;
7643
7644         switch (cdb->options & RSO_OPTIONS_MASK) {
7645         case RSO_OPTIONS_ALL:
7646                 all = (struct scsi_report_supported_opcodes_all *)
7647                     ctsio->kern_data_ptr;
7648                 num = 0;
7649                 for (i = 0; i < 256; i++) {
7650                         entry = &ctl_cmd_table[i];
7651                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7652                                 for (j = 0; j < 32; j++) {
7653                                         sentry = &((const struct ctl_cmd_entry *)
7654                                             entry->execute)[j];
7655                                         if (!ctl_cmd_applicable(
7656                                             lun->be_lun->lun_type, sentry))
7657                                                 continue;
7658                                         descr = &all->descr[num++];
7659                                         descr->opcode = i;
7660                                         scsi_ulto2b(j, descr->service_action);
7661                                         descr->flags = RSO_SERVACTV;
7662                                         scsi_ulto2b(sentry->length,
7663                                             descr->cdb_length);
7664                                 }
7665                         } else {
7666                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7667                                     entry))
7668                                         continue;
7669                                 descr = &all->descr[num++];
7670                                 descr->opcode = i;
7671                                 scsi_ulto2b(0, descr->service_action);
7672                                 descr->flags = 0;
7673                                 scsi_ulto2b(entry->length, descr->cdb_length);
7674                         }
7675                 }
7676                 scsi_ulto4b(
7677                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7678                     all->length);
7679                 break;
7680         case RSO_OPTIONS_OC:
7681                 one = (struct scsi_report_supported_opcodes_one *)
7682                     ctsio->kern_data_ptr;
7683                 entry = &ctl_cmd_table[opcode];
7684                 goto fill_one;
7685         case RSO_OPTIONS_OC_SA:
7686                 one = (struct scsi_report_supported_opcodes_one *)
7687                     ctsio->kern_data_ptr;
7688                 entry = &ctl_cmd_table[opcode];
7689                 entry = &((const struct ctl_cmd_entry *)
7690                     entry->execute)[service_action];
7691 fill_one:
7692                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7693                         one->support = 3;
7694                         scsi_ulto2b(entry->length, one->cdb_length);
7695                         one->cdb_usage[0] = opcode;
7696                         memcpy(&one->cdb_usage[1], entry->usage,
7697                             entry->length - 1);
7698                 } else
7699                         one->support = 1;
7700                 break;
7701         }
7702
7703         ctl_set_success(ctsio);
7704         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7705         ctsio->be_move_done = ctl_config_move_done;
7706         ctl_datamove((union ctl_io *)ctsio);
7707         return(retval);
7708 }
7709
7710 int
7711 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7712 {
7713         struct scsi_report_supported_tmf *cdb;
7714         struct scsi_report_supported_tmf_data *data;
7715         int retval;
7716         int alloc_len, total_len;
7717
7718         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7719
7720         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7721
7722         retval = CTL_RETVAL_COMPLETE;
7723
7724         total_len = sizeof(struct scsi_report_supported_tmf_data);
7725         alloc_len = scsi_4btoul(cdb->length);
7726
7727         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7728
7729         ctsio->kern_sg_entries = 0;
7730
7731         if (total_len < alloc_len) {
7732                 ctsio->residual = alloc_len - total_len;
7733                 ctsio->kern_data_len = total_len;
7734                 ctsio->kern_total_len = total_len;
7735         } else {
7736                 ctsio->residual = 0;
7737                 ctsio->kern_data_len = alloc_len;
7738                 ctsio->kern_total_len = alloc_len;
7739         }
7740         ctsio->kern_data_resid = 0;
7741         ctsio->kern_rel_offset = 0;
7742
7743         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7744         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7745         data->byte2 |= RST_ITNRS;
7746
7747         ctl_set_success(ctsio);
7748         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7749         ctsio->be_move_done = ctl_config_move_done;
7750         ctl_datamove((union ctl_io *)ctsio);
7751         return (retval);
7752 }
7753
7754 int
7755 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7756 {
7757         struct scsi_report_timestamp *cdb;
7758         struct scsi_report_timestamp_data *data;
7759         struct timeval tv;
7760         int64_t timestamp;
7761         int retval;
7762         int alloc_len, total_len;
7763
7764         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7765
7766         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7767
7768         retval = CTL_RETVAL_COMPLETE;
7769
7770         total_len = sizeof(struct scsi_report_timestamp_data);
7771         alloc_len = scsi_4btoul(cdb->length);
7772
7773         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7774
7775         ctsio->kern_sg_entries = 0;
7776
7777         if (total_len < alloc_len) {
7778                 ctsio->residual = alloc_len - total_len;
7779                 ctsio->kern_data_len = total_len;
7780                 ctsio->kern_total_len = total_len;
7781         } else {
7782                 ctsio->residual = 0;
7783                 ctsio->kern_data_len = alloc_len;
7784                 ctsio->kern_total_len = alloc_len;
7785         }
7786         ctsio->kern_data_resid = 0;
7787         ctsio->kern_rel_offset = 0;
7788
7789         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7790         scsi_ulto2b(sizeof(*data) - 2, data->length);
7791         data->origin = RTS_ORIG_OUTSIDE;
7792         getmicrotime(&tv);
7793         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7794         scsi_ulto4b(timestamp >> 16, data->timestamp);
7795         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7796
7797         ctl_set_success(ctsio);
7798         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7799         ctsio->be_move_done = ctl_config_move_done;
7800         ctl_datamove((union ctl_io *)ctsio);
7801         return (retval);
7802 }
7803
7804 int
7805 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7806 {
7807         struct scsi_per_res_in *cdb;
7808         int alloc_len, total_len = 0;
7809         /* struct scsi_per_res_in_rsrv in_data; */
7810         struct ctl_lun *lun;
7811         struct ctl_softc *softc;
7812         uint64_t key;
7813
7814         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7815
7816         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7817
7818         alloc_len = scsi_2btoul(cdb->length);
7819
7820         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7821         softc = lun->ctl_softc;
7822
7823 retry:
7824         mtx_lock(&lun->lun_lock);
7825         switch (cdb->action) {
7826         case SPRI_RK: /* read keys */
7827                 total_len = sizeof(struct scsi_per_res_in_keys) +
7828                         lun->pr_key_count *
7829                         sizeof(struct scsi_per_res_key);
7830                 break;
7831         case SPRI_RR: /* read reservation */
7832                 if (lun->flags & CTL_LUN_PR_RESERVED)
7833                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7834                 else
7835                         total_len = sizeof(struct scsi_per_res_in_header);
7836                 break;
7837         case SPRI_RC: /* report capabilities */
7838                 total_len = sizeof(struct scsi_per_res_cap);
7839                 break;
7840         case SPRI_RS: /* read full status */
7841                 total_len = sizeof(struct scsi_per_res_in_header) +
7842                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7843                     lun->pr_key_count;
7844                 break;
7845         default:
7846                 panic("Invalid PR type %x", cdb->action);
7847         }
7848         mtx_unlock(&lun->lun_lock);
7849
7850         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7851
7852         if (total_len < alloc_len) {
7853                 ctsio->residual = alloc_len - total_len;
7854                 ctsio->kern_data_len = total_len;
7855                 ctsio->kern_total_len = total_len;
7856         } else {
7857                 ctsio->residual = 0;
7858                 ctsio->kern_data_len = alloc_len;
7859                 ctsio->kern_total_len = alloc_len;
7860         }
7861
7862         ctsio->kern_data_resid = 0;
7863         ctsio->kern_rel_offset = 0;
7864         ctsio->kern_sg_entries = 0;
7865
7866         mtx_lock(&lun->lun_lock);
7867         switch (cdb->action) {
7868         case SPRI_RK: { // read keys
7869         struct scsi_per_res_in_keys *res_keys;
7870                 int i, key_count;
7871
7872                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7873
7874                 /*
7875                  * We had to drop the lock to allocate our buffer, which
7876                  * leaves time for someone to come in with another
7877                  * persistent reservation.  (That is unlikely, though,
7878                  * since this should be the only persistent reservation
7879                  * command active right now.)
7880                  */
7881                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7882                     (lun->pr_key_count *
7883                      sizeof(struct scsi_per_res_key)))){
7884                         mtx_unlock(&lun->lun_lock);
7885                         free(ctsio->kern_data_ptr, M_CTL);
7886                         printf("%s: reservation length changed, retrying\n",
7887                                __func__);
7888                         goto retry;
7889                 }
7890
7891                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7892
7893                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7894                              lun->pr_key_count, res_keys->header.length);
7895
7896                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7897                         if ((key = ctl_get_prkey(lun, i)) == 0)
7898                                 continue;
7899
7900                         /*
7901                          * We used lun->pr_key_count to calculate the
7902                          * size to allocate.  If it turns out the number of
7903                          * initiators with the registered flag set is
7904                          * larger than that (i.e. they haven't been kept in
7905                          * sync), we've got a problem.
7906                          */
7907                         if (key_count >= lun->pr_key_count) {
7908 #ifdef NEEDTOPORT
7909                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7910                                             CTL_PR_ERROR,
7911                                             csevent_LogType_Fault,
7912                                             csevent_AlertLevel_Yellow,
7913                                             csevent_FRU_ShelfController,
7914                                             csevent_FRU_Firmware,
7915                                         csevent_FRU_Unknown,
7916                                             "registered keys %d >= key "
7917                                             "count %d", key_count,
7918                                             lun->pr_key_count);
7919 #endif
7920                                 key_count++;
7921                                 continue;
7922                         }
7923                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7924                         key_count++;
7925                 }
7926                 break;
7927         }
7928         case SPRI_RR: { // read reservation
7929                 struct scsi_per_res_in_rsrv *res;
7930                 int tmp_len, header_only;
7931
7932                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7933
7934                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7935
7936                 if (lun->flags & CTL_LUN_PR_RESERVED)
7937                 {
7938                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7939                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7940                                     res->header.length);
7941                         header_only = 0;
7942                 } else {
7943                         tmp_len = sizeof(struct scsi_per_res_in_header);
7944                         scsi_ulto4b(0, res->header.length);
7945                         header_only = 1;
7946                 }
7947
7948                 /*
7949                  * We had to drop the lock to allocate our buffer, which
7950                  * leaves time for someone to come in with another
7951                  * persistent reservation.  (That is unlikely, though,
7952                  * since this should be the only persistent reservation
7953                  * command active right now.)
7954                  */
7955                 if (tmp_len != total_len) {
7956                         mtx_unlock(&lun->lun_lock);
7957                         free(ctsio->kern_data_ptr, M_CTL);
7958                         printf("%s: reservation status changed, retrying\n",
7959                                __func__);
7960                         goto retry;
7961                 }
7962
7963                 /*
7964                  * No reservation held, so we're done.
7965                  */
7966                 if (header_only != 0)
7967                         break;
7968
7969                 /*
7970                  * If the registration is an All Registrants type, the key
7971                  * is 0, since it doesn't really matter.
7972                  */
7973                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7974                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7975                             res->data.reservation);
7976                 }
7977                 res->data.scopetype = lun->res_type;
7978                 break;
7979         }
7980         case SPRI_RC:     //report capabilities
7981         {
7982                 struct scsi_per_res_cap *res_cap;
7983                 uint16_t type_mask;
7984
7985                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7986                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7987                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7988                 type_mask = SPRI_TM_WR_EX_AR |
7989                             SPRI_TM_EX_AC_RO |
7990                             SPRI_TM_WR_EX_RO |
7991                             SPRI_TM_EX_AC |
7992                             SPRI_TM_WR_EX |
7993                             SPRI_TM_EX_AC_AR;
7994                 scsi_ulto2b(type_mask, res_cap->type_mask);
7995                 break;
7996         }
7997         case SPRI_RS: { // read full status
7998                 struct scsi_per_res_in_full *res_status;
7999                 struct scsi_per_res_in_full_desc *res_desc;
8000                 struct ctl_port *port;
8001                 int i, len;
8002
8003                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8004
8005                 /*
8006                  * We had to drop the lock to allocate our buffer, which
8007                  * leaves time for someone to come in with another
8008                  * persistent reservation.  (That is unlikely, though,
8009                  * since this should be the only persistent reservation
8010                  * command active right now.)
8011                  */
8012                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
8013                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8014                      lun->pr_key_count)){
8015                         mtx_unlock(&lun->lun_lock);
8016                         free(ctsio->kern_data_ptr, M_CTL);
8017                         printf("%s: reservation length changed, retrying\n",
8018                                __func__);
8019                         goto retry;
8020                 }
8021
8022                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8023
8024                 res_desc = &res_status->desc[0];
8025                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8026                         if ((key = ctl_get_prkey(lun, i)) == 0)
8027                                 continue;
8028
8029                         scsi_u64to8b(key, res_desc->res_key.key);
8030                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8031                             (lun->pr_res_idx == i ||
8032                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8033                                 res_desc->flags = SPRI_FULL_R_HOLDER;
8034                                 res_desc->scopetype = lun->res_type;
8035                         }
8036                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8037                             res_desc->rel_trgt_port_id);
8038                         len = 0;
8039                         port = softc->ctl_ports[
8040                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8041                         if (port != NULL)
8042                                 len = ctl_create_iid(port,
8043                                     i % CTL_MAX_INIT_PER_PORT,
8044                                     res_desc->transport_id);
8045                         scsi_ulto4b(len, res_desc->additional_length);
8046                         res_desc = (struct scsi_per_res_in_full_desc *)
8047                             &res_desc->transport_id[len];
8048                 }
8049                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8050                     res_status->header.length);
8051                 break;
8052         }
8053         default:
8054                 /*
8055                  * This is a bug, because we just checked for this above,
8056                  * and should have returned an error.
8057                  */
8058                 panic("Invalid PR type %x", cdb->action);
8059                 break; /* NOTREACHED */
8060         }
8061         mtx_unlock(&lun->lun_lock);
8062
8063         ctl_set_success(ctsio);
8064         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8065         ctsio->be_move_done = ctl_config_move_done;
8066         ctl_datamove((union ctl_io *)ctsio);
8067         return (CTL_RETVAL_COMPLETE);
8068 }
8069
8070 static void
8071 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8072 {
8073         int off = lun->ctl_softc->persis_offset;
8074
8075         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8076                 ctl_est_ua(lun, residx - off, ua);
8077 }
8078
8079 /*
8080  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8081  * it should return.
8082  */
8083 static int
8084 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8085                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8086                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8087                 struct scsi_per_res_out_parms* param)
8088 {
8089         union ctl_ha_msg persis_io;
8090         int retval, i;
8091         int isc_retval;
8092
8093         retval = 0;
8094
8095         mtx_lock(&lun->lun_lock);
8096         if (sa_res_key == 0) {
8097                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8098                         /* validate scope and type */
8099                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8100                              SPR_LU_SCOPE) {
8101                                 mtx_unlock(&lun->lun_lock);
8102                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8103                                                       /*sks_valid*/ 1,
8104                                                       /*command*/ 1,
8105                                                       /*field*/ 2,
8106                                                       /*bit_valid*/ 1,
8107                                                       /*bit*/ 4);
8108                                 ctl_done((union ctl_io *)ctsio);
8109                                 return (1);
8110                         }
8111
8112                         if (type>8 || type==2 || type==4 || type==0) {
8113                                 mtx_unlock(&lun->lun_lock);
8114                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8115                                                       /*sks_valid*/ 1,
8116                                                       /*command*/ 1,
8117                                                       /*field*/ 2,
8118                                                       /*bit_valid*/ 1,
8119                                                       /*bit*/ 0);
8120                                 ctl_done((union ctl_io *)ctsio);
8121                                 return (1);
8122                         }
8123
8124                         /*
8125                          * Unregister everybody else and build UA for
8126                          * them
8127                          */
8128                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8129                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8130                                         continue;
8131
8132                                 ctl_clr_prkey(lun, i);
8133                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8134                         }
8135                         lun->pr_key_count = 1;
8136                         lun->res_type = type;
8137                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8138                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8139                                 lun->pr_res_idx = residx;
8140
8141                         /* send msg to other side */
8142                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8143                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8144                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8145                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8146                         persis_io.pr.pr_info.res_type = type;
8147                         memcpy(persis_io.pr.pr_info.sa_res_key,
8148                                param->serv_act_res_key,
8149                                sizeof(param->serv_act_res_key));
8150                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8151                              &persis_io, sizeof(persis_io), 0)) >
8152                              CTL_HA_STATUS_SUCCESS) {
8153                                 printf("CTL:Persis Out error returned "
8154                                        "from ctl_ha_msg_send %d\n",
8155                                        isc_retval);
8156                         }
8157                 } else {
8158                         /* not all registrants */
8159                         mtx_unlock(&lun->lun_lock);
8160                         free(ctsio->kern_data_ptr, M_CTL);
8161                         ctl_set_invalid_field(ctsio,
8162                                               /*sks_valid*/ 1,
8163                                               /*command*/ 0,
8164                                               /*field*/ 8,
8165                                               /*bit_valid*/ 0,
8166                                               /*bit*/ 0);
8167                         ctl_done((union ctl_io *)ctsio);
8168                         return (1);
8169                 }
8170         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8171                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8172                 int found = 0;
8173
8174                 if (res_key == sa_res_key) {
8175                         /* special case */
8176                         /*
8177                          * The spec implies this is not good but doesn't
8178                          * say what to do. There are two choices either
8179                          * generate a res conflict or check condition
8180                          * with illegal field in parameter data. Since
8181                          * that is what is done when the sa_res_key is
8182                          * zero I'll take that approach since this has
8183                          * to do with the sa_res_key.
8184                          */
8185                         mtx_unlock(&lun->lun_lock);
8186                         free(ctsio->kern_data_ptr, M_CTL);
8187                         ctl_set_invalid_field(ctsio,
8188                                               /*sks_valid*/ 1,
8189                                               /*command*/ 0,
8190                                               /*field*/ 8,
8191                                               /*bit_valid*/ 0,
8192                                               /*bit*/ 0);
8193                         ctl_done((union ctl_io *)ctsio);
8194                         return (1);
8195                 }
8196
8197                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8198                         if (ctl_get_prkey(lun, i) != sa_res_key)
8199                                 continue;
8200
8201                         found = 1;
8202                         ctl_clr_prkey(lun, i);
8203                         lun->pr_key_count--;
8204                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8205                 }
8206                 if (!found) {
8207                         mtx_unlock(&lun->lun_lock);
8208                         free(ctsio->kern_data_ptr, M_CTL);
8209                         ctl_set_reservation_conflict(ctsio);
8210                         ctl_done((union ctl_io *)ctsio);
8211                         return (CTL_RETVAL_COMPLETE);
8212                 }
8213                 /* send msg to other side */
8214                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8215                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8216                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8217                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8218                 persis_io.pr.pr_info.res_type = type;
8219                 memcpy(persis_io.pr.pr_info.sa_res_key,
8220                        param->serv_act_res_key,
8221                        sizeof(param->serv_act_res_key));
8222                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8223                      &persis_io, sizeof(persis_io), 0)) >
8224                      CTL_HA_STATUS_SUCCESS) {
8225                         printf("CTL:Persis Out error returned from "
8226                                "ctl_ha_msg_send %d\n", isc_retval);
8227                 }
8228         } else {
8229                 /* Reserved but not all registrants */
8230                 /* sa_res_key is res holder */
8231                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8232                         /* validate scope and type */
8233                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8234                              SPR_LU_SCOPE) {
8235                                 mtx_unlock(&lun->lun_lock);
8236                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8237                                                       /*sks_valid*/ 1,
8238                                                       /*command*/ 1,
8239                                                       /*field*/ 2,
8240                                                       /*bit_valid*/ 1,
8241                                                       /*bit*/ 4);
8242                                 ctl_done((union ctl_io *)ctsio);
8243                                 return (1);
8244                         }
8245
8246                         if (type>8 || type==2 || type==4 || type==0) {
8247                                 mtx_unlock(&lun->lun_lock);
8248                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8249                                                       /*sks_valid*/ 1,
8250                                                       /*command*/ 1,
8251                                                       /*field*/ 2,
8252                                                       /*bit_valid*/ 1,
8253                                                       /*bit*/ 0);
8254                                 ctl_done((union ctl_io *)ctsio);
8255                                 return (1);
8256                         }
8257
8258                         /*
8259                          * Do the following:
8260                          * if sa_res_key != res_key remove all
8261                          * registrants w/sa_res_key and generate UA
8262                          * for these registrants(Registrations
8263                          * Preempted) if it wasn't an exclusive
8264                          * reservation generate UA(Reservations
8265                          * Preempted) for all other registered nexuses
8266                          * if the type has changed. Establish the new
8267                          * reservation and holder. If res_key and
8268                          * sa_res_key are the same do the above
8269                          * except don't unregister the res holder.
8270                          */
8271
8272                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8273                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8274                                         continue;
8275
8276                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8277                                         ctl_clr_prkey(lun, i);
8278                                         lun->pr_key_count--;
8279                                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8280                                 } else if (type != lun->res_type
8281                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8282                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8283                                         ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8284                                 }
8285                         }
8286                         lun->res_type = type;
8287                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8288                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8289                                 lun->pr_res_idx = residx;
8290                         else
8291                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8292
8293                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8294                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8295                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8296                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8297                         persis_io.pr.pr_info.res_type = type;
8298                         memcpy(persis_io.pr.pr_info.sa_res_key,
8299                                param->serv_act_res_key,
8300                                sizeof(param->serv_act_res_key));
8301                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8302                              &persis_io, sizeof(persis_io), 0)) >
8303                              CTL_HA_STATUS_SUCCESS) {
8304                                 printf("CTL:Persis Out error returned "
8305                                        "from ctl_ha_msg_send %d\n",
8306                                        isc_retval);
8307                         }
8308                 } else {
8309                         /*
8310                          * sa_res_key is not the res holder just
8311                          * remove registrants
8312                          */
8313                         int found=0;
8314
8315                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8316                                 if (sa_res_key != ctl_get_prkey(lun, i))
8317                                         continue;
8318
8319                                 found = 1;
8320                                 ctl_clr_prkey(lun, i);
8321                                 lun->pr_key_count--;
8322                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8323                         }
8324
8325                         if (!found) {
8326                                 mtx_unlock(&lun->lun_lock);
8327                                 free(ctsio->kern_data_ptr, M_CTL);
8328                                 ctl_set_reservation_conflict(ctsio);
8329                                 ctl_done((union ctl_io *)ctsio);
8330                                 return (1);
8331                         }
8332                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8333                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8334                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8335                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8336                         persis_io.pr.pr_info.res_type = type;
8337                         memcpy(persis_io.pr.pr_info.sa_res_key,
8338                                param->serv_act_res_key,
8339                                sizeof(param->serv_act_res_key));
8340                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8341                              &persis_io, sizeof(persis_io), 0)) >
8342                              CTL_HA_STATUS_SUCCESS) {
8343                                 printf("CTL:Persis Out error returned "
8344                                        "from ctl_ha_msg_send %d\n",
8345                                 isc_retval);
8346                         }
8347                 }
8348         }
8349
8350         lun->PRGeneration++;
8351         mtx_unlock(&lun->lun_lock);
8352
8353         return (retval);
8354 }
8355
8356 static void
8357 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8358 {
8359         uint64_t sa_res_key;
8360         int i;
8361
8362         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8363
8364         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8365          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8366          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8367                 if (sa_res_key == 0) {
8368                         /*
8369                          * Unregister everybody else and build UA for
8370                          * them
8371                          */
8372                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8373                                 if (i == msg->pr.pr_info.residx ||
8374                                     ctl_get_prkey(lun, i) == 0)
8375                                         continue;
8376
8377                                 ctl_clr_prkey(lun, i);
8378                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8379                         }
8380
8381                         lun->pr_key_count = 1;
8382                         lun->res_type = msg->pr.pr_info.res_type;
8383                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8384                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8385                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8386                 } else {
8387                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8388                                 if (sa_res_key == ctl_get_prkey(lun, i))
8389                                         continue;
8390
8391                                 ctl_clr_prkey(lun, i);
8392                                 lun->pr_key_count--;
8393                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8394                         }
8395                 }
8396         } else {
8397                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8398                         if (i == msg->pr.pr_info.residx ||
8399                             ctl_get_prkey(lun, i) == 0)
8400                                 continue;
8401
8402                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8403                                 ctl_clr_prkey(lun, i);
8404                                 lun->pr_key_count--;
8405                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8406                         } else if (msg->pr.pr_info.res_type != lun->res_type
8407                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8408                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8409                                 ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8410                         }
8411                 }
8412                 lun->res_type = msg->pr.pr_info.res_type;
8413                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8414                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8415                         lun->pr_res_idx = msg->pr.pr_info.residx;
8416                 else
8417                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8418         }
8419         lun->PRGeneration++;
8420
8421 }
8422
8423
8424 int
8425 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8426 {
8427         int retval;
8428         int isc_retval;
8429         u_int32_t param_len;
8430         struct scsi_per_res_out *cdb;
8431         struct ctl_lun *lun;
8432         struct scsi_per_res_out_parms* param;
8433         struct ctl_softc *softc;
8434         uint32_t residx;
8435         uint64_t res_key, sa_res_key, key;
8436         uint8_t type;
8437         union ctl_ha_msg persis_io;
8438         int    i;
8439
8440         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8441
8442         retval = CTL_RETVAL_COMPLETE;
8443
8444         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8445         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8446         softc = lun->ctl_softc;
8447
8448         /*
8449          * We only support whole-LUN scope.  The scope & type are ignored for
8450          * register, register and ignore existing key and clear.
8451          * We sometimes ignore scope and type on preempts too!!
8452          * Verify reservation type here as well.
8453          */
8454         type = cdb->scope_type & SPR_TYPE_MASK;
8455         if ((cdb->action == SPRO_RESERVE)
8456          || (cdb->action == SPRO_RELEASE)) {
8457                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8458                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8459                                               /*sks_valid*/ 1,
8460                                               /*command*/ 1,
8461                                               /*field*/ 2,
8462                                               /*bit_valid*/ 1,
8463                                               /*bit*/ 4);
8464                         ctl_done((union ctl_io *)ctsio);
8465                         return (CTL_RETVAL_COMPLETE);
8466                 }
8467
8468                 if (type>8 || type==2 || type==4 || type==0) {
8469                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8470                                               /*sks_valid*/ 1,
8471                                               /*command*/ 1,
8472                                               /*field*/ 2,
8473                                               /*bit_valid*/ 1,
8474                                               /*bit*/ 0);
8475                         ctl_done((union ctl_io *)ctsio);
8476                         return (CTL_RETVAL_COMPLETE);
8477                 }
8478         }
8479
8480         param_len = scsi_4btoul(cdb->length);
8481
8482         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8483                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8484                 ctsio->kern_data_len = param_len;
8485                 ctsio->kern_total_len = param_len;
8486                 ctsio->kern_data_resid = 0;
8487                 ctsio->kern_rel_offset = 0;
8488                 ctsio->kern_sg_entries = 0;
8489                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8490                 ctsio->be_move_done = ctl_config_move_done;
8491                 ctl_datamove((union ctl_io *)ctsio);
8492
8493                 return (CTL_RETVAL_COMPLETE);
8494         }
8495
8496         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8497
8498         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8499         res_key = scsi_8btou64(param->res_key.key);
8500         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8501
8502         /*
8503          * Validate the reservation key here except for SPRO_REG_IGNO
8504          * This must be done for all other service actions
8505          */
8506         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8507                 mtx_lock(&lun->lun_lock);
8508                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8509                         if (res_key != key) {
8510                                 /*
8511                                  * The current key passed in doesn't match
8512                                  * the one the initiator previously
8513                                  * registered.
8514                                  */
8515                                 mtx_unlock(&lun->lun_lock);
8516                                 free(ctsio->kern_data_ptr, M_CTL);
8517                                 ctl_set_reservation_conflict(ctsio);
8518                                 ctl_done((union ctl_io *)ctsio);
8519                                 return (CTL_RETVAL_COMPLETE);
8520                         }
8521                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8522                         /*
8523                          * We are not registered
8524                          */
8525                         mtx_unlock(&lun->lun_lock);
8526                         free(ctsio->kern_data_ptr, M_CTL);
8527                         ctl_set_reservation_conflict(ctsio);
8528                         ctl_done((union ctl_io *)ctsio);
8529                         return (CTL_RETVAL_COMPLETE);
8530                 } else if (res_key != 0) {
8531                         /*
8532                          * We are not registered and trying to register but
8533                          * the register key isn't zero.
8534                          */
8535                         mtx_unlock(&lun->lun_lock);
8536                         free(ctsio->kern_data_ptr, M_CTL);
8537                         ctl_set_reservation_conflict(ctsio);
8538                         ctl_done((union ctl_io *)ctsio);
8539                         return (CTL_RETVAL_COMPLETE);
8540                 }
8541                 mtx_unlock(&lun->lun_lock);
8542         }
8543
8544         switch (cdb->action & SPRO_ACTION_MASK) {
8545         case SPRO_REGISTER:
8546         case SPRO_REG_IGNO: {
8547
8548 #if 0
8549                 printf("Registration received\n");
8550 #endif
8551
8552                 /*
8553                  * We don't support any of these options, as we report in
8554                  * the read capabilities request (see
8555                  * ctl_persistent_reserve_in(), above).
8556                  */
8557                 if ((param->flags & SPR_SPEC_I_PT)
8558                  || (param->flags & SPR_ALL_TG_PT)
8559                  || (param->flags & SPR_APTPL)) {
8560                         int bit_ptr;
8561
8562                         if (param->flags & SPR_APTPL)
8563                                 bit_ptr = 0;
8564                         else if (param->flags & SPR_ALL_TG_PT)
8565                                 bit_ptr = 2;
8566                         else /* SPR_SPEC_I_PT */
8567                                 bit_ptr = 3;
8568
8569                         free(ctsio->kern_data_ptr, M_CTL);
8570                         ctl_set_invalid_field(ctsio,
8571                                               /*sks_valid*/ 1,
8572                                               /*command*/ 0,
8573                                               /*field*/ 20,
8574                                               /*bit_valid*/ 1,
8575                                               /*bit*/ bit_ptr);
8576                         ctl_done((union ctl_io *)ctsio);
8577                         return (CTL_RETVAL_COMPLETE);
8578                 }
8579
8580                 mtx_lock(&lun->lun_lock);
8581
8582                 /*
8583                  * The initiator wants to clear the
8584                  * key/unregister.
8585                  */
8586                 if (sa_res_key == 0) {
8587                         if ((res_key == 0
8588                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8589                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8590                           && ctl_get_prkey(lun, residx) == 0)) {
8591                                 mtx_unlock(&lun->lun_lock);
8592                                 goto done;
8593                         }
8594
8595                         ctl_clr_prkey(lun, residx);
8596                         lun->pr_key_count--;
8597
8598                         if (residx == lun->pr_res_idx) {
8599                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8600                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8601
8602                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8603                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8604                                  && lun->pr_key_count) {
8605                                         /*
8606                                          * If the reservation is a registrants
8607                                          * only type we need to generate a UA
8608                                          * for other registered inits.  The
8609                                          * sense code should be RESERVATIONS
8610                                          * RELEASED
8611                                          */
8612
8613                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8614                                                 if (ctl_get_prkey(lun, i +
8615                                                     softc->persis_offset) == 0)
8616                                                         continue;
8617                                                 ctl_est_ua(lun, i,
8618                                                     CTL_UA_RES_RELEASE);
8619                                         }
8620                                 }
8621                                 lun->res_type = 0;
8622                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8623                                 if (lun->pr_key_count==0) {
8624                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8625                                         lun->res_type = 0;
8626                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8627                                 }
8628                         }
8629                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8630                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8631                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8632                         persis_io.pr.pr_info.residx = residx;
8633                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8634                              &persis_io, sizeof(persis_io), 0 )) >
8635                              CTL_HA_STATUS_SUCCESS) {
8636                                 printf("CTL:Persis Out error returned from "
8637                                        "ctl_ha_msg_send %d\n", isc_retval);
8638                         }
8639                 } else /* sa_res_key != 0 */ {
8640
8641                         /*
8642                          * If we aren't registered currently then increment
8643                          * the key count and set the registered flag.
8644                          */
8645                         ctl_alloc_prkey(lun, residx);
8646                         if (ctl_get_prkey(lun, residx) == 0)
8647                                 lun->pr_key_count++;
8648                         ctl_set_prkey(lun, residx, sa_res_key);
8649
8650                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8651                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8652                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8653                         persis_io.pr.pr_info.residx = residx;
8654                         memcpy(persis_io.pr.pr_info.sa_res_key,
8655                                param->serv_act_res_key,
8656                                sizeof(param->serv_act_res_key));
8657                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8658                              &persis_io, sizeof(persis_io), 0)) >
8659                              CTL_HA_STATUS_SUCCESS) {
8660                                 printf("CTL:Persis Out error returned from "
8661                                        "ctl_ha_msg_send %d\n", isc_retval);
8662                         }
8663                 }
8664                 lun->PRGeneration++;
8665                 mtx_unlock(&lun->lun_lock);
8666
8667                 break;
8668         }
8669         case SPRO_RESERVE:
8670 #if 0
8671                 printf("Reserve executed type %d\n", type);
8672 #endif
8673                 mtx_lock(&lun->lun_lock);
8674                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8675                         /*
8676                          * if this isn't the reservation holder and it's
8677                          * not a "all registrants" type or if the type is
8678                          * different then we have a conflict
8679                          */
8680                         if ((lun->pr_res_idx != residx
8681                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8682                          || lun->res_type != type) {
8683                                 mtx_unlock(&lun->lun_lock);
8684                                 free(ctsio->kern_data_ptr, M_CTL);
8685                                 ctl_set_reservation_conflict(ctsio);
8686                                 ctl_done((union ctl_io *)ctsio);
8687                                 return (CTL_RETVAL_COMPLETE);
8688                         }
8689                         mtx_unlock(&lun->lun_lock);
8690                 } else /* create a reservation */ {
8691                         /*
8692                          * If it's not an "all registrants" type record
8693                          * reservation holder
8694                          */
8695                         if (type != SPR_TYPE_WR_EX_AR
8696                          && type != SPR_TYPE_EX_AC_AR)
8697                                 lun->pr_res_idx = residx; /* Res holder */
8698                         else
8699                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8700
8701                         lun->flags |= CTL_LUN_PR_RESERVED;
8702                         lun->res_type = type;
8703
8704                         mtx_unlock(&lun->lun_lock);
8705
8706                         /* send msg to other side */
8707                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8708                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8709                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8710                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8711                         persis_io.pr.pr_info.res_type = type;
8712                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8713                              &persis_io, sizeof(persis_io), 0)) >
8714                              CTL_HA_STATUS_SUCCESS) {
8715                                 printf("CTL:Persis Out error returned from "
8716                                        "ctl_ha_msg_send %d\n", isc_retval);
8717                         }
8718                 }
8719                 break;
8720
8721         case SPRO_RELEASE:
8722                 mtx_lock(&lun->lun_lock);
8723                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8724                         /* No reservation exists return good status */
8725                         mtx_unlock(&lun->lun_lock);
8726                         goto done;
8727                 }
8728                 /*
8729                  * Is this nexus a reservation holder?
8730                  */
8731                 if (lun->pr_res_idx != residx
8732                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8733                         /*
8734                          * not a res holder return good status but
8735                          * do nothing
8736                          */
8737                         mtx_unlock(&lun->lun_lock);
8738                         goto done;
8739                 }
8740
8741                 if (lun->res_type != type) {
8742                         mtx_unlock(&lun->lun_lock);
8743                         free(ctsio->kern_data_ptr, M_CTL);
8744                         ctl_set_illegal_pr_release(ctsio);
8745                         ctl_done((union ctl_io *)ctsio);
8746                         return (CTL_RETVAL_COMPLETE);
8747                 }
8748
8749                 /* okay to release */
8750                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8751                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8752                 lun->res_type = 0;
8753
8754                 /*
8755                  * if this isn't an exclusive access
8756                  * res generate UA for all other
8757                  * registrants.
8758                  */
8759                 if (type != SPR_TYPE_EX_AC
8760                  && type != SPR_TYPE_WR_EX) {
8761                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8762                                 if (i == residx ||
8763                                     ctl_get_prkey(lun,
8764                                      i + softc->persis_offset) == 0)
8765                                         continue;
8766                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8767                         }
8768                 }
8769                 mtx_unlock(&lun->lun_lock);
8770                 /* Send msg to other side */
8771                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8772                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8773                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8774                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8775                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8776                         printf("CTL:Persis Out error returned from "
8777                                "ctl_ha_msg_send %d\n", isc_retval);
8778                 }
8779                 break;
8780
8781         case SPRO_CLEAR:
8782                 /* send msg to other side */
8783
8784                 mtx_lock(&lun->lun_lock);
8785                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8786                 lun->res_type = 0;
8787                 lun->pr_key_count = 0;
8788                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8789
8790                 ctl_clr_prkey(lun, residx);
8791                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8792                         if (ctl_get_prkey(lun, i) != 0) {
8793                                 ctl_clr_prkey(lun, i);
8794                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8795                         }
8796                 lun->PRGeneration++;
8797                 mtx_unlock(&lun->lun_lock);
8798                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8799                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8800                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8801                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8802                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8803                         printf("CTL:Persis Out error returned from "
8804                                "ctl_ha_msg_send %d\n", isc_retval);
8805                 }
8806                 break;
8807
8808         case SPRO_PREEMPT:
8809         case SPRO_PRE_ABO: {
8810                 int nretval;
8811
8812                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8813                                           residx, ctsio, cdb, param);
8814                 if (nretval != 0)
8815                         return (CTL_RETVAL_COMPLETE);
8816                 break;
8817         }
8818         default:
8819                 panic("Invalid PR type %x", cdb->action);
8820         }
8821
8822 done:
8823         free(ctsio->kern_data_ptr, M_CTL);
8824         ctl_set_success(ctsio);
8825         ctl_done((union ctl_io *)ctsio);
8826
8827         return (retval);
8828 }
8829
8830 /*
8831  * This routine is for handling a message from the other SC pertaining to
8832  * persistent reserve out. All the error checking will have been done
8833  * so only perorming the action need be done here to keep the two
8834  * in sync.
8835  */
8836 static void
8837 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8838 {
8839         struct ctl_lun *lun;
8840         struct ctl_softc *softc;
8841         int i;
8842         uint32_t targ_lun;
8843
8844         softc = control_softc;
8845
8846         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8847         lun = softc->ctl_luns[targ_lun];
8848         mtx_lock(&lun->lun_lock);
8849         switch(msg->pr.pr_info.action) {
8850         case CTL_PR_REG_KEY:
8851                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8852                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8853                         lun->pr_key_count++;
8854                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8855                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8856                 lun->PRGeneration++;
8857                 break;
8858
8859         case CTL_PR_UNREG_KEY:
8860                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8861                 lun->pr_key_count--;
8862
8863                 /* XXX Need to see if the reservation has been released */
8864                 /* if so do we need to generate UA? */
8865                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8866                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8867                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8868
8869                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8870                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8871                          && lun->pr_key_count) {
8872                                 /*
8873                                  * If the reservation is a registrants
8874                                  * only type we need to generate a UA
8875                                  * for other registered inits.  The
8876                                  * sense code should be RESERVATIONS
8877                                  * RELEASED
8878                                  */
8879
8880                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8881                                         if (ctl_get_prkey(lun, i +
8882                                             softc->persis_offset) == 0)
8883                                                 continue;
8884
8885                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8886                                 }
8887                         }
8888                         lun->res_type = 0;
8889                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8890                         if (lun->pr_key_count==0) {
8891                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8892                                 lun->res_type = 0;
8893                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8894                         }
8895                 }
8896                 lun->PRGeneration++;
8897                 break;
8898
8899         case CTL_PR_RESERVE:
8900                 lun->flags |= CTL_LUN_PR_RESERVED;
8901                 lun->res_type = msg->pr.pr_info.res_type;
8902                 lun->pr_res_idx = msg->pr.pr_info.residx;
8903
8904                 break;
8905
8906         case CTL_PR_RELEASE:
8907                 /*
8908                  * if this isn't an exclusive access res generate UA for all
8909                  * other registrants.
8910                  */
8911                 if (lun->res_type != SPR_TYPE_EX_AC
8912                  && lun->res_type != SPR_TYPE_WR_EX) {
8913                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8914                                 if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8915                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8916                 }
8917
8918                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8919                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8920                 lun->res_type = 0;
8921                 break;
8922
8923         case CTL_PR_PREEMPT:
8924                 ctl_pro_preempt_other(lun, msg);
8925                 break;
8926         case CTL_PR_CLEAR:
8927                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8928                 lun->res_type = 0;
8929                 lun->pr_key_count = 0;
8930                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8931
8932                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8933                         if (ctl_get_prkey(lun, i) == 0)
8934                                 continue;
8935                         ctl_clr_prkey(lun, i);
8936                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8937                 }
8938                 lun->PRGeneration++;
8939                 break;
8940         }
8941
8942         mtx_unlock(&lun->lun_lock);
8943 }
8944
8945 int
8946 ctl_read_write(struct ctl_scsiio *ctsio)
8947 {
8948         struct ctl_lun *lun;
8949         struct ctl_lba_len_flags *lbalen;
8950         uint64_t lba;
8951         uint32_t num_blocks;
8952         int flags, retval;
8953         int isread;
8954
8955         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8956
8957         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8958
8959         flags = 0;
8960         retval = CTL_RETVAL_COMPLETE;
8961
8962         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8963               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8964         switch (ctsio->cdb[0]) {
8965         case READ_6:
8966         case WRITE_6: {
8967                 struct scsi_rw_6 *cdb;
8968
8969                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8970
8971                 lba = scsi_3btoul(cdb->addr);
8972                 /* only 5 bits are valid in the most significant address byte */
8973                 lba &= 0x1fffff;
8974                 num_blocks = cdb->length;
8975                 /*
8976                  * This is correct according to SBC-2.
8977                  */
8978                 if (num_blocks == 0)
8979                         num_blocks = 256;
8980                 break;
8981         }
8982         case READ_10:
8983         case WRITE_10: {
8984                 struct scsi_rw_10 *cdb;
8985
8986                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8987                 if (cdb->byte2 & SRW10_FUA)
8988                         flags |= CTL_LLF_FUA;
8989                 if (cdb->byte2 & SRW10_DPO)
8990                         flags |= CTL_LLF_DPO;
8991                 lba = scsi_4btoul(cdb->addr);
8992                 num_blocks = scsi_2btoul(cdb->length);
8993                 break;
8994         }
8995         case WRITE_VERIFY_10: {
8996                 struct scsi_write_verify_10 *cdb;
8997
8998                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8999                 flags |= CTL_LLF_FUA;
9000                 if (cdb->byte2 & SWV_DPO)
9001                         flags |= CTL_LLF_DPO;
9002                 lba = scsi_4btoul(cdb->addr);
9003                 num_blocks = scsi_2btoul(cdb->length);
9004                 break;
9005         }
9006         case READ_12:
9007         case WRITE_12: {
9008                 struct scsi_rw_12 *cdb;
9009
9010                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9011                 if (cdb->byte2 & SRW12_FUA)
9012                         flags |= CTL_LLF_FUA;
9013                 if (cdb->byte2 & SRW12_DPO)
9014                         flags |= CTL_LLF_DPO;
9015                 lba = scsi_4btoul(cdb->addr);
9016                 num_blocks = scsi_4btoul(cdb->length);
9017                 break;
9018         }
9019         case WRITE_VERIFY_12: {
9020                 struct scsi_write_verify_12 *cdb;
9021
9022                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9023                 flags |= CTL_LLF_FUA;
9024                 if (cdb->byte2 & SWV_DPO)
9025                         flags |= CTL_LLF_DPO;
9026                 lba = scsi_4btoul(cdb->addr);
9027                 num_blocks = scsi_4btoul(cdb->length);
9028                 break;
9029         }
9030         case READ_16:
9031         case WRITE_16: {
9032                 struct scsi_rw_16 *cdb;
9033
9034                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9035                 if (cdb->byte2 & SRW12_FUA)
9036                         flags |= CTL_LLF_FUA;
9037                 if (cdb->byte2 & SRW12_DPO)
9038                         flags |= CTL_LLF_DPO;
9039                 lba = scsi_8btou64(cdb->addr);
9040                 num_blocks = scsi_4btoul(cdb->length);
9041                 break;
9042         }
9043         case WRITE_ATOMIC_16: {
9044                 struct scsi_rw_16 *cdb;
9045
9046                 if (lun->be_lun->atomicblock == 0) {
9047                         ctl_set_invalid_opcode(ctsio);
9048                         ctl_done((union ctl_io *)ctsio);
9049                         return (CTL_RETVAL_COMPLETE);
9050                 }
9051
9052                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9053                 if (cdb->byte2 & SRW12_FUA)
9054                         flags |= CTL_LLF_FUA;
9055                 if (cdb->byte2 & SRW12_DPO)
9056                         flags |= CTL_LLF_DPO;
9057                 lba = scsi_8btou64(cdb->addr);
9058                 num_blocks = scsi_4btoul(cdb->length);
9059                 if (num_blocks > lun->be_lun->atomicblock) {
9060                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9061                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9062                             /*bit*/ 0);
9063                         ctl_done((union ctl_io *)ctsio);
9064                         return (CTL_RETVAL_COMPLETE);
9065                 }
9066                 break;
9067         }
9068         case WRITE_VERIFY_16: {
9069                 struct scsi_write_verify_16 *cdb;
9070
9071                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9072                 flags |= CTL_LLF_FUA;
9073                 if (cdb->byte2 & SWV_DPO)
9074                         flags |= CTL_LLF_DPO;
9075                 lba = scsi_8btou64(cdb->addr);
9076                 num_blocks = scsi_4btoul(cdb->length);
9077                 break;
9078         }
9079         default:
9080                 /*
9081                  * We got a command we don't support.  This shouldn't
9082                  * happen, commands should be filtered out above us.
9083                  */
9084                 ctl_set_invalid_opcode(ctsio);
9085                 ctl_done((union ctl_io *)ctsio);
9086
9087                 return (CTL_RETVAL_COMPLETE);
9088                 break; /* NOTREACHED */
9089         }
9090
9091         /*
9092          * The first check is to make sure we're in bounds, the second
9093          * check is to catch wrap-around problems.  If the lba + num blocks
9094          * is less than the lba, then we've wrapped around and the block
9095          * range is invalid anyway.
9096          */
9097         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9098          || ((lba + num_blocks) < lba)) {
9099                 ctl_set_lba_out_of_range(ctsio);
9100                 ctl_done((union ctl_io *)ctsio);
9101                 return (CTL_RETVAL_COMPLETE);
9102         }
9103
9104         /*
9105          * According to SBC-3, a transfer length of 0 is not an error.
9106          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9107          * translates to 256 blocks for those commands.
9108          */
9109         if (num_blocks == 0) {
9110                 ctl_set_success(ctsio);
9111                 ctl_done((union ctl_io *)ctsio);
9112                 return (CTL_RETVAL_COMPLETE);
9113         }
9114
9115         /* Set FUA and/or DPO if caches are disabled. */
9116         if (isread) {
9117                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9118                     SCP_RCD) != 0)
9119                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9120         } else {
9121                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9122                     SCP_WCE) == 0)
9123                         flags |= CTL_LLF_FUA;
9124         }
9125
9126         lbalen = (struct ctl_lba_len_flags *)
9127             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9128         lbalen->lba = lba;
9129         lbalen->len = num_blocks;
9130         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9131
9132         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9133         ctsio->kern_rel_offset = 0;
9134
9135         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9136
9137         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9138
9139         return (retval);
9140 }
9141
9142 static int
9143 ctl_cnw_cont(union ctl_io *io)
9144 {
9145         struct ctl_scsiio *ctsio;
9146         struct ctl_lun *lun;
9147         struct ctl_lba_len_flags *lbalen;
9148         int retval;
9149
9150         ctsio = &io->scsiio;
9151         ctsio->io_hdr.status = CTL_STATUS_NONE;
9152         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9153         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9154         lbalen = (struct ctl_lba_len_flags *)
9155             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9156         lbalen->flags &= ~CTL_LLF_COMPARE;
9157         lbalen->flags |= CTL_LLF_WRITE;
9158
9159         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9160         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9161         return (retval);
9162 }
9163
9164 int
9165 ctl_cnw(struct ctl_scsiio *ctsio)
9166 {
9167         struct ctl_lun *lun;
9168         struct ctl_lba_len_flags *lbalen;
9169         uint64_t lba;
9170         uint32_t num_blocks;
9171         int flags, retval;
9172
9173         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9174
9175         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9176
9177         flags = 0;
9178         retval = CTL_RETVAL_COMPLETE;
9179
9180         switch (ctsio->cdb[0]) {
9181         case COMPARE_AND_WRITE: {
9182                 struct scsi_compare_and_write *cdb;
9183
9184                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9185                 if (cdb->byte2 & SRW10_FUA)
9186                         flags |= CTL_LLF_FUA;
9187                 if (cdb->byte2 & SRW10_DPO)
9188                         flags |= CTL_LLF_DPO;
9189                 lba = scsi_8btou64(cdb->addr);
9190                 num_blocks = cdb->length;
9191                 break;
9192         }
9193         default:
9194                 /*
9195                  * We got a command we don't support.  This shouldn't
9196                  * happen, commands should be filtered out above us.
9197                  */
9198                 ctl_set_invalid_opcode(ctsio);
9199                 ctl_done((union ctl_io *)ctsio);
9200
9201                 return (CTL_RETVAL_COMPLETE);
9202                 break; /* NOTREACHED */
9203         }
9204
9205         /*
9206          * The first check is to make sure we're in bounds, the second
9207          * check is to catch wrap-around problems.  If the lba + num blocks
9208          * is less than the lba, then we've wrapped around and the block
9209          * range is invalid anyway.
9210          */
9211         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9212          || ((lba + num_blocks) < lba)) {
9213                 ctl_set_lba_out_of_range(ctsio);
9214                 ctl_done((union ctl_io *)ctsio);
9215                 return (CTL_RETVAL_COMPLETE);
9216         }
9217
9218         /*
9219          * According to SBC-3, a transfer length of 0 is not an error.
9220          */
9221         if (num_blocks == 0) {
9222                 ctl_set_success(ctsio);
9223                 ctl_done((union ctl_io *)ctsio);
9224                 return (CTL_RETVAL_COMPLETE);
9225         }
9226
9227         /* Set FUA if write cache is disabled. */
9228         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9229             SCP_WCE) == 0)
9230                 flags |= CTL_LLF_FUA;
9231
9232         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9233         ctsio->kern_rel_offset = 0;
9234
9235         /*
9236          * Set the IO_CONT flag, so that if this I/O gets passed to
9237          * ctl_data_submit_done(), it'll get passed back to
9238          * ctl_ctl_cnw_cont() for further processing.
9239          */
9240         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9241         ctsio->io_cont = ctl_cnw_cont;
9242
9243         lbalen = (struct ctl_lba_len_flags *)
9244             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9245         lbalen->lba = lba;
9246         lbalen->len = num_blocks;
9247         lbalen->flags = CTL_LLF_COMPARE | flags;
9248
9249         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9250         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9251         return (retval);
9252 }
9253
9254 int
9255 ctl_verify(struct ctl_scsiio *ctsio)
9256 {
9257         struct ctl_lun *lun;
9258         struct ctl_lba_len_flags *lbalen;
9259         uint64_t lba;
9260         uint32_t num_blocks;
9261         int bytchk, flags;
9262         int retval;
9263
9264         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9265
9266         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9267
9268         bytchk = 0;
9269         flags = CTL_LLF_FUA;
9270         retval = CTL_RETVAL_COMPLETE;
9271
9272         switch (ctsio->cdb[0]) {
9273         case VERIFY_10: {
9274                 struct scsi_verify_10 *cdb;
9275
9276                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9277                 if (cdb->byte2 & SVFY_BYTCHK)
9278                         bytchk = 1;
9279                 if (cdb->byte2 & SVFY_DPO)
9280                         flags |= CTL_LLF_DPO;
9281                 lba = scsi_4btoul(cdb->addr);
9282                 num_blocks = scsi_2btoul(cdb->length);
9283                 break;
9284         }
9285         case VERIFY_12: {
9286                 struct scsi_verify_12 *cdb;
9287
9288                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9289                 if (cdb->byte2 & SVFY_BYTCHK)
9290                         bytchk = 1;
9291                 if (cdb->byte2 & SVFY_DPO)
9292                         flags |= CTL_LLF_DPO;
9293                 lba = scsi_4btoul(cdb->addr);
9294                 num_blocks = scsi_4btoul(cdb->length);
9295                 break;
9296         }
9297         case VERIFY_16: {
9298                 struct scsi_rw_16 *cdb;
9299
9300                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9301                 if (cdb->byte2 & SVFY_BYTCHK)
9302                         bytchk = 1;
9303                 if (cdb->byte2 & SVFY_DPO)
9304                         flags |= CTL_LLF_DPO;
9305                 lba = scsi_8btou64(cdb->addr);
9306                 num_blocks = scsi_4btoul(cdb->length);
9307                 break;
9308         }
9309         default:
9310                 /*
9311                  * We got a command we don't support.  This shouldn't
9312                  * happen, commands should be filtered out above us.
9313                  */
9314                 ctl_set_invalid_opcode(ctsio);
9315                 ctl_done((union ctl_io *)ctsio);
9316                 return (CTL_RETVAL_COMPLETE);
9317         }
9318
9319         /*
9320          * The first check is to make sure we're in bounds, the second
9321          * check is to catch wrap-around problems.  If the lba + num blocks
9322          * is less than the lba, then we've wrapped around and the block
9323          * range is invalid anyway.
9324          */
9325         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9326          || ((lba + num_blocks) < lba)) {
9327                 ctl_set_lba_out_of_range(ctsio);
9328                 ctl_done((union ctl_io *)ctsio);
9329                 return (CTL_RETVAL_COMPLETE);
9330         }
9331
9332         /*
9333          * According to SBC-3, a transfer length of 0 is not an error.
9334          */
9335         if (num_blocks == 0) {
9336                 ctl_set_success(ctsio);
9337                 ctl_done((union ctl_io *)ctsio);
9338                 return (CTL_RETVAL_COMPLETE);
9339         }
9340
9341         lbalen = (struct ctl_lba_len_flags *)
9342             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9343         lbalen->lba = lba;
9344         lbalen->len = num_blocks;
9345         if (bytchk) {
9346                 lbalen->flags = CTL_LLF_COMPARE | flags;
9347                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9348         } else {
9349                 lbalen->flags = CTL_LLF_VERIFY | flags;
9350                 ctsio->kern_total_len = 0;
9351         }
9352         ctsio->kern_rel_offset = 0;
9353
9354         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9355         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9356         return (retval);
9357 }
9358
9359 int
9360 ctl_report_luns(struct ctl_scsiio *ctsio)
9361 {
9362         struct ctl_softc *softc = control_softc;
9363         struct scsi_report_luns *cdb;
9364         struct scsi_report_luns_data *lun_data;
9365         struct ctl_lun *lun, *request_lun;
9366         struct ctl_port *port;
9367         int num_luns, retval;
9368         uint32_t alloc_len, lun_datalen;
9369         int num_filled, well_known;
9370         uint32_t initidx, targ_lun_id, lun_id;
9371
9372         retval = CTL_RETVAL_COMPLETE;
9373         well_known = 0;
9374
9375         cdb = (struct scsi_report_luns *)ctsio->cdb;
9376
9377         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9378
9379         mtx_lock(&softc->ctl_lock);
9380         num_luns = softc->num_luns;
9381         mtx_unlock(&softc->ctl_lock);
9382
9383         switch (cdb->select_report) {
9384         case RPL_REPORT_DEFAULT:
9385         case RPL_REPORT_ALL:
9386                 break;
9387         case RPL_REPORT_WELLKNOWN:
9388                 well_known = 1;
9389                 num_luns = 0;
9390                 break;
9391         default:
9392                 ctl_set_invalid_field(ctsio,
9393                                       /*sks_valid*/ 1,
9394                                       /*command*/ 1,
9395                                       /*field*/ 2,
9396                                       /*bit_valid*/ 0,
9397                                       /*bit*/ 0);
9398                 ctl_done((union ctl_io *)ctsio);
9399                 return (retval);
9400                 break; /* NOTREACHED */
9401         }
9402
9403         alloc_len = scsi_4btoul(cdb->length);
9404         /*
9405          * The initiator has to allocate at least 16 bytes for this request,
9406          * so he can at least get the header and the first LUN.  Otherwise
9407          * we reject the request (per SPC-3 rev 14, section 6.21).
9408          */
9409         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9410             sizeof(struct scsi_report_luns_lundata))) {
9411                 ctl_set_invalid_field(ctsio,
9412                                       /*sks_valid*/ 1,
9413                                       /*command*/ 1,
9414                                       /*field*/ 6,
9415                                       /*bit_valid*/ 0,
9416                                       /*bit*/ 0);
9417                 ctl_done((union ctl_io *)ctsio);
9418                 return (retval);
9419         }
9420
9421         request_lun = (struct ctl_lun *)
9422                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9423         port = ctl_io_port(&ctsio->io_hdr);
9424
9425         lun_datalen = sizeof(*lun_data) +
9426                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9427
9428         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9429         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9430         ctsio->kern_sg_entries = 0;
9431
9432         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9433
9434         mtx_lock(&softc->ctl_lock);
9435         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9436                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9437                 if (lun_id >= CTL_MAX_LUNS)
9438                         continue;
9439                 lun = softc->ctl_luns[lun_id];
9440                 if (lun == NULL)
9441                         continue;
9442
9443                 if (targ_lun_id <= 0xff) {
9444                         /*
9445                          * Peripheral addressing method, bus number 0.
9446                          */
9447                         lun_data->luns[num_filled].lundata[0] =
9448                                 RPL_LUNDATA_ATYP_PERIPH;
9449                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9450                         num_filled++;
9451                 } else if (targ_lun_id <= 0x3fff) {
9452                         /*
9453                          * Flat addressing method.
9454                          */
9455                         lun_data->luns[num_filled].lundata[0] =
9456                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9457                         lun_data->luns[num_filled].lundata[1] =
9458                                 (targ_lun_id & 0xff);
9459                         num_filled++;
9460                 } else if (targ_lun_id <= 0xffffff) {
9461                         /*
9462                          * Extended flat addressing method.
9463                          */
9464                         lun_data->luns[num_filled].lundata[0] =
9465                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9466                         scsi_ulto3b(targ_lun_id,
9467                             &lun_data->luns[num_filled].lundata[1]);
9468                         num_filled++;
9469                 } else {
9470                         printf("ctl_report_luns: bogus LUN number %jd, "
9471                                "skipping\n", (intmax_t)targ_lun_id);
9472                 }
9473                 /*
9474                  * According to SPC-3, rev 14 section 6.21:
9475                  *
9476                  * "The execution of a REPORT LUNS command to any valid and
9477                  * installed logical unit shall clear the REPORTED LUNS DATA
9478                  * HAS CHANGED unit attention condition for all logical
9479                  * units of that target with respect to the requesting
9480                  * initiator. A valid and installed logical unit is one
9481                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9482                  * INQUIRY data (see 6.4.2)."
9483                  *
9484                  * If request_lun is NULL, the LUN this report luns command
9485                  * was issued to is either disabled or doesn't exist. In that
9486                  * case, we shouldn't clear any pending lun change unit
9487                  * attention.
9488                  */
9489                 if (request_lun != NULL) {
9490                         mtx_lock(&lun->lun_lock);
9491                         ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9492                         mtx_unlock(&lun->lun_lock);
9493                 }
9494         }
9495         mtx_unlock(&softc->ctl_lock);
9496
9497         /*
9498          * It's quite possible that we've returned fewer LUNs than we allocated
9499          * space for.  Trim it.
9500          */
9501         lun_datalen = sizeof(*lun_data) +
9502                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9503
9504         if (lun_datalen < alloc_len) {
9505                 ctsio->residual = alloc_len - lun_datalen;
9506                 ctsio->kern_data_len = lun_datalen;
9507                 ctsio->kern_total_len = lun_datalen;
9508         } else {
9509                 ctsio->residual = 0;
9510                 ctsio->kern_data_len = alloc_len;
9511                 ctsio->kern_total_len = alloc_len;
9512         }
9513         ctsio->kern_data_resid = 0;
9514         ctsio->kern_rel_offset = 0;
9515         ctsio->kern_sg_entries = 0;
9516
9517         /*
9518          * We set this to the actual data length, regardless of how much
9519          * space we actually have to return results.  If the user looks at
9520          * this value, he'll know whether or not he allocated enough space
9521          * and reissue the command if necessary.  We don't support well
9522          * known logical units, so if the user asks for that, return none.
9523          */
9524         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9525
9526         /*
9527          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9528          * this request.
9529          */
9530         ctl_set_success(ctsio);
9531         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9532         ctsio->be_move_done = ctl_config_move_done;
9533         ctl_datamove((union ctl_io *)ctsio);
9534         return (retval);
9535 }
9536
9537 int
9538 ctl_request_sense(struct ctl_scsiio *ctsio)
9539 {
9540         struct scsi_request_sense *cdb;
9541         struct scsi_sense_data *sense_ptr;
9542         struct ctl_softc *ctl_softc;
9543         struct ctl_lun *lun;
9544         uint32_t initidx;
9545         int have_error;
9546         scsi_sense_data_type sense_format;
9547         ctl_ua_type ua_type;
9548
9549         cdb = (struct scsi_request_sense *)ctsio->cdb;
9550
9551         ctl_softc = control_softc;
9552         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9553
9554         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9555
9556         /*
9557          * Determine which sense format the user wants.
9558          */
9559         if (cdb->byte2 & SRS_DESC)
9560                 sense_format = SSD_TYPE_DESC;
9561         else
9562                 sense_format = SSD_TYPE_FIXED;
9563
9564         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9565         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9566         ctsio->kern_sg_entries = 0;
9567
9568         /*
9569          * struct scsi_sense_data, which is currently set to 256 bytes, is
9570          * larger than the largest allowed value for the length field in the
9571          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9572          */
9573         ctsio->residual = 0;
9574         ctsio->kern_data_len = cdb->length;
9575         ctsio->kern_total_len = cdb->length;
9576
9577         ctsio->kern_data_resid = 0;
9578         ctsio->kern_rel_offset = 0;
9579         ctsio->kern_sg_entries = 0;
9580
9581         /*
9582          * If we don't have a LUN, we don't have any pending sense.
9583          */
9584         if (lun == NULL)
9585                 goto no_sense;
9586
9587         have_error = 0;
9588         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9589         /*
9590          * Check for pending sense, and then for pending unit attentions.
9591          * Pending sense gets returned first, then pending unit attentions.
9592          */
9593         mtx_lock(&lun->lun_lock);
9594 #ifdef CTL_WITH_CA
9595         if (ctl_is_set(lun->have_ca, initidx)) {
9596                 scsi_sense_data_type stored_format;
9597
9598                 /*
9599                  * Check to see which sense format was used for the stored
9600                  * sense data.
9601                  */
9602                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9603
9604                 /*
9605                  * If the user requested a different sense format than the
9606                  * one we stored, then we need to convert it to the other
9607                  * format.  If we're going from descriptor to fixed format
9608                  * sense data, we may lose things in translation, depending
9609                  * on what options were used.
9610                  *
9611                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9612                  * for some reason we'll just copy it out as-is.
9613                  */
9614                 if ((stored_format == SSD_TYPE_FIXED)
9615                  && (sense_format == SSD_TYPE_DESC))
9616                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9617                             &lun->pending_sense[initidx],
9618                             (struct scsi_sense_data_desc *)sense_ptr);
9619                 else if ((stored_format == SSD_TYPE_DESC)
9620                       && (sense_format == SSD_TYPE_FIXED))
9621                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9622                             &lun->pending_sense[initidx],
9623                             (struct scsi_sense_data_fixed *)sense_ptr);
9624                 else
9625                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9626                                MIN(sizeof(*sense_ptr),
9627                                sizeof(lun->pending_sense[initidx])));
9628
9629                 ctl_clear_mask(lun->have_ca, initidx);
9630                 have_error = 1;
9631         } else
9632 #endif
9633         {
9634                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9635                 if (ua_type != CTL_UA_NONE)
9636                         have_error = 1;
9637                 if (ua_type == CTL_UA_LUN_CHANGE) {
9638                         mtx_unlock(&lun->lun_lock);
9639                         mtx_lock(&ctl_softc->ctl_lock);
9640                         ctl_clear_ua(ctl_softc, initidx, ua_type);
9641                         mtx_unlock(&ctl_softc->ctl_lock);
9642                         mtx_lock(&lun->lun_lock);
9643                 }
9644
9645         }
9646         mtx_unlock(&lun->lun_lock);
9647
9648         /*
9649          * We already have a pending error, return it.
9650          */
9651         if (have_error != 0) {
9652                 /*
9653                  * We report the SCSI status as OK, since the status of the
9654                  * request sense command itself is OK.
9655                  * We report 0 for the sense length, because we aren't doing
9656                  * autosense in this case.  We're reporting sense as
9657                  * parameter data.
9658                  */
9659                 ctl_set_success(ctsio);
9660                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9661                 ctsio->be_move_done = ctl_config_move_done;
9662                 ctl_datamove((union ctl_io *)ctsio);
9663                 return (CTL_RETVAL_COMPLETE);
9664         }
9665
9666 no_sense:
9667
9668         /*
9669          * No sense information to report, so we report that everything is
9670          * okay.
9671          */
9672         ctl_set_sense_data(sense_ptr,
9673                            lun,
9674                            sense_format,
9675                            /*current_error*/ 1,
9676                            /*sense_key*/ SSD_KEY_NO_SENSE,
9677                            /*asc*/ 0x00,
9678                            /*ascq*/ 0x00,
9679                            SSD_ELEM_NONE);
9680
9681         /*
9682          * We report 0 for the sense length, because we aren't doing
9683          * autosense in this case.  We're reporting sense as parameter data.
9684          */
9685         ctl_set_success(ctsio);
9686         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9687         ctsio->be_move_done = ctl_config_move_done;
9688         ctl_datamove((union ctl_io *)ctsio);
9689         return (CTL_RETVAL_COMPLETE);
9690 }
9691
9692 int
9693 ctl_tur(struct ctl_scsiio *ctsio)
9694 {
9695
9696         CTL_DEBUG_PRINT(("ctl_tur\n"));
9697
9698         ctl_set_success(ctsio);
9699         ctl_done((union ctl_io *)ctsio);
9700
9701         return (CTL_RETVAL_COMPLETE);
9702 }
9703
9704 #ifdef notyet
9705 static int
9706 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9707 {
9708
9709 }
9710 #endif
9711
9712 /*
9713  * SCSI VPD page 0x00, the Supported VPD Pages page.
9714  */
9715 static int
9716 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9717 {
9718         struct scsi_vpd_supported_pages *pages;
9719         int sup_page_size;
9720         struct ctl_lun *lun;
9721         int p;
9722
9723         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9724
9725         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9726             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9727         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9728         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9729         ctsio->kern_sg_entries = 0;
9730
9731         if (sup_page_size < alloc_len) {
9732                 ctsio->residual = alloc_len - sup_page_size;
9733                 ctsio->kern_data_len = sup_page_size;
9734                 ctsio->kern_total_len = sup_page_size;
9735         } else {
9736                 ctsio->residual = 0;
9737                 ctsio->kern_data_len = alloc_len;
9738                 ctsio->kern_total_len = alloc_len;
9739         }
9740         ctsio->kern_data_resid = 0;
9741         ctsio->kern_rel_offset = 0;
9742         ctsio->kern_sg_entries = 0;
9743
9744         /*
9745          * The control device is always connected.  The disk device, on the
9746          * other hand, may not be online all the time.  Need to change this
9747          * to figure out whether the disk device is actually online or not.
9748          */
9749         if (lun != NULL)
9750                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9751                                 lun->be_lun->lun_type;
9752         else
9753                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9754
9755         p = 0;
9756         /* Supported VPD pages */
9757         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9758         /* Serial Number */
9759         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9760         /* Device Identification */
9761         pages->page_list[p++] = SVPD_DEVICE_ID;
9762         /* Extended INQUIRY Data */
9763         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9764         /* Mode Page Policy */
9765         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9766         /* SCSI Ports */
9767         pages->page_list[p++] = SVPD_SCSI_PORTS;
9768         /* Third-party Copy */
9769         pages->page_list[p++] = SVPD_SCSI_TPC;
9770         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9771                 /* Block limits */
9772                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9773                 /* Block Device Characteristics */
9774                 pages->page_list[p++] = SVPD_BDC;
9775                 /* Logical Block Provisioning */
9776                 pages->page_list[p++] = SVPD_LBP;
9777         }
9778         pages->length = p;
9779
9780         ctl_set_success(ctsio);
9781         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9782         ctsio->be_move_done = ctl_config_move_done;
9783         ctl_datamove((union ctl_io *)ctsio);
9784         return (CTL_RETVAL_COMPLETE);
9785 }
9786
9787 /*
9788  * SCSI VPD page 0x80, the Unit Serial Number page.
9789  */
9790 static int
9791 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9792 {
9793         struct scsi_vpd_unit_serial_number *sn_ptr;
9794         struct ctl_lun *lun;
9795         int data_len;
9796
9797         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9798
9799         data_len = 4 + CTL_SN_LEN;
9800         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9801         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9802         if (data_len < alloc_len) {
9803                 ctsio->residual = alloc_len - data_len;
9804                 ctsio->kern_data_len = data_len;
9805                 ctsio->kern_total_len = data_len;
9806         } else {
9807                 ctsio->residual = 0;
9808                 ctsio->kern_data_len = alloc_len;
9809                 ctsio->kern_total_len = alloc_len;
9810         }
9811         ctsio->kern_data_resid = 0;
9812         ctsio->kern_rel_offset = 0;
9813         ctsio->kern_sg_entries = 0;
9814
9815         /*
9816          * The control device is always connected.  The disk device, on the
9817          * other hand, may not be online all the time.  Need to change this
9818          * to figure out whether the disk device is actually online or not.
9819          */
9820         if (lun != NULL)
9821                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9822                                   lun->be_lun->lun_type;
9823         else
9824                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9825
9826         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9827         sn_ptr->length = CTL_SN_LEN;
9828         /*
9829          * If we don't have a LUN, we just leave the serial number as
9830          * all spaces.
9831          */
9832         if (lun != NULL) {
9833                 strncpy((char *)sn_ptr->serial_num,
9834                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9835         } else
9836                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9837
9838         ctl_set_success(ctsio);
9839         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9840         ctsio->be_move_done = ctl_config_move_done;
9841         ctl_datamove((union ctl_io *)ctsio);
9842         return (CTL_RETVAL_COMPLETE);
9843 }
9844
9845
9846 /*
9847  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9848  */
9849 static int
9850 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9851 {
9852         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9853         struct ctl_lun *lun;
9854         int data_len;
9855
9856         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9857
9858         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9859         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9860         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9861         ctsio->kern_sg_entries = 0;
9862
9863         if (data_len < alloc_len) {
9864                 ctsio->residual = alloc_len - data_len;
9865                 ctsio->kern_data_len = data_len;
9866                 ctsio->kern_total_len = data_len;
9867         } else {
9868                 ctsio->residual = 0;
9869                 ctsio->kern_data_len = alloc_len;
9870                 ctsio->kern_total_len = alloc_len;
9871         }
9872         ctsio->kern_data_resid = 0;
9873         ctsio->kern_rel_offset = 0;
9874         ctsio->kern_sg_entries = 0;
9875
9876         /*
9877          * The control device is always connected.  The disk device, on the
9878          * other hand, may not be online all the time.
9879          */
9880         if (lun != NULL)
9881                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9882                                      lun->be_lun->lun_type;
9883         else
9884                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9885         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9886         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9887         /*
9888          * We support head of queue, ordered and simple tags.
9889          */
9890         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9891         /*
9892          * Volatile cache supported.
9893          */
9894         eid_ptr->flags3 = SVPD_EID_V_SUP;
9895
9896         /*
9897          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9898          * attention for a particular IT nexus on all LUNs once we report
9899          * it to that nexus once.  This bit is required as of SPC-4.
9900          */
9901         eid_ptr->flags4 = SVPD_EID_LUICLT;
9902
9903         /*
9904          * XXX KDM in order to correctly answer this, we would need
9905          * information from the SIM to determine how much sense data it
9906          * can send.  So this would really be a path inquiry field, most
9907          * likely.  This can be set to a maximum of 252 according to SPC-4,
9908          * but the hardware may or may not be able to support that much.
9909          * 0 just means that the maximum sense data length is not reported.
9910          */
9911         eid_ptr->max_sense_length = 0;
9912
9913         ctl_set_success(ctsio);
9914         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9915         ctsio->be_move_done = ctl_config_move_done;
9916         ctl_datamove((union ctl_io *)ctsio);
9917         return (CTL_RETVAL_COMPLETE);
9918 }
9919
9920 static int
9921 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9922 {
9923         struct scsi_vpd_mode_page_policy *mpp_ptr;
9924         struct ctl_lun *lun;
9925         int data_len;
9926
9927         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9928
9929         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9930             sizeof(struct scsi_vpd_mode_page_policy_descr);
9931
9932         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9933         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9934         ctsio->kern_sg_entries = 0;
9935
9936         if (data_len < alloc_len) {
9937                 ctsio->residual = alloc_len - data_len;
9938                 ctsio->kern_data_len = data_len;
9939                 ctsio->kern_total_len = data_len;
9940         } else {
9941                 ctsio->residual = 0;
9942                 ctsio->kern_data_len = alloc_len;
9943                 ctsio->kern_total_len = alloc_len;
9944         }
9945         ctsio->kern_data_resid = 0;
9946         ctsio->kern_rel_offset = 0;
9947         ctsio->kern_sg_entries = 0;
9948
9949         /*
9950          * The control device is always connected.  The disk device, on the
9951          * other hand, may not be online all the time.
9952          */
9953         if (lun != NULL)
9954                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9955                                      lun->be_lun->lun_type;
9956         else
9957                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9958         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9959         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9960         mpp_ptr->descr[0].page_code = 0x3f;
9961         mpp_ptr->descr[0].subpage_code = 0xff;
9962         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9963
9964         ctl_set_success(ctsio);
9965         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9966         ctsio->be_move_done = ctl_config_move_done;
9967         ctl_datamove((union ctl_io *)ctsio);
9968         return (CTL_RETVAL_COMPLETE);
9969 }
9970
9971 /*
9972  * SCSI VPD page 0x83, the Device Identification page.
9973  */
9974 static int
9975 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9976 {
9977         struct scsi_vpd_device_id *devid_ptr;
9978         struct scsi_vpd_id_descriptor *desc;
9979         struct ctl_softc *softc;
9980         struct ctl_lun *lun;
9981         struct ctl_port *port;
9982         int data_len;
9983         uint8_t proto;
9984
9985         softc = control_softc;
9986
9987         port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9988         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9989
9990         data_len = sizeof(struct scsi_vpd_device_id) +
9991             sizeof(struct scsi_vpd_id_descriptor) +
9992                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9993             sizeof(struct scsi_vpd_id_descriptor) +
9994                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9995         if (lun && lun->lun_devid)
9996                 data_len += lun->lun_devid->len;
9997         if (port->port_devid)
9998                 data_len += port->port_devid->len;
9999         if (port->target_devid)
10000                 data_len += port->target_devid->len;
10001
10002         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10003         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10004         ctsio->kern_sg_entries = 0;
10005
10006         if (data_len < alloc_len) {
10007                 ctsio->residual = alloc_len - data_len;
10008                 ctsio->kern_data_len = data_len;
10009                 ctsio->kern_total_len = data_len;
10010         } else {
10011                 ctsio->residual = 0;
10012                 ctsio->kern_data_len = alloc_len;
10013                 ctsio->kern_total_len = alloc_len;
10014         }
10015         ctsio->kern_data_resid = 0;
10016         ctsio->kern_rel_offset = 0;
10017         ctsio->kern_sg_entries = 0;
10018
10019         /*
10020          * The control device is always connected.  The disk device, on the
10021          * other hand, may not be online all the time.
10022          */
10023         if (lun != NULL)
10024                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10025                                      lun->be_lun->lun_type;
10026         else
10027                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10028         devid_ptr->page_code = SVPD_DEVICE_ID;
10029         scsi_ulto2b(data_len - 4, devid_ptr->length);
10030
10031         if (port->port_type == CTL_PORT_FC)
10032                 proto = SCSI_PROTO_FC << 4;
10033         else if (port->port_type == CTL_PORT_ISCSI)
10034                 proto = SCSI_PROTO_ISCSI << 4;
10035         else
10036                 proto = SCSI_PROTO_SPI << 4;
10037         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10038
10039         /*
10040          * We're using a LUN association here.  i.e., this device ID is a
10041          * per-LUN identifier.
10042          */
10043         if (lun && lun->lun_devid) {
10044                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10045                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10046                     lun->lun_devid->len);
10047         }
10048
10049         /*
10050          * This is for the WWPN which is a port association.
10051          */
10052         if (port->port_devid) {
10053                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10054                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10055                     port->port_devid->len);
10056         }
10057
10058         /*
10059          * This is for the Relative Target Port(type 4h) identifier
10060          */
10061         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10062         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10063             SVPD_ID_TYPE_RELTARG;
10064         desc->length = 4;
10065         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10066         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10067             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10068
10069         /*
10070          * This is for the Target Port Group(type 5h) identifier
10071          */
10072         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10073         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10074             SVPD_ID_TYPE_TPORTGRP;
10075         desc->length = 4;
10076         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10077             &desc->identifier[2]);
10078         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10079             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10080
10081         /*
10082          * This is for the Target identifier
10083          */
10084         if (port->target_devid) {
10085                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10086         }
10087
10088         ctl_set_success(ctsio);
10089         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10090         ctsio->be_move_done = ctl_config_move_done;
10091         ctl_datamove((union ctl_io *)ctsio);
10092         return (CTL_RETVAL_COMPLETE);
10093 }
10094
10095 static int
10096 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10097 {
10098         struct ctl_softc *softc = control_softc;
10099         struct scsi_vpd_scsi_ports *sp;
10100         struct scsi_vpd_port_designation *pd;
10101         struct scsi_vpd_port_designation_cont *pdc;
10102         struct ctl_lun *lun;
10103         struct ctl_port *port;
10104         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10105         int num_target_port_groups;
10106
10107         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10108
10109         if (softc->is_single)
10110                 num_target_port_groups = 1;
10111         else
10112                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10113         num_target_ports = 0;
10114         iid_len = 0;
10115         id_len = 0;
10116         mtx_lock(&softc->ctl_lock);
10117         STAILQ_FOREACH(port, &softc->port_list, links) {
10118                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10119                         continue;
10120                 if (lun != NULL &&
10121                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10122                         continue;
10123                 num_target_ports++;
10124                 if (port->init_devid)
10125                         iid_len += port->init_devid->len;
10126                 if (port->port_devid)
10127                         id_len += port->port_devid->len;
10128         }
10129         mtx_unlock(&softc->ctl_lock);
10130
10131         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10132             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10133              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10134         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10135         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10136         ctsio->kern_sg_entries = 0;
10137
10138         if (data_len < alloc_len) {
10139                 ctsio->residual = alloc_len - data_len;
10140                 ctsio->kern_data_len = data_len;
10141                 ctsio->kern_total_len = data_len;
10142         } else {
10143                 ctsio->residual = 0;
10144                 ctsio->kern_data_len = alloc_len;
10145                 ctsio->kern_total_len = alloc_len;
10146         }
10147         ctsio->kern_data_resid = 0;
10148         ctsio->kern_rel_offset = 0;
10149         ctsio->kern_sg_entries = 0;
10150
10151         /*
10152          * The control device is always connected.  The disk device, on the
10153          * other hand, may not be online all the time.  Need to change this
10154          * to figure out whether the disk device is actually online or not.
10155          */
10156         if (lun != NULL)
10157                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10158                                   lun->be_lun->lun_type;
10159         else
10160                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10161
10162         sp->page_code = SVPD_SCSI_PORTS;
10163         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10164             sp->page_length);
10165         pd = &sp->design[0];
10166
10167         mtx_lock(&softc->ctl_lock);
10168         pg = softc->port_offset / CTL_MAX_PORTS;
10169         for (g = 0; g < num_target_port_groups; g++) {
10170                 STAILQ_FOREACH(port, &softc->port_list, links) {
10171                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10172                                 continue;
10173                         if (lun != NULL &&
10174                             ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10175                                 continue;
10176                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10177                         scsi_ulto2b(p, pd->relative_port_id);
10178                         if (port->init_devid && g == pg) {
10179                                 iid_len = port->init_devid->len;
10180                                 memcpy(pd->initiator_transportid,
10181                                     port->init_devid->data, port->init_devid->len);
10182                         } else
10183                                 iid_len = 0;
10184                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10185                         pdc = (struct scsi_vpd_port_designation_cont *)
10186                             (&pd->initiator_transportid[iid_len]);
10187                         if (port->port_devid && g == pg) {
10188                                 id_len = port->port_devid->len;
10189                                 memcpy(pdc->target_port_descriptors,
10190                                     port->port_devid->data, port->port_devid->len);
10191                         } else
10192                                 id_len = 0;
10193                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10194                         pd = (struct scsi_vpd_port_designation *)
10195                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10196                 }
10197         }
10198         mtx_unlock(&softc->ctl_lock);
10199
10200         ctl_set_success(ctsio);
10201         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10202         ctsio->be_move_done = ctl_config_move_done;
10203         ctl_datamove((union ctl_io *)ctsio);
10204         return (CTL_RETVAL_COMPLETE);
10205 }
10206
10207 static int
10208 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10209 {
10210         struct scsi_vpd_block_limits *bl_ptr;
10211         struct ctl_lun *lun;
10212         int bs;
10213
10214         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10215
10216         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10217         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10218         ctsio->kern_sg_entries = 0;
10219
10220         if (sizeof(*bl_ptr) < alloc_len) {
10221                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10222                 ctsio->kern_data_len = sizeof(*bl_ptr);
10223                 ctsio->kern_total_len = sizeof(*bl_ptr);
10224         } else {
10225                 ctsio->residual = 0;
10226                 ctsio->kern_data_len = alloc_len;
10227                 ctsio->kern_total_len = alloc_len;
10228         }
10229         ctsio->kern_data_resid = 0;
10230         ctsio->kern_rel_offset = 0;
10231         ctsio->kern_sg_entries = 0;
10232
10233         /*
10234          * The control device is always connected.  The disk device, on the
10235          * other hand, may not be online all the time.  Need to change this
10236          * to figure out whether the disk device is actually online or not.
10237          */
10238         if (lun != NULL)
10239                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10240                                   lun->be_lun->lun_type;
10241         else
10242                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10243
10244         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10245         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10246         bl_ptr->max_cmp_write_len = 0xff;
10247         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10248         if (lun != NULL) {
10249                 bs = lun->be_lun->blocksize;
10250                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10251                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10252                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10253                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10254                         if (lun->be_lun->ublockexp != 0) {
10255                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
10256                                     bl_ptr->opt_unmap_grain);
10257                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10258                                     bl_ptr->unmap_grain_align);
10259                         }
10260                 }
10261                 scsi_ulto4b(lun->be_lun->atomicblock,
10262                     bl_ptr->max_atomic_transfer_length);
10263                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10264                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10265         }
10266         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10267
10268         ctl_set_success(ctsio);
10269         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10270         ctsio->be_move_done = ctl_config_move_done;
10271         ctl_datamove((union ctl_io *)ctsio);
10272         return (CTL_RETVAL_COMPLETE);
10273 }
10274
10275 static int
10276 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10277 {
10278         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10279         struct ctl_lun *lun;
10280         const char *value;
10281         u_int i;
10282
10283         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10284
10285         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10286         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10287         ctsio->kern_sg_entries = 0;
10288
10289         if (sizeof(*bdc_ptr) < alloc_len) {
10290                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10291                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10292                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10293         } else {
10294                 ctsio->residual = 0;
10295                 ctsio->kern_data_len = alloc_len;
10296                 ctsio->kern_total_len = alloc_len;
10297         }
10298         ctsio->kern_data_resid = 0;
10299         ctsio->kern_rel_offset = 0;
10300         ctsio->kern_sg_entries = 0;
10301
10302         /*
10303          * The control device is always connected.  The disk device, on the
10304          * other hand, may not be online all the time.  Need to change this
10305          * to figure out whether the disk device is actually online or not.
10306          */
10307         if (lun != NULL)
10308                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10309                                   lun->be_lun->lun_type;
10310         else
10311                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10312         bdc_ptr->page_code = SVPD_BDC;
10313         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10314         if (lun != NULL &&
10315             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10316                 i = strtol(value, NULL, 0);
10317         else
10318                 i = CTL_DEFAULT_ROTATION_RATE;
10319         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10320         if (lun != NULL &&
10321             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10322                 i = strtol(value, NULL, 0);
10323         else
10324                 i = 0;
10325         bdc_ptr->wab_wac_ff = (i & 0x0f);
10326         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10327
10328         ctl_set_success(ctsio);
10329         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10330         ctsio->be_move_done = ctl_config_move_done;
10331         ctl_datamove((union ctl_io *)ctsio);
10332         return (CTL_RETVAL_COMPLETE);
10333 }
10334
10335 static int
10336 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10337 {
10338         struct scsi_vpd_logical_block_prov *lbp_ptr;
10339         struct ctl_lun *lun;
10340
10341         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10342
10343         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10344         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10345         ctsio->kern_sg_entries = 0;
10346
10347         if (sizeof(*lbp_ptr) < alloc_len) {
10348                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10349                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10350                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10351         } else {
10352                 ctsio->residual = 0;
10353                 ctsio->kern_data_len = alloc_len;
10354                 ctsio->kern_total_len = alloc_len;
10355         }
10356         ctsio->kern_data_resid = 0;
10357         ctsio->kern_rel_offset = 0;
10358         ctsio->kern_sg_entries = 0;
10359
10360         /*
10361          * The control device is always connected.  The disk device, on the
10362          * other hand, may not be online all the time.  Need to change this
10363          * to figure out whether the disk device is actually online or not.
10364          */
10365         if (lun != NULL)
10366                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10367                                   lun->be_lun->lun_type;
10368         else
10369                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10370
10371         lbp_ptr->page_code = SVPD_LBP;
10372         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10373         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10374         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10375                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10376                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10377                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10378         }
10379
10380         ctl_set_success(ctsio);
10381         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10382         ctsio->be_move_done = ctl_config_move_done;
10383         ctl_datamove((union ctl_io *)ctsio);
10384         return (CTL_RETVAL_COMPLETE);
10385 }
10386
10387 /*
10388  * INQUIRY with the EVPD bit set.
10389  */
10390 static int
10391 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10392 {
10393         struct ctl_lun *lun;
10394         struct scsi_inquiry *cdb;
10395         int alloc_len, retval;
10396
10397         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10398         cdb = (struct scsi_inquiry *)ctsio->cdb;
10399         alloc_len = scsi_2btoul(cdb->length);
10400
10401         switch (cdb->page_code) {
10402         case SVPD_SUPPORTED_PAGES:
10403                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10404                 break;
10405         case SVPD_UNIT_SERIAL_NUMBER:
10406                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10407                 break;
10408         case SVPD_DEVICE_ID:
10409                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10410                 break;
10411         case SVPD_EXTENDED_INQUIRY_DATA:
10412                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10413                 break;
10414         case SVPD_MODE_PAGE_POLICY:
10415                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10416                 break;
10417         case SVPD_SCSI_PORTS:
10418                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10419                 break;
10420         case SVPD_SCSI_TPC:
10421                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10422                 break;
10423         case SVPD_BLOCK_LIMITS:
10424                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10425                         goto err;
10426                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10427                 break;
10428         case SVPD_BDC:
10429                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10430                         goto err;
10431                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10432                 break;
10433         case SVPD_LBP:
10434                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10435                         goto err;
10436                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10437                 break;
10438         default:
10439 err:
10440                 ctl_set_invalid_field(ctsio,
10441                                       /*sks_valid*/ 1,
10442                                       /*command*/ 1,
10443                                       /*field*/ 2,
10444                                       /*bit_valid*/ 0,
10445                                       /*bit*/ 0);
10446                 ctl_done((union ctl_io *)ctsio);
10447                 retval = CTL_RETVAL_COMPLETE;
10448                 break;
10449         }
10450
10451         return (retval);
10452 }
10453
10454 /*
10455  * Standard INQUIRY data.
10456  */
10457 static int
10458 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10459 {
10460         struct scsi_inquiry_data *inq_ptr;
10461         struct scsi_inquiry *cdb;
10462         struct ctl_softc *softc;
10463         struct ctl_lun *lun;
10464         char *val;
10465         uint32_t alloc_len, data_len;
10466         ctl_port_type port_type;
10467
10468         softc = control_softc;
10469
10470         /*
10471          * Figure out whether we're talking to a Fibre Channel port or not.
10472          * We treat the ioctl front end, and any SCSI adapters, as packetized
10473          * SCSI front ends.
10474          */
10475         port_type = softc->ctl_ports[
10476             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10477         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10478                 port_type = CTL_PORT_SCSI;
10479
10480         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10481         cdb = (struct scsi_inquiry *)ctsio->cdb;
10482         alloc_len = scsi_2btoul(cdb->length);
10483
10484         /*
10485          * We malloc the full inquiry data size here and fill it
10486          * in.  If the user only asks for less, we'll give him
10487          * that much.
10488          */
10489         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10490         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10491         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10492         ctsio->kern_sg_entries = 0;
10493         ctsio->kern_data_resid = 0;
10494         ctsio->kern_rel_offset = 0;
10495
10496         if (data_len < alloc_len) {
10497                 ctsio->residual = alloc_len - data_len;
10498                 ctsio->kern_data_len = data_len;
10499                 ctsio->kern_total_len = data_len;
10500         } else {
10501                 ctsio->residual = 0;
10502                 ctsio->kern_data_len = alloc_len;
10503                 ctsio->kern_total_len = alloc_len;
10504         }
10505
10506         /*
10507          * If we have a LUN configured, report it as connected.  Otherwise,
10508          * report that it is offline or no device is supported, depending 
10509          * on the value of inquiry_pq_no_lun.
10510          *
10511          * According to the spec (SPC-4 r34), the peripheral qualifier
10512          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10513          *
10514          * "A peripheral device having the specified peripheral device type 
10515          * is not connected to this logical unit. However, the device
10516          * server is capable of supporting the specified peripheral device
10517          * type on this logical unit."
10518          *
10519          * According to the same spec, the peripheral qualifier
10520          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10521          *
10522          * "The device server is not capable of supporting a peripheral
10523          * device on this logical unit. For this peripheral qualifier the
10524          * peripheral device type shall be set to 1Fh. All other peripheral
10525          * device type values are reserved for this peripheral qualifier."
10526          *
10527          * Given the text, it would seem that we probably want to report that
10528          * the LUN is offline here.  There is no LUN connected, but we can
10529          * support a LUN at the given LUN number.
10530          *
10531          * In the real world, though, it sounds like things are a little
10532          * different:
10533          *
10534          * - Linux, when presented with a LUN with the offline peripheral
10535          *   qualifier, will create an sg driver instance for it.  So when
10536          *   you attach it to CTL, you wind up with a ton of sg driver
10537          *   instances.  (One for every LUN that Linux bothered to probe.)
10538          *   Linux does this despite the fact that it issues a REPORT LUNs
10539          *   to LUN 0 to get the inventory of supported LUNs.
10540          *
10541          * - There is other anecdotal evidence (from Emulex folks) about
10542          *   arrays that use the offline peripheral qualifier for LUNs that
10543          *   are on the "passive" path in an active/passive array.
10544          *
10545          * So the solution is provide a hopefully reasonable default
10546          * (return bad/no LUN) and allow the user to change the behavior
10547          * with a tunable/sysctl variable.
10548          */
10549         if (lun != NULL)
10550                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10551                                   lun->be_lun->lun_type;
10552         else if (softc->inquiry_pq_no_lun == 0)
10553                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10554         else
10555                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10556
10557         /* RMB in byte 2 is 0 */
10558         inq_ptr->version = SCSI_REV_SPC4;
10559
10560         /*
10561          * According to SAM-3, even if a device only supports a single
10562          * level of LUN addressing, it should still set the HISUP bit:
10563          *
10564          * 4.9.1 Logical unit numbers overview
10565          *
10566          * All logical unit number formats described in this standard are
10567          * hierarchical in structure even when only a single level in that
10568          * hierarchy is used. The HISUP bit shall be set to one in the
10569          * standard INQUIRY data (see SPC-2) when any logical unit number
10570          * format described in this standard is used.  Non-hierarchical
10571          * formats are outside the scope of this standard.
10572          *
10573          * Therefore we set the HiSup bit here.
10574          *
10575          * The reponse format is 2, per SPC-3.
10576          */
10577         inq_ptr->response_format = SID_HiSup | 2;
10578
10579         inq_ptr->additional_length = data_len -
10580             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10581         CTL_DEBUG_PRINT(("additional_length = %d\n",
10582                          inq_ptr->additional_length));
10583
10584         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10585         /* 16 bit addressing */
10586         if (port_type == CTL_PORT_SCSI)
10587                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10588         /* XXX set the SID_MultiP bit here if we're actually going to
10589            respond on multiple ports */
10590         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10591
10592         /* 16 bit data bus, synchronous transfers */
10593         if (port_type == CTL_PORT_SCSI)
10594                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10595         /*
10596          * XXX KDM do we want to support tagged queueing on the control
10597          * device at all?
10598          */
10599         if ((lun == NULL)
10600          || (lun->be_lun->lun_type != T_PROCESSOR))
10601                 inq_ptr->flags |= SID_CmdQue;
10602         /*
10603          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10604          * We have 8 bytes for the vendor name, and 16 bytes for the device
10605          * name and 4 bytes for the revision.
10606          */
10607         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10608             "vendor")) == NULL) {
10609                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10610         } else {
10611                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10612                 strncpy(inq_ptr->vendor, val,
10613                     min(sizeof(inq_ptr->vendor), strlen(val)));
10614         }
10615         if (lun == NULL) {
10616                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10617                     sizeof(inq_ptr->product));
10618         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10619                 switch (lun->be_lun->lun_type) {
10620                 case T_DIRECT:
10621                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10622                             sizeof(inq_ptr->product));
10623                         break;
10624                 case T_PROCESSOR:
10625                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10626                             sizeof(inq_ptr->product));
10627                         break;
10628                 default:
10629                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10630                             sizeof(inq_ptr->product));
10631                         break;
10632                 }
10633         } else {
10634                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10635                 strncpy(inq_ptr->product, val,
10636                     min(sizeof(inq_ptr->product), strlen(val)));
10637         }
10638
10639         /*
10640          * XXX make this a macro somewhere so it automatically gets
10641          * incremented when we make changes.
10642          */
10643         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10644             "revision")) == NULL) {
10645                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10646         } else {
10647                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10648                 strncpy(inq_ptr->revision, val,
10649                     min(sizeof(inq_ptr->revision), strlen(val)));
10650         }
10651
10652         /*
10653          * For parallel SCSI, we support double transition and single
10654          * transition clocking.  We also support QAS (Quick Arbitration
10655          * and Selection) and Information Unit transfers on both the
10656          * control and array devices.
10657          */
10658         if (port_type == CTL_PORT_SCSI)
10659                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10660                                     SID_SPI_IUS;
10661
10662         /* SAM-5 (no version claimed) */
10663         scsi_ulto2b(0x00A0, inq_ptr->version1);
10664         /* SPC-4 (no version claimed) */
10665         scsi_ulto2b(0x0460, inq_ptr->version2);
10666         if (port_type == CTL_PORT_FC) {
10667                 /* FCP-2 ANSI INCITS.350:2003 */
10668                 scsi_ulto2b(0x0917, inq_ptr->version3);
10669         } else if (port_type == CTL_PORT_SCSI) {
10670                 /* SPI-4 ANSI INCITS.362:200x */
10671                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10672         } else if (port_type == CTL_PORT_ISCSI) {
10673                 /* iSCSI (no version claimed) */
10674                 scsi_ulto2b(0x0960, inq_ptr->version3);
10675         } else if (port_type == CTL_PORT_SAS) {
10676                 /* SAS (no version claimed) */
10677                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10678         }
10679
10680         if (lun == NULL) {
10681                 /* SBC-4 (no version claimed) */
10682                 scsi_ulto2b(0x0600, inq_ptr->version4);
10683         } else {
10684                 switch (lun->be_lun->lun_type) {
10685                 case T_DIRECT:
10686                         /* SBC-4 (no version claimed) */
10687                         scsi_ulto2b(0x0600, inq_ptr->version4);
10688                         break;
10689                 case T_PROCESSOR:
10690                 default:
10691                         break;
10692                 }
10693         }
10694
10695         ctl_set_success(ctsio);
10696         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10697         ctsio->be_move_done = ctl_config_move_done;
10698         ctl_datamove((union ctl_io *)ctsio);
10699         return (CTL_RETVAL_COMPLETE);
10700 }
10701
10702 int
10703 ctl_inquiry(struct ctl_scsiio *ctsio)
10704 {
10705         struct scsi_inquiry *cdb;
10706         int retval;
10707
10708         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10709
10710         cdb = (struct scsi_inquiry *)ctsio->cdb;
10711         if (cdb->byte2 & SI_EVPD)
10712                 retval = ctl_inquiry_evpd(ctsio);
10713         else if (cdb->page_code == 0)
10714                 retval = ctl_inquiry_std(ctsio);
10715         else {
10716                 ctl_set_invalid_field(ctsio,
10717                                       /*sks_valid*/ 1,
10718                                       /*command*/ 1,
10719                                       /*field*/ 2,
10720                                       /*bit_valid*/ 0,
10721                                       /*bit*/ 0);
10722                 ctl_done((union ctl_io *)ctsio);
10723                 return (CTL_RETVAL_COMPLETE);
10724         }
10725
10726         return (retval);
10727 }
10728
10729 /*
10730  * For known CDB types, parse the LBA and length.
10731  */
10732 static int
10733 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10734 {
10735         if (io->io_hdr.io_type != CTL_IO_SCSI)
10736                 return (1);
10737
10738         switch (io->scsiio.cdb[0]) {
10739         case COMPARE_AND_WRITE: {
10740                 struct scsi_compare_and_write *cdb;
10741
10742                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10743
10744                 *lba = scsi_8btou64(cdb->addr);
10745                 *len = cdb->length;
10746                 break;
10747         }
10748         case READ_6:
10749         case WRITE_6: {
10750                 struct scsi_rw_6 *cdb;
10751
10752                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10753
10754                 *lba = scsi_3btoul(cdb->addr);
10755                 /* only 5 bits are valid in the most significant address byte */
10756                 *lba &= 0x1fffff;
10757                 *len = cdb->length;
10758                 break;
10759         }
10760         case READ_10:
10761         case WRITE_10: {
10762                 struct scsi_rw_10 *cdb;
10763
10764                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10765
10766                 *lba = scsi_4btoul(cdb->addr);
10767                 *len = scsi_2btoul(cdb->length);
10768                 break;
10769         }
10770         case WRITE_VERIFY_10: {
10771                 struct scsi_write_verify_10 *cdb;
10772
10773                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10774
10775                 *lba = scsi_4btoul(cdb->addr);
10776                 *len = scsi_2btoul(cdb->length);
10777                 break;
10778         }
10779         case READ_12:
10780         case WRITE_12: {
10781                 struct scsi_rw_12 *cdb;
10782
10783                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10784
10785                 *lba = scsi_4btoul(cdb->addr);
10786                 *len = scsi_4btoul(cdb->length);
10787                 break;
10788         }
10789         case WRITE_VERIFY_12: {
10790                 struct scsi_write_verify_12 *cdb;
10791
10792                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10793
10794                 *lba = scsi_4btoul(cdb->addr);
10795                 *len = scsi_4btoul(cdb->length);
10796                 break;
10797         }
10798         case READ_16:
10799         case WRITE_16:
10800         case WRITE_ATOMIC_16: {
10801                 struct scsi_rw_16 *cdb;
10802
10803                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10804
10805                 *lba = scsi_8btou64(cdb->addr);
10806                 *len = scsi_4btoul(cdb->length);
10807                 break;
10808         }
10809         case WRITE_VERIFY_16: {
10810                 struct scsi_write_verify_16 *cdb;
10811
10812                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10813
10814                 *lba = scsi_8btou64(cdb->addr);
10815                 *len = scsi_4btoul(cdb->length);
10816                 break;
10817         }
10818         case WRITE_SAME_10: {
10819                 struct scsi_write_same_10 *cdb;
10820
10821                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10822
10823                 *lba = scsi_4btoul(cdb->addr);
10824                 *len = scsi_2btoul(cdb->length);
10825                 break;
10826         }
10827         case WRITE_SAME_16: {
10828                 struct scsi_write_same_16 *cdb;
10829
10830                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10831
10832                 *lba = scsi_8btou64(cdb->addr);
10833                 *len = scsi_4btoul(cdb->length);
10834                 break;
10835         }
10836         case VERIFY_10: {
10837                 struct scsi_verify_10 *cdb;
10838
10839                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10840
10841                 *lba = scsi_4btoul(cdb->addr);
10842                 *len = scsi_2btoul(cdb->length);
10843                 break;
10844         }
10845         case VERIFY_12: {
10846                 struct scsi_verify_12 *cdb;
10847
10848                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10849
10850                 *lba = scsi_4btoul(cdb->addr);
10851                 *len = scsi_4btoul(cdb->length);
10852                 break;
10853         }
10854         case VERIFY_16: {
10855                 struct scsi_verify_16 *cdb;
10856
10857                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10858
10859                 *lba = scsi_8btou64(cdb->addr);
10860                 *len = scsi_4btoul(cdb->length);
10861                 break;
10862         }
10863         case UNMAP: {
10864                 *lba = 0;
10865                 *len = UINT64_MAX;
10866                 break;
10867         }
10868         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10869                 struct scsi_get_lba_status *cdb;
10870
10871                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10872                 *lba = scsi_8btou64(cdb->addr);
10873                 *len = UINT32_MAX;
10874                 break;
10875         }
10876         default:
10877                 return (1);
10878                 break; /* NOTREACHED */
10879         }
10880
10881         return (0);
10882 }
10883
10884 static ctl_action
10885 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10886     bool seq)
10887 {
10888         uint64_t endlba1, endlba2;
10889
10890         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10891         endlba2 = lba2 + len2 - 1;
10892
10893         if ((endlba1 < lba2) || (endlba2 < lba1))
10894                 return (CTL_ACTION_PASS);
10895         else
10896                 return (CTL_ACTION_BLOCK);
10897 }
10898
10899 static int
10900 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10901 {
10902         struct ctl_ptr_len_flags *ptrlen;
10903         struct scsi_unmap_desc *buf, *end, *range;
10904         uint64_t lba;
10905         uint32_t len;
10906
10907         /* If not UNMAP -- go other way. */
10908         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10909             io->scsiio.cdb[0] != UNMAP)
10910                 return (CTL_ACTION_ERROR);
10911
10912         /* If UNMAP without data -- block and wait for data. */
10913         ptrlen = (struct ctl_ptr_len_flags *)
10914             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10915         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10916             ptrlen->ptr == NULL)
10917                 return (CTL_ACTION_BLOCK);
10918
10919         /* UNMAP with data -- check for collision. */
10920         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10921         end = buf + ptrlen->len / sizeof(*buf);
10922         for (range = buf; range < end; range++) {
10923                 lba = scsi_8btou64(range->lba);
10924                 len = scsi_4btoul(range->length);
10925                 if ((lba < lba2 + len2) && (lba + len > lba2))
10926                         return (CTL_ACTION_BLOCK);
10927         }
10928         return (CTL_ACTION_PASS);
10929 }
10930
10931 static ctl_action
10932 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10933 {
10934         uint64_t lba1, lba2;
10935         uint64_t len1, len2;
10936         int retval;
10937
10938         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10939                 return (CTL_ACTION_ERROR);
10940
10941         retval = ctl_extent_check_unmap(io1, lba2, len2);
10942         if (retval != CTL_ACTION_ERROR)
10943                 return (retval);
10944
10945         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10946                 return (CTL_ACTION_ERROR);
10947
10948         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10949 }
10950
10951 static ctl_action
10952 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10953 {
10954         uint64_t lba1, lba2;
10955         uint64_t len1, len2;
10956
10957         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10958                 return (CTL_ACTION_ERROR);
10959         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10960                 return (CTL_ACTION_ERROR);
10961
10962         if (lba1 + len1 == lba2)
10963                 return (CTL_ACTION_BLOCK);
10964         return (CTL_ACTION_PASS);
10965 }
10966
10967 static ctl_action
10968 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10969     union ctl_io *ooa_io)
10970 {
10971         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10972         ctl_serialize_action *serialize_row;
10973
10974         /*
10975          * The initiator attempted multiple untagged commands at the same
10976          * time.  Can't do that.
10977          */
10978         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10979          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10980          && ((pending_io->io_hdr.nexus.targ_port ==
10981               ooa_io->io_hdr.nexus.targ_port)
10982           && (pending_io->io_hdr.nexus.initid.id ==
10983               ooa_io->io_hdr.nexus.initid.id))
10984          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10985               CTL_FLAG_STATUS_SENT)) == 0))
10986                 return (CTL_ACTION_OVERLAP);
10987
10988         /*
10989          * The initiator attempted to send multiple tagged commands with
10990          * the same ID.  (It's fine if different initiators have the same
10991          * tag ID.)
10992          *
10993          * Even if all of those conditions are true, we don't kill the I/O
10994          * if the command ahead of us has been aborted.  We won't end up
10995          * sending it to the FETD, and it's perfectly legal to resend a
10996          * command with the same tag number as long as the previous
10997          * instance of this tag number has been aborted somehow.
10998          */
10999         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11000          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11001          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11002          && ((pending_io->io_hdr.nexus.targ_port ==
11003               ooa_io->io_hdr.nexus.targ_port)
11004           && (pending_io->io_hdr.nexus.initid.id ==
11005               ooa_io->io_hdr.nexus.initid.id))
11006          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11007               CTL_FLAG_STATUS_SENT)) == 0))
11008                 return (CTL_ACTION_OVERLAP_TAG);
11009
11010         /*
11011          * If we get a head of queue tag, SAM-3 says that we should
11012          * immediately execute it.
11013          *
11014          * What happens if this command would normally block for some other
11015          * reason?  e.g. a request sense with a head of queue tag
11016          * immediately after a write.  Normally that would block, but this
11017          * will result in its getting executed immediately...
11018          *
11019          * We currently return "pass" instead of "skip", so we'll end up
11020          * going through the rest of the queue to check for overlapped tags.
11021          *
11022          * XXX KDM check for other types of blockage first??
11023          */
11024         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11025                 return (CTL_ACTION_PASS);
11026
11027         /*
11028          * Ordered tags have to block until all items ahead of them
11029          * have completed.  If we get called with an ordered tag, we always
11030          * block, if something else is ahead of us in the queue.
11031          */
11032         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11033                 return (CTL_ACTION_BLOCK);
11034
11035         /*
11036          * Simple tags get blocked until all head of queue and ordered tags
11037          * ahead of them have completed.  I'm lumping untagged commands in
11038          * with simple tags here.  XXX KDM is that the right thing to do?
11039          */
11040         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11041           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11042          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11043           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11044                 return (CTL_ACTION_BLOCK);
11045
11046         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11047         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11048
11049         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11050
11051         switch (serialize_row[pending_entry->seridx]) {
11052         case CTL_SER_BLOCK:
11053                 return (CTL_ACTION_BLOCK);
11054         case CTL_SER_EXTENT:
11055                 return (ctl_extent_check(ooa_io, pending_io,
11056                     (lun->serseq == CTL_LUN_SERSEQ_ON)));
11057         case CTL_SER_EXTENTOPT:
11058                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11059                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11060                         return (ctl_extent_check(ooa_io, pending_io,
11061                             (lun->serseq == CTL_LUN_SERSEQ_ON)));
11062                 return (CTL_ACTION_PASS);
11063         case CTL_SER_EXTENTSEQ:
11064                 if (lun->serseq != CTL_LUN_SERSEQ_OFF)
11065                         return (ctl_extent_check_seq(ooa_io, pending_io));
11066                 return (CTL_ACTION_PASS);
11067         case CTL_SER_PASS:
11068                 return (CTL_ACTION_PASS);
11069         case CTL_SER_BLOCKOPT:
11070                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11071                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11072                         return (CTL_ACTION_BLOCK);
11073                 return (CTL_ACTION_PASS);
11074         case CTL_SER_SKIP:
11075                 return (CTL_ACTION_SKIP);
11076         default:
11077                 panic("invalid serialization value %d",
11078                       serialize_row[pending_entry->seridx]);
11079         }
11080
11081         return (CTL_ACTION_ERROR);
11082 }
11083
11084 /*
11085  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11086  * Assumptions:
11087  * - pending_io is generally either incoming, or on the blocked queue
11088  * - starting I/O is the I/O we want to start the check with.
11089  */
11090 static ctl_action
11091 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11092               union ctl_io *starting_io)
11093 {
11094         union ctl_io *ooa_io;
11095         ctl_action action;
11096
11097         mtx_assert(&lun->lun_lock, MA_OWNED);
11098
11099         /*
11100          * Run back along the OOA queue, starting with the current
11101          * blocked I/O and going through every I/O before it on the
11102          * queue.  If starting_io is NULL, we'll just end up returning
11103          * CTL_ACTION_PASS.
11104          */
11105         for (ooa_io = starting_io; ooa_io != NULL;
11106              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11107              ooa_links)){
11108
11109                 /*
11110                  * This routine just checks to see whether
11111                  * cur_blocked is blocked by ooa_io, which is ahead
11112                  * of it in the queue.  It doesn't queue/dequeue
11113                  * cur_blocked.
11114                  */
11115                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11116                 switch (action) {
11117                 case CTL_ACTION_BLOCK:
11118                 case CTL_ACTION_OVERLAP:
11119                 case CTL_ACTION_OVERLAP_TAG:
11120                 case CTL_ACTION_SKIP:
11121                 case CTL_ACTION_ERROR:
11122                         return (action);
11123                         break; /* NOTREACHED */
11124                 case CTL_ACTION_PASS:
11125                         break;
11126                 default:
11127                         panic("invalid action %d", action);
11128                         break;  /* NOTREACHED */
11129                 }
11130         }
11131
11132         return (CTL_ACTION_PASS);
11133 }
11134
11135 /*
11136  * Assumptions:
11137  * - An I/O has just completed, and has been removed from the per-LUN OOA
11138  *   queue, so some items on the blocked queue may now be unblocked.
11139  */
11140 static int
11141 ctl_check_blocked(struct ctl_lun *lun)
11142 {
11143         union ctl_io *cur_blocked, *next_blocked;
11144
11145         mtx_assert(&lun->lun_lock, MA_OWNED);
11146
11147         /*
11148          * Run forward from the head of the blocked queue, checking each
11149          * entry against the I/Os prior to it on the OOA queue to see if
11150          * there is still any blockage.
11151          *
11152          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11153          * with our removing a variable on it while it is traversing the
11154          * list.
11155          */
11156         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11157              cur_blocked != NULL; cur_blocked = next_blocked) {
11158                 union ctl_io *prev_ooa;
11159                 ctl_action action;
11160
11161                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11162                                                           blocked_links);
11163
11164                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11165                                                       ctl_ooaq, ooa_links);
11166
11167                 /*
11168                  * If cur_blocked happens to be the first item in the OOA
11169                  * queue now, prev_ooa will be NULL, and the action
11170                  * returned will just be CTL_ACTION_PASS.
11171                  */
11172                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11173
11174                 switch (action) {
11175                 case CTL_ACTION_BLOCK:
11176                         /* Nothing to do here, still blocked */
11177                         break;
11178                 case CTL_ACTION_OVERLAP:
11179                 case CTL_ACTION_OVERLAP_TAG:
11180                         /*
11181                          * This shouldn't happen!  In theory we've already
11182                          * checked this command for overlap...
11183                          */
11184                         break;
11185                 case CTL_ACTION_PASS:
11186                 case CTL_ACTION_SKIP: {
11187                         const struct ctl_cmd_entry *entry;
11188                         int isc_retval;
11189
11190                         /*
11191                          * The skip case shouldn't happen, this transaction
11192                          * should have never made it onto the blocked queue.
11193                          */
11194                         /*
11195                          * This I/O is no longer blocked, we can remove it
11196                          * from the blocked queue.  Since this is a TAILQ
11197                          * (doubly linked list), we can do O(1) removals
11198                          * from any place on the list.
11199                          */
11200                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11201                                      blocked_links);
11202                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11203
11204                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11205                                 /*
11206                                  * Need to send IO back to original side to
11207                                  * run
11208                                  */
11209                                 union ctl_ha_msg msg_info;
11210
11211                                 msg_info.hdr.original_sc =
11212                                         cur_blocked->io_hdr.original_sc;
11213                                 msg_info.hdr.serializing_sc = cur_blocked;
11214                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11215                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11216                                      &msg_info, sizeof(msg_info), 0)) >
11217                                      CTL_HA_STATUS_SUCCESS) {
11218                                         printf("CTL:Check Blocked error from "
11219                                                "ctl_ha_msg_send %d\n",
11220                                                isc_retval);
11221                                 }
11222                                 break;
11223                         }
11224                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11225
11226                         /*
11227                          * Check this I/O for LUN state changes that may
11228                          * have happened while this command was blocked.
11229                          * The LUN state may have been changed by a command
11230                          * ahead of us in the queue, so we need to re-check
11231                          * for any states that can be caused by SCSI
11232                          * commands.
11233                          */
11234                         if (ctl_scsiio_lun_check(lun, entry,
11235                                                  &cur_blocked->scsiio) == 0) {
11236                                 cur_blocked->io_hdr.flags |=
11237                                                       CTL_FLAG_IS_WAS_ON_RTR;
11238                                 ctl_enqueue_rtr(cur_blocked);
11239                         } else
11240                                 ctl_done(cur_blocked);
11241                         break;
11242                 }
11243                 default:
11244                         /*
11245                          * This probably shouldn't happen -- we shouldn't
11246                          * get CTL_ACTION_ERROR, or anything else.
11247                          */
11248                         break;
11249                 }
11250         }
11251
11252         return (CTL_RETVAL_COMPLETE);
11253 }
11254
11255 /*
11256  * This routine (with one exception) checks LUN flags that can be set by
11257  * commands ahead of us in the OOA queue.  These flags have to be checked
11258  * when a command initially comes in, and when we pull a command off the
11259  * blocked queue and are preparing to execute it.  The reason we have to
11260  * check these flags for commands on the blocked queue is that the LUN
11261  * state may have been changed by a command ahead of us while we're on the
11262  * blocked queue.
11263  *
11264  * Ordering is somewhat important with these checks, so please pay
11265  * careful attention to the placement of any new checks.
11266  */
11267 static int
11268 ctl_scsiio_lun_check(struct ctl_lun *lun,
11269     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11270 {
11271         struct ctl_softc *softc = lun->ctl_softc;
11272         int retval;
11273         uint32_t residx;
11274
11275         retval = 0;
11276
11277         mtx_assert(&lun->lun_lock, MA_OWNED);
11278
11279         /*
11280          * If this shelf is a secondary shelf controller, we have to reject
11281          * any media access commands.
11282          */
11283         if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11284             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11285                 ctl_set_lun_standby(ctsio);
11286                 retval = 1;
11287                 goto bailout;
11288         }
11289
11290         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11291                 if (lun->flags & CTL_LUN_READONLY) {
11292                         ctl_set_sense(ctsio, /*current_error*/ 1,
11293                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11294                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11295                         retval = 1;
11296                         goto bailout;
11297                 }
11298                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11299                     .eca_and_aen & SCP_SWP) != 0) {
11300                         ctl_set_sense(ctsio, /*current_error*/ 1,
11301                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11302                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11303                         retval = 1;
11304                         goto bailout;
11305                 }
11306         }
11307
11308         /*
11309          * Check for a reservation conflict.  If this command isn't allowed
11310          * even on reserved LUNs, and if this initiator isn't the one who
11311          * reserved us, reject the command with a reservation conflict.
11312          */
11313         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11314         if ((lun->flags & CTL_LUN_RESERVED)
11315          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11316                 if (lun->res_idx != residx) {
11317                         ctl_set_reservation_conflict(ctsio);
11318                         retval = 1;
11319                         goto bailout;
11320                 }
11321         }
11322
11323         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11324             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11325                 /* No reservation or command is allowed. */;
11326         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11327             (lun->res_type == SPR_TYPE_WR_EX ||
11328              lun->res_type == SPR_TYPE_WR_EX_RO ||
11329              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11330                 /* The command is allowed for Write Exclusive resv. */;
11331         } else {
11332                 /*
11333                  * if we aren't registered or it's a res holder type
11334                  * reservation and this isn't the res holder then set a
11335                  * conflict.
11336                  */
11337                 if (ctl_get_prkey(lun, residx) == 0
11338                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11339                         ctl_set_reservation_conflict(ctsio);
11340                         retval = 1;
11341                         goto bailout;
11342                 }
11343
11344         }
11345
11346         if ((lun->flags & CTL_LUN_OFFLINE)
11347          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11348                 ctl_set_lun_not_ready(ctsio);
11349                 retval = 1;
11350                 goto bailout;
11351         }
11352
11353         /*
11354          * If the LUN is stopped, see if this particular command is allowed
11355          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11356          */
11357         if ((lun->flags & CTL_LUN_STOPPED)
11358          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11359                 /* "Logical unit not ready, initializing cmd. required" */
11360                 ctl_set_lun_stopped(ctsio);
11361                 retval = 1;
11362                 goto bailout;
11363         }
11364
11365         if ((lun->flags & CTL_LUN_INOPERABLE)
11366          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11367                 /* "Medium format corrupted" */
11368                 ctl_set_medium_format_corrupted(ctsio);
11369                 retval = 1;
11370                 goto bailout;
11371         }
11372
11373 bailout:
11374         return (retval);
11375
11376 }
11377
11378 static void
11379 ctl_failover_io(union ctl_io *io, int have_lock)
11380 {
11381         ctl_set_busy(&io->scsiio);
11382         ctl_done(io);
11383 }
11384
11385 static void
11386 ctl_failover(void)
11387 {
11388         struct ctl_lun *lun;
11389         struct ctl_softc *softc;
11390         union ctl_io *next_io, *pending_io;
11391         union ctl_io *io;
11392         int lun_idx;
11393
11394         softc = control_softc;
11395
11396         mtx_lock(&softc->ctl_lock);
11397         /*
11398          * Remove any cmds from the other SC from the rtr queue.  These
11399          * will obviously only be for LUNs for which we're the primary.
11400          * We can't send status or get/send data for these commands.
11401          * Since they haven't been executed yet, we can just remove them.
11402          * We'll either abort them or delete them below, depending on
11403          * which HA mode we're in.
11404          */
11405 #ifdef notyet
11406         mtx_lock(&softc->queue_lock);
11407         for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11408              io != NULL; io = next_io) {
11409                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11410                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11411                         STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11412                                       ctl_io_hdr, links);
11413         }
11414         mtx_unlock(&softc->queue_lock);
11415 #endif
11416
11417         for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11418                 lun = softc->ctl_luns[lun_idx];
11419                 if (lun==NULL)
11420                         continue;
11421
11422                 /*
11423                  * Processor LUNs are primary on both sides.
11424                  * XXX will this always be true?
11425                  */
11426                 if (lun->be_lun->lun_type == T_PROCESSOR)
11427                         continue;
11428
11429                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11430                  && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11431                         printf("FAILOVER: primary lun %d\n", lun_idx);
11432                         /*
11433                          * Remove all commands from the other SC. First from the
11434                          * blocked queue then from the ooa queue. Once we have
11435                          * removed them. Call ctl_check_blocked to see if there
11436                          * is anything that can run.
11437                          */
11438                         for (io = (union ctl_io *)TAILQ_FIRST(
11439                              &lun->blocked_queue); io != NULL; io = next_io) {
11440
11441                                 next_io = (union ctl_io *)TAILQ_NEXT(
11442                                     &io->io_hdr, blocked_links);
11443
11444                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11445                                         TAILQ_REMOVE(&lun->blocked_queue,
11446                                                      &io->io_hdr,blocked_links);
11447                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11448                                         TAILQ_REMOVE(&lun->ooa_queue,
11449                                                      &io->io_hdr, ooa_links);
11450
11451                                         ctl_free_io(io);
11452                                 }
11453                         }
11454
11455                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11456                              io != NULL; io = next_io) {
11457
11458                                 next_io = (union ctl_io *)TAILQ_NEXT(
11459                                     &io->io_hdr, ooa_links);
11460
11461                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11462
11463                                         TAILQ_REMOVE(&lun->ooa_queue,
11464                                                 &io->io_hdr,
11465                                                 ooa_links);
11466
11467                                         ctl_free_io(io);
11468                                 }
11469                         }
11470                         ctl_check_blocked(lun);
11471                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11472                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11473
11474                         printf("FAILOVER: primary lun %d\n", lun_idx);
11475                         /*
11476                          * Abort all commands from the other SC.  We can't
11477                          * send status back for them now.  These should get
11478                          * cleaned up when they are completed or come out
11479                          * for a datamove operation.
11480                          */
11481                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11482                              io != NULL; io = next_io) {
11483                                 next_io = (union ctl_io *)TAILQ_NEXT(
11484                                         &io->io_hdr, ooa_links);
11485
11486                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11487                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11488                         }
11489                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11490                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11491
11492                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11493
11494                         lun->flags |= CTL_LUN_PRIMARY_SC;
11495
11496                         /*
11497                          * We send all I/O that was sent to this controller
11498                          * and redirected to the other side back with
11499                          * busy status, and have the initiator retry it.
11500                          * Figuring out how much data has been transferred,
11501                          * etc. and picking up where we left off would be 
11502                          * very tricky.
11503                          *
11504                          * XXX KDM need to remove I/O from the blocked
11505                          * queue as well!
11506                          */
11507                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11508                              &lun->ooa_queue); pending_io != NULL;
11509                              pending_io = next_io) {
11510
11511                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11512                                         &pending_io->io_hdr, ooa_links);
11513
11514                                 pending_io->io_hdr.flags &=
11515                                         ~CTL_FLAG_SENT_2OTHER_SC;
11516
11517                                 if (pending_io->io_hdr.flags &
11518                                     CTL_FLAG_IO_ACTIVE) {
11519                                         pending_io->io_hdr.flags |=
11520                                                 CTL_FLAG_FAILOVER;
11521                                 } else {
11522                                         ctl_set_busy(&pending_io->scsiio);
11523                                         ctl_done(pending_io);
11524                                 }
11525                         }
11526
11527                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11528                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11529                         && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11530                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11531                         /*
11532                          * if the first io on the OOA is not on the RtR queue
11533                          * add it.
11534                          */
11535                         lun->flags |= CTL_LUN_PRIMARY_SC;
11536
11537                         pending_io = (union ctl_io *)TAILQ_FIRST(
11538                             &lun->ooa_queue);
11539                         if (pending_io==NULL) {
11540                                 printf("Nothing on OOA queue\n");
11541                                 continue;
11542                         }
11543
11544                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11545                         if ((pending_io->io_hdr.flags &
11546                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11547                                 pending_io->io_hdr.flags |=
11548                                     CTL_FLAG_IS_WAS_ON_RTR;
11549                                 ctl_enqueue_rtr(pending_io);
11550                         }
11551 #if 0
11552                         else
11553                         {
11554                                 printf("Tag 0x%04x is running\n",
11555                                       pending_io->scsiio.tag_num);
11556                         }
11557 #endif
11558
11559                         next_io = (union ctl_io *)TAILQ_NEXT(
11560                             &pending_io->io_hdr, ooa_links);
11561                         for (pending_io=next_io; pending_io != NULL;
11562                              pending_io = next_io) {
11563                                 pending_io->io_hdr.flags &=
11564                                     ~CTL_FLAG_SENT_2OTHER_SC;
11565                                 next_io = (union ctl_io *)TAILQ_NEXT(
11566                                         &pending_io->io_hdr, ooa_links);
11567                                 if (pending_io->io_hdr.flags &
11568                                     CTL_FLAG_IS_WAS_ON_RTR) {
11569 #if 0
11570                                         printf("Tag 0x%04x is running\n",
11571                                                 pending_io->scsiio.tag_num);
11572 #endif
11573                                         continue;
11574                                 }
11575
11576                                 switch (ctl_check_ooa(lun, pending_io,
11577                                     (union ctl_io *)TAILQ_PREV(
11578                                     &pending_io->io_hdr, ctl_ooaq,
11579                                     ooa_links))) {
11580
11581                                 case CTL_ACTION_BLOCK:
11582                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11583                                                           &pending_io->io_hdr,
11584                                                           blocked_links);
11585                                         pending_io->io_hdr.flags |=
11586                                             CTL_FLAG_BLOCKED;
11587                                         break;
11588                                 case CTL_ACTION_PASS:
11589                                 case CTL_ACTION_SKIP:
11590                                         pending_io->io_hdr.flags |=
11591                                             CTL_FLAG_IS_WAS_ON_RTR;
11592                                         ctl_enqueue_rtr(pending_io);
11593                                         break;
11594                                 case CTL_ACTION_OVERLAP:
11595                                         ctl_set_overlapped_cmd(
11596                                             (struct ctl_scsiio *)pending_io);
11597                                         ctl_done(pending_io);
11598                                         break;
11599                                 case CTL_ACTION_OVERLAP_TAG:
11600                                         ctl_set_overlapped_tag(
11601                                             (struct ctl_scsiio *)pending_io,
11602                                             pending_io->scsiio.tag_num & 0xff);
11603                                         ctl_done(pending_io);
11604                                         break;
11605                                 case CTL_ACTION_ERROR:
11606                                 default:
11607                                         ctl_set_internal_failure(
11608                                                 (struct ctl_scsiio *)pending_io,
11609                                                 0,  // sks_valid
11610                                                 0); //retry count
11611                                         ctl_done(pending_io);
11612                                         break;
11613                                 }
11614                         }
11615
11616                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11617                 } else {
11618                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11619                               "ha_mode = #%x", lun->flags, softc->ha_mode);
11620                 }
11621         }
11622         ctl_pause_rtr = 0;
11623         mtx_unlock(&softc->ctl_lock);
11624 }
11625
11626 static void
11627 ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
11628              ctl_ua_type ua_type)
11629 {
11630         struct ctl_lun *lun;
11631         ctl_ua_type *pu;
11632
11633         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
11634
11635         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
11636                 mtx_lock(&lun->lun_lock);
11637                 pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
11638                 if (pu != NULL)
11639                         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua_type;
11640                 mtx_unlock(&lun->lun_lock);
11641         }
11642 }
11643
11644 static int
11645 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11646 {
11647         struct ctl_lun *lun;
11648         const struct ctl_cmd_entry *entry;
11649         uint32_t initidx, targ_lun;
11650         int retval;
11651
11652         retval = 0;
11653
11654         lun = NULL;
11655
11656         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11657         if ((targ_lun < CTL_MAX_LUNS)
11658          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11659                 /*
11660                  * If the LUN is invalid, pretend that it doesn't exist.
11661                  * It will go away as soon as all pending I/O has been
11662                  * completed.
11663                  */
11664                 mtx_lock(&lun->lun_lock);
11665                 if (lun->flags & CTL_LUN_DISABLED) {
11666                         mtx_unlock(&lun->lun_lock);
11667                         lun = NULL;
11668                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11669                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11670                 } else {
11671                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11672                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11673                                 lun->be_lun;
11674                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11675                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11676                         }
11677
11678                         /*
11679                          * Every I/O goes into the OOA queue for a
11680                          * particular LUN, and stays there until completion.
11681                          */
11682 #ifdef CTL_TIME_IO
11683                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11684                                 lun->idle_time += getsbinuptime() -
11685                                     lun->last_busy;
11686                         }
11687 #endif
11688                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11689                             ooa_links);
11690                 }
11691         } else {
11692                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11693                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11694         }
11695
11696         /* Get command entry and return error if it is unsuppotyed. */
11697         entry = ctl_validate_command(ctsio);
11698         if (entry == NULL) {
11699                 if (lun)
11700                         mtx_unlock(&lun->lun_lock);
11701                 return (retval);
11702         }
11703
11704         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11705         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11706
11707         /*
11708          * Check to see whether we can send this command to LUNs that don't
11709          * exist.  This should pretty much only be the case for inquiry
11710          * and request sense.  Further checks, below, really require having
11711          * a LUN, so we can't really check the command anymore.  Just put
11712          * it on the rtr queue.
11713          */
11714         if (lun == NULL) {
11715                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11716                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11717                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11718                         return (retval);
11719                 }
11720
11721                 ctl_set_unsupported_lun(ctsio);
11722                 ctl_done((union ctl_io *)ctsio);
11723                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11724                 return (retval);
11725         } else {
11726                 /*
11727                  * Make sure we support this particular command on this LUN.
11728                  * e.g., we don't support writes to the control LUN.
11729                  */
11730                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11731                         mtx_unlock(&lun->lun_lock);
11732                         ctl_set_invalid_opcode(ctsio);
11733                         ctl_done((union ctl_io *)ctsio);
11734                         return (retval);
11735                 }
11736         }
11737
11738         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11739
11740 #ifdef CTL_WITH_CA
11741         /*
11742          * If we've got a request sense, it'll clear the contingent
11743          * allegiance condition.  Otherwise, if we have a CA condition for
11744          * this initiator, clear it, because it sent down a command other
11745          * than request sense.
11746          */
11747         if ((ctsio->cdb[0] != REQUEST_SENSE)
11748          && (ctl_is_set(lun->have_ca, initidx)))
11749                 ctl_clear_mask(lun->have_ca, initidx);
11750 #endif
11751
11752         /*
11753          * If the command has this flag set, it handles its own unit
11754          * attention reporting, we shouldn't do anything.  Otherwise we
11755          * check for any pending unit attentions, and send them back to the
11756          * initiator.  We only do this when a command initially comes in,
11757          * not when we pull it off the blocked queue.
11758          *
11759          * According to SAM-3, section 5.3.2, the order that things get
11760          * presented back to the host is basically unit attentions caused
11761          * by some sort of reset event, busy status, reservation conflicts
11762          * or task set full, and finally any other status.
11763          *
11764          * One issue here is that some of the unit attentions we report
11765          * don't fall into the "reset" category (e.g. "reported luns data
11766          * has changed").  So reporting it here, before the reservation
11767          * check, may be technically wrong.  I guess the only thing to do
11768          * would be to check for and report the reset events here, and then
11769          * check for the other unit attention types after we check for a
11770          * reservation conflict.
11771          *
11772          * XXX KDM need to fix this
11773          */
11774         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11775                 ctl_ua_type ua_type;
11776                 scsi_sense_data_type sense_format;
11777
11778                 if (lun->flags & CTL_LUN_SENSE_DESC)
11779                         sense_format = SSD_TYPE_DESC;
11780                 else
11781                         sense_format = SSD_TYPE_FIXED;
11782
11783                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11784                     sense_format);
11785                 if (ua_type != CTL_UA_NONE) {
11786                         mtx_unlock(&lun->lun_lock);
11787                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11788                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11789                         ctsio->sense_len = SSD_FULL_SIZE;
11790                         ctl_done((union ctl_io *)ctsio);
11791                         return (retval);
11792                 }
11793         }
11794
11795
11796         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11797                 mtx_unlock(&lun->lun_lock);
11798                 ctl_done((union ctl_io *)ctsio);
11799                 return (retval);
11800         }
11801
11802         /*
11803          * XXX CHD this is where we want to send IO to other side if
11804          * this LUN is secondary on this SC. We will need to make a copy
11805          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11806          * the copy we send as FROM_OTHER.
11807          * We also need to stuff the address of the original IO so we can
11808          * find it easily. Something similar will need be done on the other
11809          * side so when we are done we can find the copy.
11810          */
11811         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11812                 union ctl_ha_msg msg_info;
11813                 int isc_retval;
11814
11815                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11816
11817                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11818                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11819 #if 0
11820                 printf("1. ctsio %p\n", ctsio);
11821 #endif
11822                 msg_info.hdr.serializing_sc = NULL;
11823                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11824                 msg_info.scsi.tag_num = ctsio->tag_num;
11825                 msg_info.scsi.tag_type = ctsio->tag_type;
11826                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11827
11828                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11829
11830                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11831                     (void *)&msg_info, sizeof(msg_info), 0)) >
11832                     CTL_HA_STATUS_SUCCESS) {
11833                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11834                                isc_retval);
11835                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11836                 } else {
11837 #if 0
11838                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11839 #endif
11840                 }
11841
11842                 /*
11843                  * XXX KDM this I/O is off the incoming queue, but hasn't
11844                  * been inserted on any other queue.  We may need to come
11845                  * up with a holding queue while we wait for serialization
11846                  * so that we have an idea of what we're waiting for from
11847                  * the other side.
11848                  */
11849                 mtx_unlock(&lun->lun_lock);
11850                 return (retval);
11851         }
11852
11853         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11854                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11855                               ctl_ooaq, ooa_links))) {
11856         case CTL_ACTION_BLOCK:
11857                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11858                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11859                                   blocked_links);
11860                 mtx_unlock(&lun->lun_lock);
11861                 return (retval);
11862         case CTL_ACTION_PASS:
11863         case CTL_ACTION_SKIP:
11864                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11865                 mtx_unlock(&lun->lun_lock);
11866                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11867                 break;
11868         case CTL_ACTION_OVERLAP:
11869                 mtx_unlock(&lun->lun_lock);
11870                 ctl_set_overlapped_cmd(ctsio);
11871                 ctl_done((union ctl_io *)ctsio);
11872                 break;
11873         case CTL_ACTION_OVERLAP_TAG:
11874                 mtx_unlock(&lun->lun_lock);
11875                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11876                 ctl_done((union ctl_io *)ctsio);
11877                 break;
11878         case CTL_ACTION_ERROR:
11879         default:
11880                 mtx_unlock(&lun->lun_lock);
11881                 ctl_set_internal_failure(ctsio,
11882                                          /*sks_valid*/ 0,
11883                                          /*retry_count*/ 0);
11884                 ctl_done((union ctl_io *)ctsio);
11885                 break;
11886         }
11887         return (retval);
11888 }
11889
11890 const struct ctl_cmd_entry *
11891 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11892 {
11893         const struct ctl_cmd_entry *entry;
11894         int service_action;
11895
11896         entry = &ctl_cmd_table[ctsio->cdb[0]];
11897         if (sa)
11898                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11899         if (entry->flags & CTL_CMD_FLAG_SA5) {
11900                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11901                 entry = &((const struct ctl_cmd_entry *)
11902                     entry->execute)[service_action];
11903         }
11904         return (entry);
11905 }
11906
11907 const struct ctl_cmd_entry *
11908 ctl_validate_command(struct ctl_scsiio *ctsio)
11909 {
11910         const struct ctl_cmd_entry *entry;
11911         int i, sa;
11912         uint8_t diff;
11913
11914         entry = ctl_get_cmd_entry(ctsio, &sa);
11915         if (entry->execute == NULL) {
11916                 if (sa)
11917                         ctl_set_invalid_field(ctsio,
11918                                               /*sks_valid*/ 1,
11919                                               /*command*/ 1,
11920                                               /*field*/ 1,
11921                                               /*bit_valid*/ 1,
11922                                               /*bit*/ 4);
11923                 else
11924                         ctl_set_invalid_opcode(ctsio);
11925                 ctl_done((union ctl_io *)ctsio);
11926                 return (NULL);
11927         }
11928         KASSERT(entry->length > 0,
11929             ("Not defined length for command 0x%02x/0x%02x",
11930              ctsio->cdb[0], ctsio->cdb[1]));
11931         for (i = 1; i < entry->length; i++) {
11932                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11933                 if (diff == 0)
11934                         continue;
11935                 ctl_set_invalid_field(ctsio,
11936                                       /*sks_valid*/ 1,
11937                                       /*command*/ 1,
11938                                       /*field*/ i,
11939                                       /*bit_valid*/ 1,
11940                                       /*bit*/ fls(diff) - 1);
11941                 ctl_done((union ctl_io *)ctsio);
11942                 return (NULL);
11943         }
11944         return (entry);
11945 }
11946
11947 static int
11948 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11949 {
11950
11951         switch (lun_type) {
11952         case T_PROCESSOR:
11953                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11954                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11955                         return (0);
11956                 break;
11957         case T_DIRECT:
11958                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11959                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11960                         return (0);
11961                 break;
11962         default:
11963                 return (0);
11964         }
11965         return (1);
11966 }
11967
11968 static int
11969 ctl_scsiio(struct ctl_scsiio *ctsio)
11970 {
11971         int retval;
11972         const struct ctl_cmd_entry *entry;
11973
11974         retval = CTL_RETVAL_COMPLETE;
11975
11976         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11977
11978         entry = ctl_get_cmd_entry(ctsio, NULL);
11979
11980         /*
11981          * If this I/O has been aborted, just send it straight to
11982          * ctl_done() without executing it.
11983          */
11984         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11985                 ctl_done((union ctl_io *)ctsio);
11986                 goto bailout;
11987         }
11988
11989         /*
11990          * All the checks should have been handled by ctl_scsiio_precheck().
11991          * We should be clear now to just execute the I/O.
11992          */
11993         retval = entry->execute(ctsio);
11994
11995 bailout:
11996         return (retval);
11997 }
11998
11999 /*
12000  * Since we only implement one target right now, a bus reset simply resets
12001  * our single target.
12002  */
12003 static int
12004 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
12005 {
12006         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
12007 }
12008
12009 static int
12010 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
12011                  ctl_ua_type ua_type)
12012 {
12013         struct ctl_lun *lun;
12014         int retval;
12015
12016         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12017                 union ctl_ha_msg msg_info;
12018
12019                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12020                 msg_info.hdr.nexus = io->io_hdr.nexus;
12021                 if (ua_type==CTL_UA_TARG_RESET)
12022                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12023                 else
12024                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
12025                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12026                 msg_info.hdr.original_sc = NULL;
12027                 msg_info.hdr.serializing_sc = NULL;
12028                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12029                     (void *)&msg_info, sizeof(msg_info), 0)) {
12030                 }
12031         }
12032         retval = 0;
12033
12034         mtx_lock(&softc->ctl_lock);
12035         STAILQ_FOREACH(lun, &softc->lun_list, links)
12036                 retval += ctl_lun_reset(lun, io, ua_type);
12037         mtx_unlock(&softc->ctl_lock);
12038
12039         return (retval);
12040 }
12041
12042 /*
12043  * The LUN should always be set.  The I/O is optional, and is used to
12044  * distinguish between I/Os sent by this initiator, and by other
12045  * initiators.  We set unit attention for initiators other than this one.
12046  * SAM-3 is vague on this point.  It does say that a unit attention should
12047  * be established for other initiators when a LUN is reset (see section
12048  * 5.7.3), but it doesn't specifically say that the unit attention should
12049  * be established for this particular initiator when a LUN is reset.  Here
12050  * is the relevant text, from SAM-3 rev 8:
12051  *
12052  * 5.7.2 When a SCSI initiator port aborts its own tasks
12053  *
12054  * When a SCSI initiator port causes its own task(s) to be aborted, no
12055  * notification that the task(s) have been aborted shall be returned to
12056  * the SCSI initiator port other than the completion response for the
12057  * command or task management function action that caused the task(s) to
12058  * be aborted and notification(s) associated with related effects of the
12059  * action (e.g., a reset unit attention condition).
12060  *
12061  * XXX KDM for now, we're setting unit attention for all initiators.
12062  */
12063 static int
12064 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12065 {
12066         union ctl_io *xio;
12067 #if 0
12068         uint32_t initidx;
12069 #endif
12070 #ifdef CTL_WITH_CA
12071         int i;
12072 #endif
12073
12074         mtx_lock(&lun->lun_lock);
12075         /*
12076          * Run through the OOA queue and abort each I/O.
12077          */
12078         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12079              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12080                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12081         }
12082
12083         /*
12084          * This version sets unit attention for every
12085          */
12086 #if 0
12087         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12088         ctl_est_ua_all(lun, initidx, ua_type);
12089 #else
12090         ctl_est_ua_all(lun, -1, ua_type);
12091 #endif
12092
12093         /*
12094          * A reset (any kind, really) clears reservations established with
12095          * RESERVE/RELEASE.  It does not clear reservations established
12096          * with PERSISTENT RESERVE OUT, but we don't support that at the
12097          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12098          * reservations made with the RESERVE/RELEASE commands, because
12099          * those commands are obsolete in SPC-3.
12100          */
12101         lun->flags &= ~CTL_LUN_RESERVED;
12102
12103 #ifdef CTL_WITH_CA
12104         for (i = 0; i < CTL_MAX_INITIATORS; i++)
12105                 ctl_clear_mask(lun->have_ca, i);
12106 #endif
12107         mtx_unlock(&lun->lun_lock);
12108
12109         return (0);
12110 }
12111
12112 static void
12113 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12114     int other_sc)
12115 {
12116         union ctl_io *xio;
12117
12118         mtx_assert(&lun->lun_lock, MA_OWNED);
12119
12120         /*
12121          * Run through the OOA queue and attempt to find the given I/O.
12122          * The target port, initiator ID, tag type and tag number have to
12123          * match the values that we got from the initiator.  If we have an
12124          * untagged command to abort, simply abort the first untagged command
12125          * we come to.  We only allow one untagged command at a time of course.
12126          */
12127         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12128              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12129
12130                 if ((targ_port == UINT32_MAX ||
12131                      targ_port == xio->io_hdr.nexus.targ_port) &&
12132                     (init_id == UINT32_MAX ||
12133                      init_id == xio->io_hdr.nexus.initid.id)) {
12134                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12135                             init_id != xio->io_hdr.nexus.initid.id)
12136                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12137                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12138                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12139                                 union ctl_ha_msg msg_info;
12140
12141                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12142                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12143                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12144                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12145                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12146                                 msg_info.hdr.original_sc = NULL;
12147                                 msg_info.hdr.serializing_sc = NULL;
12148                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12149                                     (void *)&msg_info, sizeof(msg_info), 0);
12150                         }
12151                 }
12152         }
12153 }
12154
12155 static int
12156 ctl_abort_task_set(union ctl_io *io)
12157 {
12158         struct ctl_softc *softc = control_softc;
12159         struct ctl_lun *lun;
12160         uint32_t targ_lun;
12161
12162         /*
12163          * Look up the LUN.
12164          */
12165         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12166         mtx_lock(&softc->ctl_lock);
12167         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12168                 lun = softc->ctl_luns[targ_lun];
12169         else {
12170                 mtx_unlock(&softc->ctl_lock);
12171                 return (1);
12172         }
12173
12174         mtx_lock(&lun->lun_lock);
12175         mtx_unlock(&softc->ctl_lock);
12176         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12177                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12178                     io->io_hdr.nexus.initid.id,
12179                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12180         } else { /* CTL_TASK_CLEAR_TASK_SET */
12181                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12182                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12183         }
12184         mtx_unlock(&lun->lun_lock);
12185         return (0);
12186 }
12187
12188 static int
12189 ctl_i_t_nexus_reset(union ctl_io *io)
12190 {
12191         struct ctl_softc *softc = control_softc;
12192         struct ctl_lun *lun;
12193         uint32_t initidx, residx;
12194
12195         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12196         residx = ctl_get_resindex(&io->io_hdr.nexus);
12197         mtx_lock(&softc->ctl_lock);
12198         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12199                 mtx_lock(&lun->lun_lock);
12200                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12201                     io->io_hdr.nexus.initid.id,
12202                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12203 #ifdef CTL_WITH_CA
12204                 ctl_clear_mask(lun->have_ca, initidx);
12205 #endif
12206                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12207                         lun->flags &= ~CTL_LUN_RESERVED;
12208                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12209                 mtx_unlock(&lun->lun_lock);
12210         }
12211         mtx_unlock(&softc->ctl_lock);
12212         return (0);
12213 }
12214
12215 static int
12216 ctl_abort_task(union ctl_io *io)
12217 {
12218         union ctl_io *xio;
12219         struct ctl_lun *lun;
12220         struct ctl_softc *softc;
12221 #if 0
12222         struct sbuf sb;
12223         char printbuf[128];
12224 #endif
12225         int found;
12226         uint32_t targ_lun;
12227
12228         softc = control_softc;
12229         found = 0;
12230
12231         /*
12232          * Look up the LUN.
12233          */
12234         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12235         mtx_lock(&softc->ctl_lock);
12236         if ((targ_lun < CTL_MAX_LUNS)
12237          && (softc->ctl_luns[targ_lun] != NULL))
12238                 lun = softc->ctl_luns[targ_lun];
12239         else {
12240                 mtx_unlock(&softc->ctl_lock);
12241                 return (1);
12242         }
12243
12244 #if 0
12245         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12246                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12247 #endif
12248
12249         mtx_lock(&lun->lun_lock);
12250         mtx_unlock(&softc->ctl_lock);
12251         /*
12252          * Run through the OOA queue and attempt to find the given I/O.
12253          * The target port, initiator ID, tag type and tag number have to
12254          * match the values that we got from the initiator.  If we have an
12255          * untagged command to abort, simply abort the first untagged command
12256          * we come to.  We only allow one untagged command at a time of course.
12257          */
12258         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12259              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12260 #if 0
12261                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12262
12263                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12264                             lun->lun, xio->scsiio.tag_num,
12265                             xio->scsiio.tag_type,
12266                             (xio->io_hdr.blocked_links.tqe_prev
12267                             == NULL) ? "" : " BLOCKED",
12268                             (xio->io_hdr.flags &
12269                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12270                             (xio->io_hdr.flags &
12271                             CTL_FLAG_ABORT) ? " ABORT" : "",
12272                             (xio->io_hdr.flags &
12273                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12274                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12275                 sbuf_finish(&sb);
12276                 printf("%s\n", sbuf_data(&sb));
12277 #endif
12278
12279                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12280                  || (xio->io_hdr.nexus.initid.id != io->io_hdr.nexus.initid.id)
12281                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12282                         continue;
12283
12284                 /*
12285                  * If the abort says that the task is untagged, the
12286                  * task in the queue must be untagged.  Otherwise,
12287                  * we just check to see whether the tag numbers
12288                  * match.  This is because the QLogic firmware
12289                  * doesn't pass back the tag type in an abort
12290                  * request.
12291                  */
12292 #if 0
12293                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12294                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12295                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12296 #endif
12297                 /*
12298                  * XXX KDM we've got problems with FC, because it
12299                  * doesn't send down a tag type with aborts.  So we
12300                  * can only really go by the tag number...
12301                  * This may cause problems with parallel SCSI.
12302                  * Need to figure that out!!
12303                  */
12304                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12305                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12306                         found = 1;
12307                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12308                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12309                                 union ctl_ha_msg msg_info;
12310
12311                                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12312                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12313                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12314                                 msg_info.task.tag_num = io->taskio.tag_num;
12315                                 msg_info.task.tag_type = io->taskio.tag_type;
12316                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12317                                 msg_info.hdr.original_sc = NULL;
12318                                 msg_info.hdr.serializing_sc = NULL;
12319 #if 0
12320                                 printf("Sent Abort to other side\n");
12321 #endif
12322                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12323                                     (void *)&msg_info, sizeof(msg_info), 0) !=
12324                                     CTL_HA_STATUS_SUCCESS) {
12325                                 }
12326                         }
12327 #if 0
12328                         printf("ctl_abort_task: found I/O to abort\n");
12329 #endif
12330                 }
12331         }
12332         mtx_unlock(&lun->lun_lock);
12333
12334         if (found == 0) {
12335                 /*
12336                  * This isn't really an error.  It's entirely possible for
12337                  * the abort and command completion to cross on the wire.
12338                  * This is more of an informative/diagnostic error.
12339                  */
12340 #if 0
12341                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12342                        "%d:%d:%d:%d tag %d type %d\n",
12343                        io->io_hdr.nexus.initid.id,
12344                        io->io_hdr.nexus.targ_port,
12345                        io->io_hdr.nexus.targ_target.id,
12346                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12347                        io->taskio.tag_type);
12348 #endif
12349         }
12350         return (0);
12351 }
12352
12353 static void
12354 ctl_run_task(union ctl_io *io)
12355 {
12356         struct ctl_softc *softc = control_softc;
12357         int retval = 1;
12358         const char *task_desc;
12359
12360         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12361
12362         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12363             ("ctl_run_task: Unextected io_type %d\n",
12364              io->io_hdr.io_type));
12365
12366         task_desc = ctl_scsi_task_string(&io->taskio);
12367         if (task_desc != NULL) {
12368 #ifdef NEEDTOPORT
12369                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12370                             CTL_TASK_REPORT,
12371                             csevent_LogType_Trace,
12372                             csevent_Severity_Information,
12373                             csevent_AlertLevel_Green,
12374                             csevent_FRU_Firmware,
12375                             csevent_FRU_Unknown,
12376                             "CTL: received task: %s",task_desc);
12377 #endif
12378         } else {
12379 #ifdef NEEDTOPORT
12380                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12381                             CTL_TASK_REPORT,
12382                             csevent_LogType_Trace,
12383                             csevent_Severity_Information,
12384                             csevent_AlertLevel_Green,
12385                             csevent_FRU_Firmware,
12386                             csevent_FRU_Unknown,
12387                             "CTL: received unknown task "
12388                             "type: %d (%#x)",
12389                             io->taskio.task_action,
12390                             io->taskio.task_action);
12391 #endif
12392         }
12393         switch (io->taskio.task_action) {
12394         case CTL_TASK_ABORT_TASK:
12395                 retval = ctl_abort_task(io);
12396                 break;
12397         case CTL_TASK_ABORT_TASK_SET:
12398         case CTL_TASK_CLEAR_TASK_SET:
12399                 retval = ctl_abort_task_set(io);
12400                 break;
12401         case CTL_TASK_CLEAR_ACA:
12402                 break;
12403         case CTL_TASK_I_T_NEXUS_RESET:
12404                 retval = ctl_i_t_nexus_reset(io);
12405                 break;
12406         case CTL_TASK_LUN_RESET: {
12407                 struct ctl_lun *lun;
12408                 uint32_t targ_lun;
12409
12410                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12411                 mtx_lock(&softc->ctl_lock);
12412                 if ((targ_lun < CTL_MAX_LUNS)
12413                  && (softc->ctl_luns[targ_lun] != NULL))
12414                         lun = softc->ctl_luns[targ_lun];
12415                 else {
12416                         mtx_unlock(&softc->ctl_lock);
12417                         retval = 1;
12418                         break;
12419                 }
12420
12421                 if (!(io->io_hdr.flags &
12422                     CTL_FLAG_FROM_OTHER_SC)) {
12423                         union ctl_ha_msg msg_info;
12424
12425                         io->io_hdr.flags |=
12426                                 CTL_FLAG_SENT_2OTHER_SC;
12427                         msg_info.hdr.msg_type =
12428                                 CTL_MSG_MANAGE_TASKS;
12429                         msg_info.hdr.nexus = io->io_hdr.nexus;
12430                         msg_info.task.task_action =
12431                                 CTL_TASK_LUN_RESET;
12432                         msg_info.hdr.original_sc = NULL;
12433                         msg_info.hdr.serializing_sc = NULL;
12434                         if (CTL_HA_STATUS_SUCCESS !=
12435                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12436                             (void *)&msg_info,
12437                             sizeof(msg_info), 0)) {
12438                         }
12439                 }
12440
12441                 retval = ctl_lun_reset(lun, io,
12442                                        CTL_UA_LUN_RESET);
12443                 mtx_unlock(&softc->ctl_lock);
12444                 break;
12445         }
12446         case CTL_TASK_TARGET_RESET:
12447                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12448                 break;
12449         case CTL_TASK_BUS_RESET:
12450                 retval = ctl_bus_reset(softc, io);
12451                 break;
12452         case CTL_TASK_PORT_LOGIN:
12453                 break;
12454         case CTL_TASK_PORT_LOGOUT:
12455                 break;
12456         default:
12457                 printf("ctl_run_task: got unknown task management event %d\n",
12458                        io->taskio.task_action);
12459                 break;
12460         }
12461         if (retval == 0)
12462                 io->io_hdr.status = CTL_SUCCESS;
12463         else
12464                 io->io_hdr.status = CTL_ERROR;
12465         ctl_done(io);
12466 }
12467
12468 /*
12469  * For HA operation.  Handle commands that come in from the other
12470  * controller.
12471  */
12472 static void
12473 ctl_handle_isc(union ctl_io *io)
12474 {
12475         int free_io;
12476         struct ctl_lun *lun;
12477         struct ctl_softc *softc;
12478         uint32_t targ_lun;
12479
12480         softc = control_softc;
12481
12482         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12483         lun = softc->ctl_luns[targ_lun];
12484
12485         switch (io->io_hdr.msg_type) {
12486         case CTL_MSG_SERIALIZE:
12487                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12488                 break;
12489         case CTL_MSG_R2R: {
12490                 const struct ctl_cmd_entry *entry;
12491
12492                 /*
12493                  * This is only used in SER_ONLY mode.
12494                  */
12495                 free_io = 0;
12496                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12497                 mtx_lock(&lun->lun_lock);
12498                 if (ctl_scsiio_lun_check(lun,
12499                     entry, (struct ctl_scsiio *)io) != 0) {
12500                         mtx_unlock(&lun->lun_lock);
12501                         ctl_done(io);
12502                         break;
12503                 }
12504                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12505                 mtx_unlock(&lun->lun_lock);
12506                 ctl_enqueue_rtr(io);
12507                 break;
12508         }
12509         case CTL_MSG_FINISH_IO:
12510                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12511                         free_io = 0;
12512                         ctl_done(io);
12513                 } else {
12514                         free_io = 1;
12515                         mtx_lock(&lun->lun_lock);
12516                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12517                                      ooa_links);
12518                         ctl_check_blocked(lun);
12519                         mtx_unlock(&lun->lun_lock);
12520                 }
12521                 break;
12522         case CTL_MSG_PERS_ACTION:
12523                 ctl_hndl_per_res_out_on_other_sc(
12524                         (union ctl_ha_msg *)&io->presio.pr_msg);
12525                 free_io = 1;
12526                 break;
12527         case CTL_MSG_BAD_JUJU:
12528                 free_io = 0;
12529                 ctl_done(io);
12530                 break;
12531         case CTL_MSG_DATAMOVE:
12532                 /* Only used in XFER mode */
12533                 free_io = 0;
12534                 ctl_datamove_remote(io);
12535                 break;
12536         case CTL_MSG_DATAMOVE_DONE:
12537                 /* Only used in XFER mode */
12538                 free_io = 0;
12539                 io->scsiio.be_move_done(io);
12540                 break;
12541         default:
12542                 free_io = 1;
12543                 printf("%s: Invalid message type %d\n",
12544                        __func__, io->io_hdr.msg_type);
12545                 break;
12546         }
12547         if (free_io)
12548                 ctl_free_io(io);
12549
12550 }
12551
12552
12553 /*
12554  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12555  * there is no match.
12556  */
12557 static ctl_lun_error_pattern
12558 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12559 {
12560         const struct ctl_cmd_entry *entry;
12561         ctl_lun_error_pattern filtered_pattern, pattern;
12562
12563         pattern = desc->error_pattern;
12564
12565         /*
12566          * XXX KDM we need more data passed into this function to match a
12567          * custom pattern, and we actually need to implement custom pattern
12568          * matching.
12569          */
12570         if (pattern & CTL_LUN_PAT_CMD)
12571                 return (CTL_LUN_PAT_CMD);
12572
12573         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12574                 return (CTL_LUN_PAT_ANY);
12575
12576         entry = ctl_get_cmd_entry(ctsio, NULL);
12577
12578         filtered_pattern = entry->pattern & pattern;
12579
12580         /*
12581          * If the user requested specific flags in the pattern (e.g.
12582          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12583          * flags.
12584          *
12585          * If the user did not specify any flags, it doesn't matter whether
12586          * or not the command supports the flags.
12587          */
12588         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12589              (pattern & ~CTL_LUN_PAT_MASK))
12590                 return (CTL_LUN_PAT_NONE);
12591
12592         /*
12593          * If the user asked for a range check, see if the requested LBA
12594          * range overlaps with this command's LBA range.
12595          */
12596         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12597                 uint64_t lba1;
12598                 uint64_t len1;
12599                 ctl_action action;
12600                 int retval;
12601
12602                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12603                 if (retval != 0)
12604                         return (CTL_LUN_PAT_NONE);
12605
12606                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12607                                               desc->lba_range.len, FALSE);
12608                 /*
12609                  * A "pass" means that the LBA ranges don't overlap, so
12610                  * this doesn't match the user's range criteria.
12611                  */
12612                 if (action == CTL_ACTION_PASS)
12613                         return (CTL_LUN_PAT_NONE);
12614         }
12615
12616         return (filtered_pattern);
12617 }
12618
12619 static void
12620 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12621 {
12622         struct ctl_error_desc *desc, *desc2;
12623
12624         mtx_assert(&lun->lun_lock, MA_OWNED);
12625
12626         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12627                 ctl_lun_error_pattern pattern;
12628                 /*
12629                  * Check to see whether this particular command matches
12630                  * the pattern in the descriptor.
12631                  */
12632                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12633                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12634                         continue;
12635
12636                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12637                 case CTL_LUN_INJ_ABORTED:
12638                         ctl_set_aborted(&io->scsiio);
12639                         break;
12640                 case CTL_LUN_INJ_MEDIUM_ERR:
12641                         ctl_set_medium_error(&io->scsiio);
12642                         break;
12643                 case CTL_LUN_INJ_UA:
12644                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12645                          * OCCURRED */
12646                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12647                         break;
12648                 case CTL_LUN_INJ_CUSTOM:
12649                         /*
12650                          * We're assuming the user knows what he is doing.
12651                          * Just copy the sense information without doing
12652                          * checks.
12653                          */
12654                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12655                               MIN(sizeof(desc->custom_sense),
12656                                   sizeof(io->scsiio.sense_data)));
12657                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12658                         io->scsiio.sense_len = SSD_FULL_SIZE;
12659                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12660                         break;
12661                 case CTL_LUN_INJ_NONE:
12662                 default:
12663                         /*
12664                          * If this is an error injection type we don't know
12665                          * about, clear the continuous flag (if it is set)
12666                          * so it will get deleted below.
12667                          */
12668                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12669                         break;
12670                 }
12671                 /*
12672                  * By default, each error injection action is a one-shot
12673                  */
12674                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12675                         continue;
12676
12677                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12678
12679                 free(desc, M_CTL);
12680         }
12681 }
12682
12683 #ifdef CTL_IO_DELAY
12684 static void
12685 ctl_datamove_timer_wakeup(void *arg)
12686 {
12687         union ctl_io *io;
12688
12689         io = (union ctl_io *)arg;
12690
12691         ctl_datamove(io);
12692 }
12693 #endif /* CTL_IO_DELAY */
12694
12695 void
12696 ctl_datamove(union ctl_io *io)
12697 {
12698         void (*fe_datamove)(union ctl_io *io);
12699
12700         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12701
12702         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12703
12704 #ifdef CTL_TIME_IO
12705         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12706                 char str[256];
12707                 char path_str[64];
12708                 struct sbuf sb;
12709
12710                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12711                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12712
12713                 sbuf_cat(&sb, path_str);
12714                 switch (io->io_hdr.io_type) {
12715                 case CTL_IO_SCSI:
12716                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12717                         sbuf_printf(&sb, "\n");
12718                         sbuf_cat(&sb, path_str);
12719                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12720                                     io->scsiio.tag_num, io->scsiio.tag_type);
12721                         break;
12722                 case CTL_IO_TASK:
12723                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12724                                     "Tag Type: %d\n", io->taskio.task_action,
12725                                     io->taskio.tag_num, io->taskio.tag_type);
12726                         break;
12727                 default:
12728                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12729                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12730                         break;
12731                 }
12732                 sbuf_cat(&sb, path_str);
12733                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12734                             (intmax_t)time_uptime - io->io_hdr.start_time);
12735                 sbuf_finish(&sb);
12736                 printf("%s", sbuf_data(&sb));
12737         }
12738 #endif /* CTL_TIME_IO */
12739
12740 #ifdef CTL_IO_DELAY
12741         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12742                 struct ctl_lun *lun;
12743
12744                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12745
12746                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12747         } else {
12748                 struct ctl_lun *lun;
12749
12750                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12751                 if ((lun != NULL)
12752                  && (lun->delay_info.datamove_delay > 0)) {
12753                         struct callout *callout;
12754
12755                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12756                         callout_init(callout, /*mpsafe*/ 1);
12757                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12758                         callout_reset(callout,
12759                                       lun->delay_info.datamove_delay * hz,
12760                                       ctl_datamove_timer_wakeup, io);
12761                         if (lun->delay_info.datamove_type ==
12762                             CTL_DELAY_TYPE_ONESHOT)
12763                                 lun->delay_info.datamove_delay = 0;
12764                         return;
12765                 }
12766         }
12767 #endif
12768
12769         /*
12770          * This command has been aborted.  Set the port status, so we fail
12771          * the data move.
12772          */
12773         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12774                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12775                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12776                        io->io_hdr.nexus.targ_port,
12777                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12778                        io->io_hdr.nexus.targ_lun);
12779                 io->io_hdr.port_status = 31337;
12780                 /*
12781                  * Note that the backend, in this case, will get the
12782                  * callback in its context.  In other cases it may get
12783                  * called in the frontend's interrupt thread context.
12784                  */
12785                 io->scsiio.be_move_done(io);
12786                 return;
12787         }
12788
12789         /* Don't confuse frontend with zero length data move. */
12790         if (io->scsiio.kern_data_len == 0) {
12791                 io->scsiio.be_move_done(io);
12792                 return;
12793         }
12794
12795         /*
12796          * If we're in XFER mode and this I/O is from the other shelf
12797          * controller, we need to send the DMA to the other side to
12798          * actually transfer the data to/from the host.  In serialize only
12799          * mode the transfer happens below CTL and ctl_datamove() is only
12800          * called on the machine that originally received the I/O.
12801          */
12802         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12803          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12804                 union ctl_ha_msg msg;
12805                 uint32_t sg_entries_sent;
12806                 int do_sg_copy;
12807                 int i;
12808
12809                 memset(&msg, 0, sizeof(msg));
12810                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12811                 msg.hdr.original_sc = io->io_hdr.original_sc;
12812                 msg.hdr.serializing_sc = io;
12813                 msg.hdr.nexus = io->io_hdr.nexus;
12814                 msg.dt.flags = io->io_hdr.flags;
12815                 /*
12816                  * We convert everything into a S/G list here.  We can't
12817                  * pass by reference, only by value between controllers.
12818                  * So we can't pass a pointer to the S/G list, only as many
12819                  * S/G entries as we can fit in here.  If it's possible for
12820                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12821                  * then we need to break this up into multiple transfers.
12822                  */
12823                 if (io->scsiio.kern_sg_entries == 0) {
12824                         msg.dt.kern_sg_entries = 1;
12825                         /*
12826                          * If this is in cached memory, flush the cache
12827                          * before we send the DMA request to the other
12828                          * controller.  We want to do this in either the
12829                          * read or the write case.  The read case is
12830                          * straightforward.  In the write case, we want to
12831                          * make sure nothing is in the local cache that
12832                          * could overwrite the DMAed data.
12833                          */
12834                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12835                                 /*
12836                                  * XXX KDM use bus_dmamap_sync() here.
12837                                  */
12838                         }
12839
12840                         /*
12841                          * Convert to a physical address if this is a
12842                          * virtual address.
12843                          */
12844                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12845                                 msg.dt.sg_list[0].addr =
12846                                         io->scsiio.kern_data_ptr;
12847                         } else {
12848                                 /*
12849                                  * XXX KDM use busdma here!
12850                                  */
12851 #if 0
12852                                 msg.dt.sg_list[0].addr = (void *)
12853                                         vtophys(io->scsiio.kern_data_ptr);
12854 #endif
12855                         }
12856
12857                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12858                         do_sg_copy = 0;
12859                 } else {
12860                         struct ctl_sg_entry *sgl;
12861
12862                         do_sg_copy = 1;
12863                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12864                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12865                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12866                                 /*
12867                                  * XXX KDM use bus_dmamap_sync() here.
12868                                  */
12869                         }
12870                 }
12871
12872                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12873                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12874                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12875                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12876                 msg.dt.sg_sequence = 0;
12877
12878                 /*
12879                  * Loop until we've sent all of the S/G entries.  On the
12880                  * other end, we'll recompose these S/G entries into one
12881                  * contiguous list before passing it to the
12882                  */
12883                 for (sg_entries_sent = 0; sg_entries_sent <
12884                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12885                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12886                                 sizeof(msg.dt.sg_list[0])),
12887                                 msg.dt.kern_sg_entries - sg_entries_sent);
12888
12889                         if (do_sg_copy != 0) {
12890                                 struct ctl_sg_entry *sgl;
12891                                 int j;
12892
12893                                 sgl = (struct ctl_sg_entry *)
12894                                         io->scsiio.kern_data_ptr;
12895                                 /*
12896                                  * If this is in cached memory, flush the cache
12897                                  * before we send the DMA request to the other
12898                                  * controller.  We want to do this in either
12899                                  * the * read or the write case.  The read
12900                                  * case is straightforward.  In the write
12901                                  * case, we want to make sure nothing is
12902                                  * in the local cache that could overwrite
12903                                  * the DMAed data.
12904                                  */
12905
12906                                 for (i = sg_entries_sent, j = 0;
12907                                      i < msg.dt.cur_sg_entries; i++, j++) {
12908                                         if ((io->io_hdr.flags &
12909                                              CTL_FLAG_NO_DATASYNC) == 0) {
12910                                                 /*
12911                                                  * XXX KDM use bus_dmamap_sync()
12912                                                  */
12913                                         }
12914                                         if ((io->io_hdr.flags &
12915                                              CTL_FLAG_BUS_ADDR) == 0) {
12916                                                 /*
12917                                                  * XXX KDM use busdma.
12918                                                  */
12919 #if 0
12920                                                 msg.dt.sg_list[j].addr =(void *)
12921                                                        vtophys(sgl[i].addr);
12922 #endif
12923                                         } else {
12924                                                 msg.dt.sg_list[j].addr =
12925                                                         sgl[i].addr;
12926                                         }
12927                                         msg.dt.sg_list[j].len = sgl[i].len;
12928                                 }
12929                         }
12930
12931                         sg_entries_sent += msg.dt.cur_sg_entries;
12932                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12933                                 msg.dt.sg_last = 1;
12934                         else
12935                                 msg.dt.sg_last = 0;
12936
12937                         /*
12938                          * XXX KDM drop and reacquire the lock here?
12939                          */
12940                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12941                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12942                                 /*
12943                                  * XXX do something here.
12944                                  */
12945                         }
12946
12947                         msg.dt.sent_sg_entries = sg_entries_sent;
12948                 }
12949                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12950                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12951                         ctl_failover_io(io, /*have_lock*/ 0);
12952
12953         } else {
12954
12955                 /*
12956                  * Lookup the fe_datamove() function for this particular
12957                  * front end.
12958                  */
12959                 fe_datamove =
12960                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12961
12962                 fe_datamove(io);
12963         }
12964 }
12965
12966 static void
12967 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12968 {
12969         union ctl_ha_msg msg;
12970         int isc_status;
12971
12972         memset(&msg, 0, sizeof(msg));
12973
12974         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12975         msg.hdr.original_sc = io;
12976         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12977         msg.hdr.nexus = io->io_hdr.nexus;
12978         msg.hdr.status = io->io_hdr.status;
12979         msg.scsi.tag_num = io->scsiio.tag_num;
12980         msg.scsi.tag_type = io->scsiio.tag_type;
12981         msg.scsi.scsi_status = io->scsiio.scsi_status;
12982         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12983                sizeof(io->scsiio.sense_data));
12984         msg.scsi.sense_len = io->scsiio.sense_len;
12985         msg.scsi.sense_residual = io->scsiio.sense_residual;
12986         msg.scsi.fetd_status = io->io_hdr.port_status;
12987         msg.scsi.residual = io->scsiio.residual;
12988         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12989
12990         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12991                 ctl_failover_io(io, /*have_lock*/ have_lock);
12992                 return;
12993         }
12994
12995         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12996         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12997                 /* XXX do something if this fails */
12998         }
12999
13000 }
13001
13002 /*
13003  * The DMA to the remote side is done, now we need to tell the other side
13004  * we're done so it can continue with its data movement.
13005  */
13006 static void
13007 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13008 {
13009         union ctl_io *io;
13010
13011         io = rq->context;
13012
13013         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13014                 printf("%s: ISC DMA write failed with error %d", __func__,
13015                        rq->ret);
13016                 ctl_set_internal_failure(&io->scsiio,
13017                                          /*sks_valid*/ 1,
13018                                          /*retry_count*/ rq->ret);
13019         }
13020
13021         ctl_dt_req_free(rq);
13022
13023         /*
13024          * In this case, we had to malloc the memory locally.  Free it.
13025          */
13026         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13027                 int i;
13028                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13029                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13030         }
13031         /*
13032          * The data is in local and remote memory, so now we need to send
13033          * status (good or back) back to the other side.
13034          */
13035         ctl_send_datamove_done(io, /*have_lock*/ 0);
13036 }
13037
13038 /*
13039  * We've moved the data from the host/controller into local memory.  Now we
13040  * need to push it over to the remote controller's memory.
13041  */
13042 static int
13043 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13044 {
13045         int retval;
13046
13047         retval = 0;
13048
13049         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13050                                           ctl_datamove_remote_write_cb);
13051
13052         return (retval);
13053 }
13054
13055 static void
13056 ctl_datamove_remote_write(union ctl_io *io)
13057 {
13058         int retval;
13059         void (*fe_datamove)(union ctl_io *io);
13060
13061         /*
13062          * - Get the data from the host/HBA into local memory.
13063          * - DMA memory from the local controller to the remote controller.
13064          * - Send status back to the remote controller.
13065          */
13066
13067         retval = ctl_datamove_remote_sgl_setup(io);
13068         if (retval != 0)
13069                 return;
13070
13071         /* Switch the pointer over so the FETD knows what to do */
13072         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13073
13074         /*
13075          * Use a custom move done callback, since we need to send completion
13076          * back to the other controller, not to the backend on this side.
13077          */
13078         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13079
13080         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13081
13082         fe_datamove(io);
13083
13084         return;
13085
13086 }
13087
13088 static int
13089 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13090 {
13091 #if 0
13092         char str[256];
13093         char path_str[64];
13094         struct sbuf sb;
13095 #endif
13096
13097         /*
13098          * In this case, we had to malloc the memory locally.  Free it.
13099          */
13100         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13101                 int i;
13102                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13103                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13104         }
13105
13106 #if 0
13107         scsi_path_string(io, path_str, sizeof(path_str));
13108         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13109         sbuf_cat(&sb, path_str);
13110         scsi_command_string(&io->scsiio, NULL, &sb);
13111         sbuf_printf(&sb, "\n");
13112         sbuf_cat(&sb, path_str);
13113         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13114                     io->scsiio.tag_num, io->scsiio.tag_type);
13115         sbuf_cat(&sb, path_str);
13116         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13117                     io->io_hdr.flags, io->io_hdr.status);
13118         sbuf_finish(&sb);
13119         printk("%s", sbuf_data(&sb));
13120 #endif
13121
13122
13123         /*
13124          * The read is done, now we need to send status (good or bad) back
13125          * to the other side.
13126          */
13127         ctl_send_datamove_done(io, /*have_lock*/ 0);
13128
13129         return (0);
13130 }
13131
13132 static void
13133 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13134 {
13135         union ctl_io *io;
13136         void (*fe_datamove)(union ctl_io *io);
13137
13138         io = rq->context;
13139
13140         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13141                 printf("%s: ISC DMA read failed with error %d", __func__,
13142                        rq->ret);
13143                 ctl_set_internal_failure(&io->scsiio,
13144                                          /*sks_valid*/ 1,
13145                                          /*retry_count*/ rq->ret);
13146         }
13147
13148         ctl_dt_req_free(rq);
13149
13150         /* Switch the pointer over so the FETD knows what to do */
13151         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13152
13153         /*
13154          * Use a custom move done callback, since we need to send completion
13155          * back to the other controller, not to the backend on this side.
13156          */
13157         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13158
13159         /* XXX KDM add checks like the ones in ctl_datamove? */
13160
13161         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13162
13163         fe_datamove(io);
13164 }
13165
13166 static int
13167 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13168 {
13169         struct ctl_sg_entry *local_sglist, *remote_sglist;
13170         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13171         struct ctl_softc *softc;
13172         int retval;
13173         int i;
13174
13175         retval = 0;
13176         softc = control_softc;
13177
13178         local_sglist = io->io_hdr.local_sglist;
13179         local_dma_sglist = io->io_hdr.local_dma_sglist;
13180         remote_sglist = io->io_hdr.remote_sglist;
13181         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13182
13183         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13184                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13185                         local_sglist[i].len = remote_sglist[i].len;
13186
13187                         /*
13188                          * XXX Detect the situation where the RS-level I/O
13189                          * redirector on the other side has already read the
13190                          * data off of the AOR RS on this side, and
13191                          * transferred it to remote (mirror) memory on the
13192                          * other side.  Since we already have the data in
13193                          * memory here, we just need to use it.
13194                          *
13195                          * XXX KDM this can probably be removed once we
13196                          * get the cache device code in and take the
13197                          * current AOR implementation out.
13198                          */
13199 #ifdef NEEDTOPORT
13200                         if ((remote_sglist[i].addr >=
13201                              (void *)vtophys(softc->mirr->addr))
13202                          && (remote_sglist[i].addr <
13203                              ((void *)vtophys(softc->mirr->addr) +
13204                              CacheMirrorOffset))) {
13205                                 local_sglist[i].addr = remote_sglist[i].addr -
13206                                         CacheMirrorOffset;
13207                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13208                                      CTL_FLAG_DATA_IN)
13209                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13210                         } else {
13211                                 local_sglist[i].addr = remote_sglist[i].addr +
13212                                         CacheMirrorOffset;
13213                         }
13214 #endif
13215 #if 0
13216                         printf("%s: local %p, remote %p, len %d\n",
13217                                __func__, local_sglist[i].addr,
13218                                remote_sglist[i].addr, local_sglist[i].len);
13219 #endif
13220                 }
13221         } else {
13222                 uint32_t len_to_go;
13223
13224                 /*
13225                  * In this case, we don't have automatically allocated
13226                  * memory for this I/O on this controller.  This typically
13227                  * happens with internal CTL I/O -- e.g. inquiry, mode
13228                  * sense, etc.  Anything coming from RAIDCore will have
13229                  * a mirror area available.
13230                  */
13231                 len_to_go = io->scsiio.kern_data_len;
13232
13233                 /*
13234                  * Clear the no datasync flag, we have to use malloced
13235                  * buffers.
13236                  */
13237                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13238
13239                 /*
13240                  * The difficult thing here is that the size of the various
13241                  * S/G segments may be different than the size from the
13242                  * remote controller.  That'll make it harder when DMAing
13243                  * the data back to the other side.
13244                  */
13245                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13246                      sizeof(io->io_hdr.remote_sglist[0])) &&
13247                      (len_to_go > 0); i++) {
13248                         local_sglist[i].len = MIN(len_to_go, 131072);
13249                         CTL_SIZE_8B(local_dma_sglist[i].len,
13250                                     local_sglist[i].len);
13251                         local_sglist[i].addr =
13252                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13253
13254                         local_dma_sglist[i].addr = local_sglist[i].addr;
13255
13256                         if (local_sglist[i].addr == NULL) {
13257                                 int j;
13258
13259                                 printf("malloc failed for %zd bytes!",
13260                                        local_dma_sglist[i].len);
13261                                 for (j = 0; j < i; j++) {
13262                                         free(local_sglist[j].addr, M_CTL);
13263                                 }
13264                                 ctl_set_internal_failure(&io->scsiio,
13265                                                          /*sks_valid*/ 1,
13266                                                          /*retry_count*/ 4857);
13267                                 retval = 1;
13268                                 goto bailout_error;
13269                                 
13270                         }
13271                         /* XXX KDM do we need a sync here? */
13272
13273                         len_to_go -= local_sglist[i].len;
13274                 }
13275                 /*
13276                  * Reset the number of S/G entries accordingly.  The
13277                  * original number of S/G entries is available in
13278                  * rem_sg_entries.
13279                  */
13280                 io->scsiio.kern_sg_entries = i;
13281
13282 #if 0
13283                 printf("%s: kern_sg_entries = %d\n", __func__,
13284                        io->scsiio.kern_sg_entries);
13285                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13286                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13287                                local_sglist[i].addr, local_sglist[i].len,
13288                                local_dma_sglist[i].len);
13289 #endif
13290         }
13291
13292
13293         return (retval);
13294
13295 bailout_error:
13296
13297         ctl_send_datamove_done(io, /*have_lock*/ 0);
13298
13299         return (retval);
13300 }
13301
13302 static int
13303 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13304                          ctl_ha_dt_cb callback)
13305 {
13306         struct ctl_ha_dt_req *rq;
13307         struct ctl_sg_entry *remote_sglist, *local_sglist;
13308         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13309         uint32_t local_used, remote_used, total_used;
13310         int retval;
13311         int i, j;
13312
13313         retval = 0;
13314
13315         rq = ctl_dt_req_alloc();
13316
13317         /*
13318          * If we failed to allocate the request, and if the DMA didn't fail
13319          * anyway, set busy status.  This is just a resource allocation
13320          * failure.
13321          */
13322         if ((rq == NULL)
13323          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13324                 ctl_set_busy(&io->scsiio);
13325
13326         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13327
13328                 if (rq != NULL)
13329                         ctl_dt_req_free(rq);
13330
13331                 /*
13332                  * The data move failed.  We need to return status back
13333                  * to the other controller.  No point in trying to DMA
13334                  * data to the remote controller.
13335                  */
13336
13337                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13338
13339                 retval = 1;
13340
13341                 goto bailout;
13342         }
13343
13344         local_sglist = io->io_hdr.local_sglist;
13345         local_dma_sglist = io->io_hdr.local_dma_sglist;
13346         remote_sglist = io->io_hdr.remote_sglist;
13347         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13348         local_used = 0;
13349         remote_used = 0;
13350         total_used = 0;
13351
13352         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13353                 rq->ret = CTL_HA_STATUS_SUCCESS;
13354                 rq->context = io;
13355                 callback(rq);
13356                 goto bailout;
13357         }
13358
13359         /*
13360          * Pull/push the data over the wire from/to the other controller.
13361          * This takes into account the possibility that the local and
13362          * remote sglists may not be identical in terms of the size of
13363          * the elements and the number of elements.
13364          *
13365          * One fundamental assumption here is that the length allocated for
13366          * both the local and remote sglists is identical.  Otherwise, we've
13367          * essentially got a coding error of some sort.
13368          */
13369         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13370                 int isc_ret;
13371                 uint32_t cur_len, dma_length;
13372                 uint8_t *tmp_ptr;
13373
13374                 rq->id = CTL_HA_DATA_CTL;
13375                 rq->command = command;
13376                 rq->context = io;
13377
13378                 /*
13379                  * Both pointers should be aligned.  But it is possible
13380                  * that the allocation length is not.  They should both
13381                  * also have enough slack left over at the end, though,
13382                  * to round up to the next 8 byte boundary.
13383                  */
13384                 cur_len = MIN(local_sglist[i].len - local_used,
13385                               remote_sglist[j].len - remote_used);
13386
13387                 /*
13388                  * In this case, we have a size issue and need to decrease
13389                  * the size, except in the case where we actually have less
13390                  * than 8 bytes left.  In that case, we need to increase
13391                  * the DMA length to get the last bit.
13392                  */
13393                 if ((cur_len & 0x7) != 0) {
13394                         if (cur_len > 0x7) {
13395                                 cur_len = cur_len - (cur_len & 0x7);
13396                                 dma_length = cur_len;
13397                         } else {
13398                                 CTL_SIZE_8B(dma_length, cur_len);
13399                         }
13400
13401                 } else
13402                         dma_length = cur_len;
13403
13404                 /*
13405                  * If we had to allocate memory for this I/O, instead of using
13406                  * the non-cached mirror memory, we'll need to flush the cache
13407                  * before trying to DMA to the other controller.
13408                  *
13409                  * We could end up doing this multiple times for the same
13410                  * segment if we have a larger local segment than remote
13411                  * segment.  That shouldn't be an issue.
13412                  */
13413                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13414                         /*
13415                          * XXX KDM use bus_dmamap_sync() here.
13416                          */
13417                 }
13418
13419                 rq->size = dma_length;
13420
13421                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13422                 tmp_ptr += local_used;
13423
13424                 /* Use physical addresses when talking to ISC hardware */
13425                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13426                         /* XXX KDM use busdma */
13427 #if 0
13428                         rq->local = vtophys(tmp_ptr);
13429 #endif
13430                 } else
13431                         rq->local = tmp_ptr;
13432
13433                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13434                 tmp_ptr += remote_used;
13435                 rq->remote = tmp_ptr;
13436
13437                 rq->callback = NULL;
13438
13439                 local_used += cur_len;
13440                 if (local_used >= local_sglist[i].len) {
13441                         i++;
13442                         local_used = 0;
13443                 }
13444
13445                 remote_used += cur_len;
13446                 if (remote_used >= remote_sglist[j].len) {
13447                         j++;
13448                         remote_used = 0;
13449                 }
13450                 total_used += cur_len;
13451
13452                 if (total_used >= io->scsiio.kern_data_len)
13453                         rq->callback = callback;
13454
13455                 if ((rq->size & 0x7) != 0) {
13456                         printf("%s: warning: size %d is not on 8b boundary\n",
13457                                __func__, rq->size);
13458                 }
13459                 if (((uintptr_t)rq->local & 0x7) != 0) {
13460                         printf("%s: warning: local %p not on 8b boundary\n",
13461                                __func__, rq->local);
13462                 }
13463                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13464                         printf("%s: warning: remote %p not on 8b boundary\n",
13465                                __func__, rq->local);
13466                 }
13467 #if 0
13468                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13469                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13470                        rq->local, rq->remote, rq->size);
13471 #endif
13472
13473                 isc_ret = ctl_dt_single(rq);
13474                 if (isc_ret == CTL_HA_STATUS_WAIT)
13475                         continue;
13476
13477                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13478                         rq->ret = CTL_HA_STATUS_SUCCESS;
13479                 } else {
13480                         rq->ret = isc_ret;
13481                 }
13482                 callback(rq);
13483                 goto bailout;
13484         }
13485
13486 bailout:
13487         return (retval);
13488
13489 }
13490
13491 static void
13492 ctl_datamove_remote_read(union ctl_io *io)
13493 {
13494         int retval;
13495         int i;
13496
13497         /*
13498          * This will send an error to the other controller in the case of a
13499          * failure.
13500          */
13501         retval = ctl_datamove_remote_sgl_setup(io);
13502         if (retval != 0)
13503                 return;
13504
13505         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13506                                           ctl_datamove_remote_read_cb);
13507         if ((retval != 0)
13508          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13509                 /*
13510                  * Make sure we free memory if there was an error..  The
13511                  * ctl_datamove_remote_xfer() function will send the
13512                  * datamove done message, or call the callback with an
13513                  * error if there is a problem.
13514                  */
13515                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13516                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13517         }
13518
13519         return;
13520 }
13521
13522 /*
13523  * Process a datamove request from the other controller.  This is used for
13524  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13525  * first.  Once that is complete, the data gets DMAed into the remote
13526  * controller's memory.  For reads, we DMA from the remote controller's
13527  * memory into our memory first, and then move it out to the FETD.
13528  */
13529 static void
13530 ctl_datamove_remote(union ctl_io *io)
13531 {
13532         struct ctl_softc *softc;
13533
13534         softc = control_softc;
13535
13536         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13537
13538         /*
13539          * Note that we look for an aborted I/O here, but don't do some of
13540          * the other checks that ctl_datamove() normally does.
13541          * We don't need to run the datamove delay code, since that should
13542          * have been done if need be on the other controller.
13543          */
13544         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13545                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13546                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13547                        io->io_hdr.nexus.targ_port,
13548                        io->io_hdr.nexus.targ_target.id,
13549                        io->io_hdr.nexus.targ_lun);
13550                 io->io_hdr.port_status = 31338;
13551                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13552                 return;
13553         }
13554
13555         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13556                 ctl_datamove_remote_write(io);
13557         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13558                 ctl_datamove_remote_read(io);
13559         } else {
13560                 union ctl_ha_msg msg;
13561                 struct scsi_sense_data *sense;
13562                 uint8_t sks[3];
13563                 int retry_count;
13564
13565                 memset(&msg, 0, sizeof(msg));
13566
13567                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13568                 msg.hdr.status = CTL_SCSI_ERROR;
13569                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13570
13571                 retry_count = 4243;
13572
13573                 sense = &msg.scsi.sense_data;
13574                 sks[0] = SSD_SCS_VALID;
13575                 sks[1] = (retry_count >> 8) & 0xff;
13576                 sks[2] = retry_count & 0xff;
13577
13578                 /* "Internal target failure" */
13579                 scsi_set_sense_data(sense,
13580                                     /*sense_format*/ SSD_TYPE_NONE,
13581                                     /*current_error*/ 1,
13582                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13583                                     /*asc*/ 0x44,
13584                                     /*ascq*/ 0x00,
13585                                     /*type*/ SSD_ELEM_SKS,
13586                                     /*size*/ sizeof(sks),
13587                                     /*data*/ sks,
13588                                     SSD_ELEM_NONE);
13589
13590                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13591                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13592                         ctl_failover_io(io, /*have_lock*/ 1);
13593                         return;
13594                 }
13595
13596                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13597                     CTL_HA_STATUS_SUCCESS) {
13598                         /* XXX KDM what to do if this fails? */
13599                 }
13600                 return;
13601         }
13602         
13603 }
13604
13605 static int
13606 ctl_process_done(union ctl_io *io)
13607 {
13608         struct ctl_lun *lun;
13609         struct ctl_softc *softc = control_softc;
13610         void (*fe_done)(union ctl_io *io);
13611         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13612
13613         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13614
13615         fe_done = softc->ctl_ports[targ_port]->fe_done;
13616
13617 #ifdef CTL_TIME_IO
13618         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13619                 char str[256];
13620                 char path_str[64];
13621                 struct sbuf sb;
13622
13623                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13624                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13625
13626                 sbuf_cat(&sb, path_str);
13627                 switch (io->io_hdr.io_type) {
13628                 case CTL_IO_SCSI:
13629                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13630                         sbuf_printf(&sb, "\n");
13631                         sbuf_cat(&sb, path_str);
13632                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13633                                     io->scsiio.tag_num, io->scsiio.tag_type);
13634                         break;
13635                 case CTL_IO_TASK:
13636                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13637                                     "Tag Type: %d\n", io->taskio.task_action,
13638                                     io->taskio.tag_num, io->taskio.tag_type);
13639                         break;
13640                 default:
13641                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13642                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13643                         break;
13644                 }
13645                 sbuf_cat(&sb, path_str);
13646                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13647                             (intmax_t)time_uptime - io->io_hdr.start_time);
13648                 sbuf_finish(&sb);
13649                 printf("%s", sbuf_data(&sb));
13650         }
13651 #endif /* CTL_TIME_IO */
13652
13653         switch (io->io_hdr.io_type) {
13654         case CTL_IO_SCSI:
13655                 break;
13656         case CTL_IO_TASK:
13657                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13658                         ctl_io_error_print(io, NULL);
13659                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13660                         ctl_free_io(io);
13661                 else
13662                         fe_done(io);
13663                 return (CTL_RETVAL_COMPLETE);
13664         default:
13665                 panic("ctl_process_done: invalid io type %d\n",
13666                       io->io_hdr.io_type);
13667                 break; /* NOTREACHED */
13668         }
13669
13670         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13671         if (lun == NULL) {
13672                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13673                                  io->io_hdr.nexus.targ_mapped_lun));
13674                 goto bailout;
13675         }
13676
13677         mtx_lock(&lun->lun_lock);
13678
13679         /*
13680          * Check to see if we have any errors to inject here.  We only
13681          * inject errors for commands that don't already have errors set.
13682          */
13683         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13684             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13685             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13686                 ctl_inject_error(lun, io);
13687
13688         /*
13689          * XXX KDM how do we treat commands that aren't completed
13690          * successfully?
13691          *
13692          * XXX KDM should we also track I/O latency?
13693          */
13694         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13695             io->io_hdr.io_type == CTL_IO_SCSI) {
13696 #ifdef CTL_TIME_IO
13697                 struct bintime cur_bt;
13698 #endif
13699                 int type;
13700
13701                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13702                     CTL_FLAG_DATA_IN)
13703                         type = CTL_STATS_READ;
13704                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13705                     CTL_FLAG_DATA_OUT)
13706                         type = CTL_STATS_WRITE;
13707                 else
13708                         type = CTL_STATS_NO_IO;
13709
13710                 lun->stats.ports[targ_port].bytes[type] +=
13711                     io->scsiio.kern_total_len;
13712                 lun->stats.ports[targ_port].operations[type]++;
13713 #ifdef CTL_TIME_IO
13714                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13715                    &io->io_hdr.dma_bt);
13716                 lun->stats.ports[targ_port].num_dmas[type] +=
13717                     io->io_hdr.num_dmas;
13718                 getbintime(&cur_bt);
13719                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13720                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13721 #endif
13722         }
13723
13724         /*
13725          * Remove this from the OOA queue.
13726          */
13727         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13728 #ifdef CTL_TIME_IO
13729         if (TAILQ_EMPTY(&lun->ooa_queue))
13730                 lun->last_busy = getsbinuptime();
13731 #endif
13732
13733         /*
13734          * Run through the blocked queue on this LUN and see if anything
13735          * has become unblocked, now that this transaction is done.
13736          */
13737         ctl_check_blocked(lun);
13738
13739         /*
13740          * If the LUN has been invalidated, free it if there is nothing
13741          * left on its OOA queue.
13742          */
13743         if ((lun->flags & CTL_LUN_INVALID)
13744          && TAILQ_EMPTY(&lun->ooa_queue)) {
13745                 mtx_unlock(&lun->lun_lock);
13746                 mtx_lock(&softc->ctl_lock);
13747                 ctl_free_lun(lun);
13748                 mtx_unlock(&softc->ctl_lock);
13749         } else
13750                 mtx_unlock(&lun->lun_lock);
13751
13752 bailout:
13753
13754         /*
13755          * If this command has been aborted, make sure we set the status
13756          * properly.  The FETD is responsible for freeing the I/O and doing
13757          * whatever it needs to do to clean up its state.
13758          */
13759         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13760                 ctl_set_task_aborted(&io->scsiio);
13761
13762         /*
13763          * If enabled, print command error status.
13764          * We don't print UAs unless debugging was enabled explicitly.
13765          */
13766         do {
13767                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13768                         break;
13769                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13770                         break;
13771                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13772                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13773                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13774                         int error_code, sense_key, asc, ascq;
13775
13776                         scsi_extract_sense_len(&io->scsiio.sense_data,
13777                             io->scsiio.sense_len, &error_code, &sense_key,
13778                             &asc, &ascq, /*show_errors*/ 0);
13779                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13780                                 break;
13781                 }
13782
13783                 ctl_io_error_print(io, NULL);
13784         } while (0);
13785
13786         /*
13787          * Tell the FETD or the other shelf controller we're done with this
13788          * command.  Note that only SCSI commands get to this point.  Task
13789          * management commands are completed above.
13790          *
13791          * We only send status to the other controller if we're in XFER
13792          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13793          * received the I/O (from CTL's perspective), and so the status is
13794          * generated there.
13795          * 
13796          * XXX KDM if we hold the lock here, we could cause a deadlock
13797          * if the frontend comes back in in this context to queue
13798          * something.
13799          */
13800         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13801          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13802                 union ctl_ha_msg msg;
13803
13804                 memset(&msg, 0, sizeof(msg));
13805                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13806                 msg.hdr.original_sc = io->io_hdr.original_sc;
13807                 msg.hdr.nexus = io->io_hdr.nexus;
13808                 msg.hdr.status = io->io_hdr.status;
13809                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13810                 msg.scsi.tag_num = io->scsiio.tag_num;
13811                 msg.scsi.tag_type = io->scsiio.tag_type;
13812                 msg.scsi.sense_len = io->scsiio.sense_len;
13813                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13814                 msg.scsi.residual = io->scsiio.residual;
13815                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13816                        sizeof(io->scsiio.sense_data));
13817                 /*
13818                  * We copy this whether or not this is an I/O-related
13819                  * command.  Otherwise, we'd have to go and check to see
13820                  * whether it's a read/write command, and it really isn't
13821                  * worth it.
13822                  */
13823                 memcpy(&msg.scsi.lbalen,
13824                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13825                        sizeof(msg.scsi.lbalen));
13826
13827                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13828                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13829                         /* XXX do something here */
13830                 }
13831
13832                 ctl_free_io(io);
13833         } else 
13834                 fe_done(io);
13835
13836         return (CTL_RETVAL_COMPLETE);
13837 }
13838
13839 #ifdef CTL_WITH_CA
13840 /*
13841  * Front end should call this if it doesn't do autosense.  When the request
13842  * sense comes back in from the initiator, we'll dequeue this and send it.
13843  */
13844 int
13845 ctl_queue_sense(union ctl_io *io)
13846 {
13847         struct ctl_lun *lun;
13848         struct ctl_port *port;
13849         struct ctl_softc *softc;
13850         uint32_t initidx, targ_lun;
13851
13852         softc = control_softc;
13853
13854         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13855
13856         /*
13857          * LUN lookup will likely move to the ctl_work_thread() once we
13858          * have our new queueing infrastructure (that doesn't put things on
13859          * a per-LUN queue initially).  That is so that we can handle
13860          * things like an INQUIRY to a LUN that we don't have enabled.  We
13861          * can't deal with that right now.
13862          */
13863         mtx_lock(&softc->ctl_lock);
13864
13865         /*
13866          * If we don't have a LUN for this, just toss the sense
13867          * information.
13868          */
13869         port = ctl_io_port(&ctsio->io_hdr);
13870         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13871         if ((targ_lun < CTL_MAX_LUNS)
13872          && (softc->ctl_luns[targ_lun] != NULL))
13873                 lun = softc->ctl_luns[targ_lun];
13874         else
13875                 goto bailout;
13876
13877         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13878
13879         mtx_lock(&lun->lun_lock);
13880         /*
13881          * Already have CA set for this LUN...toss the sense information.
13882          */
13883         if (ctl_is_set(lun->have_ca, initidx)) {
13884                 mtx_unlock(&lun->lun_lock);
13885                 goto bailout;
13886         }
13887
13888         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13889                MIN(sizeof(lun->pending_sense[initidx]),
13890                sizeof(io->scsiio.sense_data)));
13891         ctl_set_mask(lun->have_ca, initidx);
13892         mtx_unlock(&lun->lun_lock);
13893
13894 bailout:
13895         mtx_unlock(&softc->ctl_lock);
13896
13897         ctl_free_io(io);
13898
13899         return (CTL_RETVAL_COMPLETE);
13900 }
13901 #endif
13902
13903 /*
13904  * Primary command inlet from frontend ports.  All SCSI and task I/O
13905  * requests must go through this function.
13906  */
13907 int
13908 ctl_queue(union ctl_io *io)
13909 {
13910         struct ctl_port *port;
13911
13912         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13913
13914 #ifdef CTL_TIME_IO
13915         io->io_hdr.start_time = time_uptime;
13916         getbintime(&io->io_hdr.start_bt);
13917 #endif /* CTL_TIME_IO */
13918
13919         /* Map FE-specific LUN ID into global one. */
13920         port = ctl_io_port(&io->io_hdr);
13921         io->io_hdr.nexus.targ_mapped_lun =
13922             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13923
13924         switch (io->io_hdr.io_type) {
13925         case CTL_IO_SCSI:
13926         case CTL_IO_TASK:
13927                 if (ctl_debug & CTL_DEBUG_CDB)
13928                         ctl_io_print(io);
13929                 ctl_enqueue_incoming(io);
13930                 break;
13931         default:
13932                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13933                 return (EINVAL);
13934         }
13935
13936         return (CTL_RETVAL_COMPLETE);
13937 }
13938
13939 #ifdef CTL_IO_DELAY
13940 static void
13941 ctl_done_timer_wakeup(void *arg)
13942 {
13943         union ctl_io *io;
13944
13945         io = (union ctl_io *)arg;
13946         ctl_done(io);
13947 }
13948 #endif /* CTL_IO_DELAY */
13949
13950 void
13951 ctl_done(union ctl_io *io)
13952 {
13953
13954         /*
13955          * Enable this to catch duplicate completion issues.
13956          */
13957 #if 0
13958         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13959                 printf("%s: type %d msg %d cdb %x iptl: "
13960                        "%d:%d:%d:%d tag 0x%04x "
13961                        "flag %#x status %x\n",
13962                         __func__,
13963                         io->io_hdr.io_type,
13964                         io->io_hdr.msg_type,
13965                         io->scsiio.cdb[0],
13966                         io->io_hdr.nexus.initid.id,
13967                         io->io_hdr.nexus.targ_port,
13968                         io->io_hdr.nexus.targ_target.id,
13969                         io->io_hdr.nexus.targ_lun,
13970                         (io->io_hdr.io_type ==
13971                         CTL_IO_TASK) ?
13972                         io->taskio.tag_num :
13973                         io->scsiio.tag_num,
13974                         io->io_hdr.flags,
13975                         io->io_hdr.status);
13976         } else
13977                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13978 #endif
13979
13980         /*
13981          * This is an internal copy of an I/O, and should not go through
13982          * the normal done processing logic.
13983          */
13984         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13985                 return;
13986
13987         /*
13988          * We need to send a msg to the serializing shelf to finish the IO
13989          * as well.  We don't send a finish message to the other shelf if
13990          * this is a task management command.  Task management commands
13991          * aren't serialized in the OOA queue, but rather just executed on
13992          * both shelf controllers for commands that originated on that
13993          * controller.
13994          */
13995         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13996          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13997                 union ctl_ha_msg msg_io;
13998
13999                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14000                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14001                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14002                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14003                 }
14004                 /* continue on to finish IO */
14005         }
14006 #ifdef CTL_IO_DELAY
14007         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14008                 struct ctl_lun *lun;
14009
14010                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14011
14012                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14013         } else {
14014                 struct ctl_lun *lun;
14015
14016                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14017
14018                 if ((lun != NULL)
14019                  && (lun->delay_info.done_delay > 0)) {
14020                         struct callout *callout;
14021
14022                         callout = (struct callout *)&io->io_hdr.timer_bytes;
14023                         callout_init(callout, /*mpsafe*/ 1);
14024                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14025                         callout_reset(callout,
14026                                       lun->delay_info.done_delay * hz,
14027                                       ctl_done_timer_wakeup, io);
14028                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14029                                 lun->delay_info.done_delay = 0;
14030                         return;
14031                 }
14032         }
14033 #endif /* CTL_IO_DELAY */
14034
14035         ctl_enqueue_done(io);
14036 }
14037
14038 int
14039 ctl_isc(struct ctl_scsiio *ctsio)
14040 {
14041         struct ctl_lun *lun;
14042         int retval;
14043
14044         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14045
14046         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14047
14048         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14049
14050         retval = lun->backend->data_submit((union ctl_io *)ctsio);
14051
14052         return (retval);
14053 }
14054
14055
14056 static void
14057 ctl_work_thread(void *arg)
14058 {
14059         struct ctl_thread *thr = (struct ctl_thread *)arg;
14060         struct ctl_softc *softc = thr->ctl_softc;
14061         union ctl_io *io;
14062         int retval;
14063
14064         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14065
14066         for (;;) {
14067                 retval = 0;
14068
14069                 /*
14070                  * We handle the queues in this order:
14071                  * - ISC
14072                  * - done queue (to free up resources, unblock other commands)
14073                  * - RtR queue
14074                  * - incoming queue
14075                  *
14076                  * If those queues are empty, we break out of the loop and
14077                  * go to sleep.
14078                  */
14079                 mtx_lock(&thr->queue_lock);
14080                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14081                 if (io != NULL) {
14082                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14083                         mtx_unlock(&thr->queue_lock);
14084                         ctl_handle_isc(io);
14085                         continue;
14086                 }
14087                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14088                 if (io != NULL) {
14089                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14090                         /* clear any blocked commands, call fe_done */
14091                         mtx_unlock(&thr->queue_lock);
14092                         retval = ctl_process_done(io);
14093                         continue;
14094                 }
14095                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14096                 if (io != NULL) {
14097                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14098                         mtx_unlock(&thr->queue_lock);
14099                         if (io->io_hdr.io_type == CTL_IO_TASK)
14100                                 ctl_run_task(io);
14101                         else
14102                                 ctl_scsiio_precheck(softc, &io->scsiio);
14103                         continue;
14104                 }
14105                 if (!ctl_pause_rtr) {
14106                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14107                         if (io != NULL) {
14108                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14109                                 mtx_unlock(&thr->queue_lock);
14110                                 retval = ctl_scsiio(&io->scsiio);
14111                                 if (retval != CTL_RETVAL_COMPLETE)
14112                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14113                                 continue;
14114                         }
14115                 }
14116
14117                 /* Sleep until we have something to do. */
14118                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14119         }
14120 }
14121
14122 static void
14123 ctl_lun_thread(void *arg)
14124 {
14125         struct ctl_softc *softc = (struct ctl_softc *)arg;
14126         struct ctl_be_lun *be_lun;
14127         int retval;
14128
14129         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14130
14131         for (;;) {
14132                 retval = 0;
14133                 mtx_lock(&softc->ctl_lock);
14134                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14135                 if (be_lun != NULL) {
14136                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14137                         mtx_unlock(&softc->ctl_lock);
14138                         ctl_create_lun(be_lun);
14139                         continue;
14140                 }
14141
14142                 /* Sleep until we have something to do. */
14143                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14144                     PDROP | PRIBIO, "-", 0);
14145         }
14146 }
14147
14148 static void
14149 ctl_thresh_thread(void *arg)
14150 {
14151         struct ctl_softc *softc = (struct ctl_softc *)arg;
14152         struct ctl_lun *lun;
14153         struct ctl_be_lun *be_lun;
14154         struct scsi_da_rw_recovery_page *rwpage;
14155         struct ctl_logical_block_provisioning_page *page;
14156         const char *attr;
14157         uint64_t thres, val;
14158         int i, e;
14159
14160         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14161
14162         for (;;) {
14163                 mtx_lock(&softc->ctl_lock);
14164                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
14165                         be_lun = lun->be_lun;
14166                         if ((lun->flags & CTL_LUN_DISABLED) ||
14167                             (lun->flags & CTL_LUN_OFFLINE) ||
14168                             lun->backend->lun_attr == NULL)
14169                                 continue;
14170                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14171                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14172                                 continue;
14173                         e = 0;
14174                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14175                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14176                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14177                                         continue;
14178                                 thres = scsi_4btoul(page->descr[i].count);
14179                                 thres <<= CTL_LBP_EXPONENT;
14180                                 switch (page->descr[i].resource) {
14181                                 case 0x01:
14182                                         attr = "blocksavail";
14183                                         break;
14184                                 case 0x02:
14185                                         attr = "blocksused";
14186                                         break;
14187                                 case 0xf1:
14188                                         attr = "poolblocksavail";
14189                                         break;
14190                                 case 0xf2:
14191                                         attr = "poolblocksused";
14192                                         break;
14193                                 default:
14194                                         continue;
14195                                 }
14196                                 mtx_unlock(&softc->ctl_lock); // XXX
14197                                 val = lun->backend->lun_attr(
14198                                     lun->be_lun->be_lun, attr);
14199                                 mtx_lock(&softc->ctl_lock);
14200                                 if (val == UINT64_MAX)
14201                                         continue;
14202                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14203                                     == SLBPPD_ARMING_INC)
14204                                         e |= (val >= thres);
14205                                 else
14206                                         e |= (val <= thres);
14207                         }
14208                         mtx_lock(&lun->lun_lock);
14209                         if (e) {
14210                                 if (lun->lasttpt == 0 ||
14211                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14212                                         lun->lasttpt = time_uptime;
14213                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14214                                 }
14215                         } else {
14216                                 lun->lasttpt = 0;
14217                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14218                         }
14219                         mtx_unlock(&lun->lun_lock);
14220                 }
14221                 mtx_unlock(&softc->ctl_lock);
14222                 pause("-", CTL_LBP_PERIOD * hz);
14223         }
14224 }
14225
14226 static void
14227 ctl_enqueue_incoming(union ctl_io *io)
14228 {
14229         struct ctl_softc *softc = control_softc;
14230         struct ctl_thread *thr;
14231         u_int idx;
14232
14233         idx = (io->io_hdr.nexus.targ_port * 127 +
14234                io->io_hdr.nexus.initid.id) % worker_threads;
14235         thr = &softc->threads[idx];
14236         mtx_lock(&thr->queue_lock);
14237         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14238         mtx_unlock(&thr->queue_lock);
14239         wakeup(thr);
14240 }
14241
14242 static void
14243 ctl_enqueue_rtr(union ctl_io *io)
14244 {
14245         struct ctl_softc *softc = control_softc;
14246         struct ctl_thread *thr;
14247
14248         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14249         mtx_lock(&thr->queue_lock);
14250         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14251         mtx_unlock(&thr->queue_lock);
14252         wakeup(thr);
14253 }
14254
14255 static void
14256 ctl_enqueue_done(union ctl_io *io)
14257 {
14258         struct ctl_softc *softc = control_softc;
14259         struct ctl_thread *thr;
14260
14261         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14262         mtx_lock(&thr->queue_lock);
14263         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14264         mtx_unlock(&thr->queue_lock);
14265         wakeup(thr);
14266 }
14267
14268 static void
14269 ctl_enqueue_isc(union ctl_io *io)
14270 {
14271         struct ctl_softc *softc = control_softc;
14272         struct ctl_thread *thr;
14273
14274         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14275         mtx_lock(&thr->queue_lock);
14276         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14277         mtx_unlock(&thr->queue_lock);
14278         wakeup(thr);
14279 }
14280
14281 /* Initialization and failover */
14282
14283 void
14284 ctl_init_isc_msg(void)
14285 {
14286         printf("CTL: Still calling this thing\n");
14287 }
14288
14289 /*
14290  * Init component
14291  *      Initializes component into configuration defined by bootMode
14292  *      (see hasc-sv.c)
14293  *      returns hasc_Status:
14294  *              OK
14295  *              ERROR - fatal error
14296  */
14297 static ctl_ha_comp_status
14298 ctl_isc_init(struct ctl_ha_component *c)
14299 {
14300         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14301
14302         c->status = ret;
14303         return ret;
14304 }
14305
14306 /* Start component
14307  *      Starts component in state requested. If component starts successfully,
14308  *      it must set its own state to the requestrd state
14309  *      When requested state is HASC_STATE_HA, the component may refine it
14310  *      by adding _SLAVE or _MASTER flags.
14311  *      Currently allowed state transitions are:
14312  *      UNKNOWN->HA             - initial startup
14313  *      UNKNOWN->SINGLE - initial startup when no parter detected
14314  *      HA->SINGLE              - failover
14315  * returns ctl_ha_comp_status:
14316  *              OK      - component successfully started in requested state
14317  *              FAILED  - could not start the requested state, failover may
14318  *                        be possible
14319  *              ERROR   - fatal error detected, no future startup possible
14320  */
14321 static ctl_ha_comp_status
14322 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14323 {
14324         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14325
14326         printf("%s: go\n", __func__);
14327
14328         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14329         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14330                 control_softc->is_single = 0;
14331                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14332                     != CTL_HA_STATUS_SUCCESS) {
14333                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14334                         ret = CTL_HA_COMP_STATUS_ERROR;
14335                 }
14336         } else if (CTL_HA_STATE_IS_HA(c->state)
14337                 && CTL_HA_STATE_IS_SINGLE(state)){
14338                 // HA->SINGLE transition
14339                 ctl_failover();
14340                 control_softc->is_single = 1;
14341         } else {
14342                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14343                        c->state, state);
14344                 ret = CTL_HA_COMP_STATUS_ERROR;
14345         }
14346         if (CTL_HA_STATE_IS_SINGLE(state))
14347                 control_softc->is_single = 1;
14348
14349         c->state = state;
14350         c->status = ret;
14351         return ret;
14352 }
14353
14354 /*
14355  * Quiesce component
14356  * The component must clear any error conditions (set status to OK) and
14357  * prepare itself to another Start call
14358  * returns ctl_ha_comp_status:
14359  *      OK
14360  *      ERROR
14361  */
14362 static ctl_ha_comp_status
14363 ctl_isc_quiesce(struct ctl_ha_component *c)
14364 {
14365         int ret = CTL_HA_COMP_STATUS_OK;
14366
14367         ctl_pause_rtr = 1;
14368         c->status = ret;
14369         return ret;
14370 }
14371
14372 struct ctl_ha_component ctl_ha_component_ctlisc =
14373 {
14374         .name = "CTL ISC",
14375         .state = CTL_HA_STATE_UNKNOWN,
14376         .init = ctl_isc_init,
14377         .start = ctl_isc_start,
14378         .quiesce = ctl_isc_quiesce
14379 };
14380
14381 /*
14382  *  vim: ts=8
14383  */