]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r273259:
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
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/kernel.h>
50 #include <sys/types.h>
51 #include <sys/kthread.h>
52 #include <sys/bio.h>
53 #include <sys/fcntl.h>
54 #include <sys/lock.h>
55 #include <sys/module.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/malloc.h>
59 #include <sys/conf.h>
60 #include <sys/ioccom.h>
61 #include <sys/queue.h>
62 #include <sys/sbuf.h>
63 #include <sys/smp.h>
64 #include <sys/endian.h>
65 #include <sys/sysctl.h>
66
67 #include <cam/cam.h>
68 #include <cam/scsi/scsi_all.h>
69 #include <cam/scsi/scsi_da.h>
70 #include <cam/ctl/ctl_io.h>
71 #include <cam/ctl/ctl.h>
72 #include <cam/ctl/ctl_frontend.h>
73 #include <cam/ctl/ctl_frontend_internal.h>
74 #include <cam/ctl/ctl_util.h>
75 #include <cam/ctl/ctl_backend.h>
76 #include <cam/ctl/ctl_ioctl.h>
77 #include <cam/ctl/ctl_ha.h>
78 #include <cam/ctl/ctl_private.h>
79 #include <cam/ctl/ctl_debug.h>
80 #include <cam/ctl/ctl_scsi_all.h>
81 #include <cam/ctl/ctl_error.h>
82
83 struct ctl_softc *control_softc = NULL;
84
85 /*
86  * Size and alignment macros needed for Copan-specific HA hardware.  These
87  * can go away when the HA code is re-written, and uses busdma for any
88  * hardware.
89  */
90 #define CTL_ALIGN_8B(target, source, type)                              \
91         if (((uint32_t)source & 0x7) != 0)                              \
92                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93         else                                                            \
94                 target = (type)source;
95
96 #define CTL_SIZE_8B(target, size)                                       \
97         if ((size & 0x7) != 0)                                          \
98                 target = size + (0x8 - (size & 0x7));                   \
99         else                                                            \
100                 target = size;
101
102 #define CTL_ALIGN_8B_MARGIN     16
103
104 /*
105  * Template mode pages.
106  */
107
108 /*
109  * Note that these are default values only.  The actual values will be
110  * filled in when the user does a mode sense.
111  */
112 static struct copan_power_subpage power_page_default = {
113         /*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114         /*subpage*/ PWR_SUBPAGE_CODE,
115         /*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116                          (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117         /*page_version*/ PWR_VERSION,
118         /* total_luns */ 26,
119         /* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120         /*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122                       0, 0, 0, 0, 0, 0}
123 };
124
125 static struct copan_power_subpage power_page_changeable = {
126         /*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127         /*subpage*/ PWR_SUBPAGE_CODE,
128         /*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129                          (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130         /*page_version*/ 0,
131         /* total_luns */ 0,
132         /* max_active_luns*/ 0,
133         /*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135                       0, 0, 0, 0, 0, 0}
136 };
137
138 static struct copan_aps_subpage aps_page_default = {
139         APS_PAGE_CODE | SMPH_SPF, //page_code
140         APS_SUBPAGE_CODE, //subpage
141         {(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142          (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143         APS_VERSION, //page_version
144         0, //lock_active
145         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146         0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147         0, 0, 0, 0, 0} //reserved
148 };
149
150 static struct copan_aps_subpage aps_page_changeable = {
151         APS_PAGE_CODE | SMPH_SPF, //page_code
152         APS_SUBPAGE_CODE, //subpage
153         {(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154          (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155         0, //page_version
156         0, //lock_active
157         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158         0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159         0, 0, 0, 0, 0} //reserved
160 };
161
162 static struct copan_debugconf_subpage debugconf_page_default = {
163         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
164         DBGCNF_SUBPAGE_CODE,            /* subpage */
165         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167         DBGCNF_VERSION,                 /* page_version */
168         {CTL_TIME_IO_DEFAULT_SECS>>8,
169          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
170 };
171
172 static struct copan_debugconf_subpage debugconf_page_changeable = {
173         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
174         DBGCNF_SUBPAGE_CODE,            /* subpage */
175         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177         0,                              /* page_version */
178         {0xff,0xff},                    /* ctl_time_io_secs */
179 };
180
181 static struct scsi_format_page format_page_default = {
182         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
183         /*page_length*/sizeof(struct scsi_format_page) - 2,
184         /*tracks_per_zone*/ {0, 0},
185         /*alt_sectors_per_zone*/ {0, 0},
186         /*alt_tracks_per_zone*/ {0, 0},
187         /*alt_tracks_per_lun*/ {0, 0},
188         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190         /*bytes_per_sector*/ {0, 0},
191         /*interleave*/ {0, 0},
192         /*track_skew*/ {0, 0},
193         /*cylinder_skew*/ {0, 0},
194         /*flags*/ SFP_HSEC,
195         /*reserved*/ {0, 0, 0}
196 };
197
198 static struct scsi_format_page format_page_changeable = {
199         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
200         /*page_length*/sizeof(struct scsi_format_page) - 2,
201         /*tracks_per_zone*/ {0, 0},
202         /*alt_sectors_per_zone*/ {0, 0},
203         /*alt_tracks_per_zone*/ {0, 0},
204         /*alt_tracks_per_lun*/ {0, 0},
205         /*sectors_per_track*/ {0, 0},
206         /*bytes_per_sector*/ {0, 0},
207         /*interleave*/ {0, 0},
208         /*track_skew*/ {0, 0},
209         /*cylinder_skew*/ {0, 0},
210         /*flags*/ 0,
211         /*reserved*/ {0, 0, 0}
212 };
213
214 static struct scsi_rigid_disk_page rigid_disk_page_default = {
215         /*page_code*/SMS_RIGID_DISK_PAGE,
216         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217         /*cylinders*/ {0, 0, 0},
218         /*heads*/ CTL_DEFAULT_HEADS,
219         /*start_write_precomp*/ {0, 0, 0},
220         /*start_reduced_current*/ {0, 0, 0},
221         /*step_rate*/ {0, 0},
222         /*landing_zone_cylinder*/ {0, 0, 0},
223         /*rpl*/ SRDP_RPL_DISABLED,
224         /*rotational_offset*/ 0,
225         /*reserved1*/ 0,
226         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227                            CTL_DEFAULT_ROTATION_RATE & 0xff},
228         /*reserved2*/ {0, 0}
229 };
230
231 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232         /*page_code*/SMS_RIGID_DISK_PAGE,
233         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234         /*cylinders*/ {0, 0, 0},
235         /*heads*/ 0,
236         /*start_write_precomp*/ {0, 0, 0},
237         /*start_reduced_current*/ {0, 0, 0},
238         /*step_rate*/ {0, 0},
239         /*landing_zone_cylinder*/ {0, 0, 0},
240         /*rpl*/ 0,
241         /*rotational_offset*/ 0,
242         /*reserved1*/ 0,
243         /*rotation_rate*/ {0, 0},
244         /*reserved2*/ {0, 0}
245 };
246
247 static struct scsi_caching_page caching_page_default = {
248         /*page_code*/SMS_CACHING_PAGE,
249         /*page_length*/sizeof(struct scsi_caching_page) - 2,
250         /*flags1*/ SCP_DISC | SCP_WCE,
251         /*ret_priority*/ 0,
252         /*disable_pf_transfer_len*/ {0xff, 0xff},
253         /*min_prefetch*/ {0, 0},
254         /*max_prefetch*/ {0xff, 0xff},
255         /*max_pf_ceiling*/ {0xff, 0xff},
256         /*flags2*/ 0,
257         /*cache_segments*/ 0,
258         /*cache_seg_size*/ {0, 0},
259         /*reserved*/ 0,
260         /*non_cache_seg_size*/ {0, 0, 0}
261 };
262
263 static struct scsi_caching_page caching_page_changeable = {
264         /*page_code*/SMS_CACHING_PAGE,
265         /*page_length*/sizeof(struct scsi_caching_page) - 2,
266         /*flags1*/ SCP_WCE | SCP_RCD,
267         /*ret_priority*/ 0,
268         /*disable_pf_transfer_len*/ {0, 0},
269         /*min_prefetch*/ {0, 0},
270         /*max_prefetch*/ {0, 0},
271         /*max_pf_ceiling*/ {0, 0},
272         /*flags2*/ 0,
273         /*cache_segments*/ 0,
274         /*cache_seg_size*/ {0, 0},
275         /*reserved*/ 0,
276         /*non_cache_seg_size*/ {0, 0, 0}
277 };
278
279 static struct scsi_control_page control_page_default = {
280         /*page_code*/SMS_CONTROL_MODE_PAGE,
281         /*page_length*/sizeof(struct scsi_control_page) - 2,
282         /*rlec*/0,
283         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
284         /*eca_and_aen*/0,
285         /*flags4*/SCP_TAS,
286         /*aen_holdoff_period*/{0, 0},
287         /*busy_timeout_period*/{0, 0},
288         /*extended_selftest_completion_time*/{0, 0}
289 };
290
291 static struct scsi_control_page control_page_changeable = {
292         /*page_code*/SMS_CONTROL_MODE_PAGE,
293         /*page_length*/sizeof(struct scsi_control_page) - 2,
294         /*rlec*/SCP_DSENSE,
295         /*queue_flags*/SCP_QUEUE_ALG_MASK,
296         /*eca_and_aen*/SCP_SWP,
297         /*flags4*/0,
298         /*aen_holdoff_period*/{0, 0},
299         /*busy_timeout_period*/{0, 0},
300         /*extended_selftest_completion_time*/{0, 0}
301 };
302
303
304 /*
305  * XXX KDM move these into the softc.
306  */
307 static int rcv_sync_msg;
308 static int persis_offset;
309 static uint8_t ctl_pause_rtr;
310 static int     ctl_is_single = 1;
311 static int     index_to_aps_page;
312
313 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314 static int worker_threads = -1;
315 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
316 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
317     &worker_threads, 1, "Number of worker threads");
318 static int ctl_debug = CTL_DEBUG_NONE;
319 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
320 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
321     &ctl_debug, 0, "Enabled debug flags");
322
323 /*
324  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
325  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
326  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
327  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
328  */
329 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
330
331 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
332                                   int param);
333 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
334 static int ctl_init(void);
335 void ctl_shutdown(void);
336 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
337 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
338 static void ctl_ioctl_online(void *arg);
339 static void ctl_ioctl_offline(void *arg);
340 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
341 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
342 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
343 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
344 static int ctl_ioctl_submit_wait(union ctl_io *io);
345 static void ctl_ioctl_datamove(union ctl_io *io);
346 static void ctl_ioctl_done(union ctl_io *io);
347 static void ctl_ioctl_hard_startstop_callback(void *arg,
348                                               struct cfi_metatask *metatask);
349 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
350 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
351                               struct ctl_ooa *ooa_hdr,
352                               struct ctl_ooa_entry *kern_entries);
353 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
354                      struct thread *td);
355 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
356 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
357 #ifdef unused
358 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
359                                    uint32_t targ_target, uint32_t targ_lun,
360                                    int can_wait);
361 static void ctl_kfree_io(union ctl_io *io);
362 #endif /* unused */
363 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
364                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
365 static int ctl_free_lun(struct ctl_lun *lun);
366 static void ctl_create_lun(struct ctl_be_lun *be_lun);
367 /**
368 static void ctl_failover_change_pages(struct ctl_softc *softc,
369                                       struct ctl_scsiio *ctsio, int master);
370 **/
371
372 static int ctl_do_mode_select(union ctl_io *io);
373 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
374                            uint64_t res_key, uint64_t sa_res_key,
375                            uint8_t type, uint32_t residx,
376                            struct ctl_scsiio *ctsio,
377                            struct scsi_per_res_out *cdb,
378                            struct scsi_per_res_out_parms* param);
379 static void ctl_pro_preempt_other(struct ctl_lun *lun,
380                                   union ctl_ha_msg *msg);
381 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
382 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
383 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
384 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
385 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
386 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
387 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
388                                          int alloc_len);
389 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
390                                          int alloc_len);
391 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
392 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
393 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
394 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
395 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
396 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
397 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
398     union ctl_io *pending_io, union ctl_io *ooa_io);
399 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
400                                 union ctl_io *starting_io);
401 static int ctl_check_blocked(struct ctl_lun *lun);
402 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
403                                 struct ctl_lun *lun,
404                                 const struct ctl_cmd_entry *entry,
405                                 struct ctl_scsiio *ctsio);
406 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
407 static void ctl_failover(void);
408 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
409                                struct ctl_scsiio *ctsio);
410 static int ctl_scsiio(struct ctl_scsiio *ctsio);
411
412 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
413 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
414                             ctl_ua_type ua_type);
415 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
416                          ctl_ua_type ua_type);
417 static int ctl_abort_task(union ctl_io *io);
418 static int ctl_abort_task_set(union ctl_io *io);
419 static int ctl_i_t_nexus_reset(union ctl_io *io);
420 static void ctl_run_task(union ctl_io *io);
421 #ifdef CTL_IO_DELAY
422 static void ctl_datamove_timer_wakeup(void *arg);
423 static void ctl_done_timer_wakeup(void *arg);
424 #endif /* CTL_IO_DELAY */
425
426 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
427 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
428 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
429 static void ctl_datamove_remote_write(union ctl_io *io);
430 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
431 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
432 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
433 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
434                                     ctl_ha_dt_cb callback);
435 static void ctl_datamove_remote_read(union ctl_io *io);
436 static void ctl_datamove_remote(union ctl_io *io);
437 static int ctl_process_done(union ctl_io *io);
438 static void ctl_lun_thread(void *arg);
439 static void ctl_work_thread(void *arg);
440 static void ctl_enqueue_incoming(union ctl_io *io);
441 static void ctl_enqueue_rtr(union ctl_io *io);
442 static void ctl_enqueue_done(union ctl_io *io);
443 static void ctl_enqueue_isc(union ctl_io *io);
444 static const struct ctl_cmd_entry *
445     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
446 static const struct ctl_cmd_entry *
447     ctl_validate_command(struct ctl_scsiio *ctsio);
448 static int ctl_cmd_applicable(uint8_t lun_type,
449     const struct ctl_cmd_entry *entry);
450
451 /*
452  * Load the serialization table.  This isn't very pretty, but is probably
453  * the easiest way to do it.
454  */
455 #include "ctl_ser_table.c"
456
457 /*
458  * We only need to define open, close and ioctl routines for this driver.
459  */
460 static struct cdevsw ctl_cdevsw = {
461         .d_version =    D_VERSION,
462         .d_flags =      0,
463         .d_open =       ctl_open,
464         .d_close =      ctl_close,
465         .d_ioctl =      ctl_ioctl,
466         .d_name =       "ctl",
467 };
468
469
470 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
471 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
472
473 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
474
475 static moduledata_t ctl_moduledata = {
476         "ctl",
477         ctl_module_event_handler,
478         NULL
479 };
480
481 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
482 MODULE_VERSION(ctl, 1);
483
484 static struct ctl_frontend ioctl_frontend =
485 {
486         .name = "ioctl",
487 };
488
489 static void
490 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
491                             union ctl_ha_msg *msg_info)
492 {
493         struct ctl_scsiio *ctsio;
494
495         if (msg_info->hdr.original_sc == NULL) {
496                 printf("%s: original_sc == NULL!\n", __func__);
497                 /* XXX KDM now what? */
498                 return;
499         }
500
501         ctsio = &msg_info->hdr.original_sc->scsiio;
502         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
503         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
504         ctsio->io_hdr.status = msg_info->hdr.status;
505         ctsio->scsi_status = msg_info->scsi.scsi_status;
506         ctsio->sense_len = msg_info->scsi.sense_len;
507         ctsio->sense_residual = msg_info->scsi.sense_residual;
508         ctsio->residual = msg_info->scsi.residual;
509         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
510                sizeof(ctsio->sense_data));
511         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
512                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
513         ctl_enqueue_isc((union ctl_io *)ctsio);
514 }
515
516 static void
517 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
518                                 union ctl_ha_msg *msg_info)
519 {
520         struct ctl_scsiio *ctsio;
521
522         if (msg_info->hdr.serializing_sc == NULL) {
523                 printf("%s: serializing_sc == NULL!\n", __func__);
524                 /* XXX KDM now what? */
525                 return;
526         }
527
528         ctsio = &msg_info->hdr.serializing_sc->scsiio;
529 #if 0
530         /*
531          * Attempt to catch the situation where an I/O has
532          * been freed, and we're using it again.
533          */
534         if (ctsio->io_hdr.io_type == 0xff) {
535                 union ctl_io *tmp_io;
536                 tmp_io = (union ctl_io *)ctsio;
537                 printf("%s: %p use after free!\n", __func__,
538                        ctsio);
539                 printf("%s: type %d msg %d cdb %x iptl: "
540                        "%d:%d:%d:%d tag 0x%04x "
541                        "flag %#x status %x\n",
542                         __func__,
543                         tmp_io->io_hdr.io_type,
544                         tmp_io->io_hdr.msg_type,
545                         tmp_io->scsiio.cdb[0],
546                         tmp_io->io_hdr.nexus.initid.id,
547                         tmp_io->io_hdr.nexus.targ_port,
548                         tmp_io->io_hdr.nexus.targ_target.id,
549                         tmp_io->io_hdr.nexus.targ_lun,
550                         (tmp_io->io_hdr.io_type ==
551                         CTL_IO_TASK) ?
552                         tmp_io->taskio.tag_num :
553                         tmp_io->scsiio.tag_num,
554                         tmp_io->io_hdr.flags,
555                         tmp_io->io_hdr.status);
556         }
557 #endif
558         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
559         ctl_enqueue_isc((union ctl_io *)ctsio);
560 }
561
562 /*
563  * ISC (Inter Shelf Communication) event handler.  Events from the HA
564  * subsystem come in here.
565  */
566 static void
567 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
568 {
569         struct ctl_softc *ctl_softc;
570         union ctl_io *io;
571         struct ctl_prio *presio;
572         ctl_ha_status isc_status;
573
574         ctl_softc = control_softc;
575         io = NULL;
576
577
578 #if 0
579         printf("CTL: Isc Msg event %d\n", event);
580 #endif
581         if (event == CTL_HA_EVT_MSG_RECV) {
582                 union ctl_ha_msg msg_info;
583
584                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
585                                              sizeof(msg_info), /*wait*/ 0);
586 #if 0
587                 printf("CTL: msg_type %d\n", msg_info.msg_type);
588 #endif
589                 if (isc_status != 0) {
590                         printf("Error receiving message, status = %d\n",
591                                isc_status);
592                         return;
593                 }
594
595                 switch (msg_info.hdr.msg_type) {
596                 case CTL_MSG_SERIALIZE:
597 #if 0
598                         printf("Serialize\n");
599 #endif
600                         io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
601                         if (io == NULL) {
602                                 printf("ctl_isc_event_handler: can't allocate "
603                                        "ctl_io!\n");
604                                 /* Bad Juju */
605                                 /* Need to set busy and send msg back */
606                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
607                                 msg_info.hdr.status = CTL_SCSI_ERROR;
608                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
609                                 msg_info.scsi.sense_len = 0;
610                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
611                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
612                                 }
613                                 goto bailout;
614                         }
615                         ctl_zero_io(io);
616                         // populate ctsio from msg_info
617                         io->io_hdr.io_type = CTL_IO_SCSI;
618                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
619                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
620 #if 0
621                         printf("pOrig %x\n", (int)msg_info.original_sc);
622 #endif
623                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
624                                             CTL_FLAG_IO_ACTIVE;
625                         /*
626                          * If we're in serialization-only mode, we don't
627                          * want to go through full done processing.  Thus
628                          * the COPY flag.
629                          *
630                          * XXX KDM add another flag that is more specific.
631                          */
632                         if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
633                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
634                         io->io_hdr.nexus = msg_info.hdr.nexus;
635 #if 0
636                         printf("targ %d, port %d, iid %d, lun %d\n",
637                                io->io_hdr.nexus.targ_target.id,
638                                io->io_hdr.nexus.targ_port,
639                                io->io_hdr.nexus.initid.id,
640                                io->io_hdr.nexus.targ_lun);
641 #endif
642                         io->scsiio.tag_num = msg_info.scsi.tag_num;
643                         io->scsiio.tag_type = msg_info.scsi.tag_type;
644                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
645                                CTL_MAX_CDBLEN);
646                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
647                                 const struct ctl_cmd_entry *entry;
648
649                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
650                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
651                                 io->io_hdr.flags |=
652                                         entry->flags & CTL_FLAG_DATA_MASK;
653                         }
654                         ctl_enqueue_isc(io);
655                         break;
656
657                 /* Performed on the Originating SC, XFER mode only */
658                 case CTL_MSG_DATAMOVE: {
659                         struct ctl_sg_entry *sgl;
660                         int i, j;
661
662                         io = msg_info.hdr.original_sc;
663                         if (io == NULL) {
664                                 printf("%s: original_sc == NULL!\n", __func__);
665                                 /* XXX KDM do something here */
666                                 break;
667                         }
668                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
669                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
670                         /*
671                          * Keep track of this, we need to send it back over
672                          * when the datamove is complete.
673                          */
674                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
675
676                         if (msg_info.dt.sg_sequence == 0) {
677                                 /*
678                                  * XXX KDM we use the preallocated S/G list
679                                  * here, but we'll need to change this to
680                                  * dynamic allocation if we need larger S/G
681                                  * lists.
682                                  */
683                                 if (msg_info.dt.kern_sg_entries >
684                                     sizeof(io->io_hdr.remote_sglist) /
685                                     sizeof(io->io_hdr.remote_sglist[0])) {
686                                         printf("%s: number of S/G entries "
687                                             "needed %u > allocated num %zd\n",
688                                             __func__,
689                                             msg_info.dt.kern_sg_entries,
690                                             sizeof(io->io_hdr.remote_sglist)/
691                                             sizeof(io->io_hdr.remote_sglist[0]));
692                                 
693                                         /*
694                                          * XXX KDM send a message back to
695                                          * the other side to shut down the
696                                          * DMA.  The error will come back
697                                          * through via the normal channel.
698                                          */
699                                         break;
700                                 }
701                                 sgl = io->io_hdr.remote_sglist;
702                                 memset(sgl, 0,
703                                        sizeof(io->io_hdr.remote_sglist));
704
705                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
706
707                                 io->scsiio.kern_sg_entries =
708                                         msg_info.dt.kern_sg_entries;
709                                 io->scsiio.rem_sg_entries =
710                                         msg_info.dt.kern_sg_entries;
711                                 io->scsiio.kern_data_len =
712                                         msg_info.dt.kern_data_len;
713                                 io->scsiio.kern_total_len =
714                                         msg_info.dt.kern_total_len;
715                                 io->scsiio.kern_data_resid =
716                                         msg_info.dt.kern_data_resid;
717                                 io->scsiio.kern_rel_offset =
718                                         msg_info.dt.kern_rel_offset;
719                                 /*
720                                  * Clear out per-DMA flags.
721                                  */
722                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
723                                 /*
724                                  * Add per-DMA flags that are set for this
725                                  * particular DMA request.
726                                  */
727                                 io->io_hdr.flags |= msg_info.dt.flags &
728                                                     CTL_FLAG_RDMA_MASK;
729                         } else
730                                 sgl = (struct ctl_sg_entry *)
731                                         io->scsiio.kern_data_ptr;
732
733                         for (i = msg_info.dt.sent_sg_entries, j = 0;
734                              i < (msg_info.dt.sent_sg_entries +
735                              msg_info.dt.cur_sg_entries); i++, j++) {
736                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
737                                 sgl[i].len = msg_info.dt.sg_list[j].len;
738
739 #if 0
740                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
741                                        __func__,
742                                        msg_info.dt.sg_list[j].addr,
743                                        msg_info.dt.sg_list[j].len,
744                                        sgl[i].addr, sgl[i].len, j, i);
745 #endif
746                         }
747 #if 0
748                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
749                                msg_info.dt.sg_list,
750                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
751 #endif
752
753                         /*
754                          * If this is the last piece of the I/O, we've got
755                          * the full S/G list.  Queue processing in the thread.
756                          * Otherwise wait for the next piece.
757                          */
758                         if (msg_info.dt.sg_last != 0)
759                                 ctl_enqueue_isc(io);
760                         break;
761                 }
762                 /* Performed on the Serializing (primary) SC, XFER mode only */
763                 case CTL_MSG_DATAMOVE_DONE: {
764                         if (msg_info.hdr.serializing_sc == NULL) {
765                                 printf("%s: serializing_sc == NULL!\n",
766                                        __func__);
767                                 /* XXX KDM now what? */
768                                 break;
769                         }
770                         /*
771                          * We grab the sense information here in case
772                          * there was a failure, so we can return status
773                          * back to the initiator.
774                          */
775                         io = msg_info.hdr.serializing_sc;
776                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
777                         io->io_hdr.status = msg_info.hdr.status;
778                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
779                         io->scsiio.sense_len = msg_info.scsi.sense_len;
780                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
781                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
782                         io->scsiio.residual = msg_info.scsi.residual;
783                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
784                                sizeof(io->scsiio.sense_data));
785                         ctl_enqueue_isc(io);
786                         break;
787                 }
788
789                 /* Preformed on Originating SC, SER_ONLY mode */
790                 case CTL_MSG_R2R:
791                         io = msg_info.hdr.original_sc;
792                         if (io == NULL) {
793                                 printf("%s: Major Bummer\n", __func__);
794                                 return;
795                         } else {
796 #if 0
797                                 printf("pOrig %x\n",(int) ctsio);
798 #endif
799                         }
800                         io->io_hdr.msg_type = CTL_MSG_R2R;
801                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
802                         ctl_enqueue_isc(io);
803                         break;
804
805                 /*
806                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
807                  * mode.
808                  * Performed on the Originating (i.e. secondary) SC in XFER
809                  * mode
810                  */
811                 case CTL_MSG_FINISH_IO:
812                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
813                                 ctl_isc_handler_finish_xfer(ctl_softc,
814                                                             &msg_info);
815                         else
816                                 ctl_isc_handler_finish_ser_only(ctl_softc,
817                                                                 &msg_info);
818                         break;
819
820                 /* Preformed on Originating SC */
821                 case CTL_MSG_BAD_JUJU:
822                         io = msg_info.hdr.original_sc;
823                         if (io == NULL) {
824                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
825                                        __func__);
826                                 break;
827                         }
828                         ctl_copy_sense_data(&msg_info, io);
829                         /*
830                          * IO should have already been cleaned up on other
831                          * SC so clear this flag so we won't send a message
832                          * back to finish the IO there.
833                          */
834                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
835                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
836
837                         /* io = msg_info.hdr.serializing_sc; */
838                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
839                         ctl_enqueue_isc(io);
840                         break;
841
842                 /* Handle resets sent from the other side */
843                 case CTL_MSG_MANAGE_TASKS: {
844                         struct ctl_taskio *taskio;
845                         taskio = (struct ctl_taskio *)ctl_alloc_io(
846                                 (void *)ctl_softc->othersc_pool);
847                         if (taskio == NULL) {
848                                 printf("ctl_isc_event_handler: can't allocate "
849                                        "ctl_io!\n");
850                                 /* Bad Juju */
851                                 /* should I just call the proper reset func
852                                    here??? */
853                                 goto bailout;
854                         }
855                         ctl_zero_io((union ctl_io *)taskio);
856                         taskio->io_hdr.io_type = CTL_IO_TASK;
857                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
858                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
859                         taskio->task_action = msg_info.task.task_action;
860                         taskio->tag_num = msg_info.task.tag_num;
861                         taskio->tag_type = msg_info.task.tag_type;
862 #ifdef CTL_TIME_IO
863                         taskio->io_hdr.start_time = time_uptime;
864                         getbintime(&taskio->io_hdr.start_bt);
865 #if 0
866                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
867 #endif
868 #endif /* CTL_TIME_IO */
869                         ctl_run_task((union ctl_io *)taskio);
870                         break;
871                 }
872                 /* Persistent Reserve action which needs attention */
873                 case CTL_MSG_PERS_ACTION:
874                         presio = (struct ctl_prio *)ctl_alloc_io(
875                                 (void *)ctl_softc->othersc_pool);
876                         if (presio == NULL) {
877                                 printf("ctl_isc_event_handler: can't allocate "
878                                        "ctl_io!\n");
879                                 /* Bad Juju */
880                                 /* Need to set busy and send msg back */
881                                 goto bailout;
882                         }
883                         ctl_zero_io((union ctl_io *)presio);
884                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
885                         presio->pr_msg = msg_info.pr;
886                         ctl_enqueue_isc((union ctl_io *)presio);
887                         break;
888                 case CTL_MSG_SYNC_FE:
889                         rcv_sync_msg = 1;
890                         break;
891                 case CTL_MSG_APS_LOCK: {
892                         // It's quicker to execute this then to
893                         // queue it.
894                         struct ctl_lun *lun;
895                         struct ctl_page_index *page_index;
896                         struct copan_aps_subpage *current_sp;
897                         uint32_t targ_lun;
898
899                         targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
900                         lun = ctl_softc->ctl_luns[targ_lun];
901                         mtx_lock(&lun->lun_lock);
902                         page_index = &lun->mode_pages.index[index_to_aps_page];
903                         current_sp = (struct copan_aps_subpage *)
904                                      (page_index->page_data +
905                                      (page_index->page_len * CTL_PAGE_CURRENT));
906
907                         current_sp->lock_active = msg_info.aps.lock_flag;
908                         mtx_unlock(&lun->lun_lock);
909                         break;
910                 }
911                 default:
912                         printf("How did I get here?\n");
913                 }
914         } else if (event == CTL_HA_EVT_MSG_SENT) {
915                 if (param != CTL_HA_STATUS_SUCCESS) {
916                         printf("Bad status from ctl_ha_msg_send status %d\n",
917                                param);
918                 }
919                 return;
920         } else if (event == CTL_HA_EVT_DISCONNECT) {
921                 printf("CTL: Got a disconnect from Isc\n");
922                 return;
923         } else {
924                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
925                 return;
926         }
927
928 bailout:
929         return;
930 }
931
932 static void
933 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
934 {
935         struct scsi_sense_data *sense;
936
937         sense = &dest->scsiio.sense_data;
938         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
939         dest->scsiio.scsi_status = src->scsi.scsi_status;
940         dest->scsiio.sense_len = src->scsi.sense_len;
941         dest->io_hdr.status = src->hdr.status;
942 }
943
944 static int
945 ctl_init(void)
946 {
947         struct ctl_softc *softc;
948         struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
949         struct ctl_port *port;
950         uint8_t sc_id =0;
951         int i, error, retval;
952         //int isc_retval;
953
954         retval = 0;
955         ctl_pause_rtr = 0;
956         rcv_sync_msg = 0;
957
958         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
959                                M_WAITOK | M_ZERO);
960         softc = control_softc;
961
962         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
963                               "cam/ctl");
964
965         softc->dev->si_drv1 = softc;
966
967         /*
968          * By default, return a "bad LUN" peripheral qualifier for unknown
969          * LUNs.  The user can override this default using the tunable or
970          * sysctl.  See the comment in ctl_inquiry_std() for more details.
971          */
972         softc->inquiry_pq_no_lun = 1;
973         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
974                           &softc->inquiry_pq_no_lun);
975         sysctl_ctx_init(&softc->sysctl_ctx);
976         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
977                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
978                 CTLFLAG_RD, 0, "CAM Target Layer");
979
980         if (softc->sysctl_tree == NULL) {
981                 printf("%s: unable to allocate sysctl tree\n", __func__);
982                 destroy_dev(softc->dev);
983                 free(control_softc, M_DEVBUF);
984                 control_softc = NULL;
985                 return (ENOMEM);
986         }
987
988         SYSCTL_ADD_INT(&softc->sysctl_ctx,
989                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
990                        "inquiry_pq_no_lun", CTLFLAG_RW,
991                        &softc->inquiry_pq_no_lun, 0,
992                        "Report no lun possible for invalid LUNs");
993
994         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
995         mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
996         softc->open_count = 0;
997
998         /*
999          * Default to actually sending a SYNCHRONIZE CACHE command down to
1000          * the drive.
1001          */
1002         softc->flags = CTL_FLAG_REAL_SYNC;
1003
1004         /*
1005          * In Copan's HA scheme, the "master" and "slave" roles are
1006          * figured out through the slot the controller is in.  Although it
1007          * is an active/active system, someone has to be in charge.
1008          */
1009 #ifdef NEEDTOPORT
1010         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1011 #endif
1012
1013         if (sc_id == 0) {
1014                 softc->flags |= CTL_FLAG_MASTER_SHELF;
1015                 persis_offset = 0;
1016         } else
1017                 persis_offset = CTL_MAX_INITIATORS;
1018
1019         /*
1020          * XXX KDM need to figure out where we want to get our target ID
1021          * and WWID.  Is it different on each port?
1022          */
1023         softc->target.id = 0;
1024         softc->target.wwid[0] = 0x12345678;
1025         softc->target.wwid[1] = 0x87654321;
1026         STAILQ_INIT(&softc->lun_list);
1027         STAILQ_INIT(&softc->pending_lun_queue);
1028         STAILQ_INIT(&softc->fe_list);
1029         STAILQ_INIT(&softc->port_list);
1030         STAILQ_INIT(&softc->be_list);
1031         STAILQ_INIT(&softc->io_pools);
1032         ctl_tpc_init(softc);
1033
1034         if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1035                             &internal_pool)!= 0){
1036                 printf("ctl: can't allocate %d entry internal pool, "
1037                        "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1038                 return (ENOMEM);
1039         }
1040
1041         if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1042                             CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1043                 printf("ctl: can't allocate %d entry emergency pool, "
1044                        "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1045                 ctl_pool_free(internal_pool);
1046                 return (ENOMEM);
1047         }
1048
1049         if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1050                             &other_pool) != 0)
1051         {
1052                 printf("ctl: can't allocate %d entry other SC pool, "
1053                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1054                 ctl_pool_free(internal_pool);
1055                 ctl_pool_free(emergency_pool);
1056                 return (ENOMEM);
1057         }
1058
1059         softc->internal_pool = internal_pool;
1060         softc->emergency_pool = emergency_pool;
1061         softc->othersc_pool = other_pool;
1062
1063         if (worker_threads <= 0)
1064                 worker_threads = max(1, mp_ncpus / 4);
1065         if (worker_threads > CTL_MAX_THREADS)
1066                 worker_threads = CTL_MAX_THREADS;
1067
1068         for (i = 0; i < worker_threads; i++) {
1069                 struct ctl_thread *thr = &softc->threads[i];
1070
1071                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1072                 thr->ctl_softc = softc;
1073                 STAILQ_INIT(&thr->incoming_queue);
1074                 STAILQ_INIT(&thr->rtr_queue);
1075                 STAILQ_INIT(&thr->done_queue);
1076                 STAILQ_INIT(&thr->isc_queue);
1077
1078                 error = kproc_kthread_add(ctl_work_thread, thr,
1079                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1080                 if (error != 0) {
1081                         printf("error creating CTL work thread!\n");
1082                         ctl_pool_free(internal_pool);
1083                         ctl_pool_free(emergency_pool);
1084                         ctl_pool_free(other_pool);
1085                         return (error);
1086                 }
1087         }
1088         error = kproc_kthread_add(ctl_lun_thread, softc,
1089             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1090         if (error != 0) {
1091                 printf("error creating CTL lun thread!\n");
1092                 ctl_pool_free(internal_pool);
1093                 ctl_pool_free(emergency_pool);
1094                 ctl_pool_free(other_pool);
1095                 return (error);
1096         }
1097         if (bootverbose)
1098                 printf("ctl: CAM Target Layer loaded\n");
1099
1100         /*
1101          * Initialize the ioctl front end.
1102          */
1103         ctl_frontend_register(&ioctl_frontend);
1104         port = &softc->ioctl_info.port;
1105         port->frontend = &ioctl_frontend;
1106         sprintf(softc->ioctl_info.port_name, "ioctl");
1107         port->port_type = CTL_PORT_IOCTL;
1108         port->num_requested_ctl_io = 100;
1109         port->port_name = softc->ioctl_info.port_name;
1110         port->port_online = ctl_ioctl_online;
1111         port->port_offline = ctl_ioctl_offline;
1112         port->onoff_arg = &softc->ioctl_info;
1113         port->lun_enable = ctl_ioctl_lun_enable;
1114         port->lun_disable = ctl_ioctl_lun_disable;
1115         port->targ_lun_arg = &softc->ioctl_info;
1116         port->fe_datamove = ctl_ioctl_datamove;
1117         port->fe_done = ctl_ioctl_done;
1118         port->max_targets = 15;
1119         port->max_target_id = 15;
1120
1121         if (ctl_port_register(&softc->ioctl_info.port,
1122                           (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1123                 printf("ctl: ioctl front end registration failed, will "
1124                        "continue anyway\n");
1125         }
1126
1127 #ifdef CTL_IO_DELAY
1128         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1129                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1130                        sizeof(struct callout), CTL_TIMER_BYTES);
1131                 return (EINVAL);
1132         }
1133 #endif /* CTL_IO_DELAY */
1134
1135         return (0);
1136 }
1137
1138 void
1139 ctl_shutdown(void)
1140 {
1141         struct ctl_softc *softc;
1142         struct ctl_lun *lun, *next_lun;
1143         struct ctl_io_pool *pool;
1144
1145         softc = (struct ctl_softc *)control_softc;
1146
1147         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1148                 printf("ctl: ioctl front end deregistration failed\n");
1149
1150         mtx_lock(&softc->ctl_lock);
1151
1152         /*
1153          * Free up each LUN.
1154          */
1155         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1156                 next_lun = STAILQ_NEXT(lun, links);
1157                 ctl_free_lun(lun);
1158         }
1159
1160         mtx_unlock(&softc->ctl_lock);
1161
1162         ctl_frontend_deregister(&ioctl_frontend);
1163
1164         /*
1165          * This will rip the rug out from under any FETDs or anyone else
1166          * that has a pool allocated.  Since we increment our module
1167          * refcount any time someone outside the main CTL module allocates
1168          * a pool, we shouldn't have any problems here.  The user won't be
1169          * able to unload the CTL module until client modules have
1170          * successfully unloaded.
1171          */
1172         while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1173                 ctl_pool_free(pool);
1174
1175 #if 0
1176         ctl_shutdown_thread(softc->work_thread);
1177         mtx_destroy(&softc->queue_lock);
1178 #endif
1179
1180         ctl_tpc_shutdown(softc);
1181         mtx_destroy(&softc->pool_lock);
1182         mtx_destroy(&softc->ctl_lock);
1183
1184         destroy_dev(softc->dev);
1185
1186         sysctl_ctx_free(&softc->sysctl_ctx);
1187
1188         free(control_softc, M_DEVBUF);
1189         control_softc = NULL;
1190
1191         if (bootverbose)
1192                 printf("ctl: CAM Target Layer unloaded\n");
1193 }
1194
1195 static int
1196 ctl_module_event_handler(module_t mod, int what, void *arg)
1197 {
1198
1199         switch (what) {
1200         case MOD_LOAD:
1201                 return (ctl_init());
1202         case MOD_UNLOAD:
1203                 return (EBUSY);
1204         default:
1205                 return (EOPNOTSUPP);
1206         }
1207 }
1208
1209 /*
1210  * XXX KDM should we do some access checks here?  Bump a reference count to
1211  * prevent a CTL module from being unloaded while someone has it open?
1212  */
1213 static int
1214 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1215 {
1216         return (0);
1217 }
1218
1219 static int
1220 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1221 {
1222         return (0);
1223 }
1224
1225 int
1226 ctl_port_enable(ctl_port_type port_type)
1227 {
1228         struct ctl_softc *softc;
1229         struct ctl_port *port;
1230
1231         if (ctl_is_single == 0) {
1232                 union ctl_ha_msg msg_info;
1233                 int isc_retval;
1234
1235 #if 0
1236                 printf("%s: HA mode, synchronizing frontend enable\n",
1237                         __func__);
1238 #endif
1239                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1240                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1241                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1242                         printf("Sync msg send error retval %d\n", isc_retval);
1243                 }
1244                 if (!rcv_sync_msg) {
1245                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1246                                 sizeof(msg_info), 1);
1247                 }
1248 #if 0
1249                 printf("CTL:Frontend Enable\n");
1250         } else {
1251                 printf("%s: single mode, skipping frontend synchronization\n",
1252                         __func__);
1253 #endif
1254         }
1255
1256         softc = control_softc;
1257
1258         STAILQ_FOREACH(port, &softc->port_list, links) {
1259                 if (port_type & port->port_type)
1260                 {
1261 #if 0
1262                         printf("port %d\n", port->targ_port);
1263 #endif
1264                         ctl_port_online(port);
1265                 }
1266         }
1267
1268         return (0);
1269 }
1270
1271 int
1272 ctl_port_disable(ctl_port_type port_type)
1273 {
1274         struct ctl_softc *softc;
1275         struct ctl_port *port;
1276
1277         softc = control_softc;
1278
1279         STAILQ_FOREACH(port, &softc->port_list, links) {
1280                 if (port_type & port->port_type)
1281                         ctl_port_offline(port);
1282         }
1283
1284         return (0);
1285 }
1286
1287 /*
1288  * Returns 0 for success, 1 for failure.
1289  * Currently the only failure mode is if there aren't enough entries
1290  * allocated.  So, in case of a failure, look at num_entries_dropped,
1291  * reallocate and try again.
1292  */
1293 int
1294 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1295               int *num_entries_filled, int *num_entries_dropped,
1296               ctl_port_type port_type, int no_virtual)
1297 {
1298         struct ctl_softc *softc;
1299         struct ctl_port *port;
1300         int entries_dropped, entries_filled;
1301         int retval;
1302         int i;
1303
1304         softc = control_softc;
1305
1306         retval = 0;
1307         entries_filled = 0;
1308         entries_dropped = 0;
1309
1310         i = 0;
1311         mtx_lock(&softc->ctl_lock);
1312         STAILQ_FOREACH(port, &softc->port_list, links) {
1313                 struct ctl_port_entry *entry;
1314
1315                 if ((port->port_type & port_type) == 0)
1316                         continue;
1317
1318                 if ((no_virtual != 0)
1319                  && (port->virtual_port != 0))
1320                         continue;
1321
1322                 if (entries_filled >= num_entries_alloced) {
1323                         entries_dropped++;
1324                         continue;
1325                 }
1326                 entry = &entries[i];
1327
1328                 entry->port_type = port->port_type;
1329                 strlcpy(entry->port_name, port->port_name,
1330                         sizeof(entry->port_name));
1331                 entry->physical_port = port->physical_port;
1332                 entry->virtual_port = port->virtual_port;
1333                 entry->wwnn = port->wwnn;
1334                 entry->wwpn = port->wwpn;
1335
1336                 i++;
1337                 entries_filled++;
1338         }
1339
1340         mtx_unlock(&softc->ctl_lock);
1341
1342         if (entries_dropped > 0)
1343                 retval = 1;
1344
1345         *num_entries_dropped = entries_dropped;
1346         *num_entries_filled = entries_filled;
1347
1348         return (retval);
1349 }
1350
1351 static void
1352 ctl_ioctl_online(void *arg)
1353 {
1354         struct ctl_ioctl_info *ioctl_info;
1355
1356         ioctl_info = (struct ctl_ioctl_info *)arg;
1357
1358         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1359 }
1360
1361 static void
1362 ctl_ioctl_offline(void *arg)
1363 {
1364         struct ctl_ioctl_info *ioctl_info;
1365
1366         ioctl_info = (struct ctl_ioctl_info *)arg;
1367
1368         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1369 }
1370
1371 /*
1372  * Remove an initiator by port number and initiator ID.
1373  * Returns 0 for success, -1 for failure.
1374  */
1375 int
1376 ctl_remove_initiator(struct ctl_port *port, int iid)
1377 {
1378         struct ctl_softc *softc = control_softc;
1379
1380         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1381
1382         if (iid > CTL_MAX_INIT_PER_PORT) {
1383                 printf("%s: initiator ID %u > maximun %u!\n",
1384                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1385                 return (-1);
1386         }
1387
1388         mtx_lock(&softc->ctl_lock);
1389         port->wwpn_iid[iid].in_use--;
1390         port->wwpn_iid[iid].last_use = time_uptime;
1391         mtx_unlock(&softc->ctl_lock);
1392
1393         return (0);
1394 }
1395
1396 /*
1397  * Add an initiator to the initiator map.
1398  * Returns iid for success, < 0 for failure.
1399  */
1400 int
1401 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1402 {
1403         struct ctl_softc *softc = control_softc;
1404         time_t best_time;
1405         int i, best;
1406
1407         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1408
1409         if (iid >= CTL_MAX_INIT_PER_PORT) {
1410                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1411                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1412                 free(name, M_CTL);
1413                 return (-1);
1414         }
1415
1416         mtx_lock(&softc->ctl_lock);
1417
1418         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1419                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1420                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1421                                 iid = i;
1422                                 break;
1423                         }
1424                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1425                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1426                                 iid = i;
1427                                 break;
1428                         }
1429                 }
1430         }
1431
1432         if (iid < 0) {
1433                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1434                         if (port->wwpn_iid[i].in_use == 0 &&
1435                             port->wwpn_iid[i].wwpn == 0 &&
1436                             port->wwpn_iid[i].name == NULL) {
1437                                 iid = i;
1438                                 break;
1439                         }
1440                 }
1441         }
1442
1443         if (iid < 0) {
1444                 best = -1;
1445                 best_time = INT32_MAX;
1446                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1447                         if (port->wwpn_iid[i].in_use == 0) {
1448                                 if (port->wwpn_iid[i].last_use < best_time) {
1449                                         best = i;
1450                                         best_time = port->wwpn_iid[i].last_use;
1451                                 }
1452                         }
1453                 }
1454                 iid = best;
1455         }
1456
1457         if (iid < 0) {
1458                 mtx_unlock(&softc->ctl_lock);
1459                 free(name, M_CTL);
1460                 return (-2);
1461         }
1462
1463         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1464                 /*
1465                  * This is not an error yet.
1466                  */
1467                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1468 #if 0
1469                         printf("%s: port %d iid %u WWPN %#jx arrived"
1470                             " again\n", __func__, port->targ_port,
1471                             iid, (uintmax_t)wwpn);
1472 #endif
1473                         goto take;
1474                 }
1475                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1476                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1477 #if 0
1478                         printf("%s: port %d iid %u name '%s' arrived"
1479                             " again\n", __func__, port->targ_port,
1480                             iid, name);
1481 #endif
1482                         goto take;
1483                 }
1484
1485                 /*
1486                  * This is an error, but what do we do about it?  The
1487                  * driver is telling us we have a new WWPN for this
1488                  * initiator ID, so we pretty much need to use it.
1489                  */
1490                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1491                     " but WWPN %#jx '%s' is still at that address\n",
1492                     __func__, port->targ_port, iid, wwpn, name,
1493                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1494                     port->wwpn_iid[iid].name);
1495
1496                 /*
1497                  * XXX KDM clear have_ca and ua_pending on each LUN for
1498                  * this initiator.
1499                  */
1500         }
1501 take:
1502         free(port->wwpn_iid[iid].name, M_CTL);
1503         port->wwpn_iid[iid].name = name;
1504         port->wwpn_iid[iid].wwpn = wwpn;
1505         port->wwpn_iid[iid].in_use++;
1506         mtx_unlock(&softc->ctl_lock);
1507
1508         return (iid);
1509 }
1510
1511 static int
1512 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1513 {
1514         int len;
1515
1516         switch (port->port_type) {
1517         case CTL_PORT_FC:
1518         {
1519                 struct scsi_transportid_fcp *id =
1520                     (struct scsi_transportid_fcp *)buf;
1521                 if (port->wwpn_iid[iid].wwpn == 0)
1522                         return (0);
1523                 memset(id, 0, sizeof(*id));
1524                 id->format_protocol = SCSI_PROTO_FC;
1525                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1526                 return (sizeof(*id));
1527         }
1528         case CTL_PORT_ISCSI:
1529         {
1530                 struct scsi_transportid_iscsi_port *id =
1531                     (struct scsi_transportid_iscsi_port *)buf;
1532                 if (port->wwpn_iid[iid].name == NULL)
1533                         return (0);
1534                 memset(id, 0, 256);
1535                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1536                     SCSI_PROTO_ISCSI;
1537                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1538                 len = roundup2(min(len, 252), 4);
1539                 scsi_ulto2b(len, id->additional_length);
1540                 return (sizeof(*id) + len);
1541         }
1542         case CTL_PORT_SAS:
1543         {
1544                 struct scsi_transportid_sas *id =
1545                     (struct scsi_transportid_sas *)buf;
1546                 if (port->wwpn_iid[iid].wwpn == 0)
1547                         return (0);
1548                 memset(id, 0, sizeof(*id));
1549                 id->format_protocol = SCSI_PROTO_SAS;
1550                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1551                 return (sizeof(*id));
1552         }
1553         default:
1554         {
1555                 struct scsi_transportid_spi *id =
1556                     (struct scsi_transportid_spi *)buf;
1557                 memset(id, 0, sizeof(*id));
1558                 id->format_protocol = SCSI_PROTO_SPI;
1559                 scsi_ulto2b(iid, id->scsi_addr);
1560                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1561                 return (sizeof(*id));
1562         }
1563         }
1564 }
1565
1566 static int
1567 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1568 {
1569         return (0);
1570 }
1571
1572 static int
1573 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1574 {
1575         return (0);
1576 }
1577
1578 /*
1579  * Data movement routine for the CTL ioctl frontend port.
1580  */
1581 static int
1582 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1583 {
1584         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1585         struct ctl_sg_entry ext_entry, kern_entry;
1586         int ext_sglen, ext_sg_entries, kern_sg_entries;
1587         int ext_sg_start, ext_offset;
1588         int len_to_copy, len_copied;
1589         int kern_watermark, ext_watermark;
1590         int ext_sglist_malloced;
1591         int i, j;
1592
1593         ext_sglist_malloced = 0;
1594         ext_sg_start = 0;
1595         ext_offset = 0;
1596
1597         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1598
1599         /*
1600          * If this flag is set, fake the data transfer.
1601          */
1602         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1603                 ctsio->ext_data_filled = ctsio->ext_data_len;
1604                 goto bailout;
1605         }
1606
1607         /*
1608          * To simplify things here, if we have a single buffer, stick it in
1609          * a S/G entry and just make it a single entry S/G list.
1610          */
1611         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1612                 int len_seen;
1613
1614                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1615
1616                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1617                                                            M_WAITOK);
1618                 ext_sglist_malloced = 1;
1619                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1620                                    ext_sglen) != 0) {
1621                         ctl_set_internal_failure(ctsio,
1622                                                  /*sks_valid*/ 0,
1623                                                  /*retry_count*/ 0);
1624                         goto bailout;
1625                 }
1626                 ext_sg_entries = ctsio->ext_sg_entries;
1627                 len_seen = 0;
1628                 for (i = 0; i < ext_sg_entries; i++) {
1629                         if ((len_seen + ext_sglist[i].len) >=
1630                              ctsio->ext_data_filled) {
1631                                 ext_sg_start = i;
1632                                 ext_offset = ctsio->ext_data_filled - len_seen;
1633                                 break;
1634                         }
1635                         len_seen += ext_sglist[i].len;
1636                 }
1637         } else {
1638                 ext_sglist = &ext_entry;
1639                 ext_sglist->addr = ctsio->ext_data_ptr;
1640                 ext_sglist->len = ctsio->ext_data_len;
1641                 ext_sg_entries = 1;
1642                 ext_sg_start = 0;
1643                 ext_offset = ctsio->ext_data_filled;
1644         }
1645
1646         if (ctsio->kern_sg_entries > 0) {
1647                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1648                 kern_sg_entries = ctsio->kern_sg_entries;
1649         } else {
1650                 kern_sglist = &kern_entry;
1651                 kern_sglist->addr = ctsio->kern_data_ptr;
1652                 kern_sglist->len = ctsio->kern_data_len;
1653                 kern_sg_entries = 1;
1654         }
1655
1656
1657         kern_watermark = 0;
1658         ext_watermark = ext_offset;
1659         len_copied = 0;
1660         for (i = ext_sg_start, j = 0;
1661              i < ext_sg_entries && j < kern_sg_entries;) {
1662                 uint8_t *ext_ptr, *kern_ptr;
1663
1664                 len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1665                                       kern_sglist[j].len - kern_watermark);
1666
1667                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1668                 ext_ptr = ext_ptr + ext_watermark;
1669                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1670                         /*
1671                          * XXX KDM fix this!
1672                          */
1673                         panic("need to implement bus address support");
1674 #if 0
1675                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1676 #endif
1677                 } else
1678                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1679                 kern_ptr = kern_ptr + kern_watermark;
1680
1681                 kern_watermark += len_to_copy;
1682                 ext_watermark += len_to_copy;
1683
1684                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1685                      CTL_FLAG_DATA_IN) {
1686                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1687                                          "bytes to user\n", len_to_copy));
1688                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1689                                          "to %p\n", kern_ptr, ext_ptr));
1690                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1691                                 ctl_set_internal_failure(ctsio,
1692                                                          /*sks_valid*/ 0,
1693                                                          /*retry_count*/ 0);
1694                                 goto bailout;
1695                         }
1696                 } else {
1697                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1698                                          "bytes from user\n", len_to_copy));
1699                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1700                                          "to %p\n", ext_ptr, kern_ptr));
1701                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1702                                 ctl_set_internal_failure(ctsio,
1703                                                          /*sks_valid*/ 0,
1704                                                          /*retry_count*/0);
1705                                 goto bailout;
1706                         }
1707                 }
1708
1709                 len_copied += len_to_copy;
1710
1711                 if (ext_sglist[i].len == ext_watermark) {
1712                         i++;
1713                         ext_watermark = 0;
1714                 }
1715
1716                 if (kern_sglist[j].len == kern_watermark) {
1717                         j++;
1718                         kern_watermark = 0;
1719                 }
1720         }
1721
1722         ctsio->ext_data_filled += len_copied;
1723
1724         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1725                          "kern_sg_entries: %d\n", ext_sg_entries,
1726                          kern_sg_entries));
1727         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1728                          "kern_data_len = %d\n", ctsio->ext_data_len,
1729                          ctsio->kern_data_len));
1730
1731
1732         /* XXX KDM set residual?? */
1733 bailout:
1734
1735         if (ext_sglist_malloced != 0)
1736                 free(ext_sglist, M_CTL);
1737
1738         return (CTL_RETVAL_COMPLETE);
1739 }
1740
1741 /*
1742  * Serialize a command that went down the "wrong" side, and so was sent to
1743  * this controller for execution.  The logic is a little different than the
1744  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1745  * sent back to the other side, but in the success case, we execute the
1746  * command on this side (XFER mode) or tell the other side to execute it
1747  * (SER_ONLY mode).
1748  */
1749 static int
1750 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1751 {
1752         struct ctl_softc *ctl_softc;
1753         union ctl_ha_msg msg_info;
1754         struct ctl_lun *lun;
1755         int retval = 0;
1756         uint32_t targ_lun;
1757
1758         ctl_softc = control_softc;
1759
1760         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1761         lun = ctl_softc->ctl_luns[targ_lun];
1762         if (lun==NULL)
1763         {
1764                 /*
1765                  * Why isn't LUN defined? The other side wouldn't
1766                  * send a cmd if the LUN is undefined.
1767                  */
1768                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1769
1770                 /* "Logical unit not supported" */
1771                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1772                                    lun,
1773                                    /*sense_format*/SSD_TYPE_NONE,
1774                                    /*current_error*/ 1,
1775                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1776                                    /*asc*/ 0x25,
1777                                    /*ascq*/ 0x00,
1778                                    SSD_ELEM_NONE);
1779
1780                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1781                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1782                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1783                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1784                 msg_info.hdr.serializing_sc = NULL;
1785                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1786                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1787                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1788                 }
1789                 return(1);
1790
1791         }
1792
1793         mtx_lock(&lun->lun_lock);
1794         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1795
1796         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1797                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1798                  ooa_links))) {
1799         case CTL_ACTION_BLOCK:
1800                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1801                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1802                                   blocked_links);
1803                 break;
1804         case CTL_ACTION_PASS:
1805         case CTL_ACTION_SKIP:
1806                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1807                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1808                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1809                 } else {
1810
1811                         /* send msg back to other side */
1812                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1813                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1814                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1815 #if 0
1816                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1817 #endif
1818                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1819                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1820                         }
1821                 }
1822                 break;
1823         case CTL_ACTION_OVERLAP:
1824                 /* OVERLAPPED COMMANDS ATTEMPTED */
1825                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1826                                    lun,
1827                                    /*sense_format*/SSD_TYPE_NONE,
1828                                    /*current_error*/ 1,
1829                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1830                                    /*asc*/ 0x4E,
1831                                    /*ascq*/ 0x00,
1832                                    SSD_ELEM_NONE);
1833
1834                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1835                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1836                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1837                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1838                 msg_info.hdr.serializing_sc = NULL;
1839                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1840 #if 0
1841                 printf("BAD JUJU:Major Bummer Overlap\n");
1842 #endif
1843                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1844                 retval = 1;
1845                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1846                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1847                 }
1848                 break;
1849         case CTL_ACTION_OVERLAP_TAG:
1850                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1851                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1852                                    lun,
1853                                    /*sense_format*/SSD_TYPE_NONE,
1854                                    /*current_error*/ 1,
1855                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1856                                    /*asc*/ 0x4D,
1857                                    /*ascq*/ ctsio->tag_num & 0xff,
1858                                    SSD_ELEM_NONE);
1859
1860                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1861                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1862                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1863                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1864                 msg_info.hdr.serializing_sc = NULL;
1865                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1866 #if 0
1867                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1868 #endif
1869                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1870                 retval = 1;
1871                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1872                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1873                 }
1874                 break;
1875         case CTL_ACTION_ERROR:
1876         default:
1877                 /* "Internal target failure" */
1878                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1879                                    lun,
1880                                    /*sense_format*/SSD_TYPE_NONE,
1881                                    /*current_error*/ 1,
1882                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1883                                    /*asc*/ 0x44,
1884                                    /*ascq*/ 0x00,
1885                                    SSD_ELEM_NONE);
1886
1887                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1888                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1889                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1890                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1891                 msg_info.hdr.serializing_sc = NULL;
1892                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1893 #if 0
1894                 printf("BAD JUJU:Major Bummer HW Error\n");
1895 #endif
1896                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1897                 retval = 1;
1898                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1899                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1900                 }
1901                 break;
1902         }
1903         mtx_unlock(&lun->lun_lock);
1904         return (retval);
1905 }
1906
1907 static int
1908 ctl_ioctl_submit_wait(union ctl_io *io)
1909 {
1910         struct ctl_fe_ioctl_params params;
1911         ctl_fe_ioctl_state last_state;
1912         int done, retval;
1913
1914         retval = 0;
1915
1916         bzero(&params, sizeof(params));
1917
1918         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1919         cv_init(&params.sem, "ctlioccv");
1920         params.state = CTL_IOCTL_INPROG;
1921         last_state = params.state;
1922
1923         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1924
1925         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1926
1927         /* This shouldn't happen */
1928         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1929                 return (retval);
1930
1931         done = 0;
1932
1933         do {
1934                 mtx_lock(&params.ioctl_mtx);
1935                 /*
1936                  * Check the state here, and don't sleep if the state has
1937                  * already changed (i.e. wakeup has already occured, but we
1938                  * weren't waiting yet).
1939                  */
1940                 if (params.state == last_state) {
1941                         /* XXX KDM cv_wait_sig instead? */
1942                         cv_wait(&params.sem, &params.ioctl_mtx);
1943                 }
1944                 last_state = params.state;
1945
1946                 switch (params.state) {
1947                 case CTL_IOCTL_INPROG:
1948                         /* Why did we wake up? */
1949                         /* XXX KDM error here? */
1950                         mtx_unlock(&params.ioctl_mtx);
1951                         break;
1952                 case CTL_IOCTL_DATAMOVE:
1953                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1954
1955                         /*
1956                          * change last_state back to INPROG to avoid
1957                          * deadlock on subsequent data moves.
1958                          */
1959                         params.state = last_state = CTL_IOCTL_INPROG;
1960
1961                         mtx_unlock(&params.ioctl_mtx);
1962                         ctl_ioctl_do_datamove(&io->scsiio);
1963                         /*
1964                          * Note that in some cases, most notably writes,
1965                          * this will queue the I/O and call us back later.
1966                          * In other cases, generally reads, this routine
1967                          * will immediately call back and wake us up,
1968                          * probably using our own context.
1969                          */
1970                         io->scsiio.be_move_done(io);
1971                         break;
1972                 case CTL_IOCTL_DONE:
1973                         mtx_unlock(&params.ioctl_mtx);
1974                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1975                         done = 1;
1976                         break;
1977                 default:
1978                         mtx_unlock(&params.ioctl_mtx);
1979                         /* XXX KDM error here? */
1980                         break;
1981                 }
1982         } while (done == 0);
1983
1984         mtx_destroy(&params.ioctl_mtx);
1985         cv_destroy(&params.sem);
1986
1987         return (CTL_RETVAL_COMPLETE);
1988 }
1989
1990 static void
1991 ctl_ioctl_datamove(union ctl_io *io)
1992 {
1993         struct ctl_fe_ioctl_params *params;
1994
1995         params = (struct ctl_fe_ioctl_params *)
1996                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1997
1998         mtx_lock(&params->ioctl_mtx);
1999         params->state = CTL_IOCTL_DATAMOVE;
2000         cv_broadcast(&params->sem);
2001         mtx_unlock(&params->ioctl_mtx);
2002 }
2003
2004 static void
2005 ctl_ioctl_done(union ctl_io *io)
2006 {
2007         struct ctl_fe_ioctl_params *params;
2008
2009         params = (struct ctl_fe_ioctl_params *)
2010                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2011
2012         mtx_lock(&params->ioctl_mtx);
2013         params->state = CTL_IOCTL_DONE;
2014         cv_broadcast(&params->sem);
2015         mtx_unlock(&params->ioctl_mtx);
2016 }
2017
2018 static void
2019 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2020 {
2021         struct ctl_fe_ioctl_startstop_info *sd_info;
2022
2023         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2024
2025         sd_info->hs_info.status = metatask->status;
2026         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2027         sd_info->hs_info.luns_complete =
2028                 metatask->taskinfo.startstop.luns_complete;
2029         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2030
2031         cv_broadcast(&sd_info->sem);
2032 }
2033
2034 static void
2035 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2036 {
2037         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2038
2039         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2040
2041         mtx_lock(fe_bbr_info->lock);
2042         fe_bbr_info->bbr_info->status = metatask->status;
2043         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2044         fe_bbr_info->wakeup_done = 1;
2045         mtx_unlock(fe_bbr_info->lock);
2046
2047         cv_broadcast(&fe_bbr_info->sem);
2048 }
2049
2050 /*
2051  * Returns 0 for success, errno for failure.
2052  */
2053 static int
2054 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2055                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2056 {
2057         union ctl_io *io;
2058         int retval;
2059
2060         retval = 0;
2061
2062         mtx_lock(&lun->lun_lock);
2063         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2064              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2065              ooa_links)) {
2066                 struct ctl_ooa_entry *entry;
2067
2068                 /*
2069                  * If we've got more than we can fit, just count the
2070                  * remaining entries.
2071                  */
2072                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2073                         continue;
2074
2075                 entry = &kern_entries[*cur_fill_num];
2076
2077                 entry->tag_num = io->scsiio.tag_num;
2078                 entry->lun_num = lun->lun;
2079 #ifdef CTL_TIME_IO
2080                 entry->start_bt = io->io_hdr.start_bt;
2081 #endif
2082                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2083                 entry->cdb_len = io->scsiio.cdb_len;
2084                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2085                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2086
2087                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2088                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2089
2090                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2091                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2092
2093                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2094                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2095
2096                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2097                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2098         }
2099         mtx_unlock(&lun->lun_lock);
2100
2101         return (retval);
2102 }
2103
2104 static void *
2105 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2106                  size_t error_str_len)
2107 {
2108         void *kptr;
2109
2110         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2111
2112         if (copyin(user_addr, kptr, len) != 0) {
2113                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2114                          "from user address %p to kernel address %p", len,
2115                          user_addr, kptr);
2116                 free(kptr, M_CTL);
2117                 return (NULL);
2118         }
2119
2120         return (kptr);
2121 }
2122
2123 static void
2124 ctl_free_args(int num_args, struct ctl_be_arg *args)
2125 {
2126         int i;
2127
2128         if (args == NULL)
2129                 return;
2130
2131         for (i = 0; i < num_args; i++) {
2132                 free(args[i].kname, M_CTL);
2133                 free(args[i].kvalue, M_CTL);
2134         }
2135
2136         free(args, M_CTL);
2137 }
2138
2139 static struct ctl_be_arg *
2140 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2141                 char *error_str, size_t error_str_len)
2142 {
2143         struct ctl_be_arg *args;
2144         int i;
2145
2146         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2147                                 error_str, error_str_len);
2148
2149         if (args == NULL)
2150                 goto bailout;
2151
2152         for (i = 0; i < num_args; i++) {
2153                 args[i].kname = NULL;
2154                 args[i].kvalue = NULL;
2155         }
2156
2157         for (i = 0; i < num_args; i++) {
2158                 uint8_t *tmpptr;
2159
2160                 args[i].kname = ctl_copyin_alloc(args[i].name,
2161                         args[i].namelen, error_str, error_str_len);
2162                 if (args[i].kname == NULL)
2163                         goto bailout;
2164
2165                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2166                         snprintf(error_str, error_str_len, "Argument %d "
2167                                  "name is not NUL-terminated", i);
2168                         goto bailout;
2169                 }
2170
2171                 if (args[i].flags & CTL_BEARG_RD) {
2172                         tmpptr = ctl_copyin_alloc(args[i].value,
2173                                 args[i].vallen, error_str, error_str_len);
2174                         if (tmpptr == NULL)
2175                                 goto bailout;
2176                         if ((args[i].flags & CTL_BEARG_ASCII)
2177                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2178                                 snprintf(error_str, error_str_len, "Argument "
2179                                     "%d value is not NUL-terminated", i);
2180                                 goto bailout;
2181                         }
2182                         args[i].kvalue = tmpptr;
2183                 } else {
2184                         args[i].kvalue = malloc(args[i].vallen,
2185                             M_CTL, M_WAITOK | M_ZERO);
2186                 }
2187         }
2188
2189         return (args);
2190 bailout:
2191
2192         ctl_free_args(num_args, args);
2193
2194         return (NULL);
2195 }
2196
2197 static void
2198 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2199 {
2200         int i;
2201
2202         for (i = 0; i < num_args; i++) {
2203                 if (args[i].flags & CTL_BEARG_WR)
2204                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2205         }
2206 }
2207
2208 /*
2209  * Escape characters that are illegal or not recommended in XML.
2210  */
2211 int
2212 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2213 {
2214         int retval;
2215
2216         retval = 0;
2217
2218         for (; *str; str++) {
2219                 switch (*str) {
2220                 case '&':
2221                         retval = sbuf_printf(sb, "&amp;");
2222                         break;
2223                 case '>':
2224                         retval = sbuf_printf(sb, "&gt;");
2225                         break;
2226                 case '<':
2227                         retval = sbuf_printf(sb, "&lt;");
2228                         break;
2229                 default:
2230                         retval = sbuf_putc(sb, *str);
2231                         break;
2232                 }
2233
2234                 if (retval != 0)
2235                         break;
2236
2237         }
2238
2239         return (retval);
2240 }
2241
2242 static void
2243 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2244 {
2245         struct scsi_vpd_id_descriptor *desc;
2246         int i;
2247
2248         if (id == NULL || id->len < 4)
2249                 return;
2250         desc = (struct scsi_vpd_id_descriptor *)id->data;
2251         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2252         case SVPD_ID_TYPE_T10:
2253                 sbuf_printf(sb, "t10.");
2254                 break;
2255         case SVPD_ID_TYPE_EUI64:
2256                 sbuf_printf(sb, "eui.");
2257                 break;
2258         case SVPD_ID_TYPE_NAA:
2259                 sbuf_printf(sb, "naa.");
2260                 break;
2261         case SVPD_ID_TYPE_SCSI_NAME:
2262                 break;
2263         }
2264         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2265         case SVPD_ID_CODESET_BINARY:
2266                 for (i = 0; i < desc->length; i++)
2267                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2268                 break;
2269         case SVPD_ID_CODESET_ASCII:
2270                 sbuf_printf(sb, "%.*s", (int)desc->length,
2271                     (char *)desc->identifier);
2272                 break;
2273         case SVPD_ID_CODESET_UTF8:
2274                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2275                 break;
2276         }
2277 }
2278
2279 static int
2280 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2281           struct thread *td)
2282 {
2283         struct ctl_softc *softc;
2284         int retval;
2285
2286         softc = control_softc;
2287
2288         retval = 0;
2289
2290         switch (cmd) {
2291         case CTL_IO: {
2292                 union ctl_io *io;
2293                 void *pool_tmp;
2294
2295                 /*
2296                  * If we haven't been "enabled", don't allow any SCSI I/O
2297                  * to this FETD.
2298                  */
2299                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2300                         retval = EPERM;
2301                         break;
2302                 }
2303
2304                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2305                 if (io == NULL) {
2306                         printf("ctl_ioctl: can't allocate ctl_io!\n");
2307                         retval = ENOSPC;
2308                         break;
2309                 }
2310
2311                 /*
2312                  * Need to save the pool reference so it doesn't get
2313                  * spammed by the user's ctl_io.
2314                  */
2315                 pool_tmp = io->io_hdr.pool;
2316
2317                 memcpy(io, (void *)addr, sizeof(*io));
2318
2319                 io->io_hdr.pool = pool_tmp;
2320                 /*
2321                  * No status yet, so make sure the status is set properly.
2322                  */
2323                 io->io_hdr.status = CTL_STATUS_NONE;
2324
2325                 /*
2326                  * The user sets the initiator ID, target and LUN IDs.
2327                  */
2328                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2329                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2330                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2331                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2332                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2333
2334                 retval = ctl_ioctl_submit_wait(io);
2335
2336                 if (retval != 0) {
2337                         ctl_free_io(io);
2338                         break;
2339                 }
2340
2341                 memcpy((void *)addr, io, sizeof(*io));
2342
2343                 /* return this to our pool */
2344                 ctl_free_io(io);
2345
2346                 break;
2347         }
2348         case CTL_ENABLE_PORT:
2349         case CTL_DISABLE_PORT:
2350         case CTL_SET_PORT_WWNS: {
2351                 struct ctl_port *port;
2352                 struct ctl_port_entry *entry;
2353
2354                 entry = (struct ctl_port_entry *)addr;
2355                 
2356                 mtx_lock(&softc->ctl_lock);
2357                 STAILQ_FOREACH(port, &softc->port_list, links) {
2358                         int action, done;
2359
2360                         action = 0;
2361                         done = 0;
2362
2363                         if ((entry->port_type == CTL_PORT_NONE)
2364                          && (entry->targ_port == port->targ_port)) {
2365                                 /*
2366                                  * If the user only wants to enable or
2367                                  * disable or set WWNs on a specific port,
2368                                  * do the operation and we're done.
2369                                  */
2370                                 action = 1;
2371                                 done = 1;
2372                         } else if (entry->port_type & port->port_type) {
2373                                 /*
2374                                  * Compare the user's type mask with the
2375                                  * particular frontend type to see if we
2376                                  * have a match.
2377                                  */
2378                                 action = 1;
2379                                 done = 0;
2380
2381                                 /*
2382                                  * Make sure the user isn't trying to set
2383                                  * WWNs on multiple ports at the same time.
2384                                  */
2385                                 if (cmd == CTL_SET_PORT_WWNS) {
2386                                         printf("%s: Can't set WWNs on "
2387                                                "multiple ports\n", __func__);
2388                                         retval = EINVAL;
2389                                         break;
2390                                 }
2391                         }
2392                         if (action != 0) {
2393                                 /*
2394                                  * XXX KDM we have to drop the lock here,
2395                                  * because the online/offline operations
2396                                  * can potentially block.  We need to
2397                                  * reference count the frontends so they
2398                                  * can't go away,
2399                                  */
2400                                 mtx_unlock(&softc->ctl_lock);
2401
2402                                 if (cmd == CTL_ENABLE_PORT) {
2403                                         struct ctl_lun *lun;
2404
2405                                         STAILQ_FOREACH(lun, &softc->lun_list,
2406                                                        links) {
2407                                                 port->lun_enable(port->targ_lun_arg,
2408                                                     lun->target,
2409                                                     lun->lun);
2410                                         }
2411
2412                                         ctl_port_online(port);
2413                                 } else if (cmd == CTL_DISABLE_PORT) {
2414                                         struct ctl_lun *lun;
2415
2416                                         ctl_port_offline(port);
2417
2418                                         STAILQ_FOREACH(lun, &softc->lun_list,
2419                                                        links) {
2420                                                 port->lun_disable(
2421                                                     port->targ_lun_arg,
2422                                                     lun->target,
2423                                                     lun->lun);
2424                                         }
2425                                 }
2426
2427                                 mtx_lock(&softc->ctl_lock);
2428
2429                                 if (cmd == CTL_SET_PORT_WWNS)
2430                                         ctl_port_set_wwns(port,
2431                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2432                                             1 : 0, entry->wwnn,
2433                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2434                                             1 : 0, entry->wwpn);
2435                         }
2436                         if (done != 0)
2437                                 break;
2438                 }
2439                 mtx_unlock(&softc->ctl_lock);
2440                 break;
2441         }
2442         case CTL_GET_PORT_LIST: {
2443                 struct ctl_port *port;
2444                 struct ctl_port_list *list;
2445                 int i;
2446
2447                 list = (struct ctl_port_list *)addr;
2448
2449                 if (list->alloc_len != (list->alloc_num *
2450                     sizeof(struct ctl_port_entry))) {
2451                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2452                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2453                                "%zu\n", __func__, list->alloc_len,
2454                                list->alloc_num, sizeof(struct ctl_port_entry));
2455                         retval = EINVAL;
2456                         break;
2457                 }
2458                 list->fill_len = 0;
2459                 list->fill_num = 0;
2460                 list->dropped_num = 0;
2461                 i = 0;
2462                 mtx_lock(&softc->ctl_lock);
2463                 STAILQ_FOREACH(port, &softc->port_list, links) {
2464                         struct ctl_port_entry entry, *list_entry;
2465
2466                         if (list->fill_num >= list->alloc_num) {
2467                                 list->dropped_num++;
2468                                 continue;
2469                         }
2470
2471                         entry.port_type = port->port_type;
2472                         strlcpy(entry.port_name, port->port_name,
2473                                 sizeof(entry.port_name));
2474                         entry.targ_port = port->targ_port;
2475                         entry.physical_port = port->physical_port;
2476                         entry.virtual_port = port->virtual_port;
2477                         entry.wwnn = port->wwnn;
2478                         entry.wwpn = port->wwpn;
2479                         if (port->status & CTL_PORT_STATUS_ONLINE)
2480                                 entry.online = 1;
2481                         else
2482                                 entry.online = 0;
2483
2484                         list_entry = &list->entries[i];
2485
2486                         retval = copyout(&entry, list_entry, sizeof(entry));
2487                         if (retval != 0) {
2488                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2489                                        "returned %d\n", __func__, retval);
2490                                 break;
2491                         }
2492                         i++;
2493                         list->fill_num++;
2494                         list->fill_len += sizeof(entry);
2495                 }
2496                 mtx_unlock(&softc->ctl_lock);
2497
2498                 /*
2499                  * If this is non-zero, we had a copyout fault, so there's
2500                  * probably no point in attempting to set the status inside
2501                  * the structure.
2502                  */
2503                 if (retval != 0)
2504                         break;
2505
2506                 if (list->dropped_num > 0)
2507                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2508                 else
2509                         list->status = CTL_PORT_LIST_OK;
2510                 break;
2511         }
2512         case CTL_DUMP_OOA: {
2513                 struct ctl_lun *lun;
2514                 union ctl_io *io;
2515                 char printbuf[128];
2516                 struct sbuf sb;
2517
2518                 mtx_lock(&softc->ctl_lock);
2519                 printf("Dumping OOA queues:\n");
2520                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2521                         mtx_lock(&lun->lun_lock);
2522                         for (io = (union ctl_io *)TAILQ_FIRST(
2523                              &lun->ooa_queue); io != NULL;
2524                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2525                              ooa_links)) {
2526                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2527                                          SBUF_FIXEDLEN);
2528                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2529                                             (intmax_t)lun->lun,
2530                                             io->scsiio.tag_num,
2531                                             (io->io_hdr.flags &
2532                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2533                                             (io->io_hdr.flags &
2534                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2535                                             (io->io_hdr.flags &
2536                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2537                                             (io->io_hdr.flags &
2538                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2539                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2540                                 sbuf_finish(&sb);
2541                                 printf("%s\n", sbuf_data(&sb));
2542                         }
2543                         mtx_unlock(&lun->lun_lock);
2544                 }
2545                 printf("OOA queues dump done\n");
2546                 mtx_unlock(&softc->ctl_lock);
2547                 break;
2548         }
2549         case CTL_GET_OOA: {
2550                 struct ctl_lun *lun;
2551                 struct ctl_ooa *ooa_hdr;
2552                 struct ctl_ooa_entry *entries;
2553                 uint32_t cur_fill_num;
2554
2555                 ooa_hdr = (struct ctl_ooa *)addr;
2556
2557                 if ((ooa_hdr->alloc_len == 0)
2558                  || (ooa_hdr->alloc_num == 0)) {
2559                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2560                                "must be non-zero\n", __func__,
2561                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2562                         retval = EINVAL;
2563                         break;
2564                 }
2565
2566                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2567                     sizeof(struct ctl_ooa_entry))) {
2568                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2569                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2570                                __func__, ooa_hdr->alloc_len,
2571                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2572                         retval = EINVAL;
2573                         break;
2574                 }
2575
2576                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2577                 if (entries == NULL) {
2578                         printf("%s: could not allocate %d bytes for OOA "
2579                                "dump\n", __func__, ooa_hdr->alloc_len);
2580                         retval = ENOMEM;
2581                         break;
2582                 }
2583
2584                 mtx_lock(&softc->ctl_lock);
2585                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2586                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2587                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2588                         mtx_unlock(&softc->ctl_lock);
2589                         free(entries, M_CTL);
2590                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2591                                __func__, (uintmax_t)ooa_hdr->lun_num);
2592                         retval = EINVAL;
2593                         break;
2594                 }
2595
2596                 cur_fill_num = 0;
2597
2598                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2599                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2600                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2601                                         ooa_hdr, entries);
2602                                 if (retval != 0)
2603                                         break;
2604                         }
2605                         if (retval != 0) {
2606                                 mtx_unlock(&softc->ctl_lock);
2607                                 free(entries, M_CTL);
2608                                 break;
2609                         }
2610                 } else {
2611                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2612
2613                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2614                                                     entries);
2615                 }
2616                 mtx_unlock(&softc->ctl_lock);
2617
2618                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2619                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2620                         sizeof(struct ctl_ooa_entry);
2621                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2622                 if (retval != 0) {
2623                         printf("%s: error copying out %d bytes for OOA dump\n", 
2624                                __func__, ooa_hdr->fill_len);
2625                 }
2626
2627                 getbintime(&ooa_hdr->cur_bt);
2628
2629                 if (cur_fill_num > ooa_hdr->alloc_num) {
2630                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2631                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2632                 } else {
2633                         ooa_hdr->dropped_num = 0;
2634                         ooa_hdr->status = CTL_OOA_OK;
2635                 }
2636
2637                 free(entries, M_CTL);
2638                 break;
2639         }
2640         case CTL_CHECK_OOA: {
2641                 union ctl_io *io;
2642                 struct ctl_lun *lun;
2643                 struct ctl_ooa_info *ooa_info;
2644
2645
2646                 ooa_info = (struct ctl_ooa_info *)addr;
2647
2648                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2649                         ooa_info->status = CTL_OOA_INVALID_LUN;
2650                         break;
2651                 }
2652                 mtx_lock(&softc->ctl_lock);
2653                 lun = softc->ctl_luns[ooa_info->lun_id];
2654                 if (lun == NULL) {
2655                         mtx_unlock(&softc->ctl_lock);
2656                         ooa_info->status = CTL_OOA_INVALID_LUN;
2657                         break;
2658                 }
2659                 mtx_lock(&lun->lun_lock);
2660                 mtx_unlock(&softc->ctl_lock);
2661                 ooa_info->num_entries = 0;
2662                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2663                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2664                      &io->io_hdr, ooa_links)) {
2665                         ooa_info->num_entries++;
2666                 }
2667                 mtx_unlock(&lun->lun_lock);
2668
2669                 ooa_info->status = CTL_OOA_SUCCESS;
2670
2671                 break;
2672         }
2673         case CTL_HARD_START:
2674         case CTL_HARD_STOP: {
2675                 struct ctl_fe_ioctl_startstop_info ss_info;
2676                 struct cfi_metatask *metatask;
2677                 struct mtx hs_mtx;
2678
2679                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2680
2681                 cv_init(&ss_info.sem, "hard start/stop cv" );
2682
2683                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2684                 if (metatask == NULL) {
2685                         retval = ENOMEM;
2686                         mtx_destroy(&hs_mtx);
2687                         break;
2688                 }
2689
2690                 if (cmd == CTL_HARD_START)
2691                         metatask->tasktype = CFI_TASK_STARTUP;
2692                 else
2693                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2694
2695                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2696                 metatask->callback_arg = &ss_info;
2697
2698                 cfi_action(metatask);
2699
2700                 /* Wait for the callback */
2701                 mtx_lock(&hs_mtx);
2702                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2703                 mtx_unlock(&hs_mtx);
2704
2705                 /*
2706                  * All information has been copied from the metatask by the
2707                  * time cv_broadcast() is called, so we free the metatask here.
2708                  */
2709                 cfi_free_metatask(metatask);
2710
2711                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2712
2713                 mtx_destroy(&hs_mtx);
2714                 break;
2715         }
2716         case CTL_BBRREAD: {
2717                 struct ctl_bbrread_info *bbr_info;
2718                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2719                 struct mtx bbr_mtx;
2720                 struct cfi_metatask *metatask;
2721
2722                 bbr_info = (struct ctl_bbrread_info *)addr;
2723
2724                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2725
2726                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2727                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2728
2729                 fe_bbr_info.bbr_info = bbr_info;
2730                 fe_bbr_info.lock = &bbr_mtx;
2731
2732                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2733                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2734
2735                 if (metatask == NULL) {
2736                         mtx_destroy(&bbr_mtx);
2737                         cv_destroy(&fe_bbr_info.sem);
2738                         retval = ENOMEM;
2739                         break;
2740                 }
2741                 metatask->tasktype = CFI_TASK_BBRREAD;
2742                 metatask->callback = ctl_ioctl_bbrread_callback;
2743                 metatask->callback_arg = &fe_bbr_info;
2744                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2745                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2746                 metatask->taskinfo.bbrread.len = bbr_info->len;
2747
2748                 cfi_action(metatask);
2749
2750                 mtx_lock(&bbr_mtx);
2751                 while (fe_bbr_info.wakeup_done == 0)
2752                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2753                 mtx_unlock(&bbr_mtx);
2754
2755                 bbr_info->status = metatask->status;
2756                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2757                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2758                 memcpy(&bbr_info->sense_data,
2759                        &metatask->taskinfo.bbrread.sense_data,
2760                        ctl_min(sizeof(bbr_info->sense_data),
2761                                sizeof(metatask->taskinfo.bbrread.sense_data)));
2762
2763                 cfi_free_metatask(metatask);
2764
2765                 mtx_destroy(&bbr_mtx);
2766                 cv_destroy(&fe_bbr_info.sem);
2767
2768                 break;
2769         }
2770         case CTL_DELAY_IO: {
2771                 struct ctl_io_delay_info *delay_info;
2772 #ifdef CTL_IO_DELAY
2773                 struct ctl_lun *lun;
2774 #endif /* CTL_IO_DELAY */
2775
2776                 delay_info = (struct ctl_io_delay_info *)addr;
2777
2778 #ifdef CTL_IO_DELAY
2779                 mtx_lock(&softc->ctl_lock);
2780
2781                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2782                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2783                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2784                 } else {
2785                         lun = softc->ctl_luns[delay_info->lun_id];
2786                         mtx_lock(&lun->lun_lock);
2787
2788                         delay_info->status = CTL_DELAY_STATUS_OK;
2789
2790                         switch (delay_info->delay_type) {
2791                         case CTL_DELAY_TYPE_CONT:
2792                                 break;
2793                         case CTL_DELAY_TYPE_ONESHOT:
2794                                 break;
2795                         default:
2796                                 delay_info->status =
2797                                         CTL_DELAY_STATUS_INVALID_TYPE;
2798                                 break;
2799                         }
2800
2801                         switch (delay_info->delay_loc) {
2802                         case CTL_DELAY_LOC_DATAMOVE:
2803                                 lun->delay_info.datamove_type =
2804                                         delay_info->delay_type;
2805                                 lun->delay_info.datamove_delay =
2806                                         delay_info->delay_secs;
2807                                 break;
2808                         case CTL_DELAY_LOC_DONE:
2809                                 lun->delay_info.done_type =
2810                                         delay_info->delay_type;
2811                                 lun->delay_info.done_delay =
2812                                         delay_info->delay_secs;
2813                                 break;
2814                         default:
2815                                 delay_info->status =
2816                                         CTL_DELAY_STATUS_INVALID_LOC;
2817                                 break;
2818                         }
2819                         mtx_unlock(&lun->lun_lock);
2820                 }
2821
2822                 mtx_unlock(&softc->ctl_lock);
2823 #else
2824                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2825 #endif /* CTL_IO_DELAY */
2826                 break;
2827         }
2828         case CTL_REALSYNC_SET: {
2829                 int *syncstate;
2830
2831                 syncstate = (int *)addr;
2832
2833                 mtx_lock(&softc->ctl_lock);
2834                 switch (*syncstate) {
2835                 case 0:
2836                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2837                         break;
2838                 case 1:
2839                         softc->flags |= CTL_FLAG_REAL_SYNC;
2840                         break;
2841                 default:
2842                         retval = EINVAL;
2843                         break;
2844                 }
2845                 mtx_unlock(&softc->ctl_lock);
2846                 break;
2847         }
2848         case CTL_REALSYNC_GET: {
2849                 int *syncstate;
2850
2851                 syncstate = (int*)addr;
2852
2853                 mtx_lock(&softc->ctl_lock);
2854                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2855                         *syncstate = 1;
2856                 else
2857                         *syncstate = 0;
2858                 mtx_unlock(&softc->ctl_lock);
2859
2860                 break;
2861         }
2862         case CTL_SETSYNC:
2863         case CTL_GETSYNC: {
2864                 struct ctl_sync_info *sync_info;
2865                 struct ctl_lun *lun;
2866
2867                 sync_info = (struct ctl_sync_info *)addr;
2868
2869                 mtx_lock(&softc->ctl_lock);
2870                 lun = softc->ctl_luns[sync_info->lun_id];
2871                 if (lun == NULL) {
2872                         mtx_unlock(&softc->ctl_lock);
2873                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2874                 }
2875                 /*
2876                  * Get or set the sync interval.  We're not bounds checking
2877                  * in the set case, hopefully the user won't do something
2878                  * silly.
2879                  */
2880                 mtx_lock(&lun->lun_lock);
2881                 mtx_unlock(&softc->ctl_lock);
2882                 if (cmd == CTL_GETSYNC)
2883                         sync_info->sync_interval = lun->sync_interval;
2884                 else
2885                         lun->sync_interval = sync_info->sync_interval;
2886                 mtx_unlock(&lun->lun_lock);
2887
2888                 sync_info->status = CTL_GS_SYNC_OK;
2889
2890                 break;
2891         }
2892         case CTL_GETSTATS: {
2893                 struct ctl_stats *stats;
2894                 struct ctl_lun *lun;
2895                 int i;
2896
2897                 stats = (struct ctl_stats *)addr;
2898
2899                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2900                      stats->alloc_len) {
2901                         stats->status = CTL_SS_NEED_MORE_SPACE;
2902                         stats->num_luns = softc->num_luns;
2903                         break;
2904                 }
2905                 /*
2906                  * XXX KDM no locking here.  If the LUN list changes,
2907                  * things can blow up.
2908                  */
2909                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2910                      i++, lun = STAILQ_NEXT(lun, links)) {
2911                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2912                                          sizeof(lun->stats));
2913                         if (retval != 0)
2914                                 break;
2915                 }
2916                 stats->num_luns = softc->num_luns;
2917                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2918                                  softc->num_luns;
2919                 stats->status = CTL_SS_OK;
2920 #ifdef CTL_TIME_IO
2921                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2922 #else
2923                 stats->flags = CTL_STATS_FLAG_NONE;
2924 #endif
2925                 getnanouptime(&stats->timestamp);
2926                 break;
2927         }
2928         case CTL_ERROR_INJECT: {
2929                 struct ctl_error_desc *err_desc, *new_err_desc;
2930                 struct ctl_lun *lun;
2931
2932                 err_desc = (struct ctl_error_desc *)addr;
2933
2934                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2935                                       M_WAITOK | M_ZERO);
2936                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2937
2938                 mtx_lock(&softc->ctl_lock);
2939                 lun = softc->ctl_luns[err_desc->lun_id];
2940                 if (lun == NULL) {
2941                         mtx_unlock(&softc->ctl_lock);
2942                         free(new_err_desc, M_CTL);
2943                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2944                                __func__, (uintmax_t)err_desc->lun_id);
2945                         retval = EINVAL;
2946                         break;
2947                 }
2948                 mtx_lock(&lun->lun_lock);
2949                 mtx_unlock(&softc->ctl_lock);
2950
2951                 /*
2952                  * We could do some checking here to verify the validity
2953                  * of the request, but given the complexity of error
2954                  * injection requests, the checking logic would be fairly
2955                  * complex.
2956                  *
2957                  * For now, if the request is invalid, it just won't get
2958                  * executed and might get deleted.
2959                  */
2960                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2961
2962                 /*
2963                  * XXX KDM check to make sure the serial number is unique,
2964                  * in case we somehow manage to wrap.  That shouldn't
2965                  * happen for a very long time, but it's the right thing to
2966                  * do.
2967                  */
2968                 new_err_desc->serial = lun->error_serial;
2969                 err_desc->serial = lun->error_serial;
2970                 lun->error_serial++;
2971
2972                 mtx_unlock(&lun->lun_lock);
2973                 break;
2974         }
2975         case CTL_ERROR_INJECT_DELETE: {
2976                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2977                 struct ctl_lun *lun;
2978                 int delete_done;
2979
2980                 delete_desc = (struct ctl_error_desc *)addr;
2981                 delete_done = 0;
2982
2983                 mtx_lock(&softc->ctl_lock);
2984                 lun = softc->ctl_luns[delete_desc->lun_id];
2985                 if (lun == NULL) {
2986                         mtx_unlock(&softc->ctl_lock);
2987                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2988                                __func__, (uintmax_t)delete_desc->lun_id);
2989                         retval = EINVAL;
2990                         break;
2991                 }
2992                 mtx_lock(&lun->lun_lock);
2993                 mtx_unlock(&softc->ctl_lock);
2994                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2995                         if (desc->serial != delete_desc->serial)
2996                                 continue;
2997
2998                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2999                                       links);
3000                         free(desc, M_CTL);
3001                         delete_done = 1;
3002                 }
3003                 mtx_unlock(&lun->lun_lock);
3004                 if (delete_done == 0) {
3005                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3006                                "error serial %ju on LUN %u\n", __func__, 
3007                                delete_desc->serial, delete_desc->lun_id);
3008                         retval = EINVAL;
3009                         break;
3010                 }
3011                 break;
3012         }
3013         case CTL_DUMP_STRUCTS: {
3014                 int i, j, k, idx;
3015                 struct ctl_port *port;
3016                 struct ctl_frontend *fe;
3017
3018                 mtx_lock(&softc->ctl_lock);
3019                 printf("CTL Persistent Reservation information start:\n");
3020                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3021                         struct ctl_lun *lun;
3022
3023                         lun = softc->ctl_luns[i];
3024
3025                         if ((lun == NULL)
3026                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3027                                 continue;
3028
3029                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3030                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3031                                         idx = j * CTL_MAX_INIT_PER_PORT + k;
3032                                         if (lun->pr_keys[idx] == 0)
3033                                                 continue;
3034                                         printf("  LUN %d port %d iid %d key "
3035                                                "%#jx\n", i, j, k,
3036                                                (uintmax_t)lun->pr_keys[idx]);
3037                                 }
3038                         }
3039                 }
3040                 printf("CTL Persistent Reservation information end\n");
3041                 printf("CTL Ports:\n");
3042                 STAILQ_FOREACH(port, &softc->port_list, links) {
3043                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3044                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3045                                port->frontend->name, port->port_type,
3046                                port->physical_port, port->virtual_port,
3047                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3048                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3049                                 if (port->wwpn_iid[j].in_use == 0 &&
3050                                     port->wwpn_iid[j].wwpn == 0 &&
3051                                     port->wwpn_iid[j].name == NULL)
3052                                         continue;
3053
3054                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3055                                     j, port->wwpn_iid[j].in_use,
3056                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3057                                     port->wwpn_iid[j].name);
3058                         }
3059                 }
3060                 printf("CTL Port information end\n");
3061                 mtx_unlock(&softc->ctl_lock);
3062                 /*
3063                  * XXX KDM calling this without a lock.  We'd likely want
3064                  * to drop the lock before calling the frontend's dump
3065                  * routine anyway.
3066                  */
3067                 printf("CTL Frontends:\n");
3068                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3069                         printf("  Frontend '%s'\n", fe->name);
3070                         if (fe->fe_dump != NULL)
3071                                 fe->fe_dump();
3072                 }
3073                 printf("CTL Frontend information end\n");
3074                 break;
3075         }
3076         case CTL_LUN_REQ: {
3077                 struct ctl_lun_req *lun_req;
3078                 struct ctl_backend_driver *backend;
3079
3080                 lun_req = (struct ctl_lun_req *)addr;
3081
3082                 backend = ctl_backend_find(lun_req->backend);
3083                 if (backend == NULL) {
3084                         lun_req->status = CTL_LUN_ERROR;
3085                         snprintf(lun_req->error_str,
3086                                  sizeof(lun_req->error_str),
3087                                  "Backend \"%s\" not found.",
3088                                  lun_req->backend);
3089                         break;
3090                 }
3091                 if (lun_req->num_be_args > 0) {
3092                         lun_req->kern_be_args = ctl_copyin_args(
3093                                 lun_req->num_be_args,
3094                                 lun_req->be_args,
3095                                 lun_req->error_str,
3096                                 sizeof(lun_req->error_str));
3097                         if (lun_req->kern_be_args == NULL) {
3098                                 lun_req->status = CTL_LUN_ERROR;
3099                                 break;
3100                         }
3101                 }
3102
3103                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3104
3105                 if (lun_req->num_be_args > 0) {
3106                         ctl_copyout_args(lun_req->num_be_args,
3107                                       lun_req->kern_be_args);
3108                         ctl_free_args(lun_req->num_be_args,
3109                                       lun_req->kern_be_args);
3110                 }
3111                 break;
3112         }
3113         case CTL_LUN_LIST: {
3114                 struct sbuf *sb;
3115                 struct ctl_lun *lun;
3116                 struct ctl_lun_list *list;
3117                 struct ctl_option *opt;
3118
3119                 list = (struct ctl_lun_list *)addr;
3120
3121                 /*
3122                  * Allocate a fixed length sbuf here, based on the length
3123                  * of the user's buffer.  We could allocate an auto-extending
3124                  * buffer, and then tell the user how much larger our
3125                  * amount of data is than his buffer, but that presents
3126                  * some problems:
3127                  *
3128                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3129                  *     we can't hold a lock while calling them with an
3130                  *     auto-extending buffer.
3131                  *
3132                  * 2.  There is not currently a LUN reference counting
3133                  *     mechanism, outside of outstanding transactions on
3134                  *     the LUN's OOA queue.  So a LUN could go away on us
3135                  *     while we're getting the LUN number, backend-specific
3136                  *     information, etc.  Thus, given the way things
3137                  *     currently work, we need to hold the CTL lock while
3138                  *     grabbing LUN information.
3139                  *
3140                  * So, from the user's standpoint, the best thing to do is
3141                  * allocate what he thinks is a reasonable buffer length,
3142                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3143                  * double the buffer length and try again.  (And repeat
3144                  * that until he succeeds.)
3145                  */
3146                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3147                 if (sb == NULL) {
3148                         list->status = CTL_LUN_LIST_ERROR;
3149                         snprintf(list->error_str, sizeof(list->error_str),
3150                                  "Unable to allocate %d bytes for LUN list",
3151                                  list->alloc_len);
3152                         break;
3153                 }
3154
3155                 sbuf_printf(sb, "<ctllunlist>\n");
3156
3157                 mtx_lock(&softc->ctl_lock);
3158                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3159                         mtx_lock(&lun->lun_lock);
3160                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3161                                              (uintmax_t)lun->lun);
3162
3163                         /*
3164                          * Bail out as soon as we see that we've overfilled
3165                          * the buffer.
3166                          */
3167                         if (retval != 0)
3168                                 break;
3169
3170                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3171                                              "</backend_type>\n",
3172                                              (lun->backend == NULL) ?  "none" :
3173                                              lun->backend->name);
3174
3175                         if (retval != 0)
3176                                 break;
3177
3178                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3179                                              lun->be_lun->lun_type);
3180
3181                         if (retval != 0)
3182                                 break;
3183
3184                         if (lun->backend == NULL) {
3185                                 retval = sbuf_printf(sb, "</lun>\n");
3186                                 if (retval != 0)
3187                                         break;
3188                                 continue;
3189                         }
3190
3191                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3192                                              (lun->be_lun->maxlba > 0) ?
3193                                              lun->be_lun->maxlba + 1 : 0);
3194
3195                         if (retval != 0)
3196                                 break;
3197
3198                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3199                                              lun->be_lun->blocksize);
3200
3201                         if (retval != 0)
3202                                 break;
3203
3204                         retval = sbuf_printf(sb, "\t<serial_number>");
3205
3206                         if (retval != 0)
3207                                 break;
3208
3209                         retval = ctl_sbuf_printf_esc(sb,
3210                                                      lun->be_lun->serial_num);
3211
3212                         if (retval != 0)
3213                                 break;
3214
3215                         retval = sbuf_printf(sb, "</serial_number>\n");
3216                 
3217                         if (retval != 0)
3218                                 break;
3219
3220                         retval = sbuf_printf(sb, "\t<device_id>");
3221
3222                         if (retval != 0)
3223                                 break;
3224
3225                         retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3226
3227                         if (retval != 0)
3228                                 break;
3229
3230                         retval = sbuf_printf(sb, "</device_id>\n");
3231
3232                         if (retval != 0)
3233                                 break;
3234
3235                         if (lun->backend->lun_info != NULL) {
3236                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3237                                 if (retval != 0)
3238                                         break;
3239                         }
3240                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3241                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3242                                     opt->name, opt->value, opt->name);
3243                                 if (retval != 0)
3244                                         break;
3245                         }
3246
3247                         retval = sbuf_printf(sb, "</lun>\n");
3248
3249                         if (retval != 0)
3250                                 break;
3251                         mtx_unlock(&lun->lun_lock);
3252                 }
3253                 if (lun != NULL)
3254                         mtx_unlock(&lun->lun_lock);
3255                 mtx_unlock(&softc->ctl_lock);
3256
3257                 if ((retval != 0)
3258                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3259                         retval = 0;
3260                         sbuf_delete(sb);
3261                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3262                         snprintf(list->error_str, sizeof(list->error_str),
3263                                  "Out of space, %d bytes is too small",
3264                                  list->alloc_len);
3265                         break;
3266                 }
3267
3268                 sbuf_finish(sb);
3269
3270                 retval = copyout(sbuf_data(sb), list->lun_xml,
3271                                  sbuf_len(sb) + 1);
3272
3273                 list->fill_len = sbuf_len(sb) + 1;
3274                 list->status = CTL_LUN_LIST_OK;
3275                 sbuf_delete(sb);
3276                 break;
3277         }
3278         case CTL_ISCSI: {
3279                 struct ctl_iscsi *ci;
3280                 struct ctl_frontend *fe;
3281
3282                 ci = (struct ctl_iscsi *)addr;
3283
3284                 fe = ctl_frontend_find("iscsi");
3285                 if (fe == NULL) {
3286                         ci->status = CTL_ISCSI_ERROR;
3287                         snprintf(ci->error_str, sizeof(ci->error_str),
3288                             "Frontend \"iscsi\" not found.");
3289                         break;
3290                 }
3291
3292                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3293                 break;
3294         }
3295         case CTL_PORT_REQ: {
3296                 struct ctl_req *req;
3297                 struct ctl_frontend *fe;
3298
3299                 req = (struct ctl_req *)addr;
3300
3301                 fe = ctl_frontend_find(req->driver);
3302                 if (fe == NULL) {
3303                         req->status = CTL_LUN_ERROR;
3304                         snprintf(req->error_str, sizeof(req->error_str),
3305                             "Frontend \"%s\" not found.", req->driver);
3306                         break;
3307                 }
3308                 if (req->num_args > 0) {
3309                         req->kern_args = ctl_copyin_args(req->num_args,
3310                             req->args, req->error_str, sizeof(req->error_str));
3311                         if (req->kern_args == NULL) {
3312                                 req->status = CTL_LUN_ERROR;
3313                                 break;
3314                         }
3315                 }
3316
3317                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3318
3319                 if (req->num_args > 0) {
3320                         ctl_copyout_args(req->num_args, req->kern_args);
3321                         ctl_free_args(req->num_args, req->kern_args);
3322                 }
3323                 break;
3324         }
3325         case CTL_PORT_LIST: {
3326                 struct sbuf *sb;
3327                 struct ctl_port *port;
3328                 struct ctl_lun_list *list;
3329                 struct ctl_option *opt;
3330                 int j;
3331
3332                 list = (struct ctl_lun_list *)addr;
3333
3334                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3335                 if (sb == NULL) {
3336                         list->status = CTL_LUN_LIST_ERROR;
3337                         snprintf(list->error_str, sizeof(list->error_str),
3338                                  "Unable to allocate %d bytes for LUN list",
3339                                  list->alloc_len);
3340                         break;
3341                 }
3342
3343                 sbuf_printf(sb, "<ctlportlist>\n");
3344
3345                 mtx_lock(&softc->ctl_lock);
3346                 STAILQ_FOREACH(port, &softc->port_list, links) {
3347                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3348                                              (uintmax_t)port->targ_port);
3349
3350                         /*
3351                          * Bail out as soon as we see that we've overfilled
3352                          * the buffer.
3353                          */
3354                         if (retval != 0)
3355                                 break;
3356
3357                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3358                             "</frontend_type>\n", port->frontend->name);
3359                         if (retval != 0)
3360                                 break;
3361
3362                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3363                                              port->port_type);
3364                         if (retval != 0)
3365                                 break;
3366
3367                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3368                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3369                         if (retval != 0)
3370                                 break;
3371
3372                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3373                             port->port_name);
3374                         if (retval != 0)
3375                                 break;
3376
3377                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3378                             port->physical_port);
3379                         if (retval != 0)
3380                                 break;
3381
3382                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3383                             port->virtual_port);
3384                         if (retval != 0)
3385                                 break;
3386
3387                         if (port->target_devid != NULL) {
3388                                 sbuf_printf(sb, "\t<target>");
3389                                 ctl_id_sbuf(port->target_devid, sb);
3390                                 sbuf_printf(sb, "</target>\n");
3391                         }
3392
3393                         if (port->port_devid != NULL) {
3394                                 sbuf_printf(sb, "\t<port>");
3395                                 ctl_id_sbuf(port->port_devid, sb);
3396                                 sbuf_printf(sb, "</port>\n");
3397                         }
3398
3399                         if (port->port_info != NULL) {
3400                                 retval = port->port_info(port->onoff_arg, sb);
3401                                 if (retval != 0)
3402                                         break;
3403                         }
3404                         STAILQ_FOREACH(opt, &port->options, links) {
3405                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3406                                     opt->name, opt->value, opt->name);
3407                                 if (retval != 0)
3408                                         break;
3409                         }
3410
3411                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3412                                 if (port->wwpn_iid[j].in_use == 0 ||
3413                                     (port->wwpn_iid[j].wwpn == 0 &&
3414                                      port->wwpn_iid[j].name == NULL))
3415                                         continue;
3416
3417                                 if (port->wwpn_iid[j].name != NULL)
3418                                         retval = sbuf_printf(sb,
3419                                             "\t<initiator>%u %s</initiator>\n",
3420                                             j, port->wwpn_iid[j].name);
3421                                 else
3422                                         retval = sbuf_printf(sb,
3423                                             "\t<initiator>%u naa.%08jx</initiator>\n",
3424                                             j, port->wwpn_iid[j].wwpn);
3425                                 if (retval != 0)
3426                                         break;
3427                         }
3428                         if (retval != 0)
3429                                 break;
3430
3431                         retval = sbuf_printf(sb, "</targ_port>\n");
3432                         if (retval != 0)
3433                                 break;
3434                 }
3435                 mtx_unlock(&softc->ctl_lock);
3436
3437                 if ((retval != 0)
3438                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3439                         retval = 0;
3440                         sbuf_delete(sb);
3441                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3442                         snprintf(list->error_str, sizeof(list->error_str),
3443                                  "Out of space, %d bytes is too small",
3444                                  list->alloc_len);
3445                         break;
3446                 }
3447
3448                 sbuf_finish(sb);
3449
3450                 retval = copyout(sbuf_data(sb), list->lun_xml,
3451                                  sbuf_len(sb) + 1);
3452
3453                 list->fill_len = sbuf_len(sb) + 1;
3454                 list->status = CTL_LUN_LIST_OK;
3455                 sbuf_delete(sb);
3456                 break;
3457         }
3458         default: {
3459                 /* XXX KDM should we fix this? */
3460 #if 0
3461                 struct ctl_backend_driver *backend;
3462                 unsigned int type;
3463                 int found;
3464
3465                 found = 0;
3466
3467                 /*
3468                  * We encode the backend type as the ioctl type for backend
3469                  * ioctls.  So parse it out here, and then search for a
3470                  * backend of this type.
3471                  */
3472                 type = _IOC_TYPE(cmd);
3473
3474                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3475                         if (backend->type == type) {
3476                                 found = 1;
3477                                 break;
3478                         }
3479                 }
3480                 if (found == 0) {
3481                         printf("ctl: unknown ioctl command %#lx or backend "
3482                                "%d\n", cmd, type);
3483                         retval = EINVAL;
3484                         break;
3485                 }
3486                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3487 #endif
3488                 retval = ENOTTY;
3489                 break;
3490         }
3491         }
3492         return (retval);
3493 }
3494
3495 uint32_t
3496 ctl_get_initindex(struct ctl_nexus *nexus)
3497 {
3498         if (nexus->targ_port < CTL_MAX_PORTS)
3499                 return (nexus->initid.id +
3500                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3501         else
3502                 return (nexus->initid.id +
3503                        ((nexus->targ_port - CTL_MAX_PORTS) *
3504                         CTL_MAX_INIT_PER_PORT));
3505 }
3506
3507 uint32_t
3508 ctl_get_resindex(struct ctl_nexus *nexus)
3509 {
3510         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3511 }
3512
3513 uint32_t
3514 ctl_port_idx(int port_num)
3515 {
3516         if (port_num < CTL_MAX_PORTS)
3517                 return(port_num);
3518         else
3519                 return(port_num - CTL_MAX_PORTS);
3520 }
3521
3522 static uint32_t
3523 ctl_map_lun(int port_num, uint32_t lun_id)
3524 {
3525         struct ctl_port *port;
3526
3527         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3528         if (port == NULL)
3529                 return (UINT32_MAX);
3530         if (port->lun_map == NULL)
3531                 return (lun_id);
3532         return (port->lun_map(port->targ_lun_arg, lun_id));
3533 }
3534
3535 static uint32_t
3536 ctl_map_lun_back(int port_num, uint32_t lun_id)
3537 {
3538         struct ctl_port *port;
3539         uint32_t i;
3540
3541         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3542         if (port->lun_map == NULL)
3543                 return (lun_id);
3544         for (i = 0; i < CTL_MAX_LUNS; i++) {
3545                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3546                         return (i);
3547         }
3548         return (UINT32_MAX);
3549 }
3550
3551 /*
3552  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3553  * that are a power of 2.
3554  */
3555 int
3556 ctl_ffz(uint32_t *mask, uint32_t size)
3557 {
3558         uint32_t num_chunks, num_pieces;
3559         int i, j;
3560
3561         num_chunks = (size >> 5);
3562         if (num_chunks == 0)
3563                 num_chunks++;
3564         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3565
3566         for (i = 0; i < num_chunks; i++) {
3567                 for (j = 0; j < num_pieces; j++) {
3568                         if ((mask[i] & (1 << j)) == 0)
3569                                 return ((i << 5) + j);
3570                 }
3571         }
3572
3573         return (-1);
3574 }
3575
3576 int
3577 ctl_set_mask(uint32_t *mask, uint32_t bit)
3578 {
3579         uint32_t chunk, piece;
3580
3581         chunk = bit >> 5;
3582         piece = bit % (sizeof(uint32_t) * 8);
3583
3584         if ((mask[chunk] & (1 << piece)) != 0)
3585                 return (-1);
3586         else
3587                 mask[chunk] |= (1 << piece);
3588
3589         return (0);
3590 }
3591
3592 int
3593 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3594 {
3595         uint32_t chunk, piece;
3596
3597         chunk = bit >> 5;
3598         piece = bit % (sizeof(uint32_t) * 8);
3599
3600         if ((mask[chunk] & (1 << piece)) == 0)
3601                 return (-1);
3602         else
3603                 mask[chunk] &= ~(1 << piece);
3604
3605         return (0);
3606 }
3607
3608 int
3609 ctl_is_set(uint32_t *mask, uint32_t bit)
3610 {
3611         uint32_t chunk, piece;
3612
3613         chunk = bit >> 5;
3614         piece = bit % (sizeof(uint32_t) * 8);
3615
3616         if ((mask[chunk] & (1 << piece)) == 0)
3617                 return (0);
3618         else
3619                 return (1);
3620 }
3621
3622 #ifdef unused
3623 /*
3624  * The bus, target and lun are optional, they can be filled in later.
3625  * can_wait is used to determine whether we can wait on the malloc or not.
3626  */
3627 union ctl_io*
3628 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3629               uint32_t targ_lun, int can_wait)
3630 {
3631         union ctl_io *io;
3632
3633         if (can_wait)
3634                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3635         else
3636                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3637
3638         if (io != NULL) {
3639                 io->io_hdr.io_type = io_type;
3640                 io->io_hdr.targ_port = targ_port;
3641                 /*
3642                  * XXX KDM this needs to change/go away.  We need to move
3643                  * to a preallocated pool of ctl_scsiio structures.
3644                  */
3645                 io->io_hdr.nexus.targ_target.id = targ_target;
3646                 io->io_hdr.nexus.targ_lun = targ_lun;
3647         }
3648
3649         return (io);
3650 }
3651
3652 void
3653 ctl_kfree_io(union ctl_io *io)
3654 {
3655         free(io, M_CTL);
3656 }
3657 #endif /* unused */
3658
3659 /*
3660  * ctl_softc, pool_type, total_ctl_io are passed in.
3661  * npool is passed out.
3662  */
3663 int
3664 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3665                 uint32_t total_ctl_io, struct ctl_io_pool **npool)
3666 {
3667         uint32_t i;
3668         union ctl_io *cur_io, *next_io;
3669         struct ctl_io_pool *pool;
3670         int retval;
3671
3672         retval = 0;
3673
3674         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3675                                             M_NOWAIT | M_ZERO);
3676         if (pool == NULL) {
3677                 retval = ENOMEM;
3678                 goto bailout;
3679         }
3680
3681         pool->type = pool_type;
3682         pool->ctl_softc = ctl_softc;
3683
3684         mtx_lock(&ctl_softc->pool_lock);
3685         pool->id = ctl_softc->cur_pool_id++;
3686         mtx_unlock(&ctl_softc->pool_lock);
3687
3688         pool->flags = CTL_POOL_FLAG_NONE;
3689         pool->refcount = 1;             /* Reference for validity. */
3690         STAILQ_INIT(&pool->free_queue);
3691
3692         /*
3693          * XXX KDM other options here:
3694          * - allocate a page at a time
3695          * - allocate one big chunk of memory.
3696          * Page allocation might work well, but would take a little more
3697          * tracking.
3698          */
3699         for (i = 0; i < total_ctl_io; i++) {
3700                 cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3701                                                 M_NOWAIT);
3702                 if (cur_io == NULL) {
3703                         retval = ENOMEM;
3704                         break;
3705                 }
3706                 cur_io->io_hdr.pool = pool;
3707                 STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3708                 pool->total_ctl_io++;
3709                 pool->free_ctl_io++;
3710         }
3711
3712         if (retval != 0) {
3713                 for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3714                      cur_io != NULL; cur_io = next_io) {
3715                         next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3716                                                               links);
3717                         STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3718                                       ctl_io_hdr, links);
3719                         free(cur_io, M_CTLIO);
3720                 }
3721
3722                 free(pool, M_CTL);
3723                 goto bailout;
3724         }
3725         mtx_lock(&ctl_softc->pool_lock);
3726         ctl_softc->num_pools++;
3727         STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3728         /*
3729          * Increment our usage count if this is an external consumer, so we
3730          * can't get unloaded until the external consumer (most likely a
3731          * FETD) unloads and frees his pool.
3732          *
3733          * XXX KDM will this increment the caller's module use count, or
3734          * mine?
3735          */
3736 #if 0
3737         if ((pool_type != CTL_POOL_EMERGENCY)
3738          && (pool_type != CTL_POOL_INTERNAL)
3739          && (pool_type != CTL_POOL_4OTHERSC))
3740                 MOD_INC_USE_COUNT;
3741 #endif
3742
3743         mtx_unlock(&ctl_softc->pool_lock);
3744
3745         *npool = pool;
3746
3747 bailout:
3748
3749         return (retval);
3750 }
3751
3752 static int
3753 ctl_pool_acquire(struct ctl_io_pool *pool)
3754 {
3755
3756         mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3757
3758         if (pool->flags & CTL_POOL_FLAG_INVALID)
3759                 return (EINVAL);
3760
3761         pool->refcount++;
3762
3763         return (0);
3764 }
3765
3766 static void
3767 ctl_pool_release(struct ctl_io_pool *pool)
3768 {
3769         struct ctl_softc *ctl_softc = pool->ctl_softc;
3770         union ctl_io *io;
3771
3772         mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3773
3774         if (--pool->refcount != 0)
3775                 return;
3776
3777         while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3778                 STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3779                               links);
3780                 free(io, M_CTLIO);
3781         }
3782
3783         STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3784         ctl_softc->num_pools--;
3785
3786         /*
3787          * XXX KDM will this decrement the caller's usage count or mine?
3788          */
3789 #if 0
3790         if ((pool->type != CTL_POOL_EMERGENCY)
3791          && (pool->type != CTL_POOL_INTERNAL)
3792          && (pool->type != CTL_POOL_4OTHERSC))
3793                 MOD_DEC_USE_COUNT;
3794 #endif
3795
3796         free(pool, M_CTL);
3797 }
3798
3799 void
3800 ctl_pool_free(struct ctl_io_pool *pool)
3801 {
3802         struct ctl_softc *ctl_softc;
3803
3804         if (pool == NULL)
3805                 return;
3806
3807         ctl_softc = pool->ctl_softc;
3808         mtx_lock(&ctl_softc->pool_lock);
3809         pool->flags |= CTL_POOL_FLAG_INVALID;
3810         ctl_pool_release(pool);
3811         mtx_unlock(&ctl_softc->pool_lock);
3812 }
3813
3814 /*
3815  * This routine does not block (except for spinlocks of course).
3816  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3817  * possible.
3818  */
3819 union ctl_io *
3820 ctl_alloc_io(void *pool_ref)
3821 {
3822         union ctl_io *io;
3823         struct ctl_softc *ctl_softc;
3824         struct ctl_io_pool *pool, *npool;
3825         struct ctl_io_pool *emergency_pool;
3826
3827         pool = (struct ctl_io_pool *)pool_ref;
3828
3829         if (pool == NULL) {
3830                 printf("%s: pool is NULL\n", __func__);
3831                 return (NULL);
3832         }
3833
3834         emergency_pool = NULL;
3835
3836         ctl_softc = pool->ctl_softc;
3837
3838         mtx_lock(&ctl_softc->pool_lock);
3839         /*
3840          * First, try to get the io structure from the user's pool.
3841          */
3842         if (ctl_pool_acquire(pool) == 0) {
3843                 io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3844                 if (io != NULL) {
3845                         STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3846                         pool->total_allocated++;
3847                         pool->free_ctl_io--;
3848                         mtx_unlock(&ctl_softc->pool_lock);
3849                         return (io);
3850                 } else
3851                         ctl_pool_release(pool);
3852         }
3853         /*
3854          * If he doesn't have any io structures left, search for an
3855          * emergency pool and grab one from there.
3856          */
3857         STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3858                 if (npool->type != CTL_POOL_EMERGENCY)
3859                         continue;
3860
3861                 if (ctl_pool_acquire(npool) != 0)
3862                         continue;
3863
3864                 emergency_pool = npool;
3865
3866                 io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3867                 if (io != NULL) {
3868                         STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3869                         npool->total_allocated++;
3870                         npool->free_ctl_io--;
3871                         mtx_unlock(&ctl_softc->pool_lock);
3872                         return (io);
3873                 } else
3874                         ctl_pool_release(npool);
3875         }
3876
3877         /* Drop the spinlock before we malloc */
3878         mtx_unlock(&ctl_softc->pool_lock);
3879
3880         /*
3881          * The emergency pool (if it exists) didn't have one, so try an
3882          * atomic (i.e. nonblocking) malloc and see if we get lucky.
3883          */
3884         io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3885         if (io != NULL) {
3886                 /*
3887                  * If the emergency pool exists but is empty, add this
3888                  * ctl_io to its list when it gets freed.
3889                  */
3890                 if (emergency_pool != NULL) {
3891                         mtx_lock(&ctl_softc->pool_lock);
3892                         if (ctl_pool_acquire(emergency_pool) == 0) {
3893                                 io->io_hdr.pool = emergency_pool;
3894                                 emergency_pool->total_ctl_io++;
3895                                 /*
3896                                  * Need to bump this, otherwise
3897                                  * total_allocated and total_freed won't
3898                                  * match when we no longer have anything
3899                                  * outstanding.
3900                                  */
3901                                 emergency_pool->total_allocated++;
3902                         }
3903                         mtx_unlock(&ctl_softc->pool_lock);
3904                 } else
3905                         io->io_hdr.pool = NULL;
3906         }
3907
3908         return (io);
3909 }
3910
3911 void
3912 ctl_free_io(union ctl_io *io)
3913 {
3914         if (io == NULL)
3915                 return;
3916
3917         /*
3918          * If this ctl_io has a pool, return it to that pool.
3919          */
3920         if (io->io_hdr.pool != NULL) {
3921                 struct ctl_io_pool *pool;
3922
3923                 pool = (struct ctl_io_pool *)io->io_hdr.pool;
3924                 mtx_lock(&pool->ctl_softc->pool_lock);
3925                 io->io_hdr.io_type = 0xff;
3926                 STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3927                 pool->total_freed++;
3928                 pool->free_ctl_io++;
3929                 ctl_pool_release(pool);
3930                 mtx_unlock(&pool->ctl_softc->pool_lock);
3931         } else {
3932                 /*
3933                  * Otherwise, just free it.  We probably malloced it and
3934                  * the emergency pool wasn't available.
3935                  */
3936                 free(io, M_CTLIO);
3937         }
3938
3939 }
3940
3941 void
3942 ctl_zero_io(union ctl_io *io)
3943 {
3944         void *pool_ref;
3945
3946         if (io == NULL)
3947                 return;
3948
3949         /*
3950          * May need to preserve linked list pointers at some point too.
3951          */
3952         pool_ref = io->io_hdr.pool;
3953
3954         memset(io, 0, sizeof(*io));
3955
3956         io->io_hdr.pool = pool_ref;
3957 }
3958
3959 /*
3960  * This routine is currently used for internal copies of ctl_ios that need
3961  * to persist for some reason after we've already returned status to the
3962  * FETD.  (Thus the flag set.)
3963  *
3964  * XXX XXX
3965  * Note that this makes a blind copy of all fields in the ctl_io, except
3966  * for the pool reference.  This includes any memory that has been
3967  * allocated!  That memory will no longer be valid after done has been
3968  * called, so this would be VERY DANGEROUS for command that actually does
3969  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3970  * start and stop commands, which don't transfer any data, so this is not a
3971  * problem.  If it is used for anything else, the caller would also need to
3972  * allocate data buffer space and this routine would need to be modified to
3973  * copy the data buffer(s) as well.
3974  */
3975 void
3976 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3977 {
3978         void *pool_ref;
3979
3980         if ((src == NULL)
3981          || (dest == NULL))
3982                 return;
3983
3984         /*
3985          * May need to preserve linked list pointers at some point too.
3986          */
3987         pool_ref = dest->io_hdr.pool;
3988
3989         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3990
3991         dest->io_hdr.pool = pool_ref;
3992         /*
3993          * We need to know that this is an internal copy, and doesn't need
3994          * to get passed back to the FETD that allocated it.
3995          */
3996         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3997 }
3998
3999 #ifdef NEEDTOPORT
4000 static void
4001 ctl_update_power_subpage(struct copan_power_subpage *page)
4002 {
4003         int num_luns, num_partitions, config_type;
4004         struct ctl_softc *softc;
4005         cs_BOOL_t aor_present, shelf_50pct_power;
4006         cs_raidset_personality_t rs_type;
4007         int max_active_luns;
4008
4009         softc = control_softc;
4010
4011         /* subtract out the processor LUN */
4012         num_luns = softc->num_luns - 1;
4013         /*
4014          * Default to 7 LUNs active, which was the only number we allowed
4015          * in the past.
4016          */
4017         max_active_luns = 7;
4018
4019         num_partitions = config_GetRsPartitionInfo();
4020         config_type = config_GetConfigType();
4021         shelf_50pct_power = config_GetShelfPowerMode();
4022         aor_present = config_IsAorRsPresent();
4023
4024         rs_type = ddb_GetRsRaidType(1);
4025         if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
4026          && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
4027                 EPRINT(0, "Unsupported RS type %d!", rs_type);
4028         }
4029
4030
4031         page->total_luns = num_luns;
4032
4033         switch (config_type) {
4034         case 40:
4035                 /*
4036                  * In a 40 drive configuration, it doesn't matter what DC
4037                  * cards we have, whether we have AOR enabled or not,
4038                  * partitioning or not, or what type of RAIDset we have.
4039                  * In that scenario, we can power up every LUN we present
4040                  * to the user.
4041                  */
4042                 max_active_luns = num_luns;
4043
4044                 break;
4045         case 64:
4046                 if (shelf_50pct_power == CS_FALSE) {
4047                         /* 25% power */
4048                         if (aor_present == CS_TRUE) {
4049                                 if (rs_type ==
4050                                      CS_RAIDSET_PERSONALITY_RAID5) {
4051                                         max_active_luns = 7;
4052                                 } else if (rs_type ==
4053                                          CS_RAIDSET_PERSONALITY_RAID1){
4054                                         max_active_luns = 14;
4055                                 } else {
4056                                         /* XXX KDM now what?? */
4057                                 }
4058                         } else {
4059                                 if (rs_type ==
4060                                      CS_RAIDSET_PERSONALITY_RAID5) {
4061                                         max_active_luns = 8;
4062                                 } else if (rs_type ==
4063                                          CS_RAIDSET_PERSONALITY_RAID1){
4064                                         max_active_luns = 16;
4065                                 } else {
4066                                         /* XXX KDM now what?? */
4067                                 }
4068                         }
4069                 } else {
4070                         /* 50% power */
4071                         /*
4072                          * With 50% power in a 64 drive configuration, we
4073                          * can power all LUNs we present.
4074                          */
4075                         max_active_luns = num_luns;
4076                 }
4077                 break;
4078         case 112:
4079                 if (shelf_50pct_power == CS_FALSE) {
4080                         /* 25% power */
4081                         if (aor_present == CS_TRUE) {
4082                                 if (rs_type ==
4083                                      CS_RAIDSET_PERSONALITY_RAID5) {
4084                                         max_active_luns = 7;
4085                                 } else if (rs_type ==
4086                                          CS_RAIDSET_PERSONALITY_RAID1){
4087                                         max_active_luns = 14;
4088                                 } else {
4089                                         /* XXX KDM now what?? */
4090                                 }
4091                         } else {
4092                                 if (rs_type ==
4093                                      CS_RAIDSET_PERSONALITY_RAID5) {
4094                                         max_active_luns = 8;
4095                                 } else if (rs_type ==
4096                                          CS_RAIDSET_PERSONALITY_RAID1){
4097                                         max_active_luns = 16;
4098                                 } else {
4099                                         /* XXX KDM now what?? */
4100                                 }
4101                         }
4102                 } else {
4103                         /* 50% power */
4104                         if (aor_present == CS_TRUE) {
4105                                 if (rs_type ==
4106                                      CS_RAIDSET_PERSONALITY_RAID5) {
4107                                         max_active_luns = 14;
4108                                 } else if (rs_type ==
4109                                          CS_RAIDSET_PERSONALITY_RAID1){
4110                                         /*
4111                                          * We're assuming here that disk
4112                                          * caching is enabled, and so we're
4113                                          * able to power up half of each
4114                                          * LUN, and cache all writes.
4115                                          */
4116                                         max_active_luns = num_luns;
4117                                 } else {
4118                                         /* XXX KDM now what?? */
4119                                 }
4120                         } else {
4121                                 if (rs_type ==
4122                                      CS_RAIDSET_PERSONALITY_RAID5) {
4123                                         max_active_luns = 15;
4124                                 } else if (rs_type ==
4125                                          CS_RAIDSET_PERSONALITY_RAID1){
4126                                         max_active_luns = 30;
4127                                 } else {
4128                                         /* XXX KDM now what?? */
4129                                 }
4130                         }
4131                 }
4132                 break;
4133         default:
4134                 /*
4135                  * In this case, we have an unknown configuration, so we
4136                  * just use the default from above.
4137                  */
4138                 break;
4139         }
4140
4141         page->max_active_luns = max_active_luns;
4142 #if 0
4143         printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4144                page->total_luns, page->max_active_luns);
4145 #endif
4146 }
4147 #endif /* NEEDTOPORT */
4148
4149 /*
4150  * This routine could be used in the future to load default and/or saved
4151  * mode page parameters for a particuar lun.
4152  */
4153 static int
4154 ctl_init_page_index(struct ctl_lun *lun)
4155 {
4156         int i;
4157         struct ctl_page_index *page_index;
4158         struct ctl_softc *softc;
4159         const char *value;
4160
4161         memcpy(&lun->mode_pages.index, page_index_template,
4162                sizeof(page_index_template));
4163
4164         softc = lun->ctl_softc;
4165
4166         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4167
4168                 page_index = &lun->mode_pages.index[i];
4169                 /*
4170                  * If this is a disk-only mode page, there's no point in
4171                  * setting it up.  For some pages, we have to have some
4172                  * basic information about the disk in order to calculate the
4173                  * mode page data.
4174                  */
4175                 if ((lun->be_lun->lun_type != T_DIRECT)
4176                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4177                         continue;
4178
4179                 switch (page_index->page_code & SMPH_PC_MASK) {
4180                 case SMS_FORMAT_DEVICE_PAGE: {
4181                         struct scsi_format_page *format_page;
4182
4183                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4184                                 panic("subpage is incorrect!");
4185
4186                         /*
4187                          * Sectors per track are set above.  Bytes per
4188                          * sector need to be set here on a per-LUN basis.
4189                          */
4190                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4191                                &format_page_default,
4192                                sizeof(format_page_default));
4193                         memcpy(&lun->mode_pages.format_page[
4194                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4195                                sizeof(format_page_changeable));
4196                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4197                                &format_page_default,
4198                                sizeof(format_page_default));
4199                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4200                                &format_page_default,
4201                                sizeof(format_page_default));
4202
4203                         format_page = &lun->mode_pages.format_page[
4204                                 CTL_PAGE_CURRENT];
4205                         scsi_ulto2b(lun->be_lun->blocksize,
4206                                     format_page->bytes_per_sector);
4207
4208                         format_page = &lun->mode_pages.format_page[
4209                                 CTL_PAGE_DEFAULT];
4210                         scsi_ulto2b(lun->be_lun->blocksize,
4211                                     format_page->bytes_per_sector);
4212
4213                         format_page = &lun->mode_pages.format_page[
4214                                 CTL_PAGE_SAVED];
4215                         scsi_ulto2b(lun->be_lun->blocksize,
4216                                     format_page->bytes_per_sector);
4217
4218                         page_index->page_data =
4219                                 (uint8_t *)lun->mode_pages.format_page;
4220                         break;
4221                 }
4222                 case SMS_RIGID_DISK_PAGE: {
4223                         struct scsi_rigid_disk_page *rigid_disk_page;
4224                         uint32_t sectors_per_cylinder;
4225                         uint64_t cylinders;
4226 #ifndef __XSCALE__
4227                         int shift;
4228 #endif /* !__XSCALE__ */
4229
4230                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4231                                 panic("invalid subpage value %d",
4232                                       page_index->subpage);
4233
4234                         /*
4235                          * Rotation rate and sectors per track are set
4236                          * above.  We calculate the cylinders here based on
4237                          * capacity.  Due to the number of heads and
4238                          * sectors per track we're using, smaller arrays
4239                          * may turn out to have 0 cylinders.  Linux and
4240                          * FreeBSD don't pay attention to these mode pages
4241                          * to figure out capacity, but Solaris does.  It
4242                          * seems to deal with 0 cylinders just fine, and
4243                          * works out a fake geometry based on the capacity.
4244                          */
4245                         memcpy(&lun->mode_pages.rigid_disk_page[
4246                                CTL_PAGE_CURRENT], &rigid_disk_page_default,
4247                                sizeof(rigid_disk_page_default));
4248                         memcpy(&lun->mode_pages.rigid_disk_page[
4249                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4250                                sizeof(rigid_disk_page_changeable));
4251                         memcpy(&lun->mode_pages.rigid_disk_page[
4252                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4253                                sizeof(rigid_disk_page_default));
4254                         memcpy(&lun->mode_pages.rigid_disk_page[
4255                                CTL_PAGE_SAVED], &rigid_disk_page_default,
4256                                sizeof(rigid_disk_page_default));
4257
4258                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4259                                 CTL_DEFAULT_HEADS;
4260
4261                         /*
4262                          * The divide method here will be more accurate,
4263                          * probably, but results in floating point being
4264                          * used in the kernel on i386 (__udivdi3()).  On the
4265                          * XScale, though, __udivdi3() is implemented in
4266                          * software.
4267                          *
4268                          * The shift method for cylinder calculation is
4269                          * accurate if sectors_per_cylinder is a power of
4270                          * 2.  Otherwise it might be slightly off -- you
4271                          * might have a bit of a truncation problem.
4272                          */
4273 #ifdef  __XSCALE__
4274                         cylinders = (lun->be_lun->maxlba + 1) /
4275                                 sectors_per_cylinder;
4276 #else
4277                         for (shift = 31; shift > 0; shift--) {
4278                                 if (sectors_per_cylinder & (1 << shift))
4279                                         break;
4280                         }
4281                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4282 #endif
4283
4284                         /*
4285                          * We've basically got 3 bytes, or 24 bits for the
4286                          * cylinder size in the mode page.  If we're over,
4287                          * just round down to 2^24.
4288                          */
4289                         if (cylinders > 0xffffff)
4290                                 cylinders = 0xffffff;
4291
4292                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4293                                 CTL_PAGE_CURRENT];
4294                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4295
4296                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4297                                 CTL_PAGE_DEFAULT];
4298                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4299
4300                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4301                                 CTL_PAGE_SAVED];
4302                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4303
4304                         page_index->page_data =
4305                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4306                         break;
4307                 }
4308                 case SMS_CACHING_PAGE: {
4309                         struct scsi_caching_page *caching_page;
4310
4311                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4312                                 panic("invalid subpage value %d",
4313                                       page_index->subpage);
4314                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4315                                &caching_page_default,
4316                                sizeof(caching_page_default));
4317                         memcpy(&lun->mode_pages.caching_page[
4318                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4319                                sizeof(caching_page_changeable));
4320                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4321                                &caching_page_default,
4322                                sizeof(caching_page_default));
4323                         caching_page = &lun->mode_pages.caching_page[
4324                             CTL_PAGE_SAVED];
4325                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4326                         if (value != NULL && strcmp(value, "off") == 0)
4327                                 caching_page->flags1 &= ~SCP_WCE;
4328                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4329                         if (value != NULL && strcmp(value, "off") == 0)
4330                                 caching_page->flags1 |= SCP_RCD;
4331                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4332                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4333                                sizeof(caching_page_default));
4334                         page_index->page_data =
4335                                 (uint8_t *)lun->mode_pages.caching_page;
4336                         break;
4337                 }
4338                 case SMS_CONTROL_MODE_PAGE: {
4339                         struct scsi_control_page *control_page;
4340
4341                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4342                                 panic("invalid subpage value %d",
4343                                       page_index->subpage);
4344
4345                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4346                                &control_page_default,
4347                                sizeof(control_page_default));
4348                         memcpy(&lun->mode_pages.control_page[
4349                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4350                                sizeof(control_page_changeable));
4351                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4352                                &control_page_default,
4353                                sizeof(control_page_default));
4354                         control_page = &lun->mode_pages.control_page[
4355                             CTL_PAGE_SAVED];
4356                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4357                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4358                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4359                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4360                         }
4361                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4362                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4363                                sizeof(control_page_default));
4364                         page_index->page_data =
4365                                 (uint8_t *)lun->mode_pages.control_page;
4366                         break;
4367
4368                 }
4369                 case SMS_VENDOR_SPECIFIC_PAGE:{
4370                         switch (page_index->subpage) {
4371                         case PWR_SUBPAGE_CODE: {
4372                                 struct copan_power_subpage *current_page,
4373                                                            *saved_page;
4374
4375                                 memcpy(&lun->mode_pages.power_subpage[
4376                                        CTL_PAGE_CURRENT],
4377                                        &power_page_default,
4378                                        sizeof(power_page_default));
4379                                 memcpy(&lun->mode_pages.power_subpage[
4380                                        CTL_PAGE_CHANGEABLE],
4381                                        &power_page_changeable,
4382                                        sizeof(power_page_changeable));
4383                                 memcpy(&lun->mode_pages.power_subpage[
4384                                        CTL_PAGE_DEFAULT],
4385                                        &power_page_default,
4386                                        sizeof(power_page_default));
4387                                 memcpy(&lun->mode_pages.power_subpage[
4388                                        CTL_PAGE_SAVED],
4389                                        &power_page_default,
4390                                        sizeof(power_page_default));
4391                                 page_index->page_data =
4392                                     (uint8_t *)lun->mode_pages.power_subpage;
4393
4394                                 current_page = (struct copan_power_subpage *)
4395                                         (page_index->page_data +
4396                                          (page_index->page_len *
4397                                           CTL_PAGE_CURRENT));
4398                                 saved_page = (struct copan_power_subpage *)
4399                                         (page_index->page_data +
4400                                          (page_index->page_len *
4401                                           CTL_PAGE_SAVED));
4402                                 break;
4403                         }
4404                         case APS_SUBPAGE_CODE: {
4405                                 struct copan_aps_subpage *current_page,
4406                                                          *saved_page;
4407
4408                                 // This gets set multiple times but
4409                                 // it should always be the same. It's
4410                                 // only done during init so who cares.
4411                                 index_to_aps_page = i;
4412
4413                                 memcpy(&lun->mode_pages.aps_subpage[
4414                                        CTL_PAGE_CURRENT],
4415                                        &aps_page_default,
4416                                        sizeof(aps_page_default));
4417                                 memcpy(&lun->mode_pages.aps_subpage[
4418                                        CTL_PAGE_CHANGEABLE],
4419                                        &aps_page_changeable,
4420                                        sizeof(aps_page_changeable));
4421                                 memcpy(&lun->mode_pages.aps_subpage[
4422                                        CTL_PAGE_DEFAULT],
4423                                        &aps_page_default,
4424                                        sizeof(aps_page_default));
4425                                 memcpy(&lun->mode_pages.aps_subpage[
4426                                        CTL_PAGE_SAVED],
4427                                        &aps_page_default,
4428                                        sizeof(aps_page_default));
4429                                 page_index->page_data =
4430                                         (uint8_t *)lun->mode_pages.aps_subpage;
4431
4432                                 current_page = (struct copan_aps_subpage *)
4433                                         (page_index->page_data +
4434                                          (page_index->page_len *
4435                                           CTL_PAGE_CURRENT));
4436                                 saved_page = (struct copan_aps_subpage *)
4437                                         (page_index->page_data +
4438                                          (page_index->page_len *
4439                                           CTL_PAGE_SAVED));
4440                                 break;
4441                         }
4442                         case DBGCNF_SUBPAGE_CODE: {
4443                                 struct copan_debugconf_subpage *current_page,
4444                                                                *saved_page;
4445
4446                                 memcpy(&lun->mode_pages.debugconf_subpage[
4447                                        CTL_PAGE_CURRENT],
4448                                        &debugconf_page_default,
4449                                        sizeof(debugconf_page_default));
4450                                 memcpy(&lun->mode_pages.debugconf_subpage[
4451                                        CTL_PAGE_CHANGEABLE],
4452                                        &debugconf_page_changeable,
4453                                        sizeof(debugconf_page_changeable));
4454                                 memcpy(&lun->mode_pages.debugconf_subpage[
4455                                        CTL_PAGE_DEFAULT],
4456                                        &debugconf_page_default,
4457                                        sizeof(debugconf_page_default));
4458                                 memcpy(&lun->mode_pages.debugconf_subpage[
4459                                        CTL_PAGE_SAVED],
4460                                        &debugconf_page_default,
4461                                        sizeof(debugconf_page_default));
4462                                 page_index->page_data =
4463                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4464
4465                                 current_page = (struct copan_debugconf_subpage *)
4466                                         (page_index->page_data +
4467                                          (page_index->page_len *
4468                                           CTL_PAGE_CURRENT));
4469                                 saved_page = (struct copan_debugconf_subpage *)
4470                                         (page_index->page_data +
4471                                          (page_index->page_len *
4472                                           CTL_PAGE_SAVED));
4473                                 break;
4474                         }
4475                         default:
4476                                 panic("invalid subpage value %d",
4477                                       page_index->subpage);
4478                                 break;
4479                         }
4480                         break;
4481                 }
4482                 default:
4483                         panic("invalid page value %d",
4484                               page_index->page_code & SMPH_PC_MASK);
4485                         break;
4486         }
4487         }
4488
4489         return (CTL_RETVAL_COMPLETE);
4490 }
4491
4492 /*
4493  * LUN allocation.
4494  *
4495  * Requirements:
4496  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4497  *   wants us to allocate the LUN and he can block.
4498  * - ctl_softc is always set
4499  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4500  *
4501  * Returns 0 for success, non-zero (errno) for failure.
4502  */
4503 static int
4504 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4505               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4506 {
4507         struct ctl_lun *nlun, *lun;
4508         struct ctl_port *port;
4509         struct scsi_vpd_id_descriptor *desc;
4510         struct scsi_vpd_id_t10 *t10id;
4511         const char *eui, *naa, *scsiname, *vendor, *value;
4512         int lun_number, i, lun_malloced;
4513         int devidlen, idlen1, idlen2 = 0, len;
4514
4515         if (be_lun == NULL)
4516                 return (EINVAL);
4517
4518         /*
4519          * We currently only support Direct Access or Processor LUN types.
4520          */
4521         switch (be_lun->lun_type) {
4522         case T_DIRECT:
4523                 break;
4524         case T_PROCESSOR:
4525                 break;
4526         case T_SEQUENTIAL:
4527         case T_CHANGER:
4528         default:
4529                 be_lun->lun_config_status(be_lun->be_lun,
4530                                           CTL_LUN_CONFIG_FAILURE);
4531                 break;
4532         }
4533         if (ctl_lun == NULL) {
4534                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4535                 lun_malloced = 1;
4536         } else {
4537                 lun_malloced = 0;
4538                 lun = ctl_lun;
4539         }
4540
4541         memset(lun, 0, sizeof(*lun));
4542         if (lun_malloced)
4543                 lun->flags = CTL_LUN_MALLOCED;
4544
4545         /* Generate LUN ID. */
4546         devidlen = max(CTL_DEVID_MIN_LEN,
4547             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4548         idlen1 = sizeof(*t10id) + devidlen;
4549         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4550         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4551         if (scsiname != NULL) {
4552                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4553                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4554         }
4555         eui = ctl_get_opt(&be_lun->options, "eui");
4556         if (eui != NULL) {
4557                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4558         }
4559         naa = ctl_get_opt(&be_lun->options, "naa");
4560         if (naa != NULL) {
4561                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4562         }
4563         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4564             M_CTL, M_WAITOK | M_ZERO);
4565         lun->lun_devid->len = len;
4566         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4567         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4568         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4569         desc->length = idlen1;
4570         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4571         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4572         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4573                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4574         } else {
4575                 strncpy(t10id->vendor, vendor,
4576                     min(sizeof(t10id->vendor), strlen(vendor)));
4577         }
4578         strncpy((char *)t10id->vendor_spec_id,
4579             (char *)be_lun->device_id, devidlen);
4580         if (scsiname != NULL) {
4581                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4582                     desc->length);
4583                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4584                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4585                     SVPD_ID_TYPE_SCSI_NAME;
4586                 desc->length = idlen2;
4587                 strlcpy(desc->identifier, scsiname, idlen2);
4588         }
4589         if (eui != NULL) {
4590                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4591                     desc->length);
4592                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4593                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4594                     SVPD_ID_TYPE_EUI64;
4595                 desc->length = 8;
4596                 scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4597         }
4598         if (naa != NULL) {
4599                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4600                     desc->length);
4601                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4602                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4603                     SVPD_ID_TYPE_NAA;
4604                 desc->length = 8;
4605                 scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4606         }
4607
4608         mtx_lock(&ctl_softc->ctl_lock);
4609         /*
4610          * See if the caller requested a particular LUN number.  If so, see
4611          * if it is available.  Otherwise, allocate the first available LUN.
4612          */
4613         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4614                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4615                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4616                         mtx_unlock(&ctl_softc->ctl_lock);
4617                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4618                                 printf("ctl: requested LUN ID %d is higher "
4619                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4620                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4621                         } else {
4622                                 /*
4623                                  * XXX KDM return an error, or just assign
4624                                  * another LUN ID in this case??
4625                                  */
4626                                 printf("ctl: requested LUN ID %d is already "
4627                                        "in use\n", be_lun->req_lun_id);
4628                         }
4629                         if (lun->flags & CTL_LUN_MALLOCED)
4630                                 free(lun, M_CTL);
4631                         be_lun->lun_config_status(be_lun->be_lun,
4632                                                   CTL_LUN_CONFIG_FAILURE);
4633                         return (ENOSPC);
4634                 }
4635                 lun_number = be_lun->req_lun_id;
4636         } else {
4637                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4638                 if (lun_number == -1) {
4639                         mtx_unlock(&ctl_softc->ctl_lock);
4640                         printf("ctl: can't allocate LUN on target %ju, out of "
4641                                "LUNs\n", (uintmax_t)target_id.id);
4642                         if (lun->flags & CTL_LUN_MALLOCED)
4643                                 free(lun, M_CTL);
4644                         be_lun->lun_config_status(be_lun->be_lun,
4645                                                   CTL_LUN_CONFIG_FAILURE);
4646                         return (ENOSPC);
4647                 }
4648         }
4649         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4650
4651         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4652         lun->target = target_id;
4653         lun->lun = lun_number;
4654         lun->be_lun = be_lun;
4655         /*
4656          * The processor LUN is always enabled.  Disk LUNs come on line
4657          * disabled, and must be enabled by the backend.
4658          */
4659         lun->flags |= CTL_LUN_DISABLED;
4660         lun->backend = be_lun->be;
4661         be_lun->ctl_lun = lun;
4662         be_lun->lun_id = lun_number;
4663         atomic_add_int(&be_lun->be->num_luns, 1);
4664         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4665                 lun->flags |= CTL_LUN_OFFLINE;
4666
4667         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4668                 lun->flags |= CTL_LUN_STOPPED;
4669
4670         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4671                 lun->flags |= CTL_LUN_INOPERABLE;
4672
4673         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4674                 lun->flags |= CTL_LUN_PRIMARY_SC;
4675
4676         value = ctl_get_opt(&be_lun->options, "readonly");
4677         if (value != NULL && strcmp(value, "on") == 0)
4678                 lun->flags |= CTL_LUN_READONLY;
4679
4680         lun->ctl_softc = ctl_softc;
4681         TAILQ_INIT(&lun->ooa_queue);
4682         TAILQ_INIT(&lun->blocked_queue);
4683         STAILQ_INIT(&lun->error_list);
4684         ctl_tpc_lun_init(lun);
4685
4686         /*
4687          * Initialize the mode page index.
4688          */
4689         ctl_init_page_index(lun);
4690
4691         /*
4692          * Set the poweron UA for all initiators on this LUN only.
4693          */
4694         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4695                 lun->pending_ua[i] = CTL_UA_POWERON;
4696
4697         /*
4698          * Now, before we insert this lun on the lun list, set the lun
4699          * inventory changed UA for all other luns.
4700          */
4701         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4702                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4703                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4704                 }
4705         }
4706
4707         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4708
4709         ctl_softc->ctl_luns[lun_number] = lun;
4710
4711         ctl_softc->num_luns++;
4712
4713         /* Setup statistics gathering */
4714         lun->stats.device_type = be_lun->lun_type;
4715         lun->stats.lun_number = lun_number;
4716         if (lun->stats.device_type == T_DIRECT)
4717                 lun->stats.blocksize = be_lun->blocksize;
4718         else
4719                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4720         for (i = 0;i < CTL_MAX_PORTS;i++)
4721                 lun->stats.ports[i].targ_port = i;
4722
4723         mtx_unlock(&ctl_softc->ctl_lock);
4724
4725         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4726
4727         /*
4728          * Run through each registered FETD and bring it online if it isn't
4729          * already.  Enable the target ID if it hasn't been enabled, and
4730          * enable this particular LUN.
4731          */
4732         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4733                 int retval;
4734
4735                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4736                 if (retval != 0) {
4737                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4738                                "%d for lun_enable on target %ju lun %d\n",
4739                                port->port_name, port->targ_port, retval,
4740                                (uintmax_t)target_id.id, lun_number);
4741                 } else
4742                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4743         }
4744         return (0);
4745 }
4746
4747 /*
4748  * Delete a LUN.
4749  * Assumptions:
4750  * - LUN has already been marked invalid and any pending I/O has been taken
4751  *   care of.
4752  */
4753 static int
4754 ctl_free_lun(struct ctl_lun *lun)
4755 {
4756         struct ctl_softc *softc;
4757 #if 0
4758         struct ctl_port *port;
4759 #endif
4760         struct ctl_lun *nlun;
4761         int i;
4762
4763         softc = lun->ctl_softc;
4764
4765         mtx_assert(&softc->ctl_lock, MA_OWNED);
4766
4767         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4768
4769         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4770
4771         softc->ctl_luns[lun->lun] = NULL;
4772
4773         if (!TAILQ_EMPTY(&lun->ooa_queue))
4774                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4775
4776         softc->num_luns--;
4777
4778         /*
4779          * XXX KDM this scheme only works for a single target/multiple LUN
4780          * setup.  It needs to be revamped for a multiple target scheme.
4781          *
4782          * XXX KDM this results in port->lun_disable() getting called twice,
4783          * once when ctl_disable_lun() is called, and a second time here.
4784          * We really need to re-think the LUN disable semantics.  There
4785          * should probably be several steps/levels to LUN removal:
4786          *  - disable
4787          *  - invalidate
4788          *  - free
4789          *
4790          * Right now we only have a disable method when communicating to
4791          * the front end ports, at least for individual LUNs.
4792          */
4793 #if 0
4794         STAILQ_FOREACH(port, &softc->port_list, links) {
4795                 int retval;
4796
4797                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4798                                          lun->lun);
4799                 if (retval != 0) {
4800                         printf("ctl_free_lun: FETD %s port %d returned error "
4801                                "%d for lun_disable on target %ju lun %jd\n",
4802                                port->port_name, port->targ_port, retval,
4803                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4804                 }
4805
4806                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4807                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4808
4809                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4810                         if (retval != 0) {
4811                                 printf("ctl_free_lun: FETD %s port %d "
4812                                        "returned error %d for targ_disable on "
4813                                        "target %ju\n", port->port_name,
4814                                        port->targ_port, retval,
4815                                        (uintmax_t)lun->target.id);
4816                         } else
4817                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4818
4819                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4820                                 continue;
4821
4822 #if 0
4823                         port->port_offline(port->onoff_arg);
4824                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4825 #endif
4826                 }
4827         }
4828 #endif
4829
4830         /*
4831          * Tell the backend to free resources, if this LUN has a backend.
4832          */
4833         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4834         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4835
4836         ctl_tpc_lun_shutdown(lun);
4837         mtx_destroy(&lun->lun_lock);
4838         free(lun->lun_devid, M_CTL);
4839         if (lun->flags & CTL_LUN_MALLOCED)
4840                 free(lun, M_CTL);
4841
4842         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4843                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4844                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4845                 }
4846         }
4847
4848         return (0);
4849 }
4850
4851 static void
4852 ctl_create_lun(struct ctl_be_lun *be_lun)
4853 {
4854         struct ctl_softc *ctl_softc;
4855
4856         ctl_softc = control_softc;
4857
4858         /*
4859          * ctl_alloc_lun() should handle all potential failure cases.
4860          */
4861         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4862 }
4863
4864 int
4865 ctl_add_lun(struct ctl_be_lun *be_lun)
4866 {
4867         struct ctl_softc *ctl_softc = control_softc;
4868
4869         mtx_lock(&ctl_softc->ctl_lock);
4870         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4871         mtx_unlock(&ctl_softc->ctl_lock);
4872         wakeup(&ctl_softc->pending_lun_queue);
4873
4874         return (0);
4875 }
4876
4877 int
4878 ctl_enable_lun(struct ctl_be_lun *be_lun)
4879 {
4880         struct ctl_softc *ctl_softc;
4881         struct ctl_port *port, *nport;
4882         struct ctl_lun *lun;
4883         int retval;
4884
4885         ctl_softc = control_softc;
4886
4887         lun = (struct ctl_lun *)be_lun->ctl_lun;
4888
4889         mtx_lock(&ctl_softc->ctl_lock);
4890         mtx_lock(&lun->lun_lock);
4891         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4892                 /*
4893                  * eh?  Why did we get called if the LUN is already
4894                  * enabled?
4895                  */
4896                 mtx_unlock(&lun->lun_lock);
4897                 mtx_unlock(&ctl_softc->ctl_lock);
4898                 return (0);
4899         }
4900         lun->flags &= ~CTL_LUN_DISABLED;
4901         mtx_unlock(&lun->lun_lock);
4902
4903         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4904                 nport = STAILQ_NEXT(port, links);
4905
4906                 /*
4907                  * Drop the lock while we call the FETD's enable routine.
4908                  * This can lead to a callback into CTL (at least in the
4909                  * case of the internal initiator frontend.
4910                  */
4911                 mtx_unlock(&ctl_softc->ctl_lock);
4912                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4913                 mtx_lock(&ctl_softc->ctl_lock);
4914                 if (retval != 0) {
4915                         printf("%s: FETD %s port %d returned error "
4916                                "%d for lun_enable on target %ju lun %jd\n",
4917                                __func__, port->port_name, port->targ_port, retval,
4918                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4919                 }
4920 #if 0
4921                  else {
4922             /* NOTE:  TODO:  why does lun enable affect port status? */
4923                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4924                 }
4925 #endif
4926         }
4927
4928         mtx_unlock(&ctl_softc->ctl_lock);
4929
4930         return (0);
4931 }
4932
4933 int
4934 ctl_disable_lun(struct ctl_be_lun *be_lun)
4935 {
4936         struct ctl_softc *ctl_softc;
4937         struct ctl_port *port;
4938         struct ctl_lun *lun;
4939         int retval;
4940
4941         ctl_softc = control_softc;
4942
4943         lun = (struct ctl_lun *)be_lun->ctl_lun;
4944
4945         mtx_lock(&ctl_softc->ctl_lock);
4946         mtx_lock(&lun->lun_lock);
4947         if (lun->flags & CTL_LUN_DISABLED) {
4948                 mtx_unlock(&lun->lun_lock);
4949                 mtx_unlock(&ctl_softc->ctl_lock);
4950                 return (0);
4951         }
4952         lun->flags |= CTL_LUN_DISABLED;
4953         mtx_unlock(&lun->lun_lock);
4954
4955         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4956                 mtx_unlock(&ctl_softc->ctl_lock);
4957                 /*
4958                  * Drop the lock before we call the frontend's disable
4959                  * routine, to avoid lock order reversals.
4960                  *
4961                  * XXX KDM what happens if the frontend list changes while
4962                  * we're traversing it?  It's unlikely, but should be handled.
4963                  */
4964                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4965                                          lun->lun);
4966                 mtx_lock(&ctl_softc->ctl_lock);
4967                 if (retval != 0) {
4968                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4969                                "%d for lun_disable on target %ju lun %jd\n",
4970                                port->port_name, port->targ_port, retval,
4971                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4972                 }
4973         }
4974
4975         mtx_unlock(&ctl_softc->ctl_lock);
4976
4977         return (0);
4978 }
4979
4980 int
4981 ctl_start_lun(struct ctl_be_lun *be_lun)
4982 {
4983         struct ctl_softc *ctl_softc;
4984         struct ctl_lun *lun;
4985
4986         ctl_softc = control_softc;
4987
4988         lun = (struct ctl_lun *)be_lun->ctl_lun;
4989
4990         mtx_lock(&lun->lun_lock);
4991         lun->flags &= ~CTL_LUN_STOPPED;
4992         mtx_unlock(&lun->lun_lock);
4993
4994         return (0);
4995 }
4996
4997 int
4998 ctl_stop_lun(struct ctl_be_lun *be_lun)
4999 {
5000         struct ctl_softc *ctl_softc;
5001         struct ctl_lun *lun;
5002
5003         ctl_softc = control_softc;
5004
5005         lun = (struct ctl_lun *)be_lun->ctl_lun;
5006
5007         mtx_lock(&lun->lun_lock);
5008         lun->flags |= CTL_LUN_STOPPED;
5009         mtx_unlock(&lun->lun_lock);
5010
5011         return (0);
5012 }
5013
5014 int
5015 ctl_lun_offline(struct ctl_be_lun *be_lun)
5016 {
5017         struct ctl_softc *ctl_softc;
5018         struct ctl_lun *lun;
5019
5020         ctl_softc = control_softc;
5021
5022         lun = (struct ctl_lun *)be_lun->ctl_lun;
5023
5024         mtx_lock(&lun->lun_lock);
5025         lun->flags |= CTL_LUN_OFFLINE;
5026         mtx_unlock(&lun->lun_lock);
5027
5028         return (0);
5029 }
5030
5031 int
5032 ctl_lun_online(struct ctl_be_lun *be_lun)
5033 {
5034         struct ctl_softc *ctl_softc;
5035         struct ctl_lun *lun;
5036
5037         ctl_softc = control_softc;
5038
5039         lun = (struct ctl_lun *)be_lun->ctl_lun;
5040
5041         mtx_lock(&lun->lun_lock);
5042         lun->flags &= ~CTL_LUN_OFFLINE;
5043         mtx_unlock(&lun->lun_lock);
5044
5045         return (0);
5046 }
5047
5048 int
5049 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5050 {
5051         struct ctl_softc *ctl_softc;
5052         struct ctl_lun *lun;
5053
5054         ctl_softc = control_softc;
5055
5056         lun = (struct ctl_lun *)be_lun->ctl_lun;
5057
5058         mtx_lock(&lun->lun_lock);
5059
5060         /*
5061          * The LUN needs to be disabled before it can be marked invalid.
5062          */
5063         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5064                 mtx_unlock(&lun->lun_lock);
5065                 return (-1);
5066         }
5067         /*
5068          * Mark the LUN invalid.
5069          */
5070         lun->flags |= CTL_LUN_INVALID;
5071
5072         /*
5073          * If there is nothing in the OOA queue, go ahead and free the LUN.
5074          * If we have something in the OOA queue, we'll free it when the
5075          * last I/O completes.
5076          */
5077         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5078                 mtx_unlock(&lun->lun_lock);
5079                 mtx_lock(&ctl_softc->ctl_lock);
5080                 ctl_free_lun(lun);
5081                 mtx_unlock(&ctl_softc->ctl_lock);
5082         } else
5083                 mtx_unlock(&lun->lun_lock);
5084
5085         return (0);
5086 }
5087
5088 int
5089 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5090 {
5091         struct ctl_softc *ctl_softc;
5092         struct ctl_lun *lun;
5093
5094         ctl_softc = control_softc;
5095         lun = (struct ctl_lun *)be_lun->ctl_lun;
5096
5097         mtx_lock(&lun->lun_lock);
5098         lun->flags |= CTL_LUN_INOPERABLE;
5099         mtx_unlock(&lun->lun_lock);
5100
5101         return (0);
5102 }
5103
5104 int
5105 ctl_lun_operable(struct ctl_be_lun *be_lun)
5106 {
5107         struct ctl_softc *ctl_softc;
5108         struct ctl_lun *lun;
5109
5110         ctl_softc = control_softc;
5111         lun = (struct ctl_lun *)be_lun->ctl_lun;
5112
5113         mtx_lock(&lun->lun_lock);
5114         lun->flags &= ~CTL_LUN_INOPERABLE;
5115         mtx_unlock(&lun->lun_lock);
5116
5117         return (0);
5118 }
5119
5120 int
5121 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5122                    int lock)
5123 {
5124         struct ctl_softc *softc;
5125         struct ctl_lun *lun;
5126         struct copan_aps_subpage *current_sp;
5127         struct ctl_page_index *page_index;
5128         int i;
5129
5130         softc = control_softc;
5131
5132         mtx_lock(&softc->ctl_lock);
5133
5134         lun = (struct ctl_lun *)be_lun->ctl_lun;
5135         mtx_lock(&lun->lun_lock);
5136
5137         page_index = NULL;
5138         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5139                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5140                      APS_PAGE_CODE)
5141                         continue;
5142
5143                 if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5144                         continue;
5145                 page_index = &lun->mode_pages.index[i];
5146         }
5147
5148         if (page_index == NULL) {
5149                 mtx_unlock(&lun->lun_lock);
5150                 mtx_unlock(&softc->ctl_lock);
5151                 printf("%s: APS subpage not found for lun %ju!\n", __func__,
5152                        (uintmax_t)lun->lun);
5153                 return (1);
5154         }
5155 #if 0
5156         if ((softc->aps_locked_lun != 0)
5157          && (softc->aps_locked_lun != lun->lun)) {
5158                 printf("%s: attempt to lock LUN %llu when %llu is already "
5159                        "locked\n");
5160                 mtx_unlock(&lun->lun_lock);
5161                 mtx_unlock(&softc->ctl_lock);
5162                 return (1);
5163         }
5164 #endif
5165
5166         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5167                 (page_index->page_len * CTL_PAGE_CURRENT));
5168
5169         if (lock != 0) {
5170                 current_sp->lock_active = APS_LOCK_ACTIVE;
5171                 softc->aps_locked_lun = lun->lun;
5172         } else {
5173                 current_sp->lock_active = 0;
5174                 softc->aps_locked_lun = 0;
5175         }
5176
5177
5178         /*
5179          * If we're in HA mode, try to send the lock message to the other
5180          * side.
5181          */
5182         if (ctl_is_single == 0) {
5183                 int isc_retval;
5184                 union ctl_ha_msg lock_msg;
5185
5186                 lock_msg.hdr.nexus = *nexus;
5187                 lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5188                 if (lock != 0)
5189                         lock_msg.aps.lock_flag = 1;
5190                 else
5191                         lock_msg.aps.lock_flag = 0;
5192                 isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5193                                          sizeof(lock_msg), 0);
5194                 if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5195                         printf("%s: APS (lock=%d) error returned from "
5196                                "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5197                         mtx_unlock(&lun->lun_lock);
5198                         mtx_unlock(&softc->ctl_lock);
5199                         return (1);
5200                 }
5201         }
5202
5203         mtx_unlock(&lun->lun_lock);
5204         mtx_unlock(&softc->ctl_lock);
5205
5206         return (0);
5207 }
5208
5209 void
5210 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5211 {
5212         struct ctl_lun *lun;
5213         struct ctl_softc *softc;
5214         int i;
5215
5216         softc = control_softc;
5217
5218         lun = (struct ctl_lun *)be_lun->ctl_lun;
5219
5220         mtx_lock(&lun->lun_lock);
5221
5222         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
5223                 lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5224
5225         mtx_unlock(&lun->lun_lock);
5226 }
5227
5228 /*
5229  * Backend "memory move is complete" callback for requests that never
5230  * make it down to say RAIDCore's configuration code.
5231  */
5232 int
5233 ctl_config_move_done(union ctl_io *io)
5234 {
5235         int retval;
5236
5237         retval = CTL_RETVAL_COMPLETE;
5238
5239
5240         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5241         /*
5242          * XXX KDM this shouldn't happen, but what if it does?
5243          */
5244         if (io->io_hdr.io_type != CTL_IO_SCSI)
5245                 panic("I/O type isn't CTL_IO_SCSI!");
5246
5247         if ((io->io_hdr.port_status == 0)
5248          && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5249          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5250                 io->io_hdr.status = CTL_SUCCESS;
5251         else if ((io->io_hdr.port_status != 0)
5252               && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5253               && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5254                 /*
5255                  * For hardware error sense keys, the sense key
5256                  * specific value is defined to be a retry count,
5257                  * but we use it to pass back an internal FETD
5258                  * error code.  XXX KDM  Hopefully the FETD is only
5259                  * using 16 bits for an error code, since that's
5260                  * all the space we have in the sks field.
5261                  */
5262                 ctl_set_internal_failure(&io->scsiio,
5263                                          /*sks_valid*/ 1,
5264                                          /*retry_count*/
5265                                          io->io_hdr.port_status);
5266                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5267                         free(io->scsiio.kern_data_ptr, M_CTL);
5268                 ctl_done(io);
5269                 goto bailout;
5270         }
5271
5272         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5273          || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5274          || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5275                 /*
5276                  * XXX KDM just assuming a single pointer here, and not a
5277                  * S/G list.  If we start using S/G lists for config data,
5278                  * we'll need to know how to clean them up here as well.
5279                  */
5280                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5281                         free(io->scsiio.kern_data_ptr, M_CTL);
5282                 /* Hopefully the user has already set the status... */
5283                 ctl_done(io);
5284         } else {
5285                 /*
5286                  * XXX KDM now we need to continue data movement.  Some
5287                  * options:
5288                  * - call ctl_scsiio() again?  We don't do this for data
5289                  *   writes, because for those at least we know ahead of
5290                  *   time where the write will go and how long it is.  For
5291                  *   config writes, though, that information is largely
5292                  *   contained within the write itself, thus we need to
5293                  *   parse out the data again.
5294                  *
5295                  * - Call some other function once the data is in?
5296                  */
5297                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5298                         ctl_data_print(io);
5299
5300                 /*
5301                  * XXX KDM call ctl_scsiio() again for now, and check flag
5302                  * bits to see whether we're allocated or not.
5303                  */
5304                 retval = ctl_scsiio(&io->scsiio);
5305         }
5306 bailout:
5307         return (retval);
5308 }
5309
5310 /*
5311  * This gets called by a backend driver when it is done with a
5312  * data_submit method.
5313  */
5314 void
5315 ctl_data_submit_done(union ctl_io *io)
5316 {
5317         /*
5318          * If the IO_CONT flag is set, we need to call the supplied
5319          * function to continue processing the I/O, instead of completing
5320          * the I/O just yet.
5321          *
5322          * If there is an error, though, we don't want to keep processing.
5323          * Instead, just send status back to the initiator.
5324          */
5325         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5326             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5327             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5328              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5329                 io->scsiio.io_cont(io);
5330                 return;
5331         }
5332         ctl_done(io);
5333 }
5334
5335 /*
5336  * This gets called by a backend driver when it is done with a
5337  * configuration write.
5338  */
5339 void
5340 ctl_config_write_done(union ctl_io *io)
5341 {
5342         uint8_t *buf;
5343
5344         /*
5345          * If the IO_CONT flag is set, we need to call the supplied
5346          * function to continue processing the I/O, instead of completing
5347          * the I/O just yet.
5348          *
5349          * If there is an error, though, we don't want to keep processing.
5350          * Instead, just send status back to the initiator.
5351          */
5352         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5353             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5354             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5355              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5356                 io->scsiio.io_cont(io);
5357                 return;
5358         }
5359         /*
5360          * Since a configuration write can be done for commands that actually
5361          * have data allocated, like write buffer, and commands that have
5362          * no data, like start/stop unit, we need to check here.
5363          */
5364         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5365                 buf = io->scsiio.kern_data_ptr;
5366         else
5367                 buf = NULL;
5368         ctl_done(io);
5369         if (buf)
5370                 free(buf, M_CTL);
5371 }
5372
5373 /*
5374  * SCSI release command.
5375  */
5376 int
5377 ctl_scsi_release(struct ctl_scsiio *ctsio)
5378 {
5379         int length, longid, thirdparty_id, resv_id;
5380         struct ctl_softc *ctl_softc;
5381         struct ctl_lun *lun;
5382         uint32_t residx;
5383
5384         length = 0;
5385         resv_id = 0;
5386
5387         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5388
5389         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5390         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5391         ctl_softc = control_softc;
5392
5393         switch (ctsio->cdb[0]) {
5394         case RELEASE_10: {
5395                 struct scsi_release_10 *cdb;
5396
5397                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5398
5399                 if (cdb->byte2 & SR10_LONGID)
5400                         longid = 1;
5401                 else
5402                         thirdparty_id = cdb->thirdparty_id;
5403
5404                 resv_id = cdb->resv_id;
5405                 length = scsi_2btoul(cdb->length);
5406                 break;
5407         }
5408         }
5409
5410
5411         /*
5412          * XXX KDM right now, we only support LUN reservation.  We don't
5413          * support 3rd party reservations, or extent reservations, which
5414          * might actually need the parameter list.  If we've gotten this
5415          * far, we've got a LUN reservation.  Anything else got kicked out
5416          * above.  So, according to SPC, ignore the length.
5417          */
5418         length = 0;
5419
5420         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5421          && (length > 0)) {
5422                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5423                 ctsio->kern_data_len = length;
5424                 ctsio->kern_total_len = length;
5425                 ctsio->kern_data_resid = 0;
5426                 ctsio->kern_rel_offset = 0;
5427                 ctsio->kern_sg_entries = 0;
5428                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5429                 ctsio->be_move_done = ctl_config_move_done;
5430                 ctl_datamove((union ctl_io *)ctsio);
5431
5432                 return (CTL_RETVAL_COMPLETE);
5433         }
5434
5435         if (length > 0)
5436                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5437
5438         mtx_lock(&lun->lun_lock);
5439
5440         /*
5441          * According to SPC, it is not an error for an intiator to attempt
5442          * to release a reservation on a LUN that isn't reserved, or that
5443          * is reserved by another initiator.  The reservation can only be
5444          * released, though, by the initiator who made it or by one of
5445          * several reset type events.
5446          */
5447         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5448                         lun->flags &= ~CTL_LUN_RESERVED;
5449
5450         mtx_unlock(&lun->lun_lock);
5451
5452         ctsio->scsi_status = SCSI_STATUS_OK;
5453         ctsio->io_hdr.status = CTL_SUCCESS;
5454
5455         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5456                 free(ctsio->kern_data_ptr, M_CTL);
5457                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5458         }
5459
5460         ctl_done((union ctl_io *)ctsio);
5461         return (CTL_RETVAL_COMPLETE);
5462 }
5463
5464 int
5465 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5466 {
5467         int extent, thirdparty, longid;
5468         int resv_id, length;
5469         uint64_t thirdparty_id;
5470         struct ctl_softc *ctl_softc;
5471         struct ctl_lun *lun;
5472         uint32_t residx;
5473
5474         extent = 0;
5475         thirdparty = 0;
5476         longid = 0;
5477         resv_id = 0;
5478         length = 0;
5479         thirdparty_id = 0;
5480
5481         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5482
5483         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5484         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5485         ctl_softc = control_softc;
5486
5487         switch (ctsio->cdb[0]) {
5488         case RESERVE_10: {
5489                 struct scsi_reserve_10 *cdb;
5490
5491                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5492
5493                 if (cdb->byte2 & SR10_LONGID)
5494                         longid = 1;
5495                 else
5496                         thirdparty_id = cdb->thirdparty_id;
5497
5498                 resv_id = cdb->resv_id;
5499                 length = scsi_2btoul(cdb->length);
5500                 break;
5501         }
5502         }
5503
5504         /*
5505          * XXX KDM right now, we only support LUN reservation.  We don't
5506          * support 3rd party reservations, or extent reservations, which
5507          * might actually need the parameter list.  If we've gotten this
5508          * far, we've got a LUN reservation.  Anything else got kicked out
5509          * above.  So, according to SPC, ignore the length.
5510          */
5511         length = 0;
5512
5513         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5514          && (length > 0)) {
5515                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5516                 ctsio->kern_data_len = length;
5517                 ctsio->kern_total_len = length;
5518                 ctsio->kern_data_resid = 0;
5519                 ctsio->kern_rel_offset = 0;
5520                 ctsio->kern_sg_entries = 0;
5521                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5522                 ctsio->be_move_done = ctl_config_move_done;
5523                 ctl_datamove((union ctl_io *)ctsio);
5524
5525                 return (CTL_RETVAL_COMPLETE);
5526         }
5527
5528         if (length > 0)
5529                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5530
5531         mtx_lock(&lun->lun_lock);
5532         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5533                 ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5534                 ctsio->io_hdr.status = CTL_SCSI_ERROR;
5535                 goto bailout;
5536         }
5537
5538         lun->flags |= CTL_LUN_RESERVED;
5539         lun->res_idx = residx;
5540
5541         ctsio->scsi_status = SCSI_STATUS_OK;
5542         ctsio->io_hdr.status = CTL_SUCCESS;
5543
5544 bailout:
5545         mtx_unlock(&lun->lun_lock);
5546
5547         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5548                 free(ctsio->kern_data_ptr, M_CTL);
5549                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5550         }
5551
5552         ctl_done((union ctl_io *)ctsio);
5553         return (CTL_RETVAL_COMPLETE);
5554 }
5555
5556 int
5557 ctl_start_stop(struct ctl_scsiio *ctsio)
5558 {
5559         struct scsi_start_stop_unit *cdb;
5560         struct ctl_lun *lun;
5561         struct ctl_softc *ctl_softc;
5562         int retval;
5563
5564         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5565
5566         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5567         ctl_softc = control_softc;
5568         retval = 0;
5569
5570         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5571
5572         /*
5573          * XXX KDM
5574          * We don't support the immediate bit on a stop unit.  In order to
5575          * do that, we would need to code up a way to know that a stop is
5576          * pending, and hold off any new commands until it completes, one
5577          * way or another.  Then we could accept or reject those commands
5578          * depending on its status.  We would almost need to do the reverse
5579          * of what we do below for an immediate start -- return the copy of
5580          * the ctl_io to the FETD with status to send to the host (and to
5581          * free the copy!) and then free the original I/O once the stop
5582          * actually completes.  That way, the OOA queue mechanism can work
5583          * to block commands that shouldn't proceed.  Another alternative
5584          * would be to put the copy in the queue in place of the original,
5585          * and return the original back to the caller.  That could be
5586          * slightly safer..
5587          */
5588         if ((cdb->byte2 & SSS_IMMED)
5589          && ((cdb->how & SSS_START) == 0)) {
5590                 ctl_set_invalid_field(ctsio,
5591                                       /*sks_valid*/ 1,
5592                                       /*command*/ 1,
5593                                       /*field*/ 1,
5594                                       /*bit_valid*/ 1,
5595                                       /*bit*/ 0);
5596                 ctl_done((union ctl_io *)ctsio);
5597                 return (CTL_RETVAL_COMPLETE);
5598         }
5599
5600         if ((lun->flags & CTL_LUN_PR_RESERVED)
5601          && ((cdb->how & SSS_START)==0)) {
5602                 uint32_t residx;
5603
5604                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5605                 if (lun->pr_keys[residx] == 0
5606                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5607
5608                         ctl_set_reservation_conflict(ctsio);
5609                         ctl_done((union ctl_io *)ctsio);
5610                         return (CTL_RETVAL_COMPLETE);
5611                 }
5612         }
5613
5614         /*
5615          * If there is no backend on this device, we can't start or stop
5616          * it.  In theory we shouldn't get any start/stop commands in the
5617          * first place at this level if the LUN doesn't have a backend.
5618          * That should get stopped by the command decode code.
5619          */
5620         if (lun->backend == NULL) {
5621                 ctl_set_invalid_opcode(ctsio);
5622                 ctl_done((union ctl_io *)ctsio);
5623                 return (CTL_RETVAL_COMPLETE);
5624         }
5625
5626         /*
5627          * XXX KDM Copan-specific offline behavior.
5628          * Figure out a reasonable way to port this?
5629          */
5630 #ifdef NEEDTOPORT
5631         mtx_lock(&lun->lun_lock);
5632
5633         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5634          && (lun->flags & CTL_LUN_OFFLINE)) {
5635                 /*
5636                  * If the LUN is offline, and the on/offline bit isn't set,
5637                  * reject the start or stop.  Otherwise, let it through.
5638                  */
5639                 mtx_unlock(&lun->lun_lock);
5640                 ctl_set_lun_not_ready(ctsio);
5641                 ctl_done((union ctl_io *)ctsio);
5642         } else {
5643                 mtx_unlock(&lun->lun_lock);
5644 #endif /* NEEDTOPORT */
5645                 /*
5646                  * This could be a start or a stop when we're online,
5647                  * or a stop/offline or start/online.  A start or stop when
5648                  * we're offline is covered in the case above.
5649                  */
5650                 /*
5651                  * In the non-immediate case, we send the request to
5652                  * the backend and return status to the user when
5653                  * it is done.
5654                  *
5655                  * In the immediate case, we allocate a new ctl_io
5656                  * to hold a copy of the request, and send that to
5657                  * the backend.  We then set good status on the
5658                  * user's request and return it immediately.
5659                  */
5660                 if (cdb->byte2 & SSS_IMMED) {
5661                         union ctl_io *new_io;
5662
5663                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5664                         if (new_io == NULL) {
5665                                 ctl_set_busy(ctsio);
5666                                 ctl_done((union ctl_io *)ctsio);
5667                         } else {
5668                                 ctl_copy_io((union ctl_io *)ctsio,
5669                                             new_io);
5670                                 retval = lun->backend->config_write(new_io);
5671                                 ctl_set_success(ctsio);
5672                                 ctl_done((union ctl_io *)ctsio);
5673                         }
5674                 } else {
5675                         retval = lun->backend->config_write(
5676                                 (union ctl_io *)ctsio);
5677                 }
5678 #ifdef NEEDTOPORT
5679         }
5680 #endif
5681         return (retval);
5682 }
5683
5684 /*
5685  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5686  * we don't really do anything with the LBA and length fields if the user
5687  * passes them in.  Instead we'll just flush out the cache for the entire
5688  * LUN.
5689  */
5690 int
5691 ctl_sync_cache(struct ctl_scsiio *ctsio)
5692 {
5693         struct ctl_lun *lun;
5694         struct ctl_softc *ctl_softc;
5695         uint64_t starting_lba;
5696         uint32_t block_count;
5697         int retval;
5698
5699         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5700
5701         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5702         ctl_softc = control_softc;
5703         retval = 0;
5704
5705         switch (ctsio->cdb[0]) {
5706         case SYNCHRONIZE_CACHE: {
5707                 struct scsi_sync_cache *cdb;
5708                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5709
5710                 starting_lba = scsi_4btoul(cdb->begin_lba);
5711                 block_count = scsi_2btoul(cdb->lb_count);
5712                 break;
5713         }
5714         case SYNCHRONIZE_CACHE_16: {
5715                 struct scsi_sync_cache_16 *cdb;
5716                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5717
5718                 starting_lba = scsi_8btou64(cdb->begin_lba);
5719                 block_count = scsi_4btoul(cdb->lb_count);
5720                 break;
5721         }
5722         default:
5723                 ctl_set_invalid_opcode(ctsio);
5724                 ctl_done((union ctl_io *)ctsio);
5725                 goto bailout;
5726                 break; /* NOTREACHED */
5727         }
5728
5729         /*
5730          * We check the LBA and length, but don't do anything with them.
5731          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5732          * get flushed.  This check will just help satisfy anyone who wants
5733          * to see an error for an out of range LBA.
5734          */
5735         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5736                 ctl_set_lba_out_of_range(ctsio);
5737                 ctl_done((union ctl_io *)ctsio);
5738                 goto bailout;
5739         }
5740
5741         /*
5742          * If this LUN has no backend, we can't flush the cache anyway.
5743          */
5744         if (lun->backend == NULL) {
5745                 ctl_set_invalid_opcode(ctsio);
5746                 ctl_done((union ctl_io *)ctsio);
5747                 goto bailout;
5748         }
5749
5750         /*
5751          * Check to see whether we're configured to send the SYNCHRONIZE
5752          * CACHE command directly to the back end.
5753          */
5754         mtx_lock(&lun->lun_lock);
5755         if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5756          && (++(lun->sync_count) >= lun->sync_interval)) {
5757                 lun->sync_count = 0;
5758                 mtx_unlock(&lun->lun_lock);
5759                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5760         } else {
5761                 mtx_unlock(&lun->lun_lock);
5762                 ctl_set_success(ctsio);
5763                 ctl_done((union ctl_io *)ctsio);
5764         }
5765
5766 bailout:
5767
5768         return (retval);
5769 }
5770
5771 int
5772 ctl_format(struct ctl_scsiio *ctsio)
5773 {
5774         struct scsi_format *cdb;
5775         struct ctl_lun *lun;
5776         struct ctl_softc *ctl_softc;
5777         int length, defect_list_len;
5778
5779         CTL_DEBUG_PRINT(("ctl_format\n"));
5780
5781         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5782         ctl_softc = control_softc;
5783
5784         cdb = (struct scsi_format *)ctsio->cdb;
5785
5786         length = 0;
5787         if (cdb->byte2 & SF_FMTDATA) {
5788                 if (cdb->byte2 & SF_LONGLIST)
5789                         length = sizeof(struct scsi_format_header_long);
5790                 else
5791                         length = sizeof(struct scsi_format_header_short);
5792         }
5793
5794         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5795          && (length > 0)) {
5796                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5797                 ctsio->kern_data_len = length;
5798                 ctsio->kern_total_len = length;
5799                 ctsio->kern_data_resid = 0;
5800                 ctsio->kern_rel_offset = 0;
5801                 ctsio->kern_sg_entries = 0;
5802                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5803                 ctsio->be_move_done = ctl_config_move_done;
5804                 ctl_datamove((union ctl_io *)ctsio);
5805
5806                 return (CTL_RETVAL_COMPLETE);
5807         }
5808
5809         defect_list_len = 0;
5810
5811         if (cdb->byte2 & SF_FMTDATA) {
5812                 if (cdb->byte2 & SF_LONGLIST) {
5813                         struct scsi_format_header_long *header;
5814
5815                         header = (struct scsi_format_header_long *)
5816                                 ctsio->kern_data_ptr;
5817
5818                         defect_list_len = scsi_4btoul(header->defect_list_len);
5819                         if (defect_list_len != 0) {
5820                                 ctl_set_invalid_field(ctsio,
5821                                                       /*sks_valid*/ 1,
5822                                                       /*command*/ 0,
5823                                                       /*field*/ 2,
5824                                                       /*bit_valid*/ 0,
5825                                                       /*bit*/ 0);
5826                                 goto bailout;
5827                         }
5828                 } else {
5829                         struct scsi_format_header_short *header;
5830
5831                         header = (struct scsi_format_header_short *)
5832                                 ctsio->kern_data_ptr;
5833
5834                         defect_list_len = scsi_2btoul(header->defect_list_len);
5835                         if (defect_list_len != 0) {
5836                                 ctl_set_invalid_field(ctsio,
5837                                                       /*sks_valid*/ 1,
5838                                                       /*command*/ 0,
5839                                                       /*field*/ 2,
5840                                                       /*bit_valid*/ 0,
5841                                                       /*bit*/ 0);
5842                                 goto bailout;
5843                         }
5844                 }
5845         }
5846
5847         /*
5848          * The format command will clear out the "Medium format corrupted"
5849          * status if set by the configuration code.  That status is really
5850          * just a way to notify the host that we have lost the media, and
5851          * get them to issue a command that will basically make them think
5852          * they're blowing away the media.
5853          */
5854         mtx_lock(&lun->lun_lock);
5855         lun->flags &= ~CTL_LUN_INOPERABLE;
5856         mtx_unlock(&lun->lun_lock);
5857
5858         ctsio->scsi_status = SCSI_STATUS_OK;
5859         ctsio->io_hdr.status = CTL_SUCCESS;
5860 bailout:
5861
5862         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5863                 free(ctsio->kern_data_ptr, M_CTL);
5864                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5865         }
5866
5867         ctl_done((union ctl_io *)ctsio);
5868         return (CTL_RETVAL_COMPLETE);
5869 }
5870
5871 int
5872 ctl_read_buffer(struct ctl_scsiio *ctsio)
5873 {
5874         struct scsi_read_buffer *cdb;
5875         struct ctl_lun *lun;
5876         int buffer_offset, len;
5877         static uint8_t descr[4];
5878         static uint8_t echo_descr[4] = { 0 };
5879
5880         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5881
5882         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5883         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5884
5885         if (lun->flags & CTL_LUN_PR_RESERVED) {
5886                 uint32_t residx;
5887
5888                 /*
5889                  * XXX KDM need a lock here.
5890                  */
5891                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5892                 if ((lun->res_type == SPR_TYPE_EX_AC
5893                   && residx != lun->pr_res_idx)
5894                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
5895                    || lun->res_type == SPR_TYPE_EX_AC_AR)
5896                   && lun->pr_keys[residx] == 0)) {
5897                         ctl_set_reservation_conflict(ctsio);
5898                         ctl_done((union ctl_io *)ctsio);
5899                         return (CTL_RETVAL_COMPLETE);
5900                 }
5901         }
5902
5903         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5904             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5905             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5906                 ctl_set_invalid_field(ctsio,
5907                                       /*sks_valid*/ 1,
5908                                       /*command*/ 1,
5909                                       /*field*/ 1,
5910                                       /*bit_valid*/ 1,
5911                                       /*bit*/ 4);
5912                 ctl_done((union ctl_io *)ctsio);
5913                 return (CTL_RETVAL_COMPLETE);
5914         }
5915
5916         len = scsi_3btoul(cdb->length);
5917         buffer_offset = scsi_3btoul(cdb->offset);
5918
5919         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5920                 ctl_set_invalid_field(ctsio,
5921                                       /*sks_valid*/ 1,
5922                                       /*command*/ 1,
5923                                       /*field*/ 6,
5924                                       /*bit_valid*/ 0,
5925                                       /*bit*/ 0);
5926                 ctl_done((union ctl_io *)ctsio);
5927                 return (CTL_RETVAL_COMPLETE);
5928         }
5929
5930         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5931                 descr[0] = 0;
5932                 scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5933                 ctsio->kern_data_ptr = descr;
5934                 len = min(len, sizeof(descr));
5935         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5936                 ctsio->kern_data_ptr = echo_descr;
5937                 len = min(len, sizeof(echo_descr));
5938         } else
5939                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5940         ctsio->kern_data_len = len;
5941         ctsio->kern_total_len = len;
5942         ctsio->kern_data_resid = 0;
5943         ctsio->kern_rel_offset = 0;
5944         ctsio->kern_sg_entries = 0;
5945         ctsio->be_move_done = ctl_config_move_done;
5946         ctl_datamove((union ctl_io *)ctsio);
5947
5948         return (CTL_RETVAL_COMPLETE);
5949 }
5950
5951 int
5952 ctl_write_buffer(struct ctl_scsiio *ctsio)
5953 {
5954         struct scsi_write_buffer *cdb;
5955         struct ctl_lun *lun;
5956         int buffer_offset, len;
5957
5958         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5959
5960         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5961         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5962
5963         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5964                 ctl_set_invalid_field(ctsio,
5965                                       /*sks_valid*/ 1,
5966                                       /*command*/ 1,
5967                                       /*field*/ 1,
5968                                       /*bit_valid*/ 1,
5969                                       /*bit*/ 4);
5970                 ctl_done((union ctl_io *)ctsio);
5971                 return (CTL_RETVAL_COMPLETE);
5972         }
5973
5974         len = scsi_3btoul(cdb->length);
5975         buffer_offset = scsi_3btoul(cdb->offset);
5976
5977         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5978                 ctl_set_invalid_field(ctsio,
5979                                       /*sks_valid*/ 1,
5980                                       /*command*/ 1,
5981                                       /*field*/ 6,
5982                                       /*bit_valid*/ 0,
5983                                       /*bit*/ 0);
5984                 ctl_done((union ctl_io *)ctsio);
5985                 return (CTL_RETVAL_COMPLETE);
5986         }
5987
5988         /*
5989          * If we've got a kernel request that hasn't been malloced yet,
5990          * malloc it and tell the caller the data buffer is here.
5991          */
5992         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5993                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5994                 ctsio->kern_data_len = len;
5995                 ctsio->kern_total_len = len;
5996                 ctsio->kern_data_resid = 0;
5997                 ctsio->kern_rel_offset = 0;
5998                 ctsio->kern_sg_entries = 0;
5999                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6000                 ctsio->be_move_done = ctl_config_move_done;
6001                 ctl_datamove((union ctl_io *)ctsio);
6002
6003                 return (CTL_RETVAL_COMPLETE);
6004         }
6005
6006         ctl_done((union ctl_io *)ctsio);
6007
6008         return (CTL_RETVAL_COMPLETE);
6009 }
6010
6011 int
6012 ctl_write_same(struct ctl_scsiio *ctsio)
6013 {
6014         struct ctl_lun *lun;
6015         struct ctl_lba_len_flags *lbalen;
6016         uint64_t lba;
6017         uint32_t num_blocks;
6018         int len, retval;
6019         uint8_t byte2;
6020
6021         retval = CTL_RETVAL_COMPLETE;
6022
6023         CTL_DEBUG_PRINT(("ctl_write_same\n"));
6024
6025         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6026
6027         switch (ctsio->cdb[0]) {
6028         case WRITE_SAME_10: {
6029                 struct scsi_write_same_10 *cdb;
6030
6031                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
6032
6033                 lba = scsi_4btoul(cdb->addr);
6034                 num_blocks = scsi_2btoul(cdb->length);
6035                 byte2 = cdb->byte2;
6036                 break;
6037         }
6038         case WRITE_SAME_16: {
6039                 struct scsi_write_same_16 *cdb;
6040
6041                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
6042
6043                 lba = scsi_8btou64(cdb->addr);
6044                 num_blocks = scsi_4btoul(cdb->length);
6045                 byte2 = cdb->byte2;
6046                 break;
6047         }
6048         default:
6049                 /*
6050                  * We got a command we don't support.  This shouldn't
6051                  * happen, commands should be filtered out above us.
6052                  */
6053                 ctl_set_invalid_opcode(ctsio);
6054                 ctl_done((union ctl_io *)ctsio);
6055
6056                 return (CTL_RETVAL_COMPLETE);
6057                 break; /* NOTREACHED */
6058         }
6059
6060         /* NDOB and ANCHOR flags can be used only together with UNMAP */
6061         if ((byte2 & SWS_UNMAP) == 0 &&
6062             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
6063                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
6064                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
6065                 ctl_done((union ctl_io *)ctsio);
6066                 return (CTL_RETVAL_COMPLETE);
6067         }
6068
6069         /*
6070          * The first check is to make sure we're in bounds, the second
6071          * check is to catch wrap-around problems.  If the lba + num blocks
6072          * is less than the lba, then we've wrapped around and the block
6073          * range is invalid anyway.
6074          */
6075         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6076          || ((lba + num_blocks) < lba)) {
6077                 ctl_set_lba_out_of_range(ctsio);
6078                 ctl_done((union ctl_io *)ctsio);
6079                 return (CTL_RETVAL_COMPLETE);
6080         }
6081
6082         /* Zero number of blocks means "to the last logical block" */
6083         if (num_blocks == 0) {
6084                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6085                         ctl_set_invalid_field(ctsio,
6086                                               /*sks_valid*/ 0,
6087                                               /*command*/ 1,
6088                                               /*field*/ 0,
6089                                               /*bit_valid*/ 0,
6090                                               /*bit*/ 0);
6091                         ctl_done((union ctl_io *)ctsio);
6092                         return (CTL_RETVAL_COMPLETE);
6093                 }
6094                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
6095         }
6096
6097         len = lun->be_lun->blocksize;
6098
6099         /*
6100          * If we've got a kernel request that hasn't been malloced yet,
6101          * malloc it and tell the caller the data buffer is here.
6102          */
6103         if ((byte2 & SWS_NDOB) == 0 &&
6104             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6105                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6106                 ctsio->kern_data_len = len;
6107                 ctsio->kern_total_len = len;
6108                 ctsio->kern_data_resid = 0;
6109                 ctsio->kern_rel_offset = 0;
6110                 ctsio->kern_sg_entries = 0;
6111                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6112                 ctsio->be_move_done = ctl_config_move_done;
6113                 ctl_datamove((union ctl_io *)ctsio);
6114
6115                 return (CTL_RETVAL_COMPLETE);
6116         }
6117
6118         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6119         lbalen->lba = lba;
6120         lbalen->len = num_blocks;
6121         lbalen->flags = byte2;
6122         retval = lun->backend->config_write((union ctl_io *)ctsio);
6123
6124         return (retval);
6125 }
6126
6127 int
6128 ctl_unmap(struct ctl_scsiio *ctsio)
6129 {
6130         struct ctl_lun *lun;
6131         struct scsi_unmap *cdb;
6132         struct ctl_ptr_len_flags *ptrlen;
6133         struct scsi_unmap_header *hdr;
6134         struct scsi_unmap_desc *buf, *end, *endnz, *range;
6135         uint64_t lba;
6136         uint32_t num_blocks;
6137         int len, retval;
6138         uint8_t byte2;
6139
6140         retval = CTL_RETVAL_COMPLETE;
6141
6142         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6143
6144         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6145         cdb = (struct scsi_unmap *)ctsio->cdb;
6146
6147         len = scsi_2btoul(cdb->length);
6148         byte2 = cdb->byte2;
6149
6150         /*
6151          * If we've got a kernel request that hasn't been malloced yet,
6152          * malloc it and tell the caller the data buffer is here.
6153          */
6154         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6155                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6156                 ctsio->kern_data_len = len;
6157                 ctsio->kern_total_len = len;
6158                 ctsio->kern_data_resid = 0;
6159                 ctsio->kern_rel_offset = 0;
6160                 ctsio->kern_sg_entries = 0;
6161                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6162                 ctsio->be_move_done = ctl_config_move_done;
6163                 ctl_datamove((union ctl_io *)ctsio);
6164
6165                 return (CTL_RETVAL_COMPLETE);
6166         }
6167
6168         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6169         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6170         if (len < sizeof (*hdr) ||
6171             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6172             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6173             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6174                 ctl_set_invalid_field(ctsio,
6175                                       /*sks_valid*/ 0,
6176                                       /*command*/ 0,
6177                                       /*field*/ 0,
6178                                       /*bit_valid*/ 0,
6179                                       /*bit*/ 0);
6180                 ctl_done((union ctl_io *)ctsio);
6181                 return (CTL_RETVAL_COMPLETE);
6182         }
6183         len = scsi_2btoul(hdr->desc_length);
6184         buf = (struct scsi_unmap_desc *)(hdr + 1);
6185         end = buf + len / sizeof(*buf);
6186
6187         endnz = buf;
6188         for (range = buf; range < end; range++) {
6189                 lba = scsi_8btou64(range->lba);
6190                 num_blocks = scsi_4btoul(range->length);
6191                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6192                  || ((lba + num_blocks) < lba)) {
6193                         ctl_set_lba_out_of_range(ctsio);
6194                         ctl_done((union ctl_io *)ctsio);
6195                         return (CTL_RETVAL_COMPLETE);
6196                 }
6197                 if (num_blocks != 0)
6198                         endnz = range + 1;
6199         }
6200
6201         /*
6202          * Block backend can not handle zero last range.
6203          * Filter it out and return if there is nothing left.
6204          */
6205         len = (uint8_t *)endnz - (uint8_t *)buf;
6206         if (len == 0) {
6207                 ctl_set_success(ctsio);
6208                 ctl_done((union ctl_io *)ctsio);
6209                 return (CTL_RETVAL_COMPLETE);
6210         }
6211
6212         mtx_lock(&lun->lun_lock);
6213         ptrlen = (struct ctl_ptr_len_flags *)
6214             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6215         ptrlen->ptr = (void *)buf;
6216         ptrlen->len = len;
6217         ptrlen->flags = byte2;
6218         ctl_check_blocked(lun);
6219         mtx_unlock(&lun->lun_lock);
6220
6221         retval = lun->backend->config_write((union ctl_io *)ctsio);
6222         return (retval);
6223 }
6224
6225 /*
6226  * Note that this function currently doesn't actually do anything inside
6227  * CTL to enforce things if the DQue bit is turned on.
6228  *
6229  * Also note that this function can't be used in the default case, because
6230  * the DQue bit isn't set in the changeable mask for the control mode page
6231  * anyway.  This is just here as an example for how to implement a page
6232  * handler, and a placeholder in case we want to allow the user to turn
6233  * tagged queueing on and off.
6234  *
6235  * The D_SENSE bit handling is functional, however, and will turn
6236  * descriptor sense on and off for a given LUN.
6237  */
6238 int
6239 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6240                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6241 {
6242         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6243         struct ctl_lun *lun;
6244         struct ctl_softc *softc;
6245         int set_ua;
6246         uint32_t initidx;
6247
6248         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6249         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6250         set_ua = 0;
6251
6252         user_cp = (struct scsi_control_page *)page_ptr;
6253         current_cp = (struct scsi_control_page *)
6254                 (page_index->page_data + (page_index->page_len *
6255                 CTL_PAGE_CURRENT));
6256         saved_cp = (struct scsi_control_page *)
6257                 (page_index->page_data + (page_index->page_len *
6258                 CTL_PAGE_SAVED));
6259
6260         softc = control_softc;
6261
6262         mtx_lock(&lun->lun_lock);
6263         if (((current_cp->rlec & SCP_DSENSE) == 0)
6264          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6265                 /*
6266                  * Descriptor sense is currently turned off and the user
6267                  * wants to turn it on.
6268                  */
6269                 current_cp->rlec |= SCP_DSENSE;
6270                 saved_cp->rlec |= SCP_DSENSE;
6271                 lun->flags |= CTL_LUN_SENSE_DESC;
6272                 set_ua = 1;
6273         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6274                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6275                 /*
6276                  * Descriptor sense is currently turned on, and the user
6277                  * wants to turn it off.
6278                  */
6279                 current_cp->rlec &= ~SCP_DSENSE;
6280                 saved_cp->rlec &= ~SCP_DSENSE;
6281                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6282                 set_ua = 1;
6283         }
6284         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6285             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6286                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6287                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6288                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6289                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6290                 set_ua = 1;
6291         }
6292         if ((current_cp->eca_and_aen & SCP_SWP) !=
6293             (user_cp->eca_and_aen & SCP_SWP)) {
6294                 current_cp->eca_and_aen &= ~SCP_SWP;
6295                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6296                 saved_cp->eca_and_aen &= ~SCP_SWP;
6297                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6298                 set_ua = 1;
6299         }
6300         if (set_ua != 0) {
6301                 int i;
6302                 /*
6303                  * Let other initiators know that the mode
6304                  * parameters for this LUN have changed.
6305                  */
6306                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6307                         if (i == initidx)
6308                                 continue;
6309
6310                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6311                 }
6312         }
6313         mtx_unlock(&lun->lun_lock);
6314
6315         return (0);
6316 }
6317
6318 int
6319 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6320                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6321 {
6322         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6323         struct ctl_lun *lun;
6324         int set_ua;
6325         uint32_t initidx;
6326
6327         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6328         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6329         set_ua = 0;
6330
6331         user_cp = (struct scsi_caching_page *)page_ptr;
6332         current_cp = (struct scsi_caching_page *)
6333                 (page_index->page_data + (page_index->page_len *
6334                 CTL_PAGE_CURRENT));
6335         saved_cp = (struct scsi_caching_page *)
6336                 (page_index->page_data + (page_index->page_len *
6337                 CTL_PAGE_SAVED));
6338
6339         mtx_lock(&lun->lun_lock);
6340         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6341             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6342                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6343                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6344                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6345                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6346                 set_ua = 1;
6347         }
6348         if (set_ua != 0) {
6349                 int i;
6350                 /*
6351                  * Let other initiators know that the mode
6352                  * parameters for this LUN have changed.
6353                  */
6354                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6355                         if (i == initidx)
6356                                 continue;
6357
6358                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6359                 }
6360         }
6361         mtx_unlock(&lun->lun_lock);
6362
6363         return (0);
6364 }
6365
6366 int
6367 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6368                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6369 {
6370         return (0);
6371 }
6372
6373 int
6374 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6375                            struct ctl_page_index *page_index, int pc)
6376 {
6377         struct copan_power_subpage *page;
6378
6379         page = (struct copan_power_subpage *)page_index->page_data +
6380                 (page_index->page_len * pc);
6381
6382         switch (pc) {
6383         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6384                 /*
6385                  * We don't update the changable bits for this page.
6386                  */
6387                 break;
6388         case SMS_PAGE_CTRL_CURRENT >> 6:
6389         case SMS_PAGE_CTRL_DEFAULT >> 6:
6390         case SMS_PAGE_CTRL_SAVED >> 6:
6391 #ifdef NEEDTOPORT
6392                 ctl_update_power_subpage(page);
6393 #endif
6394                 break;
6395         default:
6396 #ifdef NEEDTOPORT
6397                 EPRINT(0, "Invalid PC %d!!", pc);
6398 #endif
6399                 break;
6400         }
6401         return (0);
6402 }
6403
6404
6405 int
6406 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6407                    struct ctl_page_index *page_index, uint8_t *page_ptr)
6408 {
6409         struct copan_aps_subpage *user_sp;
6410         struct copan_aps_subpage *current_sp;
6411         union ctl_modepage_info *modepage_info;
6412         struct ctl_softc *softc;
6413         struct ctl_lun *lun;
6414         int retval;
6415
6416         retval = CTL_RETVAL_COMPLETE;
6417         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6418                      (page_index->page_len * CTL_PAGE_CURRENT));
6419         softc = control_softc;
6420         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6421
6422         user_sp = (struct copan_aps_subpage *)page_ptr;
6423
6424         modepage_info = (union ctl_modepage_info *)
6425                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6426
6427         modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6428         modepage_info->header.subpage = page_index->subpage;
6429         modepage_info->aps.lock_active = user_sp->lock_active;
6430
6431         mtx_lock(&softc->ctl_lock);
6432
6433         /*
6434          * If there is a request to lock the LUN and another LUN is locked
6435          * this is an error. If the requested LUN is already locked ignore
6436          * the request. If no LUN is locked attempt to lock it.
6437          * if there is a request to unlock the LUN and the LUN is currently
6438          * locked attempt to unlock it. Otherwise ignore the request. i.e.
6439          * if another LUN is locked or no LUN is locked.
6440          */
6441         if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6442                 if (softc->aps_locked_lun == lun->lun) {
6443                         /*
6444                          * This LUN is already locked, so we're done.
6445                          */
6446                         retval = CTL_RETVAL_COMPLETE;
6447                 } else if (softc->aps_locked_lun == 0) {
6448                         /*
6449                          * No one has the lock, pass the request to the
6450                          * backend.
6451                          */
6452                         retval = lun->backend->config_write(
6453                                 (union ctl_io *)ctsio);
6454                 } else {
6455                         /*
6456                          * Someone else has the lock, throw out the request.
6457                          */
6458                         ctl_set_already_locked(ctsio);
6459                         free(ctsio->kern_data_ptr, M_CTL);
6460                         ctl_done((union ctl_io *)ctsio);
6461
6462                         /*
6463                          * Set the return value so that ctl_do_mode_select()
6464                          * won't try to complete the command.  We already
6465                          * completed it here.
6466                          */
6467                         retval = CTL_RETVAL_ERROR;
6468                 }
6469         } else if (softc->aps_locked_lun == lun->lun) {
6470                 /*
6471                  * This LUN is locked, so pass the unlock request to the
6472                  * backend.
6473                  */
6474                 retval = lun->backend->config_write((union ctl_io *)ctsio);
6475         }
6476         mtx_unlock(&softc->ctl_lock);
6477
6478         return (retval);
6479 }
6480
6481 int
6482 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6483                                 struct ctl_page_index *page_index,
6484                                 uint8_t *page_ptr)
6485 {
6486         uint8_t *c;
6487         int i;
6488
6489         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6490         ctl_time_io_secs =
6491                 (c[0] << 8) |
6492                 (c[1] << 0) |
6493                 0;
6494         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6495         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6496         printf("page data:");
6497         for (i=0; i<8; i++)
6498                 printf(" %.2x",page_ptr[i]);
6499         printf("\n");
6500         return (0);
6501 }
6502
6503 int
6504 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6505                                struct ctl_page_index *page_index,
6506                                int pc)
6507 {
6508         struct copan_debugconf_subpage *page;
6509
6510         page = (struct copan_debugconf_subpage *)page_index->page_data +
6511                 (page_index->page_len * pc);
6512
6513         switch (pc) {
6514         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6515         case SMS_PAGE_CTRL_DEFAULT >> 6:
6516         case SMS_PAGE_CTRL_SAVED >> 6:
6517                 /*
6518                  * We don't update the changable or default bits for this page.
6519                  */
6520                 break;
6521         case SMS_PAGE_CTRL_CURRENT >> 6:
6522                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6523                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6524                 break;
6525         default:
6526 #ifdef NEEDTOPORT
6527                 EPRINT(0, "Invalid PC %d!!", pc);
6528 #endif /* NEEDTOPORT */
6529                 break;
6530         }
6531         return (0);
6532 }
6533
6534
6535 static int
6536 ctl_do_mode_select(union ctl_io *io)
6537 {
6538         struct scsi_mode_page_header *page_header;
6539         struct ctl_page_index *page_index;
6540         struct ctl_scsiio *ctsio;
6541         int control_dev, page_len;
6542         int page_len_offset, page_len_size;
6543         union ctl_modepage_info *modepage_info;
6544         struct ctl_lun *lun;
6545         int *len_left, *len_used;
6546         int retval, i;
6547
6548         ctsio = &io->scsiio;
6549         page_index = NULL;
6550         page_len = 0;
6551         retval = CTL_RETVAL_COMPLETE;
6552
6553         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6554
6555         if (lun->be_lun->lun_type != T_DIRECT)
6556                 control_dev = 1;
6557         else
6558                 control_dev = 0;
6559
6560         modepage_info = (union ctl_modepage_info *)
6561                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6562         len_left = &modepage_info->header.len_left;
6563         len_used = &modepage_info->header.len_used;
6564
6565 do_next_page:
6566
6567         page_header = (struct scsi_mode_page_header *)
6568                 (ctsio->kern_data_ptr + *len_used);
6569
6570         if (*len_left == 0) {
6571                 free(ctsio->kern_data_ptr, M_CTL);
6572                 ctl_set_success(ctsio);
6573                 ctl_done((union ctl_io *)ctsio);
6574                 return (CTL_RETVAL_COMPLETE);
6575         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6576
6577                 free(ctsio->kern_data_ptr, M_CTL);
6578                 ctl_set_param_len_error(ctsio);
6579                 ctl_done((union ctl_io *)ctsio);
6580                 return (CTL_RETVAL_COMPLETE);
6581
6582         } else if ((page_header->page_code & SMPH_SPF)
6583                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6584
6585                 free(ctsio->kern_data_ptr, M_CTL);
6586                 ctl_set_param_len_error(ctsio);
6587                 ctl_done((union ctl_io *)ctsio);
6588                 return (CTL_RETVAL_COMPLETE);
6589         }
6590
6591
6592         /*
6593          * XXX KDM should we do something with the block descriptor?
6594          */
6595         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6596
6597                 if ((control_dev != 0)
6598                  && (lun->mode_pages.index[i].page_flags &
6599                      CTL_PAGE_FLAG_DISK_ONLY))
6600                         continue;
6601
6602                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6603                     (page_header->page_code & SMPH_PC_MASK))
6604                         continue;
6605
6606                 /*
6607                  * If neither page has a subpage code, then we've got a
6608                  * match.
6609                  */
6610                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6611                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6612                         page_index = &lun->mode_pages.index[i];
6613                         page_len = page_header->page_length;
6614                         break;
6615                 }
6616
6617                 /*
6618                  * If both pages have subpages, then the subpage numbers
6619                  * have to match.
6620                  */
6621                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6622                   && (page_header->page_code & SMPH_SPF)) {
6623                         struct scsi_mode_page_header_sp *sph;
6624
6625                         sph = (struct scsi_mode_page_header_sp *)page_header;
6626
6627                         if (lun->mode_pages.index[i].subpage ==
6628                             sph->subpage) {
6629                                 page_index = &lun->mode_pages.index[i];
6630                                 page_len = scsi_2btoul(sph->page_length);
6631                                 break;
6632                         }
6633                 }
6634         }
6635
6636         /*
6637          * If we couldn't find the page, or if we don't have a mode select
6638          * handler for it, send back an error to the user.
6639          */
6640         if ((page_index == NULL)
6641          || (page_index->select_handler == NULL)) {
6642                 ctl_set_invalid_field(ctsio,
6643                                       /*sks_valid*/ 1,
6644                                       /*command*/ 0,
6645                                       /*field*/ *len_used,
6646                                       /*bit_valid*/ 0,
6647                                       /*bit*/ 0);
6648                 free(ctsio->kern_data_ptr, M_CTL);
6649                 ctl_done((union ctl_io *)ctsio);
6650                 return (CTL_RETVAL_COMPLETE);
6651         }
6652
6653         if (page_index->page_code & SMPH_SPF) {
6654                 page_len_offset = 2;
6655                 page_len_size = 2;
6656         } else {
6657                 page_len_size = 1;
6658                 page_len_offset = 1;
6659         }
6660
6661         /*
6662          * If the length the initiator gives us isn't the one we specify in
6663          * the mode page header, or if they didn't specify enough data in
6664          * the CDB to avoid truncating this page, kick out the request.
6665          */
6666         if ((page_len != (page_index->page_len - page_len_offset -
6667                           page_len_size))
6668          || (*len_left < page_index->page_len)) {
6669
6670
6671                 ctl_set_invalid_field(ctsio,
6672                                       /*sks_valid*/ 1,
6673                                       /*command*/ 0,
6674                                       /*field*/ *len_used + page_len_offset,
6675                                       /*bit_valid*/ 0,
6676                                       /*bit*/ 0);
6677                 free(ctsio->kern_data_ptr, M_CTL);
6678                 ctl_done((union ctl_io *)ctsio);
6679                 return (CTL_RETVAL_COMPLETE);
6680         }
6681
6682         /*
6683          * Run through the mode page, checking to make sure that the bits
6684          * the user changed are actually legal for him to change.
6685          */
6686         for (i = 0; i < page_index->page_len; i++) {
6687                 uint8_t *user_byte, *change_mask, *current_byte;
6688                 int bad_bit;
6689                 int j;
6690
6691                 user_byte = (uint8_t *)page_header + i;
6692                 change_mask = page_index->page_data +
6693                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6694                 current_byte = page_index->page_data +
6695                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6696
6697                 /*
6698                  * Check to see whether the user set any bits in this byte
6699                  * that he is not allowed to set.
6700                  */
6701                 if ((*user_byte & ~(*change_mask)) ==
6702                     (*current_byte & ~(*change_mask)))
6703                         continue;
6704
6705                 /*
6706                  * Go through bit by bit to determine which one is illegal.
6707                  */
6708                 bad_bit = 0;
6709                 for (j = 7; j >= 0; j--) {
6710                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6711                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6712                                 bad_bit = i;
6713                                 break;
6714                         }
6715                 }
6716                 ctl_set_invalid_field(ctsio,
6717                                       /*sks_valid*/ 1,
6718                                       /*command*/ 0,
6719                                       /*field*/ *len_used + i,
6720                                       /*bit_valid*/ 1,
6721                                       /*bit*/ bad_bit);
6722                 free(ctsio->kern_data_ptr, M_CTL);
6723                 ctl_done((union ctl_io *)ctsio);
6724                 return (CTL_RETVAL_COMPLETE);
6725         }
6726
6727         /*
6728          * Decrement these before we call the page handler, since we may
6729          * end up getting called back one way or another before the handler
6730          * returns to this context.
6731          */
6732         *len_left -= page_index->page_len;
6733         *len_used += page_index->page_len;
6734
6735         retval = page_index->select_handler(ctsio, page_index,
6736                                             (uint8_t *)page_header);
6737
6738         /*
6739          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6740          * wait until this queued command completes to finish processing
6741          * the mode page.  If it returns anything other than
6742          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6743          * already set the sense information, freed the data pointer, and
6744          * completed the io for us.
6745          */
6746         if (retval != CTL_RETVAL_COMPLETE)
6747                 goto bailout_no_done;
6748
6749         /*
6750          * If the initiator sent us more than one page, parse the next one.
6751          */
6752         if (*len_left > 0)
6753                 goto do_next_page;
6754
6755         ctl_set_success(ctsio);
6756         free(ctsio->kern_data_ptr, M_CTL);
6757         ctl_done((union ctl_io *)ctsio);
6758
6759 bailout_no_done:
6760
6761         return (CTL_RETVAL_COMPLETE);
6762
6763 }
6764
6765 int
6766 ctl_mode_select(struct ctl_scsiio *ctsio)
6767 {
6768         int param_len, pf, sp;
6769         int header_size, bd_len;
6770         int len_left, len_used;
6771         struct ctl_page_index *page_index;
6772         struct ctl_lun *lun;
6773         int control_dev, page_len;
6774         union ctl_modepage_info *modepage_info;
6775         int retval;
6776
6777         pf = 0;
6778         sp = 0;
6779         page_len = 0;
6780         len_used = 0;
6781         len_left = 0;
6782         retval = 0;
6783         bd_len = 0;
6784         page_index = NULL;
6785
6786         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6787
6788         if (lun->be_lun->lun_type != T_DIRECT)
6789                 control_dev = 1;
6790         else
6791                 control_dev = 0;
6792
6793         switch (ctsio->cdb[0]) {
6794         case MODE_SELECT_6: {
6795                 struct scsi_mode_select_6 *cdb;
6796
6797                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6798
6799                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6800                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6801
6802                 param_len = cdb->length;
6803                 header_size = sizeof(struct scsi_mode_header_6);
6804                 break;
6805         }
6806         case MODE_SELECT_10: {
6807                 struct scsi_mode_select_10 *cdb;
6808
6809                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6810
6811                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6812                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6813
6814                 param_len = scsi_2btoul(cdb->length);
6815                 header_size = sizeof(struct scsi_mode_header_10);
6816                 break;
6817         }
6818         default:
6819                 ctl_set_invalid_opcode(ctsio);
6820                 ctl_done((union ctl_io *)ctsio);
6821                 return (CTL_RETVAL_COMPLETE);
6822                 break; /* NOTREACHED */
6823         }
6824
6825         /*
6826          * From SPC-3:
6827          * "A parameter list length of zero indicates that the Data-Out Buffer
6828          * shall be empty. This condition shall not be considered as an error."
6829          */
6830         if (param_len == 0) {
6831                 ctl_set_success(ctsio);
6832                 ctl_done((union ctl_io *)ctsio);
6833                 return (CTL_RETVAL_COMPLETE);
6834         }
6835
6836         /*
6837          * Since we'll hit this the first time through, prior to
6838          * allocation, we don't need to free a data buffer here.
6839          */
6840         if (param_len < header_size) {
6841                 ctl_set_param_len_error(ctsio);
6842                 ctl_done((union ctl_io *)ctsio);
6843                 return (CTL_RETVAL_COMPLETE);
6844         }
6845
6846         /*
6847          * Allocate the data buffer and grab the user's data.  In theory,
6848          * we shouldn't have to sanity check the parameter list length here
6849          * because the maximum size is 64K.  We should be able to malloc
6850          * that much without too many problems.
6851          */
6852         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6853                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6854                 ctsio->kern_data_len = param_len;
6855                 ctsio->kern_total_len = param_len;
6856                 ctsio->kern_data_resid = 0;
6857                 ctsio->kern_rel_offset = 0;
6858                 ctsio->kern_sg_entries = 0;
6859                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6860                 ctsio->be_move_done = ctl_config_move_done;
6861                 ctl_datamove((union ctl_io *)ctsio);
6862
6863                 return (CTL_RETVAL_COMPLETE);
6864         }
6865
6866         switch (ctsio->cdb[0]) {
6867         case MODE_SELECT_6: {
6868                 struct scsi_mode_header_6 *mh6;
6869
6870                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6871                 bd_len = mh6->blk_desc_len;
6872                 break;
6873         }
6874         case MODE_SELECT_10: {
6875                 struct scsi_mode_header_10 *mh10;
6876
6877                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6878                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6879                 break;
6880         }
6881         default:
6882                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6883                 break;
6884         }
6885
6886         if (param_len < (header_size + bd_len)) {
6887                 free(ctsio->kern_data_ptr, M_CTL);
6888                 ctl_set_param_len_error(ctsio);
6889                 ctl_done((union ctl_io *)ctsio);
6890                 return (CTL_RETVAL_COMPLETE);
6891         }
6892
6893         /*
6894          * Set the IO_CONT flag, so that if this I/O gets passed to
6895          * ctl_config_write_done(), it'll get passed back to
6896          * ctl_do_mode_select() for further processing, or completion if
6897          * we're all done.
6898          */
6899         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6900         ctsio->io_cont = ctl_do_mode_select;
6901
6902         modepage_info = (union ctl_modepage_info *)
6903                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6904
6905         memset(modepage_info, 0, sizeof(*modepage_info));
6906
6907         len_left = param_len - header_size - bd_len;
6908         len_used = header_size + bd_len;
6909
6910         modepage_info->header.len_left = len_left;
6911         modepage_info->header.len_used = len_used;
6912
6913         return (ctl_do_mode_select((union ctl_io *)ctsio));
6914 }
6915
6916 int
6917 ctl_mode_sense(struct ctl_scsiio *ctsio)
6918 {
6919         struct ctl_lun *lun;
6920         int pc, page_code, dbd, llba, subpage;
6921         int alloc_len, page_len, header_len, total_len;
6922         struct scsi_mode_block_descr *block_desc;
6923         struct ctl_page_index *page_index;
6924         int control_dev;
6925
6926         dbd = 0;
6927         llba = 0;
6928         block_desc = NULL;
6929         page_index = NULL;
6930
6931         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6932
6933         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6934
6935         if (lun->be_lun->lun_type != T_DIRECT)
6936                 control_dev = 1;
6937         else
6938                 control_dev = 0;
6939
6940         if (lun->flags & CTL_LUN_PR_RESERVED) {
6941                 uint32_t residx;
6942
6943                 /*
6944                  * XXX KDM need a lock here.
6945                  */
6946                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6947                 if ((lun->res_type == SPR_TYPE_EX_AC
6948                   && residx != lun->pr_res_idx)
6949                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
6950                    || lun->res_type == SPR_TYPE_EX_AC_AR)
6951                   && lun->pr_keys[residx] == 0)) {
6952                         ctl_set_reservation_conflict(ctsio);
6953                         ctl_done((union ctl_io *)ctsio);
6954                         return (CTL_RETVAL_COMPLETE);
6955                 }
6956         }
6957
6958         switch (ctsio->cdb[0]) {
6959         case MODE_SENSE_6: {
6960                 struct scsi_mode_sense_6 *cdb;
6961
6962                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6963
6964                 header_len = sizeof(struct scsi_mode_hdr_6);
6965                 if (cdb->byte2 & SMS_DBD)
6966                         dbd = 1;
6967                 else
6968                         header_len += sizeof(struct scsi_mode_block_descr);
6969
6970                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6971                 page_code = cdb->page & SMS_PAGE_CODE;
6972                 subpage = cdb->subpage;
6973                 alloc_len = cdb->length;
6974                 break;
6975         }
6976         case MODE_SENSE_10: {
6977                 struct scsi_mode_sense_10 *cdb;
6978
6979                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6980
6981                 header_len = sizeof(struct scsi_mode_hdr_10);
6982
6983                 if (cdb->byte2 & SMS_DBD)
6984                         dbd = 1;
6985                 else
6986                         header_len += sizeof(struct scsi_mode_block_descr);
6987                 if (cdb->byte2 & SMS10_LLBAA)
6988                         llba = 1;
6989                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6990                 page_code = cdb->page & SMS_PAGE_CODE;
6991                 subpage = cdb->subpage;
6992                 alloc_len = scsi_2btoul(cdb->length);
6993                 break;
6994         }
6995         default:
6996                 ctl_set_invalid_opcode(ctsio);
6997                 ctl_done((union ctl_io *)ctsio);
6998                 return (CTL_RETVAL_COMPLETE);
6999                 break; /* NOTREACHED */
7000         }
7001
7002         /*
7003          * We have to make a first pass through to calculate the size of
7004          * the pages that match the user's query.  Then we allocate enough
7005          * memory to hold it, and actually copy the data into the buffer.
7006          */
7007         switch (page_code) {
7008         case SMS_ALL_PAGES_PAGE: {
7009                 int i;
7010
7011                 page_len = 0;
7012
7013                 /*
7014                  * At the moment, values other than 0 and 0xff here are
7015                  * reserved according to SPC-3.
7016                  */
7017                 if ((subpage != SMS_SUBPAGE_PAGE_0)
7018                  && (subpage != SMS_SUBPAGE_ALL)) {
7019                         ctl_set_invalid_field(ctsio,
7020                                               /*sks_valid*/ 1,
7021                                               /*command*/ 1,
7022                                               /*field*/ 3,
7023                                               /*bit_valid*/ 0,
7024                                               /*bit*/ 0);
7025                         ctl_done((union ctl_io *)ctsio);
7026                         return (CTL_RETVAL_COMPLETE);
7027                 }
7028
7029                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7030                         if ((control_dev != 0)
7031                          && (lun->mode_pages.index[i].page_flags &
7032                              CTL_PAGE_FLAG_DISK_ONLY))
7033                                 continue;
7034
7035                         /*
7036                          * We don't use this subpage if the user didn't
7037                          * request all subpages.
7038                          */
7039                         if ((lun->mode_pages.index[i].subpage != 0)
7040                          && (subpage == SMS_SUBPAGE_PAGE_0))
7041                                 continue;
7042
7043 #if 0
7044                         printf("found page %#x len %d\n",
7045                                lun->mode_pages.index[i].page_code &
7046                                SMPH_PC_MASK,
7047                                lun->mode_pages.index[i].page_len);
7048 #endif
7049                         page_len += lun->mode_pages.index[i].page_len;
7050                 }
7051                 break;
7052         }
7053         default: {
7054                 int i;
7055
7056                 page_len = 0;
7057
7058                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7059                         /* Look for the right page code */
7060                         if ((lun->mode_pages.index[i].page_code &
7061                              SMPH_PC_MASK) != page_code)
7062                                 continue;
7063
7064                         /* Look for the right subpage or the subpage wildcard*/
7065                         if ((lun->mode_pages.index[i].subpage != subpage)
7066                          && (subpage != SMS_SUBPAGE_ALL))
7067                                 continue;
7068
7069                         /* Make sure the page is supported for this dev type */
7070                         if ((control_dev != 0)
7071                          && (lun->mode_pages.index[i].page_flags &
7072                              CTL_PAGE_FLAG_DISK_ONLY))
7073                                 continue;
7074
7075 #if 0
7076                         printf("found page %#x len %d\n",
7077                                lun->mode_pages.index[i].page_code &
7078                                SMPH_PC_MASK,
7079                                lun->mode_pages.index[i].page_len);
7080 #endif
7081
7082                         page_len += lun->mode_pages.index[i].page_len;
7083                 }
7084
7085                 if (page_len == 0) {
7086                         ctl_set_invalid_field(ctsio,
7087                                               /*sks_valid*/ 1,
7088                                               /*command*/ 1,
7089                                               /*field*/ 2,
7090                                               /*bit_valid*/ 1,
7091                                               /*bit*/ 5);
7092                         ctl_done((union ctl_io *)ctsio);
7093                         return (CTL_RETVAL_COMPLETE);
7094                 }
7095                 break;
7096         }
7097         }
7098
7099         total_len = header_len + page_len;
7100 #if 0
7101         printf("header_len = %d, page_len = %d, total_len = %d\n",
7102                header_len, page_len, total_len);
7103 #endif
7104
7105         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7106         ctsio->kern_sg_entries = 0;
7107         ctsio->kern_data_resid = 0;
7108         ctsio->kern_rel_offset = 0;
7109         if (total_len < alloc_len) {
7110                 ctsio->residual = alloc_len - total_len;
7111                 ctsio->kern_data_len = total_len;
7112                 ctsio->kern_total_len = total_len;
7113         } else {
7114                 ctsio->residual = 0;
7115                 ctsio->kern_data_len = alloc_len;
7116                 ctsio->kern_total_len = alloc_len;
7117         }
7118
7119         switch (ctsio->cdb[0]) {
7120         case MODE_SENSE_6: {
7121                 struct scsi_mode_hdr_6 *header;
7122
7123                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7124
7125                 header->datalen = ctl_min(total_len - 1, 254);
7126                 if (control_dev == 0) {
7127                         header->dev_specific = 0x10; /* DPOFUA */
7128                         if ((lun->flags & CTL_LUN_READONLY) ||
7129                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7130                             .eca_and_aen & SCP_SWP) != 0)
7131                                     header->dev_specific |= 0x80; /* WP */
7132                 }
7133                 if (dbd)
7134                         header->block_descr_len = 0;
7135                 else
7136                         header->block_descr_len =
7137                                 sizeof(struct scsi_mode_block_descr);
7138                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7139                 break;
7140         }
7141         case MODE_SENSE_10: {
7142                 struct scsi_mode_hdr_10 *header;
7143                 int datalen;
7144
7145                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7146
7147                 datalen = ctl_min(total_len - 2, 65533);
7148                 scsi_ulto2b(datalen, header->datalen);
7149                 if (control_dev == 0) {
7150                         header->dev_specific = 0x10; /* DPOFUA */
7151                         if ((lun->flags & CTL_LUN_READONLY) ||
7152                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7153                             .eca_and_aen & SCP_SWP) != 0)
7154                                     header->dev_specific |= 0x80; /* WP */
7155                 }
7156                 if (dbd)
7157                         scsi_ulto2b(0, header->block_descr_len);
7158                 else
7159                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7160                                     header->block_descr_len);
7161                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7162                 break;
7163         }
7164         default:
7165                 panic("invalid CDB type %#x", ctsio->cdb[0]);
7166                 break; /* NOTREACHED */
7167         }
7168
7169         /*
7170          * If we've got a disk, use its blocksize in the block
7171          * descriptor.  Otherwise, just set it to 0.
7172          */
7173         if (dbd == 0) {
7174                 if (control_dev == 0)
7175                         scsi_ulto3b(lun->be_lun->blocksize,
7176                                     block_desc->block_len);
7177                 else
7178                         scsi_ulto3b(0, block_desc->block_len);
7179         }
7180
7181         switch (page_code) {
7182         case SMS_ALL_PAGES_PAGE: {
7183                 int i, data_used;
7184
7185                 data_used = header_len;
7186                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7187                         struct ctl_page_index *page_index;
7188
7189                         page_index = &lun->mode_pages.index[i];
7190
7191                         if ((control_dev != 0)
7192                          && (page_index->page_flags &
7193                             CTL_PAGE_FLAG_DISK_ONLY))
7194                                 continue;
7195
7196                         /*
7197                          * We don't use this subpage if the user didn't
7198                          * request all subpages.  We already checked (above)
7199                          * to make sure the user only specified a subpage
7200                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7201                          */
7202                         if ((page_index->subpage != 0)
7203                          && (subpage == SMS_SUBPAGE_PAGE_0))
7204                                 continue;
7205
7206                         /*
7207                          * Call the handler, if it exists, to update the
7208                          * page to the latest values.
7209                          */
7210                         if (page_index->sense_handler != NULL)
7211                                 page_index->sense_handler(ctsio, page_index,pc);
7212
7213                         memcpy(ctsio->kern_data_ptr + data_used,
7214                                page_index->page_data +
7215                                (page_index->page_len * pc),
7216                                page_index->page_len);
7217                         data_used += page_index->page_len;
7218                 }
7219                 break;
7220         }
7221         default: {
7222                 int i, data_used;
7223
7224                 data_used = header_len;
7225
7226                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7227                         struct ctl_page_index *page_index;
7228
7229                         page_index = &lun->mode_pages.index[i];
7230
7231                         /* Look for the right page code */
7232                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7233                                 continue;
7234
7235                         /* Look for the right subpage or the subpage wildcard*/
7236                         if ((page_index->subpage != subpage)
7237                          && (subpage != SMS_SUBPAGE_ALL))
7238                                 continue;
7239
7240                         /* Make sure the page is supported for this dev type */
7241                         if ((control_dev != 0)
7242                          && (page_index->page_flags &
7243                              CTL_PAGE_FLAG_DISK_ONLY))
7244                                 continue;
7245
7246                         /*
7247                          * Call the handler, if it exists, to update the
7248                          * page to the latest values.
7249                          */
7250                         if (page_index->sense_handler != NULL)
7251                                 page_index->sense_handler(ctsio, page_index,pc);
7252
7253                         memcpy(ctsio->kern_data_ptr + data_used,
7254                                page_index->page_data +
7255                                (page_index->page_len * pc),
7256                                page_index->page_len);
7257                         data_used += page_index->page_len;
7258                 }
7259                 break;
7260         }
7261         }
7262
7263         ctsio->scsi_status = SCSI_STATUS_OK;
7264
7265         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7266         ctsio->be_move_done = ctl_config_move_done;
7267         ctl_datamove((union ctl_io *)ctsio);
7268
7269         return (CTL_RETVAL_COMPLETE);
7270 }
7271
7272 int
7273 ctl_read_capacity(struct ctl_scsiio *ctsio)
7274 {
7275         struct scsi_read_capacity *cdb;
7276         struct scsi_read_capacity_data *data;
7277         struct ctl_lun *lun;
7278         uint32_t lba;
7279
7280         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7281
7282         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7283
7284         lba = scsi_4btoul(cdb->addr);
7285         if (((cdb->pmi & SRC_PMI) == 0)
7286          && (lba != 0)) {
7287                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7288                                       /*sks_valid*/ 1,
7289                                       /*command*/ 1,
7290                                       /*field*/ 2,
7291                                       /*bit_valid*/ 0,
7292                                       /*bit*/ 0);
7293                 ctl_done((union ctl_io *)ctsio);
7294                 return (CTL_RETVAL_COMPLETE);
7295         }
7296
7297         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7298
7299         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7300         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7301         ctsio->residual = 0;
7302         ctsio->kern_data_len = sizeof(*data);
7303         ctsio->kern_total_len = sizeof(*data);
7304         ctsio->kern_data_resid = 0;
7305         ctsio->kern_rel_offset = 0;
7306         ctsio->kern_sg_entries = 0;
7307
7308         /*
7309          * If the maximum LBA is greater than 0xfffffffe, the user must
7310          * issue a SERVICE ACTION IN (16) command, with the read capacity
7311          * serivce action set.
7312          */
7313         if (lun->be_lun->maxlba > 0xfffffffe)
7314                 scsi_ulto4b(0xffffffff, data->addr);
7315         else
7316                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7317
7318         /*
7319          * XXX KDM this may not be 512 bytes...
7320          */
7321         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7322
7323         ctsio->scsi_status = SCSI_STATUS_OK;
7324
7325         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7326         ctsio->be_move_done = ctl_config_move_done;
7327         ctl_datamove((union ctl_io *)ctsio);
7328
7329         return (CTL_RETVAL_COMPLETE);
7330 }
7331
7332 int
7333 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7334 {
7335         struct scsi_read_capacity_16 *cdb;
7336         struct scsi_read_capacity_data_long *data;
7337         struct ctl_lun *lun;
7338         uint64_t lba;
7339         uint32_t alloc_len;
7340
7341         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7342
7343         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7344
7345         alloc_len = scsi_4btoul(cdb->alloc_len);
7346         lba = scsi_8btou64(cdb->addr);
7347
7348         if ((cdb->reladr & SRC16_PMI)
7349          && (lba != 0)) {
7350                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7351                                       /*sks_valid*/ 1,
7352                                       /*command*/ 1,
7353                                       /*field*/ 2,
7354                                       /*bit_valid*/ 0,
7355                                       /*bit*/ 0);
7356                 ctl_done((union ctl_io *)ctsio);
7357                 return (CTL_RETVAL_COMPLETE);
7358         }
7359
7360         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7361
7362         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7363         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7364
7365         if (sizeof(*data) < alloc_len) {
7366                 ctsio->residual = alloc_len - sizeof(*data);
7367                 ctsio->kern_data_len = sizeof(*data);
7368                 ctsio->kern_total_len = sizeof(*data);
7369         } else {
7370                 ctsio->residual = 0;
7371                 ctsio->kern_data_len = alloc_len;
7372                 ctsio->kern_total_len = alloc_len;
7373         }
7374         ctsio->kern_data_resid = 0;
7375         ctsio->kern_rel_offset = 0;
7376         ctsio->kern_sg_entries = 0;
7377
7378         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7379         /* XXX KDM this may not be 512 bytes... */
7380         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7381         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7382         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7383         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7384                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7385
7386         ctsio->scsi_status = SCSI_STATUS_OK;
7387
7388         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7389         ctsio->be_move_done = ctl_config_move_done;
7390         ctl_datamove((union ctl_io *)ctsio);
7391
7392         return (CTL_RETVAL_COMPLETE);
7393 }
7394
7395 int
7396 ctl_read_defect(struct ctl_scsiio *ctsio)
7397 {
7398         struct scsi_read_defect_data_10 *ccb10;
7399         struct scsi_read_defect_data_12 *ccb12;
7400         struct scsi_read_defect_data_hdr_10 *data10;
7401         struct scsi_read_defect_data_hdr_12 *data12;
7402         struct ctl_lun *lun;
7403         uint32_t alloc_len, data_len;
7404         uint8_t format;
7405
7406         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7407
7408         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7409         if (lun->flags & CTL_LUN_PR_RESERVED) {
7410                 uint32_t residx;
7411
7412                 /*
7413                  * XXX KDM need a lock here.
7414                  */
7415                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
7416                 if ((lun->res_type == SPR_TYPE_EX_AC
7417                   && residx != lun->pr_res_idx)
7418                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
7419                    || lun->res_type == SPR_TYPE_EX_AC_AR)
7420                   && lun->pr_keys[residx] == 0)) {
7421                         ctl_set_reservation_conflict(ctsio);
7422                         ctl_done((union ctl_io *)ctsio);
7423                         return (CTL_RETVAL_COMPLETE);
7424                 }
7425         }
7426
7427         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7428                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7429                 format = ccb10->format;
7430                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7431                 data_len = sizeof(*data10);
7432         } else {
7433                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7434                 format = ccb12->format;
7435                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7436                 data_len = sizeof(*data12);
7437         }
7438         if (alloc_len == 0) {
7439                 ctl_set_success(ctsio);
7440                 ctl_done((union ctl_io *)ctsio);
7441                 return (CTL_RETVAL_COMPLETE);
7442         }
7443
7444         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7445         if (data_len < alloc_len) {
7446                 ctsio->residual = alloc_len - data_len;
7447                 ctsio->kern_data_len = data_len;
7448                 ctsio->kern_total_len = data_len;
7449         } else {
7450                 ctsio->residual = 0;
7451                 ctsio->kern_data_len = alloc_len;
7452                 ctsio->kern_total_len = alloc_len;
7453         }
7454         ctsio->kern_data_resid = 0;
7455         ctsio->kern_rel_offset = 0;
7456         ctsio->kern_sg_entries = 0;
7457
7458         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7459                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7460                     ctsio->kern_data_ptr;
7461                 data10->format = format;
7462                 scsi_ulto2b(0, data10->length);
7463         } else {
7464                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7465                     ctsio->kern_data_ptr;
7466                 data12->format = format;
7467                 scsi_ulto2b(0, data12->generation);
7468                 scsi_ulto4b(0, data12->length);
7469         }
7470
7471         ctsio->scsi_status = SCSI_STATUS_OK;
7472         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7473         ctsio->be_move_done = ctl_config_move_done;
7474         ctl_datamove((union ctl_io *)ctsio);
7475         return (CTL_RETVAL_COMPLETE);
7476 }
7477
7478 int
7479 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7480 {
7481         struct scsi_maintenance_in *cdb;
7482         int retval;
7483         int alloc_len, ext, total_len = 0, g, p, pc, pg;
7484         int num_target_port_groups, num_target_ports, single;
7485         struct ctl_lun *lun;
7486         struct ctl_softc *softc;
7487         struct ctl_port *port;
7488         struct scsi_target_group_data *rtg_ptr;
7489         struct scsi_target_group_data_extended *rtg_ext_ptr;
7490         struct scsi_target_port_group_descriptor *tpg_desc;
7491
7492         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7493
7494         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7495         softc = control_softc;
7496         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7497
7498         retval = CTL_RETVAL_COMPLETE;
7499
7500         switch (cdb->byte2 & STG_PDF_MASK) {
7501         case STG_PDF_LENGTH:
7502                 ext = 0;
7503                 break;
7504         case STG_PDF_EXTENDED:
7505                 ext = 1;
7506                 break;
7507         default:
7508                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7509                                       /*sks_valid*/ 1,
7510                                       /*command*/ 1,
7511                                       /*field*/ 2,
7512                                       /*bit_valid*/ 1,
7513                                       /*bit*/ 5);
7514                 ctl_done((union ctl_io *)ctsio);
7515                 return(retval);
7516         }
7517
7518         single = ctl_is_single;
7519         if (single)
7520                 num_target_port_groups = 1;
7521         else
7522                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7523         num_target_ports = 0;
7524         mtx_lock(&softc->ctl_lock);
7525         STAILQ_FOREACH(port, &softc->port_list, links) {
7526                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7527                         continue;
7528                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7529                         continue;
7530                 num_target_ports++;
7531         }
7532         mtx_unlock(&softc->ctl_lock);
7533
7534         if (ext)
7535                 total_len = sizeof(struct scsi_target_group_data_extended);
7536         else
7537                 total_len = sizeof(struct scsi_target_group_data);
7538         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7539                 num_target_port_groups +
7540             sizeof(struct scsi_target_port_descriptor) *
7541                 num_target_ports * num_target_port_groups;
7542
7543         alloc_len = scsi_4btoul(cdb->length);
7544
7545         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7546
7547         ctsio->kern_sg_entries = 0;
7548
7549         if (total_len < alloc_len) {
7550                 ctsio->residual = alloc_len - total_len;
7551                 ctsio->kern_data_len = total_len;
7552                 ctsio->kern_total_len = total_len;
7553         } else {
7554                 ctsio->residual = 0;
7555                 ctsio->kern_data_len = alloc_len;
7556                 ctsio->kern_total_len = alloc_len;
7557         }
7558         ctsio->kern_data_resid = 0;
7559         ctsio->kern_rel_offset = 0;
7560
7561         if (ext) {
7562                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7563                     ctsio->kern_data_ptr;
7564                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7565                 rtg_ext_ptr->format_type = 0x10;
7566                 rtg_ext_ptr->implicit_transition_time = 0;
7567                 tpg_desc = &rtg_ext_ptr->groups[0];
7568         } else {
7569                 rtg_ptr = (struct scsi_target_group_data *)
7570                     ctsio->kern_data_ptr;
7571                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7572                 tpg_desc = &rtg_ptr->groups[0];
7573         }
7574
7575         pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7576         mtx_lock(&softc->ctl_lock);
7577         for (g = 0; g < num_target_port_groups; g++) {
7578                 if (g == pg)
7579                         tpg_desc->pref_state = TPG_PRIMARY |
7580                             TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7581                 else
7582                         tpg_desc->pref_state =
7583                             TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7584                 tpg_desc->support = TPG_AO_SUP;
7585                 if (!single)
7586                         tpg_desc->support |= TPG_AN_SUP;
7587                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7588                 tpg_desc->status = TPG_IMPLICIT;
7589                 pc = 0;
7590                 STAILQ_FOREACH(port, &softc->port_list, links) {
7591                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7592                                 continue;
7593                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7594                             CTL_MAX_LUNS)
7595                                 continue;
7596                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7597                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7598                             relative_target_port_identifier);
7599                         pc++;
7600                 }
7601                 tpg_desc->target_port_count = pc;
7602                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7603                     &tpg_desc->descriptors[pc];
7604         }
7605         mtx_unlock(&softc->ctl_lock);
7606
7607         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7608         ctsio->be_move_done = ctl_config_move_done;
7609
7610         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7611                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7612                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7613                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7614                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7615
7616         ctl_datamove((union ctl_io *)ctsio);
7617         return(retval);
7618 }
7619
7620 int
7621 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7622 {
7623         struct ctl_lun *lun;
7624         struct scsi_report_supported_opcodes *cdb;
7625         const struct ctl_cmd_entry *entry, *sentry;
7626         struct scsi_report_supported_opcodes_all *all;
7627         struct scsi_report_supported_opcodes_descr *descr;
7628         struct scsi_report_supported_opcodes_one *one;
7629         int retval;
7630         int alloc_len, total_len;
7631         int opcode, service_action, i, j, num;
7632
7633         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7634
7635         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7636         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7637
7638         retval = CTL_RETVAL_COMPLETE;
7639
7640         opcode = cdb->requested_opcode;
7641         service_action = scsi_2btoul(cdb->requested_service_action);
7642         switch (cdb->options & RSO_OPTIONS_MASK) {
7643         case RSO_OPTIONS_ALL:
7644                 num = 0;
7645                 for (i = 0; i < 256; i++) {
7646                         entry = &ctl_cmd_table[i];
7647                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7648                                 for (j = 0; j < 32; j++) {
7649                                         sentry = &((const struct ctl_cmd_entry *)
7650                                             entry->execute)[j];
7651                                         if (ctl_cmd_applicable(
7652                                             lun->be_lun->lun_type, sentry))
7653                                                 num++;
7654                                 }
7655                         } else {
7656                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7657                                     entry))
7658                                         num++;
7659                         }
7660                 }
7661                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7662                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7663                 break;
7664         case RSO_OPTIONS_OC:
7665                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7666                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7667                                               /*sks_valid*/ 1,
7668                                               /*command*/ 1,
7669                                               /*field*/ 2,
7670                                               /*bit_valid*/ 1,
7671                                               /*bit*/ 2);
7672                         ctl_done((union ctl_io *)ctsio);
7673                         return (CTL_RETVAL_COMPLETE);
7674                 }
7675                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7676                 break;
7677         case RSO_OPTIONS_OC_SA:
7678                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7679                     service_action >= 32) {
7680                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7681                                               /*sks_valid*/ 1,
7682                                               /*command*/ 1,
7683                                               /*field*/ 2,
7684                                               /*bit_valid*/ 1,
7685                                               /*bit*/ 2);
7686                         ctl_done((union ctl_io *)ctsio);
7687                         return (CTL_RETVAL_COMPLETE);
7688                 }
7689                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7690                 break;
7691         default:
7692                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7693                                       /*sks_valid*/ 1,
7694                                       /*command*/ 1,
7695                                       /*field*/ 2,
7696                                       /*bit_valid*/ 1,
7697                                       /*bit*/ 2);
7698                 ctl_done((union ctl_io *)ctsio);
7699                 return (CTL_RETVAL_COMPLETE);
7700         }
7701
7702         alloc_len = scsi_4btoul(cdb->length);
7703
7704         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7705
7706         ctsio->kern_sg_entries = 0;
7707
7708         if (total_len < alloc_len) {
7709                 ctsio->residual = alloc_len - total_len;
7710                 ctsio->kern_data_len = total_len;
7711                 ctsio->kern_total_len = total_len;
7712         } else {
7713                 ctsio->residual = 0;
7714                 ctsio->kern_data_len = alloc_len;
7715                 ctsio->kern_total_len = alloc_len;
7716         }
7717         ctsio->kern_data_resid = 0;
7718         ctsio->kern_rel_offset = 0;
7719
7720         switch (cdb->options & RSO_OPTIONS_MASK) {
7721         case RSO_OPTIONS_ALL:
7722                 all = (struct scsi_report_supported_opcodes_all *)
7723                     ctsio->kern_data_ptr;
7724                 num = 0;
7725                 for (i = 0; i < 256; i++) {
7726                         entry = &ctl_cmd_table[i];
7727                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7728                                 for (j = 0; j < 32; j++) {
7729                                         sentry = &((const struct ctl_cmd_entry *)
7730                                             entry->execute)[j];
7731                                         if (!ctl_cmd_applicable(
7732                                             lun->be_lun->lun_type, sentry))
7733                                                 continue;
7734                                         descr = &all->descr[num++];
7735                                         descr->opcode = i;
7736                                         scsi_ulto2b(j, descr->service_action);
7737                                         descr->flags = RSO_SERVACTV;
7738                                         scsi_ulto2b(sentry->length,
7739                                             descr->cdb_length);
7740                                 }
7741                         } else {
7742                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7743                                     entry))
7744                                         continue;
7745                                 descr = &all->descr[num++];
7746                                 descr->opcode = i;
7747                                 scsi_ulto2b(0, descr->service_action);
7748                                 descr->flags = 0;
7749                                 scsi_ulto2b(entry->length, descr->cdb_length);
7750                         }
7751                 }
7752                 scsi_ulto4b(
7753                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7754                     all->length);
7755                 break;
7756         case RSO_OPTIONS_OC:
7757                 one = (struct scsi_report_supported_opcodes_one *)
7758                     ctsio->kern_data_ptr;
7759                 entry = &ctl_cmd_table[opcode];
7760                 goto fill_one;
7761         case RSO_OPTIONS_OC_SA:
7762                 one = (struct scsi_report_supported_opcodes_one *)
7763                     ctsio->kern_data_ptr;
7764                 entry = &ctl_cmd_table[opcode];
7765                 entry = &((const struct ctl_cmd_entry *)
7766                     entry->execute)[service_action];
7767 fill_one:
7768                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7769                         one->support = 3;
7770                         scsi_ulto2b(entry->length, one->cdb_length);
7771                         one->cdb_usage[0] = opcode;
7772                         memcpy(&one->cdb_usage[1], entry->usage,
7773                             entry->length - 1);
7774                 } else
7775                         one->support = 1;
7776                 break;
7777         }
7778
7779         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7780         ctsio->be_move_done = ctl_config_move_done;
7781
7782         ctl_datamove((union ctl_io *)ctsio);
7783         return(retval);
7784 }
7785
7786 int
7787 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7788 {
7789         struct ctl_lun *lun;
7790         struct scsi_report_supported_tmf *cdb;
7791         struct scsi_report_supported_tmf_data *data;
7792         int retval;
7793         int alloc_len, total_len;
7794
7795         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7796
7797         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7798         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7799
7800         retval = CTL_RETVAL_COMPLETE;
7801
7802         total_len = sizeof(struct scsi_report_supported_tmf_data);
7803         alloc_len = scsi_4btoul(cdb->length);
7804
7805         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7806
7807         ctsio->kern_sg_entries = 0;
7808
7809         if (total_len < alloc_len) {
7810                 ctsio->residual = alloc_len - total_len;
7811                 ctsio->kern_data_len = total_len;
7812                 ctsio->kern_total_len = total_len;
7813         } else {
7814                 ctsio->residual = 0;
7815                 ctsio->kern_data_len = alloc_len;
7816                 ctsio->kern_total_len = alloc_len;
7817         }
7818         ctsio->kern_data_resid = 0;
7819         ctsio->kern_rel_offset = 0;
7820
7821         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7822         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7823         data->byte2 |= RST_ITNRS;
7824
7825         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7826         ctsio->be_move_done = ctl_config_move_done;
7827
7828         ctl_datamove((union ctl_io *)ctsio);
7829         return (retval);
7830 }
7831
7832 int
7833 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7834 {
7835         struct ctl_lun *lun;
7836         struct scsi_report_timestamp *cdb;
7837         struct scsi_report_timestamp_data *data;
7838         struct timeval tv;
7839         int64_t timestamp;
7840         int retval;
7841         int alloc_len, total_len;
7842
7843         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7844
7845         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7846         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7847
7848         retval = CTL_RETVAL_COMPLETE;
7849
7850         total_len = sizeof(struct scsi_report_timestamp_data);
7851         alloc_len = scsi_4btoul(cdb->length);
7852
7853         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7854
7855         ctsio->kern_sg_entries = 0;
7856
7857         if (total_len < alloc_len) {
7858                 ctsio->residual = alloc_len - total_len;
7859                 ctsio->kern_data_len = total_len;
7860                 ctsio->kern_total_len = total_len;
7861         } else {
7862                 ctsio->residual = 0;
7863                 ctsio->kern_data_len = alloc_len;
7864                 ctsio->kern_total_len = alloc_len;
7865         }
7866         ctsio->kern_data_resid = 0;
7867         ctsio->kern_rel_offset = 0;
7868
7869         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7870         scsi_ulto2b(sizeof(*data) - 2, data->length);
7871         data->origin = RTS_ORIG_OUTSIDE;
7872         getmicrotime(&tv);
7873         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7874         scsi_ulto4b(timestamp >> 16, data->timestamp);
7875         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7876
7877         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7878         ctsio->be_move_done = ctl_config_move_done;
7879
7880         ctl_datamove((union ctl_io *)ctsio);
7881         return (retval);
7882 }
7883
7884 int
7885 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7886 {
7887         struct scsi_per_res_in *cdb;
7888         int alloc_len, total_len = 0;
7889         /* struct scsi_per_res_in_rsrv in_data; */
7890         struct ctl_lun *lun;
7891         struct ctl_softc *softc;
7892
7893         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7894
7895         softc = control_softc;
7896
7897         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7898
7899         alloc_len = scsi_2btoul(cdb->length);
7900
7901         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7902
7903 retry:
7904         mtx_lock(&lun->lun_lock);
7905         switch (cdb->action) {
7906         case SPRI_RK: /* read keys */
7907                 total_len = sizeof(struct scsi_per_res_in_keys) +
7908                         lun->pr_key_count *
7909                         sizeof(struct scsi_per_res_key);
7910                 break;
7911         case SPRI_RR: /* read reservation */
7912                 if (lun->flags & CTL_LUN_PR_RESERVED)
7913                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7914                 else
7915                         total_len = sizeof(struct scsi_per_res_in_header);
7916                 break;
7917         case SPRI_RC: /* report capabilities */
7918                 total_len = sizeof(struct scsi_per_res_cap);
7919                 break;
7920         case SPRI_RS: /* read full status */
7921                 total_len = sizeof(struct scsi_per_res_in_header) +
7922                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7923                     lun->pr_key_count;
7924                 break;
7925         default:
7926                 panic("Invalid PR type %x", cdb->action);
7927         }
7928         mtx_unlock(&lun->lun_lock);
7929
7930         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7931
7932         if (total_len < alloc_len) {
7933                 ctsio->residual = alloc_len - total_len;
7934                 ctsio->kern_data_len = total_len;
7935                 ctsio->kern_total_len = total_len;
7936         } else {
7937                 ctsio->residual = 0;
7938                 ctsio->kern_data_len = alloc_len;
7939                 ctsio->kern_total_len = alloc_len;
7940         }
7941
7942         ctsio->kern_data_resid = 0;
7943         ctsio->kern_rel_offset = 0;
7944         ctsio->kern_sg_entries = 0;
7945
7946         mtx_lock(&lun->lun_lock);
7947         switch (cdb->action) {
7948         case SPRI_RK: { // read keys
7949         struct scsi_per_res_in_keys *res_keys;
7950                 int i, key_count;
7951
7952                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7953
7954                 /*
7955                  * We had to drop the lock to allocate our buffer, which
7956                  * leaves time for someone to come in with another
7957                  * persistent reservation.  (That is unlikely, though,
7958                  * since this should be the only persistent reservation
7959                  * command active right now.)
7960                  */
7961                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7962                     (lun->pr_key_count *
7963                      sizeof(struct scsi_per_res_key)))){
7964                         mtx_unlock(&lun->lun_lock);
7965                         free(ctsio->kern_data_ptr, M_CTL);
7966                         printf("%s: reservation length changed, retrying\n",
7967                                __func__);
7968                         goto retry;
7969                 }
7970
7971                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7972
7973                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7974                              lun->pr_key_count, res_keys->header.length);
7975
7976                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7977                         if (lun->pr_keys[i] == 0)
7978                                 continue;
7979
7980                         /*
7981                          * We used lun->pr_key_count to calculate the
7982                          * size to allocate.  If it turns out the number of
7983                          * initiators with the registered flag set is
7984                          * larger than that (i.e. they haven't been kept in
7985                          * sync), we've got a problem.
7986                          */
7987                         if (key_count >= lun->pr_key_count) {
7988 #ifdef NEEDTOPORT
7989                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7990                                             CTL_PR_ERROR,
7991                                             csevent_LogType_Fault,
7992                                             csevent_AlertLevel_Yellow,
7993                                             csevent_FRU_ShelfController,
7994                                             csevent_FRU_Firmware,
7995                                         csevent_FRU_Unknown,
7996                                             "registered keys %d >= key "
7997                                             "count %d", key_count,
7998                                             lun->pr_key_count);
7999 #endif
8000                                 key_count++;
8001                                 continue;
8002                         }
8003                         scsi_u64to8b(lun->pr_keys[i],
8004                             res_keys->keys[key_count].key);
8005                         key_count++;
8006                 }
8007                 break;
8008         }
8009         case SPRI_RR: { // read reservation
8010                 struct scsi_per_res_in_rsrv *res;
8011                 int tmp_len, header_only;
8012
8013                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
8014
8015                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
8016
8017                 if (lun->flags & CTL_LUN_PR_RESERVED)
8018                 {
8019                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
8020                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
8021                                     res->header.length);
8022                         header_only = 0;
8023                 } else {
8024                         tmp_len = sizeof(struct scsi_per_res_in_header);
8025                         scsi_ulto4b(0, res->header.length);
8026                         header_only = 1;
8027                 }
8028
8029                 /*
8030                  * We had to drop the lock to allocate our buffer, which
8031                  * leaves time for someone to come in with another
8032                  * persistent reservation.  (That is unlikely, though,
8033                  * since this should be the only persistent reservation
8034                  * command active right now.)
8035                  */
8036                 if (tmp_len != total_len) {
8037                         mtx_unlock(&lun->lun_lock);
8038                         free(ctsio->kern_data_ptr, M_CTL);
8039                         printf("%s: reservation status changed, retrying\n",
8040                                __func__);
8041                         goto retry;
8042                 }
8043
8044                 /*
8045                  * No reservation held, so we're done.
8046                  */
8047                 if (header_only != 0)
8048                         break;
8049
8050                 /*
8051                  * If the registration is an All Registrants type, the key
8052                  * is 0, since it doesn't really matter.
8053                  */
8054                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8055                         scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
8056                             res->data.reservation);
8057                 }
8058                 res->data.scopetype = lun->res_type;
8059                 break;
8060         }
8061         case SPRI_RC:     //report capabilities
8062         {
8063                 struct scsi_per_res_cap *res_cap;
8064                 uint16_t type_mask;
8065
8066                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
8067                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
8068                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
8069                 type_mask = SPRI_TM_WR_EX_AR |
8070                             SPRI_TM_EX_AC_RO |
8071                             SPRI_TM_WR_EX_RO |
8072                             SPRI_TM_EX_AC |
8073                             SPRI_TM_WR_EX |
8074                             SPRI_TM_EX_AC_AR;
8075                 scsi_ulto2b(type_mask, res_cap->type_mask);
8076                 break;
8077         }
8078         case SPRI_RS: { // read full status
8079                 struct scsi_per_res_in_full *res_status;
8080                 struct scsi_per_res_in_full_desc *res_desc;
8081                 struct ctl_port *port;
8082                 int i, len;
8083
8084                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8085
8086                 /*
8087                  * We had to drop the lock to allocate our buffer, which
8088                  * leaves time for someone to come in with another
8089                  * persistent reservation.  (That is unlikely, though,
8090                  * since this should be the only persistent reservation
8091                  * command active right now.)
8092                  */
8093                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
8094                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8095                      lun->pr_key_count)){
8096                         mtx_unlock(&lun->lun_lock);
8097                         free(ctsio->kern_data_ptr, M_CTL);
8098                         printf("%s: reservation length changed, retrying\n",
8099                                __func__);
8100                         goto retry;
8101                 }
8102
8103                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8104
8105                 res_desc = &res_status->desc[0];
8106                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8107                         if (lun->pr_keys[i] == 0)
8108                                 continue;
8109
8110                         scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
8111                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8112                             (lun->pr_res_idx == i ||
8113                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8114                                 res_desc->flags = SPRI_FULL_R_HOLDER;
8115                                 res_desc->scopetype = lun->res_type;
8116                         }
8117                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8118                             res_desc->rel_trgt_port_id);
8119                         len = 0;
8120                         port = softc->ctl_ports[
8121                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8122                         if (port != NULL)
8123                                 len = ctl_create_iid(port,
8124                                     i % CTL_MAX_INIT_PER_PORT,
8125                                     res_desc->transport_id);
8126                         scsi_ulto4b(len, res_desc->additional_length);
8127                         res_desc = (struct scsi_per_res_in_full_desc *)
8128                             &res_desc->transport_id[len];
8129                 }
8130                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8131                     res_status->header.length);
8132                 break;
8133         }
8134         default:
8135                 /*
8136                  * This is a bug, because we just checked for this above,
8137                  * and should have returned an error.
8138                  */
8139                 panic("Invalid PR type %x", cdb->action);
8140                 break; /* NOTREACHED */
8141         }
8142         mtx_unlock(&lun->lun_lock);
8143
8144         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8145         ctsio->be_move_done = ctl_config_move_done;
8146
8147         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8148                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8149                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8150                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8151                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8152
8153         ctl_datamove((union ctl_io *)ctsio);
8154
8155         return (CTL_RETVAL_COMPLETE);
8156 }
8157
8158 /*
8159  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8160  * it should return.
8161  */
8162 static int
8163 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8164                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8165                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8166                 struct scsi_per_res_out_parms* param)
8167 {
8168         union ctl_ha_msg persis_io;
8169         int retval, i;
8170         int isc_retval;
8171
8172         retval = 0;
8173
8174         mtx_lock(&lun->lun_lock);
8175         if (sa_res_key == 0) {
8176                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8177                         /* validate scope and type */
8178                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8179                              SPR_LU_SCOPE) {
8180                                 mtx_unlock(&lun->lun_lock);
8181                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8182                                                       /*sks_valid*/ 1,
8183                                                       /*command*/ 1,
8184                                                       /*field*/ 2,
8185                                                       /*bit_valid*/ 1,
8186                                                       /*bit*/ 4);
8187                                 ctl_done((union ctl_io *)ctsio);
8188                                 return (1);
8189                         }
8190
8191                         if (type>8 || type==2 || type==4 || type==0) {
8192                                 mtx_unlock(&lun->lun_lock);
8193                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8194                                                       /*sks_valid*/ 1,
8195                                                       /*command*/ 1,
8196                                                       /*field*/ 2,
8197                                                       /*bit_valid*/ 1,
8198                                                       /*bit*/ 0);
8199                                 ctl_done((union ctl_io *)ctsio);
8200                                 return (1);
8201                         }
8202
8203                         /*
8204                          * Unregister everybody else and build UA for
8205                          * them
8206                          */
8207                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8208                                 if (i == residx || lun->pr_keys[i] == 0)
8209                                         continue;
8210
8211                                 if (!persis_offset
8212                                  && i <CTL_MAX_INITIATORS)
8213                                         lun->pending_ua[i] |=
8214                                                 CTL_UA_REG_PREEMPT;
8215                                 else if (persis_offset
8216                                       && i >= persis_offset)
8217                                         lun->pending_ua[i-persis_offset] |=
8218                                                 CTL_UA_REG_PREEMPT;
8219                                 lun->pr_keys[i] = 0;
8220                         }
8221                         lun->pr_key_count = 1;
8222                         lun->res_type = type;
8223                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8224                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8225                                 lun->pr_res_idx = residx;
8226
8227                         /* send msg to other side */
8228                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8229                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8230                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8231                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8232                         persis_io.pr.pr_info.res_type = type;
8233                         memcpy(persis_io.pr.pr_info.sa_res_key,
8234                                param->serv_act_res_key,
8235                                sizeof(param->serv_act_res_key));
8236                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8237                              &persis_io, sizeof(persis_io), 0)) >
8238                              CTL_HA_STATUS_SUCCESS) {
8239                                 printf("CTL:Persis Out error returned "
8240                                        "from ctl_ha_msg_send %d\n",
8241                                        isc_retval);
8242                         }
8243                 } else {
8244                         /* not all registrants */
8245                         mtx_unlock(&lun->lun_lock);
8246                         free(ctsio->kern_data_ptr, M_CTL);
8247                         ctl_set_invalid_field(ctsio,
8248                                               /*sks_valid*/ 1,
8249                                               /*command*/ 0,
8250                                               /*field*/ 8,
8251                                               /*bit_valid*/ 0,
8252                                               /*bit*/ 0);
8253                         ctl_done((union ctl_io *)ctsio);
8254                         return (1);
8255                 }
8256         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8257                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8258                 int found = 0;
8259
8260                 if (res_key == sa_res_key) {
8261                         /* special case */
8262                         /*
8263                          * The spec implies this is not good but doesn't
8264                          * say what to do. There are two choices either
8265                          * generate a res conflict or check condition
8266                          * with illegal field in parameter data. Since
8267                          * that is what is done when the sa_res_key is
8268                          * zero I'll take that approach since this has
8269                          * to do with the sa_res_key.
8270                          */
8271                         mtx_unlock(&lun->lun_lock);
8272                         free(ctsio->kern_data_ptr, M_CTL);
8273                         ctl_set_invalid_field(ctsio,
8274                                               /*sks_valid*/ 1,
8275                                               /*command*/ 0,
8276                                               /*field*/ 8,
8277                                               /*bit_valid*/ 0,
8278                                               /*bit*/ 0);
8279                         ctl_done((union ctl_io *)ctsio);
8280                         return (1);
8281                 }
8282
8283                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8284                         if (lun->pr_keys[i] != sa_res_key)
8285                                 continue;
8286
8287                         found = 1;
8288                         lun->pr_keys[i] = 0;
8289                         lun->pr_key_count--;
8290
8291                         if (!persis_offset && i < CTL_MAX_INITIATORS)
8292                                 lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8293                         else if (persis_offset && i >= persis_offset)
8294                                 lun->pending_ua[i-persis_offset] |=
8295                                         CTL_UA_REG_PREEMPT;
8296                 }
8297                 if (!found) {
8298                         mtx_unlock(&lun->lun_lock);
8299                         free(ctsio->kern_data_ptr, M_CTL);
8300                         ctl_set_reservation_conflict(ctsio);
8301                         ctl_done((union ctl_io *)ctsio);
8302                         return (CTL_RETVAL_COMPLETE);
8303                 }
8304                 /* send msg to other side */
8305                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8306                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8307                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8308                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8309                 persis_io.pr.pr_info.res_type = type;
8310                 memcpy(persis_io.pr.pr_info.sa_res_key,
8311                        param->serv_act_res_key,
8312                        sizeof(param->serv_act_res_key));
8313                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8314                      &persis_io, sizeof(persis_io), 0)) >
8315                      CTL_HA_STATUS_SUCCESS) {
8316                         printf("CTL:Persis Out error returned from "
8317                                "ctl_ha_msg_send %d\n", isc_retval);
8318                 }
8319         } else {
8320                 /* Reserved but not all registrants */
8321                 /* sa_res_key is res holder */
8322                 if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8323                         /* validate scope and type */
8324                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8325                              SPR_LU_SCOPE) {
8326                                 mtx_unlock(&lun->lun_lock);
8327                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8328                                                       /*sks_valid*/ 1,
8329                                                       /*command*/ 1,
8330                                                       /*field*/ 2,
8331                                                       /*bit_valid*/ 1,
8332                                                       /*bit*/ 4);
8333                                 ctl_done((union ctl_io *)ctsio);
8334                                 return (1);
8335                         }
8336
8337                         if (type>8 || type==2 || type==4 || type==0) {
8338                                 mtx_unlock(&lun->lun_lock);
8339                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8340                                                       /*sks_valid*/ 1,
8341                                                       /*command*/ 1,
8342                                                       /*field*/ 2,
8343                                                       /*bit_valid*/ 1,
8344                                                       /*bit*/ 0);
8345                                 ctl_done((union ctl_io *)ctsio);
8346                                 return (1);
8347                         }
8348
8349                         /*
8350                          * Do the following:
8351                          * if sa_res_key != res_key remove all
8352                          * registrants w/sa_res_key and generate UA
8353                          * for these registrants(Registrations
8354                          * Preempted) if it wasn't an exclusive
8355                          * reservation generate UA(Reservations
8356                          * Preempted) for all other registered nexuses
8357                          * if the type has changed. Establish the new
8358                          * reservation and holder. If res_key and
8359                          * sa_res_key are the same do the above
8360                          * except don't unregister the res holder.
8361                          */
8362
8363                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8364                                 if (i == residx || lun->pr_keys[i] == 0)
8365                                         continue;
8366
8367                                 if (sa_res_key == lun->pr_keys[i]) {
8368                                         lun->pr_keys[i] = 0;
8369                                         lun->pr_key_count--;
8370
8371                                         if (!persis_offset
8372                                          && i < CTL_MAX_INITIATORS)
8373                                                 lun->pending_ua[i] |=
8374                                                         CTL_UA_REG_PREEMPT;
8375                                         else if (persis_offset
8376                                               && i >= persis_offset)
8377                                                 lun->pending_ua[i-persis_offset] |=
8378                                                   CTL_UA_REG_PREEMPT;
8379                                 } else if (type != lun->res_type
8380                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8381                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8382                                                 if (!persis_offset
8383                                                  && i < CTL_MAX_INITIATORS)
8384                                                         lun->pending_ua[i] |=
8385                                                         CTL_UA_RES_RELEASE;
8386                                                 else if (persis_offset
8387                                                       && i >= persis_offset)
8388                                                         lun->pending_ua[
8389                                                         i-persis_offset] |=
8390                                                         CTL_UA_RES_RELEASE;
8391                                 }
8392                         }
8393                         lun->res_type = type;
8394                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8395                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8396                                 lun->pr_res_idx = residx;
8397                         else
8398                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8399
8400                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8401                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8402                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8403                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8404                         persis_io.pr.pr_info.res_type = type;
8405                         memcpy(persis_io.pr.pr_info.sa_res_key,
8406                                param->serv_act_res_key,
8407                                sizeof(param->serv_act_res_key));
8408                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8409                              &persis_io, sizeof(persis_io), 0)) >
8410                              CTL_HA_STATUS_SUCCESS) {
8411                                 printf("CTL:Persis Out error returned "
8412                                        "from ctl_ha_msg_send %d\n",
8413                                        isc_retval);
8414                         }
8415                 } else {
8416                         /*
8417                          * sa_res_key is not the res holder just
8418                          * remove registrants
8419                          */
8420                         int found=0;
8421
8422                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8423                                 if (sa_res_key != lun->pr_keys[i])
8424                                         continue;
8425
8426                                 found = 1;
8427                                 lun->pr_keys[i] = 0;
8428                                 lun->pr_key_count--;
8429
8430                                 if (!persis_offset
8431                                  && i < CTL_MAX_INITIATORS)
8432                                         lun->pending_ua[i] |=
8433                                                 CTL_UA_REG_PREEMPT;
8434                                 else if (persis_offset
8435                                       && i >= persis_offset)
8436                                         lun->pending_ua[i-persis_offset] |=
8437                                                 CTL_UA_REG_PREEMPT;
8438                         }
8439
8440                         if (!found) {
8441                                 mtx_unlock(&lun->lun_lock);
8442                                 free(ctsio->kern_data_ptr, M_CTL);
8443                                 ctl_set_reservation_conflict(ctsio);
8444                                 ctl_done((union ctl_io *)ctsio);
8445                                 return (1);
8446                         }
8447                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8448                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8449                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8450                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8451                         persis_io.pr.pr_info.res_type = type;
8452                         memcpy(persis_io.pr.pr_info.sa_res_key,
8453                                param->serv_act_res_key,
8454                                sizeof(param->serv_act_res_key));
8455                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8456                              &persis_io, sizeof(persis_io), 0)) >
8457                              CTL_HA_STATUS_SUCCESS) {
8458                                 printf("CTL:Persis Out error returned "
8459                                        "from ctl_ha_msg_send %d\n",
8460                                 isc_retval);
8461                         }
8462                 }
8463         }
8464
8465         lun->PRGeneration++;
8466         mtx_unlock(&lun->lun_lock);
8467
8468         return (retval);
8469 }
8470
8471 static void
8472 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8473 {
8474         uint64_t sa_res_key;
8475         int i;
8476
8477         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8478
8479         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8480          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8481          || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8482                 if (sa_res_key == 0) {
8483                         /*
8484                          * Unregister everybody else and build UA for
8485                          * them
8486                          */
8487                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8488                                 if (i == msg->pr.pr_info.residx ||
8489                                     lun->pr_keys[i] == 0)
8490                                         continue;
8491
8492                                 if (!persis_offset
8493                                  && i < CTL_MAX_INITIATORS)
8494                                         lun->pending_ua[i] |=
8495                                                 CTL_UA_REG_PREEMPT;
8496                                 else if (persis_offset && i >= persis_offset)
8497                                         lun->pending_ua[i - persis_offset] |=
8498                                                 CTL_UA_REG_PREEMPT;
8499                                 lun->pr_keys[i] = 0;
8500                         }
8501
8502                         lun->pr_key_count = 1;
8503                         lun->res_type = msg->pr.pr_info.res_type;
8504                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8505                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8506                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8507                 } else {
8508                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8509                                 if (sa_res_key == lun->pr_keys[i])
8510                                         continue;
8511
8512                                 lun->pr_keys[i] = 0;
8513                                 lun->pr_key_count--;
8514
8515                                 if (!persis_offset
8516                                  && i < persis_offset)
8517                                         lun->pending_ua[i] |=
8518                                                 CTL_UA_REG_PREEMPT;
8519                                 else if (persis_offset
8520                                       && i >= persis_offset)
8521                                         lun->pending_ua[i - persis_offset] |=
8522                                                 CTL_UA_REG_PREEMPT;
8523                         }
8524                 }
8525         } else {
8526                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8527                         if (i == msg->pr.pr_info.residx ||
8528                             lun->pr_keys[i] == 0)
8529                                 continue;
8530
8531                         if (sa_res_key == lun->pr_keys[i]) {
8532                                 lun->pr_keys[i] = 0;
8533                                 lun->pr_key_count--;
8534                                 if (!persis_offset
8535                                  && i < CTL_MAX_INITIATORS)
8536                                         lun->pending_ua[i] |=
8537                                                 CTL_UA_REG_PREEMPT;
8538                                 else if (persis_offset
8539                                       && i >= persis_offset)
8540                                         lun->pending_ua[i - persis_offset] |=
8541                                                 CTL_UA_REG_PREEMPT;
8542                         } else if (msg->pr.pr_info.res_type != lun->res_type
8543                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8544                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8545                                         if (!persis_offset
8546                                          && i < persis_offset)
8547                                                 lun->pending_ua[i] |=
8548                                                         CTL_UA_RES_RELEASE;
8549                                         else if (persis_offset
8550                                               && i >= persis_offset)
8551                                         lun->pending_ua[i - persis_offset] |=
8552                                                 CTL_UA_RES_RELEASE;
8553                         }
8554                 }
8555                 lun->res_type = msg->pr.pr_info.res_type;
8556                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8557                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8558                         lun->pr_res_idx = msg->pr.pr_info.residx;
8559                 else
8560                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8561         }
8562         lun->PRGeneration++;
8563
8564 }
8565
8566
8567 int
8568 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8569 {
8570         int retval;
8571         int isc_retval;
8572         u_int32_t param_len;
8573         struct scsi_per_res_out *cdb;
8574         struct ctl_lun *lun;
8575         struct scsi_per_res_out_parms* param;
8576         struct ctl_softc *softc;
8577         uint32_t residx;
8578         uint64_t res_key, sa_res_key;
8579         uint8_t type;
8580         union ctl_ha_msg persis_io;
8581         int    i;
8582
8583         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8584
8585         retval = CTL_RETVAL_COMPLETE;
8586
8587         softc = control_softc;
8588
8589         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8590         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8591
8592         /*
8593          * We only support whole-LUN scope.  The scope & type are ignored for
8594          * register, register and ignore existing key and clear.
8595          * We sometimes ignore scope and type on preempts too!!
8596          * Verify reservation type here as well.
8597          */
8598         type = cdb->scope_type & SPR_TYPE_MASK;
8599         if ((cdb->action == SPRO_RESERVE)
8600          || (cdb->action == SPRO_RELEASE)) {
8601                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8602                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8603                                               /*sks_valid*/ 1,
8604                                               /*command*/ 1,
8605                                               /*field*/ 2,
8606                                               /*bit_valid*/ 1,
8607                                               /*bit*/ 4);
8608                         ctl_done((union ctl_io *)ctsio);
8609                         return (CTL_RETVAL_COMPLETE);
8610                 }
8611
8612                 if (type>8 || type==2 || type==4 || type==0) {
8613                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8614                                               /*sks_valid*/ 1,
8615                                               /*command*/ 1,
8616                                               /*field*/ 2,
8617                                               /*bit_valid*/ 1,
8618                                               /*bit*/ 0);
8619                         ctl_done((union ctl_io *)ctsio);
8620                         return (CTL_RETVAL_COMPLETE);
8621                 }
8622         }
8623
8624         param_len = scsi_4btoul(cdb->length);
8625
8626         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8627                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8628                 ctsio->kern_data_len = param_len;
8629                 ctsio->kern_total_len = param_len;
8630                 ctsio->kern_data_resid = 0;
8631                 ctsio->kern_rel_offset = 0;
8632                 ctsio->kern_sg_entries = 0;
8633                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8634                 ctsio->be_move_done = ctl_config_move_done;
8635                 ctl_datamove((union ctl_io *)ctsio);
8636
8637                 return (CTL_RETVAL_COMPLETE);
8638         }
8639
8640         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8641
8642         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8643         res_key = scsi_8btou64(param->res_key.key);
8644         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8645
8646         /*
8647          * Validate the reservation key here except for SPRO_REG_IGNO
8648          * This must be done for all other service actions
8649          */
8650         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8651                 mtx_lock(&lun->lun_lock);
8652                 if (lun->pr_keys[residx] != 0) {
8653                     if (res_key != lun->pr_keys[residx]) {
8654                                 /*
8655                                  * The current key passed in doesn't match
8656                                  * the one the initiator previously
8657                                  * registered.
8658                                  */
8659                                 mtx_unlock(&lun->lun_lock);
8660                                 free(ctsio->kern_data_ptr, M_CTL);
8661                                 ctl_set_reservation_conflict(ctsio);
8662                                 ctl_done((union ctl_io *)ctsio);
8663                                 return (CTL_RETVAL_COMPLETE);
8664                         }
8665                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8666                         /*
8667                          * We are not registered
8668                          */
8669                         mtx_unlock(&lun->lun_lock);
8670                         free(ctsio->kern_data_ptr, M_CTL);
8671                         ctl_set_reservation_conflict(ctsio);
8672                         ctl_done((union ctl_io *)ctsio);
8673                         return (CTL_RETVAL_COMPLETE);
8674                 } else if (res_key != 0) {
8675                         /*
8676                          * We are not registered and trying to register but
8677                          * the register key isn't zero.
8678                          */
8679                         mtx_unlock(&lun->lun_lock);
8680                         free(ctsio->kern_data_ptr, M_CTL);
8681                         ctl_set_reservation_conflict(ctsio);
8682                         ctl_done((union ctl_io *)ctsio);
8683                         return (CTL_RETVAL_COMPLETE);
8684                 }
8685                 mtx_unlock(&lun->lun_lock);
8686         }
8687
8688         switch (cdb->action & SPRO_ACTION_MASK) {
8689         case SPRO_REGISTER:
8690         case SPRO_REG_IGNO: {
8691
8692 #if 0
8693                 printf("Registration received\n");
8694 #endif
8695
8696                 /*
8697                  * We don't support any of these options, as we report in
8698                  * the read capabilities request (see
8699                  * ctl_persistent_reserve_in(), above).
8700                  */
8701                 if ((param->flags & SPR_SPEC_I_PT)
8702                  || (param->flags & SPR_ALL_TG_PT)
8703                  || (param->flags & SPR_APTPL)) {
8704                         int bit_ptr;
8705
8706                         if (param->flags & SPR_APTPL)
8707                                 bit_ptr = 0;
8708                         else if (param->flags & SPR_ALL_TG_PT)
8709                                 bit_ptr = 2;
8710                         else /* SPR_SPEC_I_PT */
8711                                 bit_ptr = 3;
8712
8713                         free(ctsio->kern_data_ptr, M_CTL);
8714                         ctl_set_invalid_field(ctsio,
8715                                               /*sks_valid*/ 1,
8716                                               /*command*/ 0,
8717                                               /*field*/ 20,
8718                                               /*bit_valid*/ 1,
8719                                               /*bit*/ bit_ptr);
8720                         ctl_done((union ctl_io *)ctsio);
8721                         return (CTL_RETVAL_COMPLETE);
8722                 }
8723
8724                 mtx_lock(&lun->lun_lock);
8725
8726                 /*
8727                  * The initiator wants to clear the
8728                  * key/unregister.
8729                  */
8730                 if (sa_res_key == 0) {
8731                         if ((res_key == 0
8732                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8733                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8734                           && lun->pr_keys[residx] == 0)) {
8735                                 mtx_unlock(&lun->lun_lock);
8736                                 goto done;
8737                         }
8738
8739                         lun->pr_keys[residx] = 0;
8740                         lun->pr_key_count--;
8741
8742                         if (residx == lun->pr_res_idx) {
8743                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8744                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8745
8746                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8747                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8748                                  && lun->pr_key_count) {
8749                                         /*
8750                                          * If the reservation is a registrants
8751                                          * only type we need to generate a UA
8752                                          * for other registered inits.  The
8753                                          * sense code should be RESERVATIONS
8754                                          * RELEASED
8755                                          */
8756
8757                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8758                                                 if (lun->pr_keys[
8759                                                     i + persis_offset] == 0)
8760                                                         continue;
8761                                                 lun->pending_ua[i] |=
8762                                                         CTL_UA_RES_RELEASE;
8763                                         }
8764                                 }
8765                                 lun->res_type = 0;
8766                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8767                                 if (lun->pr_key_count==0) {
8768                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8769                                         lun->res_type = 0;
8770                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8771                                 }
8772                         }
8773                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8774                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8775                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8776                         persis_io.pr.pr_info.residx = residx;
8777                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8778                              &persis_io, sizeof(persis_io), 0 )) >
8779                              CTL_HA_STATUS_SUCCESS) {
8780                                 printf("CTL:Persis Out error returned from "
8781                                        "ctl_ha_msg_send %d\n", isc_retval);
8782                         }
8783                 } else /* sa_res_key != 0 */ {
8784
8785                         /*
8786                          * If we aren't registered currently then increment
8787                          * the key count and set the registered flag.
8788                          */
8789                         if (lun->pr_keys[residx] == 0)
8790                                 lun->pr_key_count++;
8791                         lun->pr_keys[residx] = sa_res_key;
8792
8793                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8794                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8795                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8796                         persis_io.pr.pr_info.residx = residx;
8797                         memcpy(persis_io.pr.pr_info.sa_res_key,
8798                                param->serv_act_res_key,
8799                                sizeof(param->serv_act_res_key));
8800                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8801                              &persis_io, sizeof(persis_io), 0)) >
8802                              CTL_HA_STATUS_SUCCESS) {
8803                                 printf("CTL:Persis Out error returned from "
8804                                        "ctl_ha_msg_send %d\n", isc_retval);
8805                         }
8806                 }
8807                 lun->PRGeneration++;
8808                 mtx_unlock(&lun->lun_lock);
8809
8810                 break;
8811         }
8812         case SPRO_RESERVE:
8813 #if 0
8814                 printf("Reserve executed type %d\n", type);
8815 #endif
8816                 mtx_lock(&lun->lun_lock);
8817                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8818                         /*
8819                          * if this isn't the reservation holder and it's
8820                          * not a "all registrants" type or if the type is
8821                          * different then we have a conflict
8822                          */
8823                         if ((lun->pr_res_idx != residx
8824                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8825                          || lun->res_type != type) {
8826                                 mtx_unlock(&lun->lun_lock);
8827                                 free(ctsio->kern_data_ptr, M_CTL);
8828                                 ctl_set_reservation_conflict(ctsio);
8829                                 ctl_done((union ctl_io *)ctsio);
8830                                 return (CTL_RETVAL_COMPLETE);
8831                         }
8832                         mtx_unlock(&lun->lun_lock);
8833                 } else /* create a reservation */ {
8834                         /*
8835                          * If it's not an "all registrants" type record
8836                          * reservation holder
8837                          */
8838                         if (type != SPR_TYPE_WR_EX_AR
8839                          && type != SPR_TYPE_EX_AC_AR)
8840                                 lun->pr_res_idx = residx; /* Res holder */
8841                         else
8842                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8843
8844                         lun->flags |= CTL_LUN_PR_RESERVED;
8845                         lun->res_type = type;
8846
8847                         mtx_unlock(&lun->lun_lock);
8848
8849                         /* send msg to other side */
8850                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8851                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8852                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8853                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8854                         persis_io.pr.pr_info.res_type = type;
8855                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8856                              &persis_io, sizeof(persis_io), 0)) >
8857                              CTL_HA_STATUS_SUCCESS) {
8858                                 printf("CTL:Persis Out error returned from "
8859                                        "ctl_ha_msg_send %d\n", isc_retval);
8860                         }
8861                 }
8862                 break;
8863
8864         case SPRO_RELEASE:
8865                 mtx_lock(&lun->lun_lock);
8866                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8867                         /* No reservation exists return good status */
8868                         mtx_unlock(&lun->lun_lock);
8869                         goto done;
8870                 }
8871                 /*
8872                  * Is this nexus a reservation holder?
8873                  */
8874                 if (lun->pr_res_idx != residx
8875                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8876                         /*
8877                          * not a res holder return good status but
8878                          * do nothing
8879                          */
8880                         mtx_unlock(&lun->lun_lock);
8881                         goto done;
8882                 }
8883
8884                 if (lun->res_type != type) {
8885                         mtx_unlock(&lun->lun_lock);
8886                         free(ctsio->kern_data_ptr, M_CTL);
8887                         ctl_set_illegal_pr_release(ctsio);
8888                         ctl_done((union ctl_io *)ctsio);
8889                         return (CTL_RETVAL_COMPLETE);
8890                 }
8891
8892                 /* okay to release */
8893                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8894                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8895                 lun->res_type = 0;
8896
8897                 /*
8898                  * if this isn't an exclusive access
8899                  * res generate UA for all other
8900                  * registrants.
8901                  */
8902                 if (type != SPR_TYPE_EX_AC
8903                  && type != SPR_TYPE_WR_EX) {
8904                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8905                                 if (i == residx ||
8906                                     lun->pr_keys[i + persis_offset] == 0)
8907                                         continue;
8908                                 lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8909                         }
8910                 }
8911                 mtx_unlock(&lun->lun_lock);
8912                 /* Send msg to other side */
8913                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8914                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8915                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8916                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8917                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8918                         printf("CTL:Persis Out error returned from "
8919                                "ctl_ha_msg_send %d\n", isc_retval);
8920                 }
8921                 break;
8922
8923         case SPRO_CLEAR:
8924                 /* send msg to other side */
8925
8926                 mtx_lock(&lun->lun_lock);
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                 lun->pr_keys[residx] = 0;
8933
8934                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8935                         if (lun->pr_keys[i] != 0) {
8936                                 if (!persis_offset && i < CTL_MAX_INITIATORS)
8937                                         lun->pending_ua[i] |=
8938                                                 CTL_UA_RES_PREEMPT;
8939                                 else if (persis_offset && i >= persis_offset)
8940                                         lun->pending_ua[i-persis_offset] |=
8941                                             CTL_UA_RES_PREEMPT;
8942
8943                                 lun->pr_keys[i] = 0;
8944                         }
8945                 lun->PRGeneration++;
8946                 mtx_unlock(&lun->lun_lock);
8947                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8948                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8949                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8950                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8951                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8952                         printf("CTL:Persis Out error returned from "
8953                                "ctl_ha_msg_send %d\n", isc_retval);
8954                 }
8955                 break;
8956
8957         case SPRO_PREEMPT: {
8958                 int nretval;
8959
8960                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8961                                           residx, ctsio, cdb, param);
8962                 if (nretval != 0)
8963                         return (CTL_RETVAL_COMPLETE);
8964                 break;
8965         }
8966         default:
8967                 panic("Invalid PR type %x", cdb->action);
8968         }
8969
8970 done:
8971         free(ctsio->kern_data_ptr, M_CTL);
8972         ctl_set_success(ctsio);
8973         ctl_done((union ctl_io *)ctsio);
8974
8975         return (retval);
8976 }
8977
8978 /*
8979  * This routine is for handling a message from the other SC pertaining to
8980  * persistent reserve out. All the error checking will have been done
8981  * so only perorming the action need be done here to keep the two
8982  * in sync.
8983  */
8984 static void
8985 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8986 {
8987         struct ctl_lun *lun;
8988         struct ctl_softc *softc;
8989         int i;
8990         uint32_t targ_lun;
8991
8992         softc = control_softc;
8993
8994         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8995         lun = softc->ctl_luns[targ_lun];
8996         mtx_lock(&lun->lun_lock);
8997         switch(msg->pr.pr_info.action) {
8998         case CTL_PR_REG_KEY:
8999                 if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
9000                         lun->pr_key_count++;
9001                 lun->pr_keys[msg->pr.pr_info.residx] =
9002                     scsi_8btou64(msg->pr.pr_info.sa_res_key);
9003                 lun->PRGeneration++;
9004                 break;
9005
9006         case CTL_PR_UNREG_KEY:
9007                 lun->pr_keys[msg->pr.pr_info.residx] = 0;
9008                 lun->pr_key_count--;
9009
9010                 /* XXX Need to see if the reservation has been released */
9011                 /* if so do we need to generate UA? */
9012                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
9013                         lun->flags &= ~CTL_LUN_PR_RESERVED;
9014                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9015
9016                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
9017                           || lun->res_type == SPR_TYPE_EX_AC_RO)
9018                          && lun->pr_key_count) {
9019                                 /*
9020                                  * If the reservation is a registrants
9021                                  * only type we need to generate a UA
9022                                  * for other registered inits.  The
9023                                  * sense code should be RESERVATIONS
9024                                  * RELEASED
9025                                  */
9026
9027                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
9028                                         if (lun->pr_keys[i+
9029                                             persis_offset] == 0)
9030                                                 continue;
9031
9032                                         lun->pending_ua[i] |=
9033                                                 CTL_UA_RES_RELEASE;
9034                                 }
9035                         }
9036                         lun->res_type = 0;
9037                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
9038                         if (lun->pr_key_count==0) {
9039                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
9040                                 lun->res_type = 0;
9041                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9042                         }
9043                 }
9044                 lun->PRGeneration++;
9045                 break;
9046
9047         case CTL_PR_RESERVE:
9048                 lun->flags |= CTL_LUN_PR_RESERVED;
9049                 lun->res_type = msg->pr.pr_info.res_type;
9050                 lun->pr_res_idx = msg->pr.pr_info.residx;
9051
9052                 break;
9053
9054         case CTL_PR_RELEASE:
9055                 /*
9056                  * if this isn't an exclusive access res generate UA for all
9057                  * other registrants.
9058                  */
9059                 if (lun->res_type != SPR_TYPE_EX_AC
9060                  && lun->res_type != SPR_TYPE_WR_EX) {
9061                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
9062                                 if (lun->pr_keys[i+persis_offset] != 0)
9063                                         lun->pending_ua[i] |=
9064                                                 CTL_UA_RES_RELEASE;
9065                 }
9066
9067                 lun->flags &= ~CTL_LUN_PR_RESERVED;
9068                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9069                 lun->res_type = 0;
9070                 break;
9071
9072         case CTL_PR_PREEMPT:
9073                 ctl_pro_preempt_other(lun, msg);
9074                 break;
9075         case CTL_PR_CLEAR:
9076                 lun->flags &= ~CTL_LUN_PR_RESERVED;
9077                 lun->res_type = 0;
9078                 lun->pr_key_count = 0;
9079                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9080
9081                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9082                         if (lun->pr_keys[i] == 0)
9083                                 continue;
9084                         if (!persis_offset
9085                          && i < CTL_MAX_INITIATORS)
9086                                 lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9087                         else if (persis_offset
9088                               && i >= persis_offset)
9089                                 lun->pending_ua[i-persis_offset] |=
9090                                         CTL_UA_RES_PREEMPT;
9091                         lun->pr_keys[i] = 0;
9092                 }
9093                 lun->PRGeneration++;
9094                 break;
9095         }
9096
9097         mtx_unlock(&lun->lun_lock);
9098 }
9099
9100 int
9101 ctl_read_write(struct ctl_scsiio *ctsio)
9102 {
9103         struct ctl_lun *lun;
9104         struct ctl_lba_len_flags *lbalen;
9105         uint64_t lba;
9106         uint32_t num_blocks;
9107         int flags, retval;
9108         int isread;
9109
9110         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9111
9112         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9113
9114         flags = 0;
9115         retval = CTL_RETVAL_COMPLETE;
9116
9117         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9118               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9119         if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9120                 uint32_t residx;
9121
9122                 /*
9123                  * XXX KDM need a lock here.
9124                  */
9125                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9126                 if ((lun->res_type == SPR_TYPE_EX_AC
9127                   && residx != lun->pr_res_idx)
9128                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
9129                    || lun->res_type == SPR_TYPE_EX_AC_AR)
9130                   && lun->pr_keys[residx] == 0)) {
9131                         ctl_set_reservation_conflict(ctsio);
9132                         ctl_done((union ctl_io *)ctsio);
9133                         return (CTL_RETVAL_COMPLETE);
9134                 }
9135         }
9136
9137         switch (ctsio->cdb[0]) {
9138         case READ_6:
9139         case WRITE_6: {
9140                 struct scsi_rw_6 *cdb;
9141
9142                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
9143
9144                 lba = scsi_3btoul(cdb->addr);
9145                 /* only 5 bits are valid in the most significant address byte */
9146                 lba &= 0x1fffff;
9147                 num_blocks = cdb->length;
9148                 /*
9149                  * This is correct according to SBC-2.
9150                  */
9151                 if (num_blocks == 0)
9152                         num_blocks = 256;
9153                 break;
9154         }
9155         case READ_10:
9156         case WRITE_10: {
9157                 struct scsi_rw_10 *cdb;
9158
9159                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9160                 if (cdb->byte2 & SRW10_FUA)
9161                         flags |= CTL_LLF_FUA;
9162                 if (cdb->byte2 & SRW10_DPO)
9163                         flags |= CTL_LLF_DPO;
9164                 lba = scsi_4btoul(cdb->addr);
9165                 num_blocks = scsi_2btoul(cdb->length);
9166                 break;
9167         }
9168         case WRITE_VERIFY_10: {
9169                 struct scsi_write_verify_10 *cdb;
9170
9171                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9172                 flags |= CTL_LLF_FUA;
9173                 if (cdb->byte2 & SWV_DPO)
9174                         flags |= CTL_LLF_DPO;
9175                 lba = scsi_4btoul(cdb->addr);
9176                 num_blocks = scsi_2btoul(cdb->length);
9177                 break;
9178         }
9179         case READ_12:
9180         case WRITE_12: {
9181                 struct scsi_rw_12 *cdb;
9182
9183                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9184                 if (cdb->byte2 & SRW12_FUA)
9185                         flags |= CTL_LLF_FUA;
9186                 if (cdb->byte2 & SRW12_DPO)
9187                         flags |= CTL_LLF_DPO;
9188                 lba = scsi_4btoul(cdb->addr);
9189                 num_blocks = scsi_4btoul(cdb->length);
9190                 break;
9191         }
9192         case WRITE_VERIFY_12: {
9193                 struct scsi_write_verify_12 *cdb;
9194
9195                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9196                 flags |= CTL_LLF_FUA;
9197                 if (cdb->byte2 & SWV_DPO)
9198                         flags |= CTL_LLF_DPO;
9199                 lba = scsi_4btoul(cdb->addr);
9200                 num_blocks = scsi_4btoul(cdb->length);
9201                 break;
9202         }
9203         case READ_16:
9204         case WRITE_16: {
9205                 struct scsi_rw_16 *cdb;
9206
9207                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9208                 if (cdb->byte2 & SRW12_FUA)
9209                         flags |= CTL_LLF_FUA;
9210                 if (cdb->byte2 & SRW12_DPO)
9211                         flags |= CTL_LLF_DPO;
9212                 lba = scsi_8btou64(cdb->addr);
9213                 num_blocks = scsi_4btoul(cdb->length);
9214                 break;
9215         }
9216         case WRITE_ATOMIC_16: {
9217                 struct scsi_rw_16 *cdb;
9218
9219                 if (lun->be_lun->atomicblock == 0) {
9220                         ctl_set_invalid_opcode(ctsio);
9221                         ctl_done((union ctl_io *)ctsio);
9222                         return (CTL_RETVAL_COMPLETE);
9223                 }
9224
9225                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9226                 if (cdb->byte2 & SRW12_FUA)
9227                         flags |= CTL_LLF_FUA;
9228                 if (cdb->byte2 & SRW12_DPO)
9229                         flags |= CTL_LLF_DPO;
9230                 lba = scsi_8btou64(cdb->addr);
9231                 num_blocks = scsi_4btoul(cdb->length);
9232                 if (num_blocks > lun->be_lun->atomicblock) {
9233                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9234                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9235                             /*bit*/ 0);
9236                         ctl_done((union ctl_io *)ctsio);
9237                         return (CTL_RETVAL_COMPLETE);
9238                 }
9239                 break;
9240         }
9241         case WRITE_VERIFY_16: {
9242                 struct scsi_write_verify_16 *cdb;
9243
9244                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9245                 flags |= CTL_LLF_FUA;
9246                 if (cdb->byte2 & SWV_DPO)
9247                         flags |= CTL_LLF_DPO;
9248                 lba = scsi_8btou64(cdb->addr);
9249                 num_blocks = scsi_4btoul(cdb->length);
9250                 break;
9251         }
9252         default:
9253                 /*
9254                  * We got a command we don't support.  This shouldn't
9255                  * happen, commands should be filtered out above us.
9256                  */
9257                 ctl_set_invalid_opcode(ctsio);
9258                 ctl_done((union ctl_io *)ctsio);
9259
9260                 return (CTL_RETVAL_COMPLETE);
9261                 break; /* NOTREACHED */
9262         }
9263
9264         /*
9265          * The first check is to make sure we're in bounds, the second
9266          * check is to catch wrap-around problems.  If the lba + num blocks
9267          * is less than the lba, then we've wrapped around and the block
9268          * range is invalid anyway.
9269          */
9270         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9271          || ((lba + num_blocks) < lba)) {
9272                 ctl_set_lba_out_of_range(ctsio);
9273                 ctl_done((union ctl_io *)ctsio);
9274                 return (CTL_RETVAL_COMPLETE);
9275         }
9276
9277         /*
9278          * According to SBC-3, a transfer length of 0 is not an error.
9279          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9280          * translates to 256 blocks for those commands.
9281          */
9282         if (num_blocks == 0) {
9283                 ctl_set_success(ctsio);
9284                 ctl_done((union ctl_io *)ctsio);
9285                 return (CTL_RETVAL_COMPLETE);
9286         }
9287
9288         /* Set FUA and/or DPO if caches are disabled. */
9289         if (isread) {
9290                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9291                     SCP_RCD) != 0)
9292                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9293         } else {
9294                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9295                     SCP_WCE) == 0)
9296                         flags |= CTL_LLF_FUA;
9297         }
9298
9299         lbalen = (struct ctl_lba_len_flags *)
9300             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9301         lbalen->lba = lba;
9302         lbalen->len = num_blocks;
9303         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9304
9305         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9306         ctsio->kern_rel_offset = 0;
9307
9308         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9309
9310         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9311
9312         return (retval);
9313 }
9314
9315 static int
9316 ctl_cnw_cont(union ctl_io *io)
9317 {
9318         struct ctl_scsiio *ctsio;
9319         struct ctl_lun *lun;
9320         struct ctl_lba_len_flags *lbalen;
9321         int retval;
9322
9323         ctsio = &io->scsiio;
9324         ctsio->io_hdr.status = CTL_STATUS_NONE;
9325         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9326         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9327         lbalen = (struct ctl_lba_len_flags *)
9328             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9329         lbalen->flags &= ~CTL_LLF_COMPARE;
9330         lbalen->flags |= CTL_LLF_WRITE;
9331
9332         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9333         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9334         return (retval);
9335 }
9336
9337 int
9338 ctl_cnw(struct ctl_scsiio *ctsio)
9339 {
9340         struct ctl_lun *lun;
9341         struct ctl_lba_len_flags *lbalen;
9342         uint64_t lba;
9343         uint32_t num_blocks;
9344         int flags, retval;
9345
9346         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9347
9348         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9349
9350         flags = 0;
9351         retval = CTL_RETVAL_COMPLETE;
9352
9353         switch (ctsio->cdb[0]) {
9354         case COMPARE_AND_WRITE: {
9355                 struct scsi_compare_and_write *cdb;
9356
9357                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9358                 if (cdb->byte2 & SRW10_FUA)
9359                         flags |= CTL_LLF_FUA;
9360                 if (cdb->byte2 & SRW10_DPO)
9361                         flags |= CTL_LLF_DPO;
9362                 lba = scsi_8btou64(cdb->addr);
9363                 num_blocks = cdb->length;
9364                 break;
9365         }
9366         default:
9367                 /*
9368                  * We got a command we don't support.  This shouldn't
9369                  * happen, commands should be filtered out above us.
9370                  */
9371                 ctl_set_invalid_opcode(ctsio);
9372                 ctl_done((union ctl_io *)ctsio);
9373
9374                 return (CTL_RETVAL_COMPLETE);
9375                 break; /* NOTREACHED */
9376         }
9377
9378         /*
9379          * The first check is to make sure we're in bounds, the second
9380          * check is to catch wrap-around problems.  If the lba + num blocks
9381          * is less than the lba, then we've wrapped around and the block
9382          * range is invalid anyway.
9383          */
9384         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9385          || ((lba + num_blocks) < lba)) {
9386                 ctl_set_lba_out_of_range(ctsio);
9387                 ctl_done((union ctl_io *)ctsio);
9388                 return (CTL_RETVAL_COMPLETE);
9389         }
9390
9391         /*
9392          * According to SBC-3, a transfer length of 0 is not an error.
9393          */
9394         if (num_blocks == 0) {
9395                 ctl_set_success(ctsio);
9396                 ctl_done((union ctl_io *)ctsio);
9397                 return (CTL_RETVAL_COMPLETE);
9398         }
9399
9400         /* Set FUA if write cache is disabled. */
9401         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9402             SCP_WCE) == 0)
9403                 flags |= CTL_LLF_FUA;
9404
9405         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9406         ctsio->kern_rel_offset = 0;
9407
9408         /*
9409          * Set the IO_CONT flag, so that if this I/O gets passed to
9410          * ctl_data_submit_done(), it'll get passed back to
9411          * ctl_ctl_cnw_cont() for further processing.
9412          */
9413         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9414         ctsio->io_cont = ctl_cnw_cont;
9415
9416         lbalen = (struct ctl_lba_len_flags *)
9417             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9418         lbalen->lba = lba;
9419         lbalen->len = num_blocks;
9420         lbalen->flags = CTL_LLF_COMPARE | flags;
9421
9422         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9423         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9424         return (retval);
9425 }
9426
9427 int
9428 ctl_verify(struct ctl_scsiio *ctsio)
9429 {
9430         struct ctl_lun *lun;
9431         struct ctl_lba_len_flags *lbalen;
9432         uint64_t lba;
9433         uint32_t num_blocks;
9434         int bytchk, flags;
9435         int retval;
9436
9437         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9438
9439         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9440
9441         bytchk = 0;
9442         flags = CTL_LLF_FUA;
9443         retval = CTL_RETVAL_COMPLETE;
9444
9445         switch (ctsio->cdb[0]) {
9446         case VERIFY_10: {
9447                 struct scsi_verify_10 *cdb;
9448
9449                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9450                 if (cdb->byte2 & SVFY_BYTCHK)
9451                         bytchk = 1;
9452                 if (cdb->byte2 & SVFY_DPO)
9453                         flags |= CTL_LLF_DPO;
9454                 lba = scsi_4btoul(cdb->addr);
9455                 num_blocks = scsi_2btoul(cdb->length);
9456                 break;
9457         }
9458         case VERIFY_12: {
9459                 struct scsi_verify_12 *cdb;
9460
9461                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9462                 if (cdb->byte2 & SVFY_BYTCHK)
9463                         bytchk = 1;
9464                 if (cdb->byte2 & SVFY_DPO)
9465                         flags |= CTL_LLF_DPO;
9466                 lba = scsi_4btoul(cdb->addr);
9467                 num_blocks = scsi_4btoul(cdb->length);
9468                 break;
9469         }
9470         case VERIFY_16: {
9471                 struct scsi_rw_16 *cdb;
9472
9473                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9474                 if (cdb->byte2 & SVFY_BYTCHK)
9475                         bytchk = 1;
9476                 if (cdb->byte2 & SVFY_DPO)
9477                         flags |= CTL_LLF_DPO;
9478                 lba = scsi_8btou64(cdb->addr);
9479                 num_blocks = scsi_4btoul(cdb->length);
9480                 break;
9481         }
9482         default:
9483                 /*
9484                  * We got a command we don't support.  This shouldn't
9485                  * happen, commands should be filtered out above us.
9486                  */
9487                 ctl_set_invalid_opcode(ctsio);
9488                 ctl_done((union ctl_io *)ctsio);
9489                 return (CTL_RETVAL_COMPLETE);
9490         }
9491
9492         /*
9493          * The first check is to make sure we're in bounds, the second
9494          * check is to catch wrap-around problems.  If the lba + num blocks
9495          * is less than the lba, then we've wrapped around and the block
9496          * range is invalid anyway.
9497          */
9498         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9499          || ((lba + num_blocks) < lba)) {
9500                 ctl_set_lba_out_of_range(ctsio);
9501                 ctl_done((union ctl_io *)ctsio);
9502                 return (CTL_RETVAL_COMPLETE);
9503         }
9504
9505         /*
9506          * According to SBC-3, a transfer length of 0 is not an error.
9507          */
9508         if (num_blocks == 0) {
9509                 ctl_set_success(ctsio);
9510                 ctl_done((union ctl_io *)ctsio);
9511                 return (CTL_RETVAL_COMPLETE);
9512         }
9513
9514         lbalen = (struct ctl_lba_len_flags *)
9515             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9516         lbalen->lba = lba;
9517         lbalen->len = num_blocks;
9518         if (bytchk) {
9519                 lbalen->flags = CTL_LLF_COMPARE | flags;
9520                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9521         } else {
9522                 lbalen->flags = CTL_LLF_VERIFY | flags;
9523                 ctsio->kern_total_len = 0;
9524         }
9525         ctsio->kern_rel_offset = 0;
9526
9527         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9528         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9529         return (retval);
9530 }
9531
9532 int
9533 ctl_report_luns(struct ctl_scsiio *ctsio)
9534 {
9535         struct scsi_report_luns *cdb;
9536         struct scsi_report_luns_data *lun_data;
9537         struct ctl_lun *lun, *request_lun;
9538         int num_luns, retval;
9539         uint32_t alloc_len, lun_datalen;
9540         int num_filled, well_known;
9541         uint32_t initidx, targ_lun_id, lun_id;
9542
9543         retval = CTL_RETVAL_COMPLETE;
9544         well_known = 0;
9545
9546         cdb = (struct scsi_report_luns *)ctsio->cdb;
9547
9548         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9549
9550         mtx_lock(&control_softc->ctl_lock);
9551         num_luns = control_softc->num_luns;
9552         mtx_unlock(&control_softc->ctl_lock);
9553
9554         switch (cdb->select_report) {
9555         case RPL_REPORT_DEFAULT:
9556         case RPL_REPORT_ALL:
9557                 break;
9558         case RPL_REPORT_WELLKNOWN:
9559                 well_known = 1;
9560                 num_luns = 0;
9561                 break;
9562         default:
9563                 ctl_set_invalid_field(ctsio,
9564                                       /*sks_valid*/ 1,
9565                                       /*command*/ 1,
9566                                       /*field*/ 2,
9567                                       /*bit_valid*/ 0,
9568                                       /*bit*/ 0);
9569                 ctl_done((union ctl_io *)ctsio);
9570                 return (retval);
9571                 break; /* NOTREACHED */
9572         }
9573
9574         alloc_len = scsi_4btoul(cdb->length);
9575         /*
9576          * The initiator has to allocate at least 16 bytes for this request,
9577          * so he can at least get the header and the first LUN.  Otherwise
9578          * we reject the request (per SPC-3 rev 14, section 6.21).
9579          */
9580         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9581             sizeof(struct scsi_report_luns_lundata))) {
9582                 ctl_set_invalid_field(ctsio,
9583                                       /*sks_valid*/ 1,
9584                                       /*command*/ 1,
9585                                       /*field*/ 6,
9586                                       /*bit_valid*/ 0,
9587                                       /*bit*/ 0);
9588                 ctl_done((union ctl_io *)ctsio);
9589                 return (retval);
9590         }
9591
9592         request_lun = (struct ctl_lun *)
9593                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9594
9595         lun_datalen = sizeof(*lun_data) +
9596                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9597
9598         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9599         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9600         ctsio->kern_sg_entries = 0;
9601
9602         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9603
9604         mtx_lock(&control_softc->ctl_lock);
9605         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9606                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9607                 if (lun_id >= CTL_MAX_LUNS)
9608                         continue;
9609                 lun = control_softc->ctl_luns[lun_id];
9610                 if (lun == NULL)
9611                         continue;
9612
9613                 if (targ_lun_id <= 0xff) {
9614                         /*
9615                          * Peripheral addressing method, bus number 0.
9616                          */
9617                         lun_data->luns[num_filled].lundata[0] =
9618                                 RPL_LUNDATA_ATYP_PERIPH;
9619                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9620                         num_filled++;
9621                 } else if (targ_lun_id <= 0x3fff) {
9622                         /*
9623                          * Flat addressing method.
9624                          */
9625                         lun_data->luns[num_filled].lundata[0] =
9626                                 RPL_LUNDATA_ATYP_FLAT |
9627                                 (targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9628 #ifdef OLDCTLHEADERS
9629                                 (SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9630                                 (targ_lun_id & SRLD_BUS_LUN_MASK);
9631 #endif
9632                         lun_data->luns[num_filled].lundata[1] =
9633 #ifdef OLDCTLHEADERS
9634                                 targ_lun_id >> SRLD_BUS_LUN_BITS;
9635 #endif
9636                                 targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9637                         num_filled++;
9638                 } else {
9639                         printf("ctl_report_luns: bogus LUN number %jd, "
9640                                "skipping\n", (intmax_t)targ_lun_id);
9641                 }
9642                 /*
9643                  * According to SPC-3, rev 14 section 6.21:
9644                  *
9645                  * "The execution of a REPORT LUNS command to any valid and
9646                  * installed logical unit shall clear the REPORTED LUNS DATA
9647                  * HAS CHANGED unit attention condition for all logical
9648                  * units of that target with respect to the requesting
9649                  * initiator. A valid and installed logical unit is one
9650                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9651                  * INQUIRY data (see 6.4.2)."
9652                  *
9653                  * If request_lun is NULL, the LUN this report luns command
9654                  * was issued to is either disabled or doesn't exist. In that
9655                  * case, we shouldn't clear any pending lun change unit
9656                  * attention.
9657                  */
9658                 if (request_lun != NULL) {
9659                         mtx_lock(&lun->lun_lock);
9660                         lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9661                         mtx_unlock(&lun->lun_lock);
9662                 }
9663         }
9664         mtx_unlock(&control_softc->ctl_lock);
9665
9666         /*
9667          * It's quite possible that we've returned fewer LUNs than we allocated
9668          * space for.  Trim it.
9669          */
9670         lun_datalen = sizeof(*lun_data) +
9671                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9672
9673         if (lun_datalen < alloc_len) {
9674                 ctsio->residual = alloc_len - lun_datalen;
9675                 ctsio->kern_data_len = lun_datalen;
9676                 ctsio->kern_total_len = lun_datalen;
9677         } else {
9678                 ctsio->residual = 0;
9679                 ctsio->kern_data_len = alloc_len;
9680                 ctsio->kern_total_len = alloc_len;
9681         }
9682         ctsio->kern_data_resid = 0;
9683         ctsio->kern_rel_offset = 0;
9684         ctsio->kern_sg_entries = 0;
9685
9686         /*
9687          * We set this to the actual data length, regardless of how much
9688          * space we actually have to return results.  If the user looks at
9689          * this value, he'll know whether or not he allocated enough space
9690          * and reissue the command if necessary.  We don't support well
9691          * known logical units, so if the user asks for that, return none.
9692          */
9693         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9694
9695         /*
9696          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9697          * this request.
9698          */
9699         ctsio->scsi_status = SCSI_STATUS_OK;
9700
9701         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9702         ctsio->be_move_done = ctl_config_move_done;
9703         ctl_datamove((union ctl_io *)ctsio);
9704
9705         return (retval);
9706 }
9707
9708 int
9709 ctl_request_sense(struct ctl_scsiio *ctsio)
9710 {
9711         struct scsi_request_sense *cdb;
9712         struct scsi_sense_data *sense_ptr;
9713         struct ctl_lun *lun;
9714         uint32_t initidx;
9715         int have_error;
9716         scsi_sense_data_type sense_format;
9717
9718         cdb = (struct scsi_request_sense *)ctsio->cdb;
9719
9720         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9721
9722         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9723
9724         /*
9725          * Determine which sense format the user wants.
9726          */
9727         if (cdb->byte2 & SRS_DESC)
9728                 sense_format = SSD_TYPE_DESC;
9729         else
9730                 sense_format = SSD_TYPE_FIXED;
9731
9732         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9733         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9734         ctsio->kern_sg_entries = 0;
9735
9736         /*
9737          * struct scsi_sense_data, which is currently set to 256 bytes, is
9738          * larger than the largest allowed value for the length field in the
9739          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9740          */
9741         ctsio->residual = 0;
9742         ctsio->kern_data_len = cdb->length;
9743         ctsio->kern_total_len = cdb->length;
9744
9745         ctsio->kern_data_resid = 0;
9746         ctsio->kern_rel_offset = 0;
9747         ctsio->kern_sg_entries = 0;
9748
9749         /*
9750          * If we don't have a LUN, we don't have any pending sense.
9751          */
9752         if (lun == NULL)
9753                 goto no_sense;
9754
9755         have_error = 0;
9756         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9757         /*
9758          * Check for pending sense, and then for pending unit attentions.
9759          * Pending sense gets returned first, then pending unit attentions.
9760          */
9761         mtx_lock(&lun->lun_lock);
9762 #ifdef CTL_WITH_CA
9763         if (ctl_is_set(lun->have_ca, initidx)) {
9764                 scsi_sense_data_type stored_format;
9765
9766                 /*
9767                  * Check to see which sense format was used for the stored
9768                  * sense data.
9769                  */
9770                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9771
9772                 /*
9773                  * If the user requested a different sense format than the
9774                  * one we stored, then we need to convert it to the other
9775                  * format.  If we're going from descriptor to fixed format
9776                  * sense data, we may lose things in translation, depending
9777                  * on what options were used.
9778                  *
9779                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9780                  * for some reason we'll just copy it out as-is.
9781                  */
9782                 if ((stored_format == SSD_TYPE_FIXED)
9783                  && (sense_format == SSD_TYPE_DESC))
9784                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9785                             &lun->pending_sense[initidx],
9786                             (struct scsi_sense_data_desc *)sense_ptr);
9787                 else if ((stored_format == SSD_TYPE_DESC)
9788                       && (sense_format == SSD_TYPE_FIXED))
9789                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9790                             &lun->pending_sense[initidx],
9791                             (struct scsi_sense_data_fixed *)sense_ptr);
9792                 else
9793                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9794                                ctl_min(sizeof(*sense_ptr),
9795                                sizeof(lun->pending_sense[initidx])));
9796
9797                 ctl_clear_mask(lun->have_ca, initidx);
9798                 have_error = 1;
9799         } else
9800 #endif
9801         if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9802                 ctl_ua_type ua_type;
9803
9804                 ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9805                                        sense_ptr, sense_format);
9806                 if (ua_type != CTL_UA_NONE)
9807                         have_error = 1;
9808         }
9809         mtx_unlock(&lun->lun_lock);
9810
9811         /*
9812          * We already have a pending error, return it.
9813          */
9814         if (have_error != 0) {
9815                 /*
9816                  * We report the SCSI status as OK, since the status of the
9817                  * request sense command itself is OK.
9818                  */
9819                 ctsio->scsi_status = SCSI_STATUS_OK;
9820
9821                 /*
9822                  * We report 0 for the sense length, because we aren't doing
9823                  * autosense in this case.  We're reporting sense as
9824                  * parameter data.
9825                  */
9826                 ctsio->sense_len = 0;
9827                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9828                 ctsio->be_move_done = ctl_config_move_done;
9829                 ctl_datamove((union ctl_io *)ctsio);
9830
9831                 return (CTL_RETVAL_COMPLETE);
9832         }
9833
9834 no_sense:
9835
9836         /*
9837          * No sense information to report, so we report that everything is
9838          * okay.
9839          */
9840         ctl_set_sense_data(sense_ptr,
9841                            lun,
9842                            sense_format,
9843                            /*current_error*/ 1,
9844                            /*sense_key*/ SSD_KEY_NO_SENSE,
9845                            /*asc*/ 0x00,
9846                            /*ascq*/ 0x00,
9847                            SSD_ELEM_NONE);
9848
9849         ctsio->scsi_status = SCSI_STATUS_OK;
9850
9851         /*
9852          * We report 0 for the sense length, because we aren't doing
9853          * autosense in this case.  We're reporting sense as parameter data.
9854          */
9855         ctsio->sense_len = 0;
9856         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9857         ctsio->be_move_done = ctl_config_move_done;
9858         ctl_datamove((union ctl_io *)ctsio);
9859
9860         return (CTL_RETVAL_COMPLETE);
9861 }
9862
9863 int
9864 ctl_tur(struct ctl_scsiio *ctsio)
9865 {
9866         struct ctl_lun *lun;
9867
9868         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9869
9870         CTL_DEBUG_PRINT(("ctl_tur\n"));
9871
9872         if (lun == NULL)
9873                 return (EINVAL);
9874
9875         ctsio->scsi_status = SCSI_STATUS_OK;
9876         ctsio->io_hdr.status = CTL_SUCCESS;
9877
9878         ctl_done((union ctl_io *)ctsio);
9879
9880         return (CTL_RETVAL_COMPLETE);
9881 }
9882
9883 #ifdef notyet
9884 static int
9885 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9886 {
9887
9888 }
9889 #endif
9890
9891 static int
9892 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9893 {
9894         struct scsi_vpd_supported_pages *pages;
9895         int sup_page_size;
9896         struct ctl_lun *lun;
9897
9898         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9899
9900         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9901             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9902         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9903         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9904         ctsio->kern_sg_entries = 0;
9905
9906         if (sup_page_size < alloc_len) {
9907                 ctsio->residual = alloc_len - sup_page_size;
9908                 ctsio->kern_data_len = sup_page_size;
9909                 ctsio->kern_total_len = sup_page_size;
9910         } else {
9911                 ctsio->residual = 0;
9912                 ctsio->kern_data_len = alloc_len;
9913                 ctsio->kern_total_len = alloc_len;
9914         }
9915         ctsio->kern_data_resid = 0;
9916         ctsio->kern_rel_offset = 0;
9917         ctsio->kern_sg_entries = 0;
9918
9919         /*
9920          * The control device is always connected.  The disk device, on the
9921          * other hand, may not be online all the time.  Need to change this
9922          * to figure out whether the disk device is actually online or not.
9923          */
9924         if (lun != NULL)
9925                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9926                                 lun->be_lun->lun_type;
9927         else
9928                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9929
9930         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9931         /* Supported VPD pages */
9932         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9933         /* Serial Number */
9934         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9935         /* Device Identification */
9936         pages->page_list[2] = SVPD_DEVICE_ID;
9937         /* Extended INQUIRY Data */
9938         pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9939         /* Mode Page Policy */
9940         pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9941         /* SCSI Ports */
9942         pages->page_list[5] = SVPD_SCSI_PORTS;
9943         /* Third-party Copy */
9944         pages->page_list[6] = SVPD_SCSI_TPC;
9945         /* Block limits */
9946         pages->page_list[7] = SVPD_BLOCK_LIMITS;
9947         /* Block Device Characteristics */
9948         pages->page_list[8] = SVPD_BDC;
9949         /* Logical Block Provisioning */
9950         pages->page_list[9] = SVPD_LBP;
9951
9952         ctsio->scsi_status = SCSI_STATUS_OK;
9953
9954         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9955         ctsio->be_move_done = ctl_config_move_done;
9956         ctl_datamove((union ctl_io *)ctsio);
9957
9958         return (CTL_RETVAL_COMPLETE);
9959 }
9960
9961 static int
9962 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9963 {
9964         struct scsi_vpd_unit_serial_number *sn_ptr;
9965         struct ctl_lun *lun;
9966         int data_len;
9967
9968         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9969
9970         data_len = 4 + CTL_SN_LEN;
9971         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9972         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9973         if (data_len < alloc_len) {
9974                 ctsio->residual = alloc_len - data_len;
9975                 ctsio->kern_data_len = data_len;
9976                 ctsio->kern_total_len = data_len;
9977         } else {
9978                 ctsio->residual = 0;
9979                 ctsio->kern_data_len = alloc_len;
9980                 ctsio->kern_total_len = alloc_len;
9981         }
9982         ctsio->kern_data_resid = 0;
9983         ctsio->kern_rel_offset = 0;
9984         ctsio->kern_sg_entries = 0;
9985
9986         /*
9987          * The control device is always connected.  The disk device, on the
9988          * other hand, may not be online all the time.  Need to change this
9989          * to figure out whether the disk device is actually online or not.
9990          */
9991         if (lun != NULL)
9992                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9993                                   lun->be_lun->lun_type;
9994         else
9995                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9996
9997         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9998         sn_ptr->length = CTL_SN_LEN;
9999         /*
10000          * If we don't have a LUN, we just leave the serial number as
10001          * all spaces.
10002          */
10003         if (lun != NULL) {
10004                 strncpy((char *)sn_ptr->serial_num,
10005                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
10006         } else
10007                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
10008         ctsio->scsi_status = SCSI_STATUS_OK;
10009
10010         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10011         ctsio->be_move_done = ctl_config_move_done;
10012         ctl_datamove((union ctl_io *)ctsio);
10013
10014         return (CTL_RETVAL_COMPLETE);
10015 }
10016
10017
10018 static int
10019 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
10020 {
10021         struct scsi_vpd_extended_inquiry_data *eid_ptr;
10022         struct ctl_lun *lun;
10023         int data_len;
10024
10025         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10026
10027         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
10028         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10029         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
10030         ctsio->kern_sg_entries = 0;
10031
10032         if (data_len < alloc_len) {
10033                 ctsio->residual = alloc_len - data_len;
10034                 ctsio->kern_data_len = data_len;
10035                 ctsio->kern_total_len = data_len;
10036         } else {
10037                 ctsio->residual = 0;
10038                 ctsio->kern_data_len = alloc_len;
10039                 ctsio->kern_total_len = alloc_len;
10040         }
10041         ctsio->kern_data_resid = 0;
10042         ctsio->kern_rel_offset = 0;
10043         ctsio->kern_sg_entries = 0;
10044
10045         /*
10046          * The control device is always connected.  The disk device, on the
10047          * other hand, may not be online all the time.
10048          */
10049         if (lun != NULL)
10050                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10051                                      lun->be_lun->lun_type;
10052         else
10053                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10054         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
10055         eid_ptr->page_length = data_len - 4;
10056         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
10057         eid_ptr->flags3 = SVPD_EID_V_SUP;
10058
10059         ctsio->scsi_status = SCSI_STATUS_OK;
10060         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10061         ctsio->be_move_done = ctl_config_move_done;
10062         ctl_datamove((union ctl_io *)ctsio);
10063
10064         return (CTL_RETVAL_COMPLETE);
10065 }
10066
10067 static int
10068 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
10069 {
10070         struct scsi_vpd_mode_page_policy *mpp_ptr;
10071         struct ctl_lun *lun;
10072         int data_len;
10073
10074         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10075
10076         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
10077             sizeof(struct scsi_vpd_mode_page_policy_descr);
10078
10079         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10080         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
10081         ctsio->kern_sg_entries = 0;
10082
10083         if (data_len < alloc_len) {
10084                 ctsio->residual = alloc_len - data_len;
10085                 ctsio->kern_data_len = data_len;
10086                 ctsio->kern_total_len = data_len;
10087         } else {
10088                 ctsio->residual = 0;
10089                 ctsio->kern_data_len = alloc_len;
10090                 ctsio->kern_total_len = alloc_len;
10091         }
10092         ctsio->kern_data_resid = 0;
10093         ctsio->kern_rel_offset = 0;
10094         ctsio->kern_sg_entries = 0;
10095
10096         /*
10097          * The control device is always connected.  The disk device, on the
10098          * other hand, may not be online all the time.
10099          */
10100         if (lun != NULL)
10101                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10102                                      lun->be_lun->lun_type;
10103         else
10104                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10105         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10106         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10107         mpp_ptr->descr[0].page_code = 0x3f;
10108         mpp_ptr->descr[0].subpage_code = 0xff;
10109         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10110
10111         ctsio->scsi_status = SCSI_STATUS_OK;
10112         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10113         ctsio->be_move_done = ctl_config_move_done;
10114         ctl_datamove((union ctl_io *)ctsio);
10115
10116         return (CTL_RETVAL_COMPLETE);
10117 }
10118
10119 static int
10120 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10121 {
10122         struct scsi_vpd_device_id *devid_ptr;
10123         struct scsi_vpd_id_descriptor *desc;
10124         struct ctl_softc *ctl_softc;
10125         struct ctl_lun *lun;
10126         struct ctl_port *port;
10127         int data_len;
10128         uint8_t proto;
10129
10130         ctl_softc = control_softc;
10131
10132         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10133         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10134
10135         data_len = sizeof(struct scsi_vpd_device_id) +
10136             sizeof(struct scsi_vpd_id_descriptor) +
10137                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10138             sizeof(struct scsi_vpd_id_descriptor) +
10139                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10140         if (lun && lun->lun_devid)
10141                 data_len += lun->lun_devid->len;
10142         if (port->port_devid)
10143                 data_len += port->port_devid->len;
10144         if (port->target_devid)
10145                 data_len += port->target_devid->len;
10146
10147         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10148         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10149         ctsio->kern_sg_entries = 0;
10150
10151         if (data_len < alloc_len) {
10152                 ctsio->residual = alloc_len - data_len;
10153                 ctsio->kern_data_len = data_len;
10154                 ctsio->kern_total_len = data_len;
10155         } else {
10156                 ctsio->residual = 0;
10157                 ctsio->kern_data_len = alloc_len;
10158                 ctsio->kern_total_len = alloc_len;
10159         }
10160         ctsio->kern_data_resid = 0;
10161         ctsio->kern_rel_offset = 0;
10162         ctsio->kern_sg_entries = 0;
10163
10164         /*
10165          * The control device is always connected.  The disk device, on the
10166          * other hand, may not be online all the time.
10167          */
10168         if (lun != NULL)
10169                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10170                                      lun->be_lun->lun_type;
10171         else
10172                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10173         devid_ptr->page_code = SVPD_DEVICE_ID;
10174         scsi_ulto2b(data_len - 4, devid_ptr->length);
10175
10176         if (port->port_type == CTL_PORT_FC)
10177                 proto = SCSI_PROTO_FC << 4;
10178         else if (port->port_type == CTL_PORT_ISCSI)
10179                 proto = SCSI_PROTO_ISCSI << 4;
10180         else
10181                 proto = SCSI_PROTO_SPI << 4;
10182         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10183
10184         /*
10185          * We're using a LUN association here.  i.e., this device ID is a
10186          * per-LUN identifier.
10187          */
10188         if (lun && lun->lun_devid) {
10189                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10190                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10191                     lun->lun_devid->len);
10192         }
10193
10194         /*
10195          * This is for the WWPN which is a port association.
10196          */
10197         if (port->port_devid) {
10198                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10199                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10200                     port->port_devid->len);
10201         }
10202
10203         /*
10204          * This is for the Relative Target Port(type 4h) identifier
10205          */
10206         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10207         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10208             SVPD_ID_TYPE_RELTARG;
10209         desc->length = 4;
10210         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10211         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10212             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10213
10214         /*
10215          * This is for the Target Port Group(type 5h) identifier
10216          */
10217         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10218         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10219             SVPD_ID_TYPE_TPORTGRP;
10220         desc->length = 4;
10221         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10222             &desc->identifier[2]);
10223         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10224             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10225
10226         /*
10227          * This is for the Target identifier
10228          */
10229         if (port->target_devid) {
10230                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10231         }
10232
10233         ctsio->scsi_status = SCSI_STATUS_OK;
10234         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10235         ctsio->be_move_done = ctl_config_move_done;
10236         ctl_datamove((union ctl_io *)ctsio);
10237
10238         return (CTL_RETVAL_COMPLETE);
10239 }
10240
10241 static int
10242 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10243 {
10244         struct ctl_softc *softc = control_softc;
10245         struct scsi_vpd_scsi_ports *sp;
10246         struct scsi_vpd_port_designation *pd;
10247         struct scsi_vpd_port_designation_cont *pdc;
10248         struct ctl_lun *lun;
10249         struct ctl_port *port;
10250         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10251         int num_target_port_groups, single;
10252
10253         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10254
10255         single = ctl_is_single;
10256         if (single)
10257                 num_target_port_groups = 1;
10258         else
10259                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10260         num_target_ports = 0;
10261         iid_len = 0;
10262         id_len = 0;
10263         mtx_lock(&softc->ctl_lock);
10264         STAILQ_FOREACH(port, &softc->port_list, links) {
10265                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10266                         continue;
10267                 if (lun != NULL &&
10268                     ctl_map_lun_back(port->targ_port, lun->lun) >=
10269                     CTL_MAX_LUNS)
10270                         continue;
10271                 num_target_ports++;
10272                 if (port->init_devid)
10273                         iid_len += port->init_devid->len;
10274                 if (port->port_devid)
10275                         id_len += port->port_devid->len;
10276         }
10277         mtx_unlock(&softc->ctl_lock);
10278
10279         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10280             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10281              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10282         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10283         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10284         ctsio->kern_sg_entries = 0;
10285
10286         if (data_len < alloc_len) {
10287                 ctsio->residual = alloc_len - data_len;
10288                 ctsio->kern_data_len = data_len;
10289                 ctsio->kern_total_len = data_len;
10290         } else {
10291                 ctsio->residual = 0;
10292                 ctsio->kern_data_len = alloc_len;
10293                 ctsio->kern_total_len = alloc_len;
10294         }
10295         ctsio->kern_data_resid = 0;
10296         ctsio->kern_rel_offset = 0;
10297         ctsio->kern_sg_entries = 0;
10298
10299         /*
10300          * The control device is always connected.  The disk device, on the
10301          * other hand, may not be online all the time.  Need to change this
10302          * to figure out whether the disk device is actually online or not.
10303          */
10304         if (lun != NULL)
10305                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10306                                   lun->be_lun->lun_type;
10307         else
10308                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10309
10310         sp->page_code = SVPD_SCSI_PORTS;
10311         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10312             sp->page_length);
10313         pd = &sp->design[0];
10314
10315         mtx_lock(&softc->ctl_lock);
10316         if (softc->flags & CTL_FLAG_MASTER_SHELF)
10317                 pg = 0;
10318         else
10319                 pg = 1;
10320         for (g = 0; g < num_target_port_groups; g++) {
10321                 STAILQ_FOREACH(port, &softc->port_list, links) {
10322                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10323                                 continue;
10324                         if (lun != NULL &&
10325                             ctl_map_lun_back(port->targ_port, lun->lun) >=
10326                             CTL_MAX_LUNS)
10327                                 continue;
10328                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10329                         scsi_ulto2b(p, pd->relative_port_id);
10330                         if (port->init_devid && g == pg) {
10331                                 iid_len = port->init_devid->len;
10332                                 memcpy(pd->initiator_transportid,
10333                                     port->init_devid->data, port->init_devid->len);
10334                         } else
10335                                 iid_len = 0;
10336                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10337                         pdc = (struct scsi_vpd_port_designation_cont *)
10338                             (&pd->initiator_transportid[iid_len]);
10339                         if (port->port_devid && g == pg) {
10340                                 id_len = port->port_devid->len;
10341                                 memcpy(pdc->target_port_descriptors,
10342                                     port->port_devid->data, port->port_devid->len);
10343                         } else
10344                                 id_len = 0;
10345                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10346                         pd = (struct scsi_vpd_port_designation *)
10347                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10348                 }
10349         }
10350         mtx_unlock(&softc->ctl_lock);
10351
10352         ctsio->scsi_status = SCSI_STATUS_OK;
10353         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10354         ctsio->be_move_done = ctl_config_move_done;
10355         ctl_datamove((union ctl_io *)ctsio);
10356
10357         return (CTL_RETVAL_COMPLETE);
10358 }
10359
10360 static int
10361 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10362 {
10363         struct scsi_vpd_block_limits *bl_ptr;
10364         struct ctl_lun *lun;
10365         int bs;
10366
10367         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10368
10369         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10370         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10371         ctsio->kern_sg_entries = 0;
10372
10373         if (sizeof(*bl_ptr) < alloc_len) {
10374                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10375                 ctsio->kern_data_len = sizeof(*bl_ptr);
10376                 ctsio->kern_total_len = sizeof(*bl_ptr);
10377         } else {
10378                 ctsio->residual = 0;
10379                 ctsio->kern_data_len = alloc_len;
10380                 ctsio->kern_total_len = alloc_len;
10381         }
10382         ctsio->kern_data_resid = 0;
10383         ctsio->kern_rel_offset = 0;
10384         ctsio->kern_sg_entries = 0;
10385
10386         /*
10387          * The control device is always connected.  The disk device, on the
10388          * other hand, may not be online all the time.  Need to change this
10389          * to figure out whether the disk device is actually online or not.
10390          */
10391         if (lun != NULL)
10392                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10393                                   lun->be_lun->lun_type;
10394         else
10395                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10396
10397         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10398         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10399         bl_ptr->max_cmp_write_len = 0xff;
10400         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10401         if (lun != NULL) {
10402                 bs = lun->be_lun->blocksize;
10403                 scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10404                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10405                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10406                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10407                         if (lun->be_lun->pblockexp != 0) {
10408                                 scsi_ulto4b((1 << lun->be_lun->pblockexp),
10409                                     bl_ptr->opt_unmap_grain);
10410                                 scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10411                                     bl_ptr->unmap_grain_align);
10412                         }
10413                 }
10414                 scsi_ulto4b(lun->be_lun->atomicblock,
10415                     bl_ptr->max_atomic_transfer_length);
10416                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10417                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10418         }
10419         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10420
10421         ctsio->scsi_status = SCSI_STATUS_OK;
10422         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10423         ctsio->be_move_done = ctl_config_move_done;
10424         ctl_datamove((union ctl_io *)ctsio);
10425
10426         return (CTL_RETVAL_COMPLETE);
10427 }
10428
10429 static int
10430 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10431 {
10432         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10433         struct ctl_lun *lun;
10434
10435         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10436
10437         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10438         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10439         ctsio->kern_sg_entries = 0;
10440
10441         if (sizeof(*bdc_ptr) < alloc_len) {
10442                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10443                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10444                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10445         } else {
10446                 ctsio->residual = 0;
10447                 ctsio->kern_data_len = alloc_len;
10448                 ctsio->kern_total_len = alloc_len;
10449         }
10450         ctsio->kern_data_resid = 0;
10451         ctsio->kern_rel_offset = 0;
10452         ctsio->kern_sg_entries = 0;
10453
10454         /*
10455          * The control device is always connected.  The disk device, on the
10456          * other hand, may not be online all the time.  Need to change this
10457          * to figure out whether the disk device is actually online or not.
10458          */
10459         if (lun != NULL)
10460                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10461                                   lun->be_lun->lun_type;
10462         else
10463                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10464         bdc_ptr->page_code = SVPD_BDC;
10465         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10466         scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10467         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10468
10469         ctsio->scsi_status = SCSI_STATUS_OK;
10470         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10471         ctsio->be_move_done = ctl_config_move_done;
10472         ctl_datamove((union ctl_io *)ctsio);
10473
10474         return (CTL_RETVAL_COMPLETE);
10475 }
10476
10477 static int
10478 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10479 {
10480         struct scsi_vpd_logical_block_prov *lbp_ptr;
10481         struct ctl_lun *lun;
10482
10483         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10484
10485         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10486         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10487         ctsio->kern_sg_entries = 0;
10488
10489         if (sizeof(*lbp_ptr) < alloc_len) {
10490                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10491                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10492                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10493         } else {
10494                 ctsio->residual = 0;
10495                 ctsio->kern_data_len = alloc_len;
10496                 ctsio->kern_total_len = alloc_len;
10497         }
10498         ctsio->kern_data_resid = 0;
10499         ctsio->kern_rel_offset = 0;
10500         ctsio->kern_sg_entries = 0;
10501
10502         /*
10503          * The control device is always connected.  The disk device, on the
10504          * other hand, may not be online all the time.  Need to change this
10505          * to figure out whether the disk device is actually online or not.
10506          */
10507         if (lun != NULL)
10508                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10509                                   lun->be_lun->lun_type;
10510         else
10511                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10512
10513         lbp_ptr->page_code = SVPD_LBP;
10514         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10515         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10516                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10517                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10518                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10519         }
10520
10521         ctsio->scsi_status = SCSI_STATUS_OK;
10522         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10523         ctsio->be_move_done = ctl_config_move_done;
10524         ctl_datamove((union ctl_io *)ctsio);
10525
10526         return (CTL_RETVAL_COMPLETE);
10527 }
10528
10529 static int
10530 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10531 {
10532         struct scsi_inquiry *cdb;
10533         struct ctl_lun *lun;
10534         int alloc_len, retval;
10535
10536         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10537         cdb = (struct scsi_inquiry *)ctsio->cdb;
10538
10539         retval = CTL_RETVAL_COMPLETE;
10540
10541         alloc_len = scsi_2btoul(cdb->length);
10542
10543         switch (cdb->page_code) {
10544         case SVPD_SUPPORTED_PAGES:
10545                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10546                 break;
10547         case SVPD_UNIT_SERIAL_NUMBER:
10548                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10549                 break;
10550         case SVPD_DEVICE_ID:
10551                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10552                 break;
10553         case SVPD_EXTENDED_INQUIRY_DATA:
10554                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10555                 break;
10556         case SVPD_MODE_PAGE_POLICY:
10557                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10558                 break;
10559         case SVPD_SCSI_PORTS:
10560                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10561                 break;
10562         case SVPD_SCSI_TPC:
10563                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10564                 break;
10565         case SVPD_BLOCK_LIMITS:
10566                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10567                 break;
10568         case SVPD_BDC:
10569                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10570                 break;
10571         case SVPD_LBP:
10572                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10573                 break;
10574         default:
10575                 ctl_set_invalid_field(ctsio,
10576                                       /*sks_valid*/ 1,
10577                                       /*command*/ 1,
10578                                       /*field*/ 2,
10579                                       /*bit_valid*/ 0,
10580                                       /*bit*/ 0);
10581                 ctl_done((union ctl_io *)ctsio);
10582                 retval = CTL_RETVAL_COMPLETE;
10583                 break;
10584         }
10585
10586         return (retval);
10587 }
10588
10589 static int
10590 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10591 {
10592         struct scsi_inquiry_data *inq_ptr;
10593         struct scsi_inquiry *cdb;
10594         struct ctl_softc *ctl_softc;
10595         struct ctl_lun *lun;
10596         char *val;
10597         uint32_t alloc_len, data_len;
10598         ctl_port_type port_type;
10599
10600         ctl_softc = control_softc;
10601
10602         /*
10603          * Figure out whether we're talking to a Fibre Channel port or not.
10604          * We treat the ioctl front end, and any SCSI adapters, as packetized
10605          * SCSI front ends.
10606          */
10607         port_type = ctl_softc->ctl_ports[
10608             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10609         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10610                 port_type = CTL_PORT_SCSI;
10611
10612         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10613         cdb = (struct scsi_inquiry *)ctsio->cdb;
10614         alloc_len = scsi_2btoul(cdb->length);
10615
10616         /*
10617          * We malloc the full inquiry data size here and fill it
10618          * in.  If the user only asks for less, we'll give him
10619          * that much.
10620          */
10621         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10622         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10623         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10624         ctsio->kern_sg_entries = 0;
10625         ctsio->kern_data_resid = 0;
10626         ctsio->kern_rel_offset = 0;
10627
10628         if (data_len < alloc_len) {
10629                 ctsio->residual = alloc_len - data_len;
10630                 ctsio->kern_data_len = data_len;
10631                 ctsio->kern_total_len = data_len;
10632         } else {
10633                 ctsio->residual = 0;
10634                 ctsio->kern_data_len = alloc_len;
10635                 ctsio->kern_total_len = alloc_len;
10636         }
10637
10638         /*
10639          * If we have a LUN configured, report it as connected.  Otherwise,
10640          * report that it is offline or no device is supported, depending 
10641          * on the value of inquiry_pq_no_lun.
10642          *
10643          * According to the spec (SPC-4 r34), the peripheral qualifier
10644          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10645          *
10646          * "A peripheral device having the specified peripheral device type 
10647          * is not connected to this logical unit. However, the device
10648          * server is capable of supporting the specified peripheral device
10649          * type on this logical unit."
10650          *
10651          * According to the same spec, the peripheral qualifier
10652          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10653          *
10654          * "The device server is not capable of supporting a peripheral
10655          * device on this logical unit. For this peripheral qualifier the
10656          * peripheral device type shall be set to 1Fh. All other peripheral
10657          * device type values are reserved for this peripheral qualifier."
10658          *
10659          * Given the text, it would seem that we probably want to report that
10660          * the LUN is offline here.  There is no LUN connected, but we can
10661          * support a LUN at the given LUN number.
10662          *
10663          * In the real world, though, it sounds like things are a little
10664          * different:
10665          *
10666          * - Linux, when presented with a LUN with the offline peripheral
10667          *   qualifier, will create an sg driver instance for it.  So when
10668          *   you attach it to CTL, you wind up with a ton of sg driver
10669          *   instances.  (One for every LUN that Linux bothered to probe.)
10670          *   Linux does this despite the fact that it issues a REPORT LUNs
10671          *   to LUN 0 to get the inventory of supported LUNs.
10672          *
10673          * - There is other anecdotal evidence (from Emulex folks) about
10674          *   arrays that use the offline peripheral qualifier for LUNs that
10675          *   are on the "passive" path in an active/passive array.
10676          *
10677          * So the solution is provide a hopefully reasonable default
10678          * (return bad/no LUN) and allow the user to change the behavior
10679          * with a tunable/sysctl variable.
10680          */
10681         if (lun != NULL)
10682                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10683                                   lun->be_lun->lun_type;
10684         else if (ctl_softc->inquiry_pq_no_lun == 0)
10685                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10686         else
10687                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10688
10689         /* RMB in byte 2 is 0 */
10690         inq_ptr->version = SCSI_REV_SPC4;
10691
10692         /*
10693          * According to SAM-3, even if a device only supports a single
10694          * level of LUN addressing, it should still set the HISUP bit:
10695          *
10696          * 4.9.1 Logical unit numbers overview
10697          *
10698          * All logical unit number formats described in this standard are
10699          * hierarchical in structure even when only a single level in that
10700          * hierarchy is used. The HISUP bit shall be set to one in the
10701          * standard INQUIRY data (see SPC-2) when any logical unit number
10702          * format described in this standard is used.  Non-hierarchical
10703          * formats are outside the scope of this standard.
10704          *
10705          * Therefore we set the HiSup bit here.
10706          *
10707          * The reponse format is 2, per SPC-3.
10708          */
10709         inq_ptr->response_format = SID_HiSup | 2;
10710
10711         inq_ptr->additional_length = data_len -
10712             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10713         CTL_DEBUG_PRINT(("additional_length = %d\n",
10714                          inq_ptr->additional_length));
10715
10716         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10717         /* 16 bit addressing */
10718         if (port_type == CTL_PORT_SCSI)
10719                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10720         /* XXX set the SID_MultiP bit here if we're actually going to
10721            respond on multiple ports */
10722         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10723
10724         /* 16 bit data bus, synchronous transfers */
10725         if (port_type == CTL_PORT_SCSI)
10726                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10727         /*
10728          * XXX KDM do we want to support tagged queueing on the control
10729          * device at all?
10730          */
10731         if ((lun == NULL)
10732          || (lun->be_lun->lun_type != T_PROCESSOR))
10733                 inq_ptr->flags |= SID_CmdQue;
10734         /*
10735          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10736          * We have 8 bytes for the vendor name, and 16 bytes for the device
10737          * name and 4 bytes for the revision.
10738          */
10739         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10740             "vendor")) == NULL) {
10741                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10742         } else {
10743                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10744                 strncpy(inq_ptr->vendor, val,
10745                     min(sizeof(inq_ptr->vendor), strlen(val)));
10746         }
10747         if (lun == NULL) {
10748                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10749                     sizeof(inq_ptr->product));
10750         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10751                 switch (lun->be_lun->lun_type) {
10752                 case T_DIRECT:
10753                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10754                             sizeof(inq_ptr->product));
10755                         break;
10756                 case T_PROCESSOR:
10757                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10758                             sizeof(inq_ptr->product));
10759                         break;
10760                 default:
10761                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10762                             sizeof(inq_ptr->product));
10763                         break;
10764                 }
10765         } else {
10766                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10767                 strncpy(inq_ptr->product, val,
10768                     min(sizeof(inq_ptr->product), strlen(val)));
10769         }
10770
10771         /*
10772          * XXX make this a macro somewhere so it automatically gets
10773          * incremented when we make changes.
10774          */
10775         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10776             "revision")) == NULL) {
10777                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10778         } else {
10779                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10780                 strncpy(inq_ptr->revision, val,
10781                     min(sizeof(inq_ptr->revision), strlen(val)));
10782         }
10783
10784         /*
10785          * For parallel SCSI, we support double transition and single
10786          * transition clocking.  We also support QAS (Quick Arbitration
10787          * and Selection) and Information Unit transfers on both the
10788          * control and array devices.
10789          */
10790         if (port_type == CTL_PORT_SCSI)
10791                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10792                                     SID_SPI_IUS;
10793
10794         /* SAM-5 (no version claimed) */
10795         scsi_ulto2b(0x00A0, inq_ptr->version1);
10796         /* SPC-4 (no version claimed) */
10797         scsi_ulto2b(0x0460, inq_ptr->version2);
10798         if (port_type == CTL_PORT_FC) {
10799                 /* FCP-2 ANSI INCITS.350:2003 */
10800                 scsi_ulto2b(0x0917, inq_ptr->version3);
10801         } else if (port_type == CTL_PORT_SCSI) {
10802                 /* SPI-4 ANSI INCITS.362:200x */
10803                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10804         } else if (port_type == CTL_PORT_ISCSI) {
10805                 /* iSCSI (no version claimed) */
10806                 scsi_ulto2b(0x0960, inq_ptr->version3);
10807         } else if (port_type == CTL_PORT_SAS) {
10808                 /* SAS (no version claimed) */
10809                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10810         }
10811
10812         if (lun == NULL) {
10813                 /* SBC-4 (no version claimed) */
10814                 scsi_ulto2b(0x0600, inq_ptr->version4);
10815         } else {
10816                 switch (lun->be_lun->lun_type) {
10817                 case T_DIRECT:
10818                         /* SBC-4 (no version claimed) */
10819                         scsi_ulto2b(0x0600, inq_ptr->version4);
10820                         break;
10821                 case T_PROCESSOR:
10822                 default:
10823                         break;
10824                 }
10825         }
10826
10827         ctsio->scsi_status = SCSI_STATUS_OK;
10828         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10829         ctsio->be_move_done = ctl_config_move_done;
10830         ctl_datamove((union ctl_io *)ctsio);
10831         return (CTL_RETVAL_COMPLETE);
10832 }
10833
10834 int
10835 ctl_inquiry(struct ctl_scsiio *ctsio)
10836 {
10837         struct scsi_inquiry *cdb;
10838         int retval;
10839
10840         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10841
10842         cdb = (struct scsi_inquiry *)ctsio->cdb;
10843         if (cdb->byte2 & SI_EVPD)
10844                 retval = ctl_inquiry_evpd(ctsio);
10845         else if (cdb->page_code == 0)
10846                 retval = ctl_inquiry_std(ctsio);
10847         else {
10848                 ctl_set_invalid_field(ctsio,
10849                                       /*sks_valid*/ 1,
10850                                       /*command*/ 1,
10851                                       /*field*/ 2,
10852                                       /*bit_valid*/ 0,
10853                                       /*bit*/ 0);
10854                 ctl_done((union ctl_io *)ctsio);
10855                 return (CTL_RETVAL_COMPLETE);
10856         }
10857
10858         return (retval);
10859 }
10860
10861 /*
10862  * For known CDB types, parse the LBA and length.
10863  */
10864 static int
10865 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10866 {
10867         if (io->io_hdr.io_type != CTL_IO_SCSI)
10868                 return (1);
10869
10870         switch (io->scsiio.cdb[0]) {
10871         case COMPARE_AND_WRITE: {
10872                 struct scsi_compare_and_write *cdb;
10873
10874                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10875
10876                 *lba = scsi_8btou64(cdb->addr);
10877                 *len = cdb->length;
10878                 break;
10879         }
10880         case READ_6:
10881         case WRITE_6: {
10882                 struct scsi_rw_6 *cdb;
10883
10884                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10885
10886                 *lba = scsi_3btoul(cdb->addr);
10887                 /* only 5 bits are valid in the most significant address byte */
10888                 *lba &= 0x1fffff;
10889                 *len = cdb->length;
10890                 break;
10891         }
10892         case READ_10:
10893         case WRITE_10: {
10894                 struct scsi_rw_10 *cdb;
10895
10896                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10897
10898                 *lba = scsi_4btoul(cdb->addr);
10899                 *len = scsi_2btoul(cdb->length);
10900                 break;
10901         }
10902         case WRITE_VERIFY_10: {
10903                 struct scsi_write_verify_10 *cdb;
10904
10905                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10906
10907                 *lba = scsi_4btoul(cdb->addr);
10908                 *len = scsi_2btoul(cdb->length);
10909                 break;
10910         }
10911         case READ_12:
10912         case WRITE_12: {
10913                 struct scsi_rw_12 *cdb;
10914
10915                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10916
10917                 *lba = scsi_4btoul(cdb->addr);
10918                 *len = scsi_4btoul(cdb->length);
10919                 break;
10920         }
10921         case WRITE_VERIFY_12: {
10922                 struct scsi_write_verify_12 *cdb;
10923
10924                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10925
10926                 *lba = scsi_4btoul(cdb->addr);
10927                 *len = scsi_4btoul(cdb->length);
10928                 break;
10929         }
10930         case READ_16:
10931         case WRITE_16:
10932         case WRITE_ATOMIC_16: {
10933                 struct scsi_rw_16 *cdb;
10934
10935                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10936
10937                 *lba = scsi_8btou64(cdb->addr);
10938                 *len = scsi_4btoul(cdb->length);
10939                 break;
10940         }
10941         case WRITE_VERIFY_16: {
10942                 struct scsi_write_verify_16 *cdb;
10943
10944                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10945
10946                 *lba = scsi_8btou64(cdb->addr);
10947                 *len = scsi_4btoul(cdb->length);
10948                 break;
10949         }
10950         case WRITE_SAME_10: {
10951                 struct scsi_write_same_10 *cdb;
10952
10953                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10954
10955                 *lba = scsi_4btoul(cdb->addr);
10956                 *len = scsi_2btoul(cdb->length);
10957                 break;
10958         }
10959         case WRITE_SAME_16: {
10960                 struct scsi_write_same_16 *cdb;
10961
10962                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10963
10964                 *lba = scsi_8btou64(cdb->addr);
10965                 *len = scsi_4btoul(cdb->length);
10966                 break;
10967         }
10968         case VERIFY_10: {
10969                 struct scsi_verify_10 *cdb;
10970
10971                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10972
10973                 *lba = scsi_4btoul(cdb->addr);
10974                 *len = scsi_2btoul(cdb->length);
10975                 break;
10976         }
10977         case VERIFY_12: {
10978                 struct scsi_verify_12 *cdb;
10979
10980                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10981
10982                 *lba = scsi_4btoul(cdb->addr);
10983                 *len = scsi_4btoul(cdb->length);
10984                 break;
10985         }
10986         case VERIFY_16: {
10987                 struct scsi_verify_16 *cdb;
10988
10989                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10990
10991                 *lba = scsi_8btou64(cdb->addr);
10992                 *len = scsi_4btoul(cdb->length);
10993                 break;
10994         }
10995         case UNMAP: {
10996                 *lba = 0;
10997                 *len = UINT64_MAX;
10998                 break;
10999         }
11000         default:
11001                 return (1);
11002                 break; /* NOTREACHED */
11003         }
11004
11005         return (0);
11006 }
11007
11008 static ctl_action
11009 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
11010 {
11011         uint64_t endlba1, endlba2;
11012
11013         endlba1 = lba1 + len1 - 1;
11014         endlba2 = lba2 + len2 - 1;
11015
11016         if ((endlba1 < lba2)
11017          || (endlba2 < lba1))
11018                 return (CTL_ACTION_PASS);
11019         else
11020                 return (CTL_ACTION_BLOCK);
11021 }
11022
11023 static int
11024 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
11025 {
11026         struct ctl_ptr_len_flags *ptrlen;
11027         struct scsi_unmap_desc *buf, *end, *range;
11028         uint64_t lba;
11029         uint32_t len;
11030
11031         /* If not UNMAP -- go other way. */
11032         if (io->io_hdr.io_type != CTL_IO_SCSI ||
11033             io->scsiio.cdb[0] != UNMAP)
11034                 return (CTL_ACTION_ERROR);
11035
11036         /* If UNMAP without data -- block and wait for data. */
11037         ptrlen = (struct ctl_ptr_len_flags *)
11038             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
11039         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
11040             ptrlen->ptr == NULL)
11041                 return (CTL_ACTION_BLOCK);
11042
11043         /* UNMAP with data -- check for collision. */
11044         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
11045         end = buf + ptrlen->len / sizeof(*buf);
11046         for (range = buf; range < end; range++) {
11047                 lba = scsi_8btou64(range->lba);
11048                 len = scsi_4btoul(range->length);
11049                 if ((lba < lba2 + len2) && (lba + len > lba2))
11050                         return (CTL_ACTION_BLOCK);
11051         }
11052         return (CTL_ACTION_PASS);
11053 }
11054
11055 static ctl_action
11056 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
11057 {
11058         uint64_t lba1, lba2;
11059         uint64_t len1, len2;
11060         int retval;
11061
11062         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11063                 return (CTL_ACTION_ERROR);
11064
11065         retval = ctl_extent_check_unmap(io2, lba1, len1);
11066         if (retval != CTL_ACTION_ERROR)
11067                 return (retval);
11068
11069         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11070                 return (CTL_ACTION_ERROR);
11071
11072         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
11073 }
11074
11075 static ctl_action
11076 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11077     union ctl_io *ooa_io)
11078 {
11079         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11080         ctl_serialize_action *serialize_row;
11081
11082         /*
11083          * The initiator attempted multiple untagged commands at the same
11084          * time.  Can't do that.
11085          */
11086         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11087          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11088          && ((pending_io->io_hdr.nexus.targ_port ==
11089               ooa_io->io_hdr.nexus.targ_port)
11090           && (pending_io->io_hdr.nexus.initid.id ==
11091               ooa_io->io_hdr.nexus.initid.id))
11092          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11093                 return (CTL_ACTION_OVERLAP);
11094
11095         /*
11096          * The initiator attempted to send multiple tagged commands with
11097          * the same ID.  (It's fine if different initiators have the same
11098          * tag ID.)
11099          *
11100          * Even if all of those conditions are true, we don't kill the I/O
11101          * if the command ahead of us has been aborted.  We won't end up
11102          * sending it to the FETD, and it's perfectly legal to resend a
11103          * command with the same tag number as long as the previous
11104          * instance of this tag number has been aborted somehow.
11105          */
11106         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11107          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11108          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11109          && ((pending_io->io_hdr.nexus.targ_port ==
11110               ooa_io->io_hdr.nexus.targ_port)
11111           && (pending_io->io_hdr.nexus.initid.id ==
11112               ooa_io->io_hdr.nexus.initid.id))
11113          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11114                 return (CTL_ACTION_OVERLAP_TAG);
11115
11116         /*
11117          * If we get a head of queue tag, SAM-3 says that we should
11118          * immediately execute it.
11119          *
11120          * What happens if this command would normally block for some other
11121          * reason?  e.g. a request sense with a head of queue tag
11122          * immediately after a write.  Normally that would block, but this
11123          * will result in its getting executed immediately...
11124          *
11125          * We currently return "pass" instead of "skip", so we'll end up
11126          * going through the rest of the queue to check for overlapped tags.
11127          *
11128          * XXX KDM check for other types of blockage first??
11129          */
11130         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11131                 return (CTL_ACTION_PASS);
11132
11133         /*
11134          * Ordered tags have to block until all items ahead of them
11135          * have completed.  If we get called with an ordered tag, we always
11136          * block, if something else is ahead of us in the queue.
11137          */
11138         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11139                 return (CTL_ACTION_BLOCK);
11140
11141         /*
11142          * Simple tags get blocked until all head of queue and ordered tags
11143          * ahead of them have completed.  I'm lumping untagged commands in
11144          * with simple tags here.  XXX KDM is that the right thing to do?
11145          */
11146         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11147           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11148          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11149           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11150                 return (CTL_ACTION_BLOCK);
11151
11152         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11153         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11154
11155         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11156
11157         switch (serialize_row[pending_entry->seridx]) {
11158         case CTL_SER_BLOCK:
11159                 return (CTL_ACTION_BLOCK);
11160         case CTL_SER_EXTENT:
11161                 return (ctl_extent_check(pending_io, ooa_io));
11162         case CTL_SER_EXTENTOPT:
11163                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11164                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11165                         return (ctl_extent_check(pending_io, ooa_io));
11166                 /* FALLTHROUGH */
11167         case CTL_SER_PASS:
11168                 return (CTL_ACTION_PASS);
11169         case CTL_SER_BLOCKOPT:
11170                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11171                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11172                         return (CTL_ACTION_BLOCK);
11173                 return (CTL_ACTION_PASS);
11174         case CTL_SER_SKIP:
11175                 return (CTL_ACTION_SKIP);
11176         default:
11177                 panic("invalid serialization value %d",
11178                       serialize_row[pending_entry->seridx]);
11179         }
11180
11181         return (CTL_ACTION_ERROR);
11182 }
11183
11184 /*
11185  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11186  * Assumptions:
11187  * - pending_io is generally either incoming, or on the blocked queue
11188  * - starting I/O is the I/O we want to start the check with.
11189  */
11190 static ctl_action
11191 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11192               union ctl_io *starting_io)
11193 {
11194         union ctl_io *ooa_io;
11195         ctl_action action;
11196
11197         mtx_assert(&lun->lun_lock, MA_OWNED);
11198
11199         /*
11200          * Run back along the OOA queue, starting with the current
11201          * blocked I/O and going through every I/O before it on the
11202          * queue.  If starting_io is NULL, we'll just end up returning
11203          * CTL_ACTION_PASS.
11204          */
11205         for (ooa_io = starting_io; ooa_io != NULL;
11206              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11207              ooa_links)){
11208
11209                 /*
11210                  * This routine just checks to see whether
11211                  * cur_blocked is blocked by ooa_io, which is ahead
11212                  * of it in the queue.  It doesn't queue/dequeue
11213                  * cur_blocked.
11214                  */
11215                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11216                 switch (action) {
11217                 case CTL_ACTION_BLOCK:
11218                 case CTL_ACTION_OVERLAP:
11219                 case CTL_ACTION_OVERLAP_TAG:
11220                 case CTL_ACTION_SKIP:
11221                 case CTL_ACTION_ERROR:
11222                         return (action);
11223                         break; /* NOTREACHED */
11224                 case CTL_ACTION_PASS:
11225                         break;
11226                 default:
11227                         panic("invalid action %d", action);
11228                         break;  /* NOTREACHED */
11229                 }
11230         }
11231
11232         return (CTL_ACTION_PASS);
11233 }
11234
11235 /*
11236  * Assumptions:
11237  * - An I/O has just completed, and has been removed from the per-LUN OOA
11238  *   queue, so some items on the blocked queue may now be unblocked.
11239  */
11240 static int
11241 ctl_check_blocked(struct ctl_lun *lun)
11242 {
11243         union ctl_io *cur_blocked, *next_blocked;
11244
11245         mtx_assert(&lun->lun_lock, MA_OWNED);
11246
11247         /*
11248          * Run forward from the head of the blocked queue, checking each
11249          * entry against the I/Os prior to it on the OOA queue to see if
11250          * there is still any blockage.
11251          *
11252          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11253          * with our removing a variable on it while it is traversing the
11254          * list.
11255          */
11256         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11257              cur_blocked != NULL; cur_blocked = next_blocked) {
11258                 union ctl_io *prev_ooa;
11259                 ctl_action action;
11260
11261                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11262                                                           blocked_links);
11263
11264                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11265                                                       ctl_ooaq, ooa_links);
11266
11267                 /*
11268                  * If cur_blocked happens to be the first item in the OOA
11269                  * queue now, prev_ooa will be NULL, and the action
11270                  * returned will just be CTL_ACTION_PASS.
11271                  */
11272                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11273
11274                 switch (action) {
11275                 case CTL_ACTION_BLOCK:
11276                         /* Nothing to do here, still blocked */
11277                         break;
11278                 case CTL_ACTION_OVERLAP:
11279                 case CTL_ACTION_OVERLAP_TAG:
11280                         /*
11281                          * This shouldn't happen!  In theory we've already
11282                          * checked this command for overlap...
11283                          */
11284                         break;
11285                 case CTL_ACTION_PASS:
11286                 case CTL_ACTION_SKIP: {
11287                         struct ctl_softc *softc;
11288                         const struct ctl_cmd_entry *entry;
11289                         uint32_t initidx;
11290                         int isc_retval;
11291
11292                         /*
11293                          * The skip case shouldn't happen, this transaction
11294                          * should have never made it onto the blocked queue.
11295                          */
11296                         /*
11297                          * This I/O is no longer blocked, we can remove it
11298                          * from the blocked queue.  Since this is a TAILQ
11299                          * (doubly linked list), we can do O(1) removals
11300                          * from any place on the list.
11301                          */
11302                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11303                                      blocked_links);
11304                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11305
11306                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11307                                 /*
11308                                  * Need to send IO back to original side to
11309                                  * run
11310                                  */
11311                                 union ctl_ha_msg msg_info;
11312
11313                                 msg_info.hdr.original_sc =
11314                                         cur_blocked->io_hdr.original_sc;
11315                                 msg_info.hdr.serializing_sc = cur_blocked;
11316                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11317                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11318                                      &msg_info, sizeof(msg_info), 0)) >
11319                                      CTL_HA_STATUS_SUCCESS) {
11320                                         printf("CTL:Check Blocked error from "
11321                                                "ctl_ha_msg_send %d\n",
11322                                                isc_retval);
11323                                 }
11324                                 break;
11325                         }
11326                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11327                         softc = control_softc;
11328
11329                         initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11330
11331                         /*
11332                          * Check this I/O for LUN state changes that may
11333                          * have happened while this command was blocked.
11334                          * The LUN state may have been changed by a command
11335                          * ahead of us in the queue, so we need to re-check
11336                          * for any states that can be caused by SCSI
11337                          * commands.
11338                          */
11339                         if (ctl_scsiio_lun_check(softc, lun, entry,
11340                                                  &cur_blocked->scsiio) == 0) {
11341                                 cur_blocked->io_hdr.flags |=
11342                                                       CTL_FLAG_IS_WAS_ON_RTR;
11343                                 ctl_enqueue_rtr(cur_blocked);
11344                         } else
11345                                 ctl_done(cur_blocked);
11346                         break;
11347                 }
11348                 default:
11349                         /*
11350                          * This probably shouldn't happen -- we shouldn't
11351                          * get CTL_ACTION_ERROR, or anything else.
11352                          */
11353                         break;
11354                 }
11355         }
11356
11357         return (CTL_RETVAL_COMPLETE);
11358 }
11359
11360 /*
11361  * This routine (with one exception) checks LUN flags that can be set by
11362  * commands ahead of us in the OOA queue.  These flags have to be checked
11363  * when a command initially comes in, and when we pull a command off the
11364  * blocked queue and are preparing to execute it.  The reason we have to
11365  * check these flags for commands on the blocked queue is that the LUN
11366  * state may have been changed by a command ahead of us while we're on the
11367  * blocked queue.
11368  *
11369  * Ordering is somewhat important with these checks, so please pay
11370  * careful attention to the placement of any new checks.
11371  */
11372 static int
11373 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11374     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11375 {
11376         int retval;
11377         uint32_t residx;
11378
11379         retval = 0;
11380
11381         mtx_assert(&lun->lun_lock, MA_OWNED);
11382
11383         /*
11384          * If this shelf is a secondary shelf controller, we have to reject
11385          * any media access commands.
11386          */
11387 #if 0
11388         /* No longer needed for HA */
11389         if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11390          && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11391                 ctl_set_lun_standby(ctsio);
11392                 retval = 1;
11393                 goto bailout;
11394         }
11395 #endif
11396
11397         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11398                 if (lun->flags & CTL_LUN_READONLY) {
11399                         ctl_set_sense(ctsio, /*current_error*/ 1,
11400                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11401                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11402                         retval = 1;
11403                         goto bailout;
11404                 }
11405                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11406                     .eca_and_aen & SCP_SWP) != 0) {
11407                         ctl_set_sense(ctsio, /*current_error*/ 1,
11408                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11409                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11410                         retval = 1;
11411                         goto bailout;
11412                 }
11413         }
11414
11415         /*
11416          * Check for a reservation conflict.  If this command isn't allowed
11417          * even on reserved LUNs, and if this initiator isn't the one who
11418          * reserved us, reject the command with a reservation conflict.
11419          */
11420         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11421         if ((lun->flags & CTL_LUN_RESERVED)
11422          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11423                 if (lun->res_idx != residx) {
11424                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11425                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11426                         retval = 1;
11427                         goto bailout;
11428                 }
11429         }
11430
11431         if ((lun->flags & CTL_LUN_PR_RESERVED)
11432          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11433                 /*
11434                  * if we aren't registered or it's a res holder type
11435                  * reservation and this isn't the res holder then set a
11436                  * conflict.
11437                  * NOTE: Commands which might be allowed on write exclusive
11438                  * type reservations are checked in the particular command
11439                  * for a conflict. Read and SSU are the only ones.
11440                  */
11441                 if (lun->pr_keys[residx] == 0
11442                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11443                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11444                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11445                         retval = 1;
11446                         goto bailout;
11447                 }
11448
11449         }
11450
11451         if ((lun->flags & CTL_LUN_OFFLINE)
11452          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11453                 ctl_set_lun_not_ready(ctsio);
11454                 retval = 1;
11455                 goto bailout;
11456         }
11457
11458         /*
11459          * If the LUN is stopped, see if this particular command is allowed
11460          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11461          */
11462         if ((lun->flags & CTL_LUN_STOPPED)
11463          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11464                 /* "Logical unit not ready, initializing cmd. required" */
11465                 ctl_set_lun_stopped(ctsio);
11466                 retval = 1;
11467                 goto bailout;
11468         }
11469
11470         if ((lun->flags & CTL_LUN_INOPERABLE)
11471          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11472                 /* "Medium format corrupted" */
11473                 ctl_set_medium_format_corrupted(ctsio);
11474                 retval = 1;
11475                 goto bailout;
11476         }
11477
11478 bailout:
11479         return (retval);
11480
11481 }
11482
11483 static void
11484 ctl_failover_io(union ctl_io *io, int have_lock)
11485 {
11486         ctl_set_busy(&io->scsiio);
11487         ctl_done(io);
11488 }
11489
11490 static void
11491 ctl_failover(void)
11492 {
11493         struct ctl_lun *lun;
11494         struct ctl_softc *ctl_softc;
11495         union ctl_io *next_io, *pending_io;
11496         union ctl_io *io;
11497         int lun_idx;
11498         int i;
11499
11500         ctl_softc = control_softc;
11501
11502         mtx_lock(&ctl_softc->ctl_lock);
11503         /*
11504          * Remove any cmds from the other SC from the rtr queue.  These
11505          * will obviously only be for LUNs for which we're the primary.
11506          * We can't send status or get/send data for these commands.
11507          * Since they haven't been executed yet, we can just remove them.
11508          * We'll either abort them or delete them below, depending on
11509          * which HA mode we're in.
11510          */
11511 #ifdef notyet
11512         mtx_lock(&ctl_softc->queue_lock);
11513         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11514              io != NULL; io = next_io) {
11515                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11516                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11517                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11518                                       ctl_io_hdr, links);
11519         }
11520         mtx_unlock(&ctl_softc->queue_lock);
11521 #endif
11522
11523         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11524                 lun = ctl_softc->ctl_luns[lun_idx];
11525                 if (lun==NULL)
11526                         continue;
11527
11528                 /*
11529                  * Processor LUNs are primary on both sides.
11530                  * XXX will this always be true?
11531                  */
11532                 if (lun->be_lun->lun_type == T_PROCESSOR)
11533                         continue;
11534
11535                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11536                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11537                         printf("FAILOVER: primary lun %d\n", lun_idx);
11538                         /*
11539                          * Remove all commands from the other SC. First from the
11540                          * blocked queue then from the ooa queue. Once we have
11541                          * removed them. Call ctl_check_blocked to see if there
11542                          * is anything that can run.
11543                          */
11544                         for (io = (union ctl_io *)TAILQ_FIRST(
11545                              &lun->blocked_queue); io != NULL; io = next_io) {
11546
11547                                 next_io = (union ctl_io *)TAILQ_NEXT(
11548                                     &io->io_hdr, blocked_links);
11549
11550                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11551                                         TAILQ_REMOVE(&lun->blocked_queue,
11552                                                      &io->io_hdr,blocked_links);
11553                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11554                                         TAILQ_REMOVE(&lun->ooa_queue,
11555                                                      &io->io_hdr, ooa_links);
11556
11557                                         ctl_free_io(io);
11558                                 }
11559                         }
11560
11561                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11562                              io != NULL; io = next_io) {
11563
11564                                 next_io = (union ctl_io *)TAILQ_NEXT(
11565                                     &io->io_hdr, ooa_links);
11566
11567                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11568
11569                                         TAILQ_REMOVE(&lun->ooa_queue,
11570                                                 &io->io_hdr,
11571                                                 ooa_links);
11572
11573                                         ctl_free_io(io);
11574                                 }
11575                         }
11576                         ctl_check_blocked(lun);
11577                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11578                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11579
11580                         printf("FAILOVER: primary lun %d\n", lun_idx);
11581                         /*
11582                          * Abort all commands from the other SC.  We can't
11583                          * send status back for them now.  These should get
11584                          * cleaned up when they are completed or come out
11585                          * for a datamove operation.
11586                          */
11587                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11588                              io != NULL; io = next_io) {
11589                                 next_io = (union ctl_io *)TAILQ_NEXT(
11590                                         &io->io_hdr, ooa_links);
11591
11592                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11593                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11594                         }
11595                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11596                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11597
11598                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11599
11600                         lun->flags |= CTL_LUN_PRIMARY_SC;
11601
11602                         /*
11603                          * We send all I/O that was sent to this controller
11604                          * and redirected to the other side back with
11605                          * busy status, and have the initiator retry it.
11606                          * Figuring out how much data has been transferred,
11607                          * etc. and picking up where we left off would be 
11608                          * very tricky.
11609                          *
11610                          * XXX KDM need to remove I/O from the blocked
11611                          * queue as well!
11612                          */
11613                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11614                              &lun->ooa_queue); pending_io != NULL;
11615                              pending_io = next_io) {
11616
11617                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11618                                         &pending_io->io_hdr, ooa_links);
11619
11620                                 pending_io->io_hdr.flags &=
11621                                         ~CTL_FLAG_SENT_2OTHER_SC;
11622
11623                                 if (pending_io->io_hdr.flags &
11624                                     CTL_FLAG_IO_ACTIVE) {
11625                                         pending_io->io_hdr.flags |=
11626                                                 CTL_FLAG_FAILOVER;
11627                                 } else {
11628                                         ctl_set_busy(&pending_io->scsiio);
11629                                         ctl_done(pending_io);
11630                                 }
11631                         }
11632
11633                         /*
11634                          * Build Unit Attention
11635                          */
11636                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11637                                 lun->pending_ua[i] |=
11638                                                      CTL_UA_ASYM_ACC_CHANGE;
11639                         }
11640                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11641                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11642                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11643                         /*
11644                          * if the first io on the OOA is not on the RtR queue
11645                          * add it.
11646                          */
11647                         lun->flags |= CTL_LUN_PRIMARY_SC;
11648
11649                         pending_io = (union ctl_io *)TAILQ_FIRST(
11650                             &lun->ooa_queue);
11651                         if (pending_io==NULL) {
11652                                 printf("Nothing on OOA queue\n");
11653                                 continue;
11654                         }
11655
11656                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11657                         if ((pending_io->io_hdr.flags &
11658                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11659                                 pending_io->io_hdr.flags |=
11660                                     CTL_FLAG_IS_WAS_ON_RTR;
11661                                 ctl_enqueue_rtr(pending_io);
11662                         }
11663 #if 0
11664                         else
11665                         {
11666                                 printf("Tag 0x%04x is running\n",
11667                                       pending_io->scsiio.tag_num);
11668                         }
11669 #endif
11670
11671                         next_io = (union ctl_io *)TAILQ_NEXT(
11672                             &pending_io->io_hdr, ooa_links);
11673                         for (pending_io=next_io; pending_io != NULL;
11674                              pending_io = next_io) {
11675                                 pending_io->io_hdr.flags &=
11676                                     ~CTL_FLAG_SENT_2OTHER_SC;
11677                                 next_io = (union ctl_io *)TAILQ_NEXT(
11678                                         &pending_io->io_hdr, ooa_links);
11679                                 if (pending_io->io_hdr.flags &
11680                                     CTL_FLAG_IS_WAS_ON_RTR) {
11681 #if 0
11682                                         printf("Tag 0x%04x is running\n",
11683                                                 pending_io->scsiio.tag_num);
11684 #endif
11685                                         continue;
11686                                 }
11687
11688                                 switch (ctl_check_ooa(lun, pending_io,
11689                                     (union ctl_io *)TAILQ_PREV(
11690                                     &pending_io->io_hdr, ctl_ooaq,
11691                                     ooa_links))) {
11692
11693                                 case CTL_ACTION_BLOCK:
11694                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11695                                                           &pending_io->io_hdr,
11696                                                           blocked_links);
11697                                         pending_io->io_hdr.flags |=
11698                                             CTL_FLAG_BLOCKED;
11699                                         break;
11700                                 case CTL_ACTION_PASS:
11701                                 case CTL_ACTION_SKIP:
11702                                         pending_io->io_hdr.flags |=
11703                                             CTL_FLAG_IS_WAS_ON_RTR;
11704                                         ctl_enqueue_rtr(pending_io);
11705                                         break;
11706                                 case CTL_ACTION_OVERLAP:
11707                                         ctl_set_overlapped_cmd(
11708                                             (struct ctl_scsiio *)pending_io);
11709                                         ctl_done(pending_io);
11710                                         break;
11711                                 case CTL_ACTION_OVERLAP_TAG:
11712                                         ctl_set_overlapped_tag(
11713                                             (struct ctl_scsiio *)pending_io,
11714                                             pending_io->scsiio.tag_num & 0xff);
11715                                         ctl_done(pending_io);
11716                                         break;
11717                                 case CTL_ACTION_ERROR:
11718                                 default:
11719                                         ctl_set_internal_failure(
11720                                                 (struct ctl_scsiio *)pending_io,
11721                                                 0,  // sks_valid
11722                                                 0); //retry count
11723                                         ctl_done(pending_io);
11724                                         break;
11725                                 }
11726                         }
11727
11728                         /*
11729                          * Build Unit Attention
11730                          */
11731                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11732                                 lun->pending_ua[i] |=
11733                                                      CTL_UA_ASYM_ACC_CHANGE;
11734                         }
11735                 } else {
11736                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11737                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11738                 }
11739         }
11740         ctl_pause_rtr = 0;
11741         mtx_unlock(&ctl_softc->ctl_lock);
11742 }
11743
11744 static int
11745 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11746 {
11747         struct ctl_lun *lun;
11748         const struct ctl_cmd_entry *entry;
11749         uint32_t initidx, targ_lun;
11750         int retval;
11751
11752         retval = 0;
11753
11754         lun = NULL;
11755
11756         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11757         if ((targ_lun < CTL_MAX_LUNS)
11758          && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11759                 lun = ctl_softc->ctl_luns[targ_lun];
11760                 /*
11761                  * If the LUN is invalid, pretend that it doesn't exist.
11762                  * It will go away as soon as all pending I/O has been
11763                  * completed.
11764                  */
11765                 if (lun->flags & CTL_LUN_DISABLED) {
11766                         lun = NULL;
11767                 } else {
11768                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11769                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11770                                 lun->be_lun;
11771                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11772                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11773                         }
11774
11775                         /*
11776                          * Every I/O goes into the OOA queue for a
11777                          * particular LUN, and stays there until completion.
11778                          */
11779                         mtx_lock(&lun->lun_lock);
11780                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11781                             ooa_links);
11782                 }
11783         } else {
11784                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11785                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11786         }
11787
11788         /* Get command entry and return error if it is unsuppotyed. */
11789         entry = ctl_validate_command(ctsio);
11790         if (entry == NULL) {
11791                 if (lun)
11792                         mtx_unlock(&lun->lun_lock);
11793                 return (retval);
11794         }
11795
11796         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11797         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11798
11799         /*
11800          * Check to see whether we can send this command to LUNs that don't
11801          * exist.  This should pretty much only be the case for inquiry
11802          * and request sense.  Further checks, below, really require having
11803          * a LUN, so we can't really check the command anymore.  Just put
11804          * it on the rtr queue.
11805          */
11806         if (lun == NULL) {
11807                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11808                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11809                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11810                         return (retval);
11811                 }
11812
11813                 ctl_set_unsupported_lun(ctsio);
11814                 ctl_done((union ctl_io *)ctsio);
11815                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11816                 return (retval);
11817         } else {
11818                 /*
11819                  * Make sure we support this particular command on this LUN.
11820                  * e.g., we don't support writes to the control LUN.
11821                  */
11822                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11823                         mtx_unlock(&lun->lun_lock);
11824                         ctl_set_invalid_opcode(ctsio);
11825                         ctl_done((union ctl_io *)ctsio);
11826                         return (retval);
11827                 }
11828         }
11829
11830         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11831
11832 #ifdef CTL_WITH_CA
11833         /*
11834          * If we've got a request sense, it'll clear the contingent
11835          * allegiance condition.  Otherwise, if we have a CA condition for
11836          * this initiator, clear it, because it sent down a command other
11837          * than request sense.
11838          */
11839         if ((ctsio->cdb[0] != REQUEST_SENSE)
11840          && (ctl_is_set(lun->have_ca, initidx)))
11841                 ctl_clear_mask(lun->have_ca, initidx);
11842 #endif
11843
11844         /*
11845          * If the command has this flag set, it handles its own unit
11846          * attention reporting, we shouldn't do anything.  Otherwise we
11847          * check for any pending unit attentions, and send them back to the
11848          * initiator.  We only do this when a command initially comes in,
11849          * not when we pull it off the blocked queue.
11850          *
11851          * According to SAM-3, section 5.3.2, the order that things get
11852          * presented back to the host is basically unit attentions caused
11853          * by some sort of reset event, busy status, reservation conflicts
11854          * or task set full, and finally any other status.
11855          *
11856          * One issue here is that some of the unit attentions we report
11857          * don't fall into the "reset" category (e.g. "reported luns data
11858          * has changed").  So reporting it here, before the reservation
11859          * check, may be technically wrong.  I guess the only thing to do
11860          * would be to check for and report the reset events here, and then
11861          * check for the other unit attention types after we check for a
11862          * reservation conflict.
11863          *
11864          * XXX KDM need to fix this
11865          */
11866         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11867                 ctl_ua_type ua_type;
11868
11869                 if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11870                         scsi_sense_data_type sense_format;
11871
11872                         if (lun != NULL)
11873                                 sense_format = (lun->flags &
11874                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11875                                     SSD_TYPE_FIXED;
11876                         else
11877                                 sense_format = SSD_TYPE_FIXED;
11878
11879                         ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11880                             &ctsio->sense_data, sense_format);
11881                         if (ua_type != CTL_UA_NONE) {
11882                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11883                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11884                                                        CTL_AUTOSENSE;
11885                                 ctsio->sense_len = SSD_FULL_SIZE;
11886                                 mtx_unlock(&lun->lun_lock);
11887                                 ctl_done((union ctl_io *)ctsio);
11888                                 return (retval);
11889                         }
11890                 }
11891         }
11892
11893
11894         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11895                 mtx_unlock(&lun->lun_lock);
11896                 ctl_done((union ctl_io *)ctsio);
11897                 return (retval);
11898         }
11899
11900         /*
11901          * XXX CHD this is where we want to send IO to other side if
11902          * this LUN is secondary on this SC. We will need to make a copy
11903          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11904          * the copy we send as FROM_OTHER.
11905          * We also need to stuff the address of the original IO so we can
11906          * find it easily. Something similar will need be done on the other
11907          * side so when we are done we can find the copy.
11908          */
11909         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11910                 union ctl_ha_msg msg_info;
11911                 int isc_retval;
11912
11913                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11914
11915                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11916                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11917 #if 0
11918                 printf("1. ctsio %p\n", ctsio);
11919 #endif
11920                 msg_info.hdr.serializing_sc = NULL;
11921                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11922                 msg_info.scsi.tag_num = ctsio->tag_num;
11923                 msg_info.scsi.tag_type = ctsio->tag_type;
11924                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11925
11926                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11927
11928                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11929                     (void *)&msg_info, sizeof(msg_info), 0)) >
11930                     CTL_HA_STATUS_SUCCESS) {
11931                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11932                                isc_retval);
11933                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11934                 } else {
11935 #if 0
11936                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11937 #endif
11938                 }
11939
11940                 /*
11941                  * XXX KDM this I/O is off the incoming queue, but hasn't
11942                  * been inserted on any other queue.  We may need to come
11943                  * up with a holding queue while we wait for serialization
11944                  * so that we have an idea of what we're waiting for from
11945                  * the other side.
11946                  */
11947                 mtx_unlock(&lun->lun_lock);
11948                 return (retval);
11949         }
11950
11951         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11952                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11953                               ctl_ooaq, ooa_links))) {
11954         case CTL_ACTION_BLOCK:
11955                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11956                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11957                                   blocked_links);
11958                 mtx_unlock(&lun->lun_lock);
11959                 return (retval);
11960         case CTL_ACTION_PASS:
11961         case CTL_ACTION_SKIP:
11962                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11963                 mtx_unlock(&lun->lun_lock);
11964                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11965                 break;
11966         case CTL_ACTION_OVERLAP:
11967                 mtx_unlock(&lun->lun_lock);
11968                 ctl_set_overlapped_cmd(ctsio);
11969                 ctl_done((union ctl_io *)ctsio);
11970                 break;
11971         case CTL_ACTION_OVERLAP_TAG:
11972                 mtx_unlock(&lun->lun_lock);
11973                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11974                 ctl_done((union ctl_io *)ctsio);
11975                 break;
11976         case CTL_ACTION_ERROR:
11977         default:
11978                 mtx_unlock(&lun->lun_lock);
11979                 ctl_set_internal_failure(ctsio,
11980                                          /*sks_valid*/ 0,
11981                                          /*retry_count*/ 0);
11982                 ctl_done((union ctl_io *)ctsio);
11983                 break;
11984         }
11985         return (retval);
11986 }
11987
11988 const struct ctl_cmd_entry *
11989 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11990 {
11991         const struct ctl_cmd_entry *entry;
11992         int service_action;
11993
11994         entry = &ctl_cmd_table[ctsio->cdb[0]];
11995         if (sa)
11996                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11997         if (entry->flags & CTL_CMD_FLAG_SA5) {
11998                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11999                 entry = &((const struct ctl_cmd_entry *)
12000                     entry->execute)[service_action];
12001         }
12002         return (entry);
12003 }
12004
12005 const struct ctl_cmd_entry *
12006 ctl_validate_command(struct ctl_scsiio *ctsio)
12007 {
12008         const struct ctl_cmd_entry *entry;
12009         int i, sa;
12010         uint8_t diff;
12011
12012         entry = ctl_get_cmd_entry(ctsio, &sa);
12013         if (entry->execute == NULL) {
12014                 if (sa)
12015                         ctl_set_invalid_field(ctsio,
12016                                               /*sks_valid*/ 1,
12017                                               /*command*/ 1,
12018                                               /*field*/ 1,
12019                                               /*bit_valid*/ 1,
12020                                               /*bit*/ 4);
12021                 else
12022                         ctl_set_invalid_opcode(ctsio);
12023                 ctl_done((union ctl_io *)ctsio);
12024                 return (NULL);
12025         }
12026         KASSERT(entry->length > 0,
12027             ("Not defined length for command 0x%02x/0x%02x",
12028              ctsio->cdb[0], ctsio->cdb[1]));
12029         for (i = 1; i < entry->length; i++) {
12030                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
12031                 if (diff == 0)
12032                         continue;
12033                 ctl_set_invalid_field(ctsio,
12034                                       /*sks_valid*/ 1,
12035                                       /*command*/ 1,
12036                                       /*field*/ i,
12037                                       /*bit_valid*/ 1,
12038                                       /*bit*/ fls(diff) - 1);
12039                 ctl_done((union ctl_io *)ctsio);
12040                 return (NULL);
12041         }
12042         return (entry);
12043 }
12044
12045 static int
12046 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
12047 {
12048
12049         switch (lun_type) {
12050         case T_PROCESSOR:
12051                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
12052                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12053                         return (0);
12054                 break;
12055         case T_DIRECT:
12056                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
12057                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12058                         return (0);
12059                 break;
12060         default:
12061                 return (0);
12062         }
12063         return (1);
12064 }
12065
12066 static int
12067 ctl_scsiio(struct ctl_scsiio *ctsio)
12068 {
12069         int retval;
12070         const struct ctl_cmd_entry *entry;
12071
12072         retval = CTL_RETVAL_COMPLETE;
12073
12074         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12075
12076         entry = ctl_get_cmd_entry(ctsio, NULL);
12077
12078         /*
12079          * If this I/O has been aborted, just send it straight to
12080          * ctl_done() without executing it.
12081          */
12082         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12083                 ctl_done((union ctl_io *)ctsio);
12084                 goto bailout;
12085         }
12086
12087         /*
12088          * All the checks should have been handled by ctl_scsiio_precheck().
12089          * We should be clear now to just execute the I/O.
12090          */
12091         retval = entry->execute(ctsio);
12092
12093 bailout:
12094         return (retval);
12095 }
12096
12097 /*
12098  * Since we only implement one target right now, a bus reset simply resets
12099  * our single target.
12100  */
12101 static int
12102 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
12103 {
12104         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
12105 }
12106
12107 static int
12108 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
12109                  ctl_ua_type ua_type)
12110 {
12111         struct ctl_lun *lun;
12112         int retval;
12113
12114         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12115                 union ctl_ha_msg msg_info;
12116
12117                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12118                 msg_info.hdr.nexus = io->io_hdr.nexus;
12119                 if (ua_type==CTL_UA_TARG_RESET)
12120                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12121                 else
12122                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
12123                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12124                 msg_info.hdr.original_sc = NULL;
12125                 msg_info.hdr.serializing_sc = NULL;
12126                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12127                     (void *)&msg_info, sizeof(msg_info), 0)) {
12128                 }
12129         }
12130         retval = 0;
12131
12132         mtx_lock(&ctl_softc->ctl_lock);
12133         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12134                 retval += ctl_lun_reset(lun, io, ua_type);
12135         mtx_unlock(&ctl_softc->ctl_lock);
12136
12137         return (retval);
12138 }
12139
12140 /*
12141  * The LUN should always be set.  The I/O is optional, and is used to
12142  * distinguish between I/Os sent by this initiator, and by other
12143  * initiators.  We set unit attention for initiators other than this one.
12144  * SAM-3 is vague on this point.  It does say that a unit attention should
12145  * be established for other initiators when a LUN is reset (see section
12146  * 5.7.3), but it doesn't specifically say that the unit attention should
12147  * be established for this particular initiator when a LUN is reset.  Here
12148  * is the relevant text, from SAM-3 rev 8:
12149  *
12150  * 5.7.2 When a SCSI initiator port aborts its own tasks
12151  *
12152  * When a SCSI initiator port causes its own task(s) to be aborted, no
12153  * notification that the task(s) have been aborted shall be returned to
12154  * the SCSI initiator port other than the completion response for the
12155  * command or task management function action that caused the task(s) to
12156  * be aborted and notification(s) associated with related effects of the
12157  * action (e.g., a reset unit attention condition).
12158  *
12159  * XXX KDM for now, we're setting unit attention for all initiators.
12160  */
12161 static int
12162 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12163 {
12164         union ctl_io *xio;
12165 #if 0
12166         uint32_t initindex;
12167 #endif
12168         int i;
12169
12170         mtx_lock(&lun->lun_lock);
12171         /*
12172          * Run through the OOA queue and abort each I/O.
12173          */
12174 #if 0
12175         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12176 #endif
12177         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12178              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12179                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12180         }
12181
12182         /*
12183          * This version sets unit attention for every
12184          */
12185 #if 0
12186         initindex = ctl_get_initindex(&io->io_hdr.nexus);
12187         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12188                 if (initindex == i)
12189                         continue;
12190                 lun->pending_ua[i] |= ua_type;
12191         }
12192 #endif
12193
12194         /*
12195          * A reset (any kind, really) clears reservations established with
12196          * RESERVE/RELEASE.  It does not clear reservations established
12197          * with PERSISTENT RESERVE OUT, but we don't support that at the
12198          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12199          * reservations made with the RESERVE/RELEASE commands, because
12200          * those commands are obsolete in SPC-3.
12201          */
12202         lun->flags &= ~CTL_LUN_RESERVED;
12203
12204         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12205 #ifdef CTL_WITH_CA
12206                 ctl_clear_mask(lun->have_ca, i);
12207 #endif
12208                 lun->pending_ua[i] |= ua_type;
12209         }
12210         mtx_unlock(&lun->lun_lock);
12211
12212         return (0);
12213 }
12214
12215 static void
12216 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12217     int other_sc)
12218 {
12219         union ctl_io *xio;
12220
12221         mtx_assert(&lun->lun_lock, MA_OWNED);
12222
12223         /*
12224          * Run through the OOA queue and attempt to find the given I/O.
12225          * The target port, initiator ID, tag type and tag number have to
12226          * match the values that we got from the initiator.  If we have an
12227          * untagged command to abort, simply abort the first untagged command
12228          * we come to.  We only allow one untagged command at a time of course.
12229          */
12230         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12231              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12232
12233                 if ((targ_port == UINT32_MAX ||
12234                      targ_port == xio->io_hdr.nexus.targ_port) &&
12235                     (init_id == UINT32_MAX ||
12236                      init_id == xio->io_hdr.nexus.initid.id)) {
12237                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12238                             init_id != xio->io_hdr.nexus.initid.id)
12239                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12240                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12241                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12242                                 union ctl_ha_msg msg_info;
12243
12244                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12245                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12246                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12247                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12248                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12249                                 msg_info.hdr.original_sc = NULL;
12250                                 msg_info.hdr.serializing_sc = NULL;
12251                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12252                                     (void *)&msg_info, sizeof(msg_info), 0);
12253                         }
12254                 }
12255         }
12256 }
12257
12258 static int
12259 ctl_abort_task_set(union ctl_io *io)
12260 {
12261         struct ctl_softc *softc = control_softc;
12262         struct ctl_lun *lun;
12263         uint32_t targ_lun;
12264
12265         /*
12266          * Look up the LUN.
12267          */
12268         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12269         mtx_lock(&softc->ctl_lock);
12270         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12271                 lun = softc->ctl_luns[targ_lun];
12272         else {
12273                 mtx_unlock(&softc->ctl_lock);
12274                 return (1);
12275         }
12276
12277         mtx_lock(&lun->lun_lock);
12278         mtx_unlock(&softc->ctl_lock);
12279         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12280                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12281                     io->io_hdr.nexus.initid.id,
12282                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12283         } else { /* CTL_TASK_CLEAR_TASK_SET */
12284                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12285                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12286         }
12287         mtx_unlock(&lun->lun_lock);
12288         return (0);
12289 }
12290
12291 static int
12292 ctl_i_t_nexus_reset(union ctl_io *io)
12293 {
12294         struct ctl_softc *softc = control_softc;
12295         struct ctl_lun *lun;
12296         uint32_t initindex, residx;
12297
12298         initindex = ctl_get_initindex(&io->io_hdr.nexus);
12299         residx = ctl_get_resindex(&io->io_hdr.nexus);
12300         mtx_lock(&softc->ctl_lock);
12301         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12302                 mtx_lock(&lun->lun_lock);
12303                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12304                     io->io_hdr.nexus.initid.id,
12305                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12306 #ifdef CTL_WITH_CA
12307                 ctl_clear_mask(lun->have_ca, initindex);
12308 #endif
12309                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12310                         lun->flags &= ~CTL_LUN_RESERVED;
12311                 lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12312                 mtx_unlock(&lun->lun_lock);
12313         }
12314         mtx_unlock(&softc->ctl_lock);
12315         return (0);
12316 }
12317
12318 static int
12319 ctl_abort_task(union ctl_io *io)
12320 {
12321         union ctl_io *xio;
12322         struct ctl_lun *lun;
12323         struct ctl_softc *ctl_softc;
12324 #if 0
12325         struct sbuf sb;
12326         char printbuf[128];
12327 #endif
12328         int found;
12329         uint32_t targ_lun;
12330
12331         ctl_softc = control_softc;
12332         found = 0;
12333
12334         /*
12335          * Look up the LUN.
12336          */
12337         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12338         mtx_lock(&ctl_softc->ctl_lock);
12339         if ((targ_lun < CTL_MAX_LUNS)
12340          && (ctl_softc->ctl_luns[targ_lun] != NULL))
12341                 lun = ctl_softc->ctl_luns[targ_lun];
12342         else {
12343                 mtx_unlock(&ctl_softc->ctl_lock);
12344                 return (1);
12345         }
12346
12347 #if 0
12348         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12349                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12350 #endif
12351
12352         mtx_lock(&lun->lun_lock);
12353         mtx_unlock(&ctl_softc->ctl_lock);
12354         /*
12355          * Run through the OOA queue and attempt to find the given I/O.
12356          * The target port, initiator ID, tag type and tag number have to
12357          * match the values that we got from the initiator.  If we have an
12358          * untagged command to abort, simply abort the first untagged command
12359          * we come to.  We only allow one untagged command at a time of course.
12360          */
12361 #if 0
12362         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12363 #endif
12364         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12365              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12366 #if 0
12367                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12368
12369                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12370                             lun->lun, xio->scsiio.tag_num,
12371                             xio->scsiio.tag_type,
12372                             (xio->io_hdr.blocked_links.tqe_prev
12373                             == NULL) ? "" : " BLOCKED",
12374                             (xio->io_hdr.flags &
12375                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12376                             (xio->io_hdr.flags &
12377                             CTL_FLAG_ABORT) ? " ABORT" : "",
12378                             (xio->io_hdr.flags &
12379                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12380                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12381                 sbuf_finish(&sb);
12382                 printf("%s\n", sbuf_data(&sb));
12383 #endif
12384
12385                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12386                  && (xio->io_hdr.nexus.initid.id ==
12387                      io->io_hdr.nexus.initid.id)) {
12388                         /*
12389                          * If the abort says that the task is untagged, the
12390                          * task in the queue must be untagged.  Otherwise,
12391                          * we just check to see whether the tag numbers
12392                          * match.  This is because the QLogic firmware
12393                          * doesn't pass back the tag type in an abort
12394                          * request.
12395                          */
12396 #if 0
12397                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12398                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12399                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12400 #endif
12401                         /*
12402                          * XXX KDM we've got problems with FC, because it
12403                          * doesn't send down a tag type with aborts.  So we
12404                          * can only really go by the tag number...
12405                          * This may cause problems with parallel SCSI.
12406                          * Need to figure that out!!
12407                          */
12408                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12409                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12410                                 found = 1;
12411                                 if ((io->io_hdr.flags &
12412                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12413                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12414                                         union ctl_ha_msg msg_info;
12415
12416                                         io->io_hdr.flags |=
12417                                                         CTL_FLAG_SENT_2OTHER_SC;
12418                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12419                                         msg_info.task.task_action =
12420                                                 CTL_TASK_ABORT_TASK;
12421                                         msg_info.task.tag_num =
12422                                                 io->taskio.tag_num;
12423                                         msg_info.task.tag_type =
12424                                                 io->taskio.tag_type;
12425                                         msg_info.hdr.msg_type =
12426                                                 CTL_MSG_MANAGE_TASKS;
12427                                         msg_info.hdr.original_sc = NULL;
12428                                         msg_info.hdr.serializing_sc = NULL;
12429 #if 0
12430                                         printf("Sent Abort to other side\n");
12431 #endif
12432                                         if (CTL_HA_STATUS_SUCCESS !=
12433                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12434                                                 (void *)&msg_info,
12435                                                 sizeof(msg_info), 0)) {
12436                                         }
12437                                 }
12438 #if 0
12439                                 printf("ctl_abort_task: found I/O to abort\n");
12440 #endif
12441                                 break;
12442                         }
12443                 }
12444         }
12445         mtx_unlock(&lun->lun_lock);
12446
12447         if (found == 0) {
12448                 /*
12449                  * This isn't really an error.  It's entirely possible for
12450                  * the abort and command completion to cross on the wire.
12451                  * This is more of an informative/diagnostic error.
12452                  */
12453 #if 0
12454                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12455                        "%d:%d:%d:%d tag %d type %d\n",
12456                        io->io_hdr.nexus.initid.id,
12457                        io->io_hdr.nexus.targ_port,
12458                        io->io_hdr.nexus.targ_target.id,
12459                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12460                        io->taskio.tag_type);
12461 #endif
12462         }
12463         return (0);
12464 }
12465
12466 static void
12467 ctl_run_task(union ctl_io *io)
12468 {
12469         struct ctl_softc *ctl_softc = control_softc;
12470         int retval = 1;
12471         const char *task_desc;
12472
12473         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12474
12475         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12476             ("ctl_run_task: Unextected io_type %d\n",
12477              io->io_hdr.io_type));
12478
12479         task_desc = ctl_scsi_task_string(&io->taskio);
12480         if (task_desc != NULL) {
12481 #ifdef NEEDTOPORT
12482                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12483                             CTL_TASK_REPORT,
12484                             csevent_LogType_Trace,
12485                             csevent_Severity_Information,
12486                             csevent_AlertLevel_Green,
12487                             csevent_FRU_Firmware,
12488                             csevent_FRU_Unknown,
12489                             "CTL: received task: %s",task_desc);
12490 #endif
12491         } else {
12492 #ifdef NEEDTOPORT
12493                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12494                             CTL_TASK_REPORT,
12495                             csevent_LogType_Trace,
12496                             csevent_Severity_Information,
12497                             csevent_AlertLevel_Green,
12498                             csevent_FRU_Firmware,
12499                             csevent_FRU_Unknown,
12500                             "CTL: received unknown task "
12501                             "type: %d (%#x)",
12502                             io->taskio.task_action,
12503                             io->taskio.task_action);
12504 #endif
12505         }
12506         switch (io->taskio.task_action) {
12507         case CTL_TASK_ABORT_TASK:
12508                 retval = ctl_abort_task(io);
12509                 break;
12510         case CTL_TASK_ABORT_TASK_SET:
12511         case CTL_TASK_CLEAR_TASK_SET:
12512                 retval = ctl_abort_task_set(io);
12513                 break;
12514         case CTL_TASK_CLEAR_ACA:
12515                 break;
12516         case CTL_TASK_I_T_NEXUS_RESET:
12517                 retval = ctl_i_t_nexus_reset(io);
12518                 break;
12519         case CTL_TASK_LUN_RESET: {
12520                 struct ctl_lun *lun;
12521                 uint32_t targ_lun;
12522
12523                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12524                 mtx_lock(&ctl_softc->ctl_lock);
12525                 if ((targ_lun < CTL_MAX_LUNS)
12526                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12527                         lun = ctl_softc->ctl_luns[targ_lun];
12528                 else {
12529                         mtx_unlock(&ctl_softc->ctl_lock);
12530                         retval = 1;
12531                         break;
12532                 }
12533
12534                 if (!(io->io_hdr.flags &
12535                     CTL_FLAG_FROM_OTHER_SC)) {
12536                         union ctl_ha_msg msg_info;
12537
12538                         io->io_hdr.flags |=
12539                                 CTL_FLAG_SENT_2OTHER_SC;
12540                         msg_info.hdr.msg_type =
12541                                 CTL_MSG_MANAGE_TASKS;
12542                         msg_info.hdr.nexus = io->io_hdr.nexus;
12543                         msg_info.task.task_action =
12544                                 CTL_TASK_LUN_RESET;
12545                         msg_info.hdr.original_sc = NULL;
12546                         msg_info.hdr.serializing_sc = NULL;
12547                         if (CTL_HA_STATUS_SUCCESS !=
12548                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12549                             (void *)&msg_info,
12550                             sizeof(msg_info), 0)) {
12551                         }
12552                 }
12553
12554                 retval = ctl_lun_reset(lun, io,
12555                                        CTL_UA_LUN_RESET);
12556                 mtx_unlock(&ctl_softc->ctl_lock);
12557                 break;
12558         }
12559         case CTL_TASK_TARGET_RESET:
12560                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12561                 break;
12562         case CTL_TASK_BUS_RESET:
12563                 retval = ctl_bus_reset(ctl_softc, io);
12564                 break;
12565         case CTL_TASK_PORT_LOGIN:
12566                 break;
12567         case CTL_TASK_PORT_LOGOUT:
12568                 break;
12569         default:
12570                 printf("ctl_run_task: got unknown task management event %d\n",
12571                        io->taskio.task_action);
12572                 break;
12573         }
12574         if (retval == 0)
12575                 io->io_hdr.status = CTL_SUCCESS;
12576         else
12577                 io->io_hdr.status = CTL_ERROR;
12578         ctl_done(io);
12579 }
12580
12581 /*
12582  * For HA operation.  Handle commands that come in from the other
12583  * controller.
12584  */
12585 static void
12586 ctl_handle_isc(union ctl_io *io)
12587 {
12588         int free_io;
12589         struct ctl_lun *lun;
12590         struct ctl_softc *ctl_softc;
12591         uint32_t targ_lun;
12592
12593         ctl_softc = control_softc;
12594
12595         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12596         lun = ctl_softc->ctl_luns[targ_lun];
12597
12598         switch (io->io_hdr.msg_type) {
12599         case CTL_MSG_SERIALIZE:
12600                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12601                 break;
12602         case CTL_MSG_R2R: {
12603                 const struct ctl_cmd_entry *entry;
12604
12605                 /*
12606                  * This is only used in SER_ONLY mode.
12607                  */
12608                 free_io = 0;
12609                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12610                 mtx_lock(&lun->lun_lock);
12611                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12612                     entry, (struct ctl_scsiio *)io) != 0) {
12613                         mtx_unlock(&lun->lun_lock);
12614                         ctl_done(io);
12615                         break;
12616                 }
12617                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12618                 mtx_unlock(&lun->lun_lock);
12619                 ctl_enqueue_rtr(io);
12620                 break;
12621         }
12622         case CTL_MSG_FINISH_IO:
12623                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12624                         free_io = 0;
12625                         ctl_done(io);
12626                 } else {
12627                         free_io = 1;
12628                         mtx_lock(&lun->lun_lock);
12629                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12630                                      ooa_links);
12631                         ctl_check_blocked(lun);
12632                         mtx_unlock(&lun->lun_lock);
12633                 }
12634                 break;
12635         case CTL_MSG_PERS_ACTION:
12636                 ctl_hndl_per_res_out_on_other_sc(
12637                         (union ctl_ha_msg *)&io->presio.pr_msg);
12638                 free_io = 1;
12639                 break;
12640         case CTL_MSG_BAD_JUJU:
12641                 free_io = 0;
12642                 ctl_done(io);
12643                 break;
12644         case CTL_MSG_DATAMOVE:
12645                 /* Only used in XFER mode */
12646                 free_io = 0;
12647                 ctl_datamove_remote(io);
12648                 break;
12649         case CTL_MSG_DATAMOVE_DONE:
12650                 /* Only used in XFER mode */
12651                 free_io = 0;
12652                 io->scsiio.be_move_done(io);
12653                 break;
12654         default:
12655                 free_io = 1;
12656                 printf("%s: Invalid message type %d\n",
12657                        __func__, io->io_hdr.msg_type);
12658                 break;
12659         }
12660         if (free_io)
12661                 ctl_free_io(io);
12662
12663 }
12664
12665
12666 /*
12667  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12668  * there is no match.
12669  */
12670 static ctl_lun_error_pattern
12671 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12672 {
12673         const struct ctl_cmd_entry *entry;
12674         ctl_lun_error_pattern filtered_pattern, pattern;
12675
12676         pattern = desc->error_pattern;
12677
12678         /*
12679          * XXX KDM we need more data passed into this function to match a
12680          * custom pattern, and we actually need to implement custom pattern
12681          * matching.
12682          */
12683         if (pattern & CTL_LUN_PAT_CMD)
12684                 return (CTL_LUN_PAT_CMD);
12685
12686         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12687                 return (CTL_LUN_PAT_ANY);
12688
12689         entry = ctl_get_cmd_entry(ctsio, NULL);
12690
12691         filtered_pattern = entry->pattern & pattern;
12692
12693         /*
12694          * If the user requested specific flags in the pattern (e.g.
12695          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12696          * flags.
12697          *
12698          * If the user did not specify any flags, it doesn't matter whether
12699          * or not the command supports the flags.
12700          */
12701         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12702              (pattern & ~CTL_LUN_PAT_MASK))
12703                 return (CTL_LUN_PAT_NONE);
12704
12705         /*
12706          * If the user asked for a range check, see if the requested LBA
12707          * range overlaps with this command's LBA range.
12708          */
12709         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12710                 uint64_t lba1;
12711                 uint64_t len1;
12712                 ctl_action action;
12713                 int retval;
12714
12715                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12716                 if (retval != 0)
12717                         return (CTL_LUN_PAT_NONE);
12718
12719                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12720                                               desc->lba_range.len);
12721                 /*
12722                  * A "pass" means that the LBA ranges don't overlap, so
12723                  * this doesn't match the user's range criteria.
12724                  */
12725                 if (action == CTL_ACTION_PASS)
12726                         return (CTL_LUN_PAT_NONE);
12727         }
12728
12729         return (filtered_pattern);
12730 }
12731
12732 static void
12733 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12734 {
12735         struct ctl_error_desc *desc, *desc2;
12736
12737         mtx_assert(&lun->lun_lock, MA_OWNED);
12738
12739         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12740                 ctl_lun_error_pattern pattern;
12741                 /*
12742                  * Check to see whether this particular command matches
12743                  * the pattern in the descriptor.
12744                  */
12745                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12746                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12747                         continue;
12748
12749                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12750                 case CTL_LUN_INJ_ABORTED:
12751                         ctl_set_aborted(&io->scsiio);
12752                         break;
12753                 case CTL_LUN_INJ_MEDIUM_ERR:
12754                         ctl_set_medium_error(&io->scsiio);
12755                         break;
12756                 case CTL_LUN_INJ_UA:
12757                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12758                          * OCCURRED */
12759                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12760                         break;
12761                 case CTL_LUN_INJ_CUSTOM:
12762                         /*
12763                          * We're assuming the user knows what he is doing.
12764                          * Just copy the sense information without doing
12765                          * checks.
12766                          */
12767                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12768                               ctl_min(sizeof(desc->custom_sense),
12769                                       sizeof(io->scsiio.sense_data)));
12770                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12771                         io->scsiio.sense_len = SSD_FULL_SIZE;
12772                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12773                         break;
12774                 case CTL_LUN_INJ_NONE:
12775                 default:
12776                         /*
12777                          * If this is an error injection type we don't know
12778                          * about, clear the continuous flag (if it is set)
12779                          * so it will get deleted below.
12780                          */
12781                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12782                         break;
12783                 }
12784                 /*
12785                  * By default, each error injection action is a one-shot
12786                  */
12787                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12788                         continue;
12789
12790                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12791
12792                 free(desc, M_CTL);
12793         }
12794 }
12795
12796 #ifdef CTL_IO_DELAY
12797 static void
12798 ctl_datamove_timer_wakeup(void *arg)
12799 {
12800         union ctl_io *io;
12801
12802         io = (union ctl_io *)arg;
12803
12804         ctl_datamove(io);
12805 }
12806 #endif /* CTL_IO_DELAY */
12807
12808 void
12809 ctl_datamove(union ctl_io *io)
12810 {
12811         void (*fe_datamove)(union ctl_io *io);
12812
12813         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12814
12815         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12816
12817 #ifdef CTL_TIME_IO
12818         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12819                 char str[256];
12820                 char path_str[64];
12821                 struct sbuf sb;
12822
12823                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12824                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12825
12826                 sbuf_cat(&sb, path_str);
12827                 switch (io->io_hdr.io_type) {
12828                 case CTL_IO_SCSI:
12829                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12830                         sbuf_printf(&sb, "\n");
12831                         sbuf_cat(&sb, path_str);
12832                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12833                                     io->scsiio.tag_num, io->scsiio.tag_type);
12834                         break;
12835                 case CTL_IO_TASK:
12836                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12837                                     "Tag Type: %d\n", io->taskio.task_action,
12838                                     io->taskio.tag_num, io->taskio.tag_type);
12839                         break;
12840                 default:
12841                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12842                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12843                         break;
12844                 }
12845                 sbuf_cat(&sb, path_str);
12846                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12847                             (intmax_t)time_uptime - io->io_hdr.start_time);
12848                 sbuf_finish(&sb);
12849                 printf("%s", sbuf_data(&sb));
12850         }
12851 #endif /* CTL_TIME_IO */
12852
12853 #ifdef CTL_IO_DELAY
12854         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12855                 struct ctl_lun *lun;
12856
12857                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12858
12859                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12860         } else {
12861                 struct ctl_lun *lun;
12862
12863                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12864                 if ((lun != NULL)
12865                  && (lun->delay_info.datamove_delay > 0)) {
12866                         struct callout *callout;
12867
12868                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12869                         callout_init(callout, /*mpsafe*/ 1);
12870                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12871                         callout_reset(callout,
12872                                       lun->delay_info.datamove_delay * hz,
12873                                       ctl_datamove_timer_wakeup, io);
12874                         if (lun->delay_info.datamove_type ==
12875                             CTL_DELAY_TYPE_ONESHOT)
12876                                 lun->delay_info.datamove_delay = 0;
12877                         return;
12878                 }
12879         }
12880 #endif
12881
12882         /*
12883          * This command has been aborted.  Set the port status, so we fail
12884          * the data move.
12885          */
12886         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12887                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12888                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12889                        io->io_hdr.nexus.targ_port,
12890                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12891                        io->io_hdr.nexus.targ_lun);
12892                 io->io_hdr.port_status = 31337;
12893                 /*
12894                  * Note that the backend, in this case, will get the
12895                  * callback in its context.  In other cases it may get
12896                  * called in the frontend's interrupt thread context.
12897                  */
12898                 io->scsiio.be_move_done(io);
12899                 return;
12900         }
12901
12902         /* Don't confuse frontend with zero length data move. */
12903         if (io->scsiio.kern_data_len == 0) {
12904                 io->scsiio.be_move_done(io);
12905                 return;
12906         }
12907
12908         /*
12909          * If we're in XFER mode and this I/O is from the other shelf
12910          * controller, we need to send the DMA to the other side to
12911          * actually transfer the data to/from the host.  In serialize only
12912          * mode the transfer happens below CTL and ctl_datamove() is only
12913          * called on the machine that originally received the I/O.
12914          */
12915         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12916          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12917                 union ctl_ha_msg msg;
12918                 uint32_t sg_entries_sent;
12919                 int do_sg_copy;
12920                 int i;
12921
12922                 memset(&msg, 0, sizeof(msg));
12923                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12924                 msg.hdr.original_sc = io->io_hdr.original_sc;
12925                 msg.hdr.serializing_sc = io;
12926                 msg.hdr.nexus = io->io_hdr.nexus;
12927                 msg.dt.flags = io->io_hdr.flags;
12928                 /*
12929                  * We convert everything into a S/G list here.  We can't
12930                  * pass by reference, only by value between controllers.
12931                  * So we can't pass a pointer to the S/G list, only as many
12932                  * S/G entries as we can fit in here.  If it's possible for
12933                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12934                  * then we need to break this up into multiple transfers.
12935                  */
12936                 if (io->scsiio.kern_sg_entries == 0) {
12937                         msg.dt.kern_sg_entries = 1;
12938                         /*
12939                          * If this is in cached memory, flush the cache
12940                          * before we send the DMA request to the other
12941                          * controller.  We want to do this in either the
12942                          * read or the write case.  The read case is
12943                          * straightforward.  In the write case, we want to
12944                          * make sure nothing is in the local cache that
12945                          * could overwrite the DMAed data.
12946                          */
12947                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12948                                 /*
12949                                  * XXX KDM use bus_dmamap_sync() here.
12950                                  */
12951                         }
12952
12953                         /*
12954                          * Convert to a physical address if this is a
12955                          * virtual address.
12956                          */
12957                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12958                                 msg.dt.sg_list[0].addr =
12959                                         io->scsiio.kern_data_ptr;
12960                         } else {
12961                                 /*
12962                                  * XXX KDM use busdma here!
12963                                  */
12964 #if 0
12965                                 msg.dt.sg_list[0].addr = (void *)
12966                                         vtophys(io->scsiio.kern_data_ptr);
12967 #endif
12968                         }
12969
12970                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12971                         do_sg_copy = 0;
12972                 } else {
12973                         struct ctl_sg_entry *sgl;
12974
12975                         do_sg_copy = 1;
12976                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12977                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12978                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12979                                 /*
12980                                  * XXX KDM use bus_dmamap_sync() here.
12981                                  */
12982                         }
12983                 }
12984
12985                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12986                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12987                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12988                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12989                 msg.dt.sg_sequence = 0;
12990
12991                 /*
12992                  * Loop until we've sent all of the S/G entries.  On the
12993                  * other end, we'll recompose these S/G entries into one
12994                  * contiguous list before passing it to the
12995                  */
12996                 for (sg_entries_sent = 0; sg_entries_sent <
12997                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12998                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12999                                 sizeof(msg.dt.sg_list[0])),
13000                                 msg.dt.kern_sg_entries - sg_entries_sent);
13001
13002                         if (do_sg_copy != 0) {
13003                                 struct ctl_sg_entry *sgl;
13004                                 int j;
13005
13006                                 sgl = (struct ctl_sg_entry *)
13007                                         io->scsiio.kern_data_ptr;
13008                                 /*
13009                                  * If this is in cached memory, flush the cache
13010                                  * before we send the DMA request to the other
13011                                  * controller.  We want to do this in either
13012                                  * the * read or the write case.  The read
13013                                  * case is straightforward.  In the write
13014                                  * case, we want to make sure nothing is
13015                                  * in the local cache that could overwrite
13016                                  * the DMAed data.
13017                                  */
13018
13019                                 for (i = sg_entries_sent, j = 0;
13020                                      i < msg.dt.cur_sg_entries; i++, j++) {
13021                                         if ((io->io_hdr.flags &
13022                                              CTL_FLAG_NO_DATASYNC) == 0) {
13023                                                 /*
13024                                                  * XXX KDM use bus_dmamap_sync()
13025                                                  */
13026                                         }
13027                                         if ((io->io_hdr.flags &
13028                                              CTL_FLAG_BUS_ADDR) == 0) {
13029                                                 /*
13030                                                  * XXX KDM use busdma.
13031                                                  */
13032 #if 0
13033                                                 msg.dt.sg_list[j].addr =(void *)
13034                                                        vtophys(sgl[i].addr);
13035 #endif
13036                                         } else {
13037                                                 msg.dt.sg_list[j].addr =
13038                                                         sgl[i].addr;
13039                                         }
13040                                         msg.dt.sg_list[j].len = sgl[i].len;
13041                                 }
13042                         }
13043
13044                         sg_entries_sent += msg.dt.cur_sg_entries;
13045                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
13046                                 msg.dt.sg_last = 1;
13047                         else
13048                                 msg.dt.sg_last = 0;
13049
13050                         /*
13051                          * XXX KDM drop and reacquire the lock here?
13052                          */
13053                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13054                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13055                                 /*
13056                                  * XXX do something here.
13057                                  */
13058                         }
13059
13060                         msg.dt.sent_sg_entries = sg_entries_sent;
13061                 }
13062                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13063                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
13064                         ctl_failover_io(io, /*have_lock*/ 0);
13065
13066         } else {
13067
13068                 /*
13069                  * Lookup the fe_datamove() function for this particular
13070                  * front end.
13071                  */
13072                 fe_datamove =
13073                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13074
13075                 fe_datamove(io);
13076         }
13077 }
13078
13079 static void
13080 ctl_send_datamove_done(union ctl_io *io, int have_lock)
13081 {
13082         union ctl_ha_msg msg;
13083         int isc_status;
13084
13085         memset(&msg, 0, sizeof(msg));
13086
13087         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13088         msg.hdr.original_sc = io;
13089         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13090         msg.hdr.nexus = io->io_hdr.nexus;
13091         msg.hdr.status = io->io_hdr.status;
13092         msg.scsi.tag_num = io->scsiio.tag_num;
13093         msg.scsi.tag_type = io->scsiio.tag_type;
13094         msg.scsi.scsi_status = io->scsiio.scsi_status;
13095         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13096                sizeof(io->scsiio.sense_data));
13097         msg.scsi.sense_len = io->scsiio.sense_len;
13098         msg.scsi.sense_residual = io->scsiio.sense_residual;
13099         msg.scsi.fetd_status = io->io_hdr.port_status;
13100         msg.scsi.residual = io->scsiio.residual;
13101         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13102
13103         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13104                 ctl_failover_io(io, /*have_lock*/ have_lock);
13105                 return;
13106         }
13107
13108         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13109         if (isc_status > CTL_HA_STATUS_SUCCESS) {
13110                 /* XXX do something if this fails */
13111         }
13112
13113 }
13114
13115 /*
13116  * The DMA to the remote side is done, now we need to tell the other side
13117  * we're done so it can continue with its data movement.
13118  */
13119 static void
13120 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13121 {
13122         union ctl_io *io;
13123
13124         io = rq->context;
13125
13126         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13127                 printf("%s: ISC DMA write failed with error %d", __func__,
13128                        rq->ret);
13129                 ctl_set_internal_failure(&io->scsiio,
13130                                          /*sks_valid*/ 1,
13131                                          /*retry_count*/ rq->ret);
13132         }
13133
13134         ctl_dt_req_free(rq);
13135
13136         /*
13137          * In this case, we had to malloc the memory locally.  Free it.
13138          */
13139         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13140                 int i;
13141                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13142                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13143         }
13144         /*
13145          * The data is in local and remote memory, so now we need to send
13146          * status (good or back) back to the other side.
13147          */
13148         ctl_send_datamove_done(io, /*have_lock*/ 0);
13149 }
13150
13151 /*
13152  * We've moved the data from the host/controller into local memory.  Now we
13153  * need to push it over to the remote controller's memory.
13154  */
13155 static int
13156 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13157 {
13158         int retval;
13159
13160         retval = 0;
13161
13162         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13163                                           ctl_datamove_remote_write_cb);
13164
13165         return (retval);
13166 }
13167
13168 static void
13169 ctl_datamove_remote_write(union ctl_io *io)
13170 {
13171         int retval;
13172         void (*fe_datamove)(union ctl_io *io);
13173
13174         /*
13175          * - Get the data from the host/HBA into local memory.
13176          * - DMA memory from the local controller to the remote controller.
13177          * - Send status back to the remote controller.
13178          */
13179
13180         retval = ctl_datamove_remote_sgl_setup(io);
13181         if (retval != 0)
13182                 return;
13183
13184         /* Switch the pointer over so the FETD knows what to do */
13185         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13186
13187         /*
13188          * Use a custom move done callback, since we need to send completion
13189          * back to the other controller, not to the backend on this side.
13190          */
13191         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13192
13193         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13194
13195         fe_datamove(io);
13196
13197         return;
13198
13199 }
13200
13201 static int
13202 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13203 {
13204 #if 0
13205         char str[256];
13206         char path_str[64];
13207         struct sbuf sb;
13208 #endif
13209
13210         /*
13211          * In this case, we had to malloc the memory locally.  Free it.
13212          */
13213         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13214                 int i;
13215                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13216                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13217         }
13218
13219 #if 0
13220         scsi_path_string(io, path_str, sizeof(path_str));
13221         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13222         sbuf_cat(&sb, path_str);
13223         scsi_command_string(&io->scsiio, NULL, &sb);
13224         sbuf_printf(&sb, "\n");
13225         sbuf_cat(&sb, path_str);
13226         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13227                     io->scsiio.tag_num, io->scsiio.tag_type);
13228         sbuf_cat(&sb, path_str);
13229         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13230                     io->io_hdr.flags, io->io_hdr.status);
13231         sbuf_finish(&sb);
13232         printk("%s", sbuf_data(&sb));
13233 #endif
13234
13235
13236         /*
13237          * The read is done, now we need to send status (good or bad) back
13238          * to the other side.
13239          */
13240         ctl_send_datamove_done(io, /*have_lock*/ 0);
13241
13242         return (0);
13243 }
13244
13245 static void
13246 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13247 {
13248         union ctl_io *io;
13249         void (*fe_datamove)(union ctl_io *io);
13250
13251         io = rq->context;
13252
13253         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13254                 printf("%s: ISC DMA read failed with error %d", __func__,
13255                        rq->ret);
13256                 ctl_set_internal_failure(&io->scsiio,
13257                                          /*sks_valid*/ 1,
13258                                          /*retry_count*/ rq->ret);
13259         }
13260
13261         ctl_dt_req_free(rq);
13262
13263         /* Switch the pointer over so the FETD knows what to do */
13264         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13265
13266         /*
13267          * Use a custom move done callback, since we need to send completion
13268          * back to the other controller, not to the backend on this side.
13269          */
13270         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13271
13272         /* XXX KDM add checks like the ones in ctl_datamove? */
13273
13274         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13275
13276         fe_datamove(io);
13277 }
13278
13279 static int
13280 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13281 {
13282         struct ctl_sg_entry *local_sglist, *remote_sglist;
13283         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13284         struct ctl_softc *softc;
13285         int retval;
13286         int i;
13287
13288         retval = 0;
13289         softc = control_softc;
13290
13291         local_sglist = io->io_hdr.local_sglist;
13292         local_dma_sglist = io->io_hdr.local_dma_sglist;
13293         remote_sglist = io->io_hdr.remote_sglist;
13294         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13295
13296         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13297                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13298                         local_sglist[i].len = remote_sglist[i].len;
13299
13300                         /*
13301                          * XXX Detect the situation where the RS-level I/O
13302                          * redirector on the other side has already read the
13303                          * data off of the AOR RS on this side, and
13304                          * transferred it to remote (mirror) memory on the
13305                          * other side.  Since we already have the data in
13306                          * memory here, we just need to use it.
13307                          *
13308                          * XXX KDM this can probably be removed once we
13309                          * get the cache device code in and take the
13310                          * current AOR implementation out.
13311                          */
13312 #ifdef NEEDTOPORT
13313                         if ((remote_sglist[i].addr >=
13314                              (void *)vtophys(softc->mirr->addr))
13315                          && (remote_sglist[i].addr <
13316                              ((void *)vtophys(softc->mirr->addr) +
13317                              CacheMirrorOffset))) {
13318                                 local_sglist[i].addr = remote_sglist[i].addr -
13319                                         CacheMirrorOffset;
13320                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13321                                      CTL_FLAG_DATA_IN)
13322                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13323                         } else {
13324                                 local_sglist[i].addr = remote_sglist[i].addr +
13325                                         CacheMirrorOffset;
13326                         }
13327 #endif
13328 #if 0
13329                         printf("%s: local %p, remote %p, len %d\n",
13330                                __func__, local_sglist[i].addr,
13331                                remote_sglist[i].addr, local_sglist[i].len);
13332 #endif
13333                 }
13334         } else {
13335                 uint32_t len_to_go;
13336
13337                 /*
13338                  * In this case, we don't have automatically allocated
13339                  * memory for this I/O on this controller.  This typically
13340                  * happens with internal CTL I/O -- e.g. inquiry, mode
13341                  * sense, etc.  Anything coming from RAIDCore will have
13342                  * a mirror area available.
13343                  */
13344                 len_to_go = io->scsiio.kern_data_len;
13345
13346                 /*
13347                  * Clear the no datasync flag, we have to use malloced
13348                  * buffers.
13349                  */
13350                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13351
13352                 /*
13353                  * The difficult thing here is that the size of the various
13354                  * S/G segments may be different than the size from the
13355                  * remote controller.  That'll make it harder when DMAing
13356                  * the data back to the other side.
13357                  */
13358                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13359                      sizeof(io->io_hdr.remote_sglist[0])) &&
13360                      (len_to_go > 0); i++) {
13361                         local_sglist[i].len = ctl_min(len_to_go, 131072);
13362                         CTL_SIZE_8B(local_dma_sglist[i].len,
13363                                     local_sglist[i].len);
13364                         local_sglist[i].addr =
13365                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13366
13367                         local_dma_sglist[i].addr = local_sglist[i].addr;
13368
13369                         if (local_sglist[i].addr == NULL) {
13370                                 int j;
13371
13372                                 printf("malloc failed for %zd bytes!",
13373                                        local_dma_sglist[i].len);
13374                                 for (j = 0; j < i; j++) {
13375                                         free(local_sglist[j].addr, M_CTL);
13376                                 }
13377                                 ctl_set_internal_failure(&io->scsiio,
13378                                                          /*sks_valid*/ 1,
13379                                                          /*retry_count*/ 4857);
13380                                 retval = 1;
13381                                 goto bailout_error;
13382                                 
13383                         }
13384                         /* XXX KDM do we need a sync here? */
13385
13386                         len_to_go -= local_sglist[i].len;
13387                 }
13388                 /*
13389                  * Reset the number of S/G entries accordingly.  The
13390                  * original number of S/G entries is available in
13391                  * rem_sg_entries.
13392                  */
13393                 io->scsiio.kern_sg_entries = i;
13394
13395 #if 0
13396                 printf("%s: kern_sg_entries = %d\n", __func__,
13397                        io->scsiio.kern_sg_entries);
13398                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13399                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13400                                local_sglist[i].addr, local_sglist[i].len,
13401                                local_dma_sglist[i].len);
13402 #endif
13403         }
13404
13405
13406         return (retval);
13407
13408 bailout_error:
13409
13410         ctl_send_datamove_done(io, /*have_lock*/ 0);
13411
13412         return (retval);
13413 }
13414
13415 static int
13416 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13417                          ctl_ha_dt_cb callback)
13418 {
13419         struct ctl_ha_dt_req *rq;
13420         struct ctl_sg_entry *remote_sglist, *local_sglist;
13421         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13422         uint32_t local_used, remote_used, total_used;
13423         int retval;
13424         int i, j;
13425
13426         retval = 0;
13427
13428         rq = ctl_dt_req_alloc();
13429
13430         /*
13431          * If we failed to allocate the request, and if the DMA didn't fail
13432          * anyway, set busy status.  This is just a resource allocation
13433          * failure.
13434          */
13435         if ((rq == NULL)
13436          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13437                 ctl_set_busy(&io->scsiio);
13438
13439         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13440
13441                 if (rq != NULL)
13442                         ctl_dt_req_free(rq);
13443
13444                 /*
13445                  * The data move failed.  We need to return status back
13446                  * to the other controller.  No point in trying to DMA
13447                  * data to the remote controller.
13448                  */
13449
13450                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13451
13452                 retval = 1;
13453
13454                 goto bailout;
13455         }
13456
13457         local_sglist = io->io_hdr.local_sglist;
13458         local_dma_sglist = io->io_hdr.local_dma_sglist;
13459         remote_sglist = io->io_hdr.remote_sglist;
13460         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13461         local_used = 0;
13462         remote_used = 0;
13463         total_used = 0;
13464
13465         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13466                 rq->ret = CTL_HA_STATUS_SUCCESS;
13467                 rq->context = io;
13468                 callback(rq);
13469                 goto bailout;
13470         }
13471
13472         /*
13473          * Pull/push the data over the wire from/to the other controller.
13474          * This takes into account the possibility that the local and
13475          * remote sglists may not be identical in terms of the size of
13476          * the elements and the number of elements.
13477          *
13478          * One fundamental assumption here is that the length allocated for
13479          * both the local and remote sglists is identical.  Otherwise, we've
13480          * essentially got a coding error of some sort.
13481          */
13482         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13483                 int isc_ret;
13484                 uint32_t cur_len, dma_length;
13485                 uint8_t *tmp_ptr;
13486
13487                 rq->id = CTL_HA_DATA_CTL;
13488                 rq->command = command;
13489                 rq->context = io;
13490
13491                 /*
13492                  * Both pointers should be aligned.  But it is possible
13493                  * that the allocation length is not.  They should both
13494                  * also have enough slack left over at the end, though,
13495                  * to round up to the next 8 byte boundary.
13496                  */
13497                 cur_len = ctl_min(local_sglist[i].len - local_used,
13498                                   remote_sglist[j].len - remote_used);
13499
13500                 /*
13501                  * In this case, we have a size issue and need to decrease
13502                  * the size, except in the case where we actually have less
13503                  * than 8 bytes left.  In that case, we need to increase
13504                  * the DMA length to get the last bit.
13505                  */
13506                 if ((cur_len & 0x7) != 0) {
13507                         if (cur_len > 0x7) {
13508                                 cur_len = cur_len - (cur_len & 0x7);
13509                                 dma_length = cur_len;
13510                         } else {
13511                                 CTL_SIZE_8B(dma_length, cur_len);
13512                         }
13513
13514                 } else
13515                         dma_length = cur_len;
13516
13517                 /*
13518                  * If we had to allocate memory for this I/O, instead of using
13519                  * the non-cached mirror memory, we'll need to flush the cache
13520                  * before trying to DMA to the other controller.
13521                  *
13522                  * We could end up doing this multiple times for the same
13523                  * segment if we have a larger local segment than remote
13524                  * segment.  That shouldn't be an issue.
13525                  */
13526                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13527                         /*
13528                          * XXX KDM use bus_dmamap_sync() here.
13529                          */
13530                 }
13531
13532                 rq->size = dma_length;
13533
13534                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13535                 tmp_ptr += local_used;
13536
13537                 /* Use physical addresses when talking to ISC hardware */
13538                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13539                         /* XXX KDM use busdma */
13540 #if 0
13541                         rq->local = vtophys(tmp_ptr);
13542 #endif
13543                 } else
13544                         rq->local = tmp_ptr;
13545
13546                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13547                 tmp_ptr += remote_used;
13548                 rq->remote = tmp_ptr;
13549
13550                 rq->callback = NULL;
13551
13552                 local_used += cur_len;
13553                 if (local_used >= local_sglist[i].len) {
13554                         i++;
13555                         local_used = 0;
13556                 }
13557
13558                 remote_used += cur_len;
13559                 if (remote_used >= remote_sglist[j].len) {
13560                         j++;
13561                         remote_used = 0;
13562                 }
13563                 total_used += cur_len;
13564
13565                 if (total_used >= io->scsiio.kern_data_len)
13566                         rq->callback = callback;
13567
13568                 if ((rq->size & 0x7) != 0) {
13569                         printf("%s: warning: size %d is not on 8b boundary\n",
13570                                __func__, rq->size);
13571                 }
13572                 if (((uintptr_t)rq->local & 0x7) != 0) {
13573                         printf("%s: warning: local %p not on 8b boundary\n",
13574                                __func__, rq->local);
13575                 }
13576                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13577                         printf("%s: warning: remote %p not on 8b boundary\n",
13578                                __func__, rq->local);
13579                 }
13580 #if 0
13581                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13582                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13583                        rq->local, rq->remote, rq->size);
13584 #endif
13585
13586                 isc_ret = ctl_dt_single(rq);
13587                 if (isc_ret == CTL_HA_STATUS_WAIT)
13588                         continue;
13589
13590                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13591                         rq->ret = CTL_HA_STATUS_SUCCESS;
13592                 } else {
13593                         rq->ret = isc_ret;
13594                 }
13595                 callback(rq);
13596                 goto bailout;
13597         }
13598
13599 bailout:
13600         return (retval);
13601
13602 }
13603
13604 static void
13605 ctl_datamove_remote_read(union ctl_io *io)
13606 {
13607         int retval;
13608         int i;
13609
13610         /*
13611          * This will send an error to the other controller in the case of a
13612          * failure.
13613          */
13614         retval = ctl_datamove_remote_sgl_setup(io);
13615         if (retval != 0)
13616                 return;
13617
13618         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13619                                           ctl_datamove_remote_read_cb);
13620         if ((retval != 0)
13621          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13622                 /*
13623                  * Make sure we free memory if there was an error..  The
13624                  * ctl_datamove_remote_xfer() function will send the
13625                  * datamove done message, or call the callback with an
13626                  * error if there is a problem.
13627                  */
13628                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13629                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13630         }
13631
13632         return;
13633 }
13634
13635 /*
13636  * Process a datamove request from the other controller.  This is used for
13637  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13638  * first.  Once that is complete, the data gets DMAed into the remote
13639  * controller's memory.  For reads, we DMA from the remote controller's
13640  * memory into our memory first, and then move it out to the FETD.
13641  */
13642 static void
13643 ctl_datamove_remote(union ctl_io *io)
13644 {
13645         struct ctl_softc *softc;
13646
13647         softc = control_softc;
13648
13649         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13650
13651         /*
13652          * Note that we look for an aborted I/O here, but don't do some of
13653          * the other checks that ctl_datamove() normally does.
13654          * We don't need to run the datamove delay code, since that should
13655          * have been done if need be on the other controller.
13656          */
13657         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13658                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13659                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13660                        io->io_hdr.nexus.targ_port,
13661                        io->io_hdr.nexus.targ_target.id,
13662                        io->io_hdr.nexus.targ_lun);
13663                 io->io_hdr.port_status = 31338;
13664                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13665                 return;
13666         }
13667
13668         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13669                 ctl_datamove_remote_write(io);
13670         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13671                 ctl_datamove_remote_read(io);
13672         } else {
13673                 union ctl_ha_msg msg;
13674                 struct scsi_sense_data *sense;
13675                 uint8_t sks[3];
13676                 int retry_count;
13677
13678                 memset(&msg, 0, sizeof(msg));
13679
13680                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13681                 msg.hdr.status = CTL_SCSI_ERROR;
13682                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13683
13684                 retry_count = 4243;
13685
13686                 sense = &msg.scsi.sense_data;
13687                 sks[0] = SSD_SCS_VALID;
13688                 sks[1] = (retry_count >> 8) & 0xff;
13689                 sks[2] = retry_count & 0xff;
13690
13691                 /* "Internal target failure" */
13692                 scsi_set_sense_data(sense,
13693                                     /*sense_format*/ SSD_TYPE_NONE,
13694                                     /*current_error*/ 1,
13695                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13696                                     /*asc*/ 0x44,
13697                                     /*ascq*/ 0x00,
13698                                     /*type*/ SSD_ELEM_SKS,
13699                                     /*size*/ sizeof(sks),
13700                                     /*data*/ sks,
13701                                     SSD_ELEM_NONE);
13702
13703                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13704                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13705                         ctl_failover_io(io, /*have_lock*/ 1);
13706                         return;
13707                 }
13708
13709                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13710                     CTL_HA_STATUS_SUCCESS) {
13711                         /* XXX KDM what to do if this fails? */
13712                 }
13713                 return;
13714         }
13715         
13716 }
13717
13718 static int
13719 ctl_process_done(union ctl_io *io)
13720 {
13721         struct ctl_lun *lun;
13722         struct ctl_softc *ctl_softc;
13723         void (*fe_done)(union ctl_io *io);
13724         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13725
13726         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13727
13728         fe_done =
13729             control_softc->ctl_ports[targ_port]->fe_done;
13730
13731 #ifdef CTL_TIME_IO
13732         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13733                 char str[256];
13734                 char path_str[64];
13735                 struct sbuf sb;
13736
13737                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13738                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13739
13740                 sbuf_cat(&sb, path_str);
13741                 switch (io->io_hdr.io_type) {
13742                 case CTL_IO_SCSI:
13743                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13744                         sbuf_printf(&sb, "\n");
13745                         sbuf_cat(&sb, path_str);
13746                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13747                                     io->scsiio.tag_num, io->scsiio.tag_type);
13748                         break;
13749                 case CTL_IO_TASK:
13750                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13751                                     "Tag Type: %d\n", io->taskio.task_action,
13752                                     io->taskio.tag_num, io->taskio.tag_type);
13753                         break;
13754                 default:
13755                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13756                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13757                         break;
13758                 }
13759                 sbuf_cat(&sb, path_str);
13760                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13761                             (intmax_t)time_uptime - io->io_hdr.start_time);
13762                 sbuf_finish(&sb);
13763                 printf("%s", sbuf_data(&sb));
13764         }
13765 #endif /* CTL_TIME_IO */
13766
13767         switch (io->io_hdr.io_type) {
13768         case CTL_IO_SCSI:
13769                 break;
13770         case CTL_IO_TASK:
13771                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13772                         ctl_io_error_print(io, NULL);
13773                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13774                         ctl_free_io(io);
13775                 else
13776                         fe_done(io);
13777                 return (CTL_RETVAL_COMPLETE);
13778         default:
13779                 panic("ctl_process_done: invalid io type %d\n",
13780                       io->io_hdr.io_type);
13781                 break; /* NOTREACHED */
13782         }
13783
13784         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13785         if (lun == NULL) {
13786                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13787                                  io->io_hdr.nexus.targ_mapped_lun));
13788                 fe_done(io);
13789                 goto bailout;
13790         }
13791         ctl_softc = lun->ctl_softc;
13792
13793         mtx_lock(&lun->lun_lock);
13794
13795         /*
13796          * Check to see if we have any errors to inject here.  We only
13797          * inject errors for commands that don't already have errors set.
13798          */
13799         if ((STAILQ_FIRST(&lun->error_list) != NULL)
13800          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13801                 ctl_inject_error(lun, io);
13802
13803         /*
13804          * XXX KDM how do we treat commands that aren't completed
13805          * successfully?
13806          *
13807          * XXX KDM should we also track I/O latency?
13808          */
13809         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13810             io->io_hdr.io_type == CTL_IO_SCSI) {
13811 #ifdef CTL_TIME_IO
13812                 struct bintime cur_bt;
13813 #endif
13814                 int type;
13815
13816                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13817                     CTL_FLAG_DATA_IN)
13818                         type = CTL_STATS_READ;
13819                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13820                     CTL_FLAG_DATA_OUT)
13821                         type = CTL_STATS_WRITE;
13822                 else
13823                         type = CTL_STATS_NO_IO;
13824
13825                 lun->stats.ports[targ_port].bytes[type] +=
13826                     io->scsiio.kern_total_len;
13827                 lun->stats.ports[targ_port].operations[type]++;
13828 #ifdef CTL_TIME_IO
13829                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13830                    &io->io_hdr.dma_bt);
13831                 lun->stats.ports[targ_port].num_dmas[type] +=
13832                     io->io_hdr.num_dmas;
13833                 getbintime(&cur_bt);
13834                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13835                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13836 #endif
13837         }
13838
13839         /*
13840          * Remove this from the OOA queue.
13841          */
13842         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13843
13844         /*
13845          * Run through the blocked queue on this LUN and see if anything
13846          * has become unblocked, now that this transaction is done.
13847          */
13848         ctl_check_blocked(lun);
13849
13850         /*
13851          * If the LUN has been invalidated, free it if there is nothing
13852          * left on its OOA queue.
13853          */
13854         if ((lun->flags & CTL_LUN_INVALID)
13855          && TAILQ_EMPTY(&lun->ooa_queue)) {
13856                 mtx_unlock(&lun->lun_lock);
13857                 mtx_lock(&ctl_softc->ctl_lock);
13858                 ctl_free_lun(lun);
13859                 mtx_unlock(&ctl_softc->ctl_lock);
13860         } else
13861                 mtx_unlock(&lun->lun_lock);
13862
13863         /*
13864          * If this command has been aborted, make sure we set the status
13865          * properly.  The FETD is responsible for freeing the I/O and doing
13866          * whatever it needs to do to clean up its state.
13867          */
13868         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13869                 ctl_set_task_aborted(&io->scsiio);
13870
13871         /*
13872          * If enabled, print command error status.
13873          * We don't print UAs unless debugging was enabled explicitly.
13874          */
13875         do {
13876                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13877                         break;
13878                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13879                         break;
13880                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13881                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13882                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13883                         int error_code, sense_key, asc, ascq;
13884
13885                         scsi_extract_sense_len(&io->scsiio.sense_data,
13886                             io->scsiio.sense_len, &error_code, &sense_key,
13887                             &asc, &ascq, /*show_errors*/ 0);
13888                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13889                                 break;
13890                 }
13891
13892                 ctl_io_error_print(io, NULL);
13893         } while (0);
13894
13895         /*
13896          * Tell the FETD or the other shelf controller we're done with this
13897          * command.  Note that only SCSI commands get to this point.  Task
13898          * management commands are completed above.
13899          *
13900          * We only send status to the other controller if we're in XFER
13901          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13902          * received the I/O (from CTL's perspective), and so the status is
13903          * generated there.
13904          * 
13905          * XXX KDM if we hold the lock here, we could cause a deadlock
13906          * if the frontend comes back in in this context to queue
13907          * something.
13908          */
13909         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13910          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13911                 union ctl_ha_msg msg;
13912
13913                 memset(&msg, 0, sizeof(msg));
13914                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13915                 msg.hdr.original_sc = io->io_hdr.original_sc;
13916                 msg.hdr.nexus = io->io_hdr.nexus;
13917                 msg.hdr.status = io->io_hdr.status;
13918                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13919                 msg.scsi.tag_num = io->scsiio.tag_num;
13920                 msg.scsi.tag_type = io->scsiio.tag_type;
13921                 msg.scsi.sense_len = io->scsiio.sense_len;
13922                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13923                 msg.scsi.residual = io->scsiio.residual;
13924                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13925                        sizeof(io->scsiio.sense_data));
13926                 /*
13927                  * We copy this whether or not this is an I/O-related
13928                  * command.  Otherwise, we'd have to go and check to see
13929                  * whether it's a read/write command, and it really isn't
13930                  * worth it.
13931                  */
13932                 memcpy(&msg.scsi.lbalen,
13933                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13934                        sizeof(msg.scsi.lbalen));
13935
13936                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13937                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13938                         /* XXX do something here */
13939                 }
13940
13941                 ctl_free_io(io);
13942         } else 
13943                 fe_done(io);
13944
13945 bailout:
13946
13947         return (CTL_RETVAL_COMPLETE);
13948 }
13949
13950 #ifdef CTL_WITH_CA
13951 /*
13952  * Front end should call this if it doesn't do autosense.  When the request
13953  * sense comes back in from the initiator, we'll dequeue this and send it.
13954  */
13955 int
13956 ctl_queue_sense(union ctl_io *io)
13957 {
13958         struct ctl_lun *lun;
13959         struct ctl_softc *ctl_softc;
13960         uint32_t initidx, targ_lun;
13961
13962         ctl_softc = control_softc;
13963
13964         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13965
13966         /*
13967          * LUN lookup will likely move to the ctl_work_thread() once we
13968          * have our new queueing infrastructure (that doesn't put things on
13969          * a per-LUN queue initially).  That is so that we can handle
13970          * things like an INQUIRY to a LUN that we don't have enabled.  We
13971          * can't deal with that right now.
13972          */
13973         mtx_lock(&ctl_softc->ctl_lock);
13974
13975         /*
13976          * If we don't have a LUN for this, just toss the sense
13977          * information.
13978          */
13979         targ_lun = io->io_hdr.nexus.targ_lun;
13980         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13981         if ((targ_lun < CTL_MAX_LUNS)
13982          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13983                 lun = ctl_softc->ctl_luns[targ_lun];
13984         else
13985                 goto bailout;
13986
13987         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13988
13989         mtx_lock(&lun->lun_lock);
13990         /*
13991          * Already have CA set for this LUN...toss the sense information.
13992          */
13993         if (ctl_is_set(lun->have_ca, initidx)) {
13994                 mtx_unlock(&lun->lun_lock);
13995                 goto bailout;
13996         }
13997
13998         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13999                ctl_min(sizeof(lun->pending_sense[initidx]),
14000                sizeof(io->scsiio.sense_data)));
14001         ctl_set_mask(lun->have_ca, initidx);
14002         mtx_unlock(&lun->lun_lock);
14003
14004 bailout:
14005         mtx_unlock(&ctl_softc->ctl_lock);
14006
14007         ctl_free_io(io);
14008
14009         return (CTL_RETVAL_COMPLETE);
14010 }
14011 #endif
14012
14013 /*
14014  * Primary command inlet from frontend ports.  All SCSI and task I/O
14015  * requests must go through this function.
14016  */
14017 int
14018 ctl_queue(union ctl_io *io)
14019 {
14020         struct ctl_softc *ctl_softc;
14021
14022         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
14023
14024         ctl_softc = control_softc;
14025
14026 #ifdef CTL_TIME_IO
14027         io->io_hdr.start_time = time_uptime;
14028         getbintime(&io->io_hdr.start_bt);
14029 #endif /* CTL_TIME_IO */
14030
14031         /* Map FE-specific LUN ID into global one. */
14032         io->io_hdr.nexus.targ_mapped_lun =
14033             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
14034
14035         switch (io->io_hdr.io_type) {
14036         case CTL_IO_SCSI:
14037         case CTL_IO_TASK:
14038                 if (ctl_debug & CTL_DEBUG_CDB)
14039                         ctl_io_print(io);
14040                 ctl_enqueue_incoming(io);
14041                 break;
14042         default:
14043                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14044                 return (EINVAL);
14045         }
14046
14047         return (CTL_RETVAL_COMPLETE);
14048 }
14049
14050 #ifdef CTL_IO_DELAY
14051 static void
14052 ctl_done_timer_wakeup(void *arg)
14053 {
14054         union ctl_io *io;
14055
14056         io = (union ctl_io *)arg;
14057         ctl_done(io);
14058 }
14059 #endif /* CTL_IO_DELAY */
14060
14061 void
14062 ctl_done(union ctl_io *io)
14063 {
14064         struct ctl_softc *ctl_softc;
14065
14066         ctl_softc = control_softc;
14067
14068         /*
14069          * Enable this to catch duplicate completion issues.
14070          */
14071 #if 0
14072         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14073                 printf("%s: type %d msg %d cdb %x iptl: "
14074                        "%d:%d:%d:%d tag 0x%04x "
14075                        "flag %#x status %x\n",
14076                         __func__,
14077                         io->io_hdr.io_type,
14078                         io->io_hdr.msg_type,
14079                         io->scsiio.cdb[0],
14080                         io->io_hdr.nexus.initid.id,
14081                         io->io_hdr.nexus.targ_port,
14082                         io->io_hdr.nexus.targ_target.id,
14083                         io->io_hdr.nexus.targ_lun,
14084                         (io->io_hdr.io_type ==
14085                         CTL_IO_TASK) ?
14086                         io->taskio.tag_num :
14087                         io->scsiio.tag_num,
14088                         io->io_hdr.flags,
14089                         io->io_hdr.status);
14090         } else
14091                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14092 #endif
14093
14094         /*
14095          * This is an internal copy of an I/O, and should not go through
14096          * the normal done processing logic.
14097          */
14098         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14099                 return;
14100
14101         /*
14102          * We need to send a msg to the serializing shelf to finish the IO
14103          * as well.  We don't send a finish message to the other shelf if
14104          * this is a task management command.  Task management commands
14105          * aren't serialized in the OOA queue, but rather just executed on
14106          * both shelf controllers for commands that originated on that
14107          * controller.
14108          */
14109         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14110          && (io->io_hdr.io_type != CTL_IO_TASK)) {
14111                 union ctl_ha_msg msg_io;
14112
14113                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14114                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14115                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14116                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14117                 }
14118                 /* continue on to finish IO */
14119         }
14120 #ifdef CTL_IO_DELAY
14121         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14122                 struct ctl_lun *lun;
14123
14124                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14125
14126                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14127         } else {
14128                 struct ctl_lun *lun;
14129
14130                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14131
14132                 if ((lun != NULL)
14133                  && (lun->delay_info.done_delay > 0)) {
14134                         struct callout *callout;
14135
14136                         callout = (struct callout *)&io->io_hdr.timer_bytes;
14137                         callout_init(callout, /*mpsafe*/ 1);
14138                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14139                         callout_reset(callout,
14140                                       lun->delay_info.done_delay * hz,
14141                                       ctl_done_timer_wakeup, io);
14142                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14143                                 lun->delay_info.done_delay = 0;
14144                         return;
14145                 }
14146         }
14147 #endif /* CTL_IO_DELAY */
14148
14149         ctl_enqueue_done(io);
14150 }
14151
14152 int
14153 ctl_isc(struct ctl_scsiio *ctsio)
14154 {
14155         struct ctl_lun *lun;
14156         int retval;
14157
14158         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14159
14160         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14161
14162         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14163
14164         retval = lun->backend->data_submit((union ctl_io *)ctsio);
14165
14166         return (retval);
14167 }
14168
14169
14170 static void
14171 ctl_work_thread(void *arg)
14172 {
14173         struct ctl_thread *thr = (struct ctl_thread *)arg;
14174         struct ctl_softc *softc = thr->ctl_softc;
14175         union ctl_io *io;
14176         int retval;
14177
14178         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14179
14180         for (;;) {
14181                 retval = 0;
14182
14183                 /*
14184                  * We handle the queues in this order:
14185                  * - ISC
14186                  * - done queue (to free up resources, unblock other commands)
14187                  * - RtR queue
14188                  * - incoming queue
14189                  *
14190                  * If those queues are empty, we break out of the loop and
14191                  * go to sleep.
14192                  */
14193                 mtx_lock(&thr->queue_lock);
14194                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14195                 if (io != NULL) {
14196                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14197                         mtx_unlock(&thr->queue_lock);
14198                         ctl_handle_isc(io);
14199                         continue;
14200                 }
14201                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14202                 if (io != NULL) {
14203                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14204                         /* clear any blocked commands, call fe_done */
14205                         mtx_unlock(&thr->queue_lock);
14206                         retval = ctl_process_done(io);
14207                         continue;
14208                 }
14209                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14210                 if (io != NULL) {
14211                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14212                         mtx_unlock(&thr->queue_lock);
14213                         if (io->io_hdr.io_type == CTL_IO_TASK)
14214                                 ctl_run_task(io);
14215                         else
14216                                 ctl_scsiio_precheck(softc, &io->scsiio);
14217                         continue;
14218                 }
14219                 if (!ctl_pause_rtr) {
14220                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14221                         if (io != NULL) {
14222                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14223                                 mtx_unlock(&thr->queue_lock);
14224                                 retval = ctl_scsiio(&io->scsiio);
14225                                 if (retval != CTL_RETVAL_COMPLETE)
14226                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14227                                 continue;
14228                         }
14229                 }
14230
14231                 /* Sleep until we have something to do. */
14232                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14233         }
14234 }
14235
14236 static void
14237 ctl_lun_thread(void *arg)
14238 {
14239         struct ctl_softc *softc = (struct ctl_softc *)arg;
14240         struct ctl_be_lun *be_lun;
14241         int retval;
14242
14243         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14244
14245         for (;;) {
14246                 retval = 0;
14247                 mtx_lock(&softc->ctl_lock);
14248                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14249                 if (be_lun != NULL) {
14250                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14251                         mtx_unlock(&softc->ctl_lock);
14252                         ctl_create_lun(be_lun);
14253                         continue;
14254                 }
14255
14256                 /* Sleep until we have something to do. */
14257                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14258                     PDROP | PRIBIO, "-", 0);
14259         }
14260 }
14261
14262 static void
14263 ctl_enqueue_incoming(union ctl_io *io)
14264 {
14265         struct ctl_softc *softc = control_softc;
14266         struct ctl_thread *thr;
14267         u_int idx;
14268
14269         idx = (io->io_hdr.nexus.targ_port * 127 +
14270                io->io_hdr.nexus.initid.id) % worker_threads;
14271         thr = &softc->threads[idx];
14272         mtx_lock(&thr->queue_lock);
14273         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14274         mtx_unlock(&thr->queue_lock);
14275         wakeup(thr);
14276 }
14277
14278 static void
14279 ctl_enqueue_rtr(union ctl_io *io)
14280 {
14281         struct ctl_softc *softc = control_softc;
14282         struct ctl_thread *thr;
14283
14284         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14285         mtx_lock(&thr->queue_lock);
14286         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14287         mtx_unlock(&thr->queue_lock);
14288         wakeup(thr);
14289 }
14290
14291 static void
14292 ctl_enqueue_done(union ctl_io *io)
14293 {
14294         struct ctl_softc *softc = control_softc;
14295         struct ctl_thread *thr;
14296
14297         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14298         mtx_lock(&thr->queue_lock);
14299         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14300         mtx_unlock(&thr->queue_lock);
14301         wakeup(thr);
14302 }
14303
14304 static void
14305 ctl_enqueue_isc(union ctl_io *io)
14306 {
14307         struct ctl_softc *softc = control_softc;
14308         struct ctl_thread *thr;
14309
14310         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14311         mtx_lock(&thr->queue_lock);
14312         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14313         mtx_unlock(&thr->queue_lock);
14314         wakeup(thr);
14315 }
14316
14317 /* Initialization and failover */
14318
14319 void
14320 ctl_init_isc_msg(void)
14321 {
14322         printf("CTL: Still calling this thing\n");
14323 }
14324
14325 /*
14326  * Init component
14327  *      Initializes component into configuration defined by bootMode
14328  *      (see hasc-sv.c)
14329  *      returns hasc_Status:
14330  *              OK
14331  *              ERROR - fatal error
14332  */
14333 static ctl_ha_comp_status
14334 ctl_isc_init(struct ctl_ha_component *c)
14335 {
14336         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14337
14338         c->status = ret;
14339         return ret;
14340 }
14341
14342 /* Start component
14343  *      Starts component in state requested. If component starts successfully,
14344  *      it must set its own state to the requestrd state
14345  *      When requested state is HASC_STATE_HA, the component may refine it
14346  *      by adding _SLAVE or _MASTER flags.
14347  *      Currently allowed state transitions are:
14348  *      UNKNOWN->HA             - initial startup
14349  *      UNKNOWN->SINGLE - initial startup when no parter detected
14350  *      HA->SINGLE              - failover
14351  * returns ctl_ha_comp_status:
14352  *              OK      - component successfully started in requested state
14353  *              FAILED  - could not start the requested state, failover may
14354  *                        be possible
14355  *              ERROR   - fatal error detected, no future startup possible
14356  */
14357 static ctl_ha_comp_status
14358 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14359 {
14360         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14361
14362         printf("%s: go\n", __func__);
14363
14364         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14365         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14366                 ctl_is_single = 0;
14367                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14368                     != CTL_HA_STATUS_SUCCESS) {
14369                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14370                         ret = CTL_HA_COMP_STATUS_ERROR;
14371                 }
14372         } else if (CTL_HA_STATE_IS_HA(c->state)
14373                 && CTL_HA_STATE_IS_SINGLE(state)){
14374                 // HA->SINGLE transition
14375                 ctl_failover();
14376                 ctl_is_single = 1;
14377         } else {
14378                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14379                        c->state, state);
14380                 ret = CTL_HA_COMP_STATUS_ERROR;
14381         }
14382         if (CTL_HA_STATE_IS_SINGLE(state))
14383                 ctl_is_single = 1;
14384
14385         c->state = state;
14386         c->status = ret;
14387         return ret;
14388 }
14389
14390 /*
14391  * Quiesce component
14392  * The component must clear any error conditions (set status to OK) and
14393  * prepare itself to another Start call
14394  * returns ctl_ha_comp_status:
14395  *      OK
14396  *      ERROR
14397  */
14398 static ctl_ha_comp_status
14399 ctl_isc_quiesce(struct ctl_ha_component *c)
14400 {
14401         int ret = CTL_HA_COMP_STATUS_OK;
14402
14403         ctl_pause_rtr = 1;
14404         c->status = ret;
14405         return ret;
14406 }
14407
14408 struct ctl_ha_component ctl_ha_component_ctlisc =
14409 {
14410         .name = "CTL ISC",
14411         .state = CTL_HA_STATE_UNKNOWN,
14412         .init = ctl_isc_init,
14413         .start = ctl_isc_start,
14414         .quiesce = ctl_isc_quiesce
14415 };
14416
14417 /*
14418  *  vim: ts=8
14419  */