]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r271845:
[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*/0,
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 verbose = 0;
319 TUNABLE_INT("kern.cam.ctl.verbose", &verbose);
320 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
321     &verbose, 0, "Show SCSI errors returned to initiator");
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);
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);
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 int
2243 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2244           struct thread *td)
2245 {
2246         struct ctl_softc *softc;
2247         int retval;
2248
2249         softc = control_softc;
2250
2251         retval = 0;
2252
2253         switch (cmd) {
2254         case CTL_IO: {
2255                 union ctl_io *io;
2256                 void *pool_tmp;
2257
2258                 /*
2259                  * If we haven't been "enabled", don't allow any SCSI I/O
2260                  * to this FETD.
2261                  */
2262                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2263                         retval = EPERM;
2264                         break;
2265                 }
2266
2267                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2268                 if (io == NULL) {
2269                         printf("ctl_ioctl: can't allocate ctl_io!\n");
2270                         retval = ENOSPC;
2271                         break;
2272                 }
2273
2274                 /*
2275                  * Need to save the pool reference so it doesn't get
2276                  * spammed by the user's ctl_io.
2277                  */
2278                 pool_tmp = io->io_hdr.pool;
2279
2280                 memcpy(io, (void *)addr, sizeof(*io));
2281
2282                 io->io_hdr.pool = pool_tmp;
2283                 /*
2284                  * No status yet, so make sure the status is set properly.
2285                  */
2286                 io->io_hdr.status = CTL_STATUS_NONE;
2287
2288                 /*
2289                  * The user sets the initiator ID, target and LUN IDs.
2290                  */
2291                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2292                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2293                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2294                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2295                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2296
2297                 retval = ctl_ioctl_submit_wait(io);
2298
2299                 if (retval != 0) {
2300                         ctl_free_io(io);
2301                         break;
2302                 }
2303
2304                 memcpy((void *)addr, io, sizeof(*io));
2305
2306                 /* return this to our pool */
2307                 ctl_free_io(io);
2308
2309                 break;
2310         }
2311         case CTL_ENABLE_PORT:
2312         case CTL_DISABLE_PORT:
2313         case CTL_SET_PORT_WWNS: {
2314                 struct ctl_port *port;
2315                 struct ctl_port_entry *entry;
2316
2317                 entry = (struct ctl_port_entry *)addr;
2318                 
2319                 mtx_lock(&softc->ctl_lock);
2320                 STAILQ_FOREACH(port, &softc->port_list, links) {
2321                         int action, done;
2322
2323                         action = 0;
2324                         done = 0;
2325
2326                         if ((entry->port_type == CTL_PORT_NONE)
2327                          && (entry->targ_port == port->targ_port)) {
2328                                 /*
2329                                  * If the user only wants to enable or
2330                                  * disable or set WWNs on a specific port,
2331                                  * do the operation and we're done.
2332                                  */
2333                                 action = 1;
2334                                 done = 1;
2335                         } else if (entry->port_type & port->port_type) {
2336                                 /*
2337                                  * Compare the user's type mask with the
2338                                  * particular frontend type to see if we
2339                                  * have a match.
2340                                  */
2341                                 action = 1;
2342                                 done = 0;
2343
2344                                 /*
2345                                  * Make sure the user isn't trying to set
2346                                  * WWNs on multiple ports at the same time.
2347                                  */
2348                                 if (cmd == CTL_SET_PORT_WWNS) {
2349                                         printf("%s: Can't set WWNs on "
2350                                                "multiple ports\n", __func__);
2351                                         retval = EINVAL;
2352                                         break;
2353                                 }
2354                         }
2355                         if (action != 0) {
2356                                 /*
2357                                  * XXX KDM we have to drop the lock here,
2358                                  * because the online/offline operations
2359                                  * can potentially block.  We need to
2360                                  * reference count the frontends so they
2361                                  * can't go away,
2362                                  */
2363                                 mtx_unlock(&softc->ctl_lock);
2364
2365                                 if (cmd == CTL_ENABLE_PORT) {
2366                                         struct ctl_lun *lun;
2367
2368                                         STAILQ_FOREACH(lun, &softc->lun_list,
2369                                                        links) {
2370                                                 port->lun_enable(port->targ_lun_arg,
2371                                                     lun->target,
2372                                                     lun->lun);
2373                                         }
2374
2375                                         ctl_port_online(port);
2376                                 } else if (cmd == CTL_DISABLE_PORT) {
2377                                         struct ctl_lun *lun;
2378
2379                                         ctl_port_offline(port);
2380
2381                                         STAILQ_FOREACH(lun, &softc->lun_list,
2382                                                        links) {
2383                                                 port->lun_disable(
2384                                                     port->targ_lun_arg,
2385                                                     lun->target,
2386                                                     lun->lun);
2387                                         }
2388                                 }
2389
2390                                 mtx_lock(&softc->ctl_lock);
2391
2392                                 if (cmd == CTL_SET_PORT_WWNS)
2393                                         ctl_port_set_wwns(port,
2394                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2395                                             1 : 0, entry->wwnn,
2396                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2397                                             1 : 0, entry->wwpn);
2398                         }
2399                         if (done != 0)
2400                                 break;
2401                 }
2402                 mtx_unlock(&softc->ctl_lock);
2403                 break;
2404         }
2405         case CTL_GET_PORT_LIST: {
2406                 struct ctl_port *port;
2407                 struct ctl_port_list *list;
2408                 int i;
2409
2410                 list = (struct ctl_port_list *)addr;
2411
2412                 if (list->alloc_len != (list->alloc_num *
2413                     sizeof(struct ctl_port_entry))) {
2414                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2415                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2416                                "%zu\n", __func__, list->alloc_len,
2417                                list->alloc_num, sizeof(struct ctl_port_entry));
2418                         retval = EINVAL;
2419                         break;
2420                 }
2421                 list->fill_len = 0;
2422                 list->fill_num = 0;
2423                 list->dropped_num = 0;
2424                 i = 0;
2425                 mtx_lock(&softc->ctl_lock);
2426                 STAILQ_FOREACH(port, &softc->port_list, links) {
2427                         struct ctl_port_entry entry, *list_entry;
2428
2429                         if (list->fill_num >= list->alloc_num) {
2430                                 list->dropped_num++;
2431                                 continue;
2432                         }
2433
2434                         entry.port_type = port->port_type;
2435                         strlcpy(entry.port_name, port->port_name,
2436                                 sizeof(entry.port_name));
2437                         entry.targ_port = port->targ_port;
2438                         entry.physical_port = port->physical_port;
2439                         entry.virtual_port = port->virtual_port;
2440                         entry.wwnn = port->wwnn;
2441                         entry.wwpn = port->wwpn;
2442                         if (port->status & CTL_PORT_STATUS_ONLINE)
2443                                 entry.online = 1;
2444                         else
2445                                 entry.online = 0;
2446
2447                         list_entry = &list->entries[i];
2448
2449                         retval = copyout(&entry, list_entry, sizeof(entry));
2450                         if (retval != 0) {
2451                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2452                                        "returned %d\n", __func__, retval);
2453                                 break;
2454                         }
2455                         i++;
2456                         list->fill_num++;
2457                         list->fill_len += sizeof(entry);
2458                 }
2459                 mtx_unlock(&softc->ctl_lock);
2460
2461                 /*
2462                  * If this is non-zero, we had a copyout fault, so there's
2463                  * probably no point in attempting to set the status inside
2464                  * the structure.
2465                  */
2466                 if (retval != 0)
2467                         break;
2468
2469                 if (list->dropped_num > 0)
2470                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2471                 else
2472                         list->status = CTL_PORT_LIST_OK;
2473                 break;
2474         }
2475         case CTL_DUMP_OOA: {
2476                 struct ctl_lun *lun;
2477                 union ctl_io *io;
2478                 char printbuf[128];
2479                 struct sbuf sb;
2480
2481                 mtx_lock(&softc->ctl_lock);
2482                 printf("Dumping OOA queues:\n");
2483                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2484                         mtx_lock(&lun->lun_lock);
2485                         for (io = (union ctl_io *)TAILQ_FIRST(
2486                              &lun->ooa_queue); io != NULL;
2487                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2488                              ooa_links)) {
2489                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2490                                          SBUF_FIXEDLEN);
2491                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2492                                             (intmax_t)lun->lun,
2493                                             io->scsiio.tag_num,
2494                                             (io->io_hdr.flags &
2495                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2496                                             (io->io_hdr.flags &
2497                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2498                                             (io->io_hdr.flags &
2499                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2500                                             (io->io_hdr.flags &
2501                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2502                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2503                                 sbuf_finish(&sb);
2504                                 printf("%s\n", sbuf_data(&sb));
2505                         }
2506                         mtx_unlock(&lun->lun_lock);
2507                 }
2508                 printf("OOA queues dump done\n");
2509                 mtx_unlock(&softc->ctl_lock);
2510                 break;
2511         }
2512         case CTL_GET_OOA: {
2513                 struct ctl_lun *lun;
2514                 struct ctl_ooa *ooa_hdr;
2515                 struct ctl_ooa_entry *entries;
2516                 uint32_t cur_fill_num;
2517
2518                 ooa_hdr = (struct ctl_ooa *)addr;
2519
2520                 if ((ooa_hdr->alloc_len == 0)
2521                  || (ooa_hdr->alloc_num == 0)) {
2522                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2523                                "must be non-zero\n", __func__,
2524                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2525                         retval = EINVAL;
2526                         break;
2527                 }
2528
2529                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2530                     sizeof(struct ctl_ooa_entry))) {
2531                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2532                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2533                                __func__, ooa_hdr->alloc_len,
2534                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2535                         retval = EINVAL;
2536                         break;
2537                 }
2538
2539                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2540                 if (entries == NULL) {
2541                         printf("%s: could not allocate %d bytes for OOA "
2542                                "dump\n", __func__, ooa_hdr->alloc_len);
2543                         retval = ENOMEM;
2544                         break;
2545                 }
2546
2547                 mtx_lock(&softc->ctl_lock);
2548                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2549                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2550                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2551                         mtx_unlock(&softc->ctl_lock);
2552                         free(entries, M_CTL);
2553                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2554                                __func__, (uintmax_t)ooa_hdr->lun_num);
2555                         retval = EINVAL;
2556                         break;
2557                 }
2558
2559                 cur_fill_num = 0;
2560
2561                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2562                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2563                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2564                                         ooa_hdr, entries);
2565                                 if (retval != 0)
2566                                         break;
2567                         }
2568                         if (retval != 0) {
2569                                 mtx_unlock(&softc->ctl_lock);
2570                                 free(entries, M_CTL);
2571                                 break;
2572                         }
2573                 } else {
2574                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2575
2576                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2577                                                     entries);
2578                 }
2579                 mtx_unlock(&softc->ctl_lock);
2580
2581                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2582                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2583                         sizeof(struct ctl_ooa_entry);
2584                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2585                 if (retval != 0) {
2586                         printf("%s: error copying out %d bytes for OOA dump\n", 
2587                                __func__, ooa_hdr->fill_len);
2588                 }
2589
2590                 getbintime(&ooa_hdr->cur_bt);
2591
2592                 if (cur_fill_num > ooa_hdr->alloc_num) {
2593                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2594                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2595                 } else {
2596                         ooa_hdr->dropped_num = 0;
2597                         ooa_hdr->status = CTL_OOA_OK;
2598                 }
2599
2600                 free(entries, M_CTL);
2601                 break;
2602         }
2603         case CTL_CHECK_OOA: {
2604                 union ctl_io *io;
2605                 struct ctl_lun *lun;
2606                 struct ctl_ooa_info *ooa_info;
2607
2608
2609                 ooa_info = (struct ctl_ooa_info *)addr;
2610
2611                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2612                         ooa_info->status = CTL_OOA_INVALID_LUN;
2613                         break;
2614                 }
2615                 mtx_lock(&softc->ctl_lock);
2616                 lun = softc->ctl_luns[ooa_info->lun_id];
2617                 if (lun == NULL) {
2618                         mtx_unlock(&softc->ctl_lock);
2619                         ooa_info->status = CTL_OOA_INVALID_LUN;
2620                         break;
2621                 }
2622                 mtx_lock(&lun->lun_lock);
2623                 mtx_unlock(&softc->ctl_lock);
2624                 ooa_info->num_entries = 0;
2625                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2626                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2627                      &io->io_hdr, ooa_links)) {
2628                         ooa_info->num_entries++;
2629                 }
2630                 mtx_unlock(&lun->lun_lock);
2631
2632                 ooa_info->status = CTL_OOA_SUCCESS;
2633
2634                 break;
2635         }
2636         case CTL_HARD_START:
2637         case CTL_HARD_STOP: {
2638                 struct ctl_fe_ioctl_startstop_info ss_info;
2639                 struct cfi_metatask *metatask;
2640                 struct mtx hs_mtx;
2641
2642                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2643
2644                 cv_init(&ss_info.sem, "hard start/stop cv" );
2645
2646                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2647                 if (metatask == NULL) {
2648                         retval = ENOMEM;
2649                         mtx_destroy(&hs_mtx);
2650                         break;
2651                 }
2652
2653                 if (cmd == CTL_HARD_START)
2654                         metatask->tasktype = CFI_TASK_STARTUP;
2655                 else
2656                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2657
2658                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2659                 metatask->callback_arg = &ss_info;
2660
2661                 cfi_action(metatask);
2662
2663                 /* Wait for the callback */
2664                 mtx_lock(&hs_mtx);
2665                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2666                 mtx_unlock(&hs_mtx);
2667
2668                 /*
2669                  * All information has been copied from the metatask by the
2670                  * time cv_broadcast() is called, so we free the metatask here.
2671                  */
2672                 cfi_free_metatask(metatask);
2673
2674                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2675
2676                 mtx_destroy(&hs_mtx);
2677                 break;
2678         }
2679         case CTL_BBRREAD: {
2680                 struct ctl_bbrread_info *bbr_info;
2681                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2682                 struct mtx bbr_mtx;
2683                 struct cfi_metatask *metatask;
2684
2685                 bbr_info = (struct ctl_bbrread_info *)addr;
2686
2687                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2688
2689                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2690                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2691
2692                 fe_bbr_info.bbr_info = bbr_info;
2693                 fe_bbr_info.lock = &bbr_mtx;
2694
2695                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2696                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2697
2698                 if (metatask == NULL) {
2699                         mtx_destroy(&bbr_mtx);
2700                         cv_destroy(&fe_bbr_info.sem);
2701                         retval = ENOMEM;
2702                         break;
2703                 }
2704                 metatask->tasktype = CFI_TASK_BBRREAD;
2705                 metatask->callback = ctl_ioctl_bbrread_callback;
2706                 metatask->callback_arg = &fe_bbr_info;
2707                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2708                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2709                 metatask->taskinfo.bbrread.len = bbr_info->len;
2710
2711                 cfi_action(metatask);
2712
2713                 mtx_lock(&bbr_mtx);
2714                 while (fe_bbr_info.wakeup_done == 0)
2715                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2716                 mtx_unlock(&bbr_mtx);
2717
2718                 bbr_info->status = metatask->status;
2719                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2720                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2721                 memcpy(&bbr_info->sense_data,
2722                        &metatask->taskinfo.bbrread.sense_data,
2723                        ctl_min(sizeof(bbr_info->sense_data),
2724                                sizeof(metatask->taskinfo.bbrread.sense_data)));
2725
2726                 cfi_free_metatask(metatask);
2727
2728                 mtx_destroy(&bbr_mtx);
2729                 cv_destroy(&fe_bbr_info.sem);
2730
2731                 break;
2732         }
2733         case CTL_DELAY_IO: {
2734                 struct ctl_io_delay_info *delay_info;
2735 #ifdef CTL_IO_DELAY
2736                 struct ctl_lun *lun;
2737 #endif /* CTL_IO_DELAY */
2738
2739                 delay_info = (struct ctl_io_delay_info *)addr;
2740
2741 #ifdef CTL_IO_DELAY
2742                 mtx_lock(&softc->ctl_lock);
2743
2744                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2745                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2746                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2747                 } else {
2748                         lun = softc->ctl_luns[delay_info->lun_id];
2749                         mtx_lock(&lun->lun_lock);
2750
2751                         delay_info->status = CTL_DELAY_STATUS_OK;
2752
2753                         switch (delay_info->delay_type) {
2754                         case CTL_DELAY_TYPE_CONT:
2755                                 break;
2756                         case CTL_DELAY_TYPE_ONESHOT:
2757                                 break;
2758                         default:
2759                                 delay_info->status =
2760                                         CTL_DELAY_STATUS_INVALID_TYPE;
2761                                 break;
2762                         }
2763
2764                         switch (delay_info->delay_loc) {
2765                         case CTL_DELAY_LOC_DATAMOVE:
2766                                 lun->delay_info.datamove_type =
2767                                         delay_info->delay_type;
2768                                 lun->delay_info.datamove_delay =
2769                                         delay_info->delay_secs;
2770                                 break;
2771                         case CTL_DELAY_LOC_DONE:
2772                                 lun->delay_info.done_type =
2773                                         delay_info->delay_type;
2774                                 lun->delay_info.done_delay =
2775                                         delay_info->delay_secs;
2776                                 break;
2777                         default:
2778                                 delay_info->status =
2779                                         CTL_DELAY_STATUS_INVALID_LOC;
2780                                 break;
2781                         }
2782                         mtx_unlock(&lun->lun_lock);
2783                 }
2784
2785                 mtx_unlock(&softc->ctl_lock);
2786 #else
2787                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2788 #endif /* CTL_IO_DELAY */
2789                 break;
2790         }
2791         case CTL_REALSYNC_SET: {
2792                 int *syncstate;
2793
2794                 syncstate = (int *)addr;
2795
2796                 mtx_lock(&softc->ctl_lock);
2797                 switch (*syncstate) {
2798                 case 0:
2799                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2800                         break;
2801                 case 1:
2802                         softc->flags |= CTL_FLAG_REAL_SYNC;
2803                         break;
2804                 default:
2805                         retval = EINVAL;
2806                         break;
2807                 }
2808                 mtx_unlock(&softc->ctl_lock);
2809                 break;
2810         }
2811         case CTL_REALSYNC_GET: {
2812                 int *syncstate;
2813
2814                 syncstate = (int*)addr;
2815
2816                 mtx_lock(&softc->ctl_lock);
2817                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2818                         *syncstate = 1;
2819                 else
2820                         *syncstate = 0;
2821                 mtx_unlock(&softc->ctl_lock);
2822
2823                 break;
2824         }
2825         case CTL_SETSYNC:
2826         case CTL_GETSYNC: {
2827                 struct ctl_sync_info *sync_info;
2828                 struct ctl_lun *lun;
2829
2830                 sync_info = (struct ctl_sync_info *)addr;
2831
2832                 mtx_lock(&softc->ctl_lock);
2833                 lun = softc->ctl_luns[sync_info->lun_id];
2834                 if (lun == NULL) {
2835                         mtx_unlock(&softc->ctl_lock);
2836                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2837                 }
2838                 /*
2839                  * Get or set the sync interval.  We're not bounds checking
2840                  * in the set case, hopefully the user won't do something
2841                  * silly.
2842                  */
2843                 mtx_lock(&lun->lun_lock);
2844                 mtx_unlock(&softc->ctl_lock);
2845                 if (cmd == CTL_GETSYNC)
2846                         sync_info->sync_interval = lun->sync_interval;
2847                 else
2848                         lun->sync_interval = sync_info->sync_interval;
2849                 mtx_unlock(&lun->lun_lock);
2850
2851                 sync_info->status = CTL_GS_SYNC_OK;
2852
2853                 break;
2854         }
2855         case CTL_GETSTATS: {
2856                 struct ctl_stats *stats;
2857                 struct ctl_lun *lun;
2858                 int i;
2859
2860                 stats = (struct ctl_stats *)addr;
2861
2862                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2863                      stats->alloc_len) {
2864                         stats->status = CTL_SS_NEED_MORE_SPACE;
2865                         stats->num_luns = softc->num_luns;
2866                         break;
2867                 }
2868                 /*
2869                  * XXX KDM no locking here.  If the LUN list changes,
2870                  * things can blow up.
2871                  */
2872                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2873                      i++, lun = STAILQ_NEXT(lun, links)) {
2874                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2875                                          sizeof(lun->stats));
2876                         if (retval != 0)
2877                                 break;
2878                 }
2879                 stats->num_luns = softc->num_luns;
2880                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2881                                  softc->num_luns;
2882                 stats->status = CTL_SS_OK;
2883 #ifdef CTL_TIME_IO
2884                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2885 #else
2886                 stats->flags = CTL_STATS_FLAG_NONE;
2887 #endif
2888                 getnanouptime(&stats->timestamp);
2889                 break;
2890         }
2891         case CTL_ERROR_INJECT: {
2892                 struct ctl_error_desc *err_desc, *new_err_desc;
2893                 struct ctl_lun *lun;
2894
2895                 err_desc = (struct ctl_error_desc *)addr;
2896
2897                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2898                                       M_WAITOK | M_ZERO);
2899                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2900
2901                 mtx_lock(&softc->ctl_lock);
2902                 lun = softc->ctl_luns[err_desc->lun_id];
2903                 if (lun == NULL) {
2904                         mtx_unlock(&softc->ctl_lock);
2905                         free(new_err_desc, M_CTL);
2906                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2907                                __func__, (uintmax_t)err_desc->lun_id);
2908                         retval = EINVAL;
2909                         break;
2910                 }
2911                 mtx_lock(&lun->lun_lock);
2912                 mtx_unlock(&softc->ctl_lock);
2913
2914                 /*
2915                  * We could do some checking here to verify the validity
2916                  * of the request, but given the complexity of error
2917                  * injection requests, the checking logic would be fairly
2918                  * complex.
2919                  *
2920                  * For now, if the request is invalid, it just won't get
2921                  * executed and might get deleted.
2922                  */
2923                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2924
2925                 /*
2926                  * XXX KDM check to make sure the serial number is unique,
2927                  * in case we somehow manage to wrap.  That shouldn't
2928                  * happen for a very long time, but it's the right thing to
2929                  * do.
2930                  */
2931                 new_err_desc->serial = lun->error_serial;
2932                 err_desc->serial = lun->error_serial;
2933                 lun->error_serial++;
2934
2935                 mtx_unlock(&lun->lun_lock);
2936                 break;
2937         }
2938         case CTL_ERROR_INJECT_DELETE: {
2939                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2940                 struct ctl_lun *lun;
2941                 int delete_done;
2942
2943                 delete_desc = (struct ctl_error_desc *)addr;
2944                 delete_done = 0;
2945
2946                 mtx_lock(&softc->ctl_lock);
2947                 lun = softc->ctl_luns[delete_desc->lun_id];
2948                 if (lun == NULL) {
2949                         mtx_unlock(&softc->ctl_lock);
2950                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2951                                __func__, (uintmax_t)delete_desc->lun_id);
2952                         retval = EINVAL;
2953                         break;
2954                 }
2955                 mtx_lock(&lun->lun_lock);
2956                 mtx_unlock(&softc->ctl_lock);
2957                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2958                         if (desc->serial != delete_desc->serial)
2959                                 continue;
2960
2961                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2962                                       links);
2963                         free(desc, M_CTL);
2964                         delete_done = 1;
2965                 }
2966                 mtx_unlock(&lun->lun_lock);
2967                 if (delete_done == 0) {
2968                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2969                                "error serial %ju on LUN %u\n", __func__, 
2970                                delete_desc->serial, delete_desc->lun_id);
2971                         retval = EINVAL;
2972                         break;
2973                 }
2974                 break;
2975         }
2976         case CTL_DUMP_STRUCTS: {
2977                 int i, j, k, idx;
2978                 struct ctl_port *port;
2979                 struct ctl_frontend *fe;
2980
2981                 mtx_lock(&softc->ctl_lock);
2982                 printf("CTL Persistent Reservation information start:\n");
2983                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2984                         struct ctl_lun *lun;
2985
2986                         lun = softc->ctl_luns[i];
2987
2988                         if ((lun == NULL)
2989                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2990                                 continue;
2991
2992                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2993                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2994                                         idx = j * CTL_MAX_INIT_PER_PORT + k;
2995                                         if (lun->per_res[idx].registered == 0)
2996                                                 continue;
2997                                         printf("  LUN %d port %d iid %d key "
2998                                                "%#jx\n", i, j, k,
2999                                                (uintmax_t)scsi_8btou64(
3000                                                lun->per_res[idx].res_key.key));
3001                                 }
3002                         }
3003                 }
3004                 printf("CTL Persistent Reservation information end\n");
3005                 printf("CTL Ports:\n");
3006                 STAILQ_FOREACH(port, &softc->port_list, links) {
3007                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3008                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3009                                port->frontend->name, port->port_type,
3010                                port->physical_port, port->virtual_port,
3011                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3012                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3013                                 if (port->wwpn_iid[j].in_use == 0 &&
3014                                     port->wwpn_iid[j].wwpn == 0 &&
3015                                     port->wwpn_iid[j].name == NULL)
3016                                         continue;
3017
3018                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3019                                     j, port->wwpn_iid[j].in_use,
3020                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3021                                     port->wwpn_iid[j].name);
3022                         }
3023                 }
3024                 printf("CTL Port information end\n");
3025                 mtx_unlock(&softc->ctl_lock);
3026                 /*
3027                  * XXX KDM calling this without a lock.  We'd likely want
3028                  * to drop the lock before calling the frontend's dump
3029                  * routine anyway.
3030                  */
3031                 printf("CTL Frontends:\n");
3032                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3033                         printf("  Frontend '%s'\n", fe->name);
3034                         if (fe->fe_dump != NULL)
3035                                 fe->fe_dump();
3036                 }
3037                 printf("CTL Frontend information end\n");
3038                 break;
3039         }
3040         case CTL_LUN_REQ: {
3041                 struct ctl_lun_req *lun_req;
3042                 struct ctl_backend_driver *backend;
3043
3044                 lun_req = (struct ctl_lun_req *)addr;
3045
3046                 backend = ctl_backend_find(lun_req->backend);
3047                 if (backend == NULL) {
3048                         lun_req->status = CTL_LUN_ERROR;
3049                         snprintf(lun_req->error_str,
3050                                  sizeof(lun_req->error_str),
3051                                  "Backend \"%s\" not found.",
3052                                  lun_req->backend);
3053                         break;
3054                 }
3055                 if (lun_req->num_be_args > 0) {
3056                         lun_req->kern_be_args = ctl_copyin_args(
3057                                 lun_req->num_be_args,
3058                                 lun_req->be_args,
3059                                 lun_req->error_str,
3060                                 sizeof(lun_req->error_str));
3061                         if (lun_req->kern_be_args == NULL) {
3062                                 lun_req->status = CTL_LUN_ERROR;
3063                                 break;
3064                         }
3065                 }
3066
3067                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3068
3069                 if (lun_req->num_be_args > 0) {
3070                         ctl_copyout_args(lun_req->num_be_args,
3071                                       lun_req->kern_be_args);
3072                         ctl_free_args(lun_req->num_be_args,
3073                                       lun_req->kern_be_args);
3074                 }
3075                 break;
3076         }
3077         case CTL_LUN_LIST: {
3078                 struct sbuf *sb;
3079                 struct ctl_lun *lun;
3080                 struct ctl_lun_list *list;
3081                 struct ctl_option *opt;
3082
3083                 list = (struct ctl_lun_list *)addr;
3084
3085                 /*
3086                  * Allocate a fixed length sbuf here, based on the length
3087                  * of the user's buffer.  We could allocate an auto-extending
3088                  * buffer, and then tell the user how much larger our
3089                  * amount of data is than his buffer, but that presents
3090                  * some problems:
3091                  *
3092                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3093                  *     we can't hold a lock while calling them with an
3094                  *     auto-extending buffer.
3095                  *
3096                  * 2.  There is not currently a LUN reference counting
3097                  *     mechanism, outside of outstanding transactions on
3098                  *     the LUN's OOA queue.  So a LUN could go away on us
3099                  *     while we're getting the LUN number, backend-specific
3100                  *     information, etc.  Thus, given the way things
3101                  *     currently work, we need to hold the CTL lock while
3102                  *     grabbing LUN information.
3103                  *
3104                  * So, from the user's standpoint, the best thing to do is
3105                  * allocate what he thinks is a reasonable buffer length,
3106                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3107                  * double the buffer length and try again.  (And repeat
3108                  * that until he succeeds.)
3109                  */
3110                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3111                 if (sb == NULL) {
3112                         list->status = CTL_LUN_LIST_ERROR;
3113                         snprintf(list->error_str, sizeof(list->error_str),
3114                                  "Unable to allocate %d bytes for LUN list",
3115                                  list->alloc_len);
3116                         break;
3117                 }
3118
3119                 sbuf_printf(sb, "<ctllunlist>\n");
3120
3121                 mtx_lock(&softc->ctl_lock);
3122                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3123                         mtx_lock(&lun->lun_lock);
3124                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3125                                              (uintmax_t)lun->lun);
3126
3127                         /*
3128                          * Bail out as soon as we see that we've overfilled
3129                          * the buffer.
3130                          */
3131                         if (retval != 0)
3132                                 break;
3133
3134                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3135                                              "</backend_type>\n",
3136                                              (lun->backend == NULL) ?  "none" :
3137                                              lun->backend->name);
3138
3139                         if (retval != 0)
3140                                 break;
3141
3142                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3143                                              lun->be_lun->lun_type);
3144
3145                         if (retval != 0)
3146                                 break;
3147
3148                         if (lun->backend == NULL) {
3149                                 retval = sbuf_printf(sb, "</lun>\n");
3150                                 if (retval != 0)
3151                                         break;
3152                                 continue;
3153                         }
3154
3155                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3156                                              (lun->be_lun->maxlba > 0) ?
3157                                              lun->be_lun->maxlba + 1 : 0);
3158
3159                         if (retval != 0)
3160                                 break;
3161
3162                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3163                                              lun->be_lun->blocksize);
3164
3165                         if (retval != 0)
3166                                 break;
3167
3168                         retval = sbuf_printf(sb, "\t<serial_number>");
3169
3170                         if (retval != 0)
3171                                 break;
3172
3173                         retval = ctl_sbuf_printf_esc(sb,
3174                                                      lun->be_lun->serial_num);
3175
3176                         if (retval != 0)
3177                                 break;
3178
3179                         retval = sbuf_printf(sb, "</serial_number>\n");
3180                 
3181                         if (retval != 0)
3182                                 break;
3183
3184                         retval = sbuf_printf(sb, "\t<device_id>");
3185
3186                         if (retval != 0)
3187                                 break;
3188
3189                         retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3190
3191                         if (retval != 0)
3192                                 break;
3193
3194                         retval = sbuf_printf(sb, "</device_id>\n");
3195
3196                         if (retval != 0)
3197                                 break;
3198
3199                         if (lun->backend->lun_info != NULL) {
3200                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3201                                 if (retval != 0)
3202                                         break;
3203                         }
3204                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3205                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3206                                     opt->name, opt->value, opt->name);
3207                                 if (retval != 0)
3208                                         break;
3209                         }
3210
3211                         retval = sbuf_printf(sb, "</lun>\n");
3212
3213                         if (retval != 0)
3214                                 break;
3215                         mtx_unlock(&lun->lun_lock);
3216                 }
3217                 if (lun != NULL)
3218                         mtx_unlock(&lun->lun_lock);
3219                 mtx_unlock(&softc->ctl_lock);
3220
3221                 if ((retval != 0)
3222                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3223                         retval = 0;
3224                         sbuf_delete(sb);
3225                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3226                         snprintf(list->error_str, sizeof(list->error_str),
3227                                  "Out of space, %d bytes is too small",
3228                                  list->alloc_len);
3229                         break;
3230                 }
3231
3232                 sbuf_finish(sb);
3233
3234                 retval = copyout(sbuf_data(sb), list->lun_xml,
3235                                  sbuf_len(sb) + 1);
3236
3237                 list->fill_len = sbuf_len(sb) + 1;
3238                 list->status = CTL_LUN_LIST_OK;
3239                 sbuf_delete(sb);
3240                 break;
3241         }
3242         case CTL_ISCSI: {
3243                 struct ctl_iscsi *ci;
3244                 struct ctl_frontend *fe;
3245
3246                 ci = (struct ctl_iscsi *)addr;
3247
3248                 fe = ctl_frontend_find("iscsi");
3249                 if (fe == NULL) {
3250                         ci->status = CTL_ISCSI_ERROR;
3251                         snprintf(ci->error_str, sizeof(ci->error_str),
3252                             "Frontend \"iscsi\" not found.");
3253                         break;
3254                 }
3255
3256                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3257                 break;
3258         }
3259         case CTL_PORT_REQ: {
3260                 struct ctl_req *req;
3261                 struct ctl_frontend *fe;
3262
3263                 req = (struct ctl_req *)addr;
3264
3265                 fe = ctl_frontend_find(req->driver);
3266                 if (fe == NULL) {
3267                         req->status = CTL_LUN_ERROR;
3268                         snprintf(req->error_str, sizeof(req->error_str),
3269                             "Frontend \"%s\" not found.", req->driver);
3270                         break;
3271                 }
3272                 if (req->num_args > 0) {
3273                         req->kern_args = ctl_copyin_args(req->num_args,
3274                             req->args, req->error_str, sizeof(req->error_str));
3275                         if (req->kern_args == NULL) {
3276                                 req->status = CTL_LUN_ERROR;
3277                                 break;
3278                         }
3279                 }
3280
3281                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3282
3283                 if (req->num_args > 0) {
3284                         ctl_copyout_args(req->num_args, req->kern_args);
3285                         ctl_free_args(req->num_args, req->kern_args);
3286                 }
3287                 break;
3288         }
3289         case CTL_PORT_LIST: {
3290                 struct sbuf *sb;
3291                 struct ctl_port *port;
3292                 struct ctl_lun_list *list;
3293                 struct ctl_option *opt;
3294
3295                 list = (struct ctl_lun_list *)addr;
3296
3297                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3298                 if (sb == NULL) {
3299                         list->status = CTL_LUN_LIST_ERROR;
3300                         snprintf(list->error_str, sizeof(list->error_str),
3301                                  "Unable to allocate %d bytes for LUN list",
3302                                  list->alloc_len);
3303                         break;
3304                 }
3305
3306                 sbuf_printf(sb, "<ctlportlist>\n");
3307
3308                 mtx_lock(&softc->ctl_lock);
3309                 STAILQ_FOREACH(port, &softc->port_list, links) {
3310                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3311                                              (uintmax_t)port->targ_port);
3312
3313                         /*
3314                          * Bail out as soon as we see that we've overfilled
3315                          * the buffer.
3316                          */
3317                         if (retval != 0)
3318                                 break;
3319
3320                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3321                             "</frontend_type>\n", port->frontend->name);
3322                         if (retval != 0)
3323                                 break;
3324
3325                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3326                                              port->port_type);
3327                         if (retval != 0)
3328                                 break;
3329
3330                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3331                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3332                         if (retval != 0)
3333                                 break;
3334
3335                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3336                             port->port_name);
3337                         if (retval != 0)
3338                                 break;
3339
3340                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3341                             port->physical_port);
3342                         if (retval != 0)
3343                                 break;
3344
3345                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3346                             port->virtual_port);
3347                         if (retval != 0)
3348                                 break;
3349
3350                         retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3351                             (uintmax_t)port->wwnn);
3352                         if (retval != 0)
3353                                 break;
3354
3355                         retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3356                             (uintmax_t)port->wwpn);
3357                         if (retval != 0)
3358                                 break;
3359
3360                         if (port->port_info != NULL) {
3361                                 retval = port->port_info(port->onoff_arg, sb);
3362                                 if (retval != 0)
3363                                         break;
3364                         }
3365                         STAILQ_FOREACH(opt, &port->options, links) {
3366                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3367                                     opt->name, opt->value, opt->name);
3368                                 if (retval != 0)
3369                                         break;
3370                         }
3371
3372                         retval = sbuf_printf(sb, "</targ_port>\n");
3373                         if (retval != 0)
3374                                 break;
3375                 }
3376                 mtx_unlock(&softc->ctl_lock);
3377
3378                 if ((retval != 0)
3379                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3380                         retval = 0;
3381                         sbuf_delete(sb);
3382                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3383                         snprintf(list->error_str, sizeof(list->error_str),
3384                                  "Out of space, %d bytes is too small",
3385                                  list->alloc_len);
3386                         break;
3387                 }
3388
3389                 sbuf_finish(sb);
3390
3391                 retval = copyout(sbuf_data(sb), list->lun_xml,
3392                                  sbuf_len(sb) + 1);
3393
3394                 list->fill_len = sbuf_len(sb) + 1;
3395                 list->status = CTL_LUN_LIST_OK;
3396                 sbuf_delete(sb);
3397                 break;
3398         }
3399         default: {
3400                 /* XXX KDM should we fix this? */
3401 #if 0
3402                 struct ctl_backend_driver *backend;
3403                 unsigned int type;
3404                 int found;
3405
3406                 found = 0;
3407
3408                 /*
3409                  * We encode the backend type as the ioctl type for backend
3410                  * ioctls.  So parse it out here, and then search for a
3411                  * backend of this type.
3412                  */
3413                 type = _IOC_TYPE(cmd);
3414
3415                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3416                         if (backend->type == type) {
3417                                 found = 1;
3418                                 break;
3419                         }
3420                 }
3421                 if (found == 0) {
3422                         printf("ctl: unknown ioctl command %#lx or backend "
3423                                "%d\n", cmd, type);
3424                         retval = EINVAL;
3425                         break;
3426                 }
3427                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3428 #endif
3429                 retval = ENOTTY;
3430                 break;
3431         }
3432         }
3433         return (retval);
3434 }
3435
3436 uint32_t
3437 ctl_get_initindex(struct ctl_nexus *nexus)
3438 {
3439         if (nexus->targ_port < CTL_MAX_PORTS)
3440                 return (nexus->initid.id +
3441                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3442         else
3443                 return (nexus->initid.id +
3444                        ((nexus->targ_port - CTL_MAX_PORTS) *
3445                         CTL_MAX_INIT_PER_PORT));
3446 }
3447
3448 uint32_t
3449 ctl_get_resindex(struct ctl_nexus *nexus)
3450 {
3451         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3452 }
3453
3454 uint32_t
3455 ctl_port_idx(int port_num)
3456 {
3457         if (port_num < CTL_MAX_PORTS)
3458                 return(port_num);
3459         else
3460                 return(port_num - CTL_MAX_PORTS);
3461 }
3462
3463 static uint32_t
3464 ctl_map_lun(int port_num, uint32_t lun_id)
3465 {
3466         struct ctl_port *port;
3467
3468         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3469         if (port == NULL)
3470                 return (UINT32_MAX);
3471         if (port->lun_map == NULL)
3472                 return (lun_id);
3473         return (port->lun_map(port->targ_lun_arg, lun_id));
3474 }
3475
3476 static uint32_t
3477 ctl_map_lun_back(int port_num, uint32_t lun_id)
3478 {
3479         struct ctl_port *port;
3480         uint32_t i;
3481
3482         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3483         if (port->lun_map == NULL)
3484                 return (lun_id);
3485         for (i = 0; i < CTL_MAX_LUNS; i++) {
3486                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3487                         return (i);
3488         }
3489         return (UINT32_MAX);
3490 }
3491
3492 /*
3493  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3494  * that are a power of 2.
3495  */
3496 int
3497 ctl_ffz(uint32_t *mask, uint32_t size)
3498 {
3499         uint32_t num_chunks, num_pieces;
3500         int i, j;
3501
3502         num_chunks = (size >> 5);
3503         if (num_chunks == 0)
3504                 num_chunks++;
3505         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3506
3507         for (i = 0; i < num_chunks; i++) {
3508                 for (j = 0; j < num_pieces; j++) {
3509                         if ((mask[i] & (1 << j)) == 0)
3510                                 return ((i << 5) + j);
3511                 }
3512         }
3513
3514         return (-1);
3515 }
3516
3517 int
3518 ctl_set_mask(uint32_t *mask, uint32_t bit)
3519 {
3520         uint32_t chunk, piece;
3521
3522         chunk = bit >> 5;
3523         piece = bit % (sizeof(uint32_t) * 8);
3524
3525         if ((mask[chunk] & (1 << piece)) != 0)
3526                 return (-1);
3527         else
3528                 mask[chunk] |= (1 << piece);
3529
3530         return (0);
3531 }
3532
3533 int
3534 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3535 {
3536         uint32_t chunk, piece;
3537
3538         chunk = bit >> 5;
3539         piece = bit % (sizeof(uint32_t) * 8);
3540
3541         if ((mask[chunk] & (1 << piece)) == 0)
3542                 return (-1);
3543         else
3544                 mask[chunk] &= ~(1 << piece);
3545
3546         return (0);
3547 }
3548
3549 int
3550 ctl_is_set(uint32_t *mask, uint32_t bit)
3551 {
3552         uint32_t chunk, piece;
3553
3554         chunk = bit >> 5;
3555         piece = bit % (sizeof(uint32_t) * 8);
3556
3557         if ((mask[chunk] & (1 << piece)) == 0)
3558                 return (0);
3559         else
3560                 return (1);
3561 }
3562
3563 #ifdef unused
3564 /*
3565  * The bus, target and lun are optional, they can be filled in later.
3566  * can_wait is used to determine whether we can wait on the malloc or not.
3567  */
3568 union ctl_io*
3569 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3570               uint32_t targ_lun, int can_wait)
3571 {
3572         union ctl_io *io;
3573
3574         if (can_wait)
3575                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3576         else
3577                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3578
3579         if (io != NULL) {
3580                 io->io_hdr.io_type = io_type;
3581                 io->io_hdr.targ_port = targ_port;
3582                 /*
3583                  * XXX KDM this needs to change/go away.  We need to move
3584                  * to a preallocated pool of ctl_scsiio structures.
3585                  */
3586                 io->io_hdr.nexus.targ_target.id = targ_target;
3587                 io->io_hdr.nexus.targ_lun = targ_lun;
3588         }
3589
3590         return (io);
3591 }
3592
3593 void
3594 ctl_kfree_io(union ctl_io *io)
3595 {
3596         free(io, M_CTL);
3597 }
3598 #endif /* unused */
3599
3600 /*
3601  * ctl_softc, pool_type, total_ctl_io are passed in.
3602  * npool is passed out.
3603  */
3604 int
3605 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3606                 uint32_t total_ctl_io, struct ctl_io_pool **npool)
3607 {
3608         uint32_t i;
3609         union ctl_io *cur_io, *next_io;
3610         struct ctl_io_pool *pool;
3611         int retval;
3612
3613         retval = 0;
3614
3615         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3616                                             M_NOWAIT | M_ZERO);
3617         if (pool == NULL) {
3618                 retval = ENOMEM;
3619                 goto bailout;
3620         }
3621
3622         pool->type = pool_type;
3623         pool->ctl_softc = ctl_softc;
3624
3625         mtx_lock(&ctl_softc->pool_lock);
3626         pool->id = ctl_softc->cur_pool_id++;
3627         mtx_unlock(&ctl_softc->pool_lock);
3628
3629         pool->flags = CTL_POOL_FLAG_NONE;
3630         pool->refcount = 1;             /* Reference for validity. */
3631         STAILQ_INIT(&pool->free_queue);
3632
3633         /*
3634          * XXX KDM other options here:
3635          * - allocate a page at a time
3636          * - allocate one big chunk of memory.
3637          * Page allocation might work well, but would take a little more
3638          * tracking.
3639          */
3640         for (i = 0; i < total_ctl_io; i++) {
3641                 cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3642                                                 M_NOWAIT);
3643                 if (cur_io == NULL) {
3644                         retval = ENOMEM;
3645                         break;
3646                 }
3647                 cur_io->io_hdr.pool = pool;
3648                 STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3649                 pool->total_ctl_io++;
3650                 pool->free_ctl_io++;
3651         }
3652
3653         if (retval != 0) {
3654                 for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3655                      cur_io != NULL; cur_io = next_io) {
3656                         next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3657                                                               links);
3658                         STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3659                                       ctl_io_hdr, links);
3660                         free(cur_io, M_CTLIO);
3661                 }
3662
3663                 free(pool, M_CTL);
3664                 goto bailout;
3665         }
3666         mtx_lock(&ctl_softc->pool_lock);
3667         ctl_softc->num_pools++;
3668         STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3669         /*
3670          * Increment our usage count if this is an external consumer, so we
3671          * can't get unloaded until the external consumer (most likely a
3672          * FETD) unloads and frees his pool.
3673          *
3674          * XXX KDM will this increment the caller's module use count, or
3675          * mine?
3676          */
3677 #if 0
3678         if ((pool_type != CTL_POOL_EMERGENCY)
3679          && (pool_type != CTL_POOL_INTERNAL)
3680          && (pool_type != CTL_POOL_4OTHERSC))
3681                 MOD_INC_USE_COUNT;
3682 #endif
3683
3684         mtx_unlock(&ctl_softc->pool_lock);
3685
3686         *npool = pool;
3687
3688 bailout:
3689
3690         return (retval);
3691 }
3692
3693 static int
3694 ctl_pool_acquire(struct ctl_io_pool *pool)
3695 {
3696
3697         mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3698
3699         if (pool->flags & CTL_POOL_FLAG_INVALID)
3700                 return (EINVAL);
3701
3702         pool->refcount++;
3703
3704         return (0);
3705 }
3706
3707 static void
3708 ctl_pool_release(struct ctl_io_pool *pool)
3709 {
3710         struct ctl_softc *ctl_softc = pool->ctl_softc;
3711         union ctl_io *io;
3712
3713         mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3714
3715         if (--pool->refcount != 0)
3716                 return;
3717
3718         while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3719                 STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3720                               links);
3721                 free(io, M_CTLIO);
3722         }
3723
3724         STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3725         ctl_softc->num_pools--;
3726
3727         /*
3728          * XXX KDM will this decrement the caller's usage count or mine?
3729          */
3730 #if 0
3731         if ((pool->type != CTL_POOL_EMERGENCY)
3732          && (pool->type != CTL_POOL_INTERNAL)
3733          && (pool->type != CTL_POOL_4OTHERSC))
3734                 MOD_DEC_USE_COUNT;
3735 #endif
3736
3737         free(pool, M_CTL);
3738 }
3739
3740 void
3741 ctl_pool_free(struct ctl_io_pool *pool)
3742 {
3743         struct ctl_softc *ctl_softc;
3744
3745         if (pool == NULL)
3746                 return;
3747
3748         ctl_softc = pool->ctl_softc;
3749         mtx_lock(&ctl_softc->pool_lock);
3750         pool->flags |= CTL_POOL_FLAG_INVALID;
3751         ctl_pool_release(pool);
3752         mtx_unlock(&ctl_softc->pool_lock);
3753 }
3754
3755 /*
3756  * This routine does not block (except for spinlocks of course).
3757  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3758  * possible.
3759  */
3760 union ctl_io *
3761 ctl_alloc_io(void *pool_ref)
3762 {
3763         union ctl_io *io;
3764         struct ctl_softc *ctl_softc;
3765         struct ctl_io_pool *pool, *npool;
3766         struct ctl_io_pool *emergency_pool;
3767
3768         pool = (struct ctl_io_pool *)pool_ref;
3769
3770         if (pool == NULL) {
3771                 printf("%s: pool is NULL\n", __func__);
3772                 return (NULL);
3773         }
3774
3775         emergency_pool = NULL;
3776
3777         ctl_softc = pool->ctl_softc;
3778
3779         mtx_lock(&ctl_softc->pool_lock);
3780         /*
3781          * First, try to get the io structure from the user's pool.
3782          */
3783         if (ctl_pool_acquire(pool) == 0) {
3784                 io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3785                 if (io != NULL) {
3786                         STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3787                         pool->total_allocated++;
3788                         pool->free_ctl_io--;
3789                         mtx_unlock(&ctl_softc->pool_lock);
3790                         return (io);
3791                 } else
3792                         ctl_pool_release(pool);
3793         }
3794         /*
3795          * If he doesn't have any io structures left, search for an
3796          * emergency pool and grab one from there.
3797          */
3798         STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3799                 if (npool->type != CTL_POOL_EMERGENCY)
3800                         continue;
3801
3802                 if (ctl_pool_acquire(npool) != 0)
3803                         continue;
3804
3805                 emergency_pool = npool;
3806
3807                 io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3808                 if (io != NULL) {
3809                         STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3810                         npool->total_allocated++;
3811                         npool->free_ctl_io--;
3812                         mtx_unlock(&ctl_softc->pool_lock);
3813                         return (io);
3814                 } else
3815                         ctl_pool_release(npool);
3816         }
3817
3818         /* Drop the spinlock before we malloc */
3819         mtx_unlock(&ctl_softc->pool_lock);
3820
3821         /*
3822          * The emergency pool (if it exists) didn't have one, so try an
3823          * atomic (i.e. nonblocking) malloc and see if we get lucky.
3824          */
3825         io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3826         if (io != NULL) {
3827                 /*
3828                  * If the emergency pool exists but is empty, add this
3829                  * ctl_io to its list when it gets freed.
3830                  */
3831                 if (emergency_pool != NULL) {
3832                         mtx_lock(&ctl_softc->pool_lock);
3833                         if (ctl_pool_acquire(emergency_pool) == 0) {
3834                                 io->io_hdr.pool = emergency_pool;
3835                                 emergency_pool->total_ctl_io++;
3836                                 /*
3837                                  * Need to bump this, otherwise
3838                                  * total_allocated and total_freed won't
3839                                  * match when we no longer have anything
3840                                  * outstanding.
3841                                  */
3842                                 emergency_pool->total_allocated++;
3843                         }
3844                         mtx_unlock(&ctl_softc->pool_lock);
3845                 } else
3846                         io->io_hdr.pool = NULL;
3847         }
3848
3849         return (io);
3850 }
3851
3852 void
3853 ctl_free_io(union ctl_io *io)
3854 {
3855         if (io == NULL)
3856                 return;
3857
3858         /*
3859          * If this ctl_io has a pool, return it to that pool.
3860          */
3861         if (io->io_hdr.pool != NULL) {
3862                 struct ctl_io_pool *pool;
3863
3864                 pool = (struct ctl_io_pool *)io->io_hdr.pool;
3865                 mtx_lock(&pool->ctl_softc->pool_lock);
3866                 io->io_hdr.io_type = 0xff;
3867                 STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3868                 pool->total_freed++;
3869                 pool->free_ctl_io++;
3870                 ctl_pool_release(pool);
3871                 mtx_unlock(&pool->ctl_softc->pool_lock);
3872         } else {
3873                 /*
3874                  * Otherwise, just free it.  We probably malloced it and
3875                  * the emergency pool wasn't available.
3876                  */
3877                 free(io, M_CTLIO);
3878         }
3879
3880 }
3881
3882 void
3883 ctl_zero_io(union ctl_io *io)
3884 {
3885         void *pool_ref;
3886
3887         if (io == NULL)
3888                 return;
3889
3890         /*
3891          * May need to preserve linked list pointers at some point too.
3892          */
3893         pool_ref = io->io_hdr.pool;
3894
3895         memset(io, 0, sizeof(*io));
3896
3897         io->io_hdr.pool = pool_ref;
3898 }
3899
3900 /*
3901  * This routine is currently used for internal copies of ctl_ios that need
3902  * to persist for some reason after we've already returned status to the
3903  * FETD.  (Thus the flag set.)
3904  *
3905  * XXX XXX
3906  * Note that this makes a blind copy of all fields in the ctl_io, except
3907  * for the pool reference.  This includes any memory that has been
3908  * allocated!  That memory will no longer be valid after done has been
3909  * called, so this would be VERY DANGEROUS for command that actually does
3910  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3911  * start and stop commands, which don't transfer any data, so this is not a
3912  * problem.  If it is used for anything else, the caller would also need to
3913  * allocate data buffer space and this routine would need to be modified to
3914  * copy the data buffer(s) as well.
3915  */
3916 void
3917 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3918 {
3919         void *pool_ref;
3920
3921         if ((src == NULL)
3922          || (dest == NULL))
3923                 return;
3924
3925         /*
3926          * May need to preserve linked list pointers at some point too.
3927          */
3928         pool_ref = dest->io_hdr.pool;
3929
3930         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3931
3932         dest->io_hdr.pool = pool_ref;
3933         /*
3934          * We need to know that this is an internal copy, and doesn't need
3935          * to get passed back to the FETD that allocated it.
3936          */
3937         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3938 }
3939
3940 #ifdef NEEDTOPORT
3941 static void
3942 ctl_update_power_subpage(struct copan_power_subpage *page)
3943 {
3944         int num_luns, num_partitions, config_type;
3945         struct ctl_softc *softc;
3946         cs_BOOL_t aor_present, shelf_50pct_power;
3947         cs_raidset_personality_t rs_type;
3948         int max_active_luns;
3949
3950         softc = control_softc;
3951
3952         /* subtract out the processor LUN */
3953         num_luns = softc->num_luns - 1;
3954         /*
3955          * Default to 7 LUNs active, which was the only number we allowed
3956          * in the past.
3957          */
3958         max_active_luns = 7;
3959
3960         num_partitions = config_GetRsPartitionInfo();
3961         config_type = config_GetConfigType();
3962         shelf_50pct_power = config_GetShelfPowerMode();
3963         aor_present = config_IsAorRsPresent();
3964
3965         rs_type = ddb_GetRsRaidType(1);
3966         if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3967          && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3968                 EPRINT(0, "Unsupported RS type %d!", rs_type);
3969         }
3970
3971
3972         page->total_luns = num_luns;
3973
3974         switch (config_type) {
3975         case 40:
3976                 /*
3977                  * In a 40 drive configuration, it doesn't matter what DC
3978                  * cards we have, whether we have AOR enabled or not,
3979                  * partitioning or not, or what type of RAIDset we have.
3980                  * In that scenario, we can power up every LUN we present
3981                  * to the user.
3982                  */
3983                 max_active_luns = num_luns;
3984
3985                 break;
3986         case 64:
3987                 if (shelf_50pct_power == CS_FALSE) {
3988                         /* 25% power */
3989                         if (aor_present == CS_TRUE) {
3990                                 if (rs_type ==
3991                                      CS_RAIDSET_PERSONALITY_RAID5) {
3992                                         max_active_luns = 7;
3993                                 } else if (rs_type ==
3994                                          CS_RAIDSET_PERSONALITY_RAID1){
3995                                         max_active_luns = 14;
3996                                 } else {
3997                                         /* XXX KDM now what?? */
3998                                 }
3999                         } else {
4000                                 if (rs_type ==
4001                                      CS_RAIDSET_PERSONALITY_RAID5) {
4002                                         max_active_luns = 8;
4003                                 } else if (rs_type ==
4004                                          CS_RAIDSET_PERSONALITY_RAID1){
4005                                         max_active_luns = 16;
4006                                 } else {
4007                                         /* XXX KDM now what?? */
4008                                 }
4009                         }
4010                 } else {
4011                         /* 50% power */
4012                         /*
4013                          * With 50% power in a 64 drive configuration, we
4014                          * can power all LUNs we present.
4015                          */
4016                         max_active_luns = num_luns;
4017                 }
4018                 break;
4019         case 112:
4020                 if (shelf_50pct_power == CS_FALSE) {
4021                         /* 25% power */
4022                         if (aor_present == CS_TRUE) {
4023                                 if (rs_type ==
4024                                      CS_RAIDSET_PERSONALITY_RAID5) {
4025                                         max_active_luns = 7;
4026                                 } else if (rs_type ==
4027                                          CS_RAIDSET_PERSONALITY_RAID1){
4028                                         max_active_luns = 14;
4029                                 } else {
4030                                         /* XXX KDM now what?? */
4031                                 }
4032                         } else {
4033                                 if (rs_type ==
4034                                      CS_RAIDSET_PERSONALITY_RAID5) {
4035                                         max_active_luns = 8;
4036                                 } else if (rs_type ==
4037                                          CS_RAIDSET_PERSONALITY_RAID1){
4038                                         max_active_luns = 16;
4039                                 } else {
4040                                         /* XXX KDM now what?? */
4041                                 }
4042                         }
4043                 } else {
4044                         /* 50% power */
4045                         if (aor_present == CS_TRUE) {
4046                                 if (rs_type ==
4047                                      CS_RAIDSET_PERSONALITY_RAID5) {
4048                                         max_active_luns = 14;
4049                                 } else if (rs_type ==
4050                                          CS_RAIDSET_PERSONALITY_RAID1){
4051                                         /*
4052                                          * We're assuming here that disk
4053                                          * caching is enabled, and so we're
4054                                          * able to power up half of each
4055                                          * LUN, and cache all writes.
4056                                          */
4057                                         max_active_luns = num_luns;
4058                                 } else {
4059                                         /* XXX KDM now what?? */
4060                                 }
4061                         } else {
4062                                 if (rs_type ==
4063                                      CS_RAIDSET_PERSONALITY_RAID5) {
4064                                         max_active_luns = 15;
4065                                 } else if (rs_type ==
4066                                          CS_RAIDSET_PERSONALITY_RAID1){
4067                                         max_active_luns = 30;
4068                                 } else {
4069                                         /* XXX KDM now what?? */
4070                                 }
4071                         }
4072                 }
4073                 break;
4074         default:
4075                 /*
4076                  * In this case, we have an unknown configuration, so we
4077                  * just use the default from above.
4078                  */
4079                 break;
4080         }
4081
4082         page->max_active_luns = max_active_luns;
4083 #if 0
4084         printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4085                page->total_luns, page->max_active_luns);
4086 #endif
4087 }
4088 #endif /* NEEDTOPORT */
4089
4090 /*
4091  * This routine could be used in the future to load default and/or saved
4092  * mode page parameters for a particuar lun.
4093  */
4094 static int
4095 ctl_init_page_index(struct ctl_lun *lun)
4096 {
4097         int i;
4098         struct ctl_page_index *page_index;
4099         struct ctl_softc *softc;
4100         const char *value;
4101
4102         memcpy(&lun->mode_pages.index, page_index_template,
4103                sizeof(page_index_template));
4104
4105         softc = lun->ctl_softc;
4106
4107         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4108
4109                 page_index = &lun->mode_pages.index[i];
4110                 /*
4111                  * If this is a disk-only mode page, there's no point in
4112                  * setting it up.  For some pages, we have to have some
4113                  * basic information about the disk in order to calculate the
4114                  * mode page data.
4115                  */
4116                 if ((lun->be_lun->lun_type != T_DIRECT)
4117                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4118                         continue;
4119
4120                 switch (page_index->page_code & SMPH_PC_MASK) {
4121                 case SMS_FORMAT_DEVICE_PAGE: {
4122                         struct scsi_format_page *format_page;
4123
4124                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4125                                 panic("subpage is incorrect!");
4126
4127                         /*
4128                          * Sectors per track are set above.  Bytes per
4129                          * sector need to be set here on a per-LUN basis.
4130                          */
4131                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4132                                &format_page_default,
4133                                sizeof(format_page_default));
4134                         memcpy(&lun->mode_pages.format_page[
4135                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4136                                sizeof(format_page_changeable));
4137                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4138                                &format_page_default,
4139                                sizeof(format_page_default));
4140                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4141                                &format_page_default,
4142                                sizeof(format_page_default));
4143
4144                         format_page = &lun->mode_pages.format_page[
4145                                 CTL_PAGE_CURRENT];
4146                         scsi_ulto2b(lun->be_lun->blocksize,
4147                                     format_page->bytes_per_sector);
4148
4149                         format_page = &lun->mode_pages.format_page[
4150                                 CTL_PAGE_DEFAULT];
4151                         scsi_ulto2b(lun->be_lun->blocksize,
4152                                     format_page->bytes_per_sector);
4153
4154                         format_page = &lun->mode_pages.format_page[
4155                                 CTL_PAGE_SAVED];
4156                         scsi_ulto2b(lun->be_lun->blocksize,
4157                                     format_page->bytes_per_sector);
4158
4159                         page_index->page_data =
4160                                 (uint8_t *)lun->mode_pages.format_page;
4161                         break;
4162                 }
4163                 case SMS_RIGID_DISK_PAGE: {
4164                         struct scsi_rigid_disk_page *rigid_disk_page;
4165                         uint32_t sectors_per_cylinder;
4166                         uint64_t cylinders;
4167 #ifndef __XSCALE__
4168                         int shift;
4169 #endif /* !__XSCALE__ */
4170
4171                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4172                                 panic("invalid subpage value %d",
4173                                       page_index->subpage);
4174
4175                         /*
4176                          * Rotation rate and sectors per track are set
4177                          * above.  We calculate the cylinders here based on
4178                          * capacity.  Due to the number of heads and
4179                          * sectors per track we're using, smaller arrays
4180                          * may turn out to have 0 cylinders.  Linux and
4181                          * FreeBSD don't pay attention to these mode pages
4182                          * to figure out capacity, but Solaris does.  It
4183                          * seems to deal with 0 cylinders just fine, and
4184                          * works out a fake geometry based on the capacity.
4185                          */
4186                         memcpy(&lun->mode_pages.rigid_disk_page[
4187                                CTL_PAGE_CURRENT], &rigid_disk_page_default,
4188                                sizeof(rigid_disk_page_default));
4189                         memcpy(&lun->mode_pages.rigid_disk_page[
4190                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4191                                sizeof(rigid_disk_page_changeable));
4192                         memcpy(&lun->mode_pages.rigid_disk_page[
4193                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4194                                sizeof(rigid_disk_page_default));
4195                         memcpy(&lun->mode_pages.rigid_disk_page[
4196                                CTL_PAGE_SAVED], &rigid_disk_page_default,
4197                                sizeof(rigid_disk_page_default));
4198
4199                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4200                                 CTL_DEFAULT_HEADS;
4201
4202                         /*
4203                          * The divide method here will be more accurate,
4204                          * probably, but results in floating point being
4205                          * used in the kernel on i386 (__udivdi3()).  On the
4206                          * XScale, though, __udivdi3() is implemented in
4207                          * software.
4208                          *
4209                          * The shift method for cylinder calculation is
4210                          * accurate if sectors_per_cylinder is a power of
4211                          * 2.  Otherwise it might be slightly off -- you
4212                          * might have a bit of a truncation problem.
4213                          */
4214 #ifdef  __XSCALE__
4215                         cylinders = (lun->be_lun->maxlba + 1) /
4216                                 sectors_per_cylinder;
4217 #else
4218                         for (shift = 31; shift > 0; shift--) {
4219                                 if (sectors_per_cylinder & (1 << shift))
4220                                         break;
4221                         }
4222                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4223 #endif
4224
4225                         /*
4226                          * We've basically got 3 bytes, or 24 bits for the
4227                          * cylinder size in the mode page.  If we're over,
4228                          * just round down to 2^24.
4229                          */
4230                         if (cylinders > 0xffffff)
4231                                 cylinders = 0xffffff;
4232
4233                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4234                                 CTL_PAGE_CURRENT];
4235                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4236
4237                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4238                                 CTL_PAGE_DEFAULT];
4239                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4240
4241                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4242                                 CTL_PAGE_SAVED];
4243                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4244
4245                         page_index->page_data =
4246                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4247                         break;
4248                 }
4249                 case SMS_CACHING_PAGE: {
4250                         struct scsi_caching_page *caching_page;
4251
4252                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4253                                 panic("invalid subpage value %d",
4254                                       page_index->subpage);
4255                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4256                                &caching_page_default,
4257                                sizeof(caching_page_default));
4258                         memcpy(&lun->mode_pages.caching_page[
4259                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4260                                sizeof(caching_page_changeable));
4261                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4262                                &caching_page_default,
4263                                sizeof(caching_page_default));
4264                         caching_page = &lun->mode_pages.caching_page[
4265                             CTL_PAGE_SAVED];
4266                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4267                         if (value != NULL && strcmp(value, "off") == 0)
4268                                 caching_page->flags1 &= ~SCP_WCE;
4269                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4270                         if (value != NULL && strcmp(value, "off") == 0)
4271                                 caching_page->flags1 |= SCP_RCD;
4272                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4273                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4274                                sizeof(caching_page_default));
4275                         page_index->page_data =
4276                                 (uint8_t *)lun->mode_pages.caching_page;
4277                         break;
4278                 }
4279                 case SMS_CONTROL_MODE_PAGE: {
4280                         struct scsi_control_page *control_page;
4281
4282                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4283                                 panic("invalid subpage value %d",
4284                                       page_index->subpage);
4285
4286                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4287                                &control_page_default,
4288                                sizeof(control_page_default));
4289                         memcpy(&lun->mode_pages.control_page[
4290                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4291                                sizeof(control_page_changeable));
4292                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4293                                &control_page_default,
4294                                sizeof(control_page_default));
4295                         control_page = &lun->mode_pages.control_page[
4296                             CTL_PAGE_SAVED];
4297                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4298                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4299                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4300                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4301                         }
4302                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4303                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4304                                sizeof(control_page_default));
4305                         page_index->page_data =
4306                                 (uint8_t *)lun->mode_pages.control_page;
4307                         break;
4308
4309                 }
4310                 case SMS_VENDOR_SPECIFIC_PAGE:{
4311                         switch (page_index->subpage) {
4312                         case PWR_SUBPAGE_CODE: {
4313                                 struct copan_power_subpage *current_page,
4314                                                            *saved_page;
4315
4316                                 memcpy(&lun->mode_pages.power_subpage[
4317                                        CTL_PAGE_CURRENT],
4318                                        &power_page_default,
4319                                        sizeof(power_page_default));
4320                                 memcpy(&lun->mode_pages.power_subpage[
4321                                        CTL_PAGE_CHANGEABLE],
4322                                        &power_page_changeable,
4323                                        sizeof(power_page_changeable));
4324                                 memcpy(&lun->mode_pages.power_subpage[
4325                                        CTL_PAGE_DEFAULT],
4326                                        &power_page_default,
4327                                        sizeof(power_page_default));
4328                                 memcpy(&lun->mode_pages.power_subpage[
4329                                        CTL_PAGE_SAVED],
4330                                        &power_page_default,
4331                                        sizeof(power_page_default));
4332                                 page_index->page_data =
4333                                     (uint8_t *)lun->mode_pages.power_subpage;
4334
4335                                 current_page = (struct copan_power_subpage *)
4336                                         (page_index->page_data +
4337                                          (page_index->page_len *
4338                                           CTL_PAGE_CURRENT));
4339                                 saved_page = (struct copan_power_subpage *)
4340                                         (page_index->page_data +
4341                                          (page_index->page_len *
4342                                           CTL_PAGE_SAVED));
4343                                 break;
4344                         }
4345                         case APS_SUBPAGE_CODE: {
4346                                 struct copan_aps_subpage *current_page,
4347                                                          *saved_page;
4348
4349                                 // This gets set multiple times but
4350                                 // it should always be the same. It's
4351                                 // only done during init so who cares.
4352                                 index_to_aps_page = i;
4353
4354                                 memcpy(&lun->mode_pages.aps_subpage[
4355                                        CTL_PAGE_CURRENT],
4356                                        &aps_page_default,
4357                                        sizeof(aps_page_default));
4358                                 memcpy(&lun->mode_pages.aps_subpage[
4359                                        CTL_PAGE_CHANGEABLE],
4360                                        &aps_page_changeable,
4361                                        sizeof(aps_page_changeable));
4362                                 memcpy(&lun->mode_pages.aps_subpage[
4363                                        CTL_PAGE_DEFAULT],
4364                                        &aps_page_default,
4365                                        sizeof(aps_page_default));
4366                                 memcpy(&lun->mode_pages.aps_subpage[
4367                                        CTL_PAGE_SAVED],
4368                                        &aps_page_default,
4369                                        sizeof(aps_page_default));
4370                                 page_index->page_data =
4371                                         (uint8_t *)lun->mode_pages.aps_subpage;
4372
4373                                 current_page = (struct copan_aps_subpage *)
4374                                         (page_index->page_data +
4375                                          (page_index->page_len *
4376                                           CTL_PAGE_CURRENT));
4377                                 saved_page = (struct copan_aps_subpage *)
4378                                         (page_index->page_data +
4379                                          (page_index->page_len *
4380                                           CTL_PAGE_SAVED));
4381                                 break;
4382                         }
4383                         case DBGCNF_SUBPAGE_CODE: {
4384                                 struct copan_debugconf_subpage *current_page,
4385                                                                *saved_page;
4386
4387                                 memcpy(&lun->mode_pages.debugconf_subpage[
4388                                        CTL_PAGE_CURRENT],
4389                                        &debugconf_page_default,
4390                                        sizeof(debugconf_page_default));
4391                                 memcpy(&lun->mode_pages.debugconf_subpage[
4392                                        CTL_PAGE_CHANGEABLE],
4393                                        &debugconf_page_changeable,
4394                                        sizeof(debugconf_page_changeable));
4395                                 memcpy(&lun->mode_pages.debugconf_subpage[
4396                                        CTL_PAGE_DEFAULT],
4397                                        &debugconf_page_default,
4398                                        sizeof(debugconf_page_default));
4399                                 memcpy(&lun->mode_pages.debugconf_subpage[
4400                                        CTL_PAGE_SAVED],
4401                                        &debugconf_page_default,
4402                                        sizeof(debugconf_page_default));
4403                                 page_index->page_data =
4404                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4405
4406                                 current_page = (struct copan_debugconf_subpage *)
4407                                         (page_index->page_data +
4408                                          (page_index->page_len *
4409                                           CTL_PAGE_CURRENT));
4410                                 saved_page = (struct copan_debugconf_subpage *)
4411                                         (page_index->page_data +
4412                                          (page_index->page_len *
4413                                           CTL_PAGE_SAVED));
4414                                 break;
4415                         }
4416                         default:
4417                                 panic("invalid subpage value %d",
4418                                       page_index->subpage);
4419                                 break;
4420                         }
4421                         break;
4422                 }
4423                 default:
4424                         panic("invalid page value %d",
4425                               page_index->page_code & SMPH_PC_MASK);
4426                         break;
4427         }
4428         }
4429
4430         return (CTL_RETVAL_COMPLETE);
4431 }
4432
4433 /*
4434  * LUN allocation.
4435  *
4436  * Requirements:
4437  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4438  *   wants us to allocate the LUN and he can block.
4439  * - ctl_softc is always set
4440  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4441  *
4442  * Returns 0 for success, non-zero (errno) for failure.
4443  */
4444 static int
4445 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4446               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4447 {
4448         struct ctl_lun *nlun, *lun;
4449         struct ctl_port *port;
4450         struct scsi_vpd_id_descriptor *desc;
4451         struct scsi_vpd_id_t10 *t10id;
4452         const char *eui, *naa, *scsiname, *vendor;
4453         int lun_number, i, lun_malloced;
4454         int devidlen, idlen1, idlen2 = 0, len;
4455
4456         if (be_lun == NULL)
4457                 return (EINVAL);
4458
4459         /*
4460          * We currently only support Direct Access or Processor LUN types.
4461          */
4462         switch (be_lun->lun_type) {
4463         case T_DIRECT:
4464                 break;
4465         case T_PROCESSOR:
4466                 break;
4467         case T_SEQUENTIAL:
4468         case T_CHANGER:
4469         default:
4470                 be_lun->lun_config_status(be_lun->be_lun,
4471                                           CTL_LUN_CONFIG_FAILURE);
4472                 break;
4473         }
4474         if (ctl_lun == NULL) {
4475                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4476                 lun_malloced = 1;
4477         } else {
4478                 lun_malloced = 0;
4479                 lun = ctl_lun;
4480         }
4481
4482         memset(lun, 0, sizeof(*lun));
4483         if (lun_malloced)
4484                 lun->flags = CTL_LUN_MALLOCED;
4485
4486         /* Generate LUN ID. */
4487         devidlen = max(CTL_DEVID_MIN_LEN,
4488             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4489         idlen1 = sizeof(*t10id) + devidlen;
4490         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4491         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4492         if (scsiname != NULL) {
4493                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4494                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4495         }
4496         eui = ctl_get_opt(&be_lun->options, "eui");
4497         if (eui != NULL) {
4498                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4499         }
4500         naa = ctl_get_opt(&be_lun->options, "naa");
4501         if (naa != NULL) {
4502                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4503         }
4504         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4505             M_CTL, M_WAITOK | M_ZERO);
4506         lun->lun_devid->len = len;
4507         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4508         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4509         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4510         desc->length = idlen1;
4511         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4512         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4513         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4514                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4515         } else {
4516                 strncpy(t10id->vendor, vendor,
4517                     min(sizeof(t10id->vendor), strlen(vendor)));
4518         }
4519         strncpy((char *)t10id->vendor_spec_id,
4520             (char *)be_lun->device_id, devidlen);
4521         if (scsiname != NULL) {
4522                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4523                     desc->length);
4524                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4525                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4526                     SVPD_ID_TYPE_SCSI_NAME;
4527                 desc->length = idlen2;
4528                 strlcpy(desc->identifier, scsiname, idlen2);
4529         }
4530         if (eui != NULL) {
4531                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4532                     desc->length);
4533                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4534                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4535                     SVPD_ID_TYPE_EUI64;
4536                 desc->length = 8;
4537                 scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4538         }
4539         if (naa != NULL) {
4540                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4541                     desc->length);
4542                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4543                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4544                     SVPD_ID_TYPE_NAA;
4545                 desc->length = 8;
4546                 scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4547         }
4548
4549         mtx_lock(&ctl_softc->ctl_lock);
4550         /*
4551          * See if the caller requested a particular LUN number.  If so, see
4552          * if it is available.  Otherwise, allocate the first available LUN.
4553          */
4554         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4555                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4556                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4557                         mtx_unlock(&ctl_softc->ctl_lock);
4558                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4559                                 printf("ctl: requested LUN ID %d is higher "
4560                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4561                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4562                         } else {
4563                                 /*
4564                                  * XXX KDM return an error, or just assign
4565                                  * another LUN ID in this case??
4566                                  */
4567                                 printf("ctl: requested LUN ID %d is already "
4568                                        "in use\n", be_lun->req_lun_id);
4569                         }
4570                         if (lun->flags & CTL_LUN_MALLOCED)
4571                                 free(lun, M_CTL);
4572                         be_lun->lun_config_status(be_lun->be_lun,
4573                                                   CTL_LUN_CONFIG_FAILURE);
4574                         return (ENOSPC);
4575                 }
4576                 lun_number = be_lun->req_lun_id;
4577         } else {
4578                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4579                 if (lun_number == -1) {
4580                         mtx_unlock(&ctl_softc->ctl_lock);
4581                         printf("ctl: can't allocate LUN on target %ju, out of "
4582                                "LUNs\n", (uintmax_t)target_id.id);
4583                         if (lun->flags & CTL_LUN_MALLOCED)
4584                                 free(lun, M_CTL);
4585                         be_lun->lun_config_status(be_lun->be_lun,
4586                                                   CTL_LUN_CONFIG_FAILURE);
4587                         return (ENOSPC);
4588                 }
4589         }
4590         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4591
4592         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4593         lun->target = target_id;
4594         lun->lun = lun_number;
4595         lun->be_lun = be_lun;
4596         /*
4597          * The processor LUN is always enabled.  Disk LUNs come on line
4598          * disabled, and must be enabled by the backend.
4599          */
4600         lun->flags |= CTL_LUN_DISABLED;
4601         lun->backend = be_lun->be;
4602         be_lun->ctl_lun = lun;
4603         be_lun->lun_id = lun_number;
4604         atomic_add_int(&be_lun->be->num_luns, 1);
4605         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4606                 lun->flags |= CTL_LUN_STOPPED;
4607
4608         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4609                 lun->flags |= CTL_LUN_INOPERABLE;
4610
4611         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4612                 lun->flags |= CTL_LUN_PRIMARY_SC;
4613
4614         lun->ctl_softc = ctl_softc;
4615         TAILQ_INIT(&lun->ooa_queue);
4616         TAILQ_INIT(&lun->blocked_queue);
4617         STAILQ_INIT(&lun->error_list);
4618         ctl_tpc_lun_init(lun);
4619
4620         /*
4621          * Initialize the mode page index.
4622          */
4623         ctl_init_page_index(lun);
4624
4625         /*
4626          * Set the poweron UA for all initiators on this LUN only.
4627          */
4628         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4629                 lun->pending_ua[i] = CTL_UA_POWERON;
4630
4631         /*
4632          * Now, before we insert this lun on the lun list, set the lun
4633          * inventory changed UA for all other luns.
4634          */
4635         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4636                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4637                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4638                 }
4639         }
4640
4641         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4642
4643         ctl_softc->ctl_luns[lun_number] = lun;
4644
4645         ctl_softc->num_luns++;
4646
4647         /* Setup statistics gathering */
4648         lun->stats.device_type = be_lun->lun_type;
4649         lun->stats.lun_number = lun_number;
4650         if (lun->stats.device_type == T_DIRECT)
4651                 lun->stats.blocksize = be_lun->blocksize;
4652         else
4653                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4654         for (i = 0;i < CTL_MAX_PORTS;i++)
4655                 lun->stats.ports[i].targ_port = i;
4656
4657         mtx_unlock(&ctl_softc->ctl_lock);
4658
4659         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4660
4661         /*
4662          * Run through each registered FETD and bring it online if it isn't
4663          * already.  Enable the target ID if it hasn't been enabled, and
4664          * enable this particular LUN.
4665          */
4666         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4667                 int retval;
4668
4669                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4670                 if (retval != 0) {
4671                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4672                                "%d for lun_enable on target %ju lun %d\n",
4673                                port->port_name, port->targ_port, retval,
4674                                (uintmax_t)target_id.id, lun_number);
4675                 } else
4676                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4677         }
4678         return (0);
4679 }
4680
4681 /*
4682  * Delete a LUN.
4683  * Assumptions:
4684  * - LUN has already been marked invalid and any pending I/O has been taken
4685  *   care of.
4686  */
4687 static int
4688 ctl_free_lun(struct ctl_lun *lun)
4689 {
4690         struct ctl_softc *softc;
4691 #if 0
4692         struct ctl_port *port;
4693 #endif
4694         struct ctl_lun *nlun;
4695         int i;
4696
4697         softc = lun->ctl_softc;
4698
4699         mtx_assert(&softc->ctl_lock, MA_OWNED);
4700
4701         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4702
4703         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4704
4705         softc->ctl_luns[lun->lun] = NULL;
4706
4707         if (!TAILQ_EMPTY(&lun->ooa_queue))
4708                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4709
4710         softc->num_luns--;
4711
4712         /*
4713          * XXX KDM this scheme only works for a single target/multiple LUN
4714          * setup.  It needs to be revamped for a multiple target scheme.
4715          *
4716          * XXX KDM this results in port->lun_disable() getting called twice,
4717          * once when ctl_disable_lun() is called, and a second time here.
4718          * We really need to re-think the LUN disable semantics.  There
4719          * should probably be several steps/levels to LUN removal:
4720          *  - disable
4721          *  - invalidate
4722          *  - free
4723          *
4724          * Right now we only have a disable method when communicating to
4725          * the front end ports, at least for individual LUNs.
4726          */
4727 #if 0
4728         STAILQ_FOREACH(port, &softc->port_list, links) {
4729                 int retval;
4730
4731                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4732                                          lun->lun);
4733                 if (retval != 0) {
4734                         printf("ctl_free_lun: FETD %s port %d returned error "
4735                                "%d for lun_disable on target %ju lun %jd\n",
4736                                port->port_name, port->targ_port, retval,
4737                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4738                 }
4739
4740                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4741                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4742
4743                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4744                         if (retval != 0) {
4745                                 printf("ctl_free_lun: FETD %s port %d "
4746                                        "returned error %d for targ_disable on "
4747                                        "target %ju\n", port->port_name,
4748                                        port->targ_port, retval,
4749                                        (uintmax_t)lun->target.id);
4750                         } else
4751                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4752
4753                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4754                                 continue;
4755
4756 #if 0
4757                         port->port_offline(port->onoff_arg);
4758                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4759 #endif
4760                 }
4761         }
4762 #endif
4763
4764         /*
4765          * Tell the backend to free resources, if this LUN has a backend.
4766          */
4767         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4768         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4769
4770         ctl_tpc_lun_shutdown(lun);
4771         mtx_destroy(&lun->lun_lock);
4772         free(lun->lun_devid, M_CTL);
4773         if (lun->flags & CTL_LUN_MALLOCED)
4774                 free(lun, M_CTL);
4775
4776         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4777                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4778                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4779                 }
4780         }
4781
4782         return (0);
4783 }
4784
4785 static void
4786 ctl_create_lun(struct ctl_be_lun *be_lun)
4787 {
4788         struct ctl_softc *ctl_softc;
4789
4790         ctl_softc = control_softc;
4791
4792         /*
4793          * ctl_alloc_lun() should handle all potential failure cases.
4794          */
4795         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4796 }
4797
4798 int
4799 ctl_add_lun(struct ctl_be_lun *be_lun)
4800 {
4801         struct ctl_softc *ctl_softc = control_softc;
4802
4803         mtx_lock(&ctl_softc->ctl_lock);
4804         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4805         mtx_unlock(&ctl_softc->ctl_lock);
4806         wakeup(&ctl_softc->pending_lun_queue);
4807
4808         return (0);
4809 }
4810
4811 int
4812 ctl_enable_lun(struct ctl_be_lun *be_lun)
4813 {
4814         struct ctl_softc *ctl_softc;
4815         struct ctl_port *port, *nport;
4816         struct ctl_lun *lun;
4817         int retval;
4818
4819         ctl_softc = control_softc;
4820
4821         lun = (struct ctl_lun *)be_lun->ctl_lun;
4822
4823         mtx_lock(&ctl_softc->ctl_lock);
4824         mtx_lock(&lun->lun_lock);
4825         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4826                 /*
4827                  * eh?  Why did we get called if the LUN is already
4828                  * enabled?
4829                  */
4830                 mtx_unlock(&lun->lun_lock);
4831                 mtx_unlock(&ctl_softc->ctl_lock);
4832                 return (0);
4833         }
4834         lun->flags &= ~CTL_LUN_DISABLED;
4835         mtx_unlock(&lun->lun_lock);
4836
4837         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4838                 nport = STAILQ_NEXT(port, links);
4839
4840                 /*
4841                  * Drop the lock while we call the FETD's enable routine.
4842                  * This can lead to a callback into CTL (at least in the
4843                  * case of the internal initiator frontend.
4844                  */
4845                 mtx_unlock(&ctl_softc->ctl_lock);
4846                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4847                 mtx_lock(&ctl_softc->ctl_lock);
4848                 if (retval != 0) {
4849                         printf("%s: FETD %s port %d returned error "
4850                                "%d for lun_enable on target %ju lun %jd\n",
4851                                __func__, port->port_name, port->targ_port, retval,
4852                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4853                 }
4854 #if 0
4855                  else {
4856             /* NOTE:  TODO:  why does lun enable affect port status? */
4857                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4858                 }
4859 #endif
4860         }
4861
4862         mtx_unlock(&ctl_softc->ctl_lock);
4863
4864         return (0);
4865 }
4866
4867 int
4868 ctl_disable_lun(struct ctl_be_lun *be_lun)
4869 {
4870         struct ctl_softc *ctl_softc;
4871         struct ctl_port *port;
4872         struct ctl_lun *lun;
4873         int retval;
4874
4875         ctl_softc = control_softc;
4876
4877         lun = (struct ctl_lun *)be_lun->ctl_lun;
4878
4879         mtx_lock(&ctl_softc->ctl_lock);
4880         mtx_lock(&lun->lun_lock);
4881         if (lun->flags & CTL_LUN_DISABLED) {
4882                 mtx_unlock(&lun->lun_lock);
4883                 mtx_unlock(&ctl_softc->ctl_lock);
4884                 return (0);
4885         }
4886         lun->flags |= CTL_LUN_DISABLED;
4887         mtx_unlock(&lun->lun_lock);
4888
4889         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4890                 mtx_unlock(&ctl_softc->ctl_lock);
4891                 /*
4892                  * Drop the lock before we call the frontend's disable
4893                  * routine, to avoid lock order reversals.
4894                  *
4895                  * XXX KDM what happens if the frontend list changes while
4896                  * we're traversing it?  It's unlikely, but should be handled.
4897                  */
4898                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4899                                          lun->lun);
4900                 mtx_lock(&ctl_softc->ctl_lock);
4901                 if (retval != 0) {
4902                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4903                                "%d for lun_disable on target %ju lun %jd\n",
4904                                port->port_name, port->targ_port, retval,
4905                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4906                 }
4907         }
4908
4909         mtx_unlock(&ctl_softc->ctl_lock);
4910
4911         return (0);
4912 }
4913
4914 int
4915 ctl_start_lun(struct ctl_be_lun *be_lun)
4916 {
4917         struct ctl_softc *ctl_softc;
4918         struct ctl_lun *lun;
4919
4920         ctl_softc = control_softc;
4921
4922         lun = (struct ctl_lun *)be_lun->ctl_lun;
4923
4924         mtx_lock(&lun->lun_lock);
4925         lun->flags &= ~CTL_LUN_STOPPED;
4926         mtx_unlock(&lun->lun_lock);
4927
4928         return (0);
4929 }
4930
4931 int
4932 ctl_stop_lun(struct ctl_be_lun *be_lun)
4933 {
4934         struct ctl_softc *ctl_softc;
4935         struct ctl_lun *lun;
4936
4937         ctl_softc = control_softc;
4938
4939         lun = (struct ctl_lun *)be_lun->ctl_lun;
4940
4941         mtx_lock(&lun->lun_lock);
4942         lun->flags |= CTL_LUN_STOPPED;
4943         mtx_unlock(&lun->lun_lock);
4944
4945         return (0);
4946 }
4947
4948 int
4949 ctl_lun_offline(struct ctl_be_lun *be_lun)
4950 {
4951         struct ctl_softc *ctl_softc;
4952         struct ctl_lun *lun;
4953
4954         ctl_softc = control_softc;
4955
4956         lun = (struct ctl_lun *)be_lun->ctl_lun;
4957
4958         mtx_lock(&lun->lun_lock);
4959         lun->flags |= CTL_LUN_OFFLINE;
4960         mtx_unlock(&lun->lun_lock);
4961
4962         return (0);
4963 }
4964
4965 int
4966 ctl_lun_online(struct ctl_be_lun *be_lun)
4967 {
4968         struct ctl_softc *ctl_softc;
4969         struct ctl_lun *lun;
4970
4971         ctl_softc = control_softc;
4972
4973         lun = (struct ctl_lun *)be_lun->ctl_lun;
4974
4975         mtx_lock(&lun->lun_lock);
4976         lun->flags &= ~CTL_LUN_OFFLINE;
4977         mtx_unlock(&lun->lun_lock);
4978
4979         return (0);
4980 }
4981
4982 int
4983 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4984 {
4985         struct ctl_softc *ctl_softc;
4986         struct ctl_lun *lun;
4987
4988         ctl_softc = control_softc;
4989
4990         lun = (struct ctl_lun *)be_lun->ctl_lun;
4991
4992         mtx_lock(&lun->lun_lock);
4993
4994         /*
4995          * The LUN needs to be disabled before it can be marked invalid.
4996          */
4997         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4998                 mtx_unlock(&lun->lun_lock);
4999                 return (-1);
5000         }
5001         /*
5002          * Mark the LUN invalid.
5003          */
5004         lun->flags |= CTL_LUN_INVALID;
5005
5006         /*
5007          * If there is nothing in the OOA queue, go ahead and free the LUN.
5008          * If we have something in the OOA queue, we'll free it when the
5009          * last I/O completes.
5010          */
5011         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5012                 mtx_unlock(&lun->lun_lock);
5013                 mtx_lock(&ctl_softc->ctl_lock);
5014                 ctl_free_lun(lun);
5015                 mtx_unlock(&ctl_softc->ctl_lock);
5016         } else
5017                 mtx_unlock(&lun->lun_lock);
5018
5019         return (0);
5020 }
5021
5022 int
5023 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5024 {
5025         struct ctl_softc *ctl_softc;
5026         struct ctl_lun *lun;
5027
5028         ctl_softc = control_softc;
5029         lun = (struct ctl_lun *)be_lun->ctl_lun;
5030
5031         mtx_lock(&lun->lun_lock);
5032         lun->flags |= CTL_LUN_INOPERABLE;
5033         mtx_unlock(&lun->lun_lock);
5034
5035         return (0);
5036 }
5037
5038 int
5039 ctl_lun_operable(struct ctl_be_lun *be_lun)
5040 {
5041         struct ctl_softc *ctl_softc;
5042         struct ctl_lun *lun;
5043
5044         ctl_softc = control_softc;
5045         lun = (struct ctl_lun *)be_lun->ctl_lun;
5046
5047         mtx_lock(&lun->lun_lock);
5048         lun->flags &= ~CTL_LUN_INOPERABLE;
5049         mtx_unlock(&lun->lun_lock);
5050
5051         return (0);
5052 }
5053
5054 int
5055 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5056                    int lock)
5057 {
5058         struct ctl_softc *softc;
5059         struct ctl_lun *lun;
5060         struct copan_aps_subpage *current_sp;
5061         struct ctl_page_index *page_index;
5062         int i;
5063
5064         softc = control_softc;
5065
5066         mtx_lock(&softc->ctl_lock);
5067
5068         lun = (struct ctl_lun *)be_lun->ctl_lun;
5069         mtx_lock(&lun->lun_lock);
5070
5071         page_index = NULL;
5072         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5073                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5074                      APS_PAGE_CODE)
5075                         continue;
5076
5077                 if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5078                         continue;
5079                 page_index = &lun->mode_pages.index[i];
5080         }
5081
5082         if (page_index == NULL) {
5083                 mtx_unlock(&lun->lun_lock);
5084                 mtx_unlock(&softc->ctl_lock);
5085                 printf("%s: APS subpage not found for lun %ju!\n", __func__,
5086                        (uintmax_t)lun->lun);
5087                 return (1);
5088         }
5089 #if 0
5090         if ((softc->aps_locked_lun != 0)
5091          && (softc->aps_locked_lun != lun->lun)) {
5092                 printf("%s: attempt to lock LUN %llu when %llu is already "
5093                        "locked\n");
5094                 mtx_unlock(&lun->lun_lock);
5095                 mtx_unlock(&softc->ctl_lock);
5096                 return (1);
5097         }
5098 #endif
5099
5100         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5101                 (page_index->page_len * CTL_PAGE_CURRENT));
5102
5103         if (lock != 0) {
5104                 current_sp->lock_active = APS_LOCK_ACTIVE;
5105                 softc->aps_locked_lun = lun->lun;
5106         } else {
5107                 current_sp->lock_active = 0;
5108                 softc->aps_locked_lun = 0;
5109         }
5110
5111
5112         /*
5113          * If we're in HA mode, try to send the lock message to the other
5114          * side.
5115          */
5116         if (ctl_is_single == 0) {
5117                 int isc_retval;
5118                 union ctl_ha_msg lock_msg;
5119
5120                 lock_msg.hdr.nexus = *nexus;
5121                 lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5122                 if (lock != 0)
5123                         lock_msg.aps.lock_flag = 1;
5124                 else
5125                         lock_msg.aps.lock_flag = 0;
5126                 isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5127                                          sizeof(lock_msg), 0);
5128                 if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5129                         printf("%s: APS (lock=%d) error returned from "
5130                                "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5131                         mtx_unlock(&lun->lun_lock);
5132                         mtx_unlock(&softc->ctl_lock);
5133                         return (1);
5134                 }
5135         }
5136
5137         mtx_unlock(&lun->lun_lock);
5138         mtx_unlock(&softc->ctl_lock);
5139
5140         return (0);
5141 }
5142
5143 void
5144 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5145 {
5146         struct ctl_lun *lun;
5147         struct ctl_softc *softc;
5148         int i;
5149
5150         softc = control_softc;
5151
5152         lun = (struct ctl_lun *)be_lun->ctl_lun;
5153
5154         mtx_lock(&lun->lun_lock);
5155
5156         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
5157                 lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5158
5159         mtx_unlock(&lun->lun_lock);
5160 }
5161
5162 /*
5163  * Backend "memory move is complete" callback for requests that never
5164  * make it down to say RAIDCore's configuration code.
5165  */
5166 int
5167 ctl_config_move_done(union ctl_io *io)
5168 {
5169         int retval;
5170
5171         retval = CTL_RETVAL_COMPLETE;
5172
5173
5174         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5175         /*
5176          * XXX KDM this shouldn't happen, but what if it does?
5177          */
5178         if (io->io_hdr.io_type != CTL_IO_SCSI)
5179                 panic("I/O type isn't CTL_IO_SCSI!");
5180
5181         if ((io->io_hdr.port_status == 0)
5182          && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5183          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5184                 io->io_hdr.status = CTL_SUCCESS;
5185         else if ((io->io_hdr.port_status != 0)
5186               && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5187               && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5188                 /*
5189                  * For hardware error sense keys, the sense key
5190                  * specific value is defined to be a retry count,
5191                  * but we use it to pass back an internal FETD
5192                  * error code.  XXX KDM  Hopefully the FETD is only
5193                  * using 16 bits for an error code, since that's
5194                  * all the space we have in the sks field.
5195                  */
5196                 ctl_set_internal_failure(&io->scsiio,
5197                                          /*sks_valid*/ 1,
5198                                          /*retry_count*/
5199                                          io->io_hdr.port_status);
5200                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5201                         free(io->scsiio.kern_data_ptr, M_CTL);
5202                 ctl_done(io);
5203                 goto bailout;
5204         }
5205
5206         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5207          || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5208          || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5209                 /*
5210                  * XXX KDM just assuming a single pointer here, and not a
5211                  * S/G list.  If we start using S/G lists for config data,
5212                  * we'll need to know how to clean them up here as well.
5213                  */
5214                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5215                         free(io->scsiio.kern_data_ptr, M_CTL);
5216                 /* Hopefully the user has already set the status... */
5217                 ctl_done(io);
5218         } else {
5219                 /*
5220                  * XXX KDM now we need to continue data movement.  Some
5221                  * options:
5222                  * - call ctl_scsiio() again?  We don't do this for data
5223                  *   writes, because for those at least we know ahead of
5224                  *   time where the write will go and how long it is.  For
5225                  *   config writes, though, that information is largely
5226                  *   contained within the write itself, thus we need to
5227                  *   parse out the data again.
5228                  *
5229                  * - Call some other function once the data is in?
5230                  */
5231
5232                 /*
5233                  * XXX KDM call ctl_scsiio() again for now, and check flag
5234                  * bits to see whether we're allocated or not.
5235                  */
5236                 retval = ctl_scsiio(&io->scsiio);
5237         }
5238 bailout:
5239         return (retval);
5240 }
5241
5242 /*
5243  * This gets called by a backend driver when it is done with a
5244  * data_submit method.
5245  */
5246 void
5247 ctl_data_submit_done(union ctl_io *io)
5248 {
5249         /*
5250          * If the IO_CONT flag is set, we need to call the supplied
5251          * function to continue processing the I/O, instead of completing
5252          * the I/O just yet.
5253          *
5254          * If there is an error, though, we don't want to keep processing.
5255          * Instead, just send status back to the initiator.
5256          */
5257         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5258             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5259             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5260              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5261                 io->scsiio.io_cont(io);
5262                 return;
5263         }
5264         ctl_done(io);
5265 }
5266
5267 /*
5268  * This gets called by a backend driver when it is done with a
5269  * configuration write.
5270  */
5271 void
5272 ctl_config_write_done(union ctl_io *io)
5273 {
5274         uint8_t *buf;
5275
5276         /*
5277          * If the IO_CONT flag is set, we need to call the supplied
5278          * function to continue processing the I/O, instead of completing
5279          * the I/O just yet.
5280          *
5281          * If there is an error, though, we don't want to keep processing.
5282          * Instead, just send status back to the initiator.
5283          */
5284         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5285          && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5286           || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5287                 io->scsiio.io_cont(io);
5288                 return;
5289         }
5290         /*
5291          * Since a configuration write can be done for commands that actually
5292          * have data allocated, like write buffer, and commands that have
5293          * no data, like start/stop unit, we need to check here.
5294          */
5295         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5296                 buf = io->scsiio.kern_data_ptr;
5297         else
5298                 buf = NULL;
5299         ctl_done(io);
5300         if (buf)
5301                 free(buf, M_CTL);
5302 }
5303
5304 /*
5305  * SCSI release command.
5306  */
5307 int
5308 ctl_scsi_release(struct ctl_scsiio *ctsio)
5309 {
5310         int length, longid, thirdparty_id, resv_id;
5311         struct ctl_softc *ctl_softc;
5312         struct ctl_lun *lun;
5313
5314         length = 0;
5315         resv_id = 0;
5316
5317         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5318
5319         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5320         ctl_softc = control_softc;
5321
5322         switch (ctsio->cdb[0]) {
5323         case RELEASE_10: {
5324                 struct scsi_release_10 *cdb;
5325
5326                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5327
5328                 if (cdb->byte2 & SR10_LONGID)
5329                         longid = 1;
5330                 else
5331                         thirdparty_id = cdb->thirdparty_id;
5332
5333                 resv_id = cdb->resv_id;
5334                 length = scsi_2btoul(cdb->length);
5335                 break;
5336         }
5337         }
5338
5339
5340         /*
5341          * XXX KDM right now, we only support LUN reservation.  We don't
5342          * support 3rd party reservations, or extent reservations, which
5343          * might actually need the parameter list.  If we've gotten this
5344          * far, we've got a LUN reservation.  Anything else got kicked out
5345          * above.  So, according to SPC, ignore the length.
5346          */
5347         length = 0;
5348
5349         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5350          && (length > 0)) {
5351                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5352                 ctsio->kern_data_len = length;
5353                 ctsio->kern_total_len = length;
5354                 ctsio->kern_data_resid = 0;
5355                 ctsio->kern_rel_offset = 0;
5356                 ctsio->kern_sg_entries = 0;
5357                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5358                 ctsio->be_move_done = ctl_config_move_done;
5359                 ctl_datamove((union ctl_io *)ctsio);
5360
5361                 return (CTL_RETVAL_COMPLETE);
5362         }
5363
5364         if (length > 0)
5365                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5366
5367         mtx_lock(&lun->lun_lock);
5368
5369         /*
5370          * According to SPC, it is not an error for an intiator to attempt
5371          * to release a reservation on a LUN that isn't reserved, or that
5372          * is reserved by another initiator.  The reservation can only be
5373          * released, though, by the initiator who made it or by one of
5374          * several reset type events.
5375          */
5376         if (lun->flags & CTL_LUN_RESERVED) {
5377                 if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5378                  && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5379                  && (ctsio->io_hdr.nexus.targ_target.id ==
5380                      lun->rsv_nexus.targ_target.id)) {
5381                         lun->flags &= ~CTL_LUN_RESERVED;
5382                 }
5383         }
5384
5385         mtx_unlock(&lun->lun_lock);
5386
5387         ctsio->scsi_status = SCSI_STATUS_OK;
5388         ctsio->io_hdr.status = CTL_SUCCESS;
5389
5390         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5391                 free(ctsio->kern_data_ptr, M_CTL);
5392                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5393         }
5394
5395         ctl_done((union ctl_io *)ctsio);
5396         return (CTL_RETVAL_COMPLETE);
5397 }
5398
5399 int
5400 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5401 {
5402         int extent, thirdparty, longid;
5403         int resv_id, length;
5404         uint64_t thirdparty_id;
5405         struct ctl_softc *ctl_softc;
5406         struct ctl_lun *lun;
5407
5408         extent = 0;
5409         thirdparty = 0;
5410         longid = 0;
5411         resv_id = 0;
5412         length = 0;
5413         thirdparty_id = 0;
5414
5415         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5416
5417         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5418         ctl_softc = control_softc;
5419
5420         switch (ctsio->cdb[0]) {
5421         case RESERVE_10: {
5422                 struct scsi_reserve_10 *cdb;
5423
5424                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5425
5426                 if (cdb->byte2 & SR10_LONGID)
5427                         longid = 1;
5428                 else
5429                         thirdparty_id = cdb->thirdparty_id;
5430
5431                 resv_id = cdb->resv_id;
5432                 length = scsi_2btoul(cdb->length);
5433                 break;
5434         }
5435         }
5436
5437         /*
5438          * XXX KDM right now, we only support LUN reservation.  We don't
5439          * support 3rd party reservations, or extent reservations, which
5440          * might actually need the parameter list.  If we've gotten this
5441          * far, we've got a LUN reservation.  Anything else got kicked out
5442          * above.  So, according to SPC, ignore the length.
5443          */
5444         length = 0;
5445
5446         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5447          && (length > 0)) {
5448                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5449                 ctsio->kern_data_len = length;
5450                 ctsio->kern_total_len = length;
5451                 ctsio->kern_data_resid = 0;
5452                 ctsio->kern_rel_offset = 0;
5453                 ctsio->kern_sg_entries = 0;
5454                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5455                 ctsio->be_move_done = ctl_config_move_done;
5456                 ctl_datamove((union ctl_io *)ctsio);
5457
5458                 return (CTL_RETVAL_COMPLETE);
5459         }
5460
5461         if (length > 0)
5462                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5463
5464         mtx_lock(&lun->lun_lock);
5465         if (lun->flags & CTL_LUN_RESERVED) {
5466                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5467                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5468                  || (ctsio->io_hdr.nexus.targ_target.id !=
5469                      lun->rsv_nexus.targ_target.id)) {
5470                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5471                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
5472                         goto bailout;
5473                 }
5474         }
5475
5476         lun->flags |= CTL_LUN_RESERVED;
5477         lun->rsv_nexus = ctsio->io_hdr.nexus;
5478
5479         ctsio->scsi_status = SCSI_STATUS_OK;
5480         ctsio->io_hdr.status = CTL_SUCCESS;
5481
5482 bailout:
5483         mtx_unlock(&lun->lun_lock);
5484
5485         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5486                 free(ctsio->kern_data_ptr, M_CTL);
5487                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5488         }
5489
5490         ctl_done((union ctl_io *)ctsio);
5491         return (CTL_RETVAL_COMPLETE);
5492 }
5493
5494 int
5495 ctl_start_stop(struct ctl_scsiio *ctsio)
5496 {
5497         struct scsi_start_stop_unit *cdb;
5498         struct ctl_lun *lun;
5499         struct ctl_softc *ctl_softc;
5500         int retval;
5501
5502         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5503
5504         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5505         ctl_softc = control_softc;
5506         retval = 0;
5507
5508         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5509
5510         /*
5511          * XXX KDM
5512          * We don't support the immediate bit on a stop unit.  In order to
5513          * do that, we would need to code up a way to know that a stop is
5514          * pending, and hold off any new commands until it completes, one
5515          * way or another.  Then we could accept or reject those commands
5516          * depending on its status.  We would almost need to do the reverse
5517          * of what we do below for an immediate start -- return the copy of
5518          * the ctl_io to the FETD with status to send to the host (and to
5519          * free the copy!) and then free the original I/O once the stop
5520          * actually completes.  That way, the OOA queue mechanism can work
5521          * to block commands that shouldn't proceed.  Another alternative
5522          * would be to put the copy in the queue in place of the original,
5523          * and return the original back to the caller.  That could be
5524          * slightly safer..
5525          */
5526         if ((cdb->byte2 & SSS_IMMED)
5527          && ((cdb->how & SSS_START) == 0)) {
5528                 ctl_set_invalid_field(ctsio,
5529                                       /*sks_valid*/ 1,
5530                                       /*command*/ 1,
5531                                       /*field*/ 1,
5532                                       /*bit_valid*/ 1,
5533                                       /*bit*/ 0);
5534                 ctl_done((union ctl_io *)ctsio);
5535                 return (CTL_RETVAL_COMPLETE);
5536         }
5537
5538         if ((lun->flags & CTL_LUN_PR_RESERVED)
5539          && ((cdb->how & SSS_START)==0)) {
5540                 uint32_t residx;
5541
5542                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5543                 if (!lun->per_res[residx].registered
5544                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5545
5546                         ctl_set_reservation_conflict(ctsio);
5547                         ctl_done((union ctl_io *)ctsio);
5548                         return (CTL_RETVAL_COMPLETE);
5549                 }
5550         }
5551
5552         /*
5553          * If there is no backend on this device, we can't start or stop
5554          * it.  In theory we shouldn't get any start/stop commands in the
5555          * first place at this level if the LUN doesn't have a backend.
5556          * That should get stopped by the command decode code.
5557          */
5558         if (lun->backend == NULL) {
5559                 ctl_set_invalid_opcode(ctsio);
5560                 ctl_done((union ctl_io *)ctsio);
5561                 return (CTL_RETVAL_COMPLETE);
5562         }
5563
5564         /*
5565          * XXX KDM Copan-specific offline behavior.
5566          * Figure out a reasonable way to port this?
5567          */
5568 #ifdef NEEDTOPORT
5569         mtx_lock(&lun->lun_lock);
5570
5571         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5572          && (lun->flags & CTL_LUN_OFFLINE)) {
5573                 /*
5574                  * If the LUN is offline, and the on/offline bit isn't set,
5575                  * reject the start or stop.  Otherwise, let it through.
5576                  */
5577                 mtx_unlock(&lun->lun_lock);
5578                 ctl_set_lun_not_ready(ctsio);
5579                 ctl_done((union ctl_io *)ctsio);
5580         } else {
5581                 mtx_unlock(&lun->lun_lock);
5582 #endif /* NEEDTOPORT */
5583                 /*
5584                  * This could be a start or a stop when we're online,
5585                  * or a stop/offline or start/online.  A start or stop when
5586                  * we're offline is covered in the case above.
5587                  */
5588                 /*
5589                  * In the non-immediate case, we send the request to
5590                  * the backend and return status to the user when
5591                  * it is done.
5592                  *
5593                  * In the immediate case, we allocate a new ctl_io
5594                  * to hold a copy of the request, and send that to
5595                  * the backend.  We then set good status on the
5596                  * user's request and return it immediately.
5597                  */
5598                 if (cdb->byte2 & SSS_IMMED) {
5599                         union ctl_io *new_io;
5600
5601                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5602                         if (new_io == NULL) {
5603                                 ctl_set_busy(ctsio);
5604                                 ctl_done((union ctl_io *)ctsio);
5605                         } else {
5606                                 ctl_copy_io((union ctl_io *)ctsio,
5607                                             new_io);
5608                                 retval = lun->backend->config_write(new_io);
5609                                 ctl_set_success(ctsio);
5610                                 ctl_done((union ctl_io *)ctsio);
5611                         }
5612                 } else {
5613                         retval = lun->backend->config_write(
5614                                 (union ctl_io *)ctsio);
5615                 }
5616 #ifdef NEEDTOPORT
5617         }
5618 #endif
5619         return (retval);
5620 }
5621
5622 /*
5623  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5624  * we don't really do anything with the LBA and length fields if the user
5625  * passes them in.  Instead we'll just flush out the cache for the entire
5626  * LUN.
5627  */
5628 int
5629 ctl_sync_cache(struct ctl_scsiio *ctsio)
5630 {
5631         struct ctl_lun *lun;
5632         struct ctl_softc *ctl_softc;
5633         uint64_t starting_lba;
5634         uint32_t block_count;
5635         int retval;
5636
5637         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5638
5639         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5640         ctl_softc = control_softc;
5641         retval = 0;
5642
5643         switch (ctsio->cdb[0]) {
5644         case SYNCHRONIZE_CACHE: {
5645                 struct scsi_sync_cache *cdb;
5646                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5647
5648                 starting_lba = scsi_4btoul(cdb->begin_lba);
5649                 block_count = scsi_2btoul(cdb->lb_count);
5650                 break;
5651         }
5652         case SYNCHRONIZE_CACHE_16: {
5653                 struct scsi_sync_cache_16 *cdb;
5654                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5655
5656                 starting_lba = scsi_8btou64(cdb->begin_lba);
5657                 block_count = scsi_4btoul(cdb->lb_count);
5658                 break;
5659         }
5660         default:
5661                 ctl_set_invalid_opcode(ctsio);
5662                 ctl_done((union ctl_io *)ctsio);
5663                 goto bailout;
5664                 break; /* NOTREACHED */
5665         }
5666
5667         /*
5668          * We check the LBA and length, but don't do anything with them.
5669          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5670          * get flushed.  This check will just help satisfy anyone who wants
5671          * to see an error for an out of range LBA.
5672          */
5673         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5674                 ctl_set_lba_out_of_range(ctsio);
5675                 ctl_done((union ctl_io *)ctsio);
5676                 goto bailout;
5677         }
5678
5679         /*
5680          * If this LUN has no backend, we can't flush the cache anyway.
5681          */
5682         if (lun->backend == NULL) {
5683                 ctl_set_invalid_opcode(ctsio);
5684                 ctl_done((union ctl_io *)ctsio);
5685                 goto bailout;
5686         }
5687
5688         /*
5689          * Check to see whether we're configured to send the SYNCHRONIZE
5690          * CACHE command directly to the back end.
5691          */
5692         mtx_lock(&lun->lun_lock);
5693         if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5694          && (++(lun->sync_count) >= lun->sync_interval)) {
5695                 lun->sync_count = 0;
5696                 mtx_unlock(&lun->lun_lock);
5697                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5698         } else {
5699                 mtx_unlock(&lun->lun_lock);
5700                 ctl_set_success(ctsio);
5701                 ctl_done((union ctl_io *)ctsio);
5702         }
5703
5704 bailout:
5705
5706         return (retval);
5707 }
5708
5709 int
5710 ctl_format(struct ctl_scsiio *ctsio)
5711 {
5712         struct scsi_format *cdb;
5713         struct ctl_lun *lun;
5714         struct ctl_softc *ctl_softc;
5715         int length, defect_list_len;
5716
5717         CTL_DEBUG_PRINT(("ctl_format\n"));
5718
5719         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5720         ctl_softc = control_softc;
5721
5722         cdb = (struct scsi_format *)ctsio->cdb;
5723
5724         length = 0;
5725         if (cdb->byte2 & SF_FMTDATA) {
5726                 if (cdb->byte2 & SF_LONGLIST)
5727                         length = sizeof(struct scsi_format_header_long);
5728                 else
5729                         length = sizeof(struct scsi_format_header_short);
5730         }
5731
5732         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5733          && (length > 0)) {
5734                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5735                 ctsio->kern_data_len = length;
5736                 ctsio->kern_total_len = length;
5737                 ctsio->kern_data_resid = 0;
5738                 ctsio->kern_rel_offset = 0;
5739                 ctsio->kern_sg_entries = 0;
5740                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5741                 ctsio->be_move_done = ctl_config_move_done;
5742                 ctl_datamove((union ctl_io *)ctsio);
5743
5744                 return (CTL_RETVAL_COMPLETE);
5745         }
5746
5747         defect_list_len = 0;
5748
5749         if (cdb->byte2 & SF_FMTDATA) {
5750                 if (cdb->byte2 & SF_LONGLIST) {
5751                         struct scsi_format_header_long *header;
5752
5753                         header = (struct scsi_format_header_long *)
5754                                 ctsio->kern_data_ptr;
5755
5756                         defect_list_len = scsi_4btoul(header->defect_list_len);
5757                         if (defect_list_len != 0) {
5758                                 ctl_set_invalid_field(ctsio,
5759                                                       /*sks_valid*/ 1,
5760                                                       /*command*/ 0,
5761                                                       /*field*/ 2,
5762                                                       /*bit_valid*/ 0,
5763                                                       /*bit*/ 0);
5764                                 goto bailout;
5765                         }
5766                 } else {
5767                         struct scsi_format_header_short *header;
5768
5769                         header = (struct scsi_format_header_short *)
5770                                 ctsio->kern_data_ptr;
5771
5772                         defect_list_len = scsi_2btoul(header->defect_list_len);
5773                         if (defect_list_len != 0) {
5774                                 ctl_set_invalid_field(ctsio,
5775                                                       /*sks_valid*/ 1,
5776                                                       /*command*/ 0,
5777                                                       /*field*/ 2,
5778                                                       /*bit_valid*/ 0,
5779                                                       /*bit*/ 0);
5780                                 goto bailout;
5781                         }
5782                 }
5783         }
5784
5785         /*
5786          * The format command will clear out the "Medium format corrupted"
5787          * status if set by the configuration code.  That status is really
5788          * just a way to notify the host that we have lost the media, and
5789          * get them to issue a command that will basically make them think
5790          * they're blowing away the media.
5791          */
5792         mtx_lock(&lun->lun_lock);
5793         lun->flags &= ~CTL_LUN_INOPERABLE;
5794         mtx_unlock(&lun->lun_lock);
5795
5796         ctsio->scsi_status = SCSI_STATUS_OK;
5797         ctsio->io_hdr.status = CTL_SUCCESS;
5798 bailout:
5799
5800         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5801                 free(ctsio->kern_data_ptr, M_CTL);
5802                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5803         }
5804
5805         ctl_done((union ctl_io *)ctsio);
5806         return (CTL_RETVAL_COMPLETE);
5807 }
5808
5809 int
5810 ctl_read_buffer(struct ctl_scsiio *ctsio)
5811 {
5812         struct scsi_read_buffer *cdb;
5813         struct ctl_lun *lun;
5814         int buffer_offset, len;
5815         static uint8_t descr[4];
5816         static uint8_t echo_descr[4] = { 0 };
5817
5818         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5819
5820         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5821         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5822
5823         if (lun->flags & CTL_LUN_PR_RESERVED) {
5824                 uint32_t residx;
5825
5826                 /*
5827                  * XXX KDM need a lock here.
5828                  */
5829                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5830                 if ((lun->res_type == SPR_TYPE_EX_AC
5831                   && residx != lun->pr_res_idx)
5832                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
5833                    || lun->res_type == SPR_TYPE_EX_AC_AR)
5834                   && !lun->per_res[residx].registered)) {
5835                         ctl_set_reservation_conflict(ctsio);
5836                         ctl_done((union ctl_io *)ctsio);
5837                         return (CTL_RETVAL_COMPLETE);
5838                 }
5839         }
5840
5841         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5842             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5843             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5844                 ctl_set_invalid_field(ctsio,
5845                                       /*sks_valid*/ 1,
5846                                       /*command*/ 1,
5847                                       /*field*/ 1,
5848                                       /*bit_valid*/ 1,
5849                                       /*bit*/ 4);
5850                 ctl_done((union ctl_io *)ctsio);
5851                 return (CTL_RETVAL_COMPLETE);
5852         }
5853
5854         len = scsi_3btoul(cdb->length);
5855         buffer_offset = scsi_3btoul(cdb->offset);
5856
5857         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5858                 ctl_set_invalid_field(ctsio,
5859                                       /*sks_valid*/ 1,
5860                                       /*command*/ 1,
5861                                       /*field*/ 6,
5862                                       /*bit_valid*/ 0,
5863                                       /*bit*/ 0);
5864                 ctl_done((union ctl_io *)ctsio);
5865                 return (CTL_RETVAL_COMPLETE);
5866         }
5867
5868         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5869                 descr[0] = 0;
5870                 scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5871                 ctsio->kern_data_ptr = descr;
5872                 len = min(len, sizeof(descr));
5873         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5874                 ctsio->kern_data_ptr = echo_descr;
5875                 len = min(len, sizeof(echo_descr));
5876         } else
5877                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5878         ctsio->kern_data_len = len;
5879         ctsio->kern_total_len = len;
5880         ctsio->kern_data_resid = 0;
5881         ctsio->kern_rel_offset = 0;
5882         ctsio->kern_sg_entries = 0;
5883         ctsio->be_move_done = ctl_config_move_done;
5884         ctl_datamove((union ctl_io *)ctsio);
5885
5886         return (CTL_RETVAL_COMPLETE);
5887 }
5888
5889 int
5890 ctl_write_buffer(struct ctl_scsiio *ctsio)
5891 {
5892         struct scsi_write_buffer *cdb;
5893         struct ctl_lun *lun;
5894         int buffer_offset, len;
5895
5896         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5897
5898         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5899         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5900
5901         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5902                 ctl_set_invalid_field(ctsio,
5903                                       /*sks_valid*/ 1,
5904                                       /*command*/ 1,
5905                                       /*field*/ 1,
5906                                       /*bit_valid*/ 1,
5907                                       /*bit*/ 4);
5908                 ctl_done((union ctl_io *)ctsio);
5909                 return (CTL_RETVAL_COMPLETE);
5910         }
5911
5912         len = scsi_3btoul(cdb->length);
5913         buffer_offset = scsi_3btoul(cdb->offset);
5914
5915         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5916                 ctl_set_invalid_field(ctsio,
5917                                       /*sks_valid*/ 1,
5918                                       /*command*/ 1,
5919                                       /*field*/ 6,
5920                                       /*bit_valid*/ 0,
5921                                       /*bit*/ 0);
5922                 ctl_done((union ctl_io *)ctsio);
5923                 return (CTL_RETVAL_COMPLETE);
5924         }
5925
5926         /*
5927          * If we've got a kernel request that hasn't been malloced yet,
5928          * malloc it and tell the caller the data buffer is here.
5929          */
5930         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5931                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5932                 ctsio->kern_data_len = len;
5933                 ctsio->kern_total_len = len;
5934                 ctsio->kern_data_resid = 0;
5935                 ctsio->kern_rel_offset = 0;
5936                 ctsio->kern_sg_entries = 0;
5937                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5938                 ctsio->be_move_done = ctl_config_move_done;
5939                 ctl_datamove((union ctl_io *)ctsio);
5940
5941                 return (CTL_RETVAL_COMPLETE);
5942         }
5943
5944         ctl_done((union ctl_io *)ctsio);
5945
5946         return (CTL_RETVAL_COMPLETE);
5947 }
5948
5949 int
5950 ctl_write_same(struct ctl_scsiio *ctsio)
5951 {
5952         struct ctl_lun *lun;
5953         struct ctl_lba_len_flags *lbalen;
5954         uint64_t lba;
5955         uint32_t num_blocks;
5956         int len, retval;
5957         uint8_t byte2;
5958
5959         retval = CTL_RETVAL_COMPLETE;
5960
5961         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5962
5963         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5964
5965         switch (ctsio->cdb[0]) {
5966         case WRITE_SAME_10: {
5967                 struct scsi_write_same_10 *cdb;
5968
5969                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5970
5971                 lba = scsi_4btoul(cdb->addr);
5972                 num_blocks = scsi_2btoul(cdb->length);
5973                 byte2 = cdb->byte2;
5974                 break;
5975         }
5976         case WRITE_SAME_16: {
5977                 struct scsi_write_same_16 *cdb;
5978
5979                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5980
5981                 lba = scsi_8btou64(cdb->addr);
5982                 num_blocks = scsi_4btoul(cdb->length);
5983                 byte2 = cdb->byte2;
5984                 break;
5985         }
5986         default:
5987                 /*
5988                  * We got a command we don't support.  This shouldn't
5989                  * happen, commands should be filtered out above us.
5990                  */
5991                 ctl_set_invalid_opcode(ctsio);
5992                 ctl_done((union ctl_io *)ctsio);
5993
5994                 return (CTL_RETVAL_COMPLETE);
5995                 break; /* NOTREACHED */
5996         }
5997
5998         /* NDOB flag can be used only together with UNMAP */
5999         if ((byte2 & (SWS_NDOB | SWS_UNMAP)) == SWS_NDOB) {
6000                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
6001                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
6002                 ctl_done((union ctl_io *)ctsio);
6003                 return (CTL_RETVAL_COMPLETE);
6004         }
6005
6006         /*
6007          * The first check is to make sure we're in bounds, the second
6008          * check is to catch wrap-around problems.  If the lba + num blocks
6009          * is less than the lba, then we've wrapped around and the block
6010          * range is invalid anyway.
6011          */
6012         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6013          || ((lba + num_blocks) < lba)) {
6014                 ctl_set_lba_out_of_range(ctsio);
6015                 ctl_done((union ctl_io *)ctsio);
6016                 return (CTL_RETVAL_COMPLETE);
6017         }
6018
6019         /* Zero number of blocks means "to the last logical block" */
6020         if (num_blocks == 0) {
6021                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6022                         ctl_set_invalid_field(ctsio,
6023                                               /*sks_valid*/ 0,
6024                                               /*command*/ 1,
6025                                               /*field*/ 0,
6026                                               /*bit_valid*/ 0,
6027                                               /*bit*/ 0);
6028                         ctl_done((union ctl_io *)ctsio);
6029                         return (CTL_RETVAL_COMPLETE);
6030                 }
6031                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
6032         }
6033
6034         len = lun->be_lun->blocksize;
6035
6036         /*
6037          * If we've got a kernel request that hasn't been malloced yet,
6038          * malloc it and tell the caller the data buffer is here.
6039          */
6040         if ((byte2 & SWS_NDOB) == 0 &&
6041             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6042                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6043                 ctsio->kern_data_len = len;
6044                 ctsio->kern_total_len = len;
6045                 ctsio->kern_data_resid = 0;
6046                 ctsio->kern_rel_offset = 0;
6047                 ctsio->kern_sg_entries = 0;
6048                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6049                 ctsio->be_move_done = ctl_config_move_done;
6050                 ctl_datamove((union ctl_io *)ctsio);
6051
6052                 return (CTL_RETVAL_COMPLETE);
6053         }
6054
6055         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6056         lbalen->lba = lba;
6057         lbalen->len = num_blocks;
6058         lbalen->flags = byte2;
6059         retval = lun->backend->config_write((union ctl_io *)ctsio);
6060
6061         return (retval);
6062 }
6063
6064 int
6065 ctl_unmap(struct ctl_scsiio *ctsio)
6066 {
6067         struct ctl_lun *lun;
6068         struct scsi_unmap *cdb;
6069         struct ctl_ptr_len_flags *ptrlen;
6070         struct scsi_unmap_header *hdr;
6071         struct scsi_unmap_desc *buf, *end, *endnz, *range;
6072         uint64_t lba;
6073         uint32_t num_blocks;
6074         int len, retval;
6075         uint8_t byte2;
6076
6077         retval = CTL_RETVAL_COMPLETE;
6078
6079         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6080
6081         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6082         cdb = (struct scsi_unmap *)ctsio->cdb;
6083
6084         len = scsi_2btoul(cdb->length);
6085         byte2 = cdb->byte2;
6086
6087         /*
6088          * If we've got a kernel request that hasn't been malloced yet,
6089          * malloc it and tell the caller the data buffer is here.
6090          */
6091         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6092                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6093                 ctsio->kern_data_len = len;
6094                 ctsio->kern_total_len = len;
6095                 ctsio->kern_data_resid = 0;
6096                 ctsio->kern_rel_offset = 0;
6097                 ctsio->kern_sg_entries = 0;
6098                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6099                 ctsio->be_move_done = ctl_config_move_done;
6100                 ctl_datamove((union ctl_io *)ctsio);
6101
6102                 return (CTL_RETVAL_COMPLETE);
6103         }
6104
6105         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6106         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6107         if (len < sizeof (*hdr) ||
6108             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6109             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6110             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6111                 ctl_set_invalid_field(ctsio,
6112                                       /*sks_valid*/ 0,
6113                                       /*command*/ 0,
6114                                       /*field*/ 0,
6115                                       /*bit_valid*/ 0,
6116                                       /*bit*/ 0);
6117                 ctl_done((union ctl_io *)ctsio);
6118                 return (CTL_RETVAL_COMPLETE);
6119         }
6120         len = scsi_2btoul(hdr->desc_length);
6121         buf = (struct scsi_unmap_desc *)(hdr + 1);
6122         end = buf + len / sizeof(*buf);
6123
6124         endnz = buf;
6125         for (range = buf; range < end; range++) {
6126                 lba = scsi_8btou64(range->lba);
6127                 num_blocks = scsi_4btoul(range->length);
6128                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6129                  || ((lba + num_blocks) < lba)) {
6130                         ctl_set_lba_out_of_range(ctsio);
6131                         ctl_done((union ctl_io *)ctsio);
6132                         return (CTL_RETVAL_COMPLETE);
6133                 }
6134                 if (num_blocks != 0)
6135                         endnz = range + 1;
6136         }
6137
6138         /*
6139          * Block backend can not handle zero last range.
6140          * Filter it out and return if there is nothing left.
6141          */
6142         len = (uint8_t *)endnz - (uint8_t *)buf;
6143         if (len == 0) {
6144                 ctl_set_success(ctsio);
6145                 ctl_done((union ctl_io *)ctsio);
6146                 return (CTL_RETVAL_COMPLETE);
6147         }
6148
6149         mtx_lock(&lun->lun_lock);
6150         ptrlen = (struct ctl_ptr_len_flags *)
6151             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6152         ptrlen->ptr = (void *)buf;
6153         ptrlen->len = len;
6154         ptrlen->flags = byte2;
6155         ctl_check_blocked(lun);
6156         mtx_unlock(&lun->lun_lock);
6157
6158         retval = lun->backend->config_write((union ctl_io *)ctsio);
6159         return (retval);
6160 }
6161
6162 /*
6163  * Note that this function currently doesn't actually do anything inside
6164  * CTL to enforce things if the DQue bit is turned on.
6165  *
6166  * Also note that this function can't be used in the default case, because
6167  * the DQue bit isn't set in the changeable mask for the control mode page
6168  * anyway.  This is just here as an example for how to implement a page
6169  * handler, and a placeholder in case we want to allow the user to turn
6170  * tagged queueing on and off.
6171  *
6172  * The D_SENSE bit handling is functional, however, and will turn
6173  * descriptor sense on and off for a given LUN.
6174  */
6175 int
6176 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6177                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6178 {
6179         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6180         struct ctl_lun *lun;
6181         struct ctl_softc *softc;
6182         int set_ua;
6183         uint32_t initidx;
6184
6185         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6186         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6187         set_ua = 0;
6188
6189         user_cp = (struct scsi_control_page *)page_ptr;
6190         current_cp = (struct scsi_control_page *)
6191                 (page_index->page_data + (page_index->page_len *
6192                 CTL_PAGE_CURRENT));
6193         saved_cp = (struct scsi_control_page *)
6194                 (page_index->page_data + (page_index->page_len *
6195                 CTL_PAGE_SAVED));
6196
6197         softc = control_softc;
6198
6199         mtx_lock(&lun->lun_lock);
6200         if (((current_cp->rlec & SCP_DSENSE) == 0)
6201          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6202                 /*
6203                  * Descriptor sense is currently turned off and the user
6204                  * wants to turn it on.
6205                  */
6206                 current_cp->rlec |= SCP_DSENSE;
6207                 saved_cp->rlec |= SCP_DSENSE;
6208                 lun->flags |= CTL_LUN_SENSE_DESC;
6209                 set_ua = 1;
6210         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6211                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6212                 /*
6213                  * Descriptor sense is currently turned on, and the user
6214                  * wants to turn it off.
6215                  */
6216                 current_cp->rlec &= ~SCP_DSENSE;
6217                 saved_cp->rlec &= ~SCP_DSENSE;
6218                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6219                 set_ua = 1;
6220         }
6221         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6222             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6223                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6224                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6225                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6226                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6227                 set_ua = 1;
6228         }
6229         if (set_ua != 0) {
6230                 int i;
6231                 /*
6232                  * Let other initiators know that the mode
6233                  * parameters for this LUN have changed.
6234                  */
6235                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6236                         if (i == initidx)
6237                                 continue;
6238
6239                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6240                 }
6241         }
6242         mtx_unlock(&lun->lun_lock);
6243
6244         return (0);
6245 }
6246
6247 int
6248 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6249                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6250 {
6251         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6252         struct ctl_lun *lun;
6253         int set_ua;
6254         uint32_t initidx;
6255
6256         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6257         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6258         set_ua = 0;
6259
6260         user_cp = (struct scsi_caching_page *)page_ptr;
6261         current_cp = (struct scsi_caching_page *)
6262                 (page_index->page_data + (page_index->page_len *
6263                 CTL_PAGE_CURRENT));
6264         saved_cp = (struct scsi_caching_page *)
6265                 (page_index->page_data + (page_index->page_len *
6266                 CTL_PAGE_SAVED));
6267
6268         mtx_lock(&lun->lun_lock);
6269         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6270             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6271                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6272                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6273                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6274                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6275                 set_ua = 1;
6276         }
6277         if (set_ua != 0) {
6278                 int i;
6279                 /*
6280                  * Let other initiators know that the mode
6281                  * parameters for this LUN have changed.
6282                  */
6283                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6284                         if (i == initidx)
6285                                 continue;
6286
6287                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6288                 }
6289         }
6290         mtx_unlock(&lun->lun_lock);
6291
6292         return (0);
6293 }
6294
6295 int
6296 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6297                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6298 {
6299         return (0);
6300 }
6301
6302 int
6303 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6304                            struct ctl_page_index *page_index, int pc)
6305 {
6306         struct copan_power_subpage *page;
6307
6308         page = (struct copan_power_subpage *)page_index->page_data +
6309                 (page_index->page_len * pc);
6310
6311         switch (pc) {
6312         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6313                 /*
6314                  * We don't update the changable bits for this page.
6315                  */
6316                 break;
6317         case SMS_PAGE_CTRL_CURRENT >> 6:
6318         case SMS_PAGE_CTRL_DEFAULT >> 6:
6319         case SMS_PAGE_CTRL_SAVED >> 6:
6320 #ifdef NEEDTOPORT
6321                 ctl_update_power_subpage(page);
6322 #endif
6323                 break;
6324         default:
6325 #ifdef NEEDTOPORT
6326                 EPRINT(0, "Invalid PC %d!!", pc);
6327 #endif
6328                 break;
6329         }
6330         return (0);
6331 }
6332
6333
6334 int
6335 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6336                    struct ctl_page_index *page_index, uint8_t *page_ptr)
6337 {
6338         struct copan_aps_subpage *user_sp;
6339         struct copan_aps_subpage *current_sp;
6340         union ctl_modepage_info *modepage_info;
6341         struct ctl_softc *softc;
6342         struct ctl_lun *lun;
6343         int retval;
6344
6345         retval = CTL_RETVAL_COMPLETE;
6346         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6347                      (page_index->page_len * CTL_PAGE_CURRENT));
6348         softc = control_softc;
6349         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6350
6351         user_sp = (struct copan_aps_subpage *)page_ptr;
6352
6353         modepage_info = (union ctl_modepage_info *)
6354                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6355
6356         modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6357         modepage_info->header.subpage = page_index->subpage;
6358         modepage_info->aps.lock_active = user_sp->lock_active;
6359
6360         mtx_lock(&softc->ctl_lock);
6361
6362         /*
6363          * If there is a request to lock the LUN and another LUN is locked
6364          * this is an error. If the requested LUN is already locked ignore
6365          * the request. If no LUN is locked attempt to lock it.
6366          * if there is a request to unlock the LUN and the LUN is currently
6367          * locked attempt to unlock it. Otherwise ignore the request. i.e.
6368          * if another LUN is locked or no LUN is locked.
6369          */
6370         if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6371                 if (softc->aps_locked_lun == lun->lun) {
6372                         /*
6373                          * This LUN is already locked, so we're done.
6374                          */
6375                         retval = CTL_RETVAL_COMPLETE;
6376                 } else if (softc->aps_locked_lun == 0) {
6377                         /*
6378                          * No one has the lock, pass the request to the
6379                          * backend.
6380                          */
6381                         retval = lun->backend->config_write(
6382                                 (union ctl_io *)ctsio);
6383                 } else {
6384                         /*
6385                          * Someone else has the lock, throw out the request.
6386                          */
6387                         ctl_set_already_locked(ctsio);
6388                         free(ctsio->kern_data_ptr, M_CTL);
6389                         ctl_done((union ctl_io *)ctsio);
6390
6391                         /*
6392                          * Set the return value so that ctl_do_mode_select()
6393                          * won't try to complete the command.  We already
6394                          * completed it here.
6395                          */
6396                         retval = CTL_RETVAL_ERROR;
6397                 }
6398         } else if (softc->aps_locked_lun == lun->lun) {
6399                 /*
6400                  * This LUN is locked, so pass the unlock request to the
6401                  * backend.
6402                  */
6403                 retval = lun->backend->config_write((union ctl_io *)ctsio);
6404         }
6405         mtx_unlock(&softc->ctl_lock);
6406
6407         return (retval);
6408 }
6409
6410 int
6411 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6412                                 struct ctl_page_index *page_index,
6413                                 uint8_t *page_ptr)
6414 {
6415         uint8_t *c;
6416         int i;
6417
6418         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6419         ctl_time_io_secs =
6420                 (c[0] << 8) |
6421                 (c[1] << 0) |
6422                 0;
6423         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6424         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6425         printf("page data:");
6426         for (i=0; i<8; i++)
6427                 printf(" %.2x",page_ptr[i]);
6428         printf("\n");
6429         return (0);
6430 }
6431
6432 int
6433 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6434                                struct ctl_page_index *page_index,
6435                                int pc)
6436 {
6437         struct copan_debugconf_subpage *page;
6438
6439         page = (struct copan_debugconf_subpage *)page_index->page_data +
6440                 (page_index->page_len * pc);
6441
6442         switch (pc) {
6443         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6444         case SMS_PAGE_CTRL_DEFAULT >> 6:
6445         case SMS_PAGE_CTRL_SAVED >> 6:
6446                 /*
6447                  * We don't update the changable or default bits for this page.
6448                  */
6449                 break;
6450         case SMS_PAGE_CTRL_CURRENT >> 6:
6451                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6452                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6453                 break;
6454         default:
6455 #ifdef NEEDTOPORT
6456                 EPRINT(0, "Invalid PC %d!!", pc);
6457 #endif /* NEEDTOPORT */
6458                 break;
6459         }
6460         return (0);
6461 }
6462
6463
6464 static int
6465 ctl_do_mode_select(union ctl_io *io)
6466 {
6467         struct scsi_mode_page_header *page_header;
6468         struct ctl_page_index *page_index;
6469         struct ctl_scsiio *ctsio;
6470         int control_dev, page_len;
6471         int page_len_offset, page_len_size;
6472         union ctl_modepage_info *modepage_info;
6473         struct ctl_lun *lun;
6474         int *len_left, *len_used;
6475         int retval, i;
6476
6477         ctsio = &io->scsiio;
6478         page_index = NULL;
6479         page_len = 0;
6480         retval = CTL_RETVAL_COMPLETE;
6481
6482         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6483
6484         if (lun->be_lun->lun_type != T_DIRECT)
6485                 control_dev = 1;
6486         else
6487                 control_dev = 0;
6488
6489         modepage_info = (union ctl_modepage_info *)
6490                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6491         len_left = &modepage_info->header.len_left;
6492         len_used = &modepage_info->header.len_used;
6493
6494 do_next_page:
6495
6496         page_header = (struct scsi_mode_page_header *)
6497                 (ctsio->kern_data_ptr + *len_used);
6498
6499         if (*len_left == 0) {
6500                 free(ctsio->kern_data_ptr, M_CTL);
6501                 ctl_set_success(ctsio);
6502                 ctl_done((union ctl_io *)ctsio);
6503                 return (CTL_RETVAL_COMPLETE);
6504         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6505
6506                 free(ctsio->kern_data_ptr, M_CTL);
6507                 ctl_set_param_len_error(ctsio);
6508                 ctl_done((union ctl_io *)ctsio);
6509                 return (CTL_RETVAL_COMPLETE);
6510
6511         } else if ((page_header->page_code & SMPH_SPF)
6512                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6513
6514                 free(ctsio->kern_data_ptr, M_CTL);
6515                 ctl_set_param_len_error(ctsio);
6516                 ctl_done((union ctl_io *)ctsio);
6517                 return (CTL_RETVAL_COMPLETE);
6518         }
6519
6520
6521         /*
6522          * XXX KDM should we do something with the block descriptor?
6523          */
6524         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6525
6526                 if ((control_dev != 0)
6527                  && (lun->mode_pages.index[i].page_flags &
6528                      CTL_PAGE_FLAG_DISK_ONLY))
6529                         continue;
6530
6531                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6532                     (page_header->page_code & SMPH_PC_MASK))
6533                         continue;
6534
6535                 /*
6536                  * If neither page has a subpage code, then we've got a
6537                  * match.
6538                  */
6539                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6540                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6541                         page_index = &lun->mode_pages.index[i];
6542                         page_len = page_header->page_length;
6543                         break;
6544                 }
6545
6546                 /*
6547                  * If both pages have subpages, then the subpage numbers
6548                  * have to match.
6549                  */
6550                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6551                   && (page_header->page_code & SMPH_SPF)) {
6552                         struct scsi_mode_page_header_sp *sph;
6553
6554                         sph = (struct scsi_mode_page_header_sp *)page_header;
6555
6556                         if (lun->mode_pages.index[i].subpage ==
6557                             sph->subpage) {
6558                                 page_index = &lun->mode_pages.index[i];
6559                                 page_len = scsi_2btoul(sph->page_length);
6560                                 break;
6561                         }
6562                 }
6563         }
6564
6565         /*
6566          * If we couldn't find the page, or if we don't have a mode select
6567          * handler for it, send back an error to the user.
6568          */
6569         if ((page_index == NULL)
6570          || (page_index->select_handler == NULL)) {
6571                 ctl_set_invalid_field(ctsio,
6572                                       /*sks_valid*/ 1,
6573                                       /*command*/ 0,
6574                                       /*field*/ *len_used,
6575                                       /*bit_valid*/ 0,
6576                                       /*bit*/ 0);
6577                 free(ctsio->kern_data_ptr, M_CTL);
6578                 ctl_done((union ctl_io *)ctsio);
6579                 return (CTL_RETVAL_COMPLETE);
6580         }
6581
6582         if (page_index->page_code & SMPH_SPF) {
6583                 page_len_offset = 2;
6584                 page_len_size = 2;
6585         } else {
6586                 page_len_size = 1;
6587                 page_len_offset = 1;
6588         }
6589
6590         /*
6591          * If the length the initiator gives us isn't the one we specify in
6592          * the mode page header, or if they didn't specify enough data in
6593          * the CDB to avoid truncating this page, kick out the request.
6594          */
6595         if ((page_len != (page_index->page_len - page_len_offset -
6596                           page_len_size))
6597          || (*len_left < page_index->page_len)) {
6598
6599
6600                 ctl_set_invalid_field(ctsio,
6601                                       /*sks_valid*/ 1,
6602                                       /*command*/ 0,
6603                                       /*field*/ *len_used + page_len_offset,
6604                                       /*bit_valid*/ 0,
6605                                       /*bit*/ 0);
6606                 free(ctsio->kern_data_ptr, M_CTL);
6607                 ctl_done((union ctl_io *)ctsio);
6608                 return (CTL_RETVAL_COMPLETE);
6609         }
6610
6611         /*
6612          * Run through the mode page, checking to make sure that the bits
6613          * the user changed are actually legal for him to change.
6614          */
6615         for (i = 0; i < page_index->page_len; i++) {
6616                 uint8_t *user_byte, *change_mask, *current_byte;
6617                 int bad_bit;
6618                 int j;
6619
6620                 user_byte = (uint8_t *)page_header + i;
6621                 change_mask = page_index->page_data +
6622                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6623                 current_byte = page_index->page_data +
6624                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6625
6626                 /*
6627                  * Check to see whether the user set any bits in this byte
6628                  * that he is not allowed to set.
6629                  */
6630                 if ((*user_byte & ~(*change_mask)) ==
6631                     (*current_byte & ~(*change_mask)))
6632                         continue;
6633
6634                 /*
6635                  * Go through bit by bit to determine which one is illegal.
6636                  */
6637                 bad_bit = 0;
6638                 for (j = 7; j >= 0; j--) {
6639                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6640                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6641                                 bad_bit = i;
6642                                 break;
6643                         }
6644                 }
6645                 ctl_set_invalid_field(ctsio,
6646                                       /*sks_valid*/ 1,
6647                                       /*command*/ 0,
6648                                       /*field*/ *len_used + i,
6649                                       /*bit_valid*/ 1,
6650                                       /*bit*/ bad_bit);
6651                 free(ctsio->kern_data_ptr, M_CTL);
6652                 ctl_done((union ctl_io *)ctsio);
6653                 return (CTL_RETVAL_COMPLETE);
6654         }
6655
6656         /*
6657          * Decrement these before we call the page handler, since we may
6658          * end up getting called back one way or another before the handler
6659          * returns to this context.
6660          */
6661         *len_left -= page_index->page_len;
6662         *len_used += page_index->page_len;
6663
6664         retval = page_index->select_handler(ctsio, page_index,
6665                                             (uint8_t *)page_header);
6666
6667         /*
6668          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6669          * wait until this queued command completes to finish processing
6670          * the mode page.  If it returns anything other than
6671          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6672          * already set the sense information, freed the data pointer, and
6673          * completed the io for us.
6674          */
6675         if (retval != CTL_RETVAL_COMPLETE)
6676                 goto bailout_no_done;
6677
6678         /*
6679          * If the initiator sent us more than one page, parse the next one.
6680          */
6681         if (*len_left > 0)
6682                 goto do_next_page;
6683
6684         ctl_set_success(ctsio);
6685         free(ctsio->kern_data_ptr, M_CTL);
6686         ctl_done((union ctl_io *)ctsio);
6687
6688 bailout_no_done:
6689
6690         return (CTL_RETVAL_COMPLETE);
6691
6692 }
6693
6694 int
6695 ctl_mode_select(struct ctl_scsiio *ctsio)
6696 {
6697         int param_len, pf, sp;
6698         int header_size, bd_len;
6699         int len_left, len_used;
6700         struct ctl_page_index *page_index;
6701         struct ctl_lun *lun;
6702         int control_dev, page_len;
6703         union ctl_modepage_info *modepage_info;
6704         int retval;
6705
6706         pf = 0;
6707         sp = 0;
6708         page_len = 0;
6709         len_used = 0;
6710         len_left = 0;
6711         retval = 0;
6712         bd_len = 0;
6713         page_index = NULL;
6714
6715         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6716
6717         if (lun->be_lun->lun_type != T_DIRECT)
6718                 control_dev = 1;
6719         else
6720                 control_dev = 0;
6721
6722         switch (ctsio->cdb[0]) {
6723         case MODE_SELECT_6: {
6724                 struct scsi_mode_select_6 *cdb;
6725
6726                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6727
6728                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6729                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6730
6731                 param_len = cdb->length;
6732                 header_size = sizeof(struct scsi_mode_header_6);
6733                 break;
6734         }
6735         case MODE_SELECT_10: {
6736                 struct scsi_mode_select_10 *cdb;
6737
6738                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6739
6740                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6741                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6742
6743                 param_len = scsi_2btoul(cdb->length);
6744                 header_size = sizeof(struct scsi_mode_header_10);
6745                 break;
6746         }
6747         default:
6748                 ctl_set_invalid_opcode(ctsio);
6749                 ctl_done((union ctl_io *)ctsio);
6750                 return (CTL_RETVAL_COMPLETE);
6751                 break; /* NOTREACHED */
6752         }
6753
6754         /*
6755          * From SPC-3:
6756          * "A parameter list length of zero indicates that the Data-Out Buffer
6757          * shall be empty. This condition shall not be considered as an error."
6758          */
6759         if (param_len == 0) {
6760                 ctl_set_success(ctsio);
6761                 ctl_done((union ctl_io *)ctsio);
6762                 return (CTL_RETVAL_COMPLETE);
6763         }
6764
6765         /*
6766          * Since we'll hit this the first time through, prior to
6767          * allocation, we don't need to free a data buffer here.
6768          */
6769         if (param_len < header_size) {
6770                 ctl_set_param_len_error(ctsio);
6771                 ctl_done((union ctl_io *)ctsio);
6772                 return (CTL_RETVAL_COMPLETE);
6773         }
6774
6775         /*
6776          * Allocate the data buffer and grab the user's data.  In theory,
6777          * we shouldn't have to sanity check the parameter list length here
6778          * because the maximum size is 64K.  We should be able to malloc
6779          * that much without too many problems.
6780          */
6781         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6782                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6783                 ctsio->kern_data_len = param_len;
6784                 ctsio->kern_total_len = param_len;
6785                 ctsio->kern_data_resid = 0;
6786                 ctsio->kern_rel_offset = 0;
6787                 ctsio->kern_sg_entries = 0;
6788                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6789                 ctsio->be_move_done = ctl_config_move_done;
6790                 ctl_datamove((union ctl_io *)ctsio);
6791
6792                 return (CTL_RETVAL_COMPLETE);
6793         }
6794
6795         switch (ctsio->cdb[0]) {
6796         case MODE_SELECT_6: {
6797                 struct scsi_mode_header_6 *mh6;
6798
6799                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6800                 bd_len = mh6->blk_desc_len;
6801                 break;
6802         }
6803         case MODE_SELECT_10: {
6804                 struct scsi_mode_header_10 *mh10;
6805
6806                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6807                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6808                 break;
6809         }
6810         default:
6811                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6812                 break;
6813         }
6814
6815         if (param_len < (header_size + bd_len)) {
6816                 free(ctsio->kern_data_ptr, M_CTL);
6817                 ctl_set_param_len_error(ctsio);
6818                 ctl_done((union ctl_io *)ctsio);
6819                 return (CTL_RETVAL_COMPLETE);
6820         }
6821
6822         /*
6823          * Set the IO_CONT flag, so that if this I/O gets passed to
6824          * ctl_config_write_done(), it'll get passed back to
6825          * ctl_do_mode_select() for further processing, or completion if
6826          * we're all done.
6827          */
6828         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6829         ctsio->io_cont = ctl_do_mode_select;
6830
6831         modepage_info = (union ctl_modepage_info *)
6832                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6833
6834         memset(modepage_info, 0, sizeof(*modepage_info));
6835
6836         len_left = param_len - header_size - bd_len;
6837         len_used = header_size + bd_len;
6838
6839         modepage_info->header.len_left = len_left;
6840         modepage_info->header.len_used = len_used;
6841
6842         return (ctl_do_mode_select((union ctl_io *)ctsio));
6843 }
6844
6845 int
6846 ctl_mode_sense(struct ctl_scsiio *ctsio)
6847 {
6848         struct ctl_lun *lun;
6849         int pc, page_code, dbd, llba, subpage;
6850         int alloc_len, page_len, header_len, total_len;
6851         struct scsi_mode_block_descr *block_desc;
6852         struct ctl_page_index *page_index;
6853         int control_dev;
6854
6855         dbd = 0;
6856         llba = 0;
6857         block_desc = NULL;
6858         page_index = NULL;
6859
6860         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6861
6862         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6863
6864         if (lun->be_lun->lun_type != T_DIRECT)
6865                 control_dev = 1;
6866         else
6867                 control_dev = 0;
6868
6869         if (lun->flags & CTL_LUN_PR_RESERVED) {
6870                 uint32_t residx;
6871
6872                 /*
6873                  * XXX KDM need a lock here.
6874                  */
6875                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6876                 if ((lun->res_type == SPR_TYPE_EX_AC
6877                   && residx != lun->pr_res_idx)
6878                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
6879                    || lun->res_type == SPR_TYPE_EX_AC_AR)
6880                   && !lun->per_res[residx].registered)) {
6881                         ctl_set_reservation_conflict(ctsio);
6882                         ctl_done((union ctl_io *)ctsio);
6883                         return (CTL_RETVAL_COMPLETE);
6884                 }
6885         }
6886
6887         switch (ctsio->cdb[0]) {
6888         case MODE_SENSE_6: {
6889                 struct scsi_mode_sense_6 *cdb;
6890
6891                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6892
6893                 header_len = sizeof(struct scsi_mode_hdr_6);
6894                 if (cdb->byte2 & SMS_DBD)
6895                         dbd = 1;
6896                 else
6897                         header_len += sizeof(struct scsi_mode_block_descr);
6898
6899                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6900                 page_code = cdb->page & SMS_PAGE_CODE;
6901                 subpage = cdb->subpage;
6902                 alloc_len = cdb->length;
6903                 break;
6904         }
6905         case MODE_SENSE_10: {
6906                 struct scsi_mode_sense_10 *cdb;
6907
6908                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6909
6910                 header_len = sizeof(struct scsi_mode_hdr_10);
6911
6912                 if (cdb->byte2 & SMS_DBD)
6913                         dbd = 1;
6914                 else
6915                         header_len += sizeof(struct scsi_mode_block_descr);
6916                 if (cdb->byte2 & SMS10_LLBAA)
6917                         llba = 1;
6918                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6919                 page_code = cdb->page & SMS_PAGE_CODE;
6920                 subpage = cdb->subpage;
6921                 alloc_len = scsi_2btoul(cdb->length);
6922                 break;
6923         }
6924         default:
6925                 ctl_set_invalid_opcode(ctsio);
6926                 ctl_done((union ctl_io *)ctsio);
6927                 return (CTL_RETVAL_COMPLETE);
6928                 break; /* NOTREACHED */
6929         }
6930
6931         /*
6932          * We have to make a first pass through to calculate the size of
6933          * the pages that match the user's query.  Then we allocate enough
6934          * memory to hold it, and actually copy the data into the buffer.
6935          */
6936         switch (page_code) {
6937         case SMS_ALL_PAGES_PAGE: {
6938                 int i;
6939
6940                 page_len = 0;
6941
6942                 /*
6943                  * At the moment, values other than 0 and 0xff here are
6944                  * reserved according to SPC-3.
6945                  */
6946                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6947                  && (subpage != SMS_SUBPAGE_ALL)) {
6948                         ctl_set_invalid_field(ctsio,
6949                                               /*sks_valid*/ 1,
6950                                               /*command*/ 1,
6951                                               /*field*/ 3,
6952                                               /*bit_valid*/ 0,
6953                                               /*bit*/ 0);
6954                         ctl_done((union ctl_io *)ctsio);
6955                         return (CTL_RETVAL_COMPLETE);
6956                 }
6957
6958                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6959                         if ((control_dev != 0)
6960                          && (lun->mode_pages.index[i].page_flags &
6961                              CTL_PAGE_FLAG_DISK_ONLY))
6962                                 continue;
6963
6964                         /*
6965                          * We don't use this subpage if the user didn't
6966                          * request all subpages.
6967                          */
6968                         if ((lun->mode_pages.index[i].subpage != 0)
6969                          && (subpage == SMS_SUBPAGE_PAGE_0))
6970                                 continue;
6971
6972 #if 0
6973                         printf("found page %#x len %d\n",
6974                                lun->mode_pages.index[i].page_code &
6975                                SMPH_PC_MASK,
6976                                lun->mode_pages.index[i].page_len);
6977 #endif
6978                         page_len += lun->mode_pages.index[i].page_len;
6979                 }
6980                 break;
6981         }
6982         default: {
6983                 int i;
6984
6985                 page_len = 0;
6986
6987                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6988                         /* Look for the right page code */
6989                         if ((lun->mode_pages.index[i].page_code &
6990                              SMPH_PC_MASK) != page_code)
6991                                 continue;
6992
6993                         /* Look for the right subpage or the subpage wildcard*/
6994                         if ((lun->mode_pages.index[i].subpage != subpage)
6995                          && (subpage != SMS_SUBPAGE_ALL))
6996                                 continue;
6997
6998                         /* Make sure the page is supported for this dev type */
6999                         if ((control_dev != 0)
7000                          && (lun->mode_pages.index[i].page_flags &
7001                              CTL_PAGE_FLAG_DISK_ONLY))
7002                                 continue;
7003
7004 #if 0
7005                         printf("found page %#x len %d\n",
7006                                lun->mode_pages.index[i].page_code &
7007                                SMPH_PC_MASK,
7008                                lun->mode_pages.index[i].page_len);
7009 #endif
7010
7011                         page_len += lun->mode_pages.index[i].page_len;
7012                 }
7013
7014                 if (page_len == 0) {
7015                         ctl_set_invalid_field(ctsio,
7016                                               /*sks_valid*/ 1,
7017                                               /*command*/ 1,
7018                                               /*field*/ 2,
7019                                               /*bit_valid*/ 1,
7020                                               /*bit*/ 5);
7021                         ctl_done((union ctl_io *)ctsio);
7022                         return (CTL_RETVAL_COMPLETE);
7023                 }
7024                 break;
7025         }
7026         }
7027
7028         total_len = header_len + page_len;
7029 #if 0
7030         printf("header_len = %d, page_len = %d, total_len = %d\n",
7031                header_len, page_len, total_len);
7032 #endif
7033
7034         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7035         ctsio->kern_sg_entries = 0;
7036         ctsio->kern_data_resid = 0;
7037         ctsio->kern_rel_offset = 0;
7038         if (total_len < alloc_len) {
7039                 ctsio->residual = alloc_len - total_len;
7040                 ctsio->kern_data_len = total_len;
7041                 ctsio->kern_total_len = total_len;
7042         } else {
7043                 ctsio->residual = 0;
7044                 ctsio->kern_data_len = alloc_len;
7045                 ctsio->kern_total_len = alloc_len;
7046         }
7047
7048         switch (ctsio->cdb[0]) {
7049         case MODE_SENSE_6: {
7050                 struct scsi_mode_hdr_6 *header;
7051
7052                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7053
7054                 header->datalen = ctl_min(total_len - 1, 254);
7055                 if (control_dev == 0)
7056                         header->dev_specific = 0x10; /* DPOFUA */
7057                 if (dbd)
7058                         header->block_descr_len = 0;
7059                 else
7060                         header->block_descr_len =
7061                                 sizeof(struct scsi_mode_block_descr);
7062                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7063                 break;
7064         }
7065         case MODE_SENSE_10: {
7066                 struct scsi_mode_hdr_10 *header;
7067                 int datalen;
7068
7069                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7070
7071                 datalen = ctl_min(total_len - 2, 65533);
7072                 scsi_ulto2b(datalen, header->datalen);
7073                 if (control_dev == 0)
7074                         header->dev_specific = 0x10; /* DPOFUA */
7075                 if (dbd)
7076                         scsi_ulto2b(0, header->block_descr_len);
7077                 else
7078                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7079                                     header->block_descr_len);
7080                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7081                 break;
7082         }
7083         default:
7084                 panic("invalid CDB type %#x", ctsio->cdb[0]);
7085                 break; /* NOTREACHED */
7086         }
7087
7088         /*
7089          * If we've got a disk, use its blocksize in the block
7090          * descriptor.  Otherwise, just set it to 0.
7091          */
7092         if (dbd == 0) {
7093                 if (control_dev != 0)
7094                         scsi_ulto3b(lun->be_lun->blocksize,
7095                                     block_desc->block_len);
7096                 else
7097                         scsi_ulto3b(0, block_desc->block_len);
7098         }
7099
7100         switch (page_code) {
7101         case SMS_ALL_PAGES_PAGE: {
7102                 int i, data_used;
7103
7104                 data_used = header_len;
7105                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7106                         struct ctl_page_index *page_index;
7107
7108                         page_index = &lun->mode_pages.index[i];
7109
7110                         if ((control_dev != 0)
7111                          && (page_index->page_flags &
7112                             CTL_PAGE_FLAG_DISK_ONLY))
7113                                 continue;
7114
7115                         /*
7116                          * We don't use this subpage if the user didn't
7117                          * request all subpages.  We already checked (above)
7118                          * to make sure the user only specified a subpage
7119                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7120                          */
7121                         if ((page_index->subpage != 0)
7122                          && (subpage == SMS_SUBPAGE_PAGE_0))
7123                                 continue;
7124
7125                         /*
7126                          * Call the handler, if it exists, to update the
7127                          * page to the latest values.
7128                          */
7129                         if (page_index->sense_handler != NULL)
7130                                 page_index->sense_handler(ctsio, page_index,pc);
7131
7132                         memcpy(ctsio->kern_data_ptr + data_used,
7133                                page_index->page_data +
7134                                (page_index->page_len * pc),
7135                                page_index->page_len);
7136                         data_used += page_index->page_len;
7137                 }
7138                 break;
7139         }
7140         default: {
7141                 int i, data_used;
7142
7143                 data_used = header_len;
7144
7145                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7146                         struct ctl_page_index *page_index;
7147
7148                         page_index = &lun->mode_pages.index[i];
7149
7150                         /* Look for the right page code */
7151                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7152                                 continue;
7153
7154                         /* Look for the right subpage or the subpage wildcard*/
7155                         if ((page_index->subpage != subpage)
7156                          && (subpage != SMS_SUBPAGE_ALL))
7157                                 continue;
7158
7159                         /* Make sure the page is supported for this dev type */
7160                         if ((control_dev != 0)
7161                          && (page_index->page_flags &
7162                              CTL_PAGE_FLAG_DISK_ONLY))
7163                                 continue;
7164
7165                         /*
7166                          * Call the handler, if it exists, to update the
7167                          * page to the latest values.
7168                          */
7169                         if (page_index->sense_handler != NULL)
7170                                 page_index->sense_handler(ctsio, page_index,pc);
7171
7172                         memcpy(ctsio->kern_data_ptr + data_used,
7173                                page_index->page_data +
7174                                (page_index->page_len * pc),
7175                                page_index->page_len);
7176                         data_used += page_index->page_len;
7177                 }
7178                 break;
7179         }
7180         }
7181
7182         ctsio->scsi_status = SCSI_STATUS_OK;
7183
7184         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7185         ctsio->be_move_done = ctl_config_move_done;
7186         ctl_datamove((union ctl_io *)ctsio);
7187
7188         return (CTL_RETVAL_COMPLETE);
7189 }
7190
7191 int
7192 ctl_read_capacity(struct ctl_scsiio *ctsio)
7193 {
7194         struct scsi_read_capacity *cdb;
7195         struct scsi_read_capacity_data *data;
7196         struct ctl_lun *lun;
7197         uint32_t lba;
7198
7199         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7200
7201         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7202
7203         lba = scsi_4btoul(cdb->addr);
7204         if (((cdb->pmi & SRC_PMI) == 0)
7205          && (lba != 0)) {
7206                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7207                                       /*sks_valid*/ 1,
7208                                       /*command*/ 1,
7209                                       /*field*/ 2,
7210                                       /*bit_valid*/ 0,
7211                                       /*bit*/ 0);
7212                 ctl_done((union ctl_io *)ctsio);
7213                 return (CTL_RETVAL_COMPLETE);
7214         }
7215
7216         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7217
7218         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7219         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7220         ctsio->residual = 0;
7221         ctsio->kern_data_len = sizeof(*data);
7222         ctsio->kern_total_len = sizeof(*data);
7223         ctsio->kern_data_resid = 0;
7224         ctsio->kern_rel_offset = 0;
7225         ctsio->kern_sg_entries = 0;
7226
7227         /*
7228          * If the maximum LBA is greater than 0xfffffffe, the user must
7229          * issue a SERVICE ACTION IN (16) command, with the read capacity
7230          * serivce action set.
7231          */
7232         if (lun->be_lun->maxlba > 0xfffffffe)
7233                 scsi_ulto4b(0xffffffff, data->addr);
7234         else
7235                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7236
7237         /*
7238          * XXX KDM this may not be 512 bytes...
7239          */
7240         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7241
7242         ctsio->scsi_status = SCSI_STATUS_OK;
7243
7244         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7245         ctsio->be_move_done = ctl_config_move_done;
7246         ctl_datamove((union ctl_io *)ctsio);
7247
7248         return (CTL_RETVAL_COMPLETE);
7249 }
7250
7251 int
7252 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7253 {
7254         struct scsi_read_capacity_16 *cdb;
7255         struct scsi_read_capacity_data_long *data;
7256         struct ctl_lun *lun;
7257         uint64_t lba;
7258         uint32_t alloc_len;
7259
7260         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7261
7262         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7263
7264         alloc_len = scsi_4btoul(cdb->alloc_len);
7265         lba = scsi_8btou64(cdb->addr);
7266
7267         if ((cdb->reladr & SRC16_PMI)
7268          && (lba != 0)) {
7269                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7270                                       /*sks_valid*/ 1,
7271                                       /*command*/ 1,
7272                                       /*field*/ 2,
7273                                       /*bit_valid*/ 0,
7274                                       /*bit*/ 0);
7275                 ctl_done((union ctl_io *)ctsio);
7276                 return (CTL_RETVAL_COMPLETE);
7277         }
7278
7279         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7280
7281         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7282         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7283
7284         if (sizeof(*data) < alloc_len) {
7285                 ctsio->residual = alloc_len - sizeof(*data);
7286                 ctsio->kern_data_len = sizeof(*data);
7287                 ctsio->kern_total_len = sizeof(*data);
7288         } else {
7289                 ctsio->residual = 0;
7290                 ctsio->kern_data_len = alloc_len;
7291                 ctsio->kern_total_len = alloc_len;
7292         }
7293         ctsio->kern_data_resid = 0;
7294         ctsio->kern_rel_offset = 0;
7295         ctsio->kern_sg_entries = 0;
7296
7297         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7298         /* XXX KDM this may not be 512 bytes... */
7299         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7300         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7301         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7302         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7303                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7304
7305         ctsio->scsi_status = SCSI_STATUS_OK;
7306
7307         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7308         ctsio->be_move_done = ctl_config_move_done;
7309         ctl_datamove((union ctl_io *)ctsio);
7310
7311         return (CTL_RETVAL_COMPLETE);
7312 }
7313
7314 int
7315 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7316 {
7317         struct scsi_maintenance_in *cdb;
7318         int retval;
7319         int alloc_len, ext, total_len = 0, g, p, pc, pg;
7320         int num_target_port_groups, num_target_ports, single;
7321         struct ctl_lun *lun;
7322         struct ctl_softc *softc;
7323         struct ctl_port *port;
7324         struct scsi_target_group_data *rtg_ptr;
7325         struct scsi_target_group_data_extended *rtg_ext_ptr;
7326         struct scsi_target_port_group_descriptor *tpg_desc;
7327
7328         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7329
7330         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7331         softc = control_softc;
7332         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7333
7334         retval = CTL_RETVAL_COMPLETE;
7335
7336         switch (cdb->byte2 & STG_PDF_MASK) {
7337         case STG_PDF_LENGTH:
7338                 ext = 0;
7339                 break;
7340         case STG_PDF_EXTENDED:
7341                 ext = 1;
7342                 break;
7343         default:
7344                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7345                                       /*sks_valid*/ 1,
7346                                       /*command*/ 1,
7347                                       /*field*/ 2,
7348                                       /*bit_valid*/ 1,
7349                                       /*bit*/ 5);
7350                 ctl_done((union ctl_io *)ctsio);
7351                 return(retval);
7352         }
7353
7354         single = ctl_is_single;
7355         if (single)
7356                 num_target_port_groups = 1;
7357         else
7358                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7359         num_target_ports = 0;
7360         mtx_lock(&softc->ctl_lock);
7361         STAILQ_FOREACH(port, &softc->port_list, links) {
7362                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7363                         continue;
7364                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7365                         continue;
7366                 num_target_ports++;
7367         }
7368         mtx_unlock(&softc->ctl_lock);
7369
7370         if (ext)
7371                 total_len = sizeof(struct scsi_target_group_data_extended);
7372         else
7373                 total_len = sizeof(struct scsi_target_group_data);
7374         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7375                 num_target_port_groups +
7376             sizeof(struct scsi_target_port_descriptor) *
7377                 num_target_ports * num_target_port_groups;
7378
7379         alloc_len = scsi_4btoul(cdb->length);
7380
7381         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7382
7383         ctsio->kern_sg_entries = 0;
7384
7385         if (total_len < alloc_len) {
7386                 ctsio->residual = alloc_len - total_len;
7387                 ctsio->kern_data_len = total_len;
7388                 ctsio->kern_total_len = total_len;
7389         } else {
7390                 ctsio->residual = 0;
7391                 ctsio->kern_data_len = alloc_len;
7392                 ctsio->kern_total_len = alloc_len;
7393         }
7394         ctsio->kern_data_resid = 0;
7395         ctsio->kern_rel_offset = 0;
7396
7397         if (ext) {
7398                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7399                     ctsio->kern_data_ptr;
7400                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7401                 rtg_ext_ptr->format_type = 0x10;
7402                 rtg_ext_ptr->implicit_transition_time = 0;
7403                 tpg_desc = &rtg_ext_ptr->groups[0];
7404         } else {
7405                 rtg_ptr = (struct scsi_target_group_data *)
7406                     ctsio->kern_data_ptr;
7407                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7408                 tpg_desc = &rtg_ptr->groups[0];
7409         }
7410
7411         pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7412         mtx_lock(&softc->ctl_lock);
7413         for (g = 0; g < num_target_port_groups; g++) {
7414                 if (g == pg)
7415                         tpg_desc->pref_state = TPG_PRIMARY |
7416                             TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7417                 else
7418                         tpg_desc->pref_state =
7419                             TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7420                 tpg_desc->support = TPG_AO_SUP;
7421                 if (!single)
7422                         tpg_desc->support |= TPG_AN_SUP;
7423                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7424                 tpg_desc->status = TPG_IMPLICIT;
7425                 pc = 0;
7426                 STAILQ_FOREACH(port, &softc->port_list, links) {
7427                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7428                                 continue;
7429                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7430                             CTL_MAX_LUNS)
7431                                 continue;
7432                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7433                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7434                             relative_target_port_identifier);
7435                         pc++;
7436                 }
7437                 tpg_desc->target_port_count = pc;
7438                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7439                     &tpg_desc->descriptors[pc];
7440         }
7441         mtx_unlock(&softc->ctl_lock);
7442
7443         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7444         ctsio->be_move_done = ctl_config_move_done;
7445
7446         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7447                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7448                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7449                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7450                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7451
7452         ctl_datamove((union ctl_io *)ctsio);
7453         return(retval);
7454 }
7455
7456 int
7457 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7458 {
7459         struct ctl_lun *lun;
7460         struct scsi_report_supported_opcodes *cdb;
7461         const struct ctl_cmd_entry *entry, *sentry;
7462         struct scsi_report_supported_opcodes_all *all;
7463         struct scsi_report_supported_opcodes_descr *descr;
7464         struct scsi_report_supported_opcodes_one *one;
7465         int retval;
7466         int alloc_len, total_len;
7467         int opcode, service_action, i, j, num;
7468
7469         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7470
7471         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7472         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7473
7474         retval = CTL_RETVAL_COMPLETE;
7475
7476         opcode = cdb->requested_opcode;
7477         service_action = scsi_2btoul(cdb->requested_service_action);
7478         switch (cdb->options & RSO_OPTIONS_MASK) {
7479         case RSO_OPTIONS_ALL:
7480                 num = 0;
7481                 for (i = 0; i < 256; i++) {
7482                         entry = &ctl_cmd_table[i];
7483                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7484                                 for (j = 0; j < 32; j++) {
7485                                         sentry = &((const struct ctl_cmd_entry *)
7486                                             entry->execute)[j];
7487                                         if (ctl_cmd_applicable(
7488                                             lun->be_lun->lun_type, sentry))
7489                                                 num++;
7490                                 }
7491                         } else {
7492                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7493                                     entry))
7494                                         num++;
7495                         }
7496                 }
7497                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7498                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7499                 break;
7500         case RSO_OPTIONS_OC:
7501                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7502                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7503                                               /*sks_valid*/ 1,
7504                                               /*command*/ 1,
7505                                               /*field*/ 2,
7506                                               /*bit_valid*/ 1,
7507                                               /*bit*/ 2);
7508                         ctl_done((union ctl_io *)ctsio);
7509                         return (CTL_RETVAL_COMPLETE);
7510                 }
7511                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7512                 break;
7513         case RSO_OPTIONS_OC_SA:
7514                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7515                     service_action >= 32) {
7516                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7517                                               /*sks_valid*/ 1,
7518                                               /*command*/ 1,
7519                                               /*field*/ 2,
7520                                               /*bit_valid*/ 1,
7521                                               /*bit*/ 2);
7522                         ctl_done((union ctl_io *)ctsio);
7523                         return (CTL_RETVAL_COMPLETE);
7524                 }
7525                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7526                 break;
7527         default:
7528                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7529                                       /*sks_valid*/ 1,
7530                                       /*command*/ 1,
7531                                       /*field*/ 2,
7532                                       /*bit_valid*/ 1,
7533                                       /*bit*/ 2);
7534                 ctl_done((union ctl_io *)ctsio);
7535                 return (CTL_RETVAL_COMPLETE);
7536         }
7537
7538         alloc_len = scsi_4btoul(cdb->length);
7539
7540         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7541
7542         ctsio->kern_sg_entries = 0;
7543
7544         if (total_len < alloc_len) {
7545                 ctsio->residual = alloc_len - total_len;
7546                 ctsio->kern_data_len = total_len;
7547                 ctsio->kern_total_len = total_len;
7548         } else {
7549                 ctsio->residual = 0;
7550                 ctsio->kern_data_len = alloc_len;
7551                 ctsio->kern_total_len = alloc_len;
7552         }
7553         ctsio->kern_data_resid = 0;
7554         ctsio->kern_rel_offset = 0;
7555
7556         switch (cdb->options & RSO_OPTIONS_MASK) {
7557         case RSO_OPTIONS_ALL:
7558                 all = (struct scsi_report_supported_opcodes_all *)
7559                     ctsio->kern_data_ptr;
7560                 num = 0;
7561                 for (i = 0; i < 256; i++) {
7562                         entry = &ctl_cmd_table[i];
7563                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7564                                 for (j = 0; j < 32; j++) {
7565                                         sentry = &((const struct ctl_cmd_entry *)
7566                                             entry->execute)[j];
7567                                         if (!ctl_cmd_applicable(
7568                                             lun->be_lun->lun_type, sentry))
7569                                                 continue;
7570                                         descr = &all->descr[num++];
7571                                         descr->opcode = i;
7572                                         scsi_ulto2b(j, descr->service_action);
7573                                         descr->flags = RSO_SERVACTV;
7574                                         scsi_ulto2b(sentry->length,
7575                                             descr->cdb_length);
7576                                 }
7577                         } else {
7578                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7579                                     entry))
7580                                         continue;
7581                                 descr = &all->descr[num++];
7582                                 descr->opcode = i;
7583                                 scsi_ulto2b(0, descr->service_action);
7584                                 descr->flags = 0;
7585                                 scsi_ulto2b(entry->length, descr->cdb_length);
7586                         }
7587                 }
7588                 scsi_ulto4b(
7589                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7590                     all->length);
7591                 break;
7592         case RSO_OPTIONS_OC:
7593                 one = (struct scsi_report_supported_opcodes_one *)
7594                     ctsio->kern_data_ptr;
7595                 entry = &ctl_cmd_table[opcode];
7596                 goto fill_one;
7597         case RSO_OPTIONS_OC_SA:
7598                 one = (struct scsi_report_supported_opcodes_one *)
7599                     ctsio->kern_data_ptr;
7600                 entry = &ctl_cmd_table[opcode];
7601                 entry = &((const struct ctl_cmd_entry *)
7602                     entry->execute)[service_action];
7603 fill_one:
7604                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7605                         one->support = 3;
7606                         scsi_ulto2b(entry->length, one->cdb_length);
7607                         one->cdb_usage[0] = opcode;
7608                         memcpy(&one->cdb_usage[1], entry->usage,
7609                             entry->length - 1);
7610                 } else
7611                         one->support = 1;
7612                 break;
7613         }
7614
7615         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7616         ctsio->be_move_done = ctl_config_move_done;
7617
7618         ctl_datamove((union ctl_io *)ctsio);
7619         return(retval);
7620 }
7621
7622 int
7623 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7624 {
7625         struct ctl_lun *lun;
7626         struct scsi_report_supported_tmf *cdb;
7627         struct scsi_report_supported_tmf_data *data;
7628         int retval;
7629         int alloc_len, total_len;
7630
7631         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7632
7633         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7634         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7635
7636         retval = CTL_RETVAL_COMPLETE;
7637
7638         total_len = sizeof(struct scsi_report_supported_tmf_data);
7639         alloc_len = scsi_4btoul(cdb->length);
7640
7641         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7642
7643         ctsio->kern_sg_entries = 0;
7644
7645         if (total_len < alloc_len) {
7646                 ctsio->residual = alloc_len - total_len;
7647                 ctsio->kern_data_len = total_len;
7648                 ctsio->kern_total_len = total_len;
7649         } else {
7650                 ctsio->residual = 0;
7651                 ctsio->kern_data_len = alloc_len;
7652                 ctsio->kern_total_len = alloc_len;
7653         }
7654         ctsio->kern_data_resid = 0;
7655         ctsio->kern_rel_offset = 0;
7656
7657         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7658         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7659         data->byte2 |= RST_ITNRS;
7660
7661         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7662         ctsio->be_move_done = ctl_config_move_done;
7663
7664         ctl_datamove((union ctl_io *)ctsio);
7665         return (retval);
7666 }
7667
7668 int
7669 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7670 {
7671         struct ctl_lun *lun;
7672         struct scsi_report_timestamp *cdb;
7673         struct scsi_report_timestamp_data *data;
7674         struct timeval tv;
7675         int64_t timestamp;
7676         int retval;
7677         int alloc_len, total_len;
7678
7679         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7680
7681         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7682         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7683
7684         retval = CTL_RETVAL_COMPLETE;
7685
7686         total_len = sizeof(struct scsi_report_timestamp_data);
7687         alloc_len = scsi_4btoul(cdb->length);
7688
7689         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7690
7691         ctsio->kern_sg_entries = 0;
7692
7693         if (total_len < alloc_len) {
7694                 ctsio->residual = alloc_len - total_len;
7695                 ctsio->kern_data_len = total_len;
7696                 ctsio->kern_total_len = total_len;
7697         } else {
7698                 ctsio->residual = 0;
7699                 ctsio->kern_data_len = alloc_len;
7700                 ctsio->kern_total_len = alloc_len;
7701         }
7702         ctsio->kern_data_resid = 0;
7703         ctsio->kern_rel_offset = 0;
7704
7705         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7706         scsi_ulto2b(sizeof(*data) - 2, data->length);
7707         data->origin = RTS_ORIG_OUTSIDE;
7708         getmicrotime(&tv);
7709         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7710         scsi_ulto4b(timestamp >> 16, data->timestamp);
7711         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7712
7713         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7714         ctsio->be_move_done = ctl_config_move_done;
7715
7716         ctl_datamove((union ctl_io *)ctsio);
7717         return (retval);
7718 }
7719
7720 int
7721 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7722 {
7723         struct scsi_per_res_in *cdb;
7724         int alloc_len, total_len = 0;
7725         /* struct scsi_per_res_in_rsrv in_data; */
7726         struct ctl_lun *lun;
7727         struct ctl_softc *softc;
7728
7729         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7730
7731         softc = control_softc;
7732
7733         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7734
7735         alloc_len = scsi_2btoul(cdb->length);
7736
7737         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7738
7739 retry:
7740         mtx_lock(&lun->lun_lock);
7741         switch (cdb->action) {
7742         case SPRI_RK: /* read keys */
7743                 total_len = sizeof(struct scsi_per_res_in_keys) +
7744                         lun->pr_key_count *
7745                         sizeof(struct scsi_per_res_key);
7746                 break;
7747         case SPRI_RR: /* read reservation */
7748                 if (lun->flags & CTL_LUN_PR_RESERVED)
7749                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7750                 else
7751                         total_len = sizeof(struct scsi_per_res_in_header);
7752                 break;
7753         case SPRI_RC: /* report capabilities */
7754                 total_len = sizeof(struct scsi_per_res_cap);
7755                 break;
7756         case SPRI_RS: /* read full status */
7757                 total_len = sizeof(struct scsi_per_res_in_header) +
7758                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7759                     lun->pr_key_count;
7760                 break;
7761         default:
7762                 panic("Invalid PR type %x", cdb->action);
7763         }
7764         mtx_unlock(&lun->lun_lock);
7765
7766         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7767
7768         if (total_len < alloc_len) {
7769                 ctsio->residual = alloc_len - total_len;
7770                 ctsio->kern_data_len = total_len;
7771                 ctsio->kern_total_len = total_len;
7772         } else {
7773                 ctsio->residual = 0;
7774                 ctsio->kern_data_len = alloc_len;
7775                 ctsio->kern_total_len = alloc_len;
7776         }
7777
7778         ctsio->kern_data_resid = 0;
7779         ctsio->kern_rel_offset = 0;
7780         ctsio->kern_sg_entries = 0;
7781
7782         mtx_lock(&lun->lun_lock);
7783         switch (cdb->action) {
7784         case SPRI_RK: { // read keys
7785         struct scsi_per_res_in_keys *res_keys;
7786                 int i, key_count;
7787
7788                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7789
7790                 /*
7791                  * We had to drop the lock to allocate our buffer, which
7792                  * leaves time for someone to come in with another
7793                  * persistent reservation.  (That is unlikely, though,
7794                  * since this should be the only persistent reservation
7795                  * command active right now.)
7796                  */
7797                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7798                     (lun->pr_key_count *
7799                      sizeof(struct scsi_per_res_key)))){
7800                         mtx_unlock(&lun->lun_lock);
7801                         free(ctsio->kern_data_ptr, M_CTL);
7802                         printf("%s: reservation length changed, retrying\n",
7803                                __func__);
7804                         goto retry;
7805                 }
7806
7807                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7808
7809                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7810                              lun->pr_key_count, res_keys->header.length);
7811
7812                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7813                         if (!lun->per_res[i].registered)
7814                                 continue;
7815
7816                         /*
7817                          * We used lun->pr_key_count to calculate the
7818                          * size to allocate.  If it turns out the number of
7819                          * initiators with the registered flag set is
7820                          * larger than that (i.e. they haven't been kept in
7821                          * sync), we've got a problem.
7822                          */
7823                         if (key_count >= lun->pr_key_count) {
7824 #ifdef NEEDTOPORT
7825                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7826                                             CTL_PR_ERROR,
7827                                             csevent_LogType_Fault,
7828                                             csevent_AlertLevel_Yellow,
7829                                             csevent_FRU_ShelfController,
7830                                             csevent_FRU_Firmware,
7831                                         csevent_FRU_Unknown,
7832                                             "registered keys %d >= key "
7833                                             "count %d", key_count,
7834                                             lun->pr_key_count);
7835 #endif
7836                                 key_count++;
7837                                 continue;
7838                         }
7839                         memcpy(res_keys->keys[key_count].key,
7840                                lun->per_res[i].res_key.key,
7841                                ctl_min(sizeof(res_keys->keys[key_count].key),
7842                                sizeof(lun->per_res[i].res_key)));
7843                         key_count++;
7844                 }
7845                 break;
7846         }
7847         case SPRI_RR: { // read reservation
7848                 struct scsi_per_res_in_rsrv *res;
7849                 int tmp_len, header_only;
7850
7851                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7852
7853                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7854
7855                 if (lun->flags & CTL_LUN_PR_RESERVED)
7856                 {
7857                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7858                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7859                                     res->header.length);
7860                         header_only = 0;
7861                 } else {
7862                         tmp_len = sizeof(struct scsi_per_res_in_header);
7863                         scsi_ulto4b(0, res->header.length);
7864                         header_only = 1;
7865                 }
7866
7867                 /*
7868                  * We had to drop the lock to allocate our buffer, which
7869                  * leaves time for someone to come in with another
7870                  * persistent reservation.  (That is unlikely, though,
7871                  * since this should be the only persistent reservation
7872                  * command active right now.)
7873                  */
7874                 if (tmp_len != total_len) {
7875                         mtx_unlock(&lun->lun_lock);
7876                         free(ctsio->kern_data_ptr, M_CTL);
7877                         printf("%s: reservation status changed, retrying\n",
7878                                __func__);
7879                         goto retry;
7880                 }
7881
7882                 /*
7883                  * No reservation held, so we're done.
7884                  */
7885                 if (header_only != 0)
7886                         break;
7887
7888                 /*
7889                  * If the registration is an All Registrants type, the key
7890                  * is 0, since it doesn't really matter.
7891                  */
7892                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7893                         memcpy(res->data.reservation,
7894                                &lun->per_res[lun->pr_res_idx].res_key,
7895                                sizeof(struct scsi_per_res_key));
7896                 }
7897                 res->data.scopetype = lun->res_type;
7898                 break;
7899         }
7900         case SPRI_RC:     //report capabilities
7901         {
7902                 struct scsi_per_res_cap *res_cap;
7903                 uint16_t type_mask;
7904
7905                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7906                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7907                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7908                 type_mask = SPRI_TM_WR_EX_AR |
7909                             SPRI_TM_EX_AC_RO |
7910                             SPRI_TM_WR_EX_RO |
7911                             SPRI_TM_EX_AC |
7912                             SPRI_TM_WR_EX |
7913                             SPRI_TM_EX_AC_AR;
7914                 scsi_ulto2b(type_mask, res_cap->type_mask);
7915                 break;
7916         }
7917         case SPRI_RS: { // read full status
7918                 struct scsi_per_res_in_full *res_status;
7919                 struct scsi_per_res_in_full_desc *res_desc;
7920                 struct ctl_port *port;
7921                 int i, len;
7922
7923                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7924
7925                 /*
7926                  * We had to drop the lock to allocate our buffer, which
7927                  * leaves time for someone to come in with another
7928                  * persistent reservation.  (That is unlikely, though,
7929                  * since this should be the only persistent reservation
7930                  * command active right now.)
7931                  */
7932                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7933                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7934                      lun->pr_key_count)){
7935                         mtx_unlock(&lun->lun_lock);
7936                         free(ctsio->kern_data_ptr, M_CTL);
7937                         printf("%s: reservation length changed, retrying\n",
7938                                __func__);
7939                         goto retry;
7940                 }
7941
7942                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7943
7944                 res_desc = &res_status->desc[0];
7945                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7946                         if (!lun->per_res[i].registered)
7947                                 continue;
7948
7949                         memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7950                             sizeof(res_desc->res_key));
7951                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7952                             (lun->pr_res_idx == i ||
7953                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7954                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7955                                 res_desc->scopetype = lun->res_type;
7956                         }
7957                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7958                             res_desc->rel_trgt_port_id);
7959                         len = 0;
7960                         port = softc->ctl_ports[
7961                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7962                         if (port != NULL)
7963                                 len = ctl_create_iid(port,
7964                                     i % CTL_MAX_INIT_PER_PORT,
7965                                     res_desc->transport_id);
7966                         scsi_ulto4b(len, res_desc->additional_length);
7967                         res_desc = (struct scsi_per_res_in_full_desc *)
7968                             &res_desc->transport_id[len];
7969                 }
7970                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7971                     res_status->header.length);
7972                 break;
7973         }
7974         default:
7975                 /*
7976                  * This is a bug, because we just checked for this above,
7977                  * and should have returned an error.
7978                  */
7979                 panic("Invalid PR type %x", cdb->action);
7980                 break; /* NOTREACHED */
7981         }
7982         mtx_unlock(&lun->lun_lock);
7983
7984         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7985         ctsio->be_move_done = ctl_config_move_done;
7986
7987         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7988                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7989                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7990                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7991                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7992
7993         ctl_datamove((union ctl_io *)ctsio);
7994
7995         return (CTL_RETVAL_COMPLETE);
7996 }
7997
7998 /*
7999  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8000  * it should return.
8001  */
8002 static int
8003 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8004                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8005                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8006                 struct scsi_per_res_out_parms* param)
8007 {
8008         union ctl_ha_msg persis_io;
8009         int retval, i;
8010         int isc_retval;
8011
8012         retval = 0;
8013
8014         mtx_lock(&lun->lun_lock);
8015         if (sa_res_key == 0) {
8016                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8017                         /* validate scope and type */
8018                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8019                              SPR_LU_SCOPE) {
8020                                 mtx_unlock(&lun->lun_lock);
8021                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8022                                                       /*sks_valid*/ 1,
8023                                                       /*command*/ 1,
8024                                                       /*field*/ 2,
8025                                                       /*bit_valid*/ 1,
8026                                                       /*bit*/ 4);
8027                                 ctl_done((union ctl_io *)ctsio);
8028                                 return (1);
8029                         }
8030
8031                         if (type>8 || type==2 || type==4 || type==0) {
8032                                 mtx_unlock(&lun->lun_lock);
8033                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8034                                                       /*sks_valid*/ 1,
8035                                                       /*command*/ 1,
8036                                                       /*field*/ 2,
8037                                                       /*bit_valid*/ 1,
8038                                                       /*bit*/ 0);
8039                                 ctl_done((union ctl_io *)ctsio);
8040                                 return (1);
8041                         }
8042
8043                         /* temporarily unregister this nexus */
8044                         lun->per_res[residx].registered = 0;
8045
8046                         /*
8047                          * Unregister everybody else and build UA for
8048                          * them
8049                          */
8050                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8051                                 if (lun->per_res[i].registered == 0)
8052                                         continue;
8053
8054                                 if (!persis_offset
8055                                  && i <CTL_MAX_INITIATORS)
8056                                         lun->pending_ua[i] |=
8057                                                 CTL_UA_REG_PREEMPT;
8058                                 else if (persis_offset
8059                                       && i >= persis_offset)
8060                                         lun->pending_ua[i-persis_offset] |=
8061                                                 CTL_UA_REG_PREEMPT;
8062                                 lun->per_res[i].registered = 0;
8063                                 memset(&lun->per_res[i].res_key, 0,
8064                                        sizeof(struct scsi_per_res_key));
8065                         }
8066                         lun->per_res[residx].registered = 1;
8067                         lun->pr_key_count = 1;
8068                         lun->res_type = type;
8069                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8070                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8071                                 lun->pr_res_idx = residx;
8072
8073                         /* send msg to other side */
8074                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8075                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8076                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8077                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8078                         persis_io.pr.pr_info.res_type = type;
8079                         memcpy(persis_io.pr.pr_info.sa_res_key,
8080                                param->serv_act_res_key,
8081                                sizeof(param->serv_act_res_key));
8082                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8083                              &persis_io, sizeof(persis_io), 0)) >
8084                              CTL_HA_STATUS_SUCCESS) {
8085                                 printf("CTL:Persis Out error returned "
8086                                        "from ctl_ha_msg_send %d\n",
8087                                        isc_retval);
8088                         }
8089                 } else {
8090                         /* not all registrants */
8091                         mtx_unlock(&lun->lun_lock);
8092                         free(ctsio->kern_data_ptr, M_CTL);
8093                         ctl_set_invalid_field(ctsio,
8094                                               /*sks_valid*/ 1,
8095                                               /*command*/ 0,
8096                                               /*field*/ 8,
8097                                               /*bit_valid*/ 0,
8098                                               /*bit*/ 0);
8099                         ctl_done((union ctl_io *)ctsio);
8100                         return (1);
8101                 }
8102         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8103                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8104                 int found = 0;
8105
8106                 if (res_key == sa_res_key) {
8107                         /* special case */
8108                         /*
8109                          * The spec implies this is not good but doesn't
8110                          * say what to do. There are two choices either
8111                          * generate a res conflict or check condition
8112                          * with illegal field in parameter data. Since
8113                          * that is what is done when the sa_res_key is
8114                          * zero I'll take that approach since this has
8115                          * to do with the sa_res_key.
8116                          */
8117                         mtx_unlock(&lun->lun_lock);
8118                         free(ctsio->kern_data_ptr, M_CTL);
8119                         ctl_set_invalid_field(ctsio,
8120                                               /*sks_valid*/ 1,
8121                                               /*command*/ 0,
8122                                               /*field*/ 8,
8123                                               /*bit_valid*/ 0,
8124                                               /*bit*/ 0);
8125                         ctl_done((union ctl_io *)ctsio);
8126                         return (1);
8127                 }
8128
8129                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8130                         if (lun->per_res[i].registered
8131                          && memcmp(param->serv_act_res_key,
8132                             lun->per_res[i].res_key.key,
8133                             sizeof(struct scsi_per_res_key)) != 0)
8134                                 continue;
8135
8136                         found = 1;
8137                         lun->per_res[i].registered = 0;
8138                         memset(&lun->per_res[i].res_key, 0,
8139                                sizeof(struct scsi_per_res_key));
8140                         lun->pr_key_count--;
8141
8142                         if (!persis_offset && i < CTL_MAX_INITIATORS)
8143                                 lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8144                         else if (persis_offset && i >= persis_offset)
8145                                 lun->pending_ua[i-persis_offset] |=
8146                                         CTL_UA_REG_PREEMPT;
8147                 }
8148                 if (!found) {
8149                         mtx_unlock(&lun->lun_lock);
8150                         free(ctsio->kern_data_ptr, M_CTL);
8151                         ctl_set_reservation_conflict(ctsio);
8152                         ctl_done((union ctl_io *)ctsio);
8153                         return (CTL_RETVAL_COMPLETE);
8154                 }
8155                 /* send msg to other side */
8156                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8157                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8158                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8159                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8160                 persis_io.pr.pr_info.res_type = type;
8161                 memcpy(persis_io.pr.pr_info.sa_res_key,
8162                        param->serv_act_res_key,
8163                        sizeof(param->serv_act_res_key));
8164                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8165                      &persis_io, sizeof(persis_io), 0)) >
8166                      CTL_HA_STATUS_SUCCESS) {
8167                         printf("CTL:Persis Out error returned from "
8168                                "ctl_ha_msg_send %d\n", isc_retval);
8169                 }
8170         } else {
8171                 /* Reserved but not all registrants */
8172                 /* sa_res_key is res holder */
8173                 if (memcmp(param->serv_act_res_key,
8174                    lun->per_res[lun->pr_res_idx].res_key.key,
8175                    sizeof(struct scsi_per_res_key)) == 0) {
8176                         /* validate scope and type */
8177                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8178                              SPR_LU_SCOPE) {
8179                                 mtx_unlock(&lun->lun_lock);
8180                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8181                                                       /*sks_valid*/ 1,
8182                                                       /*command*/ 1,
8183                                                       /*field*/ 2,
8184                                                       /*bit_valid*/ 1,
8185                                                       /*bit*/ 4);
8186                                 ctl_done((union ctl_io *)ctsio);
8187                                 return (1);
8188                         }
8189
8190                         if (type>8 || type==2 || type==4 || type==0) {
8191                                 mtx_unlock(&lun->lun_lock);
8192                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8193                                                       /*sks_valid*/ 1,
8194                                                       /*command*/ 1,
8195                                                       /*field*/ 2,
8196                                                       /*bit_valid*/ 1,
8197                                                       /*bit*/ 0);
8198                                 ctl_done((union ctl_io *)ctsio);
8199                                 return (1);
8200                         }
8201
8202                         /*
8203                          * Do the following:
8204                          * if sa_res_key != res_key remove all
8205                          * registrants w/sa_res_key and generate UA
8206                          * for these registrants(Registrations
8207                          * Preempted) if it wasn't an exclusive
8208                          * reservation generate UA(Reservations
8209                          * Preempted) for all other registered nexuses
8210                          * if the type has changed. Establish the new
8211                          * reservation and holder. If res_key and
8212                          * sa_res_key are the same do the above
8213                          * except don't unregister the res holder.
8214                          */
8215
8216                         /*
8217                          * Temporarily unregister so it won't get
8218                          * removed or UA generated
8219                          */
8220                         lun->per_res[residx].registered = 0;
8221                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8222                                 if (lun->per_res[i].registered == 0)
8223                                         continue;
8224
8225                                 if (memcmp(param->serv_act_res_key,
8226                                     lun->per_res[i].res_key.key,
8227                                     sizeof(struct scsi_per_res_key)) == 0) {
8228                                         lun->per_res[i].registered = 0;
8229                                         memset(&lun->per_res[i].res_key,
8230                                                0,
8231                                                sizeof(struct scsi_per_res_key));
8232                                         lun->pr_key_count--;
8233
8234                                         if (!persis_offset
8235                                          && i < CTL_MAX_INITIATORS)
8236                                                 lun->pending_ua[i] |=
8237                                                         CTL_UA_REG_PREEMPT;
8238                                         else if (persis_offset
8239                                               && i >= persis_offset)
8240                                                 lun->pending_ua[i-persis_offset] |=
8241                                                   CTL_UA_REG_PREEMPT;
8242                                 } else if (type != lun->res_type
8243                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8244                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8245                                                 if (!persis_offset
8246                                                  && i < CTL_MAX_INITIATORS)
8247                                                         lun->pending_ua[i] |=
8248                                                         CTL_UA_RES_RELEASE;
8249                                                 else if (persis_offset
8250                                                       && i >= persis_offset)
8251                                                         lun->pending_ua[
8252                                                         i-persis_offset] |=
8253                                                         CTL_UA_RES_RELEASE;
8254                                 }
8255                         }
8256                         lun->per_res[residx].registered = 1;
8257                         lun->res_type = type;
8258                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8259                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8260                                 lun->pr_res_idx = residx;
8261                         else
8262                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8263
8264                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8265                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8266                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8267                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8268                         persis_io.pr.pr_info.res_type = type;
8269                         memcpy(persis_io.pr.pr_info.sa_res_key,
8270                                param->serv_act_res_key,
8271                                sizeof(param->serv_act_res_key));
8272                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8273                              &persis_io, sizeof(persis_io), 0)) >
8274                              CTL_HA_STATUS_SUCCESS) {
8275                                 printf("CTL:Persis Out error returned "
8276                                        "from ctl_ha_msg_send %d\n",
8277                                        isc_retval);
8278                         }
8279                 } else {
8280                         /*
8281                          * sa_res_key is not the res holder just
8282                          * remove registrants
8283                          */
8284                         int found=0;
8285
8286                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8287                                 if (memcmp(param->serv_act_res_key,
8288                                     lun->per_res[i].res_key.key,
8289                                     sizeof(struct scsi_per_res_key)) != 0)
8290                                         continue;
8291
8292                                 found = 1;
8293                                 lun->per_res[i].registered = 0;
8294                                 memset(&lun->per_res[i].res_key, 0,
8295                                        sizeof(struct scsi_per_res_key));
8296                                 lun->pr_key_count--;
8297
8298                                 if (!persis_offset
8299                                  && i < CTL_MAX_INITIATORS)
8300                                         lun->pending_ua[i] |=
8301                                                 CTL_UA_REG_PREEMPT;
8302                                 else if (persis_offset
8303                                       && i >= persis_offset)
8304                                         lun->pending_ua[i-persis_offset] |=
8305                                                 CTL_UA_REG_PREEMPT;
8306                         }
8307
8308                         if (!found) {
8309                                 mtx_unlock(&lun->lun_lock);
8310                                 free(ctsio->kern_data_ptr, M_CTL);
8311                                 ctl_set_reservation_conflict(ctsio);
8312                                 ctl_done((union ctl_io *)ctsio);
8313                                 return (1);
8314                         }
8315                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8316                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8317                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8318                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8319                         persis_io.pr.pr_info.res_type = type;
8320                         memcpy(persis_io.pr.pr_info.sa_res_key,
8321                                param->serv_act_res_key,
8322                                sizeof(param->serv_act_res_key));
8323                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8324                              &persis_io, sizeof(persis_io), 0)) >
8325                              CTL_HA_STATUS_SUCCESS) {
8326                                 printf("CTL:Persis Out error returned "
8327                                        "from ctl_ha_msg_send %d\n",
8328                                 isc_retval);
8329                         }
8330                 }
8331         }
8332
8333         lun->PRGeneration++;
8334         mtx_unlock(&lun->lun_lock);
8335
8336         return (retval);
8337 }
8338
8339 static void
8340 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8341 {
8342         int i;
8343
8344         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8345          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8346          || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8347                    msg->pr.pr_info.sa_res_key,
8348                    sizeof(struct scsi_per_res_key)) != 0) {
8349                 uint64_t sa_res_key;
8350                 sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8351
8352                 if (sa_res_key == 0) {
8353                         /* temporarily unregister this nexus */
8354                         lun->per_res[msg->pr.pr_info.residx].registered = 0;
8355
8356                         /*
8357                          * Unregister everybody else and build UA for
8358                          * them
8359                          */
8360                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8361                                 if (lun->per_res[i].registered == 0)
8362                                         continue;
8363
8364                                 if (!persis_offset
8365                                  && i < CTL_MAX_INITIATORS)
8366                                         lun->pending_ua[i] |=
8367                                                 CTL_UA_REG_PREEMPT;
8368                                 else if (persis_offset && i >= persis_offset)
8369                                         lun->pending_ua[i - persis_offset] |=
8370                                                 CTL_UA_REG_PREEMPT;
8371                                 lun->per_res[i].registered = 0;
8372                                 memset(&lun->per_res[i].res_key, 0,
8373                                        sizeof(struct scsi_per_res_key));
8374                         }
8375
8376                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8377                         lun->pr_key_count = 1;
8378                         lun->res_type = msg->pr.pr_info.res_type;
8379                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8380                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8381                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8382                 } else {
8383                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8384                                 if (memcmp(msg->pr.pr_info.sa_res_key,
8385                                    lun->per_res[i].res_key.key,
8386                                    sizeof(struct scsi_per_res_key)) != 0)
8387                                         continue;
8388
8389                                 lun->per_res[i].registered = 0;
8390                                 memset(&lun->per_res[i].res_key, 0,
8391                                        sizeof(struct scsi_per_res_key));
8392                                 lun->pr_key_count--;
8393
8394                                 if (!persis_offset
8395                                  && i < persis_offset)
8396                                         lun->pending_ua[i] |=
8397                                                 CTL_UA_REG_PREEMPT;
8398                                 else if (persis_offset
8399                                       && i >= persis_offset)
8400                                         lun->pending_ua[i - persis_offset] |=
8401                                                 CTL_UA_REG_PREEMPT;
8402                         }
8403                 }
8404         } else {
8405                 /*
8406                  * Temporarily unregister so it won't get removed
8407                  * or UA generated
8408                  */
8409                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8410                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8411                         if (lun->per_res[i].registered == 0)
8412                                 continue;
8413
8414                         if (memcmp(msg->pr.pr_info.sa_res_key,
8415                            lun->per_res[i].res_key.key,
8416                            sizeof(struct scsi_per_res_key)) == 0) {
8417                                 lun->per_res[i].registered = 0;
8418                                 memset(&lun->per_res[i].res_key, 0,
8419                                        sizeof(struct scsi_per_res_key));
8420                                 lun->pr_key_count--;
8421                                 if (!persis_offset
8422                                  && i < CTL_MAX_INITIATORS)
8423                                         lun->pending_ua[i] |=
8424                                                 CTL_UA_REG_PREEMPT;
8425                                 else if (persis_offset
8426                                       && i >= persis_offset)
8427                                         lun->pending_ua[i - persis_offset] |=
8428                                                 CTL_UA_REG_PREEMPT;
8429                         } else if (msg->pr.pr_info.res_type != lun->res_type
8430                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8431                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8432                                         if (!persis_offset
8433                                          && i < persis_offset)
8434                                                 lun->pending_ua[i] |=
8435                                                         CTL_UA_RES_RELEASE;
8436                                         else if (persis_offset
8437                                               && i >= persis_offset)
8438                                         lun->pending_ua[i - persis_offset] |=
8439                                                 CTL_UA_RES_RELEASE;
8440                         }
8441                 }
8442                 lun->per_res[msg->pr.pr_info.residx].registered = 1;
8443                 lun->res_type = msg->pr.pr_info.res_type;
8444                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8445                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8446                         lun->pr_res_idx = msg->pr.pr_info.residx;
8447                 else
8448                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8449         }
8450         lun->PRGeneration++;
8451
8452 }
8453
8454
8455 int
8456 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8457 {
8458         int retval;
8459         int isc_retval;
8460         u_int32_t param_len;
8461         struct scsi_per_res_out *cdb;
8462         struct ctl_lun *lun;
8463         struct scsi_per_res_out_parms* param;
8464         struct ctl_softc *softc;
8465         uint32_t residx;
8466         uint64_t res_key, sa_res_key;
8467         uint8_t type;
8468         union ctl_ha_msg persis_io;
8469         int    i;
8470
8471         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8472
8473         retval = CTL_RETVAL_COMPLETE;
8474
8475         softc = control_softc;
8476
8477         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8478         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8479
8480         /*
8481          * We only support whole-LUN scope.  The scope & type are ignored for
8482          * register, register and ignore existing key and clear.
8483          * We sometimes ignore scope and type on preempts too!!
8484          * Verify reservation type here as well.
8485          */
8486         type = cdb->scope_type & SPR_TYPE_MASK;
8487         if ((cdb->action == SPRO_RESERVE)
8488          || (cdb->action == SPRO_RELEASE)) {
8489                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8490                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8491                                               /*sks_valid*/ 1,
8492                                               /*command*/ 1,
8493                                               /*field*/ 2,
8494                                               /*bit_valid*/ 1,
8495                                               /*bit*/ 4);
8496                         ctl_done((union ctl_io *)ctsio);
8497                         return (CTL_RETVAL_COMPLETE);
8498                 }
8499
8500                 if (type>8 || type==2 || type==4 || type==0) {
8501                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8502                                               /*sks_valid*/ 1,
8503                                               /*command*/ 1,
8504                                               /*field*/ 2,
8505                                               /*bit_valid*/ 1,
8506                                               /*bit*/ 0);
8507                         ctl_done((union ctl_io *)ctsio);
8508                         return (CTL_RETVAL_COMPLETE);
8509                 }
8510         }
8511
8512         param_len = scsi_4btoul(cdb->length);
8513
8514         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8515                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8516                 ctsio->kern_data_len = param_len;
8517                 ctsio->kern_total_len = param_len;
8518                 ctsio->kern_data_resid = 0;
8519                 ctsio->kern_rel_offset = 0;
8520                 ctsio->kern_sg_entries = 0;
8521                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8522                 ctsio->be_move_done = ctl_config_move_done;
8523                 ctl_datamove((union ctl_io *)ctsio);
8524
8525                 return (CTL_RETVAL_COMPLETE);
8526         }
8527
8528         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8529
8530         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8531         res_key = scsi_8btou64(param->res_key.key);
8532         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8533
8534         /*
8535          * Validate the reservation key here except for SPRO_REG_IGNO
8536          * This must be done for all other service actions
8537          */
8538         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8539                 mtx_lock(&lun->lun_lock);
8540                 if (lun->per_res[residx].registered) {
8541                     if (memcmp(param->res_key.key,
8542                                lun->per_res[residx].res_key.key,
8543                                ctl_min(sizeof(param->res_key),
8544                                sizeof(lun->per_res[residx].res_key))) != 0) {
8545                                 /*
8546                                  * The current key passed in doesn't match
8547                                  * the one the initiator previously
8548                                  * registered.
8549                                  */
8550                                 mtx_unlock(&lun->lun_lock);
8551                                 free(ctsio->kern_data_ptr, M_CTL);
8552                                 ctl_set_reservation_conflict(ctsio);
8553                                 ctl_done((union ctl_io *)ctsio);
8554                                 return (CTL_RETVAL_COMPLETE);
8555                         }
8556                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8557                         /*
8558                          * We are not registered
8559                          */
8560                         mtx_unlock(&lun->lun_lock);
8561                         free(ctsio->kern_data_ptr, M_CTL);
8562                         ctl_set_reservation_conflict(ctsio);
8563                         ctl_done((union ctl_io *)ctsio);
8564                         return (CTL_RETVAL_COMPLETE);
8565                 } else if (res_key != 0) {
8566                         /*
8567                          * We are not registered and trying to register but
8568                          * the register key isn't zero.
8569                          */
8570                         mtx_unlock(&lun->lun_lock);
8571                         free(ctsio->kern_data_ptr, M_CTL);
8572                         ctl_set_reservation_conflict(ctsio);
8573                         ctl_done((union ctl_io *)ctsio);
8574                         return (CTL_RETVAL_COMPLETE);
8575                 }
8576                 mtx_unlock(&lun->lun_lock);
8577         }
8578
8579         switch (cdb->action & SPRO_ACTION_MASK) {
8580         case SPRO_REGISTER:
8581         case SPRO_REG_IGNO: {
8582
8583 #if 0
8584                 printf("Registration received\n");
8585 #endif
8586
8587                 /*
8588                  * We don't support any of these options, as we report in
8589                  * the read capabilities request (see
8590                  * ctl_persistent_reserve_in(), above).
8591                  */
8592                 if ((param->flags & SPR_SPEC_I_PT)
8593                  || (param->flags & SPR_ALL_TG_PT)
8594                  || (param->flags & SPR_APTPL)) {
8595                         int bit_ptr;
8596
8597                         if (param->flags & SPR_APTPL)
8598                                 bit_ptr = 0;
8599                         else if (param->flags & SPR_ALL_TG_PT)
8600                                 bit_ptr = 2;
8601                         else /* SPR_SPEC_I_PT */
8602                                 bit_ptr = 3;
8603
8604                         free(ctsio->kern_data_ptr, M_CTL);
8605                         ctl_set_invalid_field(ctsio,
8606                                               /*sks_valid*/ 1,
8607                                               /*command*/ 0,
8608                                               /*field*/ 20,
8609                                               /*bit_valid*/ 1,
8610                                               /*bit*/ bit_ptr);
8611                         ctl_done((union ctl_io *)ctsio);
8612                         return (CTL_RETVAL_COMPLETE);
8613                 }
8614
8615                 mtx_lock(&lun->lun_lock);
8616
8617                 /*
8618                  * The initiator wants to clear the
8619                  * key/unregister.
8620                  */
8621                 if (sa_res_key == 0) {
8622                         if ((res_key == 0
8623                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8624                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8625                           && !lun->per_res[residx].registered)) {
8626                                 mtx_unlock(&lun->lun_lock);
8627                                 goto done;
8628                         }
8629
8630                         lun->per_res[residx].registered = 0;
8631                         memset(&lun->per_res[residx].res_key,
8632                                0, sizeof(lun->per_res[residx].res_key));
8633                         lun->pr_key_count--;
8634
8635                         if (residx == lun->pr_res_idx) {
8636                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8637                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8638
8639                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8640                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8641                                  && lun->pr_key_count) {
8642                                         /*
8643                                          * If the reservation is a registrants
8644                                          * only type we need to generate a UA
8645                                          * for other registered inits.  The
8646                                          * sense code should be RESERVATIONS
8647                                          * RELEASED
8648                                          */
8649
8650                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8651                                                 if (lun->per_res[
8652                                                     i+persis_offset].registered
8653                                                     == 0)
8654                                                         continue;
8655                                                 lun->pending_ua[i] |=
8656                                                         CTL_UA_RES_RELEASE;
8657                                         }
8658                                 }
8659                                 lun->res_type = 0;
8660                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8661                                 if (lun->pr_key_count==0) {
8662                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8663                                         lun->res_type = 0;
8664                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8665                                 }
8666                         }
8667                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8668                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8669                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8670                         persis_io.pr.pr_info.residx = residx;
8671                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8672                              &persis_io, sizeof(persis_io), 0 )) >
8673                              CTL_HA_STATUS_SUCCESS) {
8674                                 printf("CTL:Persis Out error returned from "
8675                                        "ctl_ha_msg_send %d\n", isc_retval);
8676                         }
8677                 } else /* sa_res_key != 0 */ {
8678
8679                         /*
8680                          * If we aren't registered currently then increment
8681                          * the key count and set the registered flag.
8682                          */
8683                         if (!lun->per_res[residx].registered) {
8684                                 lun->pr_key_count++;
8685                                 lun->per_res[residx].registered = 1;
8686                         }
8687
8688                         memcpy(&lun->per_res[residx].res_key,
8689                                param->serv_act_res_key,
8690                                ctl_min(sizeof(param->serv_act_res_key),
8691                                sizeof(lun->per_res[residx].res_key)));
8692
8693                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8694                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8695                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8696                         persis_io.pr.pr_info.residx = residx;
8697                         memcpy(persis_io.pr.pr_info.sa_res_key,
8698                                param->serv_act_res_key,
8699                                sizeof(param->serv_act_res_key));
8700                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8701                              &persis_io, sizeof(persis_io), 0)) >
8702                              CTL_HA_STATUS_SUCCESS) {
8703                                 printf("CTL:Persis Out error returned from "
8704                                        "ctl_ha_msg_send %d\n", isc_retval);
8705                         }
8706                 }
8707                 lun->PRGeneration++;
8708                 mtx_unlock(&lun->lun_lock);
8709
8710                 break;
8711         }
8712         case SPRO_RESERVE:
8713 #if 0
8714                 printf("Reserve executed type %d\n", type);
8715 #endif
8716                 mtx_lock(&lun->lun_lock);
8717                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8718                         /*
8719                          * if this isn't the reservation holder and it's
8720                          * not a "all registrants" type or if the type is
8721                          * different then we have a conflict
8722                          */
8723                         if ((lun->pr_res_idx != residx
8724                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8725                          || lun->res_type != type) {
8726                                 mtx_unlock(&lun->lun_lock);
8727                                 free(ctsio->kern_data_ptr, M_CTL);
8728                                 ctl_set_reservation_conflict(ctsio);
8729                                 ctl_done((union ctl_io *)ctsio);
8730                                 return (CTL_RETVAL_COMPLETE);
8731                         }
8732                         mtx_unlock(&lun->lun_lock);
8733                 } else /* create a reservation */ {
8734                         /*
8735                          * If it's not an "all registrants" type record
8736                          * reservation holder
8737                          */
8738                         if (type != SPR_TYPE_WR_EX_AR
8739                          && type != SPR_TYPE_EX_AC_AR)
8740                                 lun->pr_res_idx = residx; /* Res holder */
8741                         else
8742                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8743
8744                         lun->flags |= CTL_LUN_PR_RESERVED;
8745                         lun->res_type = type;
8746
8747                         mtx_unlock(&lun->lun_lock);
8748
8749                         /* send msg to other side */
8750                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8751                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8752                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8753                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8754                         persis_io.pr.pr_info.res_type = type;
8755                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8756                              &persis_io, sizeof(persis_io), 0)) >
8757                              CTL_HA_STATUS_SUCCESS) {
8758                                 printf("CTL:Persis Out error returned from "
8759                                        "ctl_ha_msg_send %d\n", isc_retval);
8760                         }
8761                 }
8762                 break;
8763
8764         case SPRO_RELEASE:
8765                 mtx_lock(&lun->lun_lock);
8766                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8767                         /* No reservation exists return good status */
8768                         mtx_unlock(&lun->lun_lock);
8769                         goto done;
8770                 }
8771                 /*
8772                  * Is this nexus a reservation holder?
8773                  */
8774                 if (lun->pr_res_idx != residx
8775                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8776                         /*
8777                          * not a res holder return good status but
8778                          * do nothing
8779                          */
8780                         mtx_unlock(&lun->lun_lock);
8781                         goto done;
8782                 }
8783
8784                 if (lun->res_type != type) {
8785                         mtx_unlock(&lun->lun_lock);
8786                         free(ctsio->kern_data_ptr, M_CTL);
8787                         ctl_set_illegal_pr_release(ctsio);
8788                         ctl_done((union ctl_io *)ctsio);
8789                         return (CTL_RETVAL_COMPLETE);
8790                 }
8791
8792                 /* okay to release */
8793                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8794                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8795                 lun->res_type = 0;
8796
8797                 /*
8798                  * if this isn't an exclusive access
8799                  * res generate UA for all other
8800                  * registrants.
8801                  */
8802                 if (type != SPR_TYPE_EX_AC
8803                  && type != SPR_TYPE_WR_EX) {
8804                         /*
8805                          * temporarily unregister so we don't generate UA
8806                          */
8807                         lun->per_res[residx].registered = 0;
8808
8809                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8810                                 if (lun->per_res[i+persis_offset].registered
8811                                     == 0)
8812                                         continue;
8813                                 lun->pending_ua[i] |=
8814                                         CTL_UA_RES_RELEASE;
8815                         }
8816
8817                         lun->per_res[residx].registered = 1;
8818                 }
8819                 mtx_unlock(&lun->lun_lock);
8820                 /* Send msg to other side */
8821                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8822                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8823                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8824                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8825                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8826                         printf("CTL:Persis Out error returned from "
8827                                "ctl_ha_msg_send %d\n", isc_retval);
8828                 }
8829                 break;
8830
8831         case SPRO_CLEAR:
8832                 /* send msg to other side */
8833
8834                 mtx_lock(&lun->lun_lock);
8835                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8836                 lun->res_type = 0;
8837                 lun->pr_key_count = 0;
8838                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8839
8840
8841                 memset(&lun->per_res[residx].res_key,
8842                        0, sizeof(lun->per_res[residx].res_key));
8843                 lun->per_res[residx].registered = 0;
8844
8845                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8846                         if (lun->per_res[i].registered) {
8847                                 if (!persis_offset && i < CTL_MAX_INITIATORS)
8848                                         lun->pending_ua[i] |=
8849                                                 CTL_UA_RES_PREEMPT;
8850                                 else if (persis_offset && i >= persis_offset)
8851                                         lun->pending_ua[i-persis_offset] |=
8852                                             CTL_UA_RES_PREEMPT;
8853
8854                                 memset(&lun->per_res[i].res_key,
8855                                        0, sizeof(struct scsi_per_res_key));
8856                                 lun->per_res[i].registered = 0;
8857                         }
8858                 lun->PRGeneration++;
8859                 mtx_unlock(&lun->lun_lock);
8860                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8861                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8862                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8863                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8864                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8865                         printf("CTL:Persis Out error returned from "
8866                                "ctl_ha_msg_send %d\n", isc_retval);
8867                 }
8868                 break;
8869
8870         case SPRO_PREEMPT: {
8871                 int nretval;
8872
8873                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8874                                           residx, ctsio, cdb, param);
8875                 if (nretval != 0)
8876                         return (CTL_RETVAL_COMPLETE);
8877                 break;
8878         }
8879         default:
8880                 panic("Invalid PR type %x", cdb->action);
8881         }
8882
8883 done:
8884         free(ctsio->kern_data_ptr, M_CTL);
8885         ctl_set_success(ctsio);
8886         ctl_done((union ctl_io *)ctsio);
8887
8888         return (retval);
8889 }
8890
8891 /*
8892  * This routine is for handling a message from the other SC pertaining to
8893  * persistent reserve out. All the error checking will have been done
8894  * so only perorming the action need be done here to keep the two
8895  * in sync.
8896  */
8897 static void
8898 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8899 {
8900         struct ctl_lun *lun;
8901         struct ctl_softc *softc;
8902         int i;
8903         uint32_t targ_lun;
8904
8905         softc = control_softc;
8906
8907         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8908         lun = softc->ctl_luns[targ_lun];
8909         mtx_lock(&lun->lun_lock);
8910         switch(msg->pr.pr_info.action) {
8911         case CTL_PR_REG_KEY:
8912                 if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8913                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8914                         lun->pr_key_count++;
8915                 }
8916                 lun->PRGeneration++;
8917                 memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8918                        msg->pr.pr_info.sa_res_key,
8919                        sizeof(struct scsi_per_res_key));
8920                 break;
8921
8922         case CTL_PR_UNREG_KEY:
8923                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8924                 memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8925                        0, sizeof(struct scsi_per_res_key));
8926                 lun->pr_key_count--;
8927
8928                 /* XXX Need to see if the reservation has been released */
8929                 /* if so do we need to generate UA? */
8930                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8931                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8932                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8933
8934                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8935                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8936                          && lun->pr_key_count) {
8937                                 /*
8938                                  * If the reservation is a registrants
8939                                  * only type we need to generate a UA
8940                                  * for other registered inits.  The
8941                                  * sense code should be RESERVATIONS
8942                                  * RELEASED
8943                                  */
8944
8945                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8946                                         if (lun->per_res[i+
8947                                             persis_offset].registered == 0)
8948                                                 continue;
8949
8950                                         lun->pending_ua[i] |=
8951                                                 CTL_UA_RES_RELEASE;
8952                                 }
8953                         }
8954                         lun->res_type = 0;
8955                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8956                         if (lun->pr_key_count==0) {
8957                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8958                                 lun->res_type = 0;
8959                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8960                         }
8961                 }
8962                 lun->PRGeneration++;
8963                 break;
8964
8965         case CTL_PR_RESERVE:
8966                 lun->flags |= CTL_LUN_PR_RESERVED;
8967                 lun->res_type = msg->pr.pr_info.res_type;
8968                 lun->pr_res_idx = msg->pr.pr_info.residx;
8969
8970                 break;
8971
8972         case CTL_PR_RELEASE:
8973                 /*
8974                  * if this isn't an exclusive access res generate UA for all
8975                  * other registrants.
8976                  */
8977                 if (lun->res_type != SPR_TYPE_EX_AC
8978                  && lun->res_type != SPR_TYPE_WR_EX) {
8979                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8980                                 if (lun->per_res[i+persis_offset].registered)
8981                                         lun->pending_ua[i] |=
8982                                                 CTL_UA_RES_RELEASE;
8983                 }
8984
8985                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8986                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8987                 lun->res_type = 0;
8988                 break;
8989
8990         case CTL_PR_PREEMPT:
8991                 ctl_pro_preempt_other(lun, msg);
8992                 break;
8993         case CTL_PR_CLEAR:
8994                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8995                 lun->res_type = 0;
8996                 lun->pr_key_count = 0;
8997                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8998
8999                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9000                         if (lun->per_res[i].registered == 0)
9001                                 continue;
9002                         if (!persis_offset
9003                          && i < CTL_MAX_INITIATORS)
9004                                 lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9005                         else if (persis_offset
9006                               && i >= persis_offset)
9007                                 lun->pending_ua[i-persis_offset] |=
9008                                         CTL_UA_RES_PREEMPT;
9009                         memset(&lun->per_res[i].res_key, 0,
9010                                sizeof(struct scsi_per_res_key));
9011                         lun->per_res[i].registered = 0;
9012                 }
9013                 lun->PRGeneration++;
9014                 break;
9015         }
9016
9017         mtx_unlock(&lun->lun_lock);
9018 }
9019
9020 int
9021 ctl_read_write(struct ctl_scsiio *ctsio)
9022 {
9023         struct ctl_lun *lun;
9024         struct ctl_lba_len_flags *lbalen;
9025         uint64_t lba;
9026         uint32_t num_blocks;
9027         int flags, retval;
9028         int isread;
9029
9030         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9031
9032         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9033
9034         flags = 0;
9035         retval = CTL_RETVAL_COMPLETE;
9036
9037         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9038               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9039         if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9040                 uint32_t residx;
9041
9042                 /*
9043                  * XXX KDM need a lock here.
9044                  */
9045                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9046                 if ((lun->res_type == SPR_TYPE_EX_AC
9047                   && residx != lun->pr_res_idx)
9048                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
9049                    || lun->res_type == SPR_TYPE_EX_AC_AR)
9050                   && !lun->per_res[residx].registered)) {
9051                         ctl_set_reservation_conflict(ctsio);
9052                         ctl_done((union ctl_io *)ctsio);
9053                         return (CTL_RETVAL_COMPLETE);
9054                 }
9055         }
9056
9057         switch (ctsio->cdb[0]) {
9058         case READ_6:
9059         case WRITE_6: {
9060                 struct scsi_rw_6 *cdb;
9061
9062                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
9063
9064                 lba = scsi_3btoul(cdb->addr);
9065                 /* only 5 bits are valid in the most significant address byte */
9066                 lba &= 0x1fffff;
9067                 num_blocks = cdb->length;
9068                 /*
9069                  * This is correct according to SBC-2.
9070                  */
9071                 if (num_blocks == 0)
9072                         num_blocks = 256;
9073                 break;
9074         }
9075         case READ_10:
9076         case WRITE_10: {
9077                 struct scsi_rw_10 *cdb;
9078
9079                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9080                 if (cdb->byte2 & SRW10_FUA)
9081                         flags |= CTL_LLF_FUA;
9082                 if (cdb->byte2 & SRW10_DPO)
9083                         flags |= CTL_LLF_DPO;
9084                 lba = scsi_4btoul(cdb->addr);
9085                 num_blocks = scsi_2btoul(cdb->length);
9086                 break;
9087         }
9088         case WRITE_VERIFY_10: {
9089                 struct scsi_write_verify_10 *cdb;
9090
9091                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9092                 flags |= CTL_LLF_FUA;
9093                 if (cdb->byte2 & SWV_DPO)
9094                         flags |= CTL_LLF_DPO;
9095                 lba = scsi_4btoul(cdb->addr);
9096                 num_blocks = scsi_2btoul(cdb->length);
9097                 break;
9098         }
9099         case READ_12:
9100         case WRITE_12: {
9101                 struct scsi_rw_12 *cdb;
9102
9103                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9104                 if (cdb->byte2 & SRW12_FUA)
9105                         flags |= CTL_LLF_FUA;
9106                 if (cdb->byte2 & SRW12_DPO)
9107                         flags |= CTL_LLF_DPO;
9108                 lba = scsi_4btoul(cdb->addr);
9109                 num_blocks = scsi_4btoul(cdb->length);
9110                 break;
9111         }
9112         case WRITE_VERIFY_12: {
9113                 struct scsi_write_verify_12 *cdb;
9114
9115                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9116                 flags |= CTL_LLF_FUA;
9117                 if (cdb->byte2 & SWV_DPO)
9118                         flags |= CTL_LLF_DPO;
9119                 lba = scsi_4btoul(cdb->addr);
9120                 num_blocks = scsi_4btoul(cdb->length);
9121                 break;
9122         }
9123         case READ_16:
9124         case WRITE_16: {
9125                 struct scsi_rw_16 *cdb;
9126
9127                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9128                 if (cdb->byte2 & SRW12_FUA)
9129                         flags |= CTL_LLF_FUA;
9130                 if (cdb->byte2 & SRW12_DPO)
9131                         flags |= CTL_LLF_DPO;
9132                 lba = scsi_8btou64(cdb->addr);
9133                 num_blocks = scsi_4btoul(cdb->length);
9134                 break;
9135         }
9136         case WRITE_VERIFY_16: {
9137                 struct scsi_write_verify_16 *cdb;
9138
9139                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9140                 flags |= CTL_LLF_FUA;
9141                 if (cdb->byte2 & SWV_DPO)
9142                         flags |= CTL_LLF_DPO;
9143                 lba = scsi_8btou64(cdb->addr);
9144                 num_blocks = scsi_4btoul(cdb->length);
9145                 break;
9146         }
9147         default:
9148                 /*
9149                  * We got a command we don't support.  This shouldn't
9150                  * happen, commands should be filtered out above us.
9151                  */
9152                 ctl_set_invalid_opcode(ctsio);
9153                 ctl_done((union ctl_io *)ctsio);
9154
9155                 return (CTL_RETVAL_COMPLETE);
9156                 break; /* NOTREACHED */
9157         }
9158
9159         /*
9160          * The first check is to make sure we're in bounds, the second
9161          * check is to catch wrap-around problems.  If the lba + num blocks
9162          * is less than the lba, then we've wrapped around and the block
9163          * range is invalid anyway.
9164          */
9165         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9166          || ((lba + num_blocks) < lba)) {
9167                 ctl_set_lba_out_of_range(ctsio);
9168                 ctl_done((union ctl_io *)ctsio);
9169                 return (CTL_RETVAL_COMPLETE);
9170         }
9171
9172         /*
9173          * According to SBC-3, a transfer length of 0 is not an error.
9174          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9175          * translates to 256 blocks for those commands.
9176          */
9177         if (num_blocks == 0) {
9178                 ctl_set_success(ctsio);
9179                 ctl_done((union ctl_io *)ctsio);
9180                 return (CTL_RETVAL_COMPLETE);
9181         }
9182
9183         /* Set FUA and/or DPO if caches are disabled. */
9184         if (isread) {
9185                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9186                     SCP_RCD) != 0)
9187                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9188         } else {
9189                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9190                     SCP_WCE) == 0)
9191                         flags |= CTL_LLF_FUA;
9192         }
9193
9194         lbalen = (struct ctl_lba_len_flags *)
9195             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9196         lbalen->lba = lba;
9197         lbalen->len = num_blocks;
9198         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9199
9200         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9201         ctsio->kern_rel_offset = 0;
9202
9203         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9204
9205         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9206
9207         return (retval);
9208 }
9209
9210 static int
9211 ctl_cnw_cont(union ctl_io *io)
9212 {
9213         struct ctl_scsiio *ctsio;
9214         struct ctl_lun *lun;
9215         struct ctl_lba_len_flags *lbalen;
9216         int retval;
9217
9218         ctsio = &io->scsiio;
9219         ctsio->io_hdr.status = CTL_STATUS_NONE;
9220         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9221         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9222         lbalen = (struct ctl_lba_len_flags *)
9223             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9224         lbalen->flags &= ~CTL_LLF_COMPARE;
9225         lbalen->flags |= CTL_LLF_WRITE;
9226
9227         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9228         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9229         return (retval);
9230 }
9231
9232 int
9233 ctl_cnw(struct ctl_scsiio *ctsio)
9234 {
9235         struct ctl_lun *lun;
9236         struct ctl_lba_len_flags *lbalen;
9237         uint64_t lba;
9238         uint32_t num_blocks;
9239         int flags, retval;
9240
9241         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9242
9243         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9244
9245         flags = 0;
9246         retval = CTL_RETVAL_COMPLETE;
9247
9248         switch (ctsio->cdb[0]) {
9249         case COMPARE_AND_WRITE: {
9250                 struct scsi_compare_and_write *cdb;
9251
9252                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9253                 if (cdb->byte2 & SRW10_FUA)
9254                         flags |= CTL_LLF_FUA;
9255                 if (cdb->byte2 & SRW10_DPO)
9256                         flags |= CTL_LLF_DPO;
9257                 lba = scsi_8btou64(cdb->addr);
9258                 num_blocks = cdb->length;
9259                 break;
9260         }
9261         default:
9262                 /*
9263                  * We got a command we don't support.  This shouldn't
9264                  * happen, commands should be filtered out above us.
9265                  */
9266                 ctl_set_invalid_opcode(ctsio);
9267                 ctl_done((union ctl_io *)ctsio);
9268
9269                 return (CTL_RETVAL_COMPLETE);
9270                 break; /* NOTREACHED */
9271         }
9272
9273         /*
9274          * The first check is to make sure we're in bounds, the second
9275          * check is to catch wrap-around problems.  If the lba + num blocks
9276          * is less than the lba, then we've wrapped around and the block
9277          * range is invalid anyway.
9278          */
9279         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9280          || ((lba + num_blocks) < lba)) {
9281                 ctl_set_lba_out_of_range(ctsio);
9282                 ctl_done((union ctl_io *)ctsio);
9283                 return (CTL_RETVAL_COMPLETE);
9284         }
9285
9286         /*
9287          * According to SBC-3, a transfer length of 0 is not an error.
9288          */
9289         if (num_blocks == 0) {
9290                 ctl_set_success(ctsio);
9291                 ctl_done((union ctl_io *)ctsio);
9292                 return (CTL_RETVAL_COMPLETE);
9293         }
9294
9295         /* Set FUA if write cache is disabled. */
9296         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9297             SCP_WCE) == 0)
9298                 flags |= CTL_LLF_FUA;
9299
9300         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9301         ctsio->kern_rel_offset = 0;
9302
9303         /*
9304          * Set the IO_CONT flag, so that if this I/O gets passed to
9305          * ctl_data_submit_done(), it'll get passed back to
9306          * ctl_ctl_cnw_cont() for further processing.
9307          */
9308         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9309         ctsio->io_cont = ctl_cnw_cont;
9310
9311         lbalen = (struct ctl_lba_len_flags *)
9312             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9313         lbalen->lba = lba;
9314         lbalen->len = num_blocks;
9315         lbalen->flags = CTL_LLF_COMPARE | flags;
9316
9317         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9318         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9319         return (retval);
9320 }
9321
9322 int
9323 ctl_verify(struct ctl_scsiio *ctsio)
9324 {
9325         struct ctl_lun *lun;
9326         struct ctl_lba_len_flags *lbalen;
9327         uint64_t lba;
9328         uint32_t num_blocks;
9329         int bytchk, flags;
9330         int retval;
9331
9332         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9333
9334         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9335
9336         bytchk = 0;
9337         flags = CTL_LLF_FUA;
9338         retval = CTL_RETVAL_COMPLETE;
9339
9340         switch (ctsio->cdb[0]) {
9341         case VERIFY_10: {
9342                 struct scsi_verify_10 *cdb;
9343
9344                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9345                 if (cdb->byte2 & SVFY_BYTCHK)
9346                         bytchk = 1;
9347                 if (cdb->byte2 & SVFY_DPO)
9348                         flags |= CTL_LLF_DPO;
9349                 lba = scsi_4btoul(cdb->addr);
9350                 num_blocks = scsi_2btoul(cdb->length);
9351                 break;
9352         }
9353         case VERIFY_12: {
9354                 struct scsi_verify_12 *cdb;
9355
9356                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9357                 if (cdb->byte2 & SVFY_BYTCHK)
9358                         bytchk = 1;
9359                 if (cdb->byte2 & SVFY_DPO)
9360                         flags |= CTL_LLF_DPO;
9361                 lba = scsi_4btoul(cdb->addr);
9362                 num_blocks = scsi_4btoul(cdb->length);
9363                 break;
9364         }
9365         case VERIFY_16: {
9366                 struct scsi_rw_16 *cdb;
9367
9368                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9369                 if (cdb->byte2 & SVFY_BYTCHK)
9370                         bytchk = 1;
9371                 if (cdb->byte2 & SVFY_DPO)
9372                         flags |= CTL_LLF_DPO;
9373                 lba = scsi_8btou64(cdb->addr);
9374                 num_blocks = scsi_4btoul(cdb->length);
9375                 break;
9376         }
9377         default:
9378                 /*
9379                  * We got a command we don't support.  This shouldn't
9380                  * happen, commands should be filtered out above us.
9381                  */
9382                 ctl_set_invalid_opcode(ctsio);
9383                 ctl_done((union ctl_io *)ctsio);
9384                 return (CTL_RETVAL_COMPLETE);
9385         }
9386
9387         /*
9388          * The first check is to make sure we're in bounds, the second
9389          * check is to catch wrap-around problems.  If the lba + num blocks
9390          * is less than the lba, then we've wrapped around and the block
9391          * range is invalid anyway.
9392          */
9393         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9394          || ((lba + num_blocks) < lba)) {
9395                 ctl_set_lba_out_of_range(ctsio);
9396                 ctl_done((union ctl_io *)ctsio);
9397                 return (CTL_RETVAL_COMPLETE);
9398         }
9399
9400         /*
9401          * According to SBC-3, a transfer length of 0 is not an error.
9402          */
9403         if (num_blocks == 0) {
9404                 ctl_set_success(ctsio);
9405                 ctl_done((union ctl_io *)ctsio);
9406                 return (CTL_RETVAL_COMPLETE);
9407         }
9408
9409         lbalen = (struct ctl_lba_len_flags *)
9410             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9411         lbalen->lba = lba;
9412         lbalen->len = num_blocks;
9413         if (bytchk) {
9414                 lbalen->flags = CTL_LLF_COMPARE | flags;
9415                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9416         } else {
9417                 lbalen->flags = CTL_LLF_VERIFY | flags;
9418                 ctsio->kern_total_len = 0;
9419         }
9420         ctsio->kern_rel_offset = 0;
9421
9422         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9423         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9424         return (retval);
9425 }
9426
9427 int
9428 ctl_report_luns(struct ctl_scsiio *ctsio)
9429 {
9430         struct scsi_report_luns *cdb;
9431         struct scsi_report_luns_data *lun_data;
9432         struct ctl_lun *lun, *request_lun;
9433         int num_luns, retval;
9434         uint32_t alloc_len, lun_datalen;
9435         int num_filled, well_known;
9436         uint32_t initidx, targ_lun_id, lun_id;
9437
9438         retval = CTL_RETVAL_COMPLETE;
9439         well_known = 0;
9440
9441         cdb = (struct scsi_report_luns *)ctsio->cdb;
9442
9443         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9444
9445         mtx_lock(&control_softc->ctl_lock);
9446         num_luns = control_softc->num_luns;
9447         mtx_unlock(&control_softc->ctl_lock);
9448
9449         switch (cdb->select_report) {
9450         case RPL_REPORT_DEFAULT:
9451         case RPL_REPORT_ALL:
9452                 break;
9453         case RPL_REPORT_WELLKNOWN:
9454                 well_known = 1;
9455                 num_luns = 0;
9456                 break;
9457         default:
9458                 ctl_set_invalid_field(ctsio,
9459                                       /*sks_valid*/ 1,
9460                                       /*command*/ 1,
9461                                       /*field*/ 2,
9462                                       /*bit_valid*/ 0,
9463                                       /*bit*/ 0);
9464                 ctl_done((union ctl_io *)ctsio);
9465                 return (retval);
9466                 break; /* NOTREACHED */
9467         }
9468
9469         alloc_len = scsi_4btoul(cdb->length);
9470         /*
9471          * The initiator has to allocate at least 16 bytes for this request,
9472          * so he can at least get the header and the first LUN.  Otherwise
9473          * we reject the request (per SPC-3 rev 14, section 6.21).
9474          */
9475         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9476             sizeof(struct scsi_report_luns_lundata))) {
9477                 ctl_set_invalid_field(ctsio,
9478                                       /*sks_valid*/ 1,
9479                                       /*command*/ 1,
9480                                       /*field*/ 6,
9481                                       /*bit_valid*/ 0,
9482                                       /*bit*/ 0);
9483                 ctl_done((union ctl_io *)ctsio);
9484                 return (retval);
9485         }
9486
9487         request_lun = (struct ctl_lun *)
9488                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9489
9490         lun_datalen = sizeof(*lun_data) +
9491                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9492
9493         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9494         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9495         ctsio->kern_sg_entries = 0;
9496
9497         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9498
9499         mtx_lock(&control_softc->ctl_lock);
9500         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9501                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9502                 if (lun_id >= CTL_MAX_LUNS)
9503                         continue;
9504                 lun = control_softc->ctl_luns[lun_id];
9505                 if (lun == NULL)
9506                         continue;
9507
9508                 if (targ_lun_id <= 0xff) {
9509                         /*
9510                          * Peripheral addressing method, bus number 0.
9511                          */
9512                         lun_data->luns[num_filled].lundata[0] =
9513                                 RPL_LUNDATA_ATYP_PERIPH;
9514                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9515                         num_filled++;
9516                 } else if (targ_lun_id <= 0x3fff) {
9517                         /*
9518                          * Flat addressing method.
9519                          */
9520                         lun_data->luns[num_filled].lundata[0] =
9521                                 RPL_LUNDATA_ATYP_FLAT |
9522                                 (targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9523 #ifdef OLDCTLHEADERS
9524                                 (SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9525                                 (targ_lun_id & SRLD_BUS_LUN_MASK);
9526 #endif
9527                         lun_data->luns[num_filled].lundata[1] =
9528 #ifdef OLDCTLHEADERS
9529                                 targ_lun_id >> SRLD_BUS_LUN_BITS;
9530 #endif
9531                                 targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9532                         num_filled++;
9533                 } else {
9534                         printf("ctl_report_luns: bogus LUN number %jd, "
9535                                "skipping\n", (intmax_t)targ_lun_id);
9536                 }
9537                 /*
9538                  * According to SPC-3, rev 14 section 6.21:
9539                  *
9540                  * "The execution of a REPORT LUNS command to any valid and
9541                  * installed logical unit shall clear the REPORTED LUNS DATA
9542                  * HAS CHANGED unit attention condition for all logical
9543                  * units of that target with respect to the requesting
9544                  * initiator. A valid and installed logical unit is one
9545                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9546                  * INQUIRY data (see 6.4.2)."
9547                  *
9548                  * If request_lun is NULL, the LUN this report luns command
9549                  * was issued to is either disabled or doesn't exist. In that
9550                  * case, we shouldn't clear any pending lun change unit
9551                  * attention.
9552                  */
9553                 if (request_lun != NULL) {
9554                         mtx_lock(&lun->lun_lock);
9555                         lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9556                         mtx_unlock(&lun->lun_lock);
9557                 }
9558         }
9559         mtx_unlock(&control_softc->ctl_lock);
9560
9561         /*
9562          * It's quite possible that we've returned fewer LUNs than we allocated
9563          * space for.  Trim it.
9564          */
9565         lun_datalen = sizeof(*lun_data) +
9566                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9567
9568         if (lun_datalen < alloc_len) {
9569                 ctsio->residual = alloc_len - lun_datalen;
9570                 ctsio->kern_data_len = lun_datalen;
9571                 ctsio->kern_total_len = lun_datalen;
9572         } else {
9573                 ctsio->residual = 0;
9574                 ctsio->kern_data_len = alloc_len;
9575                 ctsio->kern_total_len = alloc_len;
9576         }
9577         ctsio->kern_data_resid = 0;
9578         ctsio->kern_rel_offset = 0;
9579         ctsio->kern_sg_entries = 0;
9580
9581         /*
9582          * We set this to the actual data length, regardless of how much
9583          * space we actually have to return results.  If the user looks at
9584          * this value, he'll know whether or not he allocated enough space
9585          * and reissue the command if necessary.  We don't support well
9586          * known logical units, so if the user asks for that, return none.
9587          */
9588         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9589
9590         /*
9591          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9592          * this request.
9593          */
9594         ctsio->scsi_status = SCSI_STATUS_OK;
9595
9596         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9597         ctsio->be_move_done = ctl_config_move_done;
9598         ctl_datamove((union ctl_io *)ctsio);
9599
9600         return (retval);
9601 }
9602
9603 int
9604 ctl_request_sense(struct ctl_scsiio *ctsio)
9605 {
9606         struct scsi_request_sense *cdb;
9607         struct scsi_sense_data *sense_ptr;
9608         struct ctl_lun *lun;
9609         uint32_t initidx;
9610         int have_error;
9611         scsi_sense_data_type sense_format;
9612
9613         cdb = (struct scsi_request_sense *)ctsio->cdb;
9614
9615         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9616
9617         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9618
9619         /*
9620          * Determine which sense format the user wants.
9621          */
9622         if (cdb->byte2 & SRS_DESC)
9623                 sense_format = SSD_TYPE_DESC;
9624         else
9625                 sense_format = SSD_TYPE_FIXED;
9626
9627         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9628         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9629         ctsio->kern_sg_entries = 0;
9630
9631         /*
9632          * struct scsi_sense_data, which is currently set to 256 bytes, is
9633          * larger than the largest allowed value for the length field in the
9634          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9635          */
9636         ctsio->residual = 0;
9637         ctsio->kern_data_len = cdb->length;
9638         ctsio->kern_total_len = cdb->length;
9639
9640         ctsio->kern_data_resid = 0;
9641         ctsio->kern_rel_offset = 0;
9642         ctsio->kern_sg_entries = 0;
9643
9644         /*
9645          * If we don't have a LUN, we don't have any pending sense.
9646          */
9647         if (lun == NULL)
9648                 goto no_sense;
9649
9650         have_error = 0;
9651         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9652         /*
9653          * Check for pending sense, and then for pending unit attentions.
9654          * Pending sense gets returned first, then pending unit attentions.
9655          */
9656         mtx_lock(&lun->lun_lock);
9657 #ifdef CTL_WITH_CA
9658         if (ctl_is_set(lun->have_ca, initidx)) {
9659                 scsi_sense_data_type stored_format;
9660
9661                 /*
9662                  * Check to see which sense format was used for the stored
9663                  * sense data.
9664                  */
9665                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9666
9667                 /*
9668                  * If the user requested a different sense format than the
9669                  * one we stored, then we need to convert it to the other
9670                  * format.  If we're going from descriptor to fixed format
9671                  * sense data, we may lose things in translation, depending
9672                  * on what options were used.
9673                  *
9674                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9675                  * for some reason we'll just copy it out as-is.
9676                  */
9677                 if ((stored_format == SSD_TYPE_FIXED)
9678                  && (sense_format == SSD_TYPE_DESC))
9679                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9680                             &lun->pending_sense[initidx],
9681                             (struct scsi_sense_data_desc *)sense_ptr);
9682                 else if ((stored_format == SSD_TYPE_DESC)
9683                       && (sense_format == SSD_TYPE_FIXED))
9684                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9685                             &lun->pending_sense[initidx],
9686                             (struct scsi_sense_data_fixed *)sense_ptr);
9687                 else
9688                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9689                                ctl_min(sizeof(*sense_ptr),
9690                                sizeof(lun->pending_sense[initidx])));
9691
9692                 ctl_clear_mask(lun->have_ca, initidx);
9693                 have_error = 1;
9694         } else
9695 #endif
9696         if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9697                 ctl_ua_type ua_type;
9698
9699                 ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9700                                        sense_ptr, sense_format);
9701                 if (ua_type != CTL_UA_NONE)
9702                         have_error = 1;
9703         }
9704         mtx_unlock(&lun->lun_lock);
9705
9706         /*
9707          * We already have a pending error, return it.
9708          */
9709         if (have_error != 0) {
9710                 /*
9711                  * We report the SCSI status as OK, since the status of the
9712                  * request sense command itself is OK.
9713                  */
9714                 ctsio->scsi_status = SCSI_STATUS_OK;
9715
9716                 /*
9717                  * We report 0 for the sense length, because we aren't doing
9718                  * autosense in this case.  We're reporting sense as
9719                  * parameter data.
9720                  */
9721                 ctsio->sense_len = 0;
9722                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9723                 ctsio->be_move_done = ctl_config_move_done;
9724                 ctl_datamove((union ctl_io *)ctsio);
9725
9726                 return (CTL_RETVAL_COMPLETE);
9727         }
9728
9729 no_sense:
9730
9731         /*
9732          * No sense information to report, so we report that everything is
9733          * okay.
9734          */
9735         ctl_set_sense_data(sense_ptr,
9736                            lun,
9737                            sense_format,
9738                            /*current_error*/ 1,
9739                            /*sense_key*/ SSD_KEY_NO_SENSE,
9740                            /*asc*/ 0x00,
9741                            /*ascq*/ 0x00,
9742                            SSD_ELEM_NONE);
9743
9744         ctsio->scsi_status = SCSI_STATUS_OK;
9745
9746         /*
9747          * We report 0 for the sense length, because we aren't doing
9748          * autosense in this case.  We're reporting sense as parameter data.
9749          */
9750         ctsio->sense_len = 0;
9751         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9752         ctsio->be_move_done = ctl_config_move_done;
9753         ctl_datamove((union ctl_io *)ctsio);
9754
9755         return (CTL_RETVAL_COMPLETE);
9756 }
9757
9758 int
9759 ctl_tur(struct ctl_scsiio *ctsio)
9760 {
9761         struct ctl_lun *lun;
9762
9763         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9764
9765         CTL_DEBUG_PRINT(("ctl_tur\n"));
9766
9767         if (lun == NULL)
9768                 return (EINVAL);
9769
9770         ctsio->scsi_status = SCSI_STATUS_OK;
9771         ctsio->io_hdr.status = CTL_SUCCESS;
9772
9773         ctl_done((union ctl_io *)ctsio);
9774
9775         return (CTL_RETVAL_COMPLETE);
9776 }
9777
9778 #ifdef notyet
9779 static int
9780 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9781 {
9782
9783 }
9784 #endif
9785
9786 static int
9787 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9788 {
9789         struct scsi_vpd_supported_pages *pages;
9790         int sup_page_size;
9791         struct ctl_lun *lun;
9792
9793         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9794
9795         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9796             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9797         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9798         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9799         ctsio->kern_sg_entries = 0;
9800
9801         if (sup_page_size < alloc_len) {
9802                 ctsio->residual = alloc_len - sup_page_size;
9803                 ctsio->kern_data_len = sup_page_size;
9804                 ctsio->kern_total_len = sup_page_size;
9805         } else {
9806                 ctsio->residual = 0;
9807                 ctsio->kern_data_len = alloc_len;
9808                 ctsio->kern_total_len = alloc_len;
9809         }
9810         ctsio->kern_data_resid = 0;
9811         ctsio->kern_rel_offset = 0;
9812         ctsio->kern_sg_entries = 0;
9813
9814         /*
9815          * The control device is always connected.  The disk device, on the
9816          * other hand, may not be online all the time.  Need to change this
9817          * to figure out whether the disk device is actually online or not.
9818          */
9819         if (lun != NULL)
9820                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9821                                 lun->be_lun->lun_type;
9822         else
9823                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9824
9825         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9826         /* Supported VPD pages */
9827         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9828         /* Serial Number */
9829         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9830         /* Device Identification */
9831         pages->page_list[2] = SVPD_DEVICE_ID;
9832         /* Extended INQUIRY Data */
9833         pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9834         /* Mode Page Policy */
9835         pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9836         /* SCSI Ports */
9837         pages->page_list[5] = SVPD_SCSI_PORTS;
9838         /* Third-party Copy */
9839         pages->page_list[6] = SVPD_SCSI_TPC;
9840         /* Block limits */
9841         pages->page_list[7] = SVPD_BLOCK_LIMITS;
9842         /* Block Device Characteristics */
9843         pages->page_list[8] = SVPD_BDC;
9844         /* Logical Block Provisioning */
9845         pages->page_list[9] = SVPD_LBP;
9846
9847         ctsio->scsi_status = SCSI_STATUS_OK;
9848
9849         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9850         ctsio->be_move_done = ctl_config_move_done;
9851         ctl_datamove((union ctl_io *)ctsio);
9852
9853         return (CTL_RETVAL_COMPLETE);
9854 }
9855
9856 static int
9857 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9858 {
9859         struct scsi_vpd_unit_serial_number *sn_ptr;
9860         struct ctl_lun *lun;
9861
9862         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9863
9864         ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9865         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9866         ctsio->kern_sg_entries = 0;
9867
9868         if (sizeof(*sn_ptr) < alloc_len) {
9869                 ctsio->residual = alloc_len - sizeof(*sn_ptr);
9870                 ctsio->kern_data_len = sizeof(*sn_ptr);
9871                 ctsio->kern_total_len = sizeof(*sn_ptr);
9872         } else {
9873                 ctsio->residual = 0;
9874                 ctsio->kern_data_len = alloc_len;
9875                 ctsio->kern_total_len = alloc_len;
9876         }
9877         ctsio->kern_data_resid = 0;
9878         ctsio->kern_rel_offset = 0;
9879         ctsio->kern_sg_entries = 0;
9880
9881         /*
9882          * The control device is always connected.  The disk device, on the
9883          * other hand, may not be online all the time.  Need to change this
9884          * to figure out whether the disk device is actually online or not.
9885          */
9886         if (lun != NULL)
9887                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9888                                   lun->be_lun->lun_type;
9889         else
9890                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9891
9892         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9893         sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9894         /*
9895          * If we don't have a LUN, we just leave the serial number as
9896          * all spaces.
9897          */
9898         memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9899         if (lun != NULL) {
9900                 strncpy((char *)sn_ptr->serial_num,
9901                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9902         }
9903         ctsio->scsi_status = SCSI_STATUS_OK;
9904
9905         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9906         ctsio->be_move_done = ctl_config_move_done;
9907         ctl_datamove((union ctl_io *)ctsio);
9908
9909         return (CTL_RETVAL_COMPLETE);
9910 }
9911
9912
9913 static int
9914 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9915 {
9916         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9917         struct ctl_lun *lun;
9918         int data_len;
9919
9920         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9921
9922         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9923             sizeof(struct scsi_vpd_mode_page_policy_descr);
9924
9925         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9926         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9927         ctsio->kern_sg_entries = 0;
9928
9929         if (data_len < alloc_len) {
9930                 ctsio->residual = alloc_len - data_len;
9931                 ctsio->kern_data_len = data_len;
9932                 ctsio->kern_total_len = data_len;
9933         } else {
9934                 ctsio->residual = 0;
9935                 ctsio->kern_data_len = alloc_len;
9936                 ctsio->kern_total_len = alloc_len;
9937         }
9938         ctsio->kern_data_resid = 0;
9939         ctsio->kern_rel_offset = 0;
9940         ctsio->kern_sg_entries = 0;
9941
9942         /*
9943          * The control device is always connected.  The disk device, on the
9944          * other hand, may not be online all the time.
9945          */
9946         if (lun != NULL)
9947                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9948                                      lun->be_lun->lun_type;
9949         else
9950                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9951         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9952         eid_ptr->page_length = data_len - 4;
9953         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9954         eid_ptr->flags3 = SVPD_EID_V_SUP;
9955
9956         ctsio->scsi_status = SCSI_STATUS_OK;
9957         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9958         ctsio->be_move_done = ctl_config_move_done;
9959         ctl_datamove((union ctl_io *)ctsio);
9960
9961         return (CTL_RETVAL_COMPLETE);
9962 }
9963
9964 static int
9965 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9966 {
9967         struct scsi_vpd_mode_page_policy *mpp_ptr;
9968         struct ctl_lun *lun;
9969         int data_len;
9970
9971         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9972
9973         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9974             sizeof(struct scsi_vpd_mode_page_policy_descr);
9975
9976         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9977         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9978         ctsio->kern_sg_entries = 0;
9979
9980         if (data_len < alloc_len) {
9981                 ctsio->residual = alloc_len - data_len;
9982                 ctsio->kern_data_len = data_len;
9983                 ctsio->kern_total_len = data_len;
9984         } else {
9985                 ctsio->residual = 0;
9986                 ctsio->kern_data_len = alloc_len;
9987                 ctsio->kern_total_len = alloc_len;
9988         }
9989         ctsio->kern_data_resid = 0;
9990         ctsio->kern_rel_offset = 0;
9991         ctsio->kern_sg_entries = 0;
9992
9993         /*
9994          * The control device is always connected.  The disk device, on the
9995          * other hand, may not be online all the time.
9996          */
9997         if (lun != NULL)
9998                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9999                                      lun->be_lun->lun_type;
10000         else
10001                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10002         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10003         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10004         mpp_ptr->descr[0].page_code = 0x3f;
10005         mpp_ptr->descr[0].subpage_code = 0xff;
10006         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10007
10008         ctsio->scsi_status = SCSI_STATUS_OK;
10009         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10010         ctsio->be_move_done = ctl_config_move_done;
10011         ctl_datamove((union ctl_io *)ctsio);
10012
10013         return (CTL_RETVAL_COMPLETE);
10014 }
10015
10016 static int
10017 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10018 {
10019         struct scsi_vpd_device_id *devid_ptr;
10020         struct scsi_vpd_id_descriptor *desc;
10021         struct ctl_softc *ctl_softc;
10022         struct ctl_lun *lun;
10023         struct ctl_port *port;
10024         int data_len;
10025         uint8_t proto;
10026
10027         ctl_softc = control_softc;
10028
10029         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10030         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10031
10032         data_len = sizeof(struct scsi_vpd_device_id) +
10033             sizeof(struct scsi_vpd_id_descriptor) +
10034                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10035             sizeof(struct scsi_vpd_id_descriptor) +
10036                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10037         if (lun && lun->lun_devid)
10038                 data_len += lun->lun_devid->len;
10039         if (port->port_devid)
10040                 data_len += port->port_devid->len;
10041         if (port->target_devid)
10042                 data_len += port->target_devid->len;
10043
10044         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10045         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10046         ctsio->kern_sg_entries = 0;
10047
10048         if (data_len < alloc_len) {
10049                 ctsio->residual = alloc_len - data_len;
10050                 ctsio->kern_data_len = data_len;
10051                 ctsio->kern_total_len = data_len;
10052         } else {
10053                 ctsio->residual = 0;
10054                 ctsio->kern_data_len = alloc_len;
10055                 ctsio->kern_total_len = alloc_len;
10056         }
10057         ctsio->kern_data_resid = 0;
10058         ctsio->kern_rel_offset = 0;
10059         ctsio->kern_sg_entries = 0;
10060
10061         /*
10062          * The control device is always connected.  The disk device, on the
10063          * other hand, may not be online all the time.
10064          */
10065         if (lun != NULL)
10066                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10067                                      lun->be_lun->lun_type;
10068         else
10069                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10070         devid_ptr->page_code = SVPD_DEVICE_ID;
10071         scsi_ulto2b(data_len - 4, devid_ptr->length);
10072
10073         if (port->port_type == CTL_PORT_FC)
10074                 proto = SCSI_PROTO_FC << 4;
10075         else if (port->port_type == CTL_PORT_ISCSI)
10076                 proto = SCSI_PROTO_ISCSI << 4;
10077         else
10078                 proto = SCSI_PROTO_SPI << 4;
10079         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10080
10081         /*
10082          * We're using a LUN association here.  i.e., this device ID is a
10083          * per-LUN identifier.
10084          */
10085         if (lun && lun->lun_devid) {
10086                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10087                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10088                     lun->lun_devid->len);
10089         }
10090
10091         /*
10092          * This is for the WWPN which is a port association.
10093          */
10094         if (port->port_devid) {
10095                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10096                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10097                     port->port_devid->len);
10098         }
10099
10100         /*
10101          * This is for the Relative Target Port(type 4h) identifier
10102          */
10103         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10104         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10105             SVPD_ID_TYPE_RELTARG;
10106         desc->length = 4;
10107         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10108         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10109             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10110
10111         /*
10112          * This is for the Target Port Group(type 5h) identifier
10113          */
10114         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10115         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10116             SVPD_ID_TYPE_TPORTGRP;
10117         desc->length = 4;
10118         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10119             &desc->identifier[2]);
10120         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10121             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10122
10123         /*
10124          * This is for the Target identifier
10125          */
10126         if (port->target_devid) {
10127                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10128         }
10129
10130         ctsio->scsi_status = SCSI_STATUS_OK;
10131         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10132         ctsio->be_move_done = ctl_config_move_done;
10133         ctl_datamove((union ctl_io *)ctsio);
10134
10135         return (CTL_RETVAL_COMPLETE);
10136 }
10137
10138 static int
10139 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10140 {
10141         struct ctl_softc *softc = control_softc;
10142         struct scsi_vpd_scsi_ports *sp;
10143         struct scsi_vpd_port_designation *pd;
10144         struct scsi_vpd_port_designation_cont *pdc;
10145         struct ctl_lun *lun;
10146         struct ctl_port *port;
10147         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10148         int num_target_port_groups, single;
10149
10150         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10151
10152         single = ctl_is_single;
10153         if (single)
10154                 num_target_port_groups = 1;
10155         else
10156                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10157         num_target_ports = 0;
10158         iid_len = 0;
10159         id_len = 0;
10160         mtx_lock(&softc->ctl_lock);
10161         STAILQ_FOREACH(port, &softc->port_list, links) {
10162                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10163                         continue;
10164                 if (lun != NULL &&
10165                     ctl_map_lun_back(port->targ_port, lun->lun) >=
10166                     CTL_MAX_LUNS)
10167                         continue;
10168                 num_target_ports++;
10169                 if (port->init_devid)
10170                         iid_len += port->init_devid->len;
10171                 if (port->port_devid)
10172                         id_len += port->port_devid->len;
10173         }
10174         mtx_unlock(&softc->ctl_lock);
10175
10176         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10177             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10178              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10179         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10180         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10181         ctsio->kern_sg_entries = 0;
10182
10183         if (data_len < alloc_len) {
10184                 ctsio->residual = alloc_len - data_len;
10185                 ctsio->kern_data_len = data_len;
10186                 ctsio->kern_total_len = data_len;
10187         } else {
10188                 ctsio->residual = 0;
10189                 ctsio->kern_data_len = alloc_len;
10190                 ctsio->kern_total_len = alloc_len;
10191         }
10192         ctsio->kern_data_resid = 0;
10193         ctsio->kern_rel_offset = 0;
10194         ctsio->kern_sg_entries = 0;
10195
10196         /*
10197          * The control device is always connected.  The disk device, on the
10198          * other hand, may not be online all the time.  Need to change this
10199          * to figure out whether the disk device is actually online or not.
10200          */
10201         if (lun != NULL)
10202                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10203                                   lun->be_lun->lun_type;
10204         else
10205                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10206
10207         sp->page_code = SVPD_SCSI_PORTS;
10208         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10209             sp->page_length);
10210         pd = &sp->design[0];
10211
10212         mtx_lock(&softc->ctl_lock);
10213         if (softc->flags & CTL_FLAG_MASTER_SHELF)
10214                 pg = 0;
10215         else
10216                 pg = 1;
10217         for (g = 0; g < num_target_port_groups; g++) {
10218                 STAILQ_FOREACH(port, &softc->port_list, links) {
10219                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10220                                 continue;
10221                         if (lun != NULL &&
10222                             ctl_map_lun_back(port->targ_port, lun->lun) >=
10223                             CTL_MAX_LUNS)
10224                                 continue;
10225                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10226                         scsi_ulto2b(p, pd->relative_port_id);
10227                         if (port->init_devid && g == pg) {
10228                                 iid_len = port->init_devid->len;
10229                                 memcpy(pd->initiator_transportid,
10230                                     port->init_devid->data, port->init_devid->len);
10231                         } else
10232                                 iid_len = 0;
10233                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10234                         pdc = (struct scsi_vpd_port_designation_cont *)
10235                             (&pd->initiator_transportid[iid_len]);
10236                         if (port->port_devid && g == pg) {
10237                                 id_len = port->port_devid->len;
10238                                 memcpy(pdc->target_port_descriptors,
10239                                     port->port_devid->data, port->port_devid->len);
10240                         } else
10241                                 id_len = 0;
10242                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10243                         pd = (struct scsi_vpd_port_designation *)
10244                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10245                 }
10246         }
10247         mtx_unlock(&softc->ctl_lock);
10248
10249         ctsio->scsi_status = SCSI_STATUS_OK;
10250         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10251         ctsio->be_move_done = ctl_config_move_done;
10252         ctl_datamove((union ctl_io *)ctsio);
10253
10254         return (CTL_RETVAL_COMPLETE);
10255 }
10256
10257 static int
10258 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10259 {
10260         struct scsi_vpd_block_limits *bl_ptr;
10261         struct ctl_lun *lun;
10262         int bs;
10263
10264         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10265
10266         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10267         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10268         ctsio->kern_sg_entries = 0;
10269
10270         if (sizeof(*bl_ptr) < alloc_len) {
10271                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10272                 ctsio->kern_data_len = sizeof(*bl_ptr);
10273                 ctsio->kern_total_len = sizeof(*bl_ptr);
10274         } else {
10275                 ctsio->residual = 0;
10276                 ctsio->kern_data_len = alloc_len;
10277                 ctsio->kern_total_len = alloc_len;
10278         }
10279         ctsio->kern_data_resid = 0;
10280         ctsio->kern_rel_offset = 0;
10281         ctsio->kern_sg_entries = 0;
10282
10283         /*
10284          * The control device is always connected.  The disk device, on the
10285          * other hand, may not be online all the time.  Need to change this
10286          * to figure out whether the disk device is actually online or not.
10287          */
10288         if (lun != NULL)
10289                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10290                                   lun->be_lun->lun_type;
10291         else
10292                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10293
10294         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10295         scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10296         bl_ptr->max_cmp_write_len = 0xff;
10297         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10298         if (lun != NULL) {
10299                 bs = lun->be_lun->blocksize;
10300                 scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10301                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10302                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10303                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10304                         if (lun->be_lun->pblockexp != 0) {
10305                                 scsi_ulto4b((1 << lun->be_lun->pblockexp),
10306                                     bl_ptr->opt_unmap_grain);
10307                                 scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10308                                     bl_ptr->unmap_grain_align);
10309                         }
10310                 }
10311         }
10312         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10313
10314         ctsio->scsi_status = SCSI_STATUS_OK;
10315         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10316         ctsio->be_move_done = ctl_config_move_done;
10317         ctl_datamove((union ctl_io *)ctsio);
10318
10319         return (CTL_RETVAL_COMPLETE);
10320 }
10321
10322 static int
10323 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10324 {
10325         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10326         struct ctl_lun *lun;
10327
10328         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10329
10330         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10331         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10332         ctsio->kern_sg_entries = 0;
10333
10334         if (sizeof(*bdc_ptr) < alloc_len) {
10335                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10336                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10337                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10338         } else {
10339                 ctsio->residual = 0;
10340                 ctsio->kern_data_len = alloc_len;
10341                 ctsio->kern_total_len = alloc_len;
10342         }
10343         ctsio->kern_data_resid = 0;
10344         ctsio->kern_rel_offset = 0;
10345         ctsio->kern_sg_entries = 0;
10346
10347         /*
10348          * The control device is always connected.  The disk device, on the
10349          * other hand, may not be online all the time.  Need to change this
10350          * to figure out whether the disk device is actually online or not.
10351          */
10352         if (lun != NULL)
10353                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10354                                   lun->be_lun->lun_type;
10355         else
10356                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10357         bdc_ptr->page_code = SVPD_BDC;
10358         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10359         scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10360         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10361
10362         ctsio->scsi_status = SCSI_STATUS_OK;
10363         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10364         ctsio->be_move_done = ctl_config_move_done;
10365         ctl_datamove((union ctl_io *)ctsio);
10366
10367         return (CTL_RETVAL_COMPLETE);
10368 }
10369
10370 static int
10371 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10372 {
10373         struct scsi_vpd_logical_block_prov *lbp_ptr;
10374         struct ctl_lun *lun;
10375
10376         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10377
10378         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10379         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10380         ctsio->kern_sg_entries = 0;
10381
10382         if (sizeof(*lbp_ptr) < alloc_len) {
10383                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10384                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10385                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10386         } else {
10387                 ctsio->residual = 0;
10388                 ctsio->kern_data_len = alloc_len;
10389                 ctsio->kern_total_len = alloc_len;
10390         }
10391         ctsio->kern_data_resid = 0;
10392         ctsio->kern_rel_offset = 0;
10393         ctsio->kern_sg_entries = 0;
10394
10395         /*
10396          * The control device is always connected.  The disk device, on the
10397          * other hand, may not be online all the time.  Need to change this
10398          * to figure out whether the disk device is actually online or not.
10399          */
10400         if (lun != NULL)
10401                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10402                                   lun->be_lun->lun_type;
10403         else
10404                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10405
10406         lbp_ptr->page_code = SVPD_LBP;
10407         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10408         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10409                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10410                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10411                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10412         }
10413
10414         ctsio->scsi_status = SCSI_STATUS_OK;
10415         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10416         ctsio->be_move_done = ctl_config_move_done;
10417         ctl_datamove((union ctl_io *)ctsio);
10418
10419         return (CTL_RETVAL_COMPLETE);
10420 }
10421
10422 static int
10423 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10424 {
10425         struct scsi_inquiry *cdb;
10426         struct ctl_lun *lun;
10427         int alloc_len, retval;
10428
10429         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10430         cdb = (struct scsi_inquiry *)ctsio->cdb;
10431
10432         retval = CTL_RETVAL_COMPLETE;
10433
10434         alloc_len = scsi_2btoul(cdb->length);
10435
10436         switch (cdb->page_code) {
10437         case SVPD_SUPPORTED_PAGES:
10438                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10439                 break;
10440         case SVPD_UNIT_SERIAL_NUMBER:
10441                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10442                 break;
10443         case SVPD_DEVICE_ID:
10444                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10445                 break;
10446         case SVPD_EXTENDED_INQUIRY_DATA:
10447                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10448                 break;
10449         case SVPD_MODE_PAGE_POLICY:
10450                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10451                 break;
10452         case SVPD_SCSI_PORTS:
10453                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10454                 break;
10455         case SVPD_SCSI_TPC:
10456                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10457                 break;
10458         case SVPD_BLOCK_LIMITS:
10459                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10460                 break;
10461         case SVPD_BDC:
10462                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10463                 break;
10464         case SVPD_LBP:
10465                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10466                 break;
10467         default:
10468                 ctl_set_invalid_field(ctsio,
10469                                       /*sks_valid*/ 1,
10470                                       /*command*/ 1,
10471                                       /*field*/ 2,
10472                                       /*bit_valid*/ 0,
10473                                       /*bit*/ 0);
10474                 ctl_done((union ctl_io *)ctsio);
10475                 retval = CTL_RETVAL_COMPLETE;
10476                 break;
10477         }
10478
10479         return (retval);
10480 }
10481
10482 static int
10483 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10484 {
10485         struct scsi_inquiry_data *inq_ptr;
10486         struct scsi_inquiry *cdb;
10487         struct ctl_softc *ctl_softc;
10488         struct ctl_lun *lun;
10489         char *val;
10490         uint32_t alloc_len;
10491         ctl_port_type port_type;
10492
10493         ctl_softc = control_softc;
10494
10495         /*
10496          * Figure out whether we're talking to a Fibre Channel port or not.
10497          * We treat the ioctl front end, and any SCSI adapters, as packetized
10498          * SCSI front ends.
10499          */
10500         port_type = ctl_softc->ctl_ports[
10501             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10502         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10503                 port_type = CTL_PORT_SCSI;
10504
10505         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10506         cdb = (struct scsi_inquiry *)ctsio->cdb;
10507         alloc_len = scsi_2btoul(cdb->length);
10508
10509         /*
10510          * We malloc the full inquiry data size here and fill it
10511          * in.  If the user only asks for less, we'll give him
10512          * that much.
10513          */
10514         ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10515         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10516         ctsio->kern_sg_entries = 0;
10517         ctsio->kern_data_resid = 0;
10518         ctsio->kern_rel_offset = 0;
10519
10520         if (sizeof(*inq_ptr) < alloc_len) {
10521                 ctsio->residual = alloc_len - sizeof(*inq_ptr);
10522                 ctsio->kern_data_len = sizeof(*inq_ptr);
10523                 ctsio->kern_total_len = sizeof(*inq_ptr);
10524         } else {
10525                 ctsio->residual = 0;
10526                 ctsio->kern_data_len = alloc_len;
10527                 ctsio->kern_total_len = alloc_len;
10528         }
10529
10530         /*
10531          * If we have a LUN configured, report it as connected.  Otherwise,
10532          * report that it is offline or no device is supported, depending 
10533          * on the value of inquiry_pq_no_lun.
10534          *
10535          * According to the spec (SPC-4 r34), the peripheral qualifier
10536          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10537          *
10538          * "A peripheral device having the specified peripheral device type 
10539          * is not connected to this logical unit. However, the device
10540          * server is capable of supporting the specified peripheral device
10541          * type on this logical unit."
10542          *
10543          * According to the same spec, the peripheral qualifier
10544          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10545          *
10546          * "The device server is not capable of supporting a peripheral
10547          * device on this logical unit. For this peripheral qualifier the
10548          * peripheral device type shall be set to 1Fh. All other peripheral
10549          * device type values are reserved for this peripheral qualifier."
10550          *
10551          * Given the text, it would seem that we probably want to report that
10552          * the LUN is offline here.  There is no LUN connected, but we can
10553          * support a LUN at the given LUN number.
10554          *
10555          * In the real world, though, it sounds like things are a little
10556          * different:
10557          *
10558          * - Linux, when presented with a LUN with the offline peripheral
10559          *   qualifier, will create an sg driver instance for it.  So when
10560          *   you attach it to CTL, you wind up with a ton of sg driver
10561          *   instances.  (One for every LUN that Linux bothered to probe.)
10562          *   Linux does this despite the fact that it issues a REPORT LUNs
10563          *   to LUN 0 to get the inventory of supported LUNs.
10564          *
10565          * - There is other anecdotal evidence (from Emulex folks) about
10566          *   arrays that use the offline peripheral qualifier for LUNs that
10567          *   are on the "passive" path in an active/passive array.
10568          *
10569          * So the solution is provide a hopefully reasonable default
10570          * (return bad/no LUN) and allow the user to change the behavior
10571          * with a tunable/sysctl variable.
10572          */
10573         if (lun != NULL)
10574                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10575                                   lun->be_lun->lun_type;
10576         else if (ctl_softc->inquiry_pq_no_lun == 0)
10577                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10578         else
10579                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10580
10581         /* RMB in byte 2 is 0 */
10582         inq_ptr->version = SCSI_REV_SPC4;
10583
10584         /*
10585          * According to SAM-3, even if a device only supports a single
10586          * level of LUN addressing, it should still set the HISUP bit:
10587          *
10588          * 4.9.1 Logical unit numbers overview
10589          *
10590          * All logical unit number formats described in this standard are
10591          * hierarchical in structure even when only a single level in that
10592          * hierarchy is used. The HISUP bit shall be set to one in the
10593          * standard INQUIRY data (see SPC-2) when any logical unit number
10594          * format described in this standard is used.  Non-hierarchical
10595          * formats are outside the scope of this standard.
10596          *
10597          * Therefore we set the HiSup bit here.
10598          *
10599          * The reponse format is 2, per SPC-3.
10600          */
10601         inq_ptr->response_format = SID_HiSup | 2;
10602
10603         inq_ptr->additional_length =
10604             offsetof(struct scsi_inquiry_data, vendor_specific1) -
10605             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10606         CTL_DEBUG_PRINT(("additional_length = %d\n",
10607                          inq_ptr->additional_length));
10608
10609         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10610         /* 16 bit addressing */
10611         if (port_type == CTL_PORT_SCSI)
10612                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10613         /* XXX set the SID_MultiP bit here if we're actually going to
10614            respond on multiple ports */
10615         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10616
10617         /* 16 bit data bus, synchronous transfers */
10618         if (port_type == CTL_PORT_SCSI)
10619                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10620         /*
10621          * XXX KDM do we want to support tagged queueing on the control
10622          * device at all?
10623          */
10624         if ((lun == NULL)
10625          || (lun->be_lun->lun_type != T_PROCESSOR))
10626                 inq_ptr->flags |= SID_CmdQue;
10627         /*
10628          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10629          * We have 8 bytes for the vendor name, and 16 bytes for the device
10630          * name and 4 bytes for the revision.
10631          */
10632         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10633             "vendor")) == NULL) {
10634                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10635         } else {
10636                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10637                 strncpy(inq_ptr->vendor, val,
10638                     min(sizeof(inq_ptr->vendor), strlen(val)));
10639         }
10640         if (lun == NULL) {
10641                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10642                     sizeof(inq_ptr->product));
10643         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10644                 switch (lun->be_lun->lun_type) {
10645                 case T_DIRECT:
10646                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10647                             sizeof(inq_ptr->product));
10648                         break;
10649                 case T_PROCESSOR:
10650                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10651                             sizeof(inq_ptr->product));
10652                         break;
10653                 default:
10654                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10655                             sizeof(inq_ptr->product));
10656                         break;
10657                 }
10658         } else {
10659                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10660                 strncpy(inq_ptr->product, val,
10661                     min(sizeof(inq_ptr->product), strlen(val)));
10662         }
10663
10664         /*
10665          * XXX make this a macro somewhere so it automatically gets
10666          * incremented when we make changes.
10667          */
10668         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10669             "revision")) == NULL) {
10670                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10671         } else {
10672                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10673                 strncpy(inq_ptr->revision, val,
10674                     min(sizeof(inq_ptr->revision), strlen(val)));
10675         }
10676
10677         /*
10678          * For parallel SCSI, we support double transition and single
10679          * transition clocking.  We also support QAS (Quick Arbitration
10680          * and Selection) and Information Unit transfers on both the
10681          * control and array devices.
10682          */
10683         if (port_type == CTL_PORT_SCSI)
10684                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10685                                     SID_SPI_IUS;
10686
10687         /* SAM-5 (no version claimed) */
10688         scsi_ulto2b(0x00A0, inq_ptr->version1);
10689         /* SPC-4 (no version claimed) */
10690         scsi_ulto2b(0x0460, inq_ptr->version2);
10691         if (port_type == CTL_PORT_FC) {
10692                 /* FCP-2 ANSI INCITS.350:2003 */
10693                 scsi_ulto2b(0x0917, inq_ptr->version3);
10694         } else if (port_type == CTL_PORT_SCSI) {
10695                 /* SPI-4 ANSI INCITS.362:200x */
10696                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10697         } else if (port_type == CTL_PORT_ISCSI) {
10698                 /* iSCSI (no version claimed) */
10699                 scsi_ulto2b(0x0960, inq_ptr->version3);
10700         } else if (port_type == CTL_PORT_SAS) {
10701                 /* SAS (no version claimed) */
10702                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10703         }
10704
10705         if (lun == NULL) {
10706                 /* SBC-3 (no version claimed) */
10707                 scsi_ulto2b(0x04C0, inq_ptr->version4);
10708         } else {
10709                 switch (lun->be_lun->lun_type) {
10710                 case T_DIRECT:
10711                         /* SBC-3 (no version claimed) */
10712                         scsi_ulto2b(0x04C0, inq_ptr->version4);
10713                         break;
10714                 case T_PROCESSOR:
10715                 default:
10716                         break;
10717                 }
10718         }
10719
10720         ctsio->scsi_status = SCSI_STATUS_OK;
10721         if (ctsio->kern_data_len > 0) {
10722                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10723                 ctsio->be_move_done = ctl_config_move_done;
10724                 ctl_datamove((union ctl_io *)ctsio);
10725         } else {
10726                 ctsio->io_hdr.status = CTL_SUCCESS;
10727                 ctl_done((union ctl_io *)ctsio);
10728         }
10729
10730         return (CTL_RETVAL_COMPLETE);
10731 }
10732
10733 int
10734 ctl_inquiry(struct ctl_scsiio *ctsio)
10735 {
10736         struct scsi_inquiry *cdb;
10737         int retval;
10738
10739         cdb = (struct scsi_inquiry *)ctsio->cdb;
10740
10741         retval = 0;
10742
10743         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10744
10745         /*
10746          * Right now, we don't support the CmdDt inquiry information.
10747          * This would be nice to support in the future.  When we do
10748          * support it, we should change this test so that it checks to make
10749          * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10750          */
10751 #ifdef notyet
10752         if (((cdb->byte2 & SI_EVPD)
10753          && (cdb->byte2 & SI_CMDDT)))
10754 #endif
10755         if (cdb->byte2 & SI_CMDDT) {
10756                 /*
10757                  * Point to the SI_CMDDT bit.  We might change this
10758                  * when we support SI_CMDDT, but since both bits would be
10759                  * "wrong", this should probably just stay as-is then.
10760                  */
10761                 ctl_set_invalid_field(ctsio,
10762                                       /*sks_valid*/ 1,
10763                                       /*command*/ 1,
10764                                       /*field*/ 1,
10765                                       /*bit_valid*/ 1,
10766                                       /*bit*/ 1);
10767                 ctl_done((union ctl_io *)ctsio);
10768                 return (CTL_RETVAL_COMPLETE);
10769         }
10770         if (cdb->byte2 & SI_EVPD)
10771                 retval = ctl_inquiry_evpd(ctsio);
10772 #ifdef notyet
10773         else if (cdb->byte2 & SI_CMDDT)
10774                 retval = ctl_inquiry_cmddt(ctsio);
10775 #endif
10776         else
10777                 retval = ctl_inquiry_std(ctsio);
10778
10779         return (retval);
10780 }
10781
10782 /*
10783  * For known CDB types, parse the LBA and length.
10784  */
10785 static int
10786 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10787 {
10788         if (io->io_hdr.io_type != CTL_IO_SCSI)
10789                 return (1);
10790
10791         switch (io->scsiio.cdb[0]) {
10792         case COMPARE_AND_WRITE: {
10793                 struct scsi_compare_and_write *cdb;
10794
10795                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10796
10797                 *lba = scsi_8btou64(cdb->addr);
10798                 *len = cdb->length;
10799                 break;
10800         }
10801         case READ_6:
10802         case WRITE_6: {
10803                 struct scsi_rw_6 *cdb;
10804
10805                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10806
10807                 *lba = scsi_3btoul(cdb->addr);
10808                 /* only 5 bits are valid in the most significant address byte */
10809                 *lba &= 0x1fffff;
10810                 *len = cdb->length;
10811                 break;
10812         }
10813         case READ_10:
10814         case WRITE_10: {
10815                 struct scsi_rw_10 *cdb;
10816
10817                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10818
10819                 *lba = scsi_4btoul(cdb->addr);
10820                 *len = scsi_2btoul(cdb->length);
10821                 break;
10822         }
10823         case WRITE_VERIFY_10: {
10824                 struct scsi_write_verify_10 *cdb;
10825
10826                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10827
10828                 *lba = scsi_4btoul(cdb->addr);
10829                 *len = scsi_2btoul(cdb->length);
10830                 break;
10831         }
10832         case READ_12:
10833         case WRITE_12: {
10834                 struct scsi_rw_12 *cdb;
10835
10836                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10837
10838                 *lba = scsi_4btoul(cdb->addr);
10839                 *len = scsi_4btoul(cdb->length);
10840                 break;
10841         }
10842         case WRITE_VERIFY_12: {
10843                 struct scsi_write_verify_12 *cdb;
10844
10845                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10846
10847                 *lba = scsi_4btoul(cdb->addr);
10848                 *len = scsi_4btoul(cdb->length);
10849                 break;
10850         }
10851         case READ_16:
10852         case WRITE_16: {
10853                 struct scsi_rw_16 *cdb;
10854
10855                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10856
10857                 *lba = scsi_8btou64(cdb->addr);
10858                 *len = scsi_4btoul(cdb->length);
10859                 break;
10860         }
10861         case WRITE_VERIFY_16: {
10862                 struct scsi_write_verify_16 *cdb;
10863
10864                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10865
10866                 
10867                 *lba = scsi_8btou64(cdb->addr);
10868                 *len = scsi_4btoul(cdb->length);
10869                 break;
10870         }
10871         case WRITE_SAME_10: {
10872                 struct scsi_write_same_10 *cdb;
10873
10874                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10875
10876                 *lba = scsi_4btoul(cdb->addr);
10877                 *len = scsi_2btoul(cdb->length);
10878                 break;
10879         }
10880         case WRITE_SAME_16: {
10881                 struct scsi_write_same_16 *cdb;
10882
10883                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10884
10885                 *lba = scsi_8btou64(cdb->addr);
10886                 *len = scsi_4btoul(cdb->length);
10887                 break;
10888         }
10889         case VERIFY_10: {
10890                 struct scsi_verify_10 *cdb;
10891
10892                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10893
10894                 *lba = scsi_4btoul(cdb->addr);
10895                 *len = scsi_2btoul(cdb->length);
10896                 break;
10897         }
10898         case VERIFY_12: {
10899                 struct scsi_verify_12 *cdb;
10900
10901                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10902
10903                 *lba = scsi_4btoul(cdb->addr);
10904                 *len = scsi_4btoul(cdb->length);
10905                 break;
10906         }
10907         case VERIFY_16: {
10908                 struct scsi_verify_16 *cdb;
10909
10910                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10911
10912                 *lba = scsi_8btou64(cdb->addr);
10913                 *len = scsi_4btoul(cdb->length);
10914                 break;
10915         }
10916         case UNMAP: {
10917                 *lba = 0;
10918                 *len = UINT64_MAX;
10919                 break;
10920         }
10921         default:
10922                 return (1);
10923                 break; /* NOTREACHED */
10924         }
10925
10926         return (0);
10927 }
10928
10929 static ctl_action
10930 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10931 {
10932         uint64_t endlba1, endlba2;
10933
10934         endlba1 = lba1 + len1 - 1;
10935         endlba2 = lba2 + len2 - 1;
10936
10937         if ((endlba1 < lba2)
10938          || (endlba2 < lba1))
10939                 return (CTL_ACTION_PASS);
10940         else
10941                 return (CTL_ACTION_BLOCK);
10942 }
10943
10944 static int
10945 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10946 {
10947         struct ctl_ptr_len_flags *ptrlen;
10948         struct scsi_unmap_desc *buf, *end, *range;
10949         uint64_t lba;
10950         uint32_t len;
10951
10952         /* If not UNMAP -- go other way. */
10953         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10954             io->scsiio.cdb[0] != UNMAP)
10955                 return (CTL_ACTION_ERROR);
10956
10957         /* If UNMAP without data -- block and wait for data. */
10958         ptrlen = (struct ctl_ptr_len_flags *)
10959             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10960         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10961             ptrlen->ptr == NULL)
10962                 return (CTL_ACTION_BLOCK);
10963
10964         /* UNMAP with data -- check for collision. */
10965         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10966         end = buf + ptrlen->len / sizeof(*buf);
10967         for (range = buf; range < end; range++) {
10968                 lba = scsi_8btou64(range->lba);
10969                 len = scsi_4btoul(range->length);
10970                 if ((lba < lba2 + len2) && (lba + len > lba2))
10971                         return (CTL_ACTION_BLOCK);
10972         }
10973         return (CTL_ACTION_PASS);
10974 }
10975
10976 static ctl_action
10977 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10978 {
10979         uint64_t lba1, lba2;
10980         uint64_t len1, len2;
10981         int retval;
10982
10983         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10984                 return (CTL_ACTION_ERROR);
10985
10986         retval = ctl_extent_check_unmap(io2, lba1, len1);
10987         if (retval != CTL_ACTION_ERROR)
10988                 return (retval);
10989
10990         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10991                 return (CTL_ACTION_ERROR);
10992
10993         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10994 }
10995
10996 static ctl_action
10997 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10998     union ctl_io *ooa_io)
10999 {
11000         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11001         ctl_serialize_action *serialize_row;
11002
11003         /*
11004          * The initiator attempted multiple untagged commands at the same
11005          * time.  Can't do that.
11006          */
11007         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11008          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11009          && ((pending_io->io_hdr.nexus.targ_port ==
11010               ooa_io->io_hdr.nexus.targ_port)
11011           && (pending_io->io_hdr.nexus.initid.id ==
11012               ooa_io->io_hdr.nexus.initid.id))
11013          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11014                 return (CTL_ACTION_OVERLAP);
11015
11016         /*
11017          * The initiator attempted to send multiple tagged commands with
11018          * the same ID.  (It's fine if different initiators have the same
11019          * tag ID.)
11020          *
11021          * Even if all of those conditions are true, we don't kill the I/O
11022          * if the command ahead of us has been aborted.  We won't end up
11023          * sending it to the FETD, and it's perfectly legal to resend a
11024          * command with the same tag number as long as the previous
11025          * instance of this tag number has been aborted somehow.
11026          */
11027         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11028          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11029          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11030          && ((pending_io->io_hdr.nexus.targ_port ==
11031               ooa_io->io_hdr.nexus.targ_port)
11032           && (pending_io->io_hdr.nexus.initid.id ==
11033               ooa_io->io_hdr.nexus.initid.id))
11034          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11035                 return (CTL_ACTION_OVERLAP_TAG);
11036
11037         /*
11038          * If we get a head of queue tag, SAM-3 says that we should
11039          * immediately execute it.
11040          *
11041          * What happens if this command would normally block for some other
11042          * reason?  e.g. a request sense with a head of queue tag
11043          * immediately after a write.  Normally that would block, but this
11044          * will result in its getting executed immediately...
11045          *
11046          * We currently return "pass" instead of "skip", so we'll end up
11047          * going through the rest of the queue to check for overlapped tags.
11048          *
11049          * XXX KDM check for other types of blockage first??
11050          */
11051         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11052                 return (CTL_ACTION_PASS);
11053
11054         /*
11055          * Ordered tags have to block until all items ahead of them
11056          * have completed.  If we get called with an ordered tag, we always
11057          * block, if something else is ahead of us in the queue.
11058          */
11059         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11060                 return (CTL_ACTION_BLOCK);
11061
11062         /*
11063          * Simple tags get blocked until all head of queue and ordered tags
11064          * ahead of them have completed.  I'm lumping untagged commands in
11065          * with simple tags here.  XXX KDM is that the right thing to do?
11066          */
11067         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11068           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11069          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11070           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11071                 return (CTL_ACTION_BLOCK);
11072
11073         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
11074         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
11075
11076         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11077
11078         switch (serialize_row[pending_entry->seridx]) {
11079         case CTL_SER_BLOCK:
11080                 return (CTL_ACTION_BLOCK);
11081         case CTL_SER_EXTENT:
11082                 return (ctl_extent_check(pending_io, ooa_io));
11083         case CTL_SER_EXTENTOPT:
11084                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11085                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11086                         return (ctl_extent_check(pending_io, ooa_io));
11087                 /* FALLTHROUGH */
11088         case CTL_SER_PASS:
11089                 return (CTL_ACTION_PASS);
11090         case CTL_SER_BLOCKOPT:
11091                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11092                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11093                         return (CTL_ACTION_BLOCK);
11094                 return (CTL_ACTION_PASS);
11095         case CTL_SER_SKIP:
11096                 return (CTL_ACTION_SKIP);
11097         default:
11098                 panic("invalid serialization value %d",
11099                       serialize_row[pending_entry->seridx]);
11100         }
11101
11102         return (CTL_ACTION_ERROR);
11103 }
11104
11105 /*
11106  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11107  * Assumptions:
11108  * - pending_io is generally either incoming, or on the blocked queue
11109  * - starting I/O is the I/O we want to start the check with.
11110  */
11111 static ctl_action
11112 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11113               union ctl_io *starting_io)
11114 {
11115         union ctl_io *ooa_io;
11116         ctl_action action;
11117
11118         mtx_assert(&lun->lun_lock, MA_OWNED);
11119
11120         /*
11121          * Run back along the OOA queue, starting with the current
11122          * blocked I/O and going through every I/O before it on the
11123          * queue.  If starting_io is NULL, we'll just end up returning
11124          * CTL_ACTION_PASS.
11125          */
11126         for (ooa_io = starting_io; ooa_io != NULL;
11127              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11128              ooa_links)){
11129
11130                 /*
11131                  * This routine just checks to see whether
11132                  * cur_blocked is blocked by ooa_io, which is ahead
11133                  * of it in the queue.  It doesn't queue/dequeue
11134                  * cur_blocked.
11135                  */
11136                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11137                 switch (action) {
11138                 case CTL_ACTION_BLOCK:
11139                 case CTL_ACTION_OVERLAP:
11140                 case CTL_ACTION_OVERLAP_TAG:
11141                 case CTL_ACTION_SKIP:
11142                 case CTL_ACTION_ERROR:
11143                         return (action);
11144                         break; /* NOTREACHED */
11145                 case CTL_ACTION_PASS:
11146                         break;
11147                 default:
11148                         panic("invalid action %d", action);
11149                         break;  /* NOTREACHED */
11150                 }
11151         }
11152
11153         return (CTL_ACTION_PASS);
11154 }
11155
11156 /*
11157  * Assumptions:
11158  * - An I/O has just completed, and has been removed from the per-LUN OOA
11159  *   queue, so some items on the blocked queue may now be unblocked.
11160  */
11161 static int
11162 ctl_check_blocked(struct ctl_lun *lun)
11163 {
11164         union ctl_io *cur_blocked, *next_blocked;
11165
11166         mtx_assert(&lun->lun_lock, MA_OWNED);
11167
11168         /*
11169          * Run forward from the head of the blocked queue, checking each
11170          * entry against the I/Os prior to it on the OOA queue to see if
11171          * there is still any blockage.
11172          *
11173          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11174          * with our removing a variable on it while it is traversing the
11175          * list.
11176          */
11177         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11178              cur_blocked != NULL; cur_blocked = next_blocked) {
11179                 union ctl_io *prev_ooa;
11180                 ctl_action action;
11181
11182                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11183                                                           blocked_links);
11184
11185                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11186                                                       ctl_ooaq, ooa_links);
11187
11188                 /*
11189                  * If cur_blocked happens to be the first item in the OOA
11190                  * queue now, prev_ooa will be NULL, and the action
11191                  * returned will just be CTL_ACTION_PASS.
11192                  */
11193                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11194
11195                 switch (action) {
11196                 case CTL_ACTION_BLOCK:
11197                         /* Nothing to do here, still blocked */
11198                         break;
11199                 case CTL_ACTION_OVERLAP:
11200                 case CTL_ACTION_OVERLAP_TAG:
11201                         /*
11202                          * This shouldn't happen!  In theory we've already
11203                          * checked this command for overlap...
11204                          */
11205                         break;
11206                 case CTL_ACTION_PASS:
11207                 case CTL_ACTION_SKIP: {
11208                         struct ctl_softc *softc;
11209                         const struct ctl_cmd_entry *entry;
11210                         uint32_t initidx;
11211                         int isc_retval;
11212
11213                         /*
11214                          * The skip case shouldn't happen, this transaction
11215                          * should have never made it onto the blocked queue.
11216                          */
11217                         /*
11218                          * This I/O is no longer blocked, we can remove it
11219                          * from the blocked queue.  Since this is a TAILQ
11220                          * (doubly linked list), we can do O(1) removals
11221                          * from any place on the list.
11222                          */
11223                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11224                                      blocked_links);
11225                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11226
11227                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11228                                 /*
11229                                  * Need to send IO back to original side to
11230                                  * run
11231                                  */
11232                                 union ctl_ha_msg msg_info;
11233
11234                                 msg_info.hdr.original_sc =
11235                                         cur_blocked->io_hdr.original_sc;
11236                                 msg_info.hdr.serializing_sc = cur_blocked;
11237                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11238                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11239                                      &msg_info, sizeof(msg_info), 0)) >
11240                                      CTL_HA_STATUS_SUCCESS) {
11241                                         printf("CTL:Check Blocked error from "
11242                                                "ctl_ha_msg_send %d\n",
11243                                                isc_retval);
11244                                 }
11245                                 break;
11246                         }
11247                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
11248                         softc = control_softc;
11249
11250                         initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11251
11252                         /*
11253                          * Check this I/O for LUN state changes that may
11254                          * have happened while this command was blocked.
11255                          * The LUN state may have been changed by a command
11256                          * ahead of us in the queue, so we need to re-check
11257                          * for any states that can be caused by SCSI
11258                          * commands.
11259                          */
11260                         if (ctl_scsiio_lun_check(softc, lun, entry,
11261                                                  &cur_blocked->scsiio) == 0) {
11262                                 cur_blocked->io_hdr.flags |=
11263                                                       CTL_FLAG_IS_WAS_ON_RTR;
11264                                 ctl_enqueue_rtr(cur_blocked);
11265                         } else
11266                                 ctl_done(cur_blocked);
11267                         break;
11268                 }
11269                 default:
11270                         /*
11271                          * This probably shouldn't happen -- we shouldn't
11272                          * get CTL_ACTION_ERROR, or anything else.
11273                          */
11274                         break;
11275                 }
11276         }
11277
11278         return (CTL_RETVAL_COMPLETE);
11279 }
11280
11281 /*
11282  * This routine (with one exception) checks LUN flags that can be set by
11283  * commands ahead of us in the OOA queue.  These flags have to be checked
11284  * when a command initially comes in, and when we pull a command off the
11285  * blocked queue and are preparing to execute it.  The reason we have to
11286  * check these flags for commands on the blocked queue is that the LUN
11287  * state may have been changed by a command ahead of us while we're on the
11288  * blocked queue.
11289  *
11290  * Ordering is somewhat important with these checks, so please pay
11291  * careful attention to the placement of any new checks.
11292  */
11293 static int
11294 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11295     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11296 {
11297         int retval;
11298
11299         retval = 0;
11300
11301         mtx_assert(&lun->lun_lock, MA_OWNED);
11302
11303         /*
11304          * If this shelf is a secondary shelf controller, we have to reject
11305          * any media access commands.
11306          */
11307 #if 0
11308         /* No longer needed for HA */
11309         if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11310          && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11311                 ctl_set_lun_standby(ctsio);
11312                 retval = 1;
11313                 goto bailout;
11314         }
11315 #endif
11316
11317         /*
11318          * Check for a reservation conflict.  If this command isn't allowed
11319          * even on reserved LUNs, and if this initiator isn't the one who
11320          * reserved us, reject the command with a reservation conflict.
11321          */
11322         if ((lun->flags & CTL_LUN_RESERVED)
11323          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11324                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11325                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11326                  || (ctsio->io_hdr.nexus.targ_target.id !=
11327                      lun->rsv_nexus.targ_target.id)) {
11328                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11329                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11330                         retval = 1;
11331                         goto bailout;
11332                 }
11333         }
11334
11335         if ( (lun->flags & CTL_LUN_PR_RESERVED)
11336          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11337                 uint32_t residx;
11338
11339                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11340                 /*
11341                  * if we aren't registered or it's a res holder type
11342                  * reservation and this isn't the res holder then set a
11343                  * conflict.
11344                  * NOTE: Commands which might be allowed on write exclusive
11345                  * type reservations are checked in the particular command
11346                  * for a conflict. Read and SSU are the only ones.
11347                  */
11348                 if (!lun->per_res[residx].registered
11349                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11350                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11351                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11352                         retval = 1;
11353                         goto bailout;
11354                 }
11355
11356         }
11357
11358         if ((lun->flags & CTL_LUN_OFFLINE)
11359          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11360                 ctl_set_lun_not_ready(ctsio);
11361                 retval = 1;
11362                 goto bailout;
11363         }
11364
11365         /*
11366          * If the LUN is stopped, see if this particular command is allowed
11367          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11368          */
11369         if ((lun->flags & CTL_LUN_STOPPED)
11370          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11371                 /* "Logical unit not ready, initializing cmd. required" */
11372                 ctl_set_lun_stopped(ctsio);
11373                 retval = 1;
11374                 goto bailout;
11375         }
11376
11377         if ((lun->flags & CTL_LUN_INOPERABLE)
11378          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11379                 /* "Medium format corrupted" */
11380                 ctl_set_medium_format_corrupted(ctsio);
11381                 retval = 1;
11382                 goto bailout;
11383         }
11384
11385 bailout:
11386         return (retval);
11387
11388 }
11389
11390 static void
11391 ctl_failover_io(union ctl_io *io, int have_lock)
11392 {
11393         ctl_set_busy(&io->scsiio);
11394         ctl_done(io);
11395 }
11396
11397 static void
11398 ctl_failover(void)
11399 {
11400         struct ctl_lun *lun;
11401         struct ctl_softc *ctl_softc;
11402         union ctl_io *next_io, *pending_io;
11403         union ctl_io *io;
11404         int lun_idx;
11405         int i;
11406
11407         ctl_softc = control_softc;
11408
11409         mtx_lock(&ctl_softc->ctl_lock);
11410         /*
11411          * Remove any cmds from the other SC from the rtr queue.  These
11412          * will obviously only be for LUNs for which we're the primary.
11413          * We can't send status or get/send data for these commands.
11414          * Since they haven't been executed yet, we can just remove them.
11415          * We'll either abort them or delete them below, depending on
11416          * which HA mode we're in.
11417          */
11418 #ifdef notyet
11419         mtx_lock(&ctl_softc->queue_lock);
11420         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11421              io != NULL; io = next_io) {
11422                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11423                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11424                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11425                                       ctl_io_hdr, links);
11426         }
11427         mtx_unlock(&ctl_softc->queue_lock);
11428 #endif
11429
11430         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11431                 lun = ctl_softc->ctl_luns[lun_idx];
11432                 if (lun==NULL)
11433                         continue;
11434
11435                 /*
11436                  * Processor LUNs are primary on both sides.
11437                  * XXX will this always be true?
11438                  */
11439                 if (lun->be_lun->lun_type == T_PROCESSOR)
11440                         continue;
11441
11442                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11443                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11444                         printf("FAILOVER: primary lun %d\n", lun_idx);
11445                         /*
11446                          * Remove all commands from the other SC. First from the
11447                          * blocked queue then from the ooa queue. Once we have
11448                          * removed them. Call ctl_check_blocked to see if there
11449                          * is anything that can run.
11450                          */
11451                         for (io = (union ctl_io *)TAILQ_FIRST(
11452                              &lun->blocked_queue); io != NULL; io = next_io) {
11453
11454                                 next_io = (union ctl_io *)TAILQ_NEXT(
11455                                     &io->io_hdr, blocked_links);
11456
11457                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11458                                         TAILQ_REMOVE(&lun->blocked_queue,
11459                                                      &io->io_hdr,blocked_links);
11460                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11461                                         TAILQ_REMOVE(&lun->ooa_queue,
11462                                                      &io->io_hdr, ooa_links);
11463
11464                                         ctl_free_io(io);
11465                                 }
11466                         }
11467
11468                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11469                              io != NULL; io = next_io) {
11470
11471                                 next_io = (union ctl_io *)TAILQ_NEXT(
11472                                     &io->io_hdr, ooa_links);
11473
11474                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11475
11476                                         TAILQ_REMOVE(&lun->ooa_queue,
11477                                                 &io->io_hdr,
11478                                                 ooa_links);
11479
11480                                         ctl_free_io(io);
11481                                 }
11482                         }
11483                         ctl_check_blocked(lun);
11484                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11485                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11486
11487                         printf("FAILOVER: primary lun %d\n", lun_idx);
11488                         /*
11489                          * Abort all commands from the other SC.  We can't
11490                          * send status back for them now.  These should get
11491                          * cleaned up when they are completed or come out
11492                          * for a datamove operation.
11493                          */
11494                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11495                              io != NULL; io = next_io) {
11496                                 next_io = (union ctl_io *)TAILQ_NEXT(
11497                                         &io->io_hdr, ooa_links);
11498
11499                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11500                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11501                         }
11502                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11503                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11504
11505                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11506
11507                         lun->flags |= CTL_LUN_PRIMARY_SC;
11508
11509                         /*
11510                          * We send all I/O that was sent to this controller
11511                          * and redirected to the other side back with
11512                          * busy status, and have the initiator retry it.
11513                          * Figuring out how much data has been transferred,
11514                          * etc. and picking up where we left off would be 
11515                          * very tricky.
11516                          *
11517                          * XXX KDM need to remove I/O from the blocked
11518                          * queue as well!
11519                          */
11520                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11521                              &lun->ooa_queue); pending_io != NULL;
11522                              pending_io = next_io) {
11523
11524                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11525                                         &pending_io->io_hdr, ooa_links);
11526
11527                                 pending_io->io_hdr.flags &=
11528                                         ~CTL_FLAG_SENT_2OTHER_SC;
11529
11530                                 if (pending_io->io_hdr.flags &
11531                                     CTL_FLAG_IO_ACTIVE) {
11532                                         pending_io->io_hdr.flags |=
11533                                                 CTL_FLAG_FAILOVER;
11534                                 } else {
11535                                         ctl_set_busy(&pending_io->scsiio);
11536                                         ctl_done(pending_io);
11537                                 }
11538                         }
11539
11540                         /*
11541                          * Build Unit Attention
11542                          */
11543                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11544                                 lun->pending_ua[i] |=
11545                                                      CTL_UA_ASYM_ACC_CHANGE;
11546                         }
11547                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11548                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11549                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11550                         /*
11551                          * if the first io on the OOA is not on the RtR queue
11552                          * add it.
11553                          */
11554                         lun->flags |= CTL_LUN_PRIMARY_SC;
11555
11556                         pending_io = (union ctl_io *)TAILQ_FIRST(
11557                             &lun->ooa_queue);
11558                         if (pending_io==NULL) {
11559                                 printf("Nothing on OOA queue\n");
11560                                 continue;
11561                         }
11562
11563                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11564                         if ((pending_io->io_hdr.flags &
11565                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11566                                 pending_io->io_hdr.flags |=
11567                                     CTL_FLAG_IS_WAS_ON_RTR;
11568                                 ctl_enqueue_rtr(pending_io);
11569                         }
11570 #if 0
11571                         else
11572                         {
11573                                 printf("Tag 0x%04x is running\n",
11574                                       pending_io->scsiio.tag_num);
11575                         }
11576 #endif
11577
11578                         next_io = (union ctl_io *)TAILQ_NEXT(
11579                             &pending_io->io_hdr, ooa_links);
11580                         for (pending_io=next_io; pending_io != NULL;
11581                              pending_io = next_io) {
11582                                 pending_io->io_hdr.flags &=
11583                                     ~CTL_FLAG_SENT_2OTHER_SC;
11584                                 next_io = (union ctl_io *)TAILQ_NEXT(
11585                                         &pending_io->io_hdr, ooa_links);
11586                                 if (pending_io->io_hdr.flags &
11587                                     CTL_FLAG_IS_WAS_ON_RTR) {
11588 #if 0
11589                                         printf("Tag 0x%04x is running\n",
11590                                                 pending_io->scsiio.tag_num);
11591 #endif
11592                                         continue;
11593                                 }
11594
11595                                 switch (ctl_check_ooa(lun, pending_io,
11596                                     (union ctl_io *)TAILQ_PREV(
11597                                     &pending_io->io_hdr, ctl_ooaq,
11598                                     ooa_links))) {
11599
11600                                 case CTL_ACTION_BLOCK:
11601                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11602                                                           &pending_io->io_hdr,
11603                                                           blocked_links);
11604                                         pending_io->io_hdr.flags |=
11605                                             CTL_FLAG_BLOCKED;
11606                                         break;
11607                                 case CTL_ACTION_PASS:
11608                                 case CTL_ACTION_SKIP:
11609                                         pending_io->io_hdr.flags |=
11610                                             CTL_FLAG_IS_WAS_ON_RTR;
11611                                         ctl_enqueue_rtr(pending_io);
11612                                         break;
11613                                 case CTL_ACTION_OVERLAP:
11614                                         ctl_set_overlapped_cmd(
11615                                             (struct ctl_scsiio *)pending_io);
11616                                         ctl_done(pending_io);
11617                                         break;
11618                                 case CTL_ACTION_OVERLAP_TAG:
11619                                         ctl_set_overlapped_tag(
11620                                             (struct ctl_scsiio *)pending_io,
11621                                             pending_io->scsiio.tag_num & 0xff);
11622                                         ctl_done(pending_io);
11623                                         break;
11624                                 case CTL_ACTION_ERROR:
11625                                 default:
11626                                         ctl_set_internal_failure(
11627                                                 (struct ctl_scsiio *)pending_io,
11628                                                 0,  // sks_valid
11629                                                 0); //retry count
11630                                         ctl_done(pending_io);
11631                                         break;
11632                                 }
11633                         }
11634
11635                         /*
11636                          * Build Unit Attention
11637                          */
11638                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11639                                 lun->pending_ua[i] |=
11640                                                      CTL_UA_ASYM_ACC_CHANGE;
11641                         }
11642                 } else {
11643                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11644                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11645                 }
11646         }
11647         ctl_pause_rtr = 0;
11648         mtx_unlock(&ctl_softc->ctl_lock);
11649 }
11650
11651 static int
11652 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11653 {
11654         struct ctl_lun *lun;
11655         const struct ctl_cmd_entry *entry;
11656         uint32_t initidx, targ_lun;
11657         int retval;
11658
11659         retval = 0;
11660
11661         lun = NULL;
11662
11663         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11664         if ((targ_lun < CTL_MAX_LUNS)
11665          && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11666                 lun = ctl_softc->ctl_luns[targ_lun];
11667                 /*
11668                  * If the LUN is invalid, pretend that it doesn't exist.
11669                  * It will go away as soon as all pending I/O has been
11670                  * completed.
11671                  */
11672                 if (lun->flags & CTL_LUN_DISABLED) {
11673                         lun = NULL;
11674                 } else {
11675                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11676                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11677                                 lun->be_lun;
11678                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11679                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11680                         }
11681
11682                         /*
11683                          * Every I/O goes into the OOA queue for a
11684                          * particular LUN, and stays there until completion.
11685                          */
11686                         mtx_lock(&lun->lun_lock);
11687                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11688                             ooa_links);
11689                 }
11690         } else {
11691                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11692                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11693         }
11694
11695         /* Get command entry and return error if it is unsuppotyed. */
11696         entry = ctl_validate_command(ctsio);
11697         if (entry == NULL) {
11698                 if (lun)
11699                         mtx_unlock(&lun->lun_lock);
11700                 return (retval);
11701         }
11702
11703         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11704         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11705
11706         /*
11707          * Check to see whether we can send this command to LUNs that don't
11708          * exist.  This should pretty much only be the case for inquiry
11709          * and request sense.  Further checks, below, really require having
11710          * a LUN, so we can't really check the command anymore.  Just put
11711          * it on the rtr queue.
11712          */
11713         if (lun == NULL) {
11714                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11715                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11716                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11717                         return (retval);
11718                 }
11719
11720                 ctl_set_unsupported_lun(ctsio);
11721                 ctl_done((union ctl_io *)ctsio);
11722                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11723                 return (retval);
11724         } else {
11725                 /*
11726                  * Make sure we support this particular command on this LUN.
11727                  * e.g., we don't support writes to the control LUN.
11728                  */
11729                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11730                         mtx_unlock(&lun->lun_lock);
11731                         ctl_set_invalid_opcode(ctsio);
11732                         ctl_done((union ctl_io *)ctsio);
11733                         return (retval);
11734                 }
11735         }
11736
11737         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11738
11739 #ifdef CTL_WITH_CA
11740         /*
11741          * If we've got a request sense, it'll clear the contingent
11742          * allegiance condition.  Otherwise, if we have a CA condition for
11743          * this initiator, clear it, because it sent down a command other
11744          * than request sense.
11745          */
11746         if ((ctsio->cdb[0] != REQUEST_SENSE)
11747          && (ctl_is_set(lun->have_ca, initidx)))
11748                 ctl_clear_mask(lun->have_ca, initidx);
11749 #endif
11750
11751         /*
11752          * If the command has this flag set, it handles its own unit
11753          * attention reporting, we shouldn't do anything.  Otherwise we
11754          * check for any pending unit attentions, and send them back to the
11755          * initiator.  We only do this when a command initially comes in,
11756          * not when we pull it off the blocked queue.
11757          *
11758          * According to SAM-3, section 5.3.2, the order that things get
11759          * presented back to the host is basically unit attentions caused
11760          * by some sort of reset event, busy status, reservation conflicts
11761          * or task set full, and finally any other status.
11762          *
11763          * One issue here is that some of the unit attentions we report
11764          * don't fall into the "reset" category (e.g. "reported luns data
11765          * has changed").  So reporting it here, before the reservation
11766          * check, may be technically wrong.  I guess the only thing to do
11767          * would be to check for and report the reset events here, and then
11768          * check for the other unit attention types after we check for a
11769          * reservation conflict.
11770          *
11771          * XXX KDM need to fix this
11772          */
11773         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11774                 ctl_ua_type ua_type;
11775
11776                 if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11777                         scsi_sense_data_type sense_format;
11778
11779                         if (lun != NULL)
11780                                 sense_format = (lun->flags &
11781                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11782                                     SSD_TYPE_FIXED;
11783                         else
11784                                 sense_format = SSD_TYPE_FIXED;
11785
11786                         ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11787                             &ctsio->sense_data, sense_format);
11788                         if (ua_type != CTL_UA_NONE) {
11789                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11790                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11791                                                        CTL_AUTOSENSE;
11792                                 ctsio->sense_len = SSD_FULL_SIZE;
11793                                 mtx_unlock(&lun->lun_lock);
11794                                 ctl_done((union ctl_io *)ctsio);
11795                                 return (retval);
11796                         }
11797                 }
11798         }
11799
11800
11801         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11802                 mtx_unlock(&lun->lun_lock);
11803                 ctl_done((union ctl_io *)ctsio);
11804                 return (retval);
11805         }
11806
11807         /*
11808          * XXX CHD this is where we want to send IO to other side if
11809          * this LUN is secondary on this SC. We will need to make a copy
11810          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11811          * the copy we send as FROM_OTHER.
11812          * We also need to stuff the address of the original IO so we can
11813          * find it easily. Something similar will need be done on the other
11814          * side so when we are done we can find the copy.
11815          */
11816         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11817                 union ctl_ha_msg msg_info;
11818                 int isc_retval;
11819
11820                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11821
11822                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11823                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11824 #if 0
11825                 printf("1. ctsio %p\n", ctsio);
11826 #endif
11827                 msg_info.hdr.serializing_sc = NULL;
11828                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11829                 msg_info.scsi.tag_num = ctsio->tag_num;
11830                 msg_info.scsi.tag_type = ctsio->tag_type;
11831                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11832
11833                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11834
11835                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11836                     (void *)&msg_info, sizeof(msg_info), 0)) >
11837                     CTL_HA_STATUS_SUCCESS) {
11838                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11839                                isc_retval);
11840                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11841                 } else {
11842 #if 0
11843                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11844 #endif
11845                 }
11846
11847                 /*
11848                  * XXX KDM this I/O is off the incoming queue, but hasn't
11849                  * been inserted on any other queue.  We may need to come
11850                  * up with a holding queue while we wait for serialization
11851                  * so that we have an idea of what we're waiting for from
11852                  * the other side.
11853                  */
11854                 mtx_unlock(&lun->lun_lock);
11855                 return (retval);
11856         }
11857
11858         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11859                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11860                               ctl_ooaq, ooa_links))) {
11861         case CTL_ACTION_BLOCK:
11862                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11863                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11864                                   blocked_links);
11865                 mtx_unlock(&lun->lun_lock);
11866                 return (retval);
11867         case CTL_ACTION_PASS:
11868         case CTL_ACTION_SKIP:
11869                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11870                 mtx_unlock(&lun->lun_lock);
11871                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11872                 break;
11873         case CTL_ACTION_OVERLAP:
11874                 mtx_unlock(&lun->lun_lock);
11875                 ctl_set_overlapped_cmd(ctsio);
11876                 ctl_done((union ctl_io *)ctsio);
11877                 break;
11878         case CTL_ACTION_OVERLAP_TAG:
11879                 mtx_unlock(&lun->lun_lock);
11880                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11881                 ctl_done((union ctl_io *)ctsio);
11882                 break;
11883         case CTL_ACTION_ERROR:
11884         default:
11885                 mtx_unlock(&lun->lun_lock);
11886                 ctl_set_internal_failure(ctsio,
11887                                          /*sks_valid*/ 0,
11888                                          /*retry_count*/ 0);
11889                 ctl_done((union ctl_io *)ctsio);
11890                 break;
11891         }
11892         return (retval);
11893 }
11894
11895 const struct ctl_cmd_entry *
11896 ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11897 {
11898         const struct ctl_cmd_entry *entry;
11899         int service_action;
11900
11901         entry = &ctl_cmd_table[ctsio->cdb[0]];
11902         if (entry->flags & CTL_CMD_FLAG_SA5) {
11903                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11904                 entry = &((const struct ctl_cmd_entry *)
11905                     entry->execute)[service_action];
11906         }
11907         return (entry);
11908 }
11909
11910 const struct ctl_cmd_entry *
11911 ctl_validate_command(struct ctl_scsiio *ctsio)
11912 {
11913         const struct ctl_cmd_entry *entry;
11914         int i;
11915         uint8_t diff;
11916
11917         entry = ctl_get_cmd_entry(ctsio);
11918         if (entry->execute == NULL) {
11919                 ctl_set_invalid_opcode(ctsio);
11920                 ctl_done((union ctl_io *)ctsio);
11921                 return (NULL);
11922         }
11923         KASSERT(entry->length > 0,
11924             ("Not defined length for command 0x%02x/0x%02x",
11925              ctsio->cdb[0], ctsio->cdb[1]));
11926         for (i = 1; i < entry->length; i++) {
11927                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11928                 if (diff == 0)
11929                         continue;
11930                 ctl_set_invalid_field(ctsio,
11931                                       /*sks_valid*/ 1,
11932                                       /*command*/ 1,
11933                                       /*field*/ i,
11934                                       /*bit_valid*/ 1,
11935                                       /*bit*/ fls(diff) - 1);
11936                 ctl_done((union ctl_io *)ctsio);
11937                 return (NULL);
11938         }
11939         return (entry);
11940 }
11941
11942 static int
11943 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11944 {
11945
11946         switch (lun_type) {
11947         case T_PROCESSOR:
11948                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11949                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11950                         return (0);
11951                 break;
11952         case T_DIRECT:
11953                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11954                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11955                         return (0);
11956                 break;
11957         default:
11958                 return (0);
11959         }
11960         return (1);
11961 }
11962
11963 static int
11964 ctl_scsiio(struct ctl_scsiio *ctsio)
11965 {
11966         int retval;
11967         const struct ctl_cmd_entry *entry;
11968
11969         retval = CTL_RETVAL_COMPLETE;
11970
11971         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11972
11973         entry = ctl_get_cmd_entry(ctsio);
11974
11975         /*
11976          * If this I/O has been aborted, just send it straight to
11977          * ctl_done() without executing it.
11978          */
11979         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11980                 ctl_done((union ctl_io *)ctsio);
11981                 goto bailout;
11982         }
11983
11984         /*
11985          * All the checks should have been handled by ctl_scsiio_precheck().
11986          * We should be clear now to just execute the I/O.
11987          */
11988         retval = entry->execute(ctsio);
11989
11990 bailout:
11991         return (retval);
11992 }
11993
11994 /*
11995  * Since we only implement one target right now, a bus reset simply resets
11996  * our single target.
11997  */
11998 static int
11999 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
12000 {
12001         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
12002 }
12003
12004 static int
12005 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
12006                  ctl_ua_type ua_type)
12007 {
12008         struct ctl_lun *lun;
12009         int retval;
12010
12011         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12012                 union ctl_ha_msg msg_info;
12013
12014                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12015                 msg_info.hdr.nexus = io->io_hdr.nexus;
12016                 if (ua_type==CTL_UA_TARG_RESET)
12017                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12018                 else
12019                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
12020                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12021                 msg_info.hdr.original_sc = NULL;
12022                 msg_info.hdr.serializing_sc = NULL;
12023                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12024                     (void *)&msg_info, sizeof(msg_info), 0)) {
12025                 }
12026         }
12027         retval = 0;
12028
12029         mtx_lock(&ctl_softc->ctl_lock);
12030         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12031                 retval += ctl_lun_reset(lun, io, ua_type);
12032         mtx_unlock(&ctl_softc->ctl_lock);
12033
12034         return (retval);
12035 }
12036
12037 /*
12038  * The LUN should always be set.  The I/O is optional, and is used to
12039  * distinguish between I/Os sent by this initiator, and by other
12040  * initiators.  We set unit attention for initiators other than this one.
12041  * SAM-3 is vague on this point.  It does say that a unit attention should
12042  * be established for other initiators when a LUN is reset (see section
12043  * 5.7.3), but it doesn't specifically say that the unit attention should
12044  * be established for this particular initiator when a LUN is reset.  Here
12045  * is the relevant text, from SAM-3 rev 8:
12046  *
12047  * 5.7.2 When a SCSI initiator port aborts its own tasks
12048  *
12049  * When a SCSI initiator port causes its own task(s) to be aborted, no
12050  * notification that the task(s) have been aborted shall be returned to
12051  * the SCSI initiator port other than the completion response for the
12052  * command or task management function action that caused the task(s) to
12053  * be aborted and notification(s) associated with related effects of the
12054  * action (e.g., a reset unit attention condition).
12055  *
12056  * XXX KDM for now, we're setting unit attention for all initiators.
12057  */
12058 static int
12059 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12060 {
12061         union ctl_io *xio;
12062 #if 0
12063         uint32_t initindex;
12064 #endif
12065         int i;
12066
12067         mtx_lock(&lun->lun_lock);
12068         /*
12069          * Run through the OOA queue and abort each I/O.
12070          */
12071 #if 0
12072         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12073 #endif
12074         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12075              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12076                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12077         }
12078
12079         /*
12080          * This version sets unit attention for every
12081          */
12082 #if 0
12083         initindex = ctl_get_initindex(&io->io_hdr.nexus);
12084         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12085                 if (initindex == i)
12086                         continue;
12087                 lun->pending_ua[i] |= ua_type;
12088         }
12089 #endif
12090
12091         /*
12092          * A reset (any kind, really) clears reservations established with
12093          * RESERVE/RELEASE.  It does not clear reservations established
12094          * with PERSISTENT RESERVE OUT, but we don't support that at the
12095          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12096          * reservations made with the RESERVE/RELEASE commands, because
12097          * those commands are obsolete in SPC-3.
12098          */
12099         lun->flags &= ~CTL_LUN_RESERVED;
12100
12101         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12102 #ifdef CTL_WITH_CA
12103                 ctl_clear_mask(lun->have_ca, i);
12104 #endif
12105                 lun->pending_ua[i] |= ua_type;
12106         }
12107         mtx_unlock(&lun->lun_lock);
12108
12109         return (0);
12110 }
12111
12112 static void
12113 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12114     int other_sc)
12115 {
12116         union ctl_io *xio;
12117
12118         mtx_assert(&lun->lun_lock, MA_OWNED);
12119
12120         /*
12121          * Run through the OOA queue and attempt to find the given I/O.
12122          * The target port, initiator ID, tag type and tag number have to
12123          * match the values that we got from the initiator.  If we have an
12124          * untagged command to abort, simply abort the first untagged command
12125          * we come to.  We only allow one untagged command at a time of course.
12126          */
12127         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12128              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12129
12130                 if ((targ_port == UINT32_MAX ||
12131                      targ_port == xio->io_hdr.nexus.targ_port) &&
12132                     (init_id == UINT32_MAX ||
12133                      init_id == xio->io_hdr.nexus.initid.id)) {
12134                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12135                             init_id != xio->io_hdr.nexus.initid.id)
12136                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12137                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12138                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12139                                 union ctl_ha_msg msg_info;
12140
12141                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12142                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12143                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12144                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12145                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12146                                 msg_info.hdr.original_sc = NULL;
12147                                 msg_info.hdr.serializing_sc = NULL;
12148                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12149                                     (void *)&msg_info, sizeof(msg_info), 0);
12150                         }
12151                 }
12152         }
12153 }
12154
12155 static int
12156 ctl_abort_task_set(union ctl_io *io)
12157 {
12158         struct ctl_softc *softc = control_softc;
12159         struct ctl_lun *lun;
12160         uint32_t targ_lun;
12161
12162         /*
12163          * Look up the LUN.
12164          */
12165         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12166         mtx_lock(&softc->ctl_lock);
12167         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12168                 lun = softc->ctl_luns[targ_lun];
12169         else {
12170                 mtx_unlock(&softc->ctl_lock);
12171                 return (1);
12172         }
12173
12174         mtx_lock(&lun->lun_lock);
12175         mtx_unlock(&softc->ctl_lock);
12176         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12177                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12178                     io->io_hdr.nexus.initid.id,
12179                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12180         } else { /* CTL_TASK_CLEAR_TASK_SET */
12181                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12182                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12183         }
12184         mtx_unlock(&lun->lun_lock);
12185         return (0);
12186 }
12187
12188 static int
12189 ctl_i_t_nexus_reset(union ctl_io *io)
12190 {
12191         struct ctl_softc *softc = control_softc;
12192         struct ctl_lun *lun;
12193         uint32_t initindex;
12194
12195         initindex = ctl_get_initindex(&io->io_hdr.nexus);
12196         mtx_lock(&softc->ctl_lock);
12197         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12198                 mtx_lock(&lun->lun_lock);
12199                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12200                     io->io_hdr.nexus.initid.id,
12201                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12202 #ifdef CTL_WITH_CA
12203                 ctl_clear_mask(lun->have_ca, initindex);
12204 #endif
12205                 lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12206                 mtx_unlock(&lun->lun_lock);
12207         }
12208         mtx_unlock(&softc->ctl_lock);
12209         return (0);
12210 }
12211
12212 static int
12213 ctl_abort_task(union ctl_io *io)
12214 {
12215         union ctl_io *xio;
12216         struct ctl_lun *lun;
12217         struct ctl_softc *ctl_softc;
12218 #if 0
12219         struct sbuf sb;
12220         char printbuf[128];
12221 #endif
12222         int found;
12223         uint32_t targ_lun;
12224
12225         ctl_softc = control_softc;
12226         found = 0;
12227
12228         /*
12229          * Look up the LUN.
12230          */
12231         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12232         mtx_lock(&ctl_softc->ctl_lock);
12233         if ((targ_lun < CTL_MAX_LUNS)
12234          && (ctl_softc->ctl_luns[targ_lun] != NULL))
12235                 lun = ctl_softc->ctl_luns[targ_lun];
12236         else {
12237                 mtx_unlock(&ctl_softc->ctl_lock);
12238                 return (1);
12239         }
12240
12241 #if 0
12242         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12243                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12244 #endif
12245
12246         mtx_lock(&lun->lun_lock);
12247         mtx_unlock(&ctl_softc->ctl_lock);
12248         /*
12249          * Run through the OOA queue and attempt to find the given I/O.
12250          * The target port, initiator ID, tag type and tag number have to
12251          * match the values that we got from the initiator.  If we have an
12252          * untagged command to abort, simply abort the first untagged command
12253          * we come to.  We only allow one untagged command at a time of course.
12254          */
12255 #if 0
12256         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12257 #endif
12258         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12259              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12260 #if 0
12261                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12262
12263                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12264                             lun->lun, xio->scsiio.tag_num,
12265                             xio->scsiio.tag_type,
12266                             (xio->io_hdr.blocked_links.tqe_prev
12267                             == NULL) ? "" : " BLOCKED",
12268                             (xio->io_hdr.flags &
12269                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12270                             (xio->io_hdr.flags &
12271                             CTL_FLAG_ABORT) ? " ABORT" : "",
12272                             (xio->io_hdr.flags &
12273                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12274                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12275                 sbuf_finish(&sb);
12276                 printf("%s\n", sbuf_data(&sb));
12277 #endif
12278
12279                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12280                  && (xio->io_hdr.nexus.initid.id ==
12281                      io->io_hdr.nexus.initid.id)) {
12282                         /*
12283                          * If the abort says that the task is untagged, the
12284                          * task in the queue must be untagged.  Otherwise,
12285                          * we just check to see whether the tag numbers
12286                          * match.  This is because the QLogic firmware
12287                          * doesn't pass back the tag type in an abort
12288                          * request.
12289                          */
12290 #if 0
12291                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12292                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12293                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12294 #endif
12295                         /*
12296                          * XXX KDM we've got problems with FC, because it
12297                          * doesn't send down a tag type with aborts.  So we
12298                          * can only really go by the tag number...
12299                          * This may cause problems with parallel SCSI.
12300                          * Need to figure that out!!
12301                          */
12302                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12303                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12304                                 found = 1;
12305                                 if ((io->io_hdr.flags &
12306                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12307                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12308                                         union ctl_ha_msg msg_info;
12309
12310                                         io->io_hdr.flags |=
12311                                                         CTL_FLAG_SENT_2OTHER_SC;
12312                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12313                                         msg_info.task.task_action =
12314                                                 CTL_TASK_ABORT_TASK;
12315                                         msg_info.task.tag_num =
12316                                                 io->taskio.tag_num;
12317                                         msg_info.task.tag_type =
12318                                                 io->taskio.tag_type;
12319                                         msg_info.hdr.msg_type =
12320                                                 CTL_MSG_MANAGE_TASKS;
12321                                         msg_info.hdr.original_sc = NULL;
12322                                         msg_info.hdr.serializing_sc = NULL;
12323 #if 0
12324                                         printf("Sent Abort to other side\n");
12325 #endif
12326                                         if (CTL_HA_STATUS_SUCCESS !=
12327                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12328                                                 (void *)&msg_info,
12329                                                 sizeof(msg_info), 0)) {
12330                                         }
12331                                 }
12332 #if 0
12333                                 printf("ctl_abort_task: found I/O to abort\n");
12334 #endif
12335                                 break;
12336                         }
12337                 }
12338         }
12339         mtx_unlock(&lun->lun_lock);
12340
12341         if (found == 0) {
12342                 /*
12343                  * This isn't really an error.  It's entirely possible for
12344                  * the abort and command completion to cross on the wire.
12345                  * This is more of an informative/diagnostic error.
12346                  */
12347 #if 0
12348                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12349                        "%d:%d:%d:%d tag %d type %d\n",
12350                        io->io_hdr.nexus.initid.id,
12351                        io->io_hdr.nexus.targ_port,
12352                        io->io_hdr.nexus.targ_target.id,
12353                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12354                        io->taskio.tag_type);
12355 #endif
12356         }
12357         return (0);
12358 }
12359
12360 static void
12361 ctl_run_task(union ctl_io *io)
12362 {
12363         struct ctl_softc *ctl_softc = control_softc;
12364         int retval = 1;
12365         const char *task_desc;
12366
12367         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12368
12369         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12370             ("ctl_run_task: Unextected io_type %d\n",
12371              io->io_hdr.io_type));
12372
12373         task_desc = ctl_scsi_task_string(&io->taskio);
12374         if (task_desc != NULL) {
12375 #ifdef NEEDTOPORT
12376                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12377                             CTL_TASK_REPORT,
12378                             csevent_LogType_Trace,
12379                             csevent_Severity_Information,
12380                             csevent_AlertLevel_Green,
12381                             csevent_FRU_Firmware,
12382                             csevent_FRU_Unknown,
12383                             "CTL: received task: %s",task_desc);
12384 #endif
12385         } else {
12386 #ifdef NEEDTOPORT
12387                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12388                             CTL_TASK_REPORT,
12389                             csevent_LogType_Trace,
12390                             csevent_Severity_Information,
12391                             csevent_AlertLevel_Green,
12392                             csevent_FRU_Firmware,
12393                             csevent_FRU_Unknown,
12394                             "CTL: received unknown task "
12395                             "type: %d (%#x)",
12396                             io->taskio.task_action,
12397                             io->taskio.task_action);
12398 #endif
12399         }
12400         switch (io->taskio.task_action) {
12401         case CTL_TASK_ABORT_TASK:
12402                 retval = ctl_abort_task(io);
12403                 break;
12404         case CTL_TASK_ABORT_TASK_SET:
12405         case CTL_TASK_CLEAR_TASK_SET:
12406                 retval = ctl_abort_task_set(io);
12407                 break;
12408         case CTL_TASK_CLEAR_ACA:
12409                 break;
12410         case CTL_TASK_I_T_NEXUS_RESET:
12411                 retval = ctl_i_t_nexus_reset(io);
12412                 break;
12413         case CTL_TASK_LUN_RESET: {
12414                 struct ctl_lun *lun;
12415                 uint32_t targ_lun;
12416
12417                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12418                 mtx_lock(&ctl_softc->ctl_lock);
12419                 if ((targ_lun < CTL_MAX_LUNS)
12420                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12421                         lun = ctl_softc->ctl_luns[targ_lun];
12422                 else {
12423                         mtx_unlock(&ctl_softc->ctl_lock);
12424                         retval = 1;
12425                         break;
12426                 }
12427
12428                 if (!(io->io_hdr.flags &
12429                     CTL_FLAG_FROM_OTHER_SC)) {
12430                         union ctl_ha_msg msg_info;
12431
12432                         io->io_hdr.flags |=
12433                                 CTL_FLAG_SENT_2OTHER_SC;
12434                         msg_info.hdr.msg_type =
12435                                 CTL_MSG_MANAGE_TASKS;
12436                         msg_info.hdr.nexus = io->io_hdr.nexus;
12437                         msg_info.task.task_action =
12438                                 CTL_TASK_LUN_RESET;
12439                         msg_info.hdr.original_sc = NULL;
12440                         msg_info.hdr.serializing_sc = NULL;
12441                         if (CTL_HA_STATUS_SUCCESS !=
12442                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12443                             (void *)&msg_info,
12444                             sizeof(msg_info), 0)) {
12445                         }
12446                 }
12447
12448                 retval = ctl_lun_reset(lun, io,
12449                                        CTL_UA_LUN_RESET);
12450                 mtx_unlock(&ctl_softc->ctl_lock);
12451                 break;
12452         }
12453         case CTL_TASK_TARGET_RESET:
12454                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12455                 break;
12456         case CTL_TASK_BUS_RESET:
12457                 retval = ctl_bus_reset(ctl_softc, io);
12458                 break;
12459         case CTL_TASK_PORT_LOGIN:
12460                 break;
12461         case CTL_TASK_PORT_LOGOUT:
12462                 break;
12463         default:
12464                 printf("ctl_run_task: got unknown task management event %d\n",
12465                        io->taskio.task_action);
12466                 break;
12467         }
12468         if (retval == 0)
12469                 io->io_hdr.status = CTL_SUCCESS;
12470         else
12471                 io->io_hdr.status = CTL_ERROR;
12472         ctl_done(io);
12473 }
12474
12475 /*
12476  * For HA operation.  Handle commands that come in from the other
12477  * controller.
12478  */
12479 static void
12480 ctl_handle_isc(union ctl_io *io)
12481 {
12482         int free_io;
12483         struct ctl_lun *lun;
12484         struct ctl_softc *ctl_softc;
12485         uint32_t targ_lun;
12486
12487         ctl_softc = control_softc;
12488
12489         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12490         lun = ctl_softc->ctl_luns[targ_lun];
12491
12492         switch (io->io_hdr.msg_type) {
12493         case CTL_MSG_SERIALIZE:
12494                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12495                 break;
12496         case CTL_MSG_R2R: {
12497                 const struct ctl_cmd_entry *entry;
12498
12499                 /*
12500                  * This is only used in SER_ONLY mode.
12501                  */
12502                 free_io = 0;
12503                 entry = ctl_get_cmd_entry(&io->scsiio);
12504                 mtx_lock(&lun->lun_lock);
12505                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12506                     entry, (struct ctl_scsiio *)io) != 0) {
12507                         mtx_unlock(&lun->lun_lock);
12508                         ctl_done(io);
12509                         break;
12510                 }
12511                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12512                 mtx_unlock(&lun->lun_lock);
12513                 ctl_enqueue_rtr(io);
12514                 break;
12515         }
12516         case CTL_MSG_FINISH_IO:
12517                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12518                         free_io = 0;
12519                         ctl_done(io);
12520                 } else {
12521                         free_io = 1;
12522                         mtx_lock(&lun->lun_lock);
12523                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12524                                      ooa_links);
12525                         ctl_check_blocked(lun);
12526                         mtx_unlock(&lun->lun_lock);
12527                 }
12528                 break;
12529         case CTL_MSG_PERS_ACTION:
12530                 ctl_hndl_per_res_out_on_other_sc(
12531                         (union ctl_ha_msg *)&io->presio.pr_msg);
12532                 free_io = 1;
12533                 break;
12534         case CTL_MSG_BAD_JUJU:
12535                 free_io = 0;
12536                 ctl_done(io);
12537                 break;
12538         case CTL_MSG_DATAMOVE:
12539                 /* Only used in XFER mode */
12540                 free_io = 0;
12541                 ctl_datamove_remote(io);
12542                 break;
12543         case CTL_MSG_DATAMOVE_DONE:
12544                 /* Only used in XFER mode */
12545                 free_io = 0;
12546                 io->scsiio.be_move_done(io);
12547                 break;
12548         default:
12549                 free_io = 1;
12550                 printf("%s: Invalid message type %d\n",
12551                        __func__, io->io_hdr.msg_type);
12552                 break;
12553         }
12554         if (free_io)
12555                 ctl_free_io(io);
12556
12557 }
12558
12559
12560 /*
12561  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12562  * there is no match.
12563  */
12564 static ctl_lun_error_pattern
12565 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12566 {
12567         const struct ctl_cmd_entry *entry;
12568         ctl_lun_error_pattern filtered_pattern, pattern;
12569
12570         pattern = desc->error_pattern;
12571
12572         /*
12573          * XXX KDM we need more data passed into this function to match a
12574          * custom pattern, and we actually need to implement custom pattern
12575          * matching.
12576          */
12577         if (pattern & CTL_LUN_PAT_CMD)
12578                 return (CTL_LUN_PAT_CMD);
12579
12580         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12581                 return (CTL_LUN_PAT_ANY);
12582
12583         entry = ctl_get_cmd_entry(ctsio);
12584
12585         filtered_pattern = entry->pattern & pattern;
12586
12587         /*
12588          * If the user requested specific flags in the pattern (e.g.
12589          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12590          * flags.
12591          *
12592          * If the user did not specify any flags, it doesn't matter whether
12593          * or not the command supports the flags.
12594          */
12595         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12596              (pattern & ~CTL_LUN_PAT_MASK))
12597                 return (CTL_LUN_PAT_NONE);
12598
12599         /*
12600          * If the user asked for a range check, see if the requested LBA
12601          * range overlaps with this command's LBA range.
12602          */
12603         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12604                 uint64_t lba1;
12605                 uint64_t len1;
12606                 ctl_action action;
12607                 int retval;
12608
12609                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12610                 if (retval != 0)
12611                         return (CTL_LUN_PAT_NONE);
12612
12613                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12614                                               desc->lba_range.len);
12615                 /*
12616                  * A "pass" means that the LBA ranges don't overlap, so
12617                  * this doesn't match the user's range criteria.
12618                  */
12619                 if (action == CTL_ACTION_PASS)
12620                         return (CTL_LUN_PAT_NONE);
12621         }
12622
12623         return (filtered_pattern);
12624 }
12625
12626 static void
12627 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12628 {
12629         struct ctl_error_desc *desc, *desc2;
12630
12631         mtx_assert(&lun->lun_lock, MA_OWNED);
12632
12633         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12634                 ctl_lun_error_pattern pattern;
12635                 /*
12636                  * Check to see whether this particular command matches
12637                  * the pattern in the descriptor.
12638                  */
12639                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12640                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12641                         continue;
12642
12643                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12644                 case CTL_LUN_INJ_ABORTED:
12645                         ctl_set_aborted(&io->scsiio);
12646                         break;
12647                 case CTL_LUN_INJ_MEDIUM_ERR:
12648                         ctl_set_medium_error(&io->scsiio);
12649                         break;
12650                 case CTL_LUN_INJ_UA:
12651                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12652                          * OCCURRED */
12653                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12654                         break;
12655                 case CTL_LUN_INJ_CUSTOM:
12656                         /*
12657                          * We're assuming the user knows what he is doing.
12658                          * Just copy the sense information without doing
12659                          * checks.
12660                          */
12661                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12662                               ctl_min(sizeof(desc->custom_sense),
12663                                       sizeof(io->scsiio.sense_data)));
12664                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12665                         io->scsiio.sense_len = SSD_FULL_SIZE;
12666                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12667                         break;
12668                 case CTL_LUN_INJ_NONE:
12669                 default:
12670                         /*
12671                          * If this is an error injection type we don't know
12672                          * about, clear the continuous flag (if it is set)
12673                          * so it will get deleted below.
12674                          */
12675                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12676                         break;
12677                 }
12678                 /*
12679                  * By default, each error injection action is a one-shot
12680                  */
12681                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12682                         continue;
12683
12684                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12685
12686                 free(desc, M_CTL);
12687         }
12688 }
12689
12690 #ifdef CTL_IO_DELAY
12691 static void
12692 ctl_datamove_timer_wakeup(void *arg)
12693 {
12694         union ctl_io *io;
12695
12696         io = (union ctl_io *)arg;
12697
12698         ctl_datamove(io);
12699 }
12700 #endif /* CTL_IO_DELAY */
12701
12702 void
12703 ctl_datamove(union ctl_io *io)
12704 {
12705         void (*fe_datamove)(union ctl_io *io);
12706
12707         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12708
12709         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12710
12711 #ifdef CTL_TIME_IO
12712         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12713                 char str[256];
12714                 char path_str[64];
12715                 struct sbuf sb;
12716
12717                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12718                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12719
12720                 sbuf_cat(&sb, path_str);
12721                 switch (io->io_hdr.io_type) {
12722                 case CTL_IO_SCSI:
12723                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12724                         sbuf_printf(&sb, "\n");
12725                         sbuf_cat(&sb, path_str);
12726                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12727                                     io->scsiio.tag_num, io->scsiio.tag_type);
12728                         break;
12729                 case CTL_IO_TASK:
12730                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12731                                     "Tag Type: %d\n", io->taskio.task_action,
12732                                     io->taskio.tag_num, io->taskio.tag_type);
12733                         break;
12734                 default:
12735                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12736                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12737                         break;
12738                 }
12739                 sbuf_cat(&sb, path_str);
12740                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12741                             (intmax_t)time_uptime - io->io_hdr.start_time);
12742                 sbuf_finish(&sb);
12743                 printf("%s", sbuf_data(&sb));
12744         }
12745 #endif /* CTL_TIME_IO */
12746
12747 #ifdef CTL_IO_DELAY
12748         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12749                 struct ctl_lun *lun;
12750
12751                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12752
12753                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12754         } else {
12755                 struct ctl_lun *lun;
12756
12757                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12758                 if ((lun != NULL)
12759                  && (lun->delay_info.datamove_delay > 0)) {
12760                         struct callout *callout;
12761
12762                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12763                         callout_init(callout, /*mpsafe*/ 1);
12764                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12765                         callout_reset(callout,
12766                                       lun->delay_info.datamove_delay * hz,
12767                                       ctl_datamove_timer_wakeup, io);
12768                         if (lun->delay_info.datamove_type ==
12769                             CTL_DELAY_TYPE_ONESHOT)
12770                                 lun->delay_info.datamove_delay = 0;
12771                         return;
12772                 }
12773         }
12774 #endif
12775
12776         /*
12777          * This command has been aborted.  Set the port status, so we fail
12778          * the data move.
12779          */
12780         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12781                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12782                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12783                        io->io_hdr.nexus.targ_port,
12784                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12785                        io->io_hdr.nexus.targ_lun);
12786                 io->io_hdr.port_status = 31337;
12787                 /*
12788                  * Note that the backend, in this case, will get the
12789                  * callback in its context.  In other cases it may get
12790                  * called in the frontend's interrupt thread context.
12791                  */
12792                 io->scsiio.be_move_done(io);
12793                 return;
12794         }
12795
12796         /*
12797          * If we're in XFER mode and this I/O is from the other shelf
12798          * controller, we need to send the DMA to the other side to
12799          * actually transfer the data to/from the host.  In serialize only
12800          * mode the transfer happens below CTL and ctl_datamove() is only
12801          * called on the machine that originally received the I/O.
12802          */
12803         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12804          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12805                 union ctl_ha_msg msg;
12806                 uint32_t sg_entries_sent;
12807                 int do_sg_copy;
12808                 int i;
12809
12810                 memset(&msg, 0, sizeof(msg));
12811                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12812                 msg.hdr.original_sc = io->io_hdr.original_sc;
12813                 msg.hdr.serializing_sc = io;
12814                 msg.hdr.nexus = io->io_hdr.nexus;
12815                 msg.dt.flags = io->io_hdr.flags;
12816                 /*
12817                  * We convert everything into a S/G list here.  We can't
12818                  * pass by reference, only by value between controllers.
12819                  * So we can't pass a pointer to the S/G list, only as many
12820                  * S/G entries as we can fit in here.  If it's possible for
12821                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12822                  * then we need to break this up into multiple transfers.
12823                  */
12824                 if (io->scsiio.kern_sg_entries == 0) {
12825                         msg.dt.kern_sg_entries = 1;
12826                         /*
12827                          * If this is in cached memory, flush the cache
12828                          * before we send the DMA request to the other
12829                          * controller.  We want to do this in either the
12830                          * read or the write case.  The read case is
12831                          * straightforward.  In the write case, we want to
12832                          * make sure nothing is in the local cache that
12833                          * could overwrite the DMAed data.
12834                          */
12835                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12836                                 /*
12837                                  * XXX KDM use bus_dmamap_sync() here.
12838                                  */
12839                         }
12840
12841                         /*
12842                          * Convert to a physical address if this is a
12843                          * virtual address.
12844                          */
12845                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12846                                 msg.dt.sg_list[0].addr =
12847                                         io->scsiio.kern_data_ptr;
12848                         } else {
12849                                 /*
12850                                  * XXX KDM use busdma here!
12851                                  */
12852 #if 0
12853                                 msg.dt.sg_list[0].addr = (void *)
12854                                         vtophys(io->scsiio.kern_data_ptr);
12855 #endif
12856                         }
12857
12858                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12859                         do_sg_copy = 0;
12860                 } else {
12861                         struct ctl_sg_entry *sgl;
12862
12863                         do_sg_copy = 1;
12864                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12865                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12866                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12867                                 /*
12868                                  * XXX KDM use bus_dmamap_sync() here.
12869                                  */
12870                         }
12871                 }
12872
12873                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12874                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12875                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12876                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12877                 msg.dt.sg_sequence = 0;
12878
12879                 /*
12880                  * Loop until we've sent all of the S/G entries.  On the
12881                  * other end, we'll recompose these S/G entries into one
12882                  * contiguous list before passing it to the
12883                  */
12884                 for (sg_entries_sent = 0; sg_entries_sent <
12885                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12886                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12887                                 sizeof(msg.dt.sg_list[0])),
12888                                 msg.dt.kern_sg_entries - sg_entries_sent);
12889
12890                         if (do_sg_copy != 0) {
12891                                 struct ctl_sg_entry *sgl;
12892                                 int j;
12893
12894                                 sgl = (struct ctl_sg_entry *)
12895                                         io->scsiio.kern_data_ptr;
12896                                 /*
12897                                  * If this is in cached memory, flush the cache
12898                                  * before we send the DMA request to the other
12899                                  * controller.  We want to do this in either
12900                                  * the * read or the write case.  The read
12901                                  * case is straightforward.  In the write
12902                                  * case, we want to make sure nothing is
12903                                  * in the local cache that could overwrite
12904                                  * the DMAed data.
12905                                  */
12906
12907                                 for (i = sg_entries_sent, j = 0;
12908                                      i < msg.dt.cur_sg_entries; i++, j++) {
12909                                         if ((io->io_hdr.flags &
12910                                              CTL_FLAG_NO_DATASYNC) == 0) {
12911                                                 /*
12912                                                  * XXX KDM use bus_dmamap_sync()
12913                                                  */
12914                                         }
12915                                         if ((io->io_hdr.flags &
12916                                              CTL_FLAG_BUS_ADDR) == 0) {
12917                                                 /*
12918                                                  * XXX KDM use busdma.
12919                                                  */
12920 #if 0
12921                                                 msg.dt.sg_list[j].addr =(void *)
12922                                                        vtophys(sgl[i].addr);
12923 #endif
12924                                         } else {
12925                                                 msg.dt.sg_list[j].addr =
12926                                                         sgl[i].addr;
12927                                         }
12928                                         msg.dt.sg_list[j].len = sgl[i].len;
12929                                 }
12930                         }
12931
12932                         sg_entries_sent += msg.dt.cur_sg_entries;
12933                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12934                                 msg.dt.sg_last = 1;
12935                         else
12936                                 msg.dt.sg_last = 0;
12937
12938                         /*
12939                          * XXX KDM drop and reacquire the lock here?
12940                          */
12941                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12942                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12943                                 /*
12944                                  * XXX do something here.
12945                                  */
12946                         }
12947
12948                         msg.dt.sent_sg_entries = sg_entries_sent;
12949                 }
12950                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12951                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12952                         ctl_failover_io(io, /*have_lock*/ 0);
12953
12954         } else {
12955
12956                 /*
12957                  * Lookup the fe_datamove() function for this particular
12958                  * front end.
12959                  */
12960                 fe_datamove =
12961                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12962
12963                 fe_datamove(io);
12964         }
12965 }
12966
12967 static void
12968 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12969 {
12970         union ctl_ha_msg msg;
12971         int isc_status;
12972
12973         memset(&msg, 0, sizeof(msg));
12974
12975         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12976         msg.hdr.original_sc = io;
12977         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12978         msg.hdr.nexus = io->io_hdr.nexus;
12979         msg.hdr.status = io->io_hdr.status;
12980         msg.scsi.tag_num = io->scsiio.tag_num;
12981         msg.scsi.tag_type = io->scsiio.tag_type;
12982         msg.scsi.scsi_status = io->scsiio.scsi_status;
12983         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12984                sizeof(io->scsiio.sense_data));
12985         msg.scsi.sense_len = io->scsiio.sense_len;
12986         msg.scsi.sense_residual = io->scsiio.sense_residual;
12987         msg.scsi.fetd_status = io->io_hdr.port_status;
12988         msg.scsi.residual = io->scsiio.residual;
12989         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12990
12991         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12992                 ctl_failover_io(io, /*have_lock*/ have_lock);
12993                 return;
12994         }
12995
12996         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12997         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12998                 /* XXX do something if this fails */
12999         }
13000
13001 }
13002
13003 /*
13004  * The DMA to the remote side is done, now we need to tell the other side
13005  * we're done so it can continue with its data movement.
13006  */
13007 static void
13008 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13009 {
13010         union ctl_io *io;
13011
13012         io = rq->context;
13013
13014         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13015                 printf("%s: ISC DMA write failed with error %d", __func__,
13016                        rq->ret);
13017                 ctl_set_internal_failure(&io->scsiio,
13018                                          /*sks_valid*/ 1,
13019                                          /*retry_count*/ rq->ret);
13020         }
13021
13022         ctl_dt_req_free(rq);
13023
13024         /*
13025          * In this case, we had to malloc the memory locally.  Free it.
13026          */
13027         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13028                 int i;
13029                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13030                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13031         }
13032         /*
13033          * The data is in local and remote memory, so now we need to send
13034          * status (good or back) back to the other side.
13035          */
13036         ctl_send_datamove_done(io, /*have_lock*/ 0);
13037 }
13038
13039 /*
13040  * We've moved the data from the host/controller into local memory.  Now we
13041  * need to push it over to the remote controller's memory.
13042  */
13043 static int
13044 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13045 {
13046         int retval;
13047
13048         retval = 0;
13049
13050         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13051                                           ctl_datamove_remote_write_cb);
13052
13053         return (retval);
13054 }
13055
13056 static void
13057 ctl_datamove_remote_write(union ctl_io *io)
13058 {
13059         int retval;
13060         void (*fe_datamove)(union ctl_io *io);
13061
13062         /*
13063          * - Get the data from the host/HBA into local memory.
13064          * - DMA memory from the local controller to the remote controller.
13065          * - Send status back to the remote controller.
13066          */
13067
13068         retval = ctl_datamove_remote_sgl_setup(io);
13069         if (retval != 0)
13070                 return;
13071
13072         /* Switch the pointer over so the FETD knows what to do */
13073         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13074
13075         /*
13076          * Use a custom move done callback, since we need to send completion
13077          * back to the other controller, not to the backend on this side.
13078          */
13079         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13080
13081         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13082
13083         fe_datamove(io);
13084
13085         return;
13086
13087 }
13088
13089 static int
13090 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13091 {
13092 #if 0
13093         char str[256];
13094         char path_str[64];
13095         struct sbuf sb;
13096 #endif
13097
13098         /*
13099          * In this case, we had to malloc the memory locally.  Free it.
13100          */
13101         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13102                 int i;
13103                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13104                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13105         }
13106
13107 #if 0
13108         scsi_path_string(io, path_str, sizeof(path_str));
13109         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13110         sbuf_cat(&sb, path_str);
13111         scsi_command_string(&io->scsiio, NULL, &sb);
13112         sbuf_printf(&sb, "\n");
13113         sbuf_cat(&sb, path_str);
13114         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13115                     io->scsiio.tag_num, io->scsiio.tag_type);
13116         sbuf_cat(&sb, path_str);
13117         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13118                     io->io_hdr.flags, io->io_hdr.status);
13119         sbuf_finish(&sb);
13120         printk("%s", sbuf_data(&sb));
13121 #endif
13122
13123
13124         /*
13125          * The read is done, now we need to send status (good or bad) back
13126          * to the other side.
13127          */
13128         ctl_send_datamove_done(io, /*have_lock*/ 0);
13129
13130         return (0);
13131 }
13132
13133 static void
13134 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13135 {
13136         union ctl_io *io;
13137         void (*fe_datamove)(union ctl_io *io);
13138
13139         io = rq->context;
13140
13141         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13142                 printf("%s: ISC DMA read failed with error %d", __func__,
13143                        rq->ret);
13144                 ctl_set_internal_failure(&io->scsiio,
13145                                          /*sks_valid*/ 1,
13146                                          /*retry_count*/ rq->ret);
13147         }
13148
13149         ctl_dt_req_free(rq);
13150
13151         /* Switch the pointer over so the FETD knows what to do */
13152         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13153
13154         /*
13155          * Use a custom move done callback, since we need to send completion
13156          * back to the other controller, not to the backend on this side.
13157          */
13158         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13159
13160         /* XXX KDM add checks like the ones in ctl_datamove? */
13161
13162         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13163
13164         fe_datamove(io);
13165 }
13166
13167 static int
13168 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13169 {
13170         struct ctl_sg_entry *local_sglist, *remote_sglist;
13171         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13172         struct ctl_softc *softc;
13173         int retval;
13174         int i;
13175
13176         retval = 0;
13177         softc = control_softc;
13178
13179         local_sglist = io->io_hdr.local_sglist;
13180         local_dma_sglist = io->io_hdr.local_dma_sglist;
13181         remote_sglist = io->io_hdr.remote_sglist;
13182         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13183
13184         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13185                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13186                         local_sglist[i].len = remote_sglist[i].len;
13187
13188                         /*
13189                          * XXX Detect the situation where the RS-level I/O
13190                          * redirector on the other side has already read the
13191                          * data off of the AOR RS on this side, and
13192                          * transferred it to remote (mirror) memory on the
13193                          * other side.  Since we already have the data in
13194                          * memory here, we just need to use it.
13195                          *
13196                          * XXX KDM this can probably be removed once we
13197                          * get the cache device code in and take the
13198                          * current AOR implementation out.
13199                          */
13200 #ifdef NEEDTOPORT
13201                         if ((remote_sglist[i].addr >=
13202                              (void *)vtophys(softc->mirr->addr))
13203                          && (remote_sglist[i].addr <
13204                              ((void *)vtophys(softc->mirr->addr) +
13205                              CacheMirrorOffset))) {
13206                                 local_sglist[i].addr = remote_sglist[i].addr -
13207                                         CacheMirrorOffset;
13208                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13209                                      CTL_FLAG_DATA_IN)
13210                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13211                         } else {
13212                                 local_sglist[i].addr = remote_sglist[i].addr +
13213                                         CacheMirrorOffset;
13214                         }
13215 #endif
13216 #if 0
13217                         printf("%s: local %p, remote %p, len %d\n",
13218                                __func__, local_sglist[i].addr,
13219                                remote_sglist[i].addr, local_sglist[i].len);
13220 #endif
13221                 }
13222         } else {
13223                 uint32_t len_to_go;
13224
13225                 /*
13226                  * In this case, we don't have automatically allocated
13227                  * memory for this I/O on this controller.  This typically
13228                  * happens with internal CTL I/O -- e.g. inquiry, mode
13229                  * sense, etc.  Anything coming from RAIDCore will have
13230                  * a mirror area available.
13231                  */
13232                 len_to_go = io->scsiio.kern_data_len;
13233
13234                 /*
13235                  * Clear the no datasync flag, we have to use malloced
13236                  * buffers.
13237                  */
13238                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13239
13240                 /*
13241                  * The difficult thing here is that the size of the various
13242                  * S/G segments may be different than the size from the
13243                  * remote controller.  That'll make it harder when DMAing
13244                  * the data back to the other side.
13245                  */
13246                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13247                      sizeof(io->io_hdr.remote_sglist[0])) &&
13248                      (len_to_go > 0); i++) {
13249                         local_sglist[i].len = ctl_min(len_to_go, 131072);
13250                         CTL_SIZE_8B(local_dma_sglist[i].len,
13251                                     local_sglist[i].len);
13252                         local_sglist[i].addr =
13253                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13254
13255                         local_dma_sglist[i].addr = local_sglist[i].addr;
13256
13257                         if (local_sglist[i].addr == NULL) {
13258                                 int j;
13259
13260                                 printf("malloc failed for %zd bytes!",
13261                                        local_dma_sglist[i].len);
13262                                 for (j = 0; j < i; j++) {
13263                                         free(local_sglist[j].addr, M_CTL);
13264                                 }
13265                                 ctl_set_internal_failure(&io->scsiio,
13266                                                          /*sks_valid*/ 1,
13267                                                          /*retry_count*/ 4857);
13268                                 retval = 1;
13269                                 goto bailout_error;
13270                                 
13271                         }
13272                         /* XXX KDM do we need a sync here? */
13273
13274                         len_to_go -= local_sglist[i].len;
13275                 }
13276                 /*
13277                  * Reset the number of S/G entries accordingly.  The
13278                  * original number of S/G entries is available in
13279                  * rem_sg_entries.
13280                  */
13281                 io->scsiio.kern_sg_entries = i;
13282
13283 #if 0
13284                 printf("%s: kern_sg_entries = %d\n", __func__,
13285                        io->scsiio.kern_sg_entries);
13286                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13287                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13288                                local_sglist[i].addr, local_sglist[i].len,
13289                                local_dma_sglist[i].len);
13290 #endif
13291         }
13292
13293
13294         return (retval);
13295
13296 bailout_error:
13297
13298         ctl_send_datamove_done(io, /*have_lock*/ 0);
13299
13300         return (retval);
13301 }
13302
13303 static int
13304 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13305                          ctl_ha_dt_cb callback)
13306 {
13307         struct ctl_ha_dt_req *rq;
13308         struct ctl_sg_entry *remote_sglist, *local_sglist;
13309         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13310         uint32_t local_used, remote_used, total_used;
13311         int retval;
13312         int i, j;
13313
13314         retval = 0;
13315
13316         rq = ctl_dt_req_alloc();
13317
13318         /*
13319          * If we failed to allocate the request, and if the DMA didn't fail
13320          * anyway, set busy status.  This is just a resource allocation
13321          * failure.
13322          */
13323         if ((rq == NULL)
13324          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13325                 ctl_set_busy(&io->scsiio);
13326
13327         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13328
13329                 if (rq != NULL)
13330                         ctl_dt_req_free(rq);
13331
13332                 /*
13333                  * The data move failed.  We need to return status back
13334                  * to the other controller.  No point in trying to DMA
13335                  * data to the remote controller.
13336                  */
13337
13338                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13339
13340                 retval = 1;
13341
13342                 goto bailout;
13343         }
13344
13345         local_sglist = io->io_hdr.local_sglist;
13346         local_dma_sglist = io->io_hdr.local_dma_sglist;
13347         remote_sglist = io->io_hdr.remote_sglist;
13348         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13349         local_used = 0;
13350         remote_used = 0;
13351         total_used = 0;
13352
13353         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13354                 rq->ret = CTL_HA_STATUS_SUCCESS;
13355                 rq->context = io;
13356                 callback(rq);
13357                 goto bailout;
13358         }
13359
13360         /*
13361          * Pull/push the data over the wire from/to the other controller.
13362          * This takes into account the possibility that the local and
13363          * remote sglists may not be identical in terms of the size of
13364          * the elements and the number of elements.
13365          *
13366          * One fundamental assumption here is that the length allocated for
13367          * both the local and remote sglists is identical.  Otherwise, we've
13368          * essentially got a coding error of some sort.
13369          */
13370         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13371                 int isc_ret;
13372                 uint32_t cur_len, dma_length;
13373                 uint8_t *tmp_ptr;
13374
13375                 rq->id = CTL_HA_DATA_CTL;
13376                 rq->command = command;
13377                 rq->context = io;
13378
13379                 /*
13380                  * Both pointers should be aligned.  But it is possible
13381                  * that the allocation length is not.  They should both
13382                  * also have enough slack left over at the end, though,
13383                  * to round up to the next 8 byte boundary.
13384                  */
13385                 cur_len = ctl_min(local_sglist[i].len - local_used,
13386                                   remote_sglist[j].len - remote_used);
13387
13388                 /*
13389                  * In this case, we have a size issue and need to decrease
13390                  * the size, except in the case where we actually have less
13391                  * than 8 bytes left.  In that case, we need to increase
13392                  * the DMA length to get the last bit.
13393                  */
13394                 if ((cur_len & 0x7) != 0) {
13395                         if (cur_len > 0x7) {
13396                                 cur_len = cur_len - (cur_len & 0x7);
13397                                 dma_length = cur_len;
13398                         } else {
13399                                 CTL_SIZE_8B(dma_length, cur_len);
13400                         }
13401
13402                 } else
13403                         dma_length = cur_len;
13404
13405                 /*
13406                  * If we had to allocate memory for this I/O, instead of using
13407                  * the non-cached mirror memory, we'll need to flush the cache
13408                  * before trying to DMA to the other controller.
13409                  *
13410                  * We could end up doing this multiple times for the same
13411                  * segment if we have a larger local segment than remote
13412                  * segment.  That shouldn't be an issue.
13413                  */
13414                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13415                         /*
13416                          * XXX KDM use bus_dmamap_sync() here.
13417                          */
13418                 }
13419
13420                 rq->size = dma_length;
13421
13422                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13423                 tmp_ptr += local_used;
13424
13425                 /* Use physical addresses when talking to ISC hardware */
13426                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13427                         /* XXX KDM use busdma */
13428 #if 0
13429                         rq->local = vtophys(tmp_ptr);
13430 #endif
13431                 } else
13432                         rq->local = tmp_ptr;
13433
13434                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13435                 tmp_ptr += remote_used;
13436                 rq->remote = tmp_ptr;
13437
13438                 rq->callback = NULL;
13439
13440                 local_used += cur_len;
13441                 if (local_used >= local_sglist[i].len) {
13442                         i++;
13443                         local_used = 0;
13444                 }
13445
13446                 remote_used += cur_len;
13447                 if (remote_used >= remote_sglist[j].len) {
13448                         j++;
13449                         remote_used = 0;
13450                 }
13451                 total_used += cur_len;
13452
13453                 if (total_used >= io->scsiio.kern_data_len)
13454                         rq->callback = callback;
13455
13456                 if ((rq->size & 0x7) != 0) {
13457                         printf("%s: warning: size %d is not on 8b boundary\n",
13458                                __func__, rq->size);
13459                 }
13460                 if (((uintptr_t)rq->local & 0x7) != 0) {
13461                         printf("%s: warning: local %p not on 8b boundary\n",
13462                                __func__, rq->local);
13463                 }
13464                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13465                         printf("%s: warning: remote %p not on 8b boundary\n",
13466                                __func__, rq->local);
13467                 }
13468 #if 0
13469                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13470                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13471                        rq->local, rq->remote, rq->size);
13472 #endif
13473
13474                 isc_ret = ctl_dt_single(rq);
13475                 if (isc_ret == CTL_HA_STATUS_WAIT)
13476                         continue;
13477
13478                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13479                         rq->ret = CTL_HA_STATUS_SUCCESS;
13480                 } else {
13481                         rq->ret = isc_ret;
13482                 }
13483                 callback(rq);
13484                 goto bailout;
13485         }
13486
13487 bailout:
13488         return (retval);
13489
13490 }
13491
13492 static void
13493 ctl_datamove_remote_read(union ctl_io *io)
13494 {
13495         int retval;
13496         int i;
13497
13498         /*
13499          * This will send an error to the other controller in the case of a
13500          * failure.
13501          */
13502         retval = ctl_datamove_remote_sgl_setup(io);
13503         if (retval != 0)
13504                 return;
13505
13506         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13507                                           ctl_datamove_remote_read_cb);
13508         if ((retval != 0)
13509          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13510                 /*
13511                  * Make sure we free memory if there was an error..  The
13512                  * ctl_datamove_remote_xfer() function will send the
13513                  * datamove done message, or call the callback with an
13514                  * error if there is a problem.
13515                  */
13516                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13517                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13518         }
13519
13520         return;
13521 }
13522
13523 /*
13524  * Process a datamove request from the other controller.  This is used for
13525  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13526  * first.  Once that is complete, the data gets DMAed into the remote
13527  * controller's memory.  For reads, we DMA from the remote controller's
13528  * memory into our memory first, and then move it out to the FETD.
13529  */
13530 static void
13531 ctl_datamove_remote(union ctl_io *io)
13532 {
13533         struct ctl_softc *softc;
13534
13535         softc = control_softc;
13536
13537         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13538
13539         /*
13540          * Note that we look for an aborted I/O here, but don't do some of
13541          * the other checks that ctl_datamove() normally does.
13542          * We don't need to run the datamove delay code, since that should
13543          * have been done if need be on the other controller.
13544          */
13545         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13546                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13547                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13548                        io->io_hdr.nexus.targ_port,
13549                        io->io_hdr.nexus.targ_target.id,
13550                        io->io_hdr.nexus.targ_lun);
13551                 io->io_hdr.port_status = 31338;
13552                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13553                 return;
13554         }
13555
13556         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13557                 ctl_datamove_remote_write(io);
13558         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13559                 ctl_datamove_remote_read(io);
13560         } else {
13561                 union ctl_ha_msg msg;
13562                 struct scsi_sense_data *sense;
13563                 uint8_t sks[3];
13564                 int retry_count;
13565
13566                 memset(&msg, 0, sizeof(msg));
13567
13568                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13569                 msg.hdr.status = CTL_SCSI_ERROR;
13570                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13571
13572                 retry_count = 4243;
13573
13574                 sense = &msg.scsi.sense_data;
13575                 sks[0] = SSD_SCS_VALID;
13576                 sks[1] = (retry_count >> 8) & 0xff;
13577                 sks[2] = retry_count & 0xff;
13578
13579                 /* "Internal target failure" */
13580                 scsi_set_sense_data(sense,
13581                                     /*sense_format*/ SSD_TYPE_NONE,
13582                                     /*current_error*/ 1,
13583                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13584                                     /*asc*/ 0x44,
13585                                     /*ascq*/ 0x00,
13586                                     /*type*/ SSD_ELEM_SKS,
13587                                     /*size*/ sizeof(sks),
13588                                     /*data*/ sks,
13589                                     SSD_ELEM_NONE);
13590
13591                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13592                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13593                         ctl_failover_io(io, /*have_lock*/ 1);
13594                         return;
13595                 }
13596
13597                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13598                     CTL_HA_STATUS_SUCCESS) {
13599                         /* XXX KDM what to do if this fails? */
13600                 }
13601                 return;
13602         }
13603         
13604 }
13605
13606 static int
13607 ctl_process_done(union ctl_io *io)
13608 {
13609         struct ctl_lun *lun;
13610         struct ctl_softc *ctl_softc;
13611         void (*fe_done)(union ctl_io *io);
13612         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13613
13614         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13615
13616         fe_done =
13617             control_softc->ctl_ports[targ_port]->fe_done;
13618
13619 #ifdef CTL_TIME_IO
13620         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13621                 char str[256];
13622                 char path_str[64];
13623                 struct sbuf sb;
13624
13625                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13626                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13627
13628                 sbuf_cat(&sb, path_str);
13629                 switch (io->io_hdr.io_type) {
13630                 case CTL_IO_SCSI:
13631                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13632                         sbuf_printf(&sb, "\n");
13633                         sbuf_cat(&sb, path_str);
13634                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13635                                     io->scsiio.tag_num, io->scsiio.tag_type);
13636                         break;
13637                 case CTL_IO_TASK:
13638                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13639                                     "Tag Type: %d\n", io->taskio.task_action,
13640                                     io->taskio.tag_num, io->taskio.tag_type);
13641                         break;
13642                 default:
13643                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13644                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13645                         break;
13646                 }
13647                 sbuf_cat(&sb, path_str);
13648                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13649                             (intmax_t)time_uptime - io->io_hdr.start_time);
13650                 sbuf_finish(&sb);
13651                 printf("%s", sbuf_data(&sb));
13652         }
13653 #endif /* CTL_TIME_IO */
13654
13655         switch (io->io_hdr.io_type) {
13656         case CTL_IO_SCSI:
13657                 break;
13658         case CTL_IO_TASK:
13659                 if (bootverbose || verbose > 0)
13660                         ctl_io_error_print(io, NULL);
13661                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13662                         ctl_free_io(io);
13663                 else
13664                         fe_done(io);
13665                 return (CTL_RETVAL_COMPLETE);
13666                 break;
13667         default:
13668                 printf("ctl_process_done: invalid io type %d\n",
13669                        io->io_hdr.io_type);
13670                 panic("ctl_process_done: invalid io type %d\n",
13671                       io->io_hdr.io_type);
13672                 break; /* NOTREACHED */
13673         }
13674
13675         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13676         if (lun == NULL) {
13677                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13678                                  io->io_hdr.nexus.targ_mapped_lun));
13679                 fe_done(io);
13680                 goto bailout;
13681         }
13682         ctl_softc = lun->ctl_softc;
13683
13684         mtx_lock(&lun->lun_lock);
13685
13686         /*
13687          * Check to see if we have any errors to inject here.  We only
13688          * inject errors for commands that don't already have errors set.
13689          */
13690         if ((STAILQ_FIRST(&lun->error_list) != NULL)
13691          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13692                 ctl_inject_error(lun, io);
13693
13694         /*
13695          * XXX KDM how do we treat commands that aren't completed
13696          * successfully?
13697          *
13698          * XXX KDM should we also track I/O latency?
13699          */
13700         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13701             io->io_hdr.io_type == CTL_IO_SCSI) {
13702 #ifdef CTL_TIME_IO
13703                 struct bintime cur_bt;
13704 #endif
13705                 int type;
13706
13707                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13708                     CTL_FLAG_DATA_IN)
13709                         type = CTL_STATS_READ;
13710                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13711                     CTL_FLAG_DATA_OUT)
13712                         type = CTL_STATS_WRITE;
13713                 else
13714                         type = CTL_STATS_NO_IO;
13715
13716                 lun->stats.ports[targ_port].bytes[type] +=
13717                     io->scsiio.kern_total_len;
13718                 lun->stats.ports[targ_port].operations[type]++;
13719 #ifdef CTL_TIME_IO
13720                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13721                    &io->io_hdr.dma_bt);
13722                 lun->stats.ports[targ_port].num_dmas[type] +=
13723                     io->io_hdr.num_dmas;
13724                 getbintime(&cur_bt);
13725                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13726                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13727 #endif
13728         }
13729
13730         /*
13731          * Remove this from the OOA queue.
13732          */
13733         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13734
13735         /*
13736          * Run through the blocked queue on this LUN and see if anything
13737          * has become unblocked, now that this transaction is done.
13738          */
13739         ctl_check_blocked(lun);
13740
13741         /*
13742          * If the LUN has been invalidated, free it if there is nothing
13743          * left on its OOA queue.
13744          */
13745         if ((lun->flags & CTL_LUN_INVALID)
13746          && TAILQ_EMPTY(&lun->ooa_queue)) {
13747                 mtx_unlock(&lun->lun_lock);
13748                 mtx_lock(&ctl_softc->ctl_lock);
13749                 ctl_free_lun(lun);
13750                 mtx_unlock(&ctl_softc->ctl_lock);
13751         } else
13752                 mtx_unlock(&lun->lun_lock);
13753
13754         /*
13755          * If this command has been aborted, make sure we set the status
13756          * properly.  The FETD is responsible for freeing the I/O and doing
13757          * whatever it needs to do to clean up its state.
13758          */
13759         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13760                 ctl_set_task_aborted(&io->scsiio);
13761
13762         /*
13763          * We print out status for every task management command.  For SCSI
13764          * commands, we filter out any unit attention errors; they happen
13765          * on every boot, and would clutter up the log.  Note:  task
13766          * management commands aren't printed here, they are printed above,
13767          * since they should never even make it down here.
13768          */
13769         switch (io->io_hdr.io_type) {
13770         case CTL_IO_SCSI: {
13771                 int error_code, sense_key, asc, ascq;
13772
13773                 sense_key = 0;
13774
13775                 if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13776                  && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13777                         /*
13778                          * Since this is just for printing, no need to
13779                          * show errors here.
13780                          */
13781                         scsi_extract_sense_len(&io->scsiio.sense_data,
13782                                                io->scsiio.sense_len,
13783                                                &error_code,
13784                                                &sense_key,
13785                                                &asc,
13786                                                &ascq,
13787                                                /*show_errors*/ 0);
13788                 }
13789
13790                 if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13791                  && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13792                   || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13793                   || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13794
13795                         if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13796                                 ctl_softc->skipped_prints++;
13797                         } else {
13798                                 uint32_t skipped_prints;
13799
13800                                 skipped_prints = ctl_softc->skipped_prints;
13801
13802                                 ctl_softc->skipped_prints = 0;
13803                                 ctl_softc->last_print_jiffies = time_uptime;
13804
13805                                 if (skipped_prints > 0) {
13806 #ifdef NEEDTOPORT
13807                                         csevent_log(CSC_CTL | CSC_SHELF_SW |
13808                                             CTL_ERROR_REPORT,
13809                                             csevent_LogType_Trace,
13810                                             csevent_Severity_Information,
13811                                             csevent_AlertLevel_Green,
13812                                             csevent_FRU_Firmware,
13813                                             csevent_FRU_Unknown,
13814                                             "High CTL error volume, %d prints "
13815                                             "skipped", skipped_prints);
13816 #endif
13817                                 }
13818                                 if (bootverbose || verbose > 0)
13819                                         ctl_io_error_print(io, NULL);
13820                         }
13821                 }
13822                 break;
13823         }
13824         case CTL_IO_TASK:
13825                 if (bootverbose || verbose > 0)
13826                         ctl_io_error_print(io, NULL);
13827                 break;
13828         default:
13829                 break;
13830         }
13831
13832         /*
13833          * Tell the FETD or the other shelf controller we're done with this
13834          * command.  Note that only SCSI commands get to this point.  Task
13835          * management commands are completed above.
13836          *
13837          * We only send status to the other controller if we're in XFER
13838          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13839          * received the I/O (from CTL's perspective), and so the status is
13840          * generated there.
13841          * 
13842          * XXX KDM if we hold the lock here, we could cause a deadlock
13843          * if the frontend comes back in in this context to queue
13844          * something.
13845          */
13846         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13847          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13848                 union ctl_ha_msg msg;
13849
13850                 memset(&msg, 0, sizeof(msg));
13851                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13852                 msg.hdr.original_sc = io->io_hdr.original_sc;
13853                 msg.hdr.nexus = io->io_hdr.nexus;
13854                 msg.hdr.status = io->io_hdr.status;
13855                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13856                 msg.scsi.tag_num = io->scsiio.tag_num;
13857                 msg.scsi.tag_type = io->scsiio.tag_type;
13858                 msg.scsi.sense_len = io->scsiio.sense_len;
13859                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13860                 msg.scsi.residual = io->scsiio.residual;
13861                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13862                        sizeof(io->scsiio.sense_data));
13863                 /*
13864                  * We copy this whether or not this is an I/O-related
13865                  * command.  Otherwise, we'd have to go and check to see
13866                  * whether it's a read/write command, and it really isn't
13867                  * worth it.
13868                  */
13869                 memcpy(&msg.scsi.lbalen,
13870                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13871                        sizeof(msg.scsi.lbalen));
13872
13873                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13874                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13875                         /* XXX do something here */
13876                 }
13877
13878                 ctl_free_io(io);
13879         } else 
13880                 fe_done(io);
13881
13882 bailout:
13883
13884         return (CTL_RETVAL_COMPLETE);
13885 }
13886
13887 #ifdef CTL_WITH_CA
13888 /*
13889  * Front end should call this if it doesn't do autosense.  When the request
13890  * sense comes back in from the initiator, we'll dequeue this and send it.
13891  */
13892 int
13893 ctl_queue_sense(union ctl_io *io)
13894 {
13895         struct ctl_lun *lun;
13896         struct ctl_softc *ctl_softc;
13897         uint32_t initidx, targ_lun;
13898
13899         ctl_softc = control_softc;
13900
13901         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13902
13903         /*
13904          * LUN lookup will likely move to the ctl_work_thread() once we
13905          * have our new queueing infrastructure (that doesn't put things on
13906          * a per-LUN queue initially).  That is so that we can handle
13907          * things like an INQUIRY to a LUN that we don't have enabled.  We
13908          * can't deal with that right now.
13909          */
13910         mtx_lock(&ctl_softc->ctl_lock);
13911
13912         /*
13913          * If we don't have a LUN for this, just toss the sense
13914          * information.
13915          */
13916         targ_lun = io->io_hdr.nexus.targ_lun;
13917         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13918         if ((targ_lun < CTL_MAX_LUNS)
13919          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13920                 lun = ctl_softc->ctl_luns[targ_lun];
13921         else
13922                 goto bailout;
13923
13924         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13925
13926         mtx_lock(&lun->lun_lock);
13927         /*
13928          * Already have CA set for this LUN...toss the sense information.
13929          */
13930         if (ctl_is_set(lun->have_ca, initidx)) {
13931                 mtx_unlock(&lun->lun_lock);
13932                 goto bailout;
13933         }
13934
13935         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13936                ctl_min(sizeof(lun->pending_sense[initidx]),
13937                sizeof(io->scsiio.sense_data)));
13938         ctl_set_mask(lun->have_ca, initidx);
13939         mtx_unlock(&lun->lun_lock);
13940
13941 bailout:
13942         mtx_unlock(&ctl_softc->ctl_lock);
13943
13944         ctl_free_io(io);
13945
13946         return (CTL_RETVAL_COMPLETE);
13947 }
13948 #endif
13949
13950 /*
13951  * Primary command inlet from frontend ports.  All SCSI and task I/O
13952  * requests must go through this function.
13953  */
13954 int
13955 ctl_queue(union ctl_io *io)
13956 {
13957         struct ctl_softc *ctl_softc;
13958
13959         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13960
13961         ctl_softc = control_softc;
13962
13963 #ifdef CTL_TIME_IO
13964         io->io_hdr.start_time = time_uptime;
13965         getbintime(&io->io_hdr.start_bt);
13966 #endif /* CTL_TIME_IO */
13967
13968         /* Map FE-specific LUN ID into global one. */
13969         io->io_hdr.nexus.targ_mapped_lun =
13970             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13971
13972         switch (io->io_hdr.io_type) {
13973         case CTL_IO_SCSI:
13974         case CTL_IO_TASK:
13975                 ctl_enqueue_incoming(io);
13976                 break;
13977         default:
13978                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13979                 return (EINVAL);
13980         }
13981
13982         return (CTL_RETVAL_COMPLETE);
13983 }
13984
13985 #ifdef CTL_IO_DELAY
13986 static void
13987 ctl_done_timer_wakeup(void *arg)
13988 {
13989         union ctl_io *io;
13990
13991         io = (union ctl_io *)arg;
13992         ctl_done(io);
13993 }
13994 #endif /* CTL_IO_DELAY */
13995
13996 void
13997 ctl_done(union ctl_io *io)
13998 {
13999         struct ctl_softc *ctl_softc;
14000
14001         ctl_softc = control_softc;
14002
14003         /*
14004          * Enable this to catch duplicate completion issues.
14005          */
14006 #if 0
14007         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14008                 printf("%s: type %d msg %d cdb %x iptl: "
14009                        "%d:%d:%d:%d tag 0x%04x "
14010                        "flag %#x status %x\n",
14011                         __func__,
14012                         io->io_hdr.io_type,
14013                         io->io_hdr.msg_type,
14014                         io->scsiio.cdb[0],
14015                         io->io_hdr.nexus.initid.id,
14016                         io->io_hdr.nexus.targ_port,
14017                         io->io_hdr.nexus.targ_target.id,
14018                         io->io_hdr.nexus.targ_lun,
14019                         (io->io_hdr.io_type ==
14020                         CTL_IO_TASK) ?
14021                         io->taskio.tag_num :
14022                         io->scsiio.tag_num,
14023                         io->io_hdr.flags,
14024                         io->io_hdr.status);
14025         } else
14026                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14027 #endif
14028
14029         /*
14030          * This is an internal copy of an I/O, and should not go through
14031          * the normal done processing logic.
14032          */
14033         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14034                 return;
14035
14036         /*
14037          * We need to send a msg to the serializing shelf to finish the IO
14038          * as well.  We don't send a finish message to the other shelf if
14039          * this is a task management command.  Task management commands
14040          * aren't serialized in the OOA queue, but rather just executed on
14041          * both shelf controllers for commands that originated on that
14042          * controller.
14043          */
14044         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14045          && (io->io_hdr.io_type != CTL_IO_TASK)) {
14046                 union ctl_ha_msg msg_io;
14047
14048                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14049                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14050                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14051                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14052                 }
14053                 /* continue on to finish IO */
14054         }
14055 #ifdef CTL_IO_DELAY
14056         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14057                 struct ctl_lun *lun;
14058
14059                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14060
14061                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14062         } else {
14063                 struct ctl_lun *lun;
14064
14065                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14066
14067                 if ((lun != NULL)
14068                  && (lun->delay_info.done_delay > 0)) {
14069                         struct callout *callout;
14070
14071                         callout = (struct callout *)&io->io_hdr.timer_bytes;
14072                         callout_init(callout, /*mpsafe*/ 1);
14073                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14074                         callout_reset(callout,
14075                                       lun->delay_info.done_delay * hz,
14076                                       ctl_done_timer_wakeup, io);
14077                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14078                                 lun->delay_info.done_delay = 0;
14079                         return;
14080                 }
14081         }
14082 #endif /* CTL_IO_DELAY */
14083
14084         ctl_enqueue_done(io);
14085 }
14086
14087 int
14088 ctl_isc(struct ctl_scsiio *ctsio)
14089 {
14090         struct ctl_lun *lun;
14091         int retval;
14092
14093         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14094
14095         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14096
14097         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14098
14099         retval = lun->backend->data_submit((union ctl_io *)ctsio);
14100
14101         return (retval);
14102 }
14103
14104
14105 static void
14106 ctl_work_thread(void *arg)
14107 {
14108         struct ctl_thread *thr = (struct ctl_thread *)arg;
14109         struct ctl_softc *softc = thr->ctl_softc;
14110         union ctl_io *io;
14111         int retval;
14112
14113         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14114
14115         for (;;) {
14116                 retval = 0;
14117
14118                 /*
14119                  * We handle the queues in this order:
14120                  * - ISC
14121                  * - done queue (to free up resources, unblock other commands)
14122                  * - RtR queue
14123                  * - incoming queue
14124                  *
14125                  * If those queues are empty, we break out of the loop and
14126                  * go to sleep.
14127                  */
14128                 mtx_lock(&thr->queue_lock);
14129                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14130                 if (io != NULL) {
14131                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14132                         mtx_unlock(&thr->queue_lock);
14133                         ctl_handle_isc(io);
14134                         continue;
14135                 }
14136                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14137                 if (io != NULL) {
14138                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14139                         /* clear any blocked commands, call fe_done */
14140                         mtx_unlock(&thr->queue_lock);
14141                         retval = ctl_process_done(io);
14142                         continue;
14143                 }
14144                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14145                 if (io != NULL) {
14146                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14147                         mtx_unlock(&thr->queue_lock);
14148                         if (io->io_hdr.io_type == CTL_IO_TASK)
14149                                 ctl_run_task(io);
14150                         else
14151                                 ctl_scsiio_precheck(softc, &io->scsiio);
14152                         continue;
14153                 }
14154                 if (!ctl_pause_rtr) {
14155                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14156                         if (io != NULL) {
14157                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14158                                 mtx_unlock(&thr->queue_lock);
14159                                 retval = ctl_scsiio(&io->scsiio);
14160                                 if (retval != CTL_RETVAL_COMPLETE)
14161                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14162                                 continue;
14163                         }
14164                 }
14165
14166                 /* Sleep until we have something to do. */
14167                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14168         }
14169 }
14170
14171 static void
14172 ctl_lun_thread(void *arg)
14173 {
14174         struct ctl_softc *softc = (struct ctl_softc *)arg;
14175         struct ctl_be_lun *be_lun;
14176         int retval;
14177
14178         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14179
14180         for (;;) {
14181                 retval = 0;
14182                 mtx_lock(&softc->ctl_lock);
14183                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14184                 if (be_lun != NULL) {
14185                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14186                         mtx_unlock(&softc->ctl_lock);
14187                         ctl_create_lun(be_lun);
14188                         continue;
14189                 }
14190
14191                 /* Sleep until we have something to do. */
14192                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14193                     PDROP | PRIBIO, "-", 0);
14194         }
14195 }
14196
14197 static void
14198 ctl_enqueue_incoming(union ctl_io *io)
14199 {
14200         struct ctl_softc *softc = control_softc;
14201         struct ctl_thread *thr;
14202         u_int idx;
14203
14204         idx = (io->io_hdr.nexus.targ_port * 127 +
14205                io->io_hdr.nexus.initid.id) % worker_threads;
14206         thr = &softc->threads[idx];
14207         mtx_lock(&thr->queue_lock);
14208         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14209         mtx_unlock(&thr->queue_lock);
14210         wakeup(thr);
14211 }
14212
14213 static void
14214 ctl_enqueue_rtr(union ctl_io *io)
14215 {
14216         struct ctl_softc *softc = control_softc;
14217         struct ctl_thread *thr;
14218
14219         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14220         mtx_lock(&thr->queue_lock);
14221         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14222         mtx_unlock(&thr->queue_lock);
14223         wakeup(thr);
14224 }
14225
14226 static void
14227 ctl_enqueue_done(union ctl_io *io)
14228 {
14229         struct ctl_softc *softc = control_softc;
14230         struct ctl_thread *thr;
14231
14232         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14233         mtx_lock(&thr->queue_lock);
14234         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14235         mtx_unlock(&thr->queue_lock);
14236         wakeup(thr);
14237 }
14238
14239 static void
14240 ctl_enqueue_isc(union ctl_io *io)
14241 {
14242         struct ctl_softc *softc = control_softc;
14243         struct ctl_thread *thr;
14244
14245         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14246         mtx_lock(&thr->queue_lock);
14247         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14248         mtx_unlock(&thr->queue_lock);
14249         wakeup(thr);
14250 }
14251
14252 /* Initialization and failover */
14253
14254 void
14255 ctl_init_isc_msg(void)
14256 {
14257         printf("CTL: Still calling this thing\n");
14258 }
14259
14260 /*
14261  * Init component
14262  *      Initializes component into configuration defined by bootMode
14263  *      (see hasc-sv.c)
14264  *      returns hasc_Status:
14265  *              OK
14266  *              ERROR - fatal error
14267  */
14268 static ctl_ha_comp_status
14269 ctl_isc_init(struct ctl_ha_component *c)
14270 {
14271         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14272
14273         c->status = ret;
14274         return ret;
14275 }
14276
14277 /* Start component
14278  *      Starts component in state requested. If component starts successfully,
14279  *      it must set its own state to the requestrd state
14280  *      When requested state is HASC_STATE_HA, the component may refine it
14281  *      by adding _SLAVE or _MASTER flags.
14282  *      Currently allowed state transitions are:
14283  *      UNKNOWN->HA             - initial startup
14284  *      UNKNOWN->SINGLE - initial startup when no parter detected
14285  *      HA->SINGLE              - failover
14286  * returns ctl_ha_comp_status:
14287  *              OK      - component successfully started in requested state
14288  *              FAILED  - could not start the requested state, failover may
14289  *                        be possible
14290  *              ERROR   - fatal error detected, no future startup possible
14291  */
14292 static ctl_ha_comp_status
14293 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14294 {
14295         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14296
14297         printf("%s: go\n", __func__);
14298
14299         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14300         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14301                 ctl_is_single = 0;
14302                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14303                     != CTL_HA_STATUS_SUCCESS) {
14304                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14305                         ret = CTL_HA_COMP_STATUS_ERROR;
14306                 }
14307         } else if (CTL_HA_STATE_IS_HA(c->state)
14308                 && CTL_HA_STATE_IS_SINGLE(state)){
14309                 // HA->SINGLE transition
14310                 ctl_failover();
14311                 ctl_is_single = 1;
14312         } else {
14313                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14314                        c->state, state);
14315                 ret = CTL_HA_COMP_STATUS_ERROR;
14316         }
14317         if (CTL_HA_STATE_IS_SINGLE(state))
14318                 ctl_is_single = 1;
14319
14320         c->state = state;
14321         c->status = ret;
14322         return ret;
14323 }
14324
14325 /*
14326  * Quiesce component
14327  * The component must clear any error conditions (set status to OK) and
14328  * prepare itself to another Start call
14329  * returns ctl_ha_comp_status:
14330  *      OK
14331  *      ERROR
14332  */
14333 static ctl_ha_comp_status
14334 ctl_isc_quiesce(struct ctl_ha_component *c)
14335 {
14336         int ret = CTL_HA_COMP_STATUS_OK;
14337
14338         ctl_pause_rtr = 1;
14339         c->status = ret;
14340         return ret;
14341 }
14342
14343 struct ctl_ha_component ctl_ha_component_ctlisc =
14344 {
14345         .name = "CTL ISC",
14346         .state = CTL_HA_STATE_UNKNOWN,
14347         .init = ctl_isc_init,
14348         .start = ctl_isc_start,
14349         .quiesce = ctl_isc_quiesce
14350 };
14351
14352 /*
14353  *  vim: ts=8
14354  */