]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r272911:
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/types.h>
51 #include <sys/kthread.h>
52 #include <sys/bio.h>
53 #include <sys/fcntl.h>
54 #include <sys/lock.h>
55 #include <sys/module.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/malloc.h>
59 #include <sys/conf.h>
60 #include <sys/ioccom.h>
61 #include <sys/queue.h>
62 #include <sys/sbuf.h>
63 #include <sys/smp.h>
64 #include <sys/endian.h>
65 #include <sys/sysctl.h>
66
67 #include <cam/cam.h>
68 #include <cam/scsi/scsi_all.h>
69 #include <cam/scsi/scsi_da.h>
70 #include <cam/ctl/ctl_io.h>
71 #include <cam/ctl/ctl.h>
72 #include <cam/ctl/ctl_frontend.h>
73 #include <cam/ctl/ctl_frontend_internal.h>
74 #include <cam/ctl/ctl_util.h>
75 #include <cam/ctl/ctl_backend.h>
76 #include <cam/ctl/ctl_ioctl.h>
77 #include <cam/ctl/ctl_ha.h>
78 #include <cam/ctl/ctl_private.h>
79 #include <cam/ctl/ctl_debug.h>
80 #include <cam/ctl/ctl_scsi_all.h>
81 #include <cam/ctl/ctl_error.h>
82
83 struct ctl_softc *control_softc = NULL;
84
85 /*
86  * Size and alignment macros needed for Copan-specific HA hardware.  These
87  * can go away when the HA code is re-written, and uses busdma for any
88  * hardware.
89  */
90 #define CTL_ALIGN_8B(target, source, type)                              \
91         if (((uint32_t)source & 0x7) != 0)                              \
92                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93         else                                                            \
94                 target = (type)source;
95
96 #define CTL_SIZE_8B(target, size)                                       \
97         if ((size & 0x7) != 0)                                          \
98                 target = size + (0x8 - (size & 0x7));                   \
99         else                                                            \
100                 target = size;
101
102 #define CTL_ALIGN_8B_MARGIN     16
103
104 /*
105  * Template mode pages.
106  */
107
108 /*
109  * Note that these are default values only.  The actual values will be
110  * filled in when the user does a mode sense.
111  */
112 static struct copan_power_subpage power_page_default = {
113         /*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114         /*subpage*/ PWR_SUBPAGE_CODE,
115         /*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116                          (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117         /*page_version*/ PWR_VERSION,
118         /* total_luns */ 26,
119         /* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120         /*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122                       0, 0, 0, 0, 0, 0}
123 };
124
125 static struct copan_power_subpage power_page_changeable = {
126         /*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127         /*subpage*/ PWR_SUBPAGE_CODE,
128         /*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129                          (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130         /*page_version*/ 0,
131         /* total_luns */ 0,
132         /* max_active_luns*/ 0,
133         /*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135                       0, 0, 0, 0, 0, 0}
136 };
137
138 static struct copan_aps_subpage aps_page_default = {
139         APS_PAGE_CODE | SMPH_SPF, //page_code
140         APS_SUBPAGE_CODE, //subpage
141         {(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142          (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143         APS_VERSION, //page_version
144         0, //lock_active
145         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146         0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147         0, 0, 0, 0, 0} //reserved
148 };
149
150 static struct copan_aps_subpage aps_page_changeable = {
151         APS_PAGE_CODE | SMPH_SPF, //page_code
152         APS_SUBPAGE_CODE, //subpage
153         {(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154          (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155         0, //page_version
156         0, //lock_active
157         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158         0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159         0, 0, 0, 0, 0} //reserved
160 };
161
162 static struct copan_debugconf_subpage debugconf_page_default = {
163         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
164         DBGCNF_SUBPAGE_CODE,            /* subpage */
165         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167         DBGCNF_VERSION,                 /* page_version */
168         {CTL_TIME_IO_DEFAULT_SECS>>8,
169          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
170 };
171
172 static struct copan_debugconf_subpage debugconf_page_changeable = {
173         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
174         DBGCNF_SUBPAGE_CODE,            /* subpage */
175         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177         0,                              /* page_version */
178         {0xff,0xff},                    /* ctl_time_io_secs */
179 };
180
181 static struct scsi_format_page format_page_default = {
182         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
183         /*page_length*/sizeof(struct scsi_format_page) - 2,
184         /*tracks_per_zone*/ {0, 0},
185         /*alt_sectors_per_zone*/ {0, 0},
186         /*alt_tracks_per_zone*/ {0, 0},
187         /*alt_tracks_per_lun*/ {0, 0},
188         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190         /*bytes_per_sector*/ {0, 0},
191         /*interleave*/ {0, 0},
192         /*track_skew*/ {0, 0},
193         /*cylinder_skew*/ {0, 0},
194         /*flags*/ SFP_HSEC,
195         /*reserved*/ {0, 0, 0}
196 };
197
198 static struct scsi_format_page format_page_changeable = {
199         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
200         /*page_length*/sizeof(struct scsi_format_page) - 2,
201         /*tracks_per_zone*/ {0, 0},
202         /*alt_sectors_per_zone*/ {0, 0},
203         /*alt_tracks_per_zone*/ {0, 0},
204         /*alt_tracks_per_lun*/ {0, 0},
205         /*sectors_per_track*/ {0, 0},
206         /*bytes_per_sector*/ {0, 0},
207         /*interleave*/ {0, 0},
208         /*track_skew*/ {0, 0},
209         /*cylinder_skew*/ {0, 0},
210         /*flags*/ 0,
211         /*reserved*/ {0, 0, 0}
212 };
213
214 static struct scsi_rigid_disk_page rigid_disk_page_default = {
215         /*page_code*/SMS_RIGID_DISK_PAGE,
216         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217         /*cylinders*/ {0, 0, 0},
218         /*heads*/ CTL_DEFAULT_HEADS,
219         /*start_write_precomp*/ {0, 0, 0},
220         /*start_reduced_current*/ {0, 0, 0},
221         /*step_rate*/ {0, 0},
222         /*landing_zone_cylinder*/ {0, 0, 0},
223         /*rpl*/ SRDP_RPL_DISABLED,
224         /*rotational_offset*/ 0,
225         /*reserved1*/ 0,
226         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227                            CTL_DEFAULT_ROTATION_RATE & 0xff},
228         /*reserved2*/ {0, 0}
229 };
230
231 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232         /*page_code*/SMS_RIGID_DISK_PAGE,
233         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234         /*cylinders*/ {0, 0, 0},
235         /*heads*/ 0,
236         /*start_write_precomp*/ {0, 0, 0},
237         /*start_reduced_current*/ {0, 0, 0},
238         /*step_rate*/ {0, 0},
239         /*landing_zone_cylinder*/ {0, 0, 0},
240         /*rpl*/ 0,
241         /*rotational_offset*/ 0,
242         /*reserved1*/ 0,
243         /*rotation_rate*/ {0, 0},
244         /*reserved2*/ {0, 0}
245 };
246
247 static struct scsi_caching_page caching_page_default = {
248         /*page_code*/SMS_CACHING_PAGE,
249         /*page_length*/sizeof(struct scsi_caching_page) - 2,
250         /*flags1*/ SCP_DISC | SCP_WCE,
251         /*ret_priority*/ 0,
252         /*disable_pf_transfer_len*/ {0xff, 0xff},
253         /*min_prefetch*/ {0, 0},
254         /*max_prefetch*/ {0xff, 0xff},
255         /*max_pf_ceiling*/ {0xff, 0xff},
256         /*flags2*/ 0,
257         /*cache_segments*/ 0,
258         /*cache_seg_size*/ {0, 0},
259         /*reserved*/ 0,
260         /*non_cache_seg_size*/ {0, 0, 0}
261 };
262
263 static struct scsi_caching_page caching_page_changeable = {
264         /*page_code*/SMS_CACHING_PAGE,
265         /*page_length*/sizeof(struct scsi_caching_page) - 2,
266         /*flags1*/ SCP_WCE | SCP_RCD,
267         /*ret_priority*/ 0,
268         /*disable_pf_transfer_len*/ {0, 0},
269         /*min_prefetch*/ {0, 0},
270         /*max_prefetch*/ {0, 0},
271         /*max_pf_ceiling*/ {0, 0},
272         /*flags2*/ 0,
273         /*cache_segments*/ 0,
274         /*cache_seg_size*/ {0, 0},
275         /*reserved*/ 0,
276         /*non_cache_seg_size*/ {0, 0, 0}
277 };
278
279 static struct scsi_control_page control_page_default = {
280         /*page_code*/SMS_CONTROL_MODE_PAGE,
281         /*page_length*/sizeof(struct scsi_control_page) - 2,
282         /*rlec*/0,
283         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
284         /*eca_and_aen*/0,
285         /*flags4*/SCP_TAS,
286         /*aen_holdoff_period*/{0, 0},
287         /*busy_timeout_period*/{0, 0},
288         /*extended_selftest_completion_time*/{0, 0}
289 };
290
291 static struct scsi_control_page control_page_changeable = {
292         /*page_code*/SMS_CONTROL_MODE_PAGE,
293         /*page_length*/sizeof(struct scsi_control_page) - 2,
294         /*rlec*/SCP_DSENSE,
295         /*queue_flags*/SCP_QUEUE_ALG_MASK,
296         /*eca_and_aen*/SCP_SWP,
297         /*flags4*/0,
298         /*aen_holdoff_period*/{0, 0},
299         /*busy_timeout_period*/{0, 0},
300         /*extended_selftest_completion_time*/{0, 0}
301 };
302
303
304 /*
305  * XXX KDM move these into the softc.
306  */
307 static int rcv_sync_msg;
308 static int persis_offset;
309 static uint8_t ctl_pause_rtr;
310 static int     ctl_is_single = 1;
311 static int     index_to_aps_page;
312
313 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314 static int worker_threads = -1;
315 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
316 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
317     &worker_threads, 1, "Number of worker threads");
318 static int 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, int *sa);
446 static const struct ctl_cmd_entry *
447     ctl_validate_command(struct ctl_scsiio *ctsio);
448 static int ctl_cmd_applicable(uint8_t lun_type,
449     const struct ctl_cmd_entry *entry);
450
451 /*
452  * Load the serialization table.  This isn't very pretty, but is probably
453  * the easiest way to do it.
454  */
455 #include "ctl_ser_table.c"
456
457 /*
458  * We only need to define open, close and ioctl routines for this driver.
459  */
460 static struct cdevsw ctl_cdevsw = {
461         .d_version =    D_VERSION,
462         .d_flags =      0,
463         .d_open =       ctl_open,
464         .d_close =      ctl_close,
465         .d_ioctl =      ctl_ioctl,
466         .d_name =       "ctl",
467 };
468
469
470 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
471 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
472
473 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
474
475 static moduledata_t ctl_moduledata = {
476         "ctl",
477         ctl_module_event_handler,
478         NULL
479 };
480
481 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
482 MODULE_VERSION(ctl, 1);
483
484 static struct ctl_frontend ioctl_frontend =
485 {
486         .name = "ioctl",
487 };
488
489 static void
490 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
491                             union ctl_ha_msg *msg_info)
492 {
493         struct ctl_scsiio *ctsio;
494
495         if (msg_info->hdr.original_sc == NULL) {
496                 printf("%s: original_sc == NULL!\n", __func__);
497                 /* XXX KDM now what? */
498                 return;
499         }
500
501         ctsio = &msg_info->hdr.original_sc->scsiio;
502         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
503         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
504         ctsio->io_hdr.status = msg_info->hdr.status;
505         ctsio->scsi_status = msg_info->scsi.scsi_status;
506         ctsio->sense_len = msg_info->scsi.sense_len;
507         ctsio->sense_residual = msg_info->scsi.sense_residual;
508         ctsio->residual = msg_info->scsi.residual;
509         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
510                sizeof(ctsio->sense_data));
511         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
512                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
513         ctl_enqueue_isc((union ctl_io *)ctsio);
514 }
515
516 static void
517 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
518                                 union ctl_ha_msg *msg_info)
519 {
520         struct ctl_scsiio *ctsio;
521
522         if (msg_info->hdr.serializing_sc == NULL) {
523                 printf("%s: serializing_sc == NULL!\n", __func__);
524                 /* XXX KDM now what? */
525                 return;
526         }
527
528         ctsio = &msg_info->hdr.serializing_sc->scsiio;
529 #if 0
530         /*
531          * Attempt to catch the situation where an I/O has
532          * been freed, and we're using it again.
533          */
534         if (ctsio->io_hdr.io_type == 0xff) {
535                 union ctl_io *tmp_io;
536                 tmp_io = (union ctl_io *)ctsio;
537                 printf("%s: %p use after free!\n", __func__,
538                        ctsio);
539                 printf("%s: type %d msg %d cdb %x iptl: "
540                        "%d:%d:%d:%d tag 0x%04x "
541                        "flag %#x status %x\n",
542                         __func__,
543                         tmp_io->io_hdr.io_type,
544                         tmp_io->io_hdr.msg_type,
545                         tmp_io->scsiio.cdb[0],
546                         tmp_io->io_hdr.nexus.initid.id,
547                         tmp_io->io_hdr.nexus.targ_port,
548                         tmp_io->io_hdr.nexus.targ_target.id,
549                         tmp_io->io_hdr.nexus.targ_lun,
550                         (tmp_io->io_hdr.io_type ==
551                         CTL_IO_TASK) ?
552                         tmp_io->taskio.tag_num :
553                         tmp_io->scsiio.tag_num,
554                         tmp_io->io_hdr.flags,
555                         tmp_io->io_hdr.status);
556         }
557 #endif
558         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
559         ctl_enqueue_isc((union ctl_io *)ctsio);
560 }
561
562 /*
563  * ISC (Inter Shelf Communication) event handler.  Events from the HA
564  * subsystem come in here.
565  */
566 static void
567 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
568 {
569         struct ctl_softc *ctl_softc;
570         union ctl_io *io;
571         struct ctl_prio *presio;
572         ctl_ha_status isc_status;
573
574         ctl_softc = control_softc;
575         io = NULL;
576
577
578 #if 0
579         printf("CTL: Isc Msg event %d\n", event);
580 #endif
581         if (event == CTL_HA_EVT_MSG_RECV) {
582                 union ctl_ha_msg msg_info;
583
584                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
585                                              sizeof(msg_info), /*wait*/ 0);
586 #if 0
587                 printf("CTL: msg_type %d\n", msg_info.msg_type);
588 #endif
589                 if (isc_status != 0) {
590                         printf("Error receiving message, status = %d\n",
591                                isc_status);
592                         return;
593                 }
594
595                 switch (msg_info.hdr.msg_type) {
596                 case CTL_MSG_SERIALIZE:
597 #if 0
598                         printf("Serialize\n");
599 #endif
600                         io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
601                         if (io == NULL) {
602                                 printf("ctl_isc_event_handler: can't allocate "
603                                        "ctl_io!\n");
604                                 /* Bad Juju */
605                                 /* Need to set busy and send msg back */
606                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
607                                 msg_info.hdr.status = CTL_SCSI_ERROR;
608                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
609                                 msg_info.scsi.sense_len = 0;
610                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
611                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
612                                 }
613                                 goto bailout;
614                         }
615                         ctl_zero_io(io);
616                         // populate ctsio from msg_info
617                         io->io_hdr.io_type = CTL_IO_SCSI;
618                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
619                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
620 #if 0
621                         printf("pOrig %x\n", (int)msg_info.original_sc);
622 #endif
623                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
624                                             CTL_FLAG_IO_ACTIVE;
625                         /*
626                          * If we're in serialization-only mode, we don't
627                          * want to go through full done processing.  Thus
628                          * the COPY flag.
629                          *
630                          * XXX KDM add another flag that is more specific.
631                          */
632                         if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
633                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
634                         io->io_hdr.nexus = msg_info.hdr.nexus;
635 #if 0
636                         printf("targ %d, port %d, iid %d, lun %d\n",
637                                io->io_hdr.nexus.targ_target.id,
638                                io->io_hdr.nexus.targ_port,
639                                io->io_hdr.nexus.initid.id,
640                                io->io_hdr.nexus.targ_lun);
641 #endif
642                         io->scsiio.tag_num = msg_info.scsi.tag_num;
643                         io->scsiio.tag_type = msg_info.scsi.tag_type;
644                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
645                                CTL_MAX_CDBLEN);
646                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
647                                 const struct ctl_cmd_entry *entry;
648
649                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
650                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
651                                 io->io_hdr.flags |=
652                                         entry->flags & CTL_FLAG_DATA_MASK;
653                         }
654                         ctl_enqueue_isc(io);
655                         break;
656
657                 /* Performed on the Originating SC, XFER mode only */
658                 case CTL_MSG_DATAMOVE: {
659                         struct ctl_sg_entry *sgl;
660                         int i, j;
661
662                         io = msg_info.hdr.original_sc;
663                         if (io == NULL) {
664                                 printf("%s: original_sc == NULL!\n", __func__);
665                                 /* XXX KDM do something here */
666                                 break;
667                         }
668                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
669                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
670                         /*
671                          * Keep track of this, we need to send it back over
672                          * when the datamove is complete.
673                          */
674                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
675
676                         if (msg_info.dt.sg_sequence == 0) {
677                                 /*
678                                  * XXX KDM we use the preallocated S/G list
679                                  * here, but we'll need to change this to
680                                  * dynamic allocation if we need larger S/G
681                                  * lists.
682                                  */
683                                 if (msg_info.dt.kern_sg_entries >
684                                     sizeof(io->io_hdr.remote_sglist) /
685                                     sizeof(io->io_hdr.remote_sglist[0])) {
686                                         printf("%s: number of S/G entries "
687                                             "needed %u > allocated num %zd\n",
688                                             __func__,
689                                             msg_info.dt.kern_sg_entries,
690                                             sizeof(io->io_hdr.remote_sglist)/
691                                             sizeof(io->io_hdr.remote_sglist[0]));
692                                 
693                                         /*
694                                          * XXX KDM send a message back to
695                                          * the other side to shut down the
696                                          * DMA.  The error will come back
697                                          * through via the normal channel.
698                                          */
699                                         break;
700                                 }
701                                 sgl = io->io_hdr.remote_sglist;
702                                 memset(sgl, 0,
703                                        sizeof(io->io_hdr.remote_sglist));
704
705                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
706
707                                 io->scsiio.kern_sg_entries =
708                                         msg_info.dt.kern_sg_entries;
709                                 io->scsiio.rem_sg_entries =
710                                         msg_info.dt.kern_sg_entries;
711                                 io->scsiio.kern_data_len =
712                                         msg_info.dt.kern_data_len;
713                                 io->scsiio.kern_total_len =
714                                         msg_info.dt.kern_total_len;
715                                 io->scsiio.kern_data_resid =
716                                         msg_info.dt.kern_data_resid;
717                                 io->scsiio.kern_rel_offset =
718                                         msg_info.dt.kern_rel_offset;
719                                 /*
720                                  * Clear out per-DMA flags.
721                                  */
722                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
723                                 /*
724                                  * Add per-DMA flags that are set for this
725                                  * particular DMA request.
726                                  */
727                                 io->io_hdr.flags |= msg_info.dt.flags &
728                                                     CTL_FLAG_RDMA_MASK;
729                         } else
730                                 sgl = (struct ctl_sg_entry *)
731                                         io->scsiio.kern_data_ptr;
732
733                         for (i = msg_info.dt.sent_sg_entries, j = 0;
734                              i < (msg_info.dt.sent_sg_entries +
735                              msg_info.dt.cur_sg_entries); i++, j++) {
736                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
737                                 sgl[i].len = msg_info.dt.sg_list[j].len;
738
739 #if 0
740                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
741                                        __func__,
742                                        msg_info.dt.sg_list[j].addr,
743                                        msg_info.dt.sg_list[j].len,
744                                        sgl[i].addr, sgl[i].len, j, i);
745 #endif
746                         }
747 #if 0
748                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
749                                msg_info.dt.sg_list,
750                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
751 #endif
752
753                         /*
754                          * If this is the last piece of the I/O, we've got
755                          * the full S/G list.  Queue processing in the thread.
756                          * Otherwise wait for the next piece.
757                          */
758                         if (msg_info.dt.sg_last != 0)
759                                 ctl_enqueue_isc(io);
760                         break;
761                 }
762                 /* Performed on the Serializing (primary) SC, XFER mode only */
763                 case CTL_MSG_DATAMOVE_DONE: {
764                         if (msg_info.hdr.serializing_sc == NULL) {
765                                 printf("%s: serializing_sc == NULL!\n",
766                                        __func__);
767                                 /* XXX KDM now what? */
768                                 break;
769                         }
770                         /*
771                          * We grab the sense information here in case
772                          * there was a failure, so we can return status
773                          * back to the initiator.
774                          */
775                         io = msg_info.hdr.serializing_sc;
776                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
777                         io->io_hdr.status = msg_info.hdr.status;
778                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
779                         io->scsiio.sense_len = msg_info.scsi.sense_len;
780                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
781                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
782                         io->scsiio.residual = msg_info.scsi.residual;
783                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
784                                sizeof(io->scsiio.sense_data));
785                         ctl_enqueue_isc(io);
786                         break;
787                 }
788
789                 /* Preformed on Originating SC, SER_ONLY mode */
790                 case CTL_MSG_R2R:
791                         io = msg_info.hdr.original_sc;
792                         if (io == NULL) {
793                                 printf("%s: Major Bummer\n", __func__);
794                                 return;
795                         } else {
796 #if 0
797                                 printf("pOrig %x\n",(int) ctsio);
798 #endif
799                         }
800                         io->io_hdr.msg_type = CTL_MSG_R2R;
801                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
802                         ctl_enqueue_isc(io);
803                         break;
804
805                 /*
806                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
807                  * mode.
808                  * Performed on the Originating (i.e. secondary) SC in XFER
809                  * mode
810                  */
811                 case CTL_MSG_FINISH_IO:
812                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
813                                 ctl_isc_handler_finish_xfer(ctl_softc,
814                                                             &msg_info);
815                         else
816                                 ctl_isc_handler_finish_ser_only(ctl_softc,
817                                                                 &msg_info);
818                         break;
819
820                 /* Preformed on Originating SC */
821                 case CTL_MSG_BAD_JUJU:
822                         io = msg_info.hdr.original_sc;
823                         if (io == NULL) {
824                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
825                                        __func__);
826                                 break;
827                         }
828                         ctl_copy_sense_data(&msg_info, io);
829                         /*
830                          * IO should have already been cleaned up on other
831                          * SC so clear this flag so we won't send a message
832                          * back to finish the IO there.
833                          */
834                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
835                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
836
837                         /* io = msg_info.hdr.serializing_sc; */
838                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
839                         ctl_enqueue_isc(io);
840                         break;
841
842                 /* Handle resets sent from the other side */
843                 case CTL_MSG_MANAGE_TASKS: {
844                         struct ctl_taskio *taskio;
845                         taskio = (struct ctl_taskio *)ctl_alloc_io(
846                                 (void *)ctl_softc->othersc_pool);
847                         if (taskio == NULL) {
848                                 printf("ctl_isc_event_handler: can't allocate "
849                                        "ctl_io!\n");
850                                 /* Bad Juju */
851                                 /* should I just call the proper reset func
852                                    here??? */
853                                 goto bailout;
854                         }
855                         ctl_zero_io((union ctl_io *)taskio);
856                         taskio->io_hdr.io_type = CTL_IO_TASK;
857                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
858                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
859                         taskio->task_action = msg_info.task.task_action;
860                         taskio->tag_num = msg_info.task.tag_num;
861                         taskio->tag_type = msg_info.task.tag_type;
862 #ifdef CTL_TIME_IO
863                         taskio->io_hdr.start_time = time_uptime;
864                         getbintime(&taskio->io_hdr.start_bt);
865 #if 0
866                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
867 #endif
868 #endif /* CTL_TIME_IO */
869                         ctl_run_task((union ctl_io *)taskio);
870                         break;
871                 }
872                 /* Persistent Reserve action which needs attention */
873                 case CTL_MSG_PERS_ACTION:
874                         presio = (struct ctl_prio *)ctl_alloc_io(
875                                 (void *)ctl_softc->othersc_pool);
876                         if (presio == NULL) {
877                                 printf("ctl_isc_event_handler: can't allocate "
878                                        "ctl_io!\n");
879                                 /* Bad Juju */
880                                 /* Need to set busy and send msg back */
881                                 goto bailout;
882                         }
883                         ctl_zero_io((union ctl_io *)presio);
884                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
885                         presio->pr_msg = msg_info.pr;
886                         ctl_enqueue_isc((union ctl_io *)presio);
887                         break;
888                 case CTL_MSG_SYNC_FE:
889                         rcv_sync_msg = 1;
890                         break;
891                 case CTL_MSG_APS_LOCK: {
892                         // It's quicker to execute this then to
893                         // queue it.
894                         struct ctl_lun *lun;
895                         struct ctl_page_index *page_index;
896                         struct copan_aps_subpage *current_sp;
897                         uint32_t targ_lun;
898
899                         targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
900                         lun = ctl_softc->ctl_luns[targ_lun];
901                         mtx_lock(&lun->lun_lock);
902                         page_index = &lun->mode_pages.index[index_to_aps_page];
903                         current_sp = (struct copan_aps_subpage *)
904                                      (page_index->page_data +
905                                      (page_index->page_len * CTL_PAGE_CURRENT));
906
907                         current_sp->lock_active = msg_info.aps.lock_flag;
908                         mtx_unlock(&lun->lun_lock);
909                         break;
910                 }
911                 default:
912                         printf("How did I get here?\n");
913                 }
914         } else if (event == CTL_HA_EVT_MSG_SENT) {
915                 if (param != CTL_HA_STATUS_SUCCESS) {
916                         printf("Bad status from ctl_ha_msg_send status %d\n",
917                                param);
918                 }
919                 return;
920         } else if (event == CTL_HA_EVT_DISCONNECT) {
921                 printf("CTL: Got a disconnect from Isc\n");
922                 return;
923         } else {
924                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
925                 return;
926         }
927
928 bailout:
929         return;
930 }
931
932 static void
933 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
934 {
935         struct scsi_sense_data *sense;
936
937         sense = &dest->scsiio.sense_data;
938         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
939         dest->scsiio.scsi_status = src->scsi.scsi_status;
940         dest->scsiio.sense_len = src->scsi.sense_len;
941         dest->io_hdr.status = src->hdr.status;
942 }
943
944 static int
945 ctl_init(void)
946 {
947         struct ctl_softc *softc;
948         struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
949         struct ctl_port *port;
950         uint8_t sc_id =0;
951         int i, error, retval;
952         //int isc_retval;
953
954         retval = 0;
955         ctl_pause_rtr = 0;
956         rcv_sync_msg = 0;
957
958         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
959                                M_WAITOK | M_ZERO);
960         softc = control_softc;
961
962         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
963                               "cam/ctl");
964
965         softc->dev->si_drv1 = softc;
966
967         /*
968          * By default, return a "bad LUN" peripheral qualifier for unknown
969          * LUNs.  The user can override this default using the tunable or
970          * sysctl.  See the comment in ctl_inquiry_std() for more details.
971          */
972         softc->inquiry_pq_no_lun = 1;
973         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
974                           &softc->inquiry_pq_no_lun);
975         sysctl_ctx_init(&softc->sysctl_ctx);
976         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
977                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
978                 CTLFLAG_RD, 0, "CAM Target Layer");
979
980         if (softc->sysctl_tree == NULL) {
981                 printf("%s: unable to allocate sysctl tree\n", __func__);
982                 destroy_dev(softc->dev);
983                 free(control_softc, M_DEVBUF);
984                 control_softc = NULL;
985                 return (ENOMEM);
986         }
987
988         SYSCTL_ADD_INT(&softc->sysctl_ctx,
989                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
990                        "inquiry_pq_no_lun", CTLFLAG_RW,
991                        &softc->inquiry_pq_no_lun, 0,
992                        "Report no lun possible for invalid LUNs");
993
994         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
995         mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
996         softc->open_count = 0;
997
998         /*
999          * Default to actually sending a SYNCHRONIZE CACHE command down to
1000          * the drive.
1001          */
1002         softc->flags = CTL_FLAG_REAL_SYNC;
1003
1004         /*
1005          * In Copan's HA scheme, the "master" and "slave" roles are
1006          * figured out through the slot the controller is in.  Although it
1007          * is an active/active system, someone has to be in charge.
1008          */
1009 #ifdef NEEDTOPORT
1010         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1011 #endif
1012
1013         if (sc_id == 0) {
1014                 softc->flags |= CTL_FLAG_MASTER_SHELF;
1015                 persis_offset = 0;
1016         } else
1017                 persis_offset = CTL_MAX_INITIATORS;
1018
1019         /*
1020          * XXX KDM need to figure out where we want to get our target ID
1021          * and WWID.  Is it different on each port?
1022          */
1023         softc->target.id = 0;
1024         softc->target.wwid[0] = 0x12345678;
1025         softc->target.wwid[1] = 0x87654321;
1026         STAILQ_INIT(&softc->lun_list);
1027         STAILQ_INIT(&softc->pending_lun_queue);
1028         STAILQ_INIT(&softc->fe_list);
1029         STAILQ_INIT(&softc->port_list);
1030         STAILQ_INIT(&softc->be_list);
1031         STAILQ_INIT(&softc->io_pools);
1032         ctl_tpc_init(softc);
1033
1034         if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1035                             &internal_pool)!= 0){
1036                 printf("ctl: can't allocate %d entry internal pool, "
1037                        "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1038                 return (ENOMEM);
1039         }
1040
1041         if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1042                             CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1043                 printf("ctl: can't allocate %d entry emergency pool, "
1044                        "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1045                 ctl_pool_free(internal_pool);
1046                 return (ENOMEM);
1047         }
1048
1049         if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1050                             &other_pool) != 0)
1051         {
1052                 printf("ctl: can't allocate %d entry other SC pool, "
1053                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1054                 ctl_pool_free(internal_pool);
1055                 ctl_pool_free(emergency_pool);
1056                 return (ENOMEM);
1057         }
1058
1059         softc->internal_pool = internal_pool;
1060         softc->emergency_pool = emergency_pool;
1061         softc->othersc_pool = other_pool;
1062
1063         if (worker_threads <= 0)
1064                 worker_threads = max(1, mp_ncpus / 4);
1065         if (worker_threads > CTL_MAX_THREADS)
1066                 worker_threads = CTL_MAX_THREADS;
1067
1068         for (i = 0; i < worker_threads; i++) {
1069                 struct ctl_thread *thr = &softc->threads[i];
1070
1071                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1072                 thr->ctl_softc = softc;
1073                 STAILQ_INIT(&thr->incoming_queue);
1074                 STAILQ_INIT(&thr->rtr_queue);
1075                 STAILQ_INIT(&thr->done_queue);
1076                 STAILQ_INIT(&thr->isc_queue);
1077
1078                 error = kproc_kthread_add(ctl_work_thread, thr,
1079                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1080                 if (error != 0) {
1081                         printf("error creating CTL work thread!\n");
1082                         ctl_pool_free(internal_pool);
1083                         ctl_pool_free(emergency_pool);
1084                         ctl_pool_free(other_pool);
1085                         return (error);
1086                 }
1087         }
1088         error = kproc_kthread_add(ctl_lun_thread, softc,
1089             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1090         if (error != 0) {
1091                 printf("error creating CTL lun thread!\n");
1092                 ctl_pool_free(internal_pool);
1093                 ctl_pool_free(emergency_pool);
1094                 ctl_pool_free(other_pool);
1095                 return (error);
1096         }
1097         if (bootverbose)
1098                 printf("ctl: CAM Target Layer loaded\n");
1099
1100         /*
1101          * Initialize the ioctl front end.
1102          */
1103         ctl_frontend_register(&ioctl_frontend);
1104         port = &softc->ioctl_info.port;
1105         port->frontend = &ioctl_frontend;
1106         sprintf(softc->ioctl_info.port_name, "ioctl");
1107         port->port_type = CTL_PORT_IOCTL;
1108         port->num_requested_ctl_io = 100;
1109         port->port_name = softc->ioctl_info.port_name;
1110         port->port_online = ctl_ioctl_online;
1111         port->port_offline = ctl_ioctl_offline;
1112         port->onoff_arg = &softc->ioctl_info;
1113         port->lun_enable = ctl_ioctl_lun_enable;
1114         port->lun_disable = ctl_ioctl_lun_disable;
1115         port->targ_lun_arg = &softc->ioctl_info;
1116         port->fe_datamove = ctl_ioctl_datamove;
1117         port->fe_done = ctl_ioctl_done;
1118         port->max_targets = 15;
1119         port->max_target_id = 15;
1120
1121         if (ctl_port_register(&softc->ioctl_info.port,
1122                           (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1123                 printf("ctl: ioctl front end registration failed, will "
1124                        "continue anyway\n");
1125         }
1126
1127 #ifdef CTL_IO_DELAY
1128         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1129                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1130                        sizeof(struct callout), CTL_TIMER_BYTES);
1131                 return (EINVAL);
1132         }
1133 #endif /* CTL_IO_DELAY */
1134
1135         return (0);
1136 }
1137
1138 void
1139 ctl_shutdown(void)
1140 {
1141         struct ctl_softc *softc;
1142         struct ctl_lun *lun, *next_lun;
1143         struct ctl_io_pool *pool;
1144
1145         softc = (struct ctl_softc *)control_softc;
1146
1147         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1148                 printf("ctl: ioctl front end deregistration failed\n");
1149
1150         mtx_lock(&softc->ctl_lock);
1151
1152         /*
1153          * Free up each LUN.
1154          */
1155         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1156                 next_lun = STAILQ_NEXT(lun, links);
1157                 ctl_free_lun(lun);
1158         }
1159
1160         mtx_unlock(&softc->ctl_lock);
1161
1162         ctl_frontend_deregister(&ioctl_frontend);
1163
1164         /*
1165          * This will rip the rug out from under any FETDs or anyone else
1166          * that has a pool allocated.  Since we increment our module
1167          * refcount any time someone outside the main CTL module allocates
1168          * a pool, we shouldn't have any problems here.  The user won't be
1169          * able to unload the CTL module until client modules have
1170          * successfully unloaded.
1171          */
1172         while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1173                 ctl_pool_free(pool);
1174
1175 #if 0
1176         ctl_shutdown_thread(softc->work_thread);
1177         mtx_destroy(&softc->queue_lock);
1178 #endif
1179
1180         ctl_tpc_shutdown(softc);
1181         mtx_destroy(&softc->pool_lock);
1182         mtx_destroy(&softc->ctl_lock);
1183
1184         destroy_dev(softc->dev);
1185
1186         sysctl_ctx_free(&softc->sysctl_ctx);
1187
1188         free(control_softc, M_DEVBUF);
1189         control_softc = NULL;
1190
1191         if (bootverbose)
1192                 printf("ctl: CAM Target Layer unloaded\n");
1193 }
1194
1195 static int
1196 ctl_module_event_handler(module_t mod, int what, void *arg)
1197 {
1198
1199         switch (what) {
1200         case MOD_LOAD:
1201                 return (ctl_init());
1202         case MOD_UNLOAD:
1203                 return (EBUSY);
1204         default:
1205                 return (EOPNOTSUPP);
1206         }
1207 }
1208
1209 /*
1210  * XXX KDM should we do some access checks here?  Bump a reference count to
1211  * prevent a CTL module from being unloaded while someone has it open?
1212  */
1213 static int
1214 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1215 {
1216         return (0);
1217 }
1218
1219 static int
1220 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1221 {
1222         return (0);
1223 }
1224
1225 int
1226 ctl_port_enable(ctl_port_type port_type)
1227 {
1228         struct ctl_softc *softc;
1229         struct ctl_port *port;
1230
1231         if (ctl_is_single == 0) {
1232                 union ctl_ha_msg msg_info;
1233                 int isc_retval;
1234
1235 #if 0
1236                 printf("%s: HA mode, synchronizing frontend enable\n",
1237                         __func__);
1238 #endif
1239                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1240                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1241                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1242                         printf("Sync msg send error retval %d\n", isc_retval);
1243                 }
1244                 if (!rcv_sync_msg) {
1245                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1246                                 sizeof(msg_info), 1);
1247                 }
1248 #if 0
1249                 printf("CTL:Frontend Enable\n");
1250         } else {
1251                 printf("%s: single mode, skipping frontend synchronization\n",
1252                         __func__);
1253 #endif
1254         }
1255
1256         softc = control_softc;
1257
1258         STAILQ_FOREACH(port, &softc->port_list, links) {
1259                 if (port_type & port->port_type)
1260                 {
1261 #if 0
1262                         printf("port %d\n", port->targ_port);
1263 #endif
1264                         ctl_port_online(port);
1265                 }
1266         }
1267
1268         return (0);
1269 }
1270
1271 int
1272 ctl_port_disable(ctl_port_type port_type)
1273 {
1274         struct ctl_softc *softc;
1275         struct ctl_port *port;
1276
1277         softc = control_softc;
1278
1279         STAILQ_FOREACH(port, &softc->port_list, links) {
1280                 if (port_type & port->port_type)
1281                         ctl_port_offline(port);
1282         }
1283
1284         return (0);
1285 }
1286
1287 /*
1288  * Returns 0 for success, 1 for failure.
1289  * Currently the only failure mode is if there aren't enough entries
1290  * allocated.  So, in case of a failure, look at num_entries_dropped,
1291  * reallocate and try again.
1292  */
1293 int
1294 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1295               int *num_entries_filled, int *num_entries_dropped,
1296               ctl_port_type port_type, int no_virtual)
1297 {
1298         struct ctl_softc *softc;
1299         struct ctl_port *port;
1300         int entries_dropped, entries_filled;
1301         int retval;
1302         int i;
1303
1304         softc = control_softc;
1305
1306         retval = 0;
1307         entries_filled = 0;
1308         entries_dropped = 0;
1309
1310         i = 0;
1311         mtx_lock(&softc->ctl_lock);
1312         STAILQ_FOREACH(port, &softc->port_list, links) {
1313                 struct ctl_port_entry *entry;
1314
1315                 if ((port->port_type & port_type) == 0)
1316                         continue;
1317
1318                 if ((no_virtual != 0)
1319                  && (port->virtual_port != 0))
1320                         continue;
1321
1322                 if (entries_filled >= num_entries_alloced) {
1323                         entries_dropped++;
1324                         continue;
1325                 }
1326                 entry = &entries[i];
1327
1328                 entry->port_type = port->port_type;
1329                 strlcpy(entry->port_name, port->port_name,
1330                         sizeof(entry->port_name));
1331                 entry->physical_port = port->physical_port;
1332                 entry->virtual_port = port->virtual_port;
1333                 entry->wwnn = port->wwnn;
1334                 entry->wwpn = port->wwpn;
1335
1336                 i++;
1337                 entries_filled++;
1338         }
1339
1340         mtx_unlock(&softc->ctl_lock);
1341
1342         if (entries_dropped > 0)
1343                 retval = 1;
1344
1345         *num_entries_dropped = entries_dropped;
1346         *num_entries_filled = entries_filled;
1347
1348         return (retval);
1349 }
1350
1351 static void
1352 ctl_ioctl_online(void *arg)
1353 {
1354         struct ctl_ioctl_info *ioctl_info;
1355
1356         ioctl_info = (struct ctl_ioctl_info *)arg;
1357
1358         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1359 }
1360
1361 static void
1362 ctl_ioctl_offline(void *arg)
1363 {
1364         struct ctl_ioctl_info *ioctl_info;
1365
1366         ioctl_info = (struct ctl_ioctl_info *)arg;
1367
1368         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1369 }
1370
1371 /*
1372  * Remove an initiator by port number and initiator ID.
1373  * Returns 0 for success, -1 for failure.
1374  */
1375 int
1376 ctl_remove_initiator(struct ctl_port *port, int iid)
1377 {
1378         struct ctl_softc *softc = control_softc;
1379
1380         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1381
1382         if (iid > CTL_MAX_INIT_PER_PORT) {
1383                 printf("%s: initiator ID %u > maximun %u!\n",
1384                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1385                 return (-1);
1386         }
1387
1388         mtx_lock(&softc->ctl_lock);
1389         port->wwpn_iid[iid].in_use--;
1390         port->wwpn_iid[iid].last_use = time_uptime;
1391         mtx_unlock(&softc->ctl_lock);
1392
1393         return (0);
1394 }
1395
1396 /*
1397  * Add an initiator to the initiator map.
1398  * Returns iid for success, < 0 for failure.
1399  */
1400 int
1401 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1402 {
1403         struct ctl_softc *softc = control_softc;
1404         time_t best_time;
1405         int i, best;
1406
1407         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1408
1409         if (iid >= CTL_MAX_INIT_PER_PORT) {
1410                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1411                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1412                 free(name, M_CTL);
1413                 return (-1);
1414         }
1415
1416         mtx_lock(&softc->ctl_lock);
1417
1418         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1419                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1420                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1421                                 iid = i;
1422                                 break;
1423                         }
1424                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1425                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1426                                 iid = i;
1427                                 break;
1428                         }
1429                 }
1430         }
1431
1432         if (iid < 0) {
1433                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1434                         if (port->wwpn_iid[i].in_use == 0 &&
1435                             port->wwpn_iid[i].wwpn == 0 &&
1436                             port->wwpn_iid[i].name == NULL) {
1437                                 iid = i;
1438                                 break;
1439                         }
1440                 }
1441         }
1442
1443         if (iid < 0) {
1444                 best = -1;
1445                 best_time = INT32_MAX;
1446                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1447                         if (port->wwpn_iid[i].in_use == 0) {
1448                                 if (port->wwpn_iid[i].last_use < best_time) {
1449                                         best = i;
1450                                         best_time = port->wwpn_iid[i].last_use;
1451                                 }
1452                         }
1453                 }
1454                 iid = best;
1455         }
1456
1457         if (iid < 0) {
1458                 mtx_unlock(&softc->ctl_lock);
1459                 free(name, M_CTL);
1460                 return (-2);
1461         }
1462
1463         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1464                 /*
1465                  * This is not an error yet.
1466                  */
1467                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1468 #if 0
1469                         printf("%s: port %d iid %u WWPN %#jx arrived"
1470                             " again\n", __func__, port->targ_port,
1471                             iid, (uintmax_t)wwpn);
1472 #endif
1473                         goto take;
1474                 }
1475                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1476                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1477 #if 0
1478                         printf("%s: port %d iid %u name '%s' arrived"
1479                             " again\n", __func__, port->targ_port,
1480                             iid, name);
1481 #endif
1482                         goto take;
1483                 }
1484
1485                 /*
1486                  * This is an error, but what do we do about it?  The
1487                  * driver is telling us we have a new WWPN for this
1488                  * initiator ID, so we pretty much need to use it.
1489                  */
1490                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1491                     " but WWPN %#jx '%s' is still at that address\n",
1492                     __func__, port->targ_port, iid, wwpn, name,
1493                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1494                     port->wwpn_iid[iid].name);
1495
1496                 /*
1497                  * XXX KDM clear have_ca and ua_pending on each LUN for
1498                  * this initiator.
1499                  */
1500         }
1501 take:
1502         free(port->wwpn_iid[iid].name, M_CTL);
1503         port->wwpn_iid[iid].name = name;
1504         port->wwpn_iid[iid].wwpn = wwpn;
1505         port->wwpn_iid[iid].in_use++;
1506         mtx_unlock(&softc->ctl_lock);
1507
1508         return (iid);
1509 }
1510
1511 static int
1512 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1513 {
1514         int len;
1515
1516         switch (port->port_type) {
1517         case CTL_PORT_FC:
1518         {
1519                 struct scsi_transportid_fcp *id =
1520                     (struct scsi_transportid_fcp *)buf;
1521                 if (port->wwpn_iid[iid].wwpn == 0)
1522                         return (0);
1523                 memset(id, 0, sizeof(*id));
1524                 id->format_protocol = SCSI_PROTO_FC;
1525                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1526                 return (sizeof(*id));
1527         }
1528         case CTL_PORT_ISCSI:
1529         {
1530                 struct scsi_transportid_iscsi_port *id =
1531                     (struct scsi_transportid_iscsi_port *)buf;
1532                 if (port->wwpn_iid[iid].name == NULL)
1533                         return (0);
1534                 memset(id, 0, 256);
1535                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1536                     SCSI_PROTO_ISCSI;
1537                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1538                 len = roundup2(min(len, 252), 4);
1539                 scsi_ulto2b(len, id->additional_length);
1540                 return (sizeof(*id) + len);
1541         }
1542         case CTL_PORT_SAS:
1543         {
1544                 struct scsi_transportid_sas *id =
1545                     (struct scsi_transportid_sas *)buf;
1546                 if (port->wwpn_iid[iid].wwpn == 0)
1547                         return (0);
1548                 memset(id, 0, sizeof(*id));
1549                 id->format_protocol = SCSI_PROTO_SAS;
1550                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1551                 return (sizeof(*id));
1552         }
1553         default:
1554         {
1555                 struct scsi_transportid_spi *id =
1556                     (struct scsi_transportid_spi *)buf;
1557                 memset(id, 0, sizeof(*id));
1558                 id->format_protocol = SCSI_PROTO_SPI;
1559                 scsi_ulto2b(iid, id->scsi_addr);
1560                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1561                 return (sizeof(*id));
1562         }
1563         }
1564 }
1565
1566 static int
1567 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1568 {
1569         return (0);
1570 }
1571
1572 static int
1573 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1574 {
1575         return (0);
1576 }
1577
1578 /*
1579  * Data movement routine for the CTL ioctl frontend port.
1580  */
1581 static int
1582 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1583 {
1584         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1585         struct ctl_sg_entry ext_entry, kern_entry;
1586         int ext_sglen, ext_sg_entries, kern_sg_entries;
1587         int ext_sg_start, ext_offset;
1588         int len_to_copy, len_copied;
1589         int kern_watermark, ext_watermark;
1590         int ext_sglist_malloced;
1591         int i, j;
1592
1593         ext_sglist_malloced = 0;
1594         ext_sg_start = 0;
1595         ext_offset = 0;
1596
1597         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1598
1599         /*
1600          * If this flag is set, fake the data transfer.
1601          */
1602         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1603                 ctsio->ext_data_filled = ctsio->ext_data_len;
1604                 goto bailout;
1605         }
1606
1607         /*
1608          * To simplify things here, if we have a single buffer, stick it in
1609          * a S/G entry and just make it a single entry S/G list.
1610          */
1611         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1612                 int len_seen;
1613
1614                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1615
1616                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1617                                                            M_WAITOK);
1618                 ext_sglist_malloced = 1;
1619                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1620                                    ext_sglen) != 0) {
1621                         ctl_set_internal_failure(ctsio,
1622                                                  /*sks_valid*/ 0,
1623                                                  /*retry_count*/ 0);
1624                         goto bailout;
1625                 }
1626                 ext_sg_entries = ctsio->ext_sg_entries;
1627                 len_seen = 0;
1628                 for (i = 0; i < ext_sg_entries; i++) {
1629                         if ((len_seen + ext_sglist[i].len) >=
1630                              ctsio->ext_data_filled) {
1631                                 ext_sg_start = i;
1632                                 ext_offset = ctsio->ext_data_filled - len_seen;
1633                                 break;
1634                         }
1635                         len_seen += ext_sglist[i].len;
1636                 }
1637         } else {
1638                 ext_sglist = &ext_entry;
1639                 ext_sglist->addr = ctsio->ext_data_ptr;
1640                 ext_sglist->len = ctsio->ext_data_len;
1641                 ext_sg_entries = 1;
1642                 ext_sg_start = 0;
1643                 ext_offset = ctsio->ext_data_filled;
1644         }
1645
1646         if (ctsio->kern_sg_entries > 0) {
1647                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1648                 kern_sg_entries = ctsio->kern_sg_entries;
1649         } else {
1650                 kern_sglist = &kern_entry;
1651                 kern_sglist->addr = ctsio->kern_data_ptr;
1652                 kern_sglist->len = ctsio->kern_data_len;
1653                 kern_sg_entries = 1;
1654         }
1655
1656
1657         kern_watermark = 0;
1658         ext_watermark = ext_offset;
1659         len_copied = 0;
1660         for (i = ext_sg_start, j = 0;
1661              i < ext_sg_entries && j < kern_sg_entries;) {
1662                 uint8_t *ext_ptr, *kern_ptr;
1663
1664                 len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1665                                       kern_sglist[j].len - kern_watermark);
1666
1667                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1668                 ext_ptr = ext_ptr + ext_watermark;
1669                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1670                         /*
1671                          * XXX KDM fix this!
1672                          */
1673                         panic("need to implement bus address support");
1674 #if 0
1675                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1676 #endif
1677                 } else
1678                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1679                 kern_ptr = kern_ptr + kern_watermark;
1680
1681                 kern_watermark += len_to_copy;
1682                 ext_watermark += len_to_copy;
1683
1684                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1685                      CTL_FLAG_DATA_IN) {
1686                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1687                                          "bytes to user\n", len_to_copy));
1688                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1689                                          "to %p\n", kern_ptr, ext_ptr));
1690                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1691                                 ctl_set_internal_failure(ctsio,
1692                                                          /*sks_valid*/ 0,
1693                                                          /*retry_count*/ 0);
1694                                 goto bailout;
1695                         }
1696                 } else {
1697                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1698                                          "bytes from user\n", len_to_copy));
1699                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1700                                          "to %p\n", ext_ptr, kern_ptr));
1701                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1702                                 ctl_set_internal_failure(ctsio,
1703                                                          /*sks_valid*/ 0,
1704                                                          /*retry_count*/0);
1705                                 goto bailout;
1706                         }
1707                 }
1708
1709                 len_copied += len_to_copy;
1710
1711                 if (ext_sglist[i].len == ext_watermark) {
1712                         i++;
1713                         ext_watermark = 0;
1714                 }
1715
1716                 if (kern_sglist[j].len == kern_watermark) {
1717                         j++;
1718                         kern_watermark = 0;
1719                 }
1720         }
1721
1722         ctsio->ext_data_filled += len_copied;
1723
1724         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1725                          "kern_sg_entries: %d\n", ext_sg_entries,
1726                          kern_sg_entries));
1727         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1728                          "kern_data_len = %d\n", ctsio->ext_data_len,
1729                          ctsio->kern_data_len));
1730
1731
1732         /* XXX KDM set residual?? */
1733 bailout:
1734
1735         if (ext_sglist_malloced != 0)
1736                 free(ext_sglist, M_CTL);
1737
1738         return (CTL_RETVAL_COMPLETE);
1739 }
1740
1741 /*
1742  * Serialize a command that went down the "wrong" side, and so was sent to
1743  * this controller for execution.  The logic is a little different than the
1744  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1745  * sent back to the other side, but in the success case, we execute the
1746  * command on this side (XFER mode) or tell the other side to execute it
1747  * (SER_ONLY mode).
1748  */
1749 static int
1750 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1751 {
1752         struct ctl_softc *ctl_softc;
1753         union ctl_ha_msg msg_info;
1754         struct ctl_lun *lun;
1755         int retval = 0;
1756         uint32_t targ_lun;
1757
1758         ctl_softc = control_softc;
1759
1760         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1761         lun = ctl_softc->ctl_luns[targ_lun];
1762         if (lun==NULL)
1763         {
1764                 /*
1765                  * Why isn't LUN defined? The other side wouldn't
1766                  * send a cmd if the LUN is undefined.
1767                  */
1768                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1769
1770                 /* "Logical unit not supported" */
1771                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1772                                    lun,
1773                                    /*sense_format*/SSD_TYPE_NONE,
1774                                    /*current_error*/ 1,
1775                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1776                                    /*asc*/ 0x25,
1777                                    /*ascq*/ 0x00,
1778                                    SSD_ELEM_NONE);
1779
1780                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1781                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1782                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1783                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1784                 msg_info.hdr.serializing_sc = NULL;
1785                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1786                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1787                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1788                 }
1789                 return(1);
1790
1791         }
1792
1793         mtx_lock(&lun->lun_lock);
1794         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1795
1796         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1797                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1798                  ooa_links))) {
1799         case CTL_ACTION_BLOCK:
1800                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1801                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1802                                   blocked_links);
1803                 break;
1804         case CTL_ACTION_PASS:
1805         case CTL_ACTION_SKIP:
1806                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1807                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1808                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1809                 } else {
1810
1811                         /* send msg back to other side */
1812                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1813                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1814                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1815 #if 0
1816                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1817 #endif
1818                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1819                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1820                         }
1821                 }
1822                 break;
1823         case CTL_ACTION_OVERLAP:
1824                 /* OVERLAPPED COMMANDS ATTEMPTED */
1825                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1826                                    lun,
1827                                    /*sense_format*/SSD_TYPE_NONE,
1828                                    /*current_error*/ 1,
1829                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1830                                    /*asc*/ 0x4E,
1831                                    /*ascq*/ 0x00,
1832                                    SSD_ELEM_NONE);
1833
1834                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1835                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1836                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1837                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1838                 msg_info.hdr.serializing_sc = NULL;
1839                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1840 #if 0
1841                 printf("BAD JUJU:Major Bummer Overlap\n");
1842 #endif
1843                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1844                 retval = 1;
1845                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1846                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1847                 }
1848                 break;
1849         case CTL_ACTION_OVERLAP_TAG:
1850                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1851                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1852                                    lun,
1853                                    /*sense_format*/SSD_TYPE_NONE,
1854                                    /*current_error*/ 1,
1855                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1856                                    /*asc*/ 0x4D,
1857                                    /*ascq*/ ctsio->tag_num & 0xff,
1858                                    SSD_ELEM_NONE);
1859
1860                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1861                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1862                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1863                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1864                 msg_info.hdr.serializing_sc = NULL;
1865                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1866 #if 0
1867                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1868 #endif
1869                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1870                 retval = 1;
1871                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1872                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1873                 }
1874                 break;
1875         case CTL_ACTION_ERROR:
1876         default:
1877                 /* "Internal target failure" */
1878                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1879                                    lun,
1880                                    /*sense_format*/SSD_TYPE_NONE,
1881                                    /*current_error*/ 1,
1882                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1883                                    /*asc*/ 0x44,
1884                                    /*ascq*/ 0x00,
1885                                    SSD_ELEM_NONE);
1886
1887                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1888                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1889                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1890                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1891                 msg_info.hdr.serializing_sc = NULL;
1892                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1893 #if 0
1894                 printf("BAD JUJU:Major Bummer HW Error\n");
1895 #endif
1896                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1897                 retval = 1;
1898                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1899                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1900                 }
1901                 break;
1902         }
1903         mtx_unlock(&lun->lun_lock);
1904         return (retval);
1905 }
1906
1907 static int
1908 ctl_ioctl_submit_wait(union ctl_io *io)
1909 {
1910         struct ctl_fe_ioctl_params params;
1911         ctl_fe_ioctl_state last_state;
1912         int done, retval;
1913
1914         retval = 0;
1915
1916         bzero(&params, sizeof(params));
1917
1918         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1919         cv_init(&params.sem, "ctlioccv");
1920         params.state = CTL_IOCTL_INPROG;
1921         last_state = params.state;
1922
1923         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1924
1925         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1926
1927         /* This shouldn't happen */
1928         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1929                 return (retval);
1930
1931         done = 0;
1932
1933         do {
1934                 mtx_lock(&params.ioctl_mtx);
1935                 /*
1936                  * Check the state here, and don't sleep if the state has
1937                  * already changed (i.e. wakeup has already occured, but we
1938                  * weren't waiting yet).
1939                  */
1940                 if (params.state == last_state) {
1941                         /* XXX KDM cv_wait_sig instead? */
1942                         cv_wait(&params.sem, &params.ioctl_mtx);
1943                 }
1944                 last_state = params.state;
1945
1946                 switch (params.state) {
1947                 case CTL_IOCTL_INPROG:
1948                         /* Why did we wake up? */
1949                         /* XXX KDM error here? */
1950                         mtx_unlock(&params.ioctl_mtx);
1951                         break;
1952                 case CTL_IOCTL_DATAMOVE:
1953                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1954
1955                         /*
1956                          * change last_state back to INPROG to avoid
1957                          * deadlock on subsequent data moves.
1958                          */
1959                         params.state = last_state = CTL_IOCTL_INPROG;
1960
1961                         mtx_unlock(&params.ioctl_mtx);
1962                         ctl_ioctl_do_datamove(&io->scsiio);
1963                         /*
1964                          * Note that in some cases, most notably writes,
1965                          * this will queue the I/O and call us back later.
1966                          * In other cases, generally reads, this routine
1967                          * will immediately call back and wake us up,
1968                          * probably using our own context.
1969                          */
1970                         io->scsiio.be_move_done(io);
1971                         break;
1972                 case CTL_IOCTL_DONE:
1973                         mtx_unlock(&params.ioctl_mtx);
1974                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1975                         done = 1;
1976                         break;
1977                 default:
1978                         mtx_unlock(&params.ioctl_mtx);
1979                         /* XXX KDM error here? */
1980                         break;
1981                 }
1982         } while (done == 0);
1983
1984         mtx_destroy(&params.ioctl_mtx);
1985         cv_destroy(&params.sem);
1986
1987         return (CTL_RETVAL_COMPLETE);
1988 }
1989
1990 static void
1991 ctl_ioctl_datamove(union ctl_io *io)
1992 {
1993         struct ctl_fe_ioctl_params *params;
1994
1995         params = (struct ctl_fe_ioctl_params *)
1996                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1997
1998         mtx_lock(&params->ioctl_mtx);
1999         params->state = CTL_IOCTL_DATAMOVE;
2000         cv_broadcast(&params->sem);
2001         mtx_unlock(&params->ioctl_mtx);
2002 }
2003
2004 static void
2005 ctl_ioctl_done(union ctl_io *io)
2006 {
2007         struct ctl_fe_ioctl_params *params;
2008
2009         params = (struct ctl_fe_ioctl_params *)
2010                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2011
2012         mtx_lock(&params->ioctl_mtx);
2013         params->state = CTL_IOCTL_DONE;
2014         cv_broadcast(&params->sem);
2015         mtx_unlock(&params->ioctl_mtx);
2016 }
2017
2018 static void
2019 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2020 {
2021         struct ctl_fe_ioctl_startstop_info *sd_info;
2022
2023         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2024
2025         sd_info->hs_info.status = metatask->status;
2026         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2027         sd_info->hs_info.luns_complete =
2028                 metatask->taskinfo.startstop.luns_complete;
2029         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2030
2031         cv_broadcast(&sd_info->sem);
2032 }
2033
2034 static void
2035 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2036 {
2037         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2038
2039         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2040
2041         mtx_lock(fe_bbr_info->lock);
2042         fe_bbr_info->bbr_info->status = metatask->status;
2043         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2044         fe_bbr_info->wakeup_done = 1;
2045         mtx_unlock(fe_bbr_info->lock);
2046
2047         cv_broadcast(&fe_bbr_info->sem);
2048 }
2049
2050 /*
2051  * Returns 0 for success, errno for failure.
2052  */
2053 static int
2054 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2055                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2056 {
2057         union ctl_io *io;
2058         int retval;
2059
2060         retval = 0;
2061
2062         mtx_lock(&lun->lun_lock);
2063         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2064              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2065              ooa_links)) {
2066                 struct ctl_ooa_entry *entry;
2067
2068                 /*
2069                  * If we've got more than we can fit, just count the
2070                  * remaining entries.
2071                  */
2072                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2073                         continue;
2074
2075                 entry = &kern_entries[*cur_fill_num];
2076
2077                 entry->tag_num = io->scsiio.tag_num;
2078                 entry->lun_num = lun->lun;
2079 #ifdef CTL_TIME_IO
2080                 entry->start_bt = io->io_hdr.start_bt;
2081 #endif
2082                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2083                 entry->cdb_len = io->scsiio.cdb_len;
2084                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2085                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2086
2087                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2088                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2089
2090                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2091                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2092
2093                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2094                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2095
2096                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2097                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2098         }
2099         mtx_unlock(&lun->lun_lock);
2100
2101         return (retval);
2102 }
2103
2104 static void *
2105 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2106                  size_t error_str_len)
2107 {
2108         void *kptr;
2109
2110         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2111
2112         if (copyin(user_addr, kptr, len) != 0) {
2113                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2114                          "from user address %p to kernel address %p", len,
2115                          user_addr, kptr);
2116                 free(kptr, M_CTL);
2117                 return (NULL);
2118         }
2119
2120         return (kptr);
2121 }
2122
2123 static void
2124 ctl_free_args(int num_args, struct ctl_be_arg *args)
2125 {
2126         int i;
2127
2128         if (args == NULL)
2129                 return;
2130
2131         for (i = 0; i < num_args; i++) {
2132                 free(args[i].kname, M_CTL);
2133                 free(args[i].kvalue, M_CTL);
2134         }
2135
2136         free(args, M_CTL);
2137 }
2138
2139 static struct ctl_be_arg *
2140 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2141                 char *error_str, size_t error_str_len)
2142 {
2143         struct ctl_be_arg *args;
2144         int i;
2145
2146         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2147                                 error_str, error_str_len);
2148
2149         if (args == NULL)
2150                 goto bailout;
2151
2152         for (i = 0; i < num_args; i++) {
2153                 args[i].kname = NULL;
2154                 args[i].kvalue = NULL;
2155         }
2156
2157         for (i = 0; i < num_args; i++) {
2158                 uint8_t *tmpptr;
2159
2160                 args[i].kname = ctl_copyin_alloc(args[i].name,
2161                         args[i].namelen, error_str, error_str_len);
2162                 if (args[i].kname == NULL)
2163                         goto bailout;
2164
2165                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2166                         snprintf(error_str, error_str_len, "Argument %d "
2167                                  "name is not NUL-terminated", i);
2168                         goto bailout;
2169                 }
2170
2171                 if (args[i].flags & CTL_BEARG_RD) {
2172                         tmpptr = ctl_copyin_alloc(args[i].value,
2173                                 args[i].vallen, error_str, error_str_len);
2174                         if (tmpptr == NULL)
2175                                 goto bailout;
2176                         if ((args[i].flags & CTL_BEARG_ASCII)
2177                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2178                                 snprintf(error_str, error_str_len, "Argument "
2179                                     "%d value is not NUL-terminated", i);
2180                                 goto bailout;
2181                         }
2182                         args[i].kvalue = tmpptr;
2183                 } else {
2184                         args[i].kvalue = malloc(args[i].vallen,
2185                             M_CTL, M_WAITOK | M_ZERO);
2186                 }
2187         }
2188
2189         return (args);
2190 bailout:
2191
2192         ctl_free_args(num_args, args);
2193
2194         return (NULL);
2195 }
2196
2197 static void
2198 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2199 {
2200         int i;
2201
2202         for (i = 0; i < num_args; i++) {
2203                 if (args[i].flags & CTL_BEARG_WR)
2204                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2205         }
2206 }
2207
2208 /*
2209  * Escape characters that are illegal or not recommended in XML.
2210  */
2211 int
2212 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2213 {
2214         int retval;
2215
2216         retval = 0;
2217
2218         for (; *str; str++) {
2219                 switch (*str) {
2220                 case '&':
2221                         retval = sbuf_printf(sb, "&amp;");
2222                         break;
2223                 case '>':
2224                         retval = sbuf_printf(sb, "&gt;");
2225                         break;
2226                 case '<':
2227                         retval = sbuf_printf(sb, "&lt;");
2228                         break;
2229                 default:
2230                         retval = sbuf_putc(sb, *str);
2231                         break;
2232                 }
2233
2234                 if (retval != 0)
2235                         break;
2236
2237         }
2238
2239         return (retval);
2240 }
2241
2242 static 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->pr_keys[idx] == 0)
2996                                                 continue;
2997                                         printf("  LUN %d port %d iid %d key "
2998                                                "%#jx\n", i, j, k,
2999                                                (uintmax_t)lun->pr_keys[idx]);
3000                                 }
3001                         }
3002                 }
3003                 printf("CTL Persistent Reservation information end\n");
3004                 printf("CTL Ports:\n");
3005                 STAILQ_FOREACH(port, &softc->port_list, links) {
3006                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3007                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3008                                port->frontend->name, port->port_type,
3009                                port->physical_port, port->virtual_port,
3010                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3011                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3012                                 if (port->wwpn_iid[j].in_use == 0 &&
3013                                     port->wwpn_iid[j].wwpn == 0 &&
3014                                     port->wwpn_iid[j].name == NULL)
3015                                         continue;
3016
3017                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3018                                     j, port->wwpn_iid[j].in_use,
3019                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3020                                     port->wwpn_iid[j].name);
3021                         }
3022                 }
3023                 printf("CTL Port information end\n");
3024                 mtx_unlock(&softc->ctl_lock);
3025                 /*
3026                  * XXX KDM calling this without a lock.  We'd likely want
3027                  * to drop the lock before calling the frontend's dump
3028                  * routine anyway.
3029                  */
3030                 printf("CTL Frontends:\n");
3031                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3032                         printf("  Frontend '%s'\n", fe->name);
3033                         if (fe->fe_dump != NULL)
3034                                 fe->fe_dump();
3035                 }
3036                 printf("CTL Frontend information end\n");
3037                 break;
3038         }
3039         case CTL_LUN_REQ: {
3040                 struct ctl_lun_req *lun_req;
3041                 struct ctl_backend_driver *backend;
3042
3043                 lun_req = (struct ctl_lun_req *)addr;
3044
3045                 backend = ctl_backend_find(lun_req->backend);
3046                 if (backend == NULL) {
3047                         lun_req->status = CTL_LUN_ERROR;
3048                         snprintf(lun_req->error_str,
3049                                  sizeof(lun_req->error_str),
3050                                  "Backend \"%s\" not found.",
3051                                  lun_req->backend);
3052                         break;
3053                 }
3054                 if (lun_req->num_be_args > 0) {
3055                         lun_req->kern_be_args = ctl_copyin_args(
3056                                 lun_req->num_be_args,
3057                                 lun_req->be_args,
3058                                 lun_req->error_str,
3059                                 sizeof(lun_req->error_str));
3060                         if (lun_req->kern_be_args == NULL) {
3061                                 lun_req->status = CTL_LUN_ERROR;
3062                                 break;
3063                         }
3064                 }
3065
3066                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3067
3068                 if (lun_req->num_be_args > 0) {
3069                         ctl_copyout_args(lun_req->num_be_args,
3070                                       lun_req->kern_be_args);
3071                         ctl_free_args(lun_req->num_be_args,
3072                                       lun_req->kern_be_args);
3073                 }
3074                 break;
3075         }
3076         case CTL_LUN_LIST: {
3077                 struct sbuf *sb;
3078                 struct ctl_lun *lun;
3079                 struct ctl_lun_list *list;
3080                 struct ctl_option *opt;
3081
3082                 list = (struct ctl_lun_list *)addr;
3083
3084                 /*
3085                  * Allocate a fixed length sbuf here, based on the length
3086                  * of the user's buffer.  We could allocate an auto-extending
3087                  * buffer, and then tell the user how much larger our
3088                  * amount of data is than his buffer, but that presents
3089                  * some problems:
3090                  *
3091                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3092                  *     we can't hold a lock while calling them with an
3093                  *     auto-extending buffer.
3094                  *
3095                  * 2.  There is not currently a LUN reference counting
3096                  *     mechanism, outside of outstanding transactions on
3097                  *     the LUN's OOA queue.  So a LUN could go away on us
3098                  *     while we're getting the LUN number, backend-specific
3099                  *     information, etc.  Thus, given the way things
3100                  *     currently work, we need to hold the CTL lock while
3101                  *     grabbing LUN information.
3102                  *
3103                  * So, from the user's standpoint, the best thing to do is
3104                  * allocate what he thinks is a reasonable buffer length,
3105                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3106                  * double the buffer length and try again.  (And repeat
3107                  * that until he succeeds.)
3108                  */
3109                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3110                 if (sb == NULL) {
3111                         list->status = CTL_LUN_LIST_ERROR;
3112                         snprintf(list->error_str, sizeof(list->error_str),
3113                                  "Unable to allocate %d bytes for LUN list",
3114                                  list->alloc_len);
3115                         break;
3116                 }
3117
3118                 sbuf_printf(sb, "<ctllunlist>\n");
3119
3120                 mtx_lock(&softc->ctl_lock);
3121                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3122                         mtx_lock(&lun->lun_lock);
3123                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3124                                              (uintmax_t)lun->lun);
3125
3126                         /*
3127                          * Bail out as soon as we see that we've overfilled
3128                          * the buffer.
3129                          */
3130                         if (retval != 0)
3131                                 break;
3132
3133                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3134                                              "</backend_type>\n",
3135                                              (lun->backend == NULL) ?  "none" :
3136                                              lun->backend->name);
3137
3138                         if (retval != 0)
3139                                 break;
3140
3141                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3142                                              lun->be_lun->lun_type);
3143
3144                         if (retval != 0)
3145                                 break;
3146
3147                         if (lun->backend == NULL) {
3148                                 retval = sbuf_printf(sb, "</lun>\n");
3149                                 if (retval != 0)
3150                                         break;
3151                                 continue;
3152                         }
3153
3154                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3155                                              (lun->be_lun->maxlba > 0) ?
3156                                              lun->be_lun->maxlba + 1 : 0);
3157
3158                         if (retval != 0)
3159                                 break;
3160
3161                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3162                                              lun->be_lun->blocksize);
3163
3164                         if (retval != 0)
3165                                 break;
3166
3167                         retval = sbuf_printf(sb, "\t<serial_number>");
3168
3169                         if (retval != 0)
3170                                 break;
3171
3172                         retval = ctl_sbuf_printf_esc(sb,
3173                                                      lun->be_lun->serial_num);
3174
3175                         if (retval != 0)
3176                                 break;
3177
3178                         retval = sbuf_printf(sb, "</serial_number>\n");
3179                 
3180                         if (retval != 0)
3181                                 break;
3182
3183                         retval = sbuf_printf(sb, "\t<device_id>");
3184
3185                         if (retval != 0)
3186                                 break;
3187
3188                         retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3189
3190                         if (retval != 0)
3191                                 break;
3192
3193                         retval = sbuf_printf(sb, "</device_id>\n");
3194
3195                         if (retval != 0)
3196                                 break;
3197
3198                         if (lun->backend->lun_info != NULL) {
3199                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3200                                 if (retval != 0)
3201                                         break;
3202                         }
3203                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3204                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3205                                     opt->name, opt->value, opt->name);
3206                                 if (retval != 0)
3207                                         break;
3208                         }
3209
3210                         retval = sbuf_printf(sb, "</lun>\n");
3211
3212                         if (retval != 0)
3213                                 break;
3214                         mtx_unlock(&lun->lun_lock);
3215                 }
3216                 if (lun != NULL)
3217                         mtx_unlock(&lun->lun_lock);
3218                 mtx_unlock(&softc->ctl_lock);
3219
3220                 if ((retval != 0)
3221                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3222                         retval = 0;
3223                         sbuf_delete(sb);
3224                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3225                         snprintf(list->error_str, sizeof(list->error_str),
3226                                  "Out of space, %d bytes is too small",
3227                                  list->alloc_len);
3228                         break;
3229                 }
3230
3231                 sbuf_finish(sb);
3232
3233                 retval = copyout(sbuf_data(sb), list->lun_xml,
3234                                  sbuf_len(sb) + 1);
3235
3236                 list->fill_len = sbuf_len(sb) + 1;
3237                 list->status = CTL_LUN_LIST_OK;
3238                 sbuf_delete(sb);
3239                 break;
3240         }
3241         case CTL_ISCSI: {
3242                 struct ctl_iscsi *ci;
3243                 struct ctl_frontend *fe;
3244
3245                 ci = (struct ctl_iscsi *)addr;
3246
3247                 fe = ctl_frontend_find("iscsi");
3248                 if (fe == NULL) {
3249                         ci->status = CTL_ISCSI_ERROR;
3250                         snprintf(ci->error_str, sizeof(ci->error_str),
3251                             "Frontend \"iscsi\" not found.");
3252                         break;
3253                 }
3254
3255                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3256                 break;
3257         }
3258         case CTL_PORT_REQ: {
3259                 struct ctl_req *req;
3260                 struct ctl_frontend *fe;
3261
3262                 req = (struct ctl_req *)addr;
3263
3264                 fe = ctl_frontend_find(req->driver);
3265                 if (fe == NULL) {
3266                         req->status = CTL_LUN_ERROR;
3267                         snprintf(req->error_str, sizeof(req->error_str),
3268                             "Frontend \"%s\" not found.", req->driver);
3269                         break;
3270                 }
3271                 if (req->num_args > 0) {
3272                         req->kern_args = ctl_copyin_args(req->num_args,
3273                             req->args, req->error_str, sizeof(req->error_str));
3274                         if (req->kern_args == NULL) {
3275                                 req->status = CTL_LUN_ERROR;
3276                                 break;
3277                         }
3278                 }
3279
3280                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3281
3282                 if (req->num_args > 0) {
3283                         ctl_copyout_args(req->num_args, req->kern_args);
3284                         ctl_free_args(req->num_args, req->kern_args);
3285                 }
3286                 break;
3287         }
3288         case CTL_PORT_LIST: {
3289                 struct sbuf *sb;
3290                 struct ctl_port *port;
3291                 struct ctl_lun_list *list;
3292                 struct ctl_option *opt;
3293
3294                 list = (struct ctl_lun_list *)addr;
3295
3296                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3297                 if (sb == NULL) {
3298                         list->status = CTL_LUN_LIST_ERROR;
3299                         snprintf(list->error_str, sizeof(list->error_str),
3300                                  "Unable to allocate %d bytes for LUN list",
3301                                  list->alloc_len);
3302                         break;
3303                 }
3304
3305                 sbuf_printf(sb, "<ctlportlist>\n");
3306
3307                 mtx_lock(&softc->ctl_lock);
3308                 STAILQ_FOREACH(port, &softc->port_list, links) {
3309                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3310                                              (uintmax_t)port->targ_port);
3311
3312                         /*
3313                          * Bail out as soon as we see that we've overfilled
3314                          * the buffer.
3315                          */
3316                         if (retval != 0)
3317                                 break;
3318
3319                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3320                             "</frontend_type>\n", port->frontend->name);
3321                         if (retval != 0)
3322                                 break;
3323
3324                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3325                                              port->port_type);
3326                         if (retval != 0)
3327                                 break;
3328
3329                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3330                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3331                         if (retval != 0)
3332                                 break;
3333
3334                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3335                             port->port_name);
3336                         if (retval != 0)
3337                                 break;
3338
3339                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3340                             port->physical_port);
3341                         if (retval != 0)
3342                                 break;
3343
3344                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3345                             port->virtual_port);
3346                         if (retval != 0)
3347                                 break;
3348
3349                         retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3350                             (uintmax_t)port->wwnn);
3351                         if (retval != 0)
3352                                 break;
3353
3354                         retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3355                             (uintmax_t)port->wwpn);
3356                         if (retval != 0)
3357                                 break;
3358
3359                         if (port->port_info != NULL) {
3360                                 retval = port->port_info(port->onoff_arg, sb);
3361                                 if (retval != 0)
3362                                         break;
3363                         }
3364                         STAILQ_FOREACH(opt, &port->options, links) {
3365                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3366                                     opt->name, opt->value, opt->name);
3367                                 if (retval != 0)
3368                                         break;
3369                         }
3370
3371                         retval = sbuf_printf(sb, "</targ_port>\n");
3372                         if (retval != 0)
3373                                 break;
3374                 }
3375                 mtx_unlock(&softc->ctl_lock);
3376
3377                 if ((retval != 0)
3378                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3379                         retval = 0;
3380                         sbuf_delete(sb);
3381                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3382                         snprintf(list->error_str, sizeof(list->error_str),
3383                                  "Out of space, %d bytes is too small",
3384                                  list->alloc_len);
3385                         break;
3386                 }
3387
3388                 sbuf_finish(sb);
3389
3390                 retval = copyout(sbuf_data(sb), list->lun_xml,
3391                                  sbuf_len(sb) + 1);
3392
3393                 list->fill_len = sbuf_len(sb) + 1;
3394                 list->status = CTL_LUN_LIST_OK;
3395                 sbuf_delete(sb);
3396                 break;
3397         }
3398         default: {
3399                 /* XXX KDM should we fix this? */
3400 #if 0
3401                 struct ctl_backend_driver *backend;
3402                 unsigned int type;
3403                 int found;
3404
3405                 found = 0;
3406
3407                 /*
3408                  * We encode the backend type as the ioctl type for backend
3409                  * ioctls.  So parse it out here, and then search for a
3410                  * backend of this type.
3411                  */
3412                 type = _IOC_TYPE(cmd);
3413
3414                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3415                         if (backend->type == type) {
3416                                 found = 1;
3417                                 break;
3418                         }
3419                 }
3420                 if (found == 0) {
3421                         printf("ctl: unknown ioctl command %#lx or backend "
3422                                "%d\n", cmd, type);
3423                         retval = EINVAL;
3424                         break;
3425                 }
3426                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3427 #endif
3428                 retval = ENOTTY;
3429                 break;
3430         }
3431         }
3432         return (retval);
3433 }
3434
3435 uint32_t
3436 ctl_get_initindex(struct ctl_nexus *nexus)
3437 {
3438         if (nexus->targ_port < CTL_MAX_PORTS)
3439                 return (nexus->initid.id +
3440                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3441         else
3442                 return (nexus->initid.id +
3443                        ((nexus->targ_port - CTL_MAX_PORTS) *
3444                         CTL_MAX_INIT_PER_PORT));
3445 }
3446
3447 uint32_t
3448 ctl_get_resindex(struct ctl_nexus *nexus)
3449 {
3450         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3451 }
3452
3453 uint32_t
3454 ctl_port_idx(int port_num)
3455 {
3456         if (port_num < CTL_MAX_PORTS)
3457                 return(port_num);
3458         else
3459                 return(port_num - CTL_MAX_PORTS);
3460 }
3461
3462 static uint32_t
3463 ctl_map_lun(int port_num, uint32_t lun_id)
3464 {
3465         struct ctl_port *port;
3466
3467         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3468         if (port == NULL)
3469                 return (UINT32_MAX);
3470         if (port->lun_map == NULL)
3471                 return (lun_id);
3472         return (port->lun_map(port->targ_lun_arg, lun_id));
3473 }
3474
3475 static uint32_t
3476 ctl_map_lun_back(int port_num, uint32_t lun_id)
3477 {
3478         struct ctl_port *port;
3479         uint32_t i;
3480
3481         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3482         if (port->lun_map == NULL)
3483                 return (lun_id);
3484         for (i = 0; i < CTL_MAX_LUNS; i++) {
3485                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3486                         return (i);
3487         }
3488         return (UINT32_MAX);
3489 }
3490
3491 /*
3492  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3493  * that are a power of 2.
3494  */
3495 int
3496 ctl_ffz(uint32_t *mask, uint32_t size)
3497 {
3498         uint32_t num_chunks, num_pieces;
3499         int i, j;
3500
3501         num_chunks = (size >> 5);
3502         if (num_chunks == 0)
3503                 num_chunks++;
3504         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3505
3506         for (i = 0; i < num_chunks; i++) {
3507                 for (j = 0; j < num_pieces; j++) {
3508                         if ((mask[i] & (1 << j)) == 0)
3509                                 return ((i << 5) + j);
3510                 }
3511         }
3512
3513         return (-1);
3514 }
3515
3516 int
3517 ctl_set_mask(uint32_t *mask, uint32_t bit)
3518 {
3519         uint32_t chunk, piece;
3520
3521         chunk = bit >> 5;
3522         piece = bit % (sizeof(uint32_t) * 8);
3523
3524         if ((mask[chunk] & (1 << piece)) != 0)
3525                 return (-1);
3526         else
3527                 mask[chunk] |= (1 << piece);
3528
3529         return (0);
3530 }
3531
3532 int
3533 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3534 {
3535         uint32_t chunk, piece;
3536
3537         chunk = bit >> 5;
3538         piece = bit % (sizeof(uint32_t) * 8);
3539
3540         if ((mask[chunk] & (1 << piece)) == 0)
3541                 return (-1);
3542         else
3543                 mask[chunk] &= ~(1 << piece);
3544
3545         return (0);
3546 }
3547
3548 int
3549 ctl_is_set(uint32_t *mask, uint32_t bit)
3550 {
3551         uint32_t chunk, piece;
3552
3553         chunk = bit >> 5;
3554         piece = bit % (sizeof(uint32_t) * 8);
3555
3556         if ((mask[chunk] & (1 << piece)) == 0)
3557                 return (0);
3558         else
3559                 return (1);
3560 }
3561
3562 #ifdef unused
3563 /*
3564  * The bus, target and lun are optional, they can be filled in later.
3565  * can_wait is used to determine whether we can wait on the malloc or not.
3566  */
3567 union ctl_io*
3568 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3569               uint32_t targ_lun, int can_wait)
3570 {
3571         union ctl_io *io;
3572
3573         if (can_wait)
3574                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3575         else
3576                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3577
3578         if (io != NULL) {
3579                 io->io_hdr.io_type = io_type;
3580                 io->io_hdr.targ_port = targ_port;
3581                 /*
3582                  * XXX KDM this needs to change/go away.  We need to move
3583                  * to a preallocated pool of ctl_scsiio structures.
3584                  */
3585                 io->io_hdr.nexus.targ_target.id = targ_target;
3586                 io->io_hdr.nexus.targ_lun = targ_lun;
3587         }
3588
3589         return (io);
3590 }
3591
3592 void
3593 ctl_kfree_io(union ctl_io *io)
3594 {
3595         free(io, M_CTL);
3596 }
3597 #endif /* unused */
3598
3599 /*
3600  * ctl_softc, pool_type, total_ctl_io are passed in.
3601  * npool is passed out.
3602  */
3603 int
3604 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3605                 uint32_t total_ctl_io, struct ctl_io_pool **npool)
3606 {
3607         uint32_t i;
3608         union ctl_io *cur_io, *next_io;
3609         struct ctl_io_pool *pool;
3610         int retval;
3611
3612         retval = 0;
3613
3614         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3615                                             M_NOWAIT | M_ZERO);
3616         if (pool == NULL) {
3617                 retval = ENOMEM;
3618                 goto bailout;
3619         }
3620
3621         pool->type = pool_type;
3622         pool->ctl_softc = ctl_softc;
3623
3624         mtx_lock(&ctl_softc->pool_lock);
3625         pool->id = ctl_softc->cur_pool_id++;
3626         mtx_unlock(&ctl_softc->pool_lock);
3627
3628         pool->flags = CTL_POOL_FLAG_NONE;
3629         pool->refcount = 1;             /* Reference for validity. */
3630         STAILQ_INIT(&pool->free_queue);
3631
3632         /*
3633          * XXX KDM other options here:
3634          * - allocate a page at a time
3635          * - allocate one big chunk of memory.
3636          * Page allocation might work well, but would take a little more
3637          * tracking.
3638          */
3639         for (i = 0; i < total_ctl_io; i++) {
3640                 cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3641                                                 M_NOWAIT);
3642                 if (cur_io == NULL) {
3643                         retval = ENOMEM;
3644                         break;
3645                 }
3646                 cur_io->io_hdr.pool = pool;
3647                 STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3648                 pool->total_ctl_io++;
3649                 pool->free_ctl_io++;
3650         }
3651
3652         if (retval != 0) {
3653                 for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3654                      cur_io != NULL; cur_io = next_io) {
3655                         next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3656                                                               links);
3657                         STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3658                                       ctl_io_hdr, links);
3659                         free(cur_io, M_CTLIO);
3660                 }
3661
3662                 free(pool, M_CTL);
3663                 goto bailout;
3664         }
3665         mtx_lock(&ctl_softc->pool_lock);
3666         ctl_softc->num_pools++;
3667         STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3668         /*
3669          * Increment our usage count if this is an external consumer, so we
3670          * can't get unloaded until the external consumer (most likely a
3671          * FETD) unloads and frees his pool.
3672          *
3673          * XXX KDM will this increment the caller's module use count, or
3674          * mine?
3675          */
3676 #if 0
3677         if ((pool_type != CTL_POOL_EMERGENCY)
3678          && (pool_type != CTL_POOL_INTERNAL)
3679          && (pool_type != CTL_POOL_4OTHERSC))
3680                 MOD_INC_USE_COUNT;
3681 #endif
3682
3683         mtx_unlock(&ctl_softc->pool_lock);
3684
3685         *npool = pool;
3686
3687 bailout:
3688
3689         return (retval);
3690 }
3691
3692 static int
3693 ctl_pool_acquire(struct ctl_io_pool *pool)
3694 {
3695
3696         mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3697
3698         if (pool->flags & CTL_POOL_FLAG_INVALID)
3699                 return (EINVAL);
3700
3701         pool->refcount++;
3702
3703         return (0);
3704 }
3705
3706 static void
3707 ctl_pool_release(struct ctl_io_pool *pool)
3708 {
3709         struct ctl_softc *ctl_softc = pool->ctl_softc;
3710         union ctl_io *io;
3711
3712         mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3713
3714         if (--pool->refcount != 0)
3715                 return;
3716
3717         while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3718                 STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3719                               links);
3720                 free(io, M_CTLIO);
3721         }
3722
3723         STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3724         ctl_softc->num_pools--;
3725
3726         /*
3727          * XXX KDM will this decrement the caller's usage count or mine?
3728          */
3729 #if 0
3730         if ((pool->type != CTL_POOL_EMERGENCY)
3731          && (pool->type != CTL_POOL_INTERNAL)
3732          && (pool->type != CTL_POOL_4OTHERSC))
3733                 MOD_DEC_USE_COUNT;
3734 #endif
3735
3736         free(pool, M_CTL);
3737 }
3738
3739 void
3740 ctl_pool_free(struct ctl_io_pool *pool)
3741 {
3742         struct ctl_softc *ctl_softc;
3743
3744         if (pool == NULL)
3745                 return;
3746
3747         ctl_softc = pool->ctl_softc;
3748         mtx_lock(&ctl_softc->pool_lock);
3749         pool->flags |= CTL_POOL_FLAG_INVALID;
3750         ctl_pool_release(pool);
3751         mtx_unlock(&ctl_softc->pool_lock);
3752 }
3753
3754 /*
3755  * This routine does not block (except for spinlocks of course).
3756  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3757  * possible.
3758  */
3759 union ctl_io *
3760 ctl_alloc_io(void *pool_ref)
3761 {
3762         union ctl_io *io;
3763         struct ctl_softc *ctl_softc;
3764         struct ctl_io_pool *pool, *npool;
3765         struct ctl_io_pool *emergency_pool;
3766
3767         pool = (struct ctl_io_pool *)pool_ref;
3768
3769         if (pool == NULL) {
3770                 printf("%s: pool is NULL\n", __func__);
3771                 return (NULL);
3772         }
3773
3774         emergency_pool = NULL;
3775
3776         ctl_softc = pool->ctl_softc;
3777
3778         mtx_lock(&ctl_softc->pool_lock);
3779         /*
3780          * First, try to get the io structure from the user's pool.
3781          */
3782         if (ctl_pool_acquire(pool) == 0) {
3783                 io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3784                 if (io != NULL) {
3785                         STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3786                         pool->total_allocated++;
3787                         pool->free_ctl_io--;
3788                         mtx_unlock(&ctl_softc->pool_lock);
3789                         return (io);
3790                 } else
3791                         ctl_pool_release(pool);
3792         }
3793         /*
3794          * If he doesn't have any io structures left, search for an
3795          * emergency pool and grab one from there.
3796          */
3797         STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3798                 if (npool->type != CTL_POOL_EMERGENCY)
3799                         continue;
3800
3801                 if (ctl_pool_acquire(npool) != 0)
3802                         continue;
3803
3804                 emergency_pool = npool;
3805
3806                 io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3807                 if (io != NULL) {
3808                         STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3809                         npool->total_allocated++;
3810                         npool->free_ctl_io--;
3811                         mtx_unlock(&ctl_softc->pool_lock);
3812                         return (io);
3813                 } else
3814                         ctl_pool_release(npool);
3815         }
3816
3817         /* Drop the spinlock before we malloc */
3818         mtx_unlock(&ctl_softc->pool_lock);
3819
3820         /*
3821          * The emergency pool (if it exists) didn't have one, so try an
3822          * atomic (i.e. nonblocking) malloc and see if we get lucky.
3823          */
3824         io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3825         if (io != NULL) {
3826                 /*
3827                  * If the emergency pool exists but is empty, add this
3828                  * ctl_io to its list when it gets freed.
3829                  */
3830                 if (emergency_pool != NULL) {
3831                         mtx_lock(&ctl_softc->pool_lock);
3832                         if (ctl_pool_acquire(emergency_pool) == 0) {
3833                                 io->io_hdr.pool = emergency_pool;
3834                                 emergency_pool->total_ctl_io++;
3835                                 /*
3836                                  * Need to bump this, otherwise
3837                                  * total_allocated and total_freed won't
3838                                  * match when we no longer have anything
3839                                  * outstanding.
3840                                  */
3841                                 emergency_pool->total_allocated++;
3842                         }
3843                         mtx_unlock(&ctl_softc->pool_lock);
3844                 } else
3845                         io->io_hdr.pool = NULL;
3846         }
3847
3848         return (io);
3849 }
3850
3851 void
3852 ctl_free_io(union ctl_io *io)
3853 {
3854         if (io == NULL)
3855                 return;
3856
3857         /*
3858          * If this ctl_io has a pool, return it to that pool.
3859          */
3860         if (io->io_hdr.pool != NULL) {
3861                 struct ctl_io_pool *pool;
3862
3863                 pool = (struct ctl_io_pool *)io->io_hdr.pool;
3864                 mtx_lock(&pool->ctl_softc->pool_lock);
3865                 io->io_hdr.io_type = 0xff;
3866                 STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3867                 pool->total_freed++;
3868                 pool->free_ctl_io++;
3869                 ctl_pool_release(pool);
3870                 mtx_unlock(&pool->ctl_softc->pool_lock);
3871         } else {
3872                 /*
3873                  * Otherwise, just free it.  We probably malloced it and
3874                  * the emergency pool wasn't available.
3875                  */
3876                 free(io, M_CTLIO);
3877         }
3878
3879 }
3880
3881 void
3882 ctl_zero_io(union ctl_io *io)
3883 {
3884         void *pool_ref;
3885
3886         if (io == NULL)
3887                 return;
3888
3889         /*
3890          * May need to preserve linked list pointers at some point too.
3891          */
3892         pool_ref = io->io_hdr.pool;
3893
3894         memset(io, 0, sizeof(*io));
3895
3896         io->io_hdr.pool = pool_ref;
3897 }
3898
3899 /*
3900  * This routine is currently used for internal copies of ctl_ios that need
3901  * to persist for some reason after we've already returned status to the
3902  * FETD.  (Thus the flag set.)
3903  *
3904  * XXX XXX
3905  * Note that this makes a blind copy of all fields in the ctl_io, except
3906  * for the pool reference.  This includes any memory that has been
3907  * allocated!  That memory will no longer be valid after done has been
3908  * called, so this would be VERY DANGEROUS for command that actually does
3909  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3910  * start and stop commands, which don't transfer any data, so this is not a
3911  * problem.  If it is used for anything else, the caller would also need to
3912  * allocate data buffer space and this routine would need to be modified to
3913  * copy the data buffer(s) as well.
3914  */
3915 void
3916 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3917 {
3918         void *pool_ref;
3919
3920         if ((src == NULL)
3921          || (dest == NULL))
3922                 return;
3923
3924         /*
3925          * May need to preserve linked list pointers at some point too.
3926          */
3927         pool_ref = dest->io_hdr.pool;
3928
3929         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3930
3931         dest->io_hdr.pool = pool_ref;
3932         /*
3933          * We need to know that this is an internal copy, and doesn't need
3934          * to get passed back to the FETD that allocated it.
3935          */
3936         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3937 }
3938
3939 #ifdef NEEDTOPORT
3940 static void
3941 ctl_update_power_subpage(struct copan_power_subpage *page)
3942 {
3943         int num_luns, num_partitions, config_type;
3944         struct ctl_softc *softc;
3945         cs_BOOL_t aor_present, shelf_50pct_power;
3946         cs_raidset_personality_t rs_type;
3947         int max_active_luns;
3948
3949         softc = control_softc;
3950
3951         /* subtract out the processor LUN */
3952         num_luns = softc->num_luns - 1;
3953         /*
3954          * Default to 7 LUNs active, which was the only number we allowed
3955          * in the past.
3956          */
3957         max_active_luns = 7;
3958
3959         num_partitions = config_GetRsPartitionInfo();
3960         config_type = config_GetConfigType();
3961         shelf_50pct_power = config_GetShelfPowerMode();
3962         aor_present = config_IsAorRsPresent();
3963
3964         rs_type = ddb_GetRsRaidType(1);
3965         if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3966          && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3967                 EPRINT(0, "Unsupported RS type %d!", rs_type);
3968         }
3969
3970
3971         page->total_luns = num_luns;
3972
3973         switch (config_type) {
3974         case 40:
3975                 /*
3976                  * In a 40 drive configuration, it doesn't matter what DC
3977                  * cards we have, whether we have AOR enabled or not,
3978                  * partitioning or not, or what type of RAIDset we have.
3979                  * In that scenario, we can power up every LUN we present
3980                  * to the user.
3981                  */
3982                 max_active_luns = num_luns;
3983
3984                 break;
3985         case 64:
3986                 if (shelf_50pct_power == CS_FALSE) {
3987                         /* 25% power */
3988                         if (aor_present == CS_TRUE) {
3989                                 if (rs_type ==
3990                                      CS_RAIDSET_PERSONALITY_RAID5) {
3991                                         max_active_luns = 7;
3992                                 } else if (rs_type ==
3993                                          CS_RAIDSET_PERSONALITY_RAID1){
3994                                         max_active_luns = 14;
3995                                 } else {
3996                                         /* XXX KDM now what?? */
3997                                 }
3998                         } else {
3999                                 if (rs_type ==
4000                                      CS_RAIDSET_PERSONALITY_RAID5) {
4001                                         max_active_luns = 8;
4002                                 } else if (rs_type ==
4003                                          CS_RAIDSET_PERSONALITY_RAID1){
4004                                         max_active_luns = 16;
4005                                 } else {
4006                                         /* XXX KDM now what?? */
4007                                 }
4008                         }
4009                 } else {
4010                         /* 50% power */
4011                         /*
4012                          * With 50% power in a 64 drive configuration, we
4013                          * can power all LUNs we present.
4014                          */
4015                         max_active_luns = num_luns;
4016                 }
4017                 break;
4018         case 112:
4019                 if (shelf_50pct_power == CS_FALSE) {
4020                         /* 25% power */
4021                         if (aor_present == CS_TRUE) {
4022                                 if (rs_type ==
4023                                      CS_RAIDSET_PERSONALITY_RAID5) {
4024                                         max_active_luns = 7;
4025                                 } else if (rs_type ==
4026                                          CS_RAIDSET_PERSONALITY_RAID1){
4027                                         max_active_luns = 14;
4028                                 } else {
4029                                         /* XXX KDM now what?? */
4030                                 }
4031                         } else {
4032                                 if (rs_type ==
4033                                      CS_RAIDSET_PERSONALITY_RAID5) {
4034                                         max_active_luns = 8;
4035                                 } else if (rs_type ==
4036                                          CS_RAIDSET_PERSONALITY_RAID1){
4037                                         max_active_luns = 16;
4038                                 } else {
4039                                         /* XXX KDM now what?? */
4040                                 }
4041                         }
4042                 } else {
4043                         /* 50% power */
4044                         if (aor_present == CS_TRUE) {
4045                                 if (rs_type ==
4046                                      CS_RAIDSET_PERSONALITY_RAID5) {
4047                                         max_active_luns = 14;
4048                                 } else if (rs_type ==
4049                                          CS_RAIDSET_PERSONALITY_RAID1){
4050                                         /*
4051                                          * We're assuming here that disk
4052                                          * caching is enabled, and so we're
4053                                          * able to power up half of each
4054                                          * LUN, and cache all writes.
4055                                          */
4056                                         max_active_luns = num_luns;
4057                                 } else {
4058                                         /* XXX KDM now what?? */
4059                                 }
4060                         } else {
4061                                 if (rs_type ==
4062                                      CS_RAIDSET_PERSONALITY_RAID5) {
4063                                         max_active_luns = 15;
4064                                 } else if (rs_type ==
4065                                          CS_RAIDSET_PERSONALITY_RAID1){
4066                                         max_active_luns = 30;
4067                                 } else {
4068                                         /* XXX KDM now what?? */
4069                                 }
4070                         }
4071                 }
4072                 break;
4073         default:
4074                 /*
4075                  * In this case, we have an unknown configuration, so we
4076                  * just use the default from above.
4077                  */
4078                 break;
4079         }
4080
4081         page->max_active_luns = max_active_luns;
4082 #if 0
4083         printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4084                page->total_luns, page->max_active_luns);
4085 #endif
4086 }
4087 #endif /* NEEDTOPORT */
4088
4089 /*
4090  * This routine could be used in the future to load default and/or saved
4091  * mode page parameters for a particuar lun.
4092  */
4093 static int
4094 ctl_init_page_index(struct ctl_lun *lun)
4095 {
4096         int i;
4097         struct ctl_page_index *page_index;
4098         struct ctl_softc *softc;
4099         const char *value;
4100
4101         memcpy(&lun->mode_pages.index, page_index_template,
4102                sizeof(page_index_template));
4103
4104         softc = lun->ctl_softc;
4105
4106         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4107
4108                 page_index = &lun->mode_pages.index[i];
4109                 /*
4110                  * If this is a disk-only mode page, there's no point in
4111                  * setting it up.  For some pages, we have to have some
4112                  * basic information about the disk in order to calculate the
4113                  * mode page data.
4114                  */
4115                 if ((lun->be_lun->lun_type != T_DIRECT)
4116                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4117                         continue;
4118
4119                 switch (page_index->page_code & SMPH_PC_MASK) {
4120                 case SMS_FORMAT_DEVICE_PAGE: {
4121                         struct scsi_format_page *format_page;
4122
4123                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4124                                 panic("subpage is incorrect!");
4125
4126                         /*
4127                          * Sectors per track are set above.  Bytes per
4128                          * sector need to be set here on a per-LUN basis.
4129                          */
4130                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4131                                &format_page_default,
4132                                sizeof(format_page_default));
4133                         memcpy(&lun->mode_pages.format_page[
4134                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4135                                sizeof(format_page_changeable));
4136                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4137                                &format_page_default,
4138                                sizeof(format_page_default));
4139                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4140                                &format_page_default,
4141                                sizeof(format_page_default));
4142
4143                         format_page = &lun->mode_pages.format_page[
4144                                 CTL_PAGE_CURRENT];
4145                         scsi_ulto2b(lun->be_lun->blocksize,
4146                                     format_page->bytes_per_sector);
4147
4148                         format_page = &lun->mode_pages.format_page[
4149                                 CTL_PAGE_DEFAULT];
4150                         scsi_ulto2b(lun->be_lun->blocksize,
4151                                     format_page->bytes_per_sector);
4152
4153                         format_page = &lun->mode_pages.format_page[
4154                                 CTL_PAGE_SAVED];
4155                         scsi_ulto2b(lun->be_lun->blocksize,
4156                                     format_page->bytes_per_sector);
4157
4158                         page_index->page_data =
4159                                 (uint8_t *)lun->mode_pages.format_page;
4160                         break;
4161                 }
4162                 case SMS_RIGID_DISK_PAGE: {
4163                         struct scsi_rigid_disk_page *rigid_disk_page;
4164                         uint32_t sectors_per_cylinder;
4165                         uint64_t cylinders;
4166 #ifndef __XSCALE__
4167                         int shift;
4168 #endif /* !__XSCALE__ */
4169
4170                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4171                                 panic("invalid subpage value %d",
4172                                       page_index->subpage);
4173
4174                         /*
4175                          * Rotation rate and sectors per track are set
4176                          * above.  We calculate the cylinders here based on
4177                          * capacity.  Due to the number of heads and
4178                          * sectors per track we're using, smaller arrays
4179                          * may turn out to have 0 cylinders.  Linux and
4180                          * FreeBSD don't pay attention to these mode pages
4181                          * to figure out capacity, but Solaris does.  It
4182                          * seems to deal with 0 cylinders just fine, and
4183                          * works out a fake geometry based on the capacity.
4184                          */
4185                         memcpy(&lun->mode_pages.rigid_disk_page[
4186                                CTL_PAGE_CURRENT], &rigid_disk_page_default,
4187                                sizeof(rigid_disk_page_default));
4188                         memcpy(&lun->mode_pages.rigid_disk_page[
4189                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4190                                sizeof(rigid_disk_page_changeable));
4191                         memcpy(&lun->mode_pages.rigid_disk_page[
4192                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4193                                sizeof(rigid_disk_page_default));
4194                         memcpy(&lun->mode_pages.rigid_disk_page[
4195                                CTL_PAGE_SAVED], &rigid_disk_page_default,
4196                                sizeof(rigid_disk_page_default));
4197
4198                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4199                                 CTL_DEFAULT_HEADS;
4200
4201                         /*
4202                          * The divide method here will be more accurate,
4203                          * probably, but results in floating point being
4204                          * used in the kernel on i386 (__udivdi3()).  On the
4205                          * XScale, though, __udivdi3() is implemented in
4206                          * software.
4207                          *
4208                          * The shift method for cylinder calculation is
4209                          * accurate if sectors_per_cylinder is a power of
4210                          * 2.  Otherwise it might be slightly off -- you
4211                          * might have a bit of a truncation problem.
4212                          */
4213 #ifdef  __XSCALE__
4214                         cylinders = (lun->be_lun->maxlba + 1) /
4215                                 sectors_per_cylinder;
4216 #else
4217                         for (shift = 31; shift > 0; shift--) {
4218                                 if (sectors_per_cylinder & (1 << shift))
4219                                         break;
4220                         }
4221                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4222 #endif
4223
4224                         /*
4225                          * We've basically got 3 bytes, or 24 bits for the
4226                          * cylinder size in the mode page.  If we're over,
4227                          * just round down to 2^24.
4228                          */
4229                         if (cylinders > 0xffffff)
4230                                 cylinders = 0xffffff;
4231
4232                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4233                                 CTL_PAGE_CURRENT];
4234                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4235
4236                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4237                                 CTL_PAGE_DEFAULT];
4238                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4239
4240                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4241                                 CTL_PAGE_SAVED];
4242                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4243
4244                         page_index->page_data =
4245                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4246                         break;
4247                 }
4248                 case SMS_CACHING_PAGE: {
4249                         struct scsi_caching_page *caching_page;
4250
4251                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4252                                 panic("invalid subpage value %d",
4253                                       page_index->subpage);
4254                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4255                                &caching_page_default,
4256                                sizeof(caching_page_default));
4257                         memcpy(&lun->mode_pages.caching_page[
4258                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4259                                sizeof(caching_page_changeable));
4260                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4261                                &caching_page_default,
4262                                sizeof(caching_page_default));
4263                         caching_page = &lun->mode_pages.caching_page[
4264                             CTL_PAGE_SAVED];
4265                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4266                         if (value != NULL && strcmp(value, "off") == 0)
4267                                 caching_page->flags1 &= ~SCP_WCE;
4268                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4269                         if (value != NULL && strcmp(value, "off") == 0)
4270                                 caching_page->flags1 |= SCP_RCD;
4271                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4272                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4273                                sizeof(caching_page_default));
4274                         page_index->page_data =
4275                                 (uint8_t *)lun->mode_pages.caching_page;
4276                         break;
4277                 }
4278                 case SMS_CONTROL_MODE_PAGE: {
4279                         struct scsi_control_page *control_page;
4280
4281                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4282                                 panic("invalid subpage value %d",
4283                                       page_index->subpage);
4284
4285                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4286                                &control_page_default,
4287                                sizeof(control_page_default));
4288                         memcpy(&lun->mode_pages.control_page[
4289                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4290                                sizeof(control_page_changeable));
4291                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4292                                &control_page_default,
4293                                sizeof(control_page_default));
4294                         control_page = &lun->mode_pages.control_page[
4295                             CTL_PAGE_SAVED];
4296                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4297                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4298                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4299                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4300                         }
4301                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4302                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4303                                sizeof(control_page_default));
4304                         page_index->page_data =
4305                                 (uint8_t *)lun->mode_pages.control_page;
4306                         break;
4307
4308                 }
4309                 case SMS_VENDOR_SPECIFIC_PAGE:{
4310                         switch (page_index->subpage) {
4311                         case PWR_SUBPAGE_CODE: {
4312                                 struct copan_power_subpage *current_page,
4313                                                            *saved_page;
4314
4315                                 memcpy(&lun->mode_pages.power_subpage[
4316                                        CTL_PAGE_CURRENT],
4317                                        &power_page_default,
4318                                        sizeof(power_page_default));
4319                                 memcpy(&lun->mode_pages.power_subpage[
4320                                        CTL_PAGE_CHANGEABLE],
4321                                        &power_page_changeable,
4322                                        sizeof(power_page_changeable));
4323                                 memcpy(&lun->mode_pages.power_subpage[
4324                                        CTL_PAGE_DEFAULT],
4325                                        &power_page_default,
4326                                        sizeof(power_page_default));
4327                                 memcpy(&lun->mode_pages.power_subpage[
4328                                        CTL_PAGE_SAVED],
4329                                        &power_page_default,
4330                                        sizeof(power_page_default));
4331                                 page_index->page_data =
4332                                     (uint8_t *)lun->mode_pages.power_subpage;
4333
4334                                 current_page = (struct copan_power_subpage *)
4335                                         (page_index->page_data +
4336                                          (page_index->page_len *
4337                                           CTL_PAGE_CURRENT));
4338                                 saved_page = (struct copan_power_subpage *)
4339                                         (page_index->page_data +
4340                                          (page_index->page_len *
4341                                           CTL_PAGE_SAVED));
4342                                 break;
4343                         }
4344                         case APS_SUBPAGE_CODE: {
4345                                 struct copan_aps_subpage *current_page,
4346                                                          *saved_page;
4347
4348                                 // This gets set multiple times but
4349                                 // it should always be the same. It's
4350                                 // only done during init so who cares.
4351                                 index_to_aps_page = i;
4352
4353                                 memcpy(&lun->mode_pages.aps_subpage[
4354                                        CTL_PAGE_CURRENT],
4355                                        &aps_page_default,
4356                                        sizeof(aps_page_default));
4357                                 memcpy(&lun->mode_pages.aps_subpage[
4358                                        CTL_PAGE_CHANGEABLE],
4359                                        &aps_page_changeable,
4360                                        sizeof(aps_page_changeable));
4361                                 memcpy(&lun->mode_pages.aps_subpage[
4362                                        CTL_PAGE_DEFAULT],
4363                                        &aps_page_default,
4364                                        sizeof(aps_page_default));
4365                                 memcpy(&lun->mode_pages.aps_subpage[
4366                                        CTL_PAGE_SAVED],
4367                                        &aps_page_default,
4368                                        sizeof(aps_page_default));
4369                                 page_index->page_data =
4370                                         (uint8_t *)lun->mode_pages.aps_subpage;
4371
4372                                 current_page = (struct copan_aps_subpage *)
4373                                         (page_index->page_data +
4374                                          (page_index->page_len *
4375                                           CTL_PAGE_CURRENT));
4376                                 saved_page = (struct copan_aps_subpage *)
4377                                         (page_index->page_data +
4378                                          (page_index->page_len *
4379                                           CTL_PAGE_SAVED));
4380                                 break;
4381                         }
4382                         case DBGCNF_SUBPAGE_CODE: {
4383                                 struct copan_debugconf_subpage *current_page,
4384                                                                *saved_page;
4385
4386                                 memcpy(&lun->mode_pages.debugconf_subpage[
4387                                        CTL_PAGE_CURRENT],
4388                                        &debugconf_page_default,
4389                                        sizeof(debugconf_page_default));
4390                                 memcpy(&lun->mode_pages.debugconf_subpage[
4391                                        CTL_PAGE_CHANGEABLE],
4392                                        &debugconf_page_changeable,
4393                                        sizeof(debugconf_page_changeable));
4394                                 memcpy(&lun->mode_pages.debugconf_subpage[
4395                                        CTL_PAGE_DEFAULT],
4396                                        &debugconf_page_default,
4397                                        sizeof(debugconf_page_default));
4398                                 memcpy(&lun->mode_pages.debugconf_subpage[
4399                                        CTL_PAGE_SAVED],
4400                                        &debugconf_page_default,
4401                                        sizeof(debugconf_page_default));
4402                                 page_index->page_data =
4403                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4404
4405                                 current_page = (struct copan_debugconf_subpage *)
4406                                         (page_index->page_data +
4407                                          (page_index->page_len *
4408                                           CTL_PAGE_CURRENT));
4409                                 saved_page = (struct copan_debugconf_subpage *)
4410                                         (page_index->page_data +
4411                                          (page_index->page_len *
4412                                           CTL_PAGE_SAVED));
4413                                 break;
4414                         }
4415                         default:
4416                                 panic("invalid subpage value %d",
4417                                       page_index->subpage);
4418                                 break;
4419                         }
4420                         break;
4421                 }
4422                 default:
4423                         panic("invalid page value %d",
4424                               page_index->page_code & SMPH_PC_MASK);
4425                         break;
4426         }
4427         }
4428
4429         return (CTL_RETVAL_COMPLETE);
4430 }
4431
4432 /*
4433  * LUN allocation.
4434  *
4435  * Requirements:
4436  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4437  *   wants us to allocate the LUN and he can block.
4438  * - ctl_softc is always set
4439  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4440  *
4441  * Returns 0 for success, non-zero (errno) for failure.
4442  */
4443 static int
4444 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4445               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4446 {
4447         struct ctl_lun *nlun, *lun;
4448         struct ctl_port *port;
4449         struct scsi_vpd_id_descriptor *desc;
4450         struct scsi_vpd_id_t10 *t10id;
4451         const char *eui, *naa, *scsiname, *vendor, *value;
4452         int lun_number, i, lun_malloced;
4453         int devidlen, idlen1, idlen2 = 0, len;
4454
4455         if (be_lun == NULL)
4456                 return (EINVAL);
4457
4458         /*
4459          * We currently only support Direct Access or Processor LUN types.
4460          */
4461         switch (be_lun->lun_type) {
4462         case T_DIRECT:
4463                 break;
4464         case T_PROCESSOR:
4465                 break;
4466         case T_SEQUENTIAL:
4467         case T_CHANGER:
4468         default:
4469                 be_lun->lun_config_status(be_lun->be_lun,
4470                                           CTL_LUN_CONFIG_FAILURE);
4471                 break;
4472         }
4473         if (ctl_lun == NULL) {
4474                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4475                 lun_malloced = 1;
4476         } else {
4477                 lun_malloced = 0;
4478                 lun = ctl_lun;
4479         }
4480
4481         memset(lun, 0, sizeof(*lun));
4482         if (lun_malloced)
4483                 lun->flags = CTL_LUN_MALLOCED;
4484
4485         /* Generate LUN ID. */
4486         devidlen = max(CTL_DEVID_MIN_LEN,
4487             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4488         idlen1 = sizeof(*t10id) + devidlen;
4489         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4490         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4491         if (scsiname != NULL) {
4492                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4493                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4494         }
4495         eui = ctl_get_opt(&be_lun->options, "eui");
4496         if (eui != NULL) {
4497                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4498         }
4499         naa = ctl_get_opt(&be_lun->options, "naa");
4500         if (naa != NULL) {
4501                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4502         }
4503         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4504             M_CTL, M_WAITOK | M_ZERO);
4505         lun->lun_devid->len = len;
4506         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4507         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4508         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4509         desc->length = idlen1;
4510         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4511         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4512         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4513                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4514         } else {
4515                 strncpy(t10id->vendor, vendor,
4516                     min(sizeof(t10id->vendor), strlen(vendor)));
4517         }
4518         strncpy((char *)t10id->vendor_spec_id,
4519             (char *)be_lun->device_id, devidlen);
4520         if (scsiname != NULL) {
4521                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4522                     desc->length);
4523                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4524                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4525                     SVPD_ID_TYPE_SCSI_NAME;
4526                 desc->length = idlen2;
4527                 strlcpy(desc->identifier, scsiname, idlen2);
4528         }
4529         if (eui != NULL) {
4530                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4531                     desc->length);
4532                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4533                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4534                     SVPD_ID_TYPE_EUI64;
4535                 desc->length = 8;
4536                 scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4537         }
4538         if (naa != NULL) {
4539                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4540                     desc->length);
4541                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4542                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4543                     SVPD_ID_TYPE_NAA;
4544                 desc->length = 8;
4545                 scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4546         }
4547
4548         mtx_lock(&ctl_softc->ctl_lock);
4549         /*
4550          * See if the caller requested a particular LUN number.  If so, see
4551          * if it is available.  Otherwise, allocate the first available LUN.
4552          */
4553         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4554                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4555                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4556                         mtx_unlock(&ctl_softc->ctl_lock);
4557                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4558                                 printf("ctl: requested LUN ID %d is higher "
4559                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4560                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4561                         } else {
4562                                 /*
4563                                  * XXX KDM return an error, or just assign
4564                                  * another LUN ID in this case??
4565                                  */
4566                                 printf("ctl: requested LUN ID %d is already "
4567                                        "in use\n", be_lun->req_lun_id);
4568                         }
4569                         if (lun->flags & CTL_LUN_MALLOCED)
4570                                 free(lun, M_CTL);
4571                         be_lun->lun_config_status(be_lun->be_lun,
4572                                                   CTL_LUN_CONFIG_FAILURE);
4573                         return (ENOSPC);
4574                 }
4575                 lun_number = be_lun->req_lun_id;
4576         } else {
4577                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4578                 if (lun_number == -1) {
4579                         mtx_unlock(&ctl_softc->ctl_lock);
4580                         printf("ctl: can't allocate LUN on target %ju, out of "
4581                                "LUNs\n", (uintmax_t)target_id.id);
4582                         if (lun->flags & CTL_LUN_MALLOCED)
4583                                 free(lun, M_CTL);
4584                         be_lun->lun_config_status(be_lun->be_lun,
4585                                                   CTL_LUN_CONFIG_FAILURE);
4586                         return (ENOSPC);
4587                 }
4588         }
4589         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4590
4591         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4592         lun->target = target_id;
4593         lun->lun = lun_number;
4594         lun->be_lun = be_lun;
4595         /*
4596          * The processor LUN is always enabled.  Disk LUNs come on line
4597          * disabled, and must be enabled by the backend.
4598          */
4599         lun->flags |= CTL_LUN_DISABLED;
4600         lun->backend = be_lun->be;
4601         be_lun->ctl_lun = lun;
4602         be_lun->lun_id = lun_number;
4603         atomic_add_int(&be_lun->be->num_luns, 1);
4604         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4605                 lun->flags |= CTL_LUN_OFFLINE;
4606
4607         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4608                 lun->flags |= CTL_LUN_STOPPED;
4609
4610         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4611                 lun->flags |= CTL_LUN_INOPERABLE;
4612
4613         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4614                 lun->flags |= CTL_LUN_PRIMARY_SC;
4615
4616         value = ctl_get_opt(&be_lun->options, "readonly");
4617         if (value != NULL && strcmp(value, "on") == 0)
4618                 lun->flags |= CTL_LUN_READONLY;
4619
4620         lun->ctl_softc = ctl_softc;
4621         TAILQ_INIT(&lun->ooa_queue);
4622         TAILQ_INIT(&lun->blocked_queue);
4623         STAILQ_INIT(&lun->error_list);
4624         ctl_tpc_lun_init(lun);
4625
4626         /*
4627          * Initialize the mode page index.
4628          */
4629         ctl_init_page_index(lun);
4630
4631         /*
4632          * Set the poweron UA for all initiators on this LUN only.
4633          */
4634         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4635                 lun->pending_ua[i] = CTL_UA_POWERON;
4636
4637         /*
4638          * Now, before we insert this lun on the lun list, set the lun
4639          * inventory changed UA for all other luns.
4640          */
4641         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4642                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4643                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4644                 }
4645         }
4646
4647         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4648
4649         ctl_softc->ctl_luns[lun_number] = lun;
4650
4651         ctl_softc->num_luns++;
4652
4653         /* Setup statistics gathering */
4654         lun->stats.device_type = be_lun->lun_type;
4655         lun->stats.lun_number = lun_number;
4656         if (lun->stats.device_type == T_DIRECT)
4657                 lun->stats.blocksize = be_lun->blocksize;
4658         else
4659                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4660         for (i = 0;i < CTL_MAX_PORTS;i++)
4661                 lun->stats.ports[i].targ_port = i;
4662
4663         mtx_unlock(&ctl_softc->ctl_lock);
4664
4665         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4666
4667         /*
4668          * Run through each registered FETD and bring it online if it isn't
4669          * already.  Enable the target ID if it hasn't been enabled, and
4670          * enable this particular LUN.
4671          */
4672         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4673                 int retval;
4674
4675                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4676                 if (retval != 0) {
4677                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4678                                "%d for lun_enable on target %ju lun %d\n",
4679                                port->port_name, port->targ_port, retval,
4680                                (uintmax_t)target_id.id, lun_number);
4681                 } else
4682                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4683         }
4684         return (0);
4685 }
4686
4687 /*
4688  * Delete a LUN.
4689  * Assumptions:
4690  * - LUN has already been marked invalid and any pending I/O has been taken
4691  *   care of.
4692  */
4693 static int
4694 ctl_free_lun(struct ctl_lun *lun)
4695 {
4696         struct ctl_softc *softc;
4697 #if 0
4698         struct ctl_port *port;
4699 #endif
4700         struct ctl_lun *nlun;
4701         int i;
4702
4703         softc = lun->ctl_softc;
4704
4705         mtx_assert(&softc->ctl_lock, MA_OWNED);
4706
4707         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4708
4709         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4710
4711         softc->ctl_luns[lun->lun] = NULL;
4712
4713         if (!TAILQ_EMPTY(&lun->ooa_queue))
4714                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4715
4716         softc->num_luns--;
4717
4718         /*
4719          * XXX KDM this scheme only works for a single target/multiple LUN
4720          * setup.  It needs to be revamped for a multiple target scheme.
4721          *
4722          * XXX KDM this results in port->lun_disable() getting called twice,
4723          * once when ctl_disable_lun() is called, and a second time here.
4724          * We really need to re-think the LUN disable semantics.  There
4725          * should probably be several steps/levels to LUN removal:
4726          *  - disable
4727          *  - invalidate
4728          *  - free
4729          *
4730          * Right now we only have a disable method when communicating to
4731          * the front end ports, at least for individual LUNs.
4732          */
4733 #if 0
4734         STAILQ_FOREACH(port, &softc->port_list, links) {
4735                 int retval;
4736
4737                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4738                                          lun->lun);
4739                 if (retval != 0) {
4740                         printf("ctl_free_lun: FETD %s port %d returned error "
4741                                "%d for lun_disable on target %ju lun %jd\n",
4742                                port->port_name, port->targ_port, retval,
4743                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4744                 }
4745
4746                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4747                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4748
4749                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4750                         if (retval != 0) {
4751                                 printf("ctl_free_lun: FETD %s port %d "
4752                                        "returned error %d for targ_disable on "
4753                                        "target %ju\n", port->port_name,
4754                                        port->targ_port, retval,
4755                                        (uintmax_t)lun->target.id);
4756                         } else
4757                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4758
4759                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4760                                 continue;
4761
4762 #if 0
4763                         port->port_offline(port->onoff_arg);
4764                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4765 #endif
4766                 }
4767         }
4768 #endif
4769
4770         /*
4771          * Tell the backend to free resources, if this LUN has a backend.
4772          */
4773         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4774         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4775
4776         ctl_tpc_lun_shutdown(lun);
4777         mtx_destroy(&lun->lun_lock);
4778         free(lun->lun_devid, M_CTL);
4779         if (lun->flags & CTL_LUN_MALLOCED)
4780                 free(lun, M_CTL);
4781
4782         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4783                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4784                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4785                 }
4786         }
4787
4788         return (0);
4789 }
4790
4791 static void
4792 ctl_create_lun(struct ctl_be_lun *be_lun)
4793 {
4794         struct ctl_softc *ctl_softc;
4795
4796         ctl_softc = control_softc;
4797
4798         /*
4799          * ctl_alloc_lun() should handle all potential failure cases.
4800          */
4801         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4802 }
4803
4804 int
4805 ctl_add_lun(struct ctl_be_lun *be_lun)
4806 {
4807         struct ctl_softc *ctl_softc = control_softc;
4808
4809         mtx_lock(&ctl_softc->ctl_lock);
4810         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4811         mtx_unlock(&ctl_softc->ctl_lock);
4812         wakeup(&ctl_softc->pending_lun_queue);
4813
4814         return (0);
4815 }
4816
4817 int
4818 ctl_enable_lun(struct ctl_be_lun *be_lun)
4819 {
4820         struct ctl_softc *ctl_softc;
4821         struct ctl_port *port, *nport;
4822         struct ctl_lun *lun;
4823         int retval;
4824
4825         ctl_softc = control_softc;
4826
4827         lun = (struct ctl_lun *)be_lun->ctl_lun;
4828
4829         mtx_lock(&ctl_softc->ctl_lock);
4830         mtx_lock(&lun->lun_lock);
4831         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4832                 /*
4833                  * eh?  Why did we get called if the LUN is already
4834                  * enabled?
4835                  */
4836                 mtx_unlock(&lun->lun_lock);
4837                 mtx_unlock(&ctl_softc->ctl_lock);
4838                 return (0);
4839         }
4840         lun->flags &= ~CTL_LUN_DISABLED;
4841         mtx_unlock(&lun->lun_lock);
4842
4843         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4844                 nport = STAILQ_NEXT(port, links);
4845
4846                 /*
4847                  * Drop the lock while we call the FETD's enable routine.
4848                  * This can lead to a callback into CTL (at least in the
4849                  * case of the internal initiator frontend.
4850                  */
4851                 mtx_unlock(&ctl_softc->ctl_lock);
4852                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4853                 mtx_lock(&ctl_softc->ctl_lock);
4854                 if (retval != 0) {
4855                         printf("%s: FETD %s port %d returned error "
4856                                "%d for lun_enable on target %ju lun %jd\n",
4857                                __func__, port->port_name, port->targ_port, retval,
4858                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4859                 }
4860 #if 0
4861                  else {
4862             /* NOTE:  TODO:  why does lun enable affect port status? */
4863                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4864                 }
4865 #endif
4866         }
4867
4868         mtx_unlock(&ctl_softc->ctl_lock);
4869
4870         return (0);
4871 }
4872
4873 int
4874 ctl_disable_lun(struct ctl_be_lun *be_lun)
4875 {
4876         struct ctl_softc *ctl_softc;
4877         struct ctl_port *port;
4878         struct ctl_lun *lun;
4879         int retval;
4880
4881         ctl_softc = control_softc;
4882
4883         lun = (struct ctl_lun *)be_lun->ctl_lun;
4884
4885         mtx_lock(&ctl_softc->ctl_lock);
4886         mtx_lock(&lun->lun_lock);
4887         if (lun->flags & CTL_LUN_DISABLED) {
4888                 mtx_unlock(&lun->lun_lock);
4889                 mtx_unlock(&ctl_softc->ctl_lock);
4890                 return (0);
4891         }
4892         lun->flags |= CTL_LUN_DISABLED;
4893         mtx_unlock(&lun->lun_lock);
4894
4895         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4896                 mtx_unlock(&ctl_softc->ctl_lock);
4897                 /*
4898                  * Drop the lock before we call the frontend's disable
4899                  * routine, to avoid lock order reversals.
4900                  *
4901                  * XXX KDM what happens if the frontend list changes while
4902                  * we're traversing it?  It's unlikely, but should be handled.
4903                  */
4904                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4905                                          lun->lun);
4906                 mtx_lock(&ctl_softc->ctl_lock);
4907                 if (retval != 0) {
4908                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4909                                "%d for lun_disable on target %ju lun %jd\n",
4910                                port->port_name, port->targ_port, retval,
4911                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4912                 }
4913         }
4914
4915         mtx_unlock(&ctl_softc->ctl_lock);
4916
4917         return (0);
4918 }
4919
4920 int
4921 ctl_start_lun(struct ctl_be_lun *be_lun)
4922 {
4923         struct ctl_softc *ctl_softc;
4924         struct ctl_lun *lun;
4925
4926         ctl_softc = control_softc;
4927
4928         lun = (struct ctl_lun *)be_lun->ctl_lun;
4929
4930         mtx_lock(&lun->lun_lock);
4931         lun->flags &= ~CTL_LUN_STOPPED;
4932         mtx_unlock(&lun->lun_lock);
4933
4934         return (0);
4935 }
4936
4937 int
4938 ctl_stop_lun(struct ctl_be_lun *be_lun)
4939 {
4940         struct ctl_softc *ctl_softc;
4941         struct ctl_lun *lun;
4942
4943         ctl_softc = control_softc;
4944
4945         lun = (struct ctl_lun *)be_lun->ctl_lun;
4946
4947         mtx_lock(&lun->lun_lock);
4948         lun->flags |= CTL_LUN_STOPPED;
4949         mtx_unlock(&lun->lun_lock);
4950
4951         return (0);
4952 }
4953
4954 int
4955 ctl_lun_offline(struct ctl_be_lun *be_lun)
4956 {
4957         struct ctl_softc *ctl_softc;
4958         struct ctl_lun *lun;
4959
4960         ctl_softc = control_softc;
4961
4962         lun = (struct ctl_lun *)be_lun->ctl_lun;
4963
4964         mtx_lock(&lun->lun_lock);
4965         lun->flags |= CTL_LUN_OFFLINE;
4966         mtx_unlock(&lun->lun_lock);
4967
4968         return (0);
4969 }
4970
4971 int
4972 ctl_lun_online(struct ctl_be_lun *be_lun)
4973 {
4974         struct ctl_softc *ctl_softc;
4975         struct ctl_lun *lun;
4976
4977         ctl_softc = control_softc;
4978
4979         lun = (struct ctl_lun *)be_lun->ctl_lun;
4980
4981         mtx_lock(&lun->lun_lock);
4982         lun->flags &= ~CTL_LUN_OFFLINE;
4983         mtx_unlock(&lun->lun_lock);
4984
4985         return (0);
4986 }
4987
4988 int
4989 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4990 {
4991         struct ctl_softc *ctl_softc;
4992         struct ctl_lun *lun;
4993
4994         ctl_softc = control_softc;
4995
4996         lun = (struct ctl_lun *)be_lun->ctl_lun;
4997
4998         mtx_lock(&lun->lun_lock);
4999
5000         /*
5001          * The LUN needs to be disabled before it can be marked invalid.
5002          */
5003         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5004                 mtx_unlock(&lun->lun_lock);
5005                 return (-1);
5006         }
5007         /*
5008          * Mark the LUN invalid.
5009          */
5010         lun->flags |= CTL_LUN_INVALID;
5011
5012         /*
5013          * If there is nothing in the OOA queue, go ahead and free the LUN.
5014          * If we have something in the OOA queue, we'll free it when the
5015          * last I/O completes.
5016          */
5017         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5018                 mtx_unlock(&lun->lun_lock);
5019                 mtx_lock(&ctl_softc->ctl_lock);
5020                 ctl_free_lun(lun);
5021                 mtx_unlock(&ctl_softc->ctl_lock);
5022         } else
5023                 mtx_unlock(&lun->lun_lock);
5024
5025         return (0);
5026 }
5027
5028 int
5029 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5030 {
5031         struct ctl_softc *ctl_softc;
5032         struct ctl_lun *lun;
5033
5034         ctl_softc = control_softc;
5035         lun = (struct ctl_lun *)be_lun->ctl_lun;
5036
5037         mtx_lock(&lun->lun_lock);
5038         lun->flags |= CTL_LUN_INOPERABLE;
5039         mtx_unlock(&lun->lun_lock);
5040
5041         return (0);
5042 }
5043
5044 int
5045 ctl_lun_operable(struct ctl_be_lun *be_lun)
5046 {
5047         struct ctl_softc *ctl_softc;
5048         struct ctl_lun *lun;
5049
5050         ctl_softc = control_softc;
5051         lun = (struct ctl_lun *)be_lun->ctl_lun;
5052
5053         mtx_lock(&lun->lun_lock);
5054         lun->flags &= ~CTL_LUN_INOPERABLE;
5055         mtx_unlock(&lun->lun_lock);
5056
5057         return (0);
5058 }
5059
5060 int
5061 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5062                    int lock)
5063 {
5064         struct ctl_softc *softc;
5065         struct ctl_lun *lun;
5066         struct copan_aps_subpage *current_sp;
5067         struct ctl_page_index *page_index;
5068         int i;
5069
5070         softc = control_softc;
5071
5072         mtx_lock(&softc->ctl_lock);
5073
5074         lun = (struct ctl_lun *)be_lun->ctl_lun;
5075         mtx_lock(&lun->lun_lock);
5076
5077         page_index = NULL;
5078         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5079                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5080                      APS_PAGE_CODE)
5081                         continue;
5082
5083                 if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5084                         continue;
5085                 page_index = &lun->mode_pages.index[i];
5086         }
5087
5088         if (page_index == NULL) {
5089                 mtx_unlock(&lun->lun_lock);
5090                 mtx_unlock(&softc->ctl_lock);
5091                 printf("%s: APS subpage not found for lun %ju!\n", __func__,
5092                        (uintmax_t)lun->lun);
5093                 return (1);
5094         }
5095 #if 0
5096         if ((softc->aps_locked_lun != 0)
5097          && (softc->aps_locked_lun != lun->lun)) {
5098                 printf("%s: attempt to lock LUN %llu when %llu is already "
5099                        "locked\n");
5100                 mtx_unlock(&lun->lun_lock);
5101                 mtx_unlock(&softc->ctl_lock);
5102                 return (1);
5103         }
5104 #endif
5105
5106         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5107                 (page_index->page_len * CTL_PAGE_CURRENT));
5108
5109         if (lock != 0) {
5110                 current_sp->lock_active = APS_LOCK_ACTIVE;
5111                 softc->aps_locked_lun = lun->lun;
5112         } else {
5113                 current_sp->lock_active = 0;
5114                 softc->aps_locked_lun = 0;
5115         }
5116
5117
5118         /*
5119          * If we're in HA mode, try to send the lock message to the other
5120          * side.
5121          */
5122         if (ctl_is_single == 0) {
5123                 int isc_retval;
5124                 union ctl_ha_msg lock_msg;
5125
5126                 lock_msg.hdr.nexus = *nexus;
5127                 lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5128                 if (lock != 0)
5129                         lock_msg.aps.lock_flag = 1;
5130                 else
5131                         lock_msg.aps.lock_flag = 0;
5132                 isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5133                                          sizeof(lock_msg), 0);
5134                 if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5135                         printf("%s: APS (lock=%d) error returned from "
5136                                "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5137                         mtx_unlock(&lun->lun_lock);
5138                         mtx_unlock(&softc->ctl_lock);
5139                         return (1);
5140                 }
5141         }
5142
5143         mtx_unlock(&lun->lun_lock);
5144         mtx_unlock(&softc->ctl_lock);
5145
5146         return (0);
5147 }
5148
5149 void
5150 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5151 {
5152         struct ctl_lun *lun;
5153         struct ctl_softc *softc;
5154         int i;
5155
5156         softc = control_softc;
5157
5158         lun = (struct ctl_lun *)be_lun->ctl_lun;
5159
5160         mtx_lock(&lun->lun_lock);
5161
5162         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
5163                 lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5164
5165         mtx_unlock(&lun->lun_lock);
5166 }
5167
5168 /*
5169  * Backend "memory move is complete" callback for requests that never
5170  * make it down to say RAIDCore's configuration code.
5171  */
5172 int
5173 ctl_config_move_done(union ctl_io *io)
5174 {
5175         int retval;
5176
5177         retval = CTL_RETVAL_COMPLETE;
5178
5179
5180         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5181         /*
5182          * XXX KDM this shouldn't happen, but what if it does?
5183          */
5184         if (io->io_hdr.io_type != CTL_IO_SCSI)
5185                 panic("I/O type isn't CTL_IO_SCSI!");
5186
5187         if ((io->io_hdr.port_status == 0)
5188          && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5189          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5190                 io->io_hdr.status = CTL_SUCCESS;
5191         else if ((io->io_hdr.port_status != 0)
5192               && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5193               && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5194                 /*
5195                  * For hardware error sense keys, the sense key
5196                  * specific value is defined to be a retry count,
5197                  * but we use it to pass back an internal FETD
5198                  * error code.  XXX KDM  Hopefully the FETD is only
5199                  * using 16 bits for an error code, since that's
5200                  * all the space we have in the sks field.
5201                  */
5202                 ctl_set_internal_failure(&io->scsiio,
5203                                          /*sks_valid*/ 1,
5204                                          /*retry_count*/
5205                                          io->io_hdr.port_status);
5206                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5207                         free(io->scsiio.kern_data_ptr, M_CTL);
5208                 ctl_done(io);
5209                 goto bailout;
5210         }
5211
5212         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5213          || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5214          || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5215                 /*
5216                  * XXX KDM just assuming a single pointer here, and not a
5217                  * S/G list.  If we start using S/G lists for config data,
5218                  * we'll need to know how to clean them up here as well.
5219                  */
5220                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5221                         free(io->scsiio.kern_data_ptr, M_CTL);
5222                 /* Hopefully the user has already set the status... */
5223                 ctl_done(io);
5224         } else {
5225                 /*
5226                  * XXX KDM now we need to continue data movement.  Some
5227                  * options:
5228                  * - call ctl_scsiio() again?  We don't do this for data
5229                  *   writes, because for those at least we know ahead of
5230                  *   time where the write will go and how long it is.  For
5231                  *   config writes, though, that information is largely
5232                  *   contained within the write itself, thus we need to
5233                  *   parse out the data again.
5234                  *
5235                  * - Call some other function once the data is in?
5236                  */
5237
5238                 /*
5239                  * XXX KDM call ctl_scsiio() again for now, and check flag
5240                  * bits to see whether we're allocated or not.
5241                  */
5242                 retval = ctl_scsiio(&io->scsiio);
5243         }
5244 bailout:
5245         return (retval);
5246 }
5247
5248 /*
5249  * This gets called by a backend driver when it is done with a
5250  * data_submit method.
5251  */
5252 void
5253 ctl_data_submit_done(union ctl_io *io)
5254 {
5255         /*
5256          * If the IO_CONT flag is set, we need to call the supplied
5257          * function to continue processing the I/O, instead of completing
5258          * the I/O just yet.
5259          *
5260          * If there is an error, though, we don't want to keep processing.
5261          * Instead, just send status back to the initiator.
5262          */
5263         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5264             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5265             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5266              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5267                 io->scsiio.io_cont(io);
5268                 return;
5269         }
5270         ctl_done(io);
5271 }
5272
5273 /*
5274  * This gets called by a backend driver when it is done with a
5275  * configuration write.
5276  */
5277 void
5278 ctl_config_write_done(union ctl_io *io)
5279 {
5280         uint8_t *buf;
5281
5282         /*
5283          * If the IO_CONT flag is set, we need to call the supplied
5284          * function to continue processing the I/O, instead of completing
5285          * the I/O just yet.
5286          *
5287          * If there is an error, though, we don't want to keep processing.
5288          * Instead, just send status back to the initiator.
5289          */
5290         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5291             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5292             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5293              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5294                 io->scsiio.io_cont(io);
5295                 return;
5296         }
5297         /*
5298          * Since a configuration write can be done for commands that actually
5299          * have data allocated, like write buffer, and commands that have
5300          * no data, like start/stop unit, we need to check here.
5301          */
5302         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5303                 buf = io->scsiio.kern_data_ptr;
5304         else
5305                 buf = NULL;
5306         ctl_done(io);
5307         if (buf)
5308                 free(buf, M_CTL);
5309 }
5310
5311 /*
5312  * SCSI release command.
5313  */
5314 int
5315 ctl_scsi_release(struct ctl_scsiio *ctsio)
5316 {
5317         int length, longid, thirdparty_id, resv_id;
5318         struct ctl_softc *ctl_softc;
5319         struct ctl_lun *lun;
5320         uint32_t residx;
5321
5322         length = 0;
5323         resv_id = 0;
5324
5325         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5326
5327         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5328         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5329         ctl_softc = control_softc;
5330
5331         switch (ctsio->cdb[0]) {
5332         case RELEASE_10: {
5333                 struct scsi_release_10 *cdb;
5334
5335                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5336
5337                 if (cdb->byte2 & SR10_LONGID)
5338                         longid = 1;
5339                 else
5340                         thirdparty_id = cdb->thirdparty_id;
5341
5342                 resv_id = cdb->resv_id;
5343                 length = scsi_2btoul(cdb->length);
5344                 break;
5345         }
5346         }
5347
5348
5349         /*
5350          * XXX KDM right now, we only support LUN reservation.  We don't
5351          * support 3rd party reservations, or extent reservations, which
5352          * might actually need the parameter list.  If we've gotten this
5353          * far, we've got a LUN reservation.  Anything else got kicked out
5354          * above.  So, according to SPC, ignore the length.
5355          */
5356         length = 0;
5357
5358         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5359          && (length > 0)) {
5360                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5361                 ctsio->kern_data_len = length;
5362                 ctsio->kern_total_len = length;
5363                 ctsio->kern_data_resid = 0;
5364                 ctsio->kern_rel_offset = 0;
5365                 ctsio->kern_sg_entries = 0;
5366                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5367                 ctsio->be_move_done = ctl_config_move_done;
5368                 ctl_datamove((union ctl_io *)ctsio);
5369
5370                 return (CTL_RETVAL_COMPLETE);
5371         }
5372
5373         if (length > 0)
5374                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5375
5376         mtx_lock(&lun->lun_lock);
5377
5378         /*
5379          * According to SPC, it is not an error for an intiator to attempt
5380          * to release a reservation on a LUN that isn't reserved, or that
5381          * is reserved by another initiator.  The reservation can only be
5382          * released, though, by the initiator who made it or by one of
5383          * several reset type events.
5384          */
5385         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5386                         lun->flags &= ~CTL_LUN_RESERVED;
5387
5388         mtx_unlock(&lun->lun_lock);
5389
5390         ctsio->scsi_status = SCSI_STATUS_OK;
5391         ctsio->io_hdr.status = CTL_SUCCESS;
5392
5393         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5394                 free(ctsio->kern_data_ptr, M_CTL);
5395                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5396         }
5397
5398         ctl_done((union ctl_io *)ctsio);
5399         return (CTL_RETVAL_COMPLETE);
5400 }
5401
5402 int
5403 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5404 {
5405         int extent, thirdparty, longid;
5406         int resv_id, length;
5407         uint64_t thirdparty_id;
5408         struct ctl_softc *ctl_softc;
5409         struct ctl_lun *lun;
5410         uint32_t residx;
5411
5412         extent = 0;
5413         thirdparty = 0;
5414         longid = 0;
5415         resv_id = 0;
5416         length = 0;
5417         thirdparty_id = 0;
5418
5419         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5420
5421         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5422         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5423         ctl_softc = control_softc;
5424
5425         switch (ctsio->cdb[0]) {
5426         case RESERVE_10: {
5427                 struct scsi_reserve_10 *cdb;
5428
5429                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5430
5431                 if (cdb->byte2 & SR10_LONGID)
5432                         longid = 1;
5433                 else
5434                         thirdparty_id = cdb->thirdparty_id;
5435
5436                 resv_id = cdb->resv_id;
5437                 length = scsi_2btoul(cdb->length);
5438                 break;
5439         }
5440         }
5441
5442         /*
5443          * XXX KDM right now, we only support LUN reservation.  We don't
5444          * support 3rd party reservations, or extent reservations, which
5445          * might actually need the parameter list.  If we've gotten this
5446          * far, we've got a LUN reservation.  Anything else got kicked out
5447          * above.  So, according to SPC, ignore the length.
5448          */
5449         length = 0;
5450
5451         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5452          && (length > 0)) {
5453                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5454                 ctsio->kern_data_len = length;
5455                 ctsio->kern_total_len = length;
5456                 ctsio->kern_data_resid = 0;
5457                 ctsio->kern_rel_offset = 0;
5458                 ctsio->kern_sg_entries = 0;
5459                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5460                 ctsio->be_move_done = ctl_config_move_done;
5461                 ctl_datamove((union ctl_io *)ctsio);
5462
5463                 return (CTL_RETVAL_COMPLETE);
5464         }
5465
5466         if (length > 0)
5467                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5468
5469         mtx_lock(&lun->lun_lock);
5470         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5471                 ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5472                 ctsio->io_hdr.status = CTL_SCSI_ERROR;
5473                 goto bailout;
5474         }
5475
5476         lun->flags |= CTL_LUN_RESERVED;
5477         lun->res_idx = residx;
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->pr_keys[residx] == 0
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->pr_keys[residx] == 0)) {
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 and ANCHOR flags can be used only together with UNMAP */
5999         if ((byte2 & SWS_UNMAP) == 0 &&
6000             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
6001                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
6002                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
6003                 ctl_done((union ctl_io *)ctsio);
6004                 return (CTL_RETVAL_COMPLETE);
6005         }
6006
6007         /*
6008          * The first check is to make sure we're in bounds, the second
6009          * check is to catch wrap-around problems.  If the lba + num blocks
6010          * is less than the lba, then we've wrapped around and the block
6011          * range is invalid anyway.
6012          */
6013         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6014          || ((lba + num_blocks) < lba)) {
6015                 ctl_set_lba_out_of_range(ctsio);
6016                 ctl_done((union ctl_io *)ctsio);
6017                 return (CTL_RETVAL_COMPLETE);
6018         }
6019
6020         /* Zero number of blocks means "to the last logical block" */
6021         if (num_blocks == 0) {
6022                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6023                         ctl_set_invalid_field(ctsio,
6024                                               /*sks_valid*/ 0,
6025                                               /*command*/ 1,
6026                                               /*field*/ 0,
6027                                               /*bit_valid*/ 0,
6028                                               /*bit*/ 0);
6029                         ctl_done((union ctl_io *)ctsio);
6030                         return (CTL_RETVAL_COMPLETE);
6031                 }
6032                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
6033         }
6034
6035         len = lun->be_lun->blocksize;
6036
6037         /*
6038          * If we've got a kernel request that hasn't been malloced yet,
6039          * malloc it and tell the caller the data buffer is here.
6040          */
6041         if ((byte2 & SWS_NDOB) == 0 &&
6042             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6043                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6044                 ctsio->kern_data_len = len;
6045                 ctsio->kern_total_len = len;
6046                 ctsio->kern_data_resid = 0;
6047                 ctsio->kern_rel_offset = 0;
6048                 ctsio->kern_sg_entries = 0;
6049                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6050                 ctsio->be_move_done = ctl_config_move_done;
6051                 ctl_datamove((union ctl_io *)ctsio);
6052
6053                 return (CTL_RETVAL_COMPLETE);
6054         }
6055
6056         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6057         lbalen->lba = lba;
6058         lbalen->len = num_blocks;
6059         lbalen->flags = byte2;
6060         retval = lun->backend->config_write((union ctl_io *)ctsio);
6061
6062         return (retval);
6063 }
6064
6065 int
6066 ctl_unmap(struct ctl_scsiio *ctsio)
6067 {
6068         struct ctl_lun *lun;
6069         struct scsi_unmap *cdb;
6070         struct ctl_ptr_len_flags *ptrlen;
6071         struct scsi_unmap_header *hdr;
6072         struct scsi_unmap_desc *buf, *end, *endnz, *range;
6073         uint64_t lba;
6074         uint32_t num_blocks;
6075         int len, retval;
6076         uint8_t byte2;
6077
6078         retval = CTL_RETVAL_COMPLETE;
6079
6080         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6081
6082         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6083         cdb = (struct scsi_unmap *)ctsio->cdb;
6084
6085         len = scsi_2btoul(cdb->length);
6086         byte2 = cdb->byte2;
6087
6088         /*
6089          * If we've got a kernel request that hasn't been malloced yet,
6090          * malloc it and tell the caller the data buffer is here.
6091          */
6092         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6093                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6094                 ctsio->kern_data_len = len;
6095                 ctsio->kern_total_len = len;
6096                 ctsio->kern_data_resid = 0;
6097                 ctsio->kern_rel_offset = 0;
6098                 ctsio->kern_sg_entries = 0;
6099                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6100                 ctsio->be_move_done = ctl_config_move_done;
6101                 ctl_datamove((union ctl_io *)ctsio);
6102
6103                 return (CTL_RETVAL_COMPLETE);
6104         }
6105
6106         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6107         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6108         if (len < sizeof (*hdr) ||
6109             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6110             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6111             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6112                 ctl_set_invalid_field(ctsio,
6113                                       /*sks_valid*/ 0,
6114                                       /*command*/ 0,
6115                                       /*field*/ 0,
6116                                       /*bit_valid*/ 0,
6117                                       /*bit*/ 0);
6118                 ctl_done((union ctl_io *)ctsio);
6119                 return (CTL_RETVAL_COMPLETE);
6120         }
6121         len = scsi_2btoul(hdr->desc_length);
6122         buf = (struct scsi_unmap_desc *)(hdr + 1);
6123         end = buf + len / sizeof(*buf);
6124
6125         endnz = buf;
6126         for (range = buf; range < end; range++) {
6127                 lba = scsi_8btou64(range->lba);
6128                 num_blocks = scsi_4btoul(range->length);
6129                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6130                  || ((lba + num_blocks) < lba)) {
6131                         ctl_set_lba_out_of_range(ctsio);
6132                         ctl_done((union ctl_io *)ctsio);
6133                         return (CTL_RETVAL_COMPLETE);
6134                 }
6135                 if (num_blocks != 0)
6136                         endnz = range + 1;
6137         }
6138
6139         /*
6140          * Block backend can not handle zero last range.
6141          * Filter it out and return if there is nothing left.
6142          */
6143         len = (uint8_t *)endnz - (uint8_t *)buf;
6144         if (len == 0) {
6145                 ctl_set_success(ctsio);
6146                 ctl_done((union ctl_io *)ctsio);
6147                 return (CTL_RETVAL_COMPLETE);
6148         }
6149
6150         mtx_lock(&lun->lun_lock);
6151         ptrlen = (struct ctl_ptr_len_flags *)
6152             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6153         ptrlen->ptr = (void *)buf;
6154         ptrlen->len = len;
6155         ptrlen->flags = byte2;
6156         ctl_check_blocked(lun);
6157         mtx_unlock(&lun->lun_lock);
6158
6159         retval = lun->backend->config_write((union ctl_io *)ctsio);
6160         return (retval);
6161 }
6162
6163 /*
6164  * Note that this function currently doesn't actually do anything inside
6165  * CTL to enforce things if the DQue bit is turned on.
6166  *
6167  * Also note that this function can't be used in the default case, because
6168  * the DQue bit isn't set in the changeable mask for the control mode page
6169  * anyway.  This is just here as an example for how to implement a page
6170  * handler, and a placeholder in case we want to allow the user to turn
6171  * tagged queueing on and off.
6172  *
6173  * The D_SENSE bit handling is functional, however, and will turn
6174  * descriptor sense on and off for a given LUN.
6175  */
6176 int
6177 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6178                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6179 {
6180         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6181         struct ctl_lun *lun;
6182         struct ctl_softc *softc;
6183         int set_ua;
6184         uint32_t initidx;
6185
6186         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6187         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6188         set_ua = 0;
6189
6190         user_cp = (struct scsi_control_page *)page_ptr;
6191         current_cp = (struct scsi_control_page *)
6192                 (page_index->page_data + (page_index->page_len *
6193                 CTL_PAGE_CURRENT));
6194         saved_cp = (struct scsi_control_page *)
6195                 (page_index->page_data + (page_index->page_len *
6196                 CTL_PAGE_SAVED));
6197
6198         softc = control_softc;
6199
6200         mtx_lock(&lun->lun_lock);
6201         if (((current_cp->rlec & SCP_DSENSE) == 0)
6202          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6203                 /*
6204                  * Descriptor sense is currently turned off and the user
6205                  * wants to turn it on.
6206                  */
6207                 current_cp->rlec |= SCP_DSENSE;
6208                 saved_cp->rlec |= SCP_DSENSE;
6209                 lun->flags |= CTL_LUN_SENSE_DESC;
6210                 set_ua = 1;
6211         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6212                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6213                 /*
6214                  * Descriptor sense is currently turned on, and the user
6215                  * wants to turn it off.
6216                  */
6217                 current_cp->rlec &= ~SCP_DSENSE;
6218                 saved_cp->rlec &= ~SCP_DSENSE;
6219                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6220                 set_ua = 1;
6221         }
6222         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6223             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6224                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6225                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6226                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6227                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6228                 set_ua = 1;
6229         }
6230         if ((current_cp->eca_and_aen & SCP_SWP) !=
6231             (user_cp->eca_and_aen & SCP_SWP)) {
6232                 current_cp->eca_and_aen &= ~SCP_SWP;
6233                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6234                 saved_cp->eca_and_aen &= ~SCP_SWP;
6235                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6236                 set_ua = 1;
6237         }
6238         if (set_ua != 0) {
6239                 int i;
6240                 /*
6241                  * Let other initiators know that the mode
6242                  * parameters for this LUN have changed.
6243                  */
6244                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6245                         if (i == initidx)
6246                                 continue;
6247
6248                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6249                 }
6250         }
6251         mtx_unlock(&lun->lun_lock);
6252
6253         return (0);
6254 }
6255
6256 int
6257 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6258                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6259 {
6260         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6261         struct ctl_lun *lun;
6262         int set_ua;
6263         uint32_t initidx;
6264
6265         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6266         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6267         set_ua = 0;
6268
6269         user_cp = (struct scsi_caching_page *)page_ptr;
6270         current_cp = (struct scsi_caching_page *)
6271                 (page_index->page_data + (page_index->page_len *
6272                 CTL_PAGE_CURRENT));
6273         saved_cp = (struct scsi_caching_page *)
6274                 (page_index->page_data + (page_index->page_len *
6275                 CTL_PAGE_SAVED));
6276
6277         mtx_lock(&lun->lun_lock);
6278         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6279             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6280                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6281                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6282                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6283                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6284                 set_ua = 1;
6285         }
6286         if (set_ua != 0) {
6287                 int i;
6288                 /*
6289                  * Let other initiators know that the mode
6290                  * parameters for this LUN have changed.
6291                  */
6292                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6293                         if (i == initidx)
6294                                 continue;
6295
6296                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6297                 }
6298         }
6299         mtx_unlock(&lun->lun_lock);
6300
6301         return (0);
6302 }
6303
6304 int
6305 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6306                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6307 {
6308         return (0);
6309 }
6310
6311 int
6312 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6313                            struct ctl_page_index *page_index, int pc)
6314 {
6315         struct copan_power_subpage *page;
6316
6317         page = (struct copan_power_subpage *)page_index->page_data +
6318                 (page_index->page_len * pc);
6319
6320         switch (pc) {
6321         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6322                 /*
6323                  * We don't update the changable bits for this page.
6324                  */
6325                 break;
6326         case SMS_PAGE_CTRL_CURRENT >> 6:
6327         case SMS_PAGE_CTRL_DEFAULT >> 6:
6328         case SMS_PAGE_CTRL_SAVED >> 6:
6329 #ifdef NEEDTOPORT
6330                 ctl_update_power_subpage(page);
6331 #endif
6332                 break;
6333         default:
6334 #ifdef NEEDTOPORT
6335                 EPRINT(0, "Invalid PC %d!!", pc);
6336 #endif
6337                 break;
6338         }
6339         return (0);
6340 }
6341
6342
6343 int
6344 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6345                    struct ctl_page_index *page_index, uint8_t *page_ptr)
6346 {
6347         struct copan_aps_subpage *user_sp;
6348         struct copan_aps_subpage *current_sp;
6349         union ctl_modepage_info *modepage_info;
6350         struct ctl_softc *softc;
6351         struct ctl_lun *lun;
6352         int retval;
6353
6354         retval = CTL_RETVAL_COMPLETE;
6355         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6356                      (page_index->page_len * CTL_PAGE_CURRENT));
6357         softc = control_softc;
6358         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6359
6360         user_sp = (struct copan_aps_subpage *)page_ptr;
6361
6362         modepage_info = (union ctl_modepage_info *)
6363                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6364
6365         modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6366         modepage_info->header.subpage = page_index->subpage;
6367         modepage_info->aps.lock_active = user_sp->lock_active;
6368
6369         mtx_lock(&softc->ctl_lock);
6370
6371         /*
6372          * If there is a request to lock the LUN and another LUN is locked
6373          * this is an error. If the requested LUN is already locked ignore
6374          * the request. If no LUN is locked attempt to lock it.
6375          * if there is a request to unlock the LUN and the LUN is currently
6376          * locked attempt to unlock it. Otherwise ignore the request. i.e.
6377          * if another LUN is locked or no LUN is locked.
6378          */
6379         if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6380                 if (softc->aps_locked_lun == lun->lun) {
6381                         /*
6382                          * This LUN is already locked, so we're done.
6383                          */
6384                         retval = CTL_RETVAL_COMPLETE;
6385                 } else if (softc->aps_locked_lun == 0) {
6386                         /*
6387                          * No one has the lock, pass the request to the
6388                          * backend.
6389                          */
6390                         retval = lun->backend->config_write(
6391                                 (union ctl_io *)ctsio);
6392                 } else {
6393                         /*
6394                          * Someone else has the lock, throw out the request.
6395                          */
6396                         ctl_set_already_locked(ctsio);
6397                         free(ctsio->kern_data_ptr, M_CTL);
6398                         ctl_done((union ctl_io *)ctsio);
6399
6400                         /*
6401                          * Set the return value so that ctl_do_mode_select()
6402                          * won't try to complete the command.  We already
6403                          * completed it here.
6404                          */
6405                         retval = CTL_RETVAL_ERROR;
6406                 }
6407         } else if (softc->aps_locked_lun == lun->lun) {
6408                 /*
6409                  * This LUN is locked, so pass the unlock request to the
6410                  * backend.
6411                  */
6412                 retval = lun->backend->config_write((union ctl_io *)ctsio);
6413         }
6414         mtx_unlock(&softc->ctl_lock);
6415
6416         return (retval);
6417 }
6418
6419 int
6420 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6421                                 struct ctl_page_index *page_index,
6422                                 uint8_t *page_ptr)
6423 {
6424         uint8_t *c;
6425         int i;
6426
6427         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6428         ctl_time_io_secs =
6429                 (c[0] << 8) |
6430                 (c[1] << 0) |
6431                 0;
6432         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6433         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6434         printf("page data:");
6435         for (i=0; i<8; i++)
6436                 printf(" %.2x",page_ptr[i]);
6437         printf("\n");
6438         return (0);
6439 }
6440
6441 int
6442 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6443                                struct ctl_page_index *page_index,
6444                                int pc)
6445 {
6446         struct copan_debugconf_subpage *page;
6447
6448         page = (struct copan_debugconf_subpage *)page_index->page_data +
6449                 (page_index->page_len * pc);
6450
6451         switch (pc) {
6452         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6453         case SMS_PAGE_CTRL_DEFAULT >> 6:
6454         case SMS_PAGE_CTRL_SAVED >> 6:
6455                 /*
6456                  * We don't update the changable or default bits for this page.
6457                  */
6458                 break;
6459         case SMS_PAGE_CTRL_CURRENT >> 6:
6460                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6461                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6462                 break;
6463         default:
6464 #ifdef NEEDTOPORT
6465                 EPRINT(0, "Invalid PC %d!!", pc);
6466 #endif /* NEEDTOPORT */
6467                 break;
6468         }
6469         return (0);
6470 }
6471
6472
6473 static int
6474 ctl_do_mode_select(union ctl_io *io)
6475 {
6476         struct scsi_mode_page_header *page_header;
6477         struct ctl_page_index *page_index;
6478         struct ctl_scsiio *ctsio;
6479         int control_dev, page_len;
6480         int page_len_offset, page_len_size;
6481         union ctl_modepage_info *modepage_info;
6482         struct ctl_lun *lun;
6483         int *len_left, *len_used;
6484         int retval, i;
6485
6486         ctsio = &io->scsiio;
6487         page_index = NULL;
6488         page_len = 0;
6489         retval = CTL_RETVAL_COMPLETE;
6490
6491         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6492
6493         if (lun->be_lun->lun_type != T_DIRECT)
6494                 control_dev = 1;
6495         else
6496                 control_dev = 0;
6497
6498         modepage_info = (union ctl_modepage_info *)
6499                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6500         len_left = &modepage_info->header.len_left;
6501         len_used = &modepage_info->header.len_used;
6502
6503 do_next_page:
6504
6505         page_header = (struct scsi_mode_page_header *)
6506                 (ctsio->kern_data_ptr + *len_used);
6507
6508         if (*len_left == 0) {
6509                 free(ctsio->kern_data_ptr, M_CTL);
6510                 ctl_set_success(ctsio);
6511                 ctl_done((union ctl_io *)ctsio);
6512                 return (CTL_RETVAL_COMPLETE);
6513         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6514
6515                 free(ctsio->kern_data_ptr, M_CTL);
6516                 ctl_set_param_len_error(ctsio);
6517                 ctl_done((union ctl_io *)ctsio);
6518                 return (CTL_RETVAL_COMPLETE);
6519
6520         } else if ((page_header->page_code & SMPH_SPF)
6521                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6522
6523                 free(ctsio->kern_data_ptr, M_CTL);
6524                 ctl_set_param_len_error(ctsio);
6525                 ctl_done((union ctl_io *)ctsio);
6526                 return (CTL_RETVAL_COMPLETE);
6527         }
6528
6529
6530         /*
6531          * XXX KDM should we do something with the block descriptor?
6532          */
6533         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6534
6535                 if ((control_dev != 0)
6536                  && (lun->mode_pages.index[i].page_flags &
6537                      CTL_PAGE_FLAG_DISK_ONLY))
6538                         continue;
6539
6540                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6541                     (page_header->page_code & SMPH_PC_MASK))
6542                         continue;
6543
6544                 /*
6545                  * If neither page has a subpage code, then we've got a
6546                  * match.
6547                  */
6548                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6549                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6550                         page_index = &lun->mode_pages.index[i];
6551                         page_len = page_header->page_length;
6552                         break;
6553                 }
6554
6555                 /*
6556                  * If both pages have subpages, then the subpage numbers
6557                  * have to match.
6558                  */
6559                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6560                   && (page_header->page_code & SMPH_SPF)) {
6561                         struct scsi_mode_page_header_sp *sph;
6562
6563                         sph = (struct scsi_mode_page_header_sp *)page_header;
6564
6565                         if (lun->mode_pages.index[i].subpage ==
6566                             sph->subpage) {
6567                                 page_index = &lun->mode_pages.index[i];
6568                                 page_len = scsi_2btoul(sph->page_length);
6569                                 break;
6570                         }
6571                 }
6572         }
6573
6574         /*
6575          * If we couldn't find the page, or if we don't have a mode select
6576          * handler for it, send back an error to the user.
6577          */
6578         if ((page_index == NULL)
6579          || (page_index->select_handler == NULL)) {
6580                 ctl_set_invalid_field(ctsio,
6581                                       /*sks_valid*/ 1,
6582                                       /*command*/ 0,
6583                                       /*field*/ *len_used,
6584                                       /*bit_valid*/ 0,
6585                                       /*bit*/ 0);
6586                 free(ctsio->kern_data_ptr, M_CTL);
6587                 ctl_done((union ctl_io *)ctsio);
6588                 return (CTL_RETVAL_COMPLETE);
6589         }
6590
6591         if (page_index->page_code & SMPH_SPF) {
6592                 page_len_offset = 2;
6593                 page_len_size = 2;
6594         } else {
6595                 page_len_size = 1;
6596                 page_len_offset = 1;
6597         }
6598
6599         /*
6600          * If the length the initiator gives us isn't the one we specify in
6601          * the mode page header, or if they didn't specify enough data in
6602          * the CDB to avoid truncating this page, kick out the request.
6603          */
6604         if ((page_len != (page_index->page_len - page_len_offset -
6605                           page_len_size))
6606          || (*len_left < page_index->page_len)) {
6607
6608
6609                 ctl_set_invalid_field(ctsio,
6610                                       /*sks_valid*/ 1,
6611                                       /*command*/ 0,
6612                                       /*field*/ *len_used + page_len_offset,
6613                                       /*bit_valid*/ 0,
6614                                       /*bit*/ 0);
6615                 free(ctsio->kern_data_ptr, M_CTL);
6616                 ctl_done((union ctl_io *)ctsio);
6617                 return (CTL_RETVAL_COMPLETE);
6618         }
6619
6620         /*
6621          * Run through the mode page, checking to make sure that the bits
6622          * the user changed are actually legal for him to change.
6623          */
6624         for (i = 0; i < page_index->page_len; i++) {
6625                 uint8_t *user_byte, *change_mask, *current_byte;
6626                 int bad_bit;
6627                 int j;
6628
6629                 user_byte = (uint8_t *)page_header + i;
6630                 change_mask = page_index->page_data +
6631                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6632                 current_byte = page_index->page_data +
6633                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6634
6635                 /*
6636                  * Check to see whether the user set any bits in this byte
6637                  * that he is not allowed to set.
6638                  */
6639                 if ((*user_byte & ~(*change_mask)) ==
6640                     (*current_byte & ~(*change_mask)))
6641                         continue;
6642
6643                 /*
6644                  * Go through bit by bit to determine which one is illegal.
6645                  */
6646                 bad_bit = 0;
6647                 for (j = 7; j >= 0; j--) {
6648                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6649                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6650                                 bad_bit = i;
6651                                 break;
6652                         }
6653                 }
6654                 ctl_set_invalid_field(ctsio,
6655                                       /*sks_valid*/ 1,
6656                                       /*command*/ 0,
6657                                       /*field*/ *len_used + i,
6658                                       /*bit_valid*/ 1,
6659                                       /*bit*/ bad_bit);
6660                 free(ctsio->kern_data_ptr, M_CTL);
6661                 ctl_done((union ctl_io *)ctsio);
6662                 return (CTL_RETVAL_COMPLETE);
6663         }
6664
6665         /*
6666          * Decrement these before we call the page handler, since we may
6667          * end up getting called back one way or another before the handler
6668          * returns to this context.
6669          */
6670         *len_left -= page_index->page_len;
6671         *len_used += page_index->page_len;
6672
6673         retval = page_index->select_handler(ctsio, page_index,
6674                                             (uint8_t *)page_header);
6675
6676         /*
6677          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6678          * wait until this queued command completes to finish processing
6679          * the mode page.  If it returns anything other than
6680          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6681          * already set the sense information, freed the data pointer, and
6682          * completed the io for us.
6683          */
6684         if (retval != CTL_RETVAL_COMPLETE)
6685                 goto bailout_no_done;
6686
6687         /*
6688          * If the initiator sent us more than one page, parse the next one.
6689          */
6690         if (*len_left > 0)
6691                 goto do_next_page;
6692
6693         ctl_set_success(ctsio);
6694         free(ctsio->kern_data_ptr, M_CTL);
6695         ctl_done((union ctl_io *)ctsio);
6696
6697 bailout_no_done:
6698
6699         return (CTL_RETVAL_COMPLETE);
6700
6701 }
6702
6703 int
6704 ctl_mode_select(struct ctl_scsiio *ctsio)
6705 {
6706         int param_len, pf, sp;
6707         int header_size, bd_len;
6708         int len_left, len_used;
6709         struct ctl_page_index *page_index;
6710         struct ctl_lun *lun;
6711         int control_dev, page_len;
6712         union ctl_modepage_info *modepage_info;
6713         int retval;
6714
6715         pf = 0;
6716         sp = 0;
6717         page_len = 0;
6718         len_used = 0;
6719         len_left = 0;
6720         retval = 0;
6721         bd_len = 0;
6722         page_index = NULL;
6723
6724         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6725
6726         if (lun->be_lun->lun_type != T_DIRECT)
6727                 control_dev = 1;
6728         else
6729                 control_dev = 0;
6730
6731         switch (ctsio->cdb[0]) {
6732         case MODE_SELECT_6: {
6733                 struct scsi_mode_select_6 *cdb;
6734
6735                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6736
6737                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6738                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6739
6740                 param_len = cdb->length;
6741                 header_size = sizeof(struct scsi_mode_header_6);
6742                 break;
6743         }
6744         case MODE_SELECT_10: {
6745                 struct scsi_mode_select_10 *cdb;
6746
6747                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6748
6749                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6750                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6751
6752                 param_len = scsi_2btoul(cdb->length);
6753                 header_size = sizeof(struct scsi_mode_header_10);
6754                 break;
6755         }
6756         default:
6757                 ctl_set_invalid_opcode(ctsio);
6758                 ctl_done((union ctl_io *)ctsio);
6759                 return (CTL_RETVAL_COMPLETE);
6760                 break; /* NOTREACHED */
6761         }
6762
6763         /*
6764          * From SPC-3:
6765          * "A parameter list length of zero indicates that the Data-Out Buffer
6766          * shall be empty. This condition shall not be considered as an error."
6767          */
6768         if (param_len == 0) {
6769                 ctl_set_success(ctsio);
6770                 ctl_done((union ctl_io *)ctsio);
6771                 return (CTL_RETVAL_COMPLETE);
6772         }
6773
6774         /*
6775          * Since we'll hit this the first time through, prior to
6776          * allocation, we don't need to free a data buffer here.
6777          */
6778         if (param_len < header_size) {
6779                 ctl_set_param_len_error(ctsio);
6780                 ctl_done((union ctl_io *)ctsio);
6781                 return (CTL_RETVAL_COMPLETE);
6782         }
6783
6784         /*
6785          * Allocate the data buffer and grab the user's data.  In theory,
6786          * we shouldn't have to sanity check the parameter list length here
6787          * because the maximum size is 64K.  We should be able to malloc
6788          * that much without too many problems.
6789          */
6790         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6791                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6792                 ctsio->kern_data_len = param_len;
6793                 ctsio->kern_total_len = param_len;
6794                 ctsio->kern_data_resid = 0;
6795                 ctsio->kern_rel_offset = 0;
6796                 ctsio->kern_sg_entries = 0;
6797                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6798                 ctsio->be_move_done = ctl_config_move_done;
6799                 ctl_datamove((union ctl_io *)ctsio);
6800
6801                 return (CTL_RETVAL_COMPLETE);
6802         }
6803
6804         switch (ctsio->cdb[0]) {
6805         case MODE_SELECT_6: {
6806                 struct scsi_mode_header_6 *mh6;
6807
6808                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6809                 bd_len = mh6->blk_desc_len;
6810                 break;
6811         }
6812         case MODE_SELECT_10: {
6813                 struct scsi_mode_header_10 *mh10;
6814
6815                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6816                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6817                 break;
6818         }
6819         default:
6820                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6821                 break;
6822         }
6823
6824         if (param_len < (header_size + bd_len)) {
6825                 free(ctsio->kern_data_ptr, M_CTL);
6826                 ctl_set_param_len_error(ctsio);
6827                 ctl_done((union ctl_io *)ctsio);
6828                 return (CTL_RETVAL_COMPLETE);
6829         }
6830
6831         /*
6832          * Set the IO_CONT flag, so that if this I/O gets passed to
6833          * ctl_config_write_done(), it'll get passed back to
6834          * ctl_do_mode_select() for further processing, or completion if
6835          * we're all done.
6836          */
6837         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6838         ctsio->io_cont = ctl_do_mode_select;
6839
6840         modepage_info = (union ctl_modepage_info *)
6841                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6842
6843         memset(modepage_info, 0, sizeof(*modepage_info));
6844
6845         len_left = param_len - header_size - bd_len;
6846         len_used = header_size + bd_len;
6847
6848         modepage_info->header.len_left = len_left;
6849         modepage_info->header.len_used = len_used;
6850
6851         return (ctl_do_mode_select((union ctl_io *)ctsio));
6852 }
6853
6854 int
6855 ctl_mode_sense(struct ctl_scsiio *ctsio)
6856 {
6857         struct ctl_lun *lun;
6858         int pc, page_code, dbd, llba, subpage;
6859         int alloc_len, page_len, header_len, total_len;
6860         struct scsi_mode_block_descr *block_desc;
6861         struct ctl_page_index *page_index;
6862         int control_dev;
6863
6864         dbd = 0;
6865         llba = 0;
6866         block_desc = NULL;
6867         page_index = NULL;
6868
6869         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6870
6871         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6872
6873         if (lun->be_lun->lun_type != T_DIRECT)
6874                 control_dev = 1;
6875         else
6876                 control_dev = 0;
6877
6878         if (lun->flags & CTL_LUN_PR_RESERVED) {
6879                 uint32_t residx;
6880
6881                 /*
6882                  * XXX KDM need a lock here.
6883                  */
6884                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6885                 if ((lun->res_type == SPR_TYPE_EX_AC
6886                   && residx != lun->pr_res_idx)
6887                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
6888                    || lun->res_type == SPR_TYPE_EX_AC_AR)
6889                   && lun->pr_keys[residx] == 0)) {
6890                         ctl_set_reservation_conflict(ctsio);
6891                         ctl_done((union ctl_io *)ctsio);
6892                         return (CTL_RETVAL_COMPLETE);
6893                 }
6894         }
6895
6896         switch (ctsio->cdb[0]) {
6897         case MODE_SENSE_6: {
6898                 struct scsi_mode_sense_6 *cdb;
6899
6900                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6901
6902                 header_len = sizeof(struct scsi_mode_hdr_6);
6903                 if (cdb->byte2 & SMS_DBD)
6904                         dbd = 1;
6905                 else
6906                         header_len += sizeof(struct scsi_mode_block_descr);
6907
6908                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6909                 page_code = cdb->page & SMS_PAGE_CODE;
6910                 subpage = cdb->subpage;
6911                 alloc_len = cdb->length;
6912                 break;
6913         }
6914         case MODE_SENSE_10: {
6915                 struct scsi_mode_sense_10 *cdb;
6916
6917                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6918
6919                 header_len = sizeof(struct scsi_mode_hdr_10);
6920
6921                 if (cdb->byte2 & SMS_DBD)
6922                         dbd = 1;
6923                 else
6924                         header_len += sizeof(struct scsi_mode_block_descr);
6925                 if (cdb->byte2 & SMS10_LLBAA)
6926                         llba = 1;
6927                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6928                 page_code = cdb->page & SMS_PAGE_CODE;
6929                 subpage = cdb->subpage;
6930                 alloc_len = scsi_2btoul(cdb->length);
6931                 break;
6932         }
6933         default:
6934                 ctl_set_invalid_opcode(ctsio);
6935                 ctl_done((union ctl_io *)ctsio);
6936                 return (CTL_RETVAL_COMPLETE);
6937                 break; /* NOTREACHED */
6938         }
6939
6940         /*
6941          * We have to make a first pass through to calculate the size of
6942          * the pages that match the user's query.  Then we allocate enough
6943          * memory to hold it, and actually copy the data into the buffer.
6944          */
6945         switch (page_code) {
6946         case SMS_ALL_PAGES_PAGE: {
6947                 int i;
6948
6949                 page_len = 0;
6950
6951                 /*
6952                  * At the moment, values other than 0 and 0xff here are
6953                  * reserved according to SPC-3.
6954                  */
6955                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6956                  && (subpage != SMS_SUBPAGE_ALL)) {
6957                         ctl_set_invalid_field(ctsio,
6958                                               /*sks_valid*/ 1,
6959                                               /*command*/ 1,
6960                                               /*field*/ 3,
6961                                               /*bit_valid*/ 0,
6962                                               /*bit*/ 0);
6963                         ctl_done((union ctl_io *)ctsio);
6964                         return (CTL_RETVAL_COMPLETE);
6965                 }
6966
6967                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6968                         if ((control_dev != 0)
6969                          && (lun->mode_pages.index[i].page_flags &
6970                              CTL_PAGE_FLAG_DISK_ONLY))
6971                                 continue;
6972
6973                         /*
6974                          * We don't use this subpage if the user didn't
6975                          * request all subpages.
6976                          */
6977                         if ((lun->mode_pages.index[i].subpage != 0)
6978                          && (subpage == SMS_SUBPAGE_PAGE_0))
6979                                 continue;
6980
6981 #if 0
6982                         printf("found page %#x len %d\n",
6983                                lun->mode_pages.index[i].page_code &
6984                                SMPH_PC_MASK,
6985                                lun->mode_pages.index[i].page_len);
6986 #endif
6987                         page_len += lun->mode_pages.index[i].page_len;
6988                 }
6989                 break;
6990         }
6991         default: {
6992                 int i;
6993
6994                 page_len = 0;
6995
6996                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6997                         /* Look for the right page code */
6998                         if ((lun->mode_pages.index[i].page_code &
6999                              SMPH_PC_MASK) != page_code)
7000                                 continue;
7001
7002                         /* Look for the right subpage or the subpage wildcard*/
7003                         if ((lun->mode_pages.index[i].subpage != subpage)
7004                          && (subpage != SMS_SUBPAGE_ALL))
7005                                 continue;
7006
7007                         /* Make sure the page is supported for this dev type */
7008                         if ((control_dev != 0)
7009                          && (lun->mode_pages.index[i].page_flags &
7010                              CTL_PAGE_FLAG_DISK_ONLY))
7011                                 continue;
7012
7013 #if 0
7014                         printf("found page %#x len %d\n",
7015                                lun->mode_pages.index[i].page_code &
7016                                SMPH_PC_MASK,
7017                                lun->mode_pages.index[i].page_len);
7018 #endif
7019
7020                         page_len += lun->mode_pages.index[i].page_len;
7021                 }
7022
7023                 if (page_len == 0) {
7024                         ctl_set_invalid_field(ctsio,
7025                                               /*sks_valid*/ 1,
7026                                               /*command*/ 1,
7027                                               /*field*/ 2,
7028                                               /*bit_valid*/ 1,
7029                                               /*bit*/ 5);
7030                         ctl_done((union ctl_io *)ctsio);
7031                         return (CTL_RETVAL_COMPLETE);
7032                 }
7033                 break;
7034         }
7035         }
7036
7037         total_len = header_len + page_len;
7038 #if 0
7039         printf("header_len = %d, page_len = %d, total_len = %d\n",
7040                header_len, page_len, total_len);
7041 #endif
7042
7043         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7044         ctsio->kern_sg_entries = 0;
7045         ctsio->kern_data_resid = 0;
7046         ctsio->kern_rel_offset = 0;
7047         if (total_len < alloc_len) {
7048                 ctsio->residual = alloc_len - total_len;
7049                 ctsio->kern_data_len = total_len;
7050                 ctsio->kern_total_len = total_len;
7051         } else {
7052                 ctsio->residual = 0;
7053                 ctsio->kern_data_len = alloc_len;
7054                 ctsio->kern_total_len = alloc_len;
7055         }
7056
7057         switch (ctsio->cdb[0]) {
7058         case MODE_SENSE_6: {
7059                 struct scsi_mode_hdr_6 *header;
7060
7061                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7062
7063                 header->datalen = ctl_min(total_len - 1, 254);
7064                 if (control_dev == 0) {
7065                         header->dev_specific = 0x10; /* DPOFUA */
7066                         if ((lun->flags & CTL_LUN_READONLY) ||
7067                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7068                             .eca_and_aen & SCP_SWP) != 0)
7069                                     header->dev_specific |= 0x80; /* WP */
7070                 }
7071                 if (dbd)
7072                         header->block_descr_len = 0;
7073                 else
7074                         header->block_descr_len =
7075                                 sizeof(struct scsi_mode_block_descr);
7076                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7077                 break;
7078         }
7079         case MODE_SENSE_10: {
7080                 struct scsi_mode_hdr_10 *header;
7081                 int datalen;
7082
7083                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7084
7085                 datalen = ctl_min(total_len - 2, 65533);
7086                 scsi_ulto2b(datalen, header->datalen);
7087                 if (control_dev == 0) {
7088                         header->dev_specific = 0x10; /* DPOFUA */
7089                         if ((lun->flags & CTL_LUN_READONLY) ||
7090                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7091                             .eca_and_aen & SCP_SWP) != 0)
7092                                     header->dev_specific |= 0x80; /* WP */
7093                 }
7094                 if (dbd)
7095                         scsi_ulto2b(0, header->block_descr_len);
7096                 else
7097                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7098                                     header->block_descr_len);
7099                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7100                 break;
7101         }
7102         default:
7103                 panic("invalid CDB type %#x", ctsio->cdb[0]);
7104                 break; /* NOTREACHED */
7105         }
7106
7107         /*
7108          * If we've got a disk, use its blocksize in the block
7109          * descriptor.  Otherwise, just set it to 0.
7110          */
7111         if (dbd == 0) {
7112                 if (control_dev == 0)
7113                         scsi_ulto3b(lun->be_lun->blocksize,
7114                                     block_desc->block_len);
7115                 else
7116                         scsi_ulto3b(0, block_desc->block_len);
7117         }
7118
7119         switch (page_code) {
7120         case SMS_ALL_PAGES_PAGE: {
7121                 int i, data_used;
7122
7123                 data_used = header_len;
7124                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7125                         struct ctl_page_index *page_index;
7126
7127                         page_index = &lun->mode_pages.index[i];
7128
7129                         if ((control_dev != 0)
7130                          && (page_index->page_flags &
7131                             CTL_PAGE_FLAG_DISK_ONLY))
7132                                 continue;
7133
7134                         /*
7135                          * We don't use this subpage if the user didn't
7136                          * request all subpages.  We already checked (above)
7137                          * to make sure the user only specified a subpage
7138                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7139                          */
7140                         if ((page_index->subpage != 0)
7141                          && (subpage == SMS_SUBPAGE_PAGE_0))
7142                                 continue;
7143
7144                         /*
7145                          * Call the handler, if it exists, to update the
7146                          * page to the latest values.
7147                          */
7148                         if (page_index->sense_handler != NULL)
7149                                 page_index->sense_handler(ctsio, page_index,pc);
7150
7151                         memcpy(ctsio->kern_data_ptr + data_used,
7152                                page_index->page_data +
7153                                (page_index->page_len * pc),
7154                                page_index->page_len);
7155                         data_used += page_index->page_len;
7156                 }
7157                 break;
7158         }
7159         default: {
7160                 int i, data_used;
7161
7162                 data_used = header_len;
7163
7164                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7165                         struct ctl_page_index *page_index;
7166
7167                         page_index = &lun->mode_pages.index[i];
7168
7169                         /* Look for the right page code */
7170                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7171                                 continue;
7172
7173                         /* Look for the right subpage or the subpage wildcard*/
7174                         if ((page_index->subpage != subpage)
7175                          && (subpage != SMS_SUBPAGE_ALL))
7176                                 continue;
7177
7178                         /* Make sure the page is supported for this dev type */
7179                         if ((control_dev != 0)
7180                          && (page_index->page_flags &
7181                              CTL_PAGE_FLAG_DISK_ONLY))
7182                                 continue;
7183
7184                         /*
7185                          * Call the handler, if it exists, to update the
7186                          * page to the latest values.
7187                          */
7188                         if (page_index->sense_handler != NULL)
7189                                 page_index->sense_handler(ctsio, page_index,pc);
7190
7191                         memcpy(ctsio->kern_data_ptr + data_used,
7192                                page_index->page_data +
7193                                (page_index->page_len * pc),
7194                                page_index->page_len);
7195                         data_used += page_index->page_len;
7196                 }
7197                 break;
7198         }
7199         }
7200
7201         ctsio->scsi_status = SCSI_STATUS_OK;
7202
7203         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7204         ctsio->be_move_done = ctl_config_move_done;
7205         ctl_datamove((union ctl_io *)ctsio);
7206
7207         return (CTL_RETVAL_COMPLETE);
7208 }
7209
7210 int
7211 ctl_read_capacity(struct ctl_scsiio *ctsio)
7212 {
7213         struct scsi_read_capacity *cdb;
7214         struct scsi_read_capacity_data *data;
7215         struct ctl_lun *lun;
7216         uint32_t lba;
7217
7218         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7219
7220         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7221
7222         lba = scsi_4btoul(cdb->addr);
7223         if (((cdb->pmi & SRC_PMI) == 0)
7224          && (lba != 0)) {
7225                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7226                                       /*sks_valid*/ 1,
7227                                       /*command*/ 1,
7228                                       /*field*/ 2,
7229                                       /*bit_valid*/ 0,
7230                                       /*bit*/ 0);
7231                 ctl_done((union ctl_io *)ctsio);
7232                 return (CTL_RETVAL_COMPLETE);
7233         }
7234
7235         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7236
7237         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7238         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7239         ctsio->residual = 0;
7240         ctsio->kern_data_len = sizeof(*data);
7241         ctsio->kern_total_len = sizeof(*data);
7242         ctsio->kern_data_resid = 0;
7243         ctsio->kern_rel_offset = 0;
7244         ctsio->kern_sg_entries = 0;
7245
7246         /*
7247          * If the maximum LBA is greater than 0xfffffffe, the user must
7248          * issue a SERVICE ACTION IN (16) command, with the read capacity
7249          * serivce action set.
7250          */
7251         if (lun->be_lun->maxlba > 0xfffffffe)
7252                 scsi_ulto4b(0xffffffff, data->addr);
7253         else
7254                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7255
7256         /*
7257          * XXX KDM this may not be 512 bytes...
7258          */
7259         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7260
7261         ctsio->scsi_status = SCSI_STATUS_OK;
7262
7263         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7264         ctsio->be_move_done = ctl_config_move_done;
7265         ctl_datamove((union ctl_io *)ctsio);
7266
7267         return (CTL_RETVAL_COMPLETE);
7268 }
7269
7270 int
7271 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7272 {
7273         struct scsi_read_capacity_16 *cdb;
7274         struct scsi_read_capacity_data_long *data;
7275         struct ctl_lun *lun;
7276         uint64_t lba;
7277         uint32_t alloc_len;
7278
7279         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7280
7281         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7282
7283         alloc_len = scsi_4btoul(cdb->alloc_len);
7284         lba = scsi_8btou64(cdb->addr);
7285
7286         if ((cdb->reladr & SRC16_PMI)
7287          && (lba != 0)) {
7288                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7289                                       /*sks_valid*/ 1,
7290                                       /*command*/ 1,
7291                                       /*field*/ 2,
7292                                       /*bit_valid*/ 0,
7293                                       /*bit*/ 0);
7294                 ctl_done((union ctl_io *)ctsio);
7295                 return (CTL_RETVAL_COMPLETE);
7296         }
7297
7298         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7299
7300         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7301         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7302
7303         if (sizeof(*data) < alloc_len) {
7304                 ctsio->residual = alloc_len - sizeof(*data);
7305                 ctsio->kern_data_len = sizeof(*data);
7306                 ctsio->kern_total_len = sizeof(*data);
7307         } else {
7308                 ctsio->residual = 0;
7309                 ctsio->kern_data_len = alloc_len;
7310                 ctsio->kern_total_len = alloc_len;
7311         }
7312         ctsio->kern_data_resid = 0;
7313         ctsio->kern_rel_offset = 0;
7314         ctsio->kern_sg_entries = 0;
7315
7316         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7317         /* XXX KDM this may not be 512 bytes... */
7318         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7319         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7320         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7321         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7322                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7323
7324         ctsio->scsi_status = SCSI_STATUS_OK;
7325
7326         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7327         ctsio->be_move_done = ctl_config_move_done;
7328         ctl_datamove((union ctl_io *)ctsio);
7329
7330         return (CTL_RETVAL_COMPLETE);
7331 }
7332
7333 int
7334 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7335 {
7336         struct scsi_maintenance_in *cdb;
7337         int retval;
7338         int alloc_len, ext, total_len = 0, g, p, pc, pg;
7339         int num_target_port_groups, num_target_ports, single;
7340         struct ctl_lun *lun;
7341         struct ctl_softc *softc;
7342         struct ctl_port *port;
7343         struct scsi_target_group_data *rtg_ptr;
7344         struct scsi_target_group_data_extended *rtg_ext_ptr;
7345         struct scsi_target_port_group_descriptor *tpg_desc;
7346
7347         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7348
7349         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7350         softc = control_softc;
7351         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7352
7353         retval = CTL_RETVAL_COMPLETE;
7354
7355         switch (cdb->byte2 & STG_PDF_MASK) {
7356         case STG_PDF_LENGTH:
7357                 ext = 0;
7358                 break;
7359         case STG_PDF_EXTENDED:
7360                 ext = 1;
7361                 break;
7362         default:
7363                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7364                                       /*sks_valid*/ 1,
7365                                       /*command*/ 1,
7366                                       /*field*/ 2,
7367                                       /*bit_valid*/ 1,
7368                                       /*bit*/ 5);
7369                 ctl_done((union ctl_io *)ctsio);
7370                 return(retval);
7371         }
7372
7373         single = ctl_is_single;
7374         if (single)
7375                 num_target_port_groups = 1;
7376         else
7377                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7378         num_target_ports = 0;
7379         mtx_lock(&softc->ctl_lock);
7380         STAILQ_FOREACH(port, &softc->port_list, links) {
7381                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7382                         continue;
7383                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7384                         continue;
7385                 num_target_ports++;
7386         }
7387         mtx_unlock(&softc->ctl_lock);
7388
7389         if (ext)
7390                 total_len = sizeof(struct scsi_target_group_data_extended);
7391         else
7392                 total_len = sizeof(struct scsi_target_group_data);
7393         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7394                 num_target_port_groups +
7395             sizeof(struct scsi_target_port_descriptor) *
7396                 num_target_ports * num_target_port_groups;
7397
7398         alloc_len = scsi_4btoul(cdb->length);
7399
7400         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7401
7402         ctsio->kern_sg_entries = 0;
7403
7404         if (total_len < alloc_len) {
7405                 ctsio->residual = alloc_len - total_len;
7406                 ctsio->kern_data_len = total_len;
7407                 ctsio->kern_total_len = total_len;
7408         } else {
7409                 ctsio->residual = 0;
7410                 ctsio->kern_data_len = alloc_len;
7411                 ctsio->kern_total_len = alloc_len;
7412         }
7413         ctsio->kern_data_resid = 0;
7414         ctsio->kern_rel_offset = 0;
7415
7416         if (ext) {
7417                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7418                     ctsio->kern_data_ptr;
7419                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7420                 rtg_ext_ptr->format_type = 0x10;
7421                 rtg_ext_ptr->implicit_transition_time = 0;
7422                 tpg_desc = &rtg_ext_ptr->groups[0];
7423         } else {
7424                 rtg_ptr = (struct scsi_target_group_data *)
7425                     ctsio->kern_data_ptr;
7426                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7427                 tpg_desc = &rtg_ptr->groups[0];
7428         }
7429
7430         pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7431         mtx_lock(&softc->ctl_lock);
7432         for (g = 0; g < num_target_port_groups; g++) {
7433                 if (g == pg)
7434                         tpg_desc->pref_state = TPG_PRIMARY |
7435                             TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7436                 else
7437                         tpg_desc->pref_state =
7438                             TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7439                 tpg_desc->support = TPG_AO_SUP;
7440                 if (!single)
7441                         tpg_desc->support |= TPG_AN_SUP;
7442                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7443                 tpg_desc->status = TPG_IMPLICIT;
7444                 pc = 0;
7445                 STAILQ_FOREACH(port, &softc->port_list, links) {
7446                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7447                                 continue;
7448                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7449                             CTL_MAX_LUNS)
7450                                 continue;
7451                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7452                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7453                             relative_target_port_identifier);
7454                         pc++;
7455                 }
7456                 tpg_desc->target_port_count = pc;
7457                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7458                     &tpg_desc->descriptors[pc];
7459         }
7460         mtx_unlock(&softc->ctl_lock);
7461
7462         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7463         ctsio->be_move_done = ctl_config_move_done;
7464
7465         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7466                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7467                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7468                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7469                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7470
7471         ctl_datamove((union ctl_io *)ctsio);
7472         return(retval);
7473 }
7474
7475 int
7476 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7477 {
7478         struct ctl_lun *lun;
7479         struct scsi_report_supported_opcodes *cdb;
7480         const struct ctl_cmd_entry *entry, *sentry;
7481         struct scsi_report_supported_opcodes_all *all;
7482         struct scsi_report_supported_opcodes_descr *descr;
7483         struct scsi_report_supported_opcodes_one *one;
7484         int retval;
7485         int alloc_len, total_len;
7486         int opcode, service_action, i, j, num;
7487
7488         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7489
7490         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7491         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7492
7493         retval = CTL_RETVAL_COMPLETE;
7494
7495         opcode = cdb->requested_opcode;
7496         service_action = scsi_2btoul(cdb->requested_service_action);
7497         switch (cdb->options & RSO_OPTIONS_MASK) {
7498         case RSO_OPTIONS_ALL:
7499                 num = 0;
7500                 for (i = 0; i < 256; i++) {
7501                         entry = &ctl_cmd_table[i];
7502                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7503                                 for (j = 0; j < 32; j++) {
7504                                         sentry = &((const struct ctl_cmd_entry *)
7505                                             entry->execute)[j];
7506                                         if (ctl_cmd_applicable(
7507                                             lun->be_lun->lun_type, sentry))
7508                                                 num++;
7509                                 }
7510                         } else {
7511                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7512                                     entry))
7513                                         num++;
7514                         }
7515                 }
7516                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7517                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7518                 break;
7519         case RSO_OPTIONS_OC:
7520                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7521                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7522                                               /*sks_valid*/ 1,
7523                                               /*command*/ 1,
7524                                               /*field*/ 2,
7525                                               /*bit_valid*/ 1,
7526                                               /*bit*/ 2);
7527                         ctl_done((union ctl_io *)ctsio);
7528                         return (CTL_RETVAL_COMPLETE);
7529                 }
7530                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7531                 break;
7532         case RSO_OPTIONS_OC_SA:
7533                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7534                     service_action >= 32) {
7535                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7536                                               /*sks_valid*/ 1,
7537                                               /*command*/ 1,
7538                                               /*field*/ 2,
7539                                               /*bit_valid*/ 1,
7540                                               /*bit*/ 2);
7541                         ctl_done((union ctl_io *)ctsio);
7542                         return (CTL_RETVAL_COMPLETE);
7543                 }
7544                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7545                 break;
7546         default:
7547                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7548                                       /*sks_valid*/ 1,
7549                                       /*command*/ 1,
7550                                       /*field*/ 2,
7551                                       /*bit_valid*/ 1,
7552                                       /*bit*/ 2);
7553                 ctl_done((union ctl_io *)ctsio);
7554                 return (CTL_RETVAL_COMPLETE);
7555         }
7556
7557         alloc_len = scsi_4btoul(cdb->length);
7558
7559         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7560
7561         ctsio->kern_sg_entries = 0;
7562
7563         if (total_len < alloc_len) {
7564                 ctsio->residual = alloc_len - total_len;
7565                 ctsio->kern_data_len = total_len;
7566                 ctsio->kern_total_len = total_len;
7567         } else {
7568                 ctsio->residual = 0;
7569                 ctsio->kern_data_len = alloc_len;
7570                 ctsio->kern_total_len = alloc_len;
7571         }
7572         ctsio->kern_data_resid = 0;
7573         ctsio->kern_rel_offset = 0;
7574
7575         switch (cdb->options & RSO_OPTIONS_MASK) {
7576         case RSO_OPTIONS_ALL:
7577                 all = (struct scsi_report_supported_opcodes_all *)
7578                     ctsio->kern_data_ptr;
7579                 num = 0;
7580                 for (i = 0; i < 256; i++) {
7581                         entry = &ctl_cmd_table[i];
7582                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7583                                 for (j = 0; j < 32; j++) {
7584                                         sentry = &((const struct ctl_cmd_entry *)
7585                                             entry->execute)[j];
7586                                         if (!ctl_cmd_applicable(
7587                                             lun->be_lun->lun_type, sentry))
7588                                                 continue;
7589                                         descr = &all->descr[num++];
7590                                         descr->opcode = i;
7591                                         scsi_ulto2b(j, descr->service_action);
7592                                         descr->flags = RSO_SERVACTV;
7593                                         scsi_ulto2b(sentry->length,
7594                                             descr->cdb_length);
7595                                 }
7596                         } else {
7597                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7598                                     entry))
7599                                         continue;
7600                                 descr = &all->descr[num++];
7601                                 descr->opcode = i;
7602                                 scsi_ulto2b(0, descr->service_action);
7603                                 descr->flags = 0;
7604                                 scsi_ulto2b(entry->length, descr->cdb_length);
7605                         }
7606                 }
7607                 scsi_ulto4b(
7608                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7609                     all->length);
7610                 break;
7611         case RSO_OPTIONS_OC:
7612                 one = (struct scsi_report_supported_opcodes_one *)
7613                     ctsio->kern_data_ptr;
7614                 entry = &ctl_cmd_table[opcode];
7615                 goto fill_one;
7616         case RSO_OPTIONS_OC_SA:
7617                 one = (struct scsi_report_supported_opcodes_one *)
7618                     ctsio->kern_data_ptr;
7619                 entry = &ctl_cmd_table[opcode];
7620                 entry = &((const struct ctl_cmd_entry *)
7621                     entry->execute)[service_action];
7622 fill_one:
7623                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7624                         one->support = 3;
7625                         scsi_ulto2b(entry->length, one->cdb_length);
7626                         one->cdb_usage[0] = opcode;
7627                         memcpy(&one->cdb_usage[1], entry->usage,
7628                             entry->length - 1);
7629                 } else
7630                         one->support = 1;
7631                 break;
7632         }
7633
7634         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7635         ctsio->be_move_done = ctl_config_move_done;
7636
7637         ctl_datamove((union ctl_io *)ctsio);
7638         return(retval);
7639 }
7640
7641 int
7642 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7643 {
7644         struct ctl_lun *lun;
7645         struct scsi_report_supported_tmf *cdb;
7646         struct scsi_report_supported_tmf_data *data;
7647         int retval;
7648         int alloc_len, total_len;
7649
7650         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7651
7652         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7653         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7654
7655         retval = CTL_RETVAL_COMPLETE;
7656
7657         total_len = sizeof(struct scsi_report_supported_tmf_data);
7658         alloc_len = scsi_4btoul(cdb->length);
7659
7660         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7661
7662         ctsio->kern_sg_entries = 0;
7663
7664         if (total_len < alloc_len) {
7665                 ctsio->residual = alloc_len - total_len;
7666                 ctsio->kern_data_len = total_len;
7667                 ctsio->kern_total_len = total_len;
7668         } else {
7669                 ctsio->residual = 0;
7670                 ctsio->kern_data_len = alloc_len;
7671                 ctsio->kern_total_len = alloc_len;
7672         }
7673         ctsio->kern_data_resid = 0;
7674         ctsio->kern_rel_offset = 0;
7675
7676         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7677         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7678         data->byte2 |= RST_ITNRS;
7679
7680         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7681         ctsio->be_move_done = ctl_config_move_done;
7682
7683         ctl_datamove((union ctl_io *)ctsio);
7684         return (retval);
7685 }
7686
7687 int
7688 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7689 {
7690         struct ctl_lun *lun;
7691         struct scsi_report_timestamp *cdb;
7692         struct scsi_report_timestamp_data *data;
7693         struct timeval tv;
7694         int64_t timestamp;
7695         int retval;
7696         int alloc_len, total_len;
7697
7698         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7699
7700         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7701         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7702
7703         retval = CTL_RETVAL_COMPLETE;
7704
7705         total_len = sizeof(struct scsi_report_timestamp_data);
7706         alloc_len = scsi_4btoul(cdb->length);
7707
7708         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7709
7710         ctsio->kern_sg_entries = 0;
7711
7712         if (total_len < alloc_len) {
7713                 ctsio->residual = alloc_len - total_len;
7714                 ctsio->kern_data_len = total_len;
7715                 ctsio->kern_total_len = total_len;
7716         } else {
7717                 ctsio->residual = 0;
7718                 ctsio->kern_data_len = alloc_len;
7719                 ctsio->kern_total_len = alloc_len;
7720         }
7721         ctsio->kern_data_resid = 0;
7722         ctsio->kern_rel_offset = 0;
7723
7724         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7725         scsi_ulto2b(sizeof(*data) - 2, data->length);
7726         data->origin = RTS_ORIG_OUTSIDE;
7727         getmicrotime(&tv);
7728         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7729         scsi_ulto4b(timestamp >> 16, data->timestamp);
7730         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7731
7732         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7733         ctsio->be_move_done = ctl_config_move_done;
7734
7735         ctl_datamove((union ctl_io *)ctsio);
7736         return (retval);
7737 }
7738
7739 int
7740 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7741 {
7742         struct scsi_per_res_in *cdb;
7743         int alloc_len, total_len = 0;
7744         /* struct scsi_per_res_in_rsrv in_data; */
7745         struct ctl_lun *lun;
7746         struct ctl_softc *softc;
7747
7748         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7749
7750         softc = control_softc;
7751
7752         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7753
7754         alloc_len = scsi_2btoul(cdb->length);
7755
7756         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7757
7758 retry:
7759         mtx_lock(&lun->lun_lock);
7760         switch (cdb->action) {
7761         case SPRI_RK: /* read keys */
7762                 total_len = sizeof(struct scsi_per_res_in_keys) +
7763                         lun->pr_key_count *
7764                         sizeof(struct scsi_per_res_key);
7765                 break;
7766         case SPRI_RR: /* read reservation */
7767                 if (lun->flags & CTL_LUN_PR_RESERVED)
7768                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7769                 else
7770                         total_len = sizeof(struct scsi_per_res_in_header);
7771                 break;
7772         case SPRI_RC: /* report capabilities */
7773                 total_len = sizeof(struct scsi_per_res_cap);
7774                 break;
7775         case SPRI_RS: /* read full status */
7776                 total_len = sizeof(struct scsi_per_res_in_header) +
7777                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7778                     lun->pr_key_count;
7779                 break;
7780         default:
7781                 panic("Invalid PR type %x", cdb->action);
7782         }
7783         mtx_unlock(&lun->lun_lock);
7784
7785         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7786
7787         if (total_len < alloc_len) {
7788                 ctsio->residual = alloc_len - total_len;
7789                 ctsio->kern_data_len = total_len;
7790                 ctsio->kern_total_len = total_len;
7791         } else {
7792                 ctsio->residual = 0;
7793                 ctsio->kern_data_len = alloc_len;
7794                 ctsio->kern_total_len = alloc_len;
7795         }
7796
7797         ctsio->kern_data_resid = 0;
7798         ctsio->kern_rel_offset = 0;
7799         ctsio->kern_sg_entries = 0;
7800
7801         mtx_lock(&lun->lun_lock);
7802         switch (cdb->action) {
7803         case SPRI_RK: { // read keys
7804         struct scsi_per_res_in_keys *res_keys;
7805                 int i, key_count;
7806
7807                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7808
7809                 /*
7810                  * We had to drop the lock to allocate our buffer, which
7811                  * leaves time for someone to come in with another
7812                  * persistent reservation.  (That is unlikely, though,
7813                  * since this should be the only persistent reservation
7814                  * command active right now.)
7815                  */
7816                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7817                     (lun->pr_key_count *
7818                      sizeof(struct scsi_per_res_key)))){
7819                         mtx_unlock(&lun->lun_lock);
7820                         free(ctsio->kern_data_ptr, M_CTL);
7821                         printf("%s: reservation length changed, retrying\n",
7822                                __func__);
7823                         goto retry;
7824                 }
7825
7826                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7827
7828                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7829                              lun->pr_key_count, res_keys->header.length);
7830
7831                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7832                         if (lun->pr_keys[i] == 0)
7833                                 continue;
7834
7835                         /*
7836                          * We used lun->pr_key_count to calculate the
7837                          * size to allocate.  If it turns out the number of
7838                          * initiators with the registered flag set is
7839                          * larger than that (i.e. they haven't been kept in
7840                          * sync), we've got a problem.
7841                          */
7842                         if (key_count >= lun->pr_key_count) {
7843 #ifdef NEEDTOPORT
7844                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7845                                             CTL_PR_ERROR,
7846                                             csevent_LogType_Fault,
7847                                             csevent_AlertLevel_Yellow,
7848                                             csevent_FRU_ShelfController,
7849                                             csevent_FRU_Firmware,
7850                                         csevent_FRU_Unknown,
7851                                             "registered keys %d >= key "
7852                                             "count %d", key_count,
7853                                             lun->pr_key_count);
7854 #endif
7855                                 key_count++;
7856                                 continue;
7857                         }
7858                         scsi_u64to8b(lun->pr_keys[i],
7859                             res_keys->keys[key_count].key);
7860                         key_count++;
7861                 }
7862                 break;
7863         }
7864         case SPRI_RR: { // read reservation
7865                 struct scsi_per_res_in_rsrv *res;
7866                 int tmp_len, header_only;
7867
7868                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7869
7870                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7871
7872                 if (lun->flags & CTL_LUN_PR_RESERVED)
7873                 {
7874                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7875                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7876                                     res->header.length);
7877                         header_only = 0;
7878                 } else {
7879                         tmp_len = sizeof(struct scsi_per_res_in_header);
7880                         scsi_ulto4b(0, res->header.length);
7881                         header_only = 1;
7882                 }
7883
7884                 /*
7885                  * We had to drop the lock to allocate our buffer, which
7886                  * leaves time for someone to come in with another
7887                  * persistent reservation.  (That is unlikely, though,
7888                  * since this should be the only persistent reservation
7889                  * command active right now.)
7890                  */
7891                 if (tmp_len != total_len) {
7892                         mtx_unlock(&lun->lun_lock);
7893                         free(ctsio->kern_data_ptr, M_CTL);
7894                         printf("%s: reservation status changed, retrying\n",
7895                                __func__);
7896                         goto retry;
7897                 }
7898
7899                 /*
7900                  * No reservation held, so we're done.
7901                  */
7902                 if (header_only != 0)
7903                         break;
7904
7905                 /*
7906                  * If the registration is an All Registrants type, the key
7907                  * is 0, since it doesn't really matter.
7908                  */
7909                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7910                         scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7911                             res->data.reservation);
7912                 }
7913                 res->data.scopetype = lun->res_type;
7914                 break;
7915         }
7916         case SPRI_RC:     //report capabilities
7917         {
7918                 struct scsi_per_res_cap *res_cap;
7919                 uint16_t type_mask;
7920
7921                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7922                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7923                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7924                 type_mask = SPRI_TM_WR_EX_AR |
7925                             SPRI_TM_EX_AC_RO |
7926                             SPRI_TM_WR_EX_RO |
7927                             SPRI_TM_EX_AC |
7928                             SPRI_TM_WR_EX |
7929                             SPRI_TM_EX_AC_AR;
7930                 scsi_ulto2b(type_mask, res_cap->type_mask);
7931                 break;
7932         }
7933         case SPRI_RS: { // read full status
7934                 struct scsi_per_res_in_full *res_status;
7935                 struct scsi_per_res_in_full_desc *res_desc;
7936                 struct ctl_port *port;
7937                 int i, len;
7938
7939                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7940
7941                 /*
7942                  * We had to drop the lock to allocate our buffer, which
7943                  * leaves time for someone to come in with another
7944                  * persistent reservation.  (That is unlikely, though,
7945                  * since this should be the only persistent reservation
7946                  * command active right now.)
7947                  */
7948                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7949                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7950                      lun->pr_key_count)){
7951                         mtx_unlock(&lun->lun_lock);
7952                         free(ctsio->kern_data_ptr, M_CTL);
7953                         printf("%s: reservation length changed, retrying\n",
7954                                __func__);
7955                         goto retry;
7956                 }
7957
7958                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7959
7960                 res_desc = &res_status->desc[0];
7961                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7962                         if (lun->pr_keys[i] == 0)
7963                                 continue;
7964
7965                         scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7966                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7967                             (lun->pr_res_idx == i ||
7968                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7969                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7970                                 res_desc->scopetype = lun->res_type;
7971                         }
7972                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7973                             res_desc->rel_trgt_port_id);
7974                         len = 0;
7975                         port = softc->ctl_ports[
7976                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7977                         if (port != NULL)
7978                                 len = ctl_create_iid(port,
7979                                     i % CTL_MAX_INIT_PER_PORT,
7980                                     res_desc->transport_id);
7981                         scsi_ulto4b(len, res_desc->additional_length);
7982                         res_desc = (struct scsi_per_res_in_full_desc *)
7983                             &res_desc->transport_id[len];
7984                 }
7985                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7986                     res_status->header.length);
7987                 break;
7988         }
7989         default:
7990                 /*
7991                  * This is a bug, because we just checked for this above,
7992                  * and should have returned an error.
7993                  */
7994                 panic("Invalid PR type %x", cdb->action);
7995                 break; /* NOTREACHED */
7996         }
7997         mtx_unlock(&lun->lun_lock);
7998
7999         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8000         ctsio->be_move_done = ctl_config_move_done;
8001
8002         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8003                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8004                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8005                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8006                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8007
8008         ctl_datamove((union ctl_io *)ctsio);
8009
8010         return (CTL_RETVAL_COMPLETE);
8011 }
8012
8013 /*
8014  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8015  * it should return.
8016  */
8017 static int
8018 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8019                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8020                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8021                 struct scsi_per_res_out_parms* param)
8022 {
8023         union ctl_ha_msg persis_io;
8024         int retval, i;
8025         int isc_retval;
8026
8027         retval = 0;
8028
8029         mtx_lock(&lun->lun_lock);
8030         if (sa_res_key == 0) {
8031                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8032                         /* validate scope and type */
8033                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8034                              SPR_LU_SCOPE) {
8035                                 mtx_unlock(&lun->lun_lock);
8036                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8037                                                       /*sks_valid*/ 1,
8038                                                       /*command*/ 1,
8039                                                       /*field*/ 2,
8040                                                       /*bit_valid*/ 1,
8041                                                       /*bit*/ 4);
8042                                 ctl_done((union ctl_io *)ctsio);
8043                                 return (1);
8044                         }
8045
8046                         if (type>8 || type==2 || type==4 || type==0) {
8047                                 mtx_unlock(&lun->lun_lock);
8048                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8049                                                       /*sks_valid*/ 1,
8050                                                       /*command*/ 1,
8051                                                       /*field*/ 2,
8052                                                       /*bit_valid*/ 1,
8053                                                       /*bit*/ 0);
8054                                 ctl_done((union ctl_io *)ctsio);
8055                                 return (1);
8056                         }
8057
8058                         /*
8059                          * Unregister everybody else and build UA for
8060                          * them
8061                          */
8062                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8063                                 if (i == residx || lun->pr_keys[i] == 0)
8064                                         continue;
8065
8066                                 if (!persis_offset
8067                                  && i <CTL_MAX_INITIATORS)
8068                                         lun->pending_ua[i] |=
8069                                                 CTL_UA_REG_PREEMPT;
8070                                 else if (persis_offset
8071                                       && i >= persis_offset)
8072                                         lun->pending_ua[i-persis_offset] |=
8073                                                 CTL_UA_REG_PREEMPT;
8074                                 lun->pr_keys[i] = 0;
8075                         }
8076                         lun->pr_key_count = 1;
8077                         lun->res_type = type;
8078                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8079                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8080                                 lun->pr_res_idx = residx;
8081
8082                         /* send msg to other side */
8083                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8084                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8085                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8086                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8087                         persis_io.pr.pr_info.res_type = type;
8088                         memcpy(persis_io.pr.pr_info.sa_res_key,
8089                                param->serv_act_res_key,
8090                                sizeof(param->serv_act_res_key));
8091                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8092                              &persis_io, sizeof(persis_io), 0)) >
8093                              CTL_HA_STATUS_SUCCESS) {
8094                                 printf("CTL:Persis Out error returned "
8095                                        "from ctl_ha_msg_send %d\n",
8096                                        isc_retval);
8097                         }
8098                 } else {
8099                         /* not all registrants */
8100                         mtx_unlock(&lun->lun_lock);
8101                         free(ctsio->kern_data_ptr, M_CTL);
8102                         ctl_set_invalid_field(ctsio,
8103                                               /*sks_valid*/ 1,
8104                                               /*command*/ 0,
8105                                               /*field*/ 8,
8106                                               /*bit_valid*/ 0,
8107                                               /*bit*/ 0);
8108                         ctl_done((union ctl_io *)ctsio);
8109                         return (1);
8110                 }
8111         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8112                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8113                 int found = 0;
8114
8115                 if (res_key == sa_res_key) {
8116                         /* special case */
8117                         /*
8118                          * The spec implies this is not good but doesn't
8119                          * say what to do. There are two choices either
8120                          * generate a res conflict or check condition
8121                          * with illegal field in parameter data. Since
8122                          * that is what is done when the sa_res_key is
8123                          * zero I'll take that approach since this has
8124                          * to do with the sa_res_key.
8125                          */
8126                         mtx_unlock(&lun->lun_lock);
8127                         free(ctsio->kern_data_ptr, M_CTL);
8128                         ctl_set_invalid_field(ctsio,
8129                                               /*sks_valid*/ 1,
8130                                               /*command*/ 0,
8131                                               /*field*/ 8,
8132                                               /*bit_valid*/ 0,
8133                                               /*bit*/ 0);
8134                         ctl_done((union ctl_io *)ctsio);
8135                         return (1);
8136                 }
8137
8138                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8139                         if (lun->pr_keys[i] != sa_res_key)
8140                                 continue;
8141
8142                         found = 1;
8143                         lun->pr_keys[i] = 0;
8144                         lun->pr_key_count--;
8145
8146                         if (!persis_offset && i < CTL_MAX_INITIATORS)
8147                                 lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8148                         else if (persis_offset && i >= persis_offset)
8149                                 lun->pending_ua[i-persis_offset] |=
8150                                         CTL_UA_REG_PREEMPT;
8151                 }
8152                 if (!found) {
8153                         mtx_unlock(&lun->lun_lock);
8154                         free(ctsio->kern_data_ptr, M_CTL);
8155                         ctl_set_reservation_conflict(ctsio);
8156                         ctl_done((union ctl_io *)ctsio);
8157                         return (CTL_RETVAL_COMPLETE);
8158                 }
8159                 /* send msg to other side */
8160                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8161                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8162                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8163                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8164                 persis_io.pr.pr_info.res_type = type;
8165                 memcpy(persis_io.pr.pr_info.sa_res_key,
8166                        param->serv_act_res_key,
8167                        sizeof(param->serv_act_res_key));
8168                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8169                      &persis_io, sizeof(persis_io), 0)) >
8170                      CTL_HA_STATUS_SUCCESS) {
8171                         printf("CTL:Persis Out error returned from "
8172                                "ctl_ha_msg_send %d\n", isc_retval);
8173                 }
8174         } else {
8175                 /* Reserved but not all registrants */
8176                 /* sa_res_key is res holder */
8177                 if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8178                         /* validate scope and type */
8179                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8180                              SPR_LU_SCOPE) {
8181                                 mtx_unlock(&lun->lun_lock);
8182                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8183                                                       /*sks_valid*/ 1,
8184                                                       /*command*/ 1,
8185                                                       /*field*/ 2,
8186                                                       /*bit_valid*/ 1,
8187                                                       /*bit*/ 4);
8188                                 ctl_done((union ctl_io *)ctsio);
8189                                 return (1);
8190                         }
8191
8192                         if (type>8 || type==2 || type==4 || type==0) {
8193                                 mtx_unlock(&lun->lun_lock);
8194                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8195                                                       /*sks_valid*/ 1,
8196                                                       /*command*/ 1,
8197                                                       /*field*/ 2,
8198                                                       /*bit_valid*/ 1,
8199                                                       /*bit*/ 0);
8200                                 ctl_done((union ctl_io *)ctsio);
8201                                 return (1);
8202                         }
8203
8204                         /*
8205                          * Do the following:
8206                          * if sa_res_key != res_key remove all
8207                          * registrants w/sa_res_key and generate UA
8208                          * for these registrants(Registrations
8209                          * Preempted) if it wasn't an exclusive
8210                          * reservation generate UA(Reservations
8211                          * Preempted) for all other registered nexuses
8212                          * if the type has changed. Establish the new
8213                          * reservation and holder. If res_key and
8214                          * sa_res_key are the same do the above
8215                          * except don't unregister the res holder.
8216                          */
8217
8218                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8219                                 if (i == residx || lun->pr_keys[i] == 0)
8220                                         continue;
8221
8222                                 if (sa_res_key == lun->pr_keys[i]) {
8223                                         lun->pr_keys[i] = 0;
8224                                         lun->pr_key_count--;
8225
8226                                         if (!persis_offset
8227                                          && i < CTL_MAX_INITIATORS)
8228                                                 lun->pending_ua[i] |=
8229                                                         CTL_UA_REG_PREEMPT;
8230                                         else if (persis_offset
8231                                               && i >= persis_offset)
8232                                                 lun->pending_ua[i-persis_offset] |=
8233                                                   CTL_UA_REG_PREEMPT;
8234                                 } else if (type != lun->res_type
8235                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8236                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8237                                                 if (!persis_offset
8238                                                  && i < CTL_MAX_INITIATORS)
8239                                                         lun->pending_ua[i] |=
8240                                                         CTL_UA_RES_RELEASE;
8241                                                 else if (persis_offset
8242                                                       && i >= persis_offset)
8243                                                         lun->pending_ua[
8244                                                         i-persis_offset] |=
8245                                                         CTL_UA_RES_RELEASE;
8246                                 }
8247                         }
8248                         lun->res_type = type;
8249                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8250                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8251                                 lun->pr_res_idx = residx;
8252                         else
8253                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8254
8255                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8256                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8257                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8258                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8259                         persis_io.pr.pr_info.res_type = type;
8260                         memcpy(persis_io.pr.pr_info.sa_res_key,
8261                                param->serv_act_res_key,
8262                                sizeof(param->serv_act_res_key));
8263                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8264                              &persis_io, sizeof(persis_io), 0)) >
8265                              CTL_HA_STATUS_SUCCESS) {
8266                                 printf("CTL:Persis Out error returned "
8267                                        "from ctl_ha_msg_send %d\n",
8268                                        isc_retval);
8269                         }
8270                 } else {
8271                         /*
8272                          * sa_res_key is not the res holder just
8273                          * remove registrants
8274                          */
8275                         int found=0;
8276
8277                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8278                                 if (sa_res_key != lun->pr_keys[i])
8279                                         continue;
8280
8281                                 found = 1;
8282                                 lun->pr_keys[i] = 0;
8283                                 lun->pr_key_count--;
8284
8285                                 if (!persis_offset
8286                                  && i < CTL_MAX_INITIATORS)
8287                                         lun->pending_ua[i] |=
8288                                                 CTL_UA_REG_PREEMPT;
8289                                 else if (persis_offset
8290                                       && i >= persis_offset)
8291                                         lun->pending_ua[i-persis_offset] |=
8292                                                 CTL_UA_REG_PREEMPT;
8293                         }
8294
8295                         if (!found) {
8296                                 mtx_unlock(&lun->lun_lock);
8297                                 free(ctsio->kern_data_ptr, M_CTL);
8298                                 ctl_set_reservation_conflict(ctsio);
8299                                 ctl_done((union ctl_io *)ctsio);
8300                                 return (1);
8301                         }
8302                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8303                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8304                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8305                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8306                         persis_io.pr.pr_info.res_type = type;
8307                         memcpy(persis_io.pr.pr_info.sa_res_key,
8308                                param->serv_act_res_key,
8309                                sizeof(param->serv_act_res_key));
8310                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8311                              &persis_io, sizeof(persis_io), 0)) >
8312                              CTL_HA_STATUS_SUCCESS) {
8313                                 printf("CTL:Persis Out error returned "
8314                                        "from ctl_ha_msg_send %d\n",
8315                                 isc_retval);
8316                         }
8317                 }
8318         }
8319
8320         lun->PRGeneration++;
8321         mtx_unlock(&lun->lun_lock);
8322
8323         return (retval);
8324 }
8325
8326 static void
8327 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8328 {
8329         uint64_t sa_res_key;
8330         int i;
8331
8332         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8333
8334         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8335          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8336          || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8337                 if (sa_res_key == 0) {
8338                         /*
8339                          * Unregister everybody else and build UA for
8340                          * them
8341                          */
8342                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8343                                 if (i == msg->pr.pr_info.residx ||
8344                                     lun->pr_keys[i] == 0)
8345                                         continue;
8346
8347                                 if (!persis_offset
8348                                  && i < CTL_MAX_INITIATORS)
8349                                         lun->pending_ua[i] |=
8350                                                 CTL_UA_REG_PREEMPT;
8351                                 else if (persis_offset && i >= persis_offset)
8352                                         lun->pending_ua[i - persis_offset] |=
8353                                                 CTL_UA_REG_PREEMPT;
8354                                 lun->pr_keys[i] = 0;
8355                         }
8356
8357                         lun->pr_key_count = 1;
8358                         lun->res_type = msg->pr.pr_info.res_type;
8359                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8360                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8361                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8362                 } else {
8363                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8364                                 if (sa_res_key == lun->pr_keys[i])
8365                                         continue;
8366
8367                                 lun->pr_keys[i] = 0;
8368                                 lun->pr_key_count--;
8369
8370                                 if (!persis_offset
8371                                  && i < persis_offset)
8372                                         lun->pending_ua[i] |=
8373                                                 CTL_UA_REG_PREEMPT;
8374                                 else if (persis_offset
8375                                       && i >= persis_offset)
8376                                         lun->pending_ua[i - persis_offset] |=
8377                                                 CTL_UA_REG_PREEMPT;
8378                         }
8379                 }
8380         } else {
8381                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8382                         if (i == msg->pr.pr_info.residx ||
8383                             lun->pr_keys[i] == 0)
8384                                 continue;
8385
8386                         if (sa_res_key == lun->pr_keys[i]) {
8387                                 lun->pr_keys[i] = 0;
8388                                 lun->pr_key_count--;
8389                                 if (!persis_offset
8390                                  && i < CTL_MAX_INITIATORS)
8391                                         lun->pending_ua[i] |=
8392                                                 CTL_UA_REG_PREEMPT;
8393                                 else if (persis_offset
8394                                       && i >= persis_offset)
8395                                         lun->pending_ua[i - persis_offset] |=
8396                                                 CTL_UA_REG_PREEMPT;
8397                         } else if (msg->pr.pr_info.res_type != lun->res_type
8398                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8399                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8400                                         if (!persis_offset
8401                                          && i < persis_offset)
8402                                                 lun->pending_ua[i] |=
8403                                                         CTL_UA_RES_RELEASE;
8404                                         else if (persis_offset
8405                                               && i >= persis_offset)
8406                                         lun->pending_ua[i - persis_offset] |=
8407                                                 CTL_UA_RES_RELEASE;
8408                         }
8409                 }
8410                 lun->res_type = msg->pr.pr_info.res_type;
8411                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8412                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8413                         lun->pr_res_idx = msg->pr.pr_info.residx;
8414                 else
8415                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8416         }
8417         lun->PRGeneration++;
8418
8419 }
8420
8421
8422 int
8423 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8424 {
8425         int retval;
8426         int isc_retval;
8427         u_int32_t param_len;
8428         struct scsi_per_res_out *cdb;
8429         struct ctl_lun *lun;
8430         struct scsi_per_res_out_parms* param;
8431         struct ctl_softc *softc;
8432         uint32_t residx;
8433         uint64_t res_key, sa_res_key;
8434         uint8_t type;
8435         union ctl_ha_msg persis_io;
8436         int    i;
8437
8438         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8439
8440         retval = CTL_RETVAL_COMPLETE;
8441
8442         softc = control_softc;
8443
8444         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8445         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8446
8447         /*
8448          * We only support whole-LUN scope.  The scope & type are ignored for
8449          * register, register and ignore existing key and clear.
8450          * We sometimes ignore scope and type on preempts too!!
8451          * Verify reservation type here as well.
8452          */
8453         type = cdb->scope_type & SPR_TYPE_MASK;
8454         if ((cdb->action == SPRO_RESERVE)
8455          || (cdb->action == SPRO_RELEASE)) {
8456                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8457                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8458                                               /*sks_valid*/ 1,
8459                                               /*command*/ 1,
8460                                               /*field*/ 2,
8461                                               /*bit_valid*/ 1,
8462                                               /*bit*/ 4);
8463                         ctl_done((union ctl_io *)ctsio);
8464                         return (CTL_RETVAL_COMPLETE);
8465                 }
8466
8467                 if (type>8 || type==2 || type==4 || type==0) {
8468                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8469                                               /*sks_valid*/ 1,
8470                                               /*command*/ 1,
8471                                               /*field*/ 2,
8472                                               /*bit_valid*/ 1,
8473                                               /*bit*/ 0);
8474                         ctl_done((union ctl_io *)ctsio);
8475                         return (CTL_RETVAL_COMPLETE);
8476                 }
8477         }
8478
8479         param_len = scsi_4btoul(cdb->length);
8480
8481         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8482                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8483                 ctsio->kern_data_len = param_len;
8484                 ctsio->kern_total_len = param_len;
8485                 ctsio->kern_data_resid = 0;
8486                 ctsio->kern_rel_offset = 0;
8487                 ctsio->kern_sg_entries = 0;
8488                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8489                 ctsio->be_move_done = ctl_config_move_done;
8490                 ctl_datamove((union ctl_io *)ctsio);
8491
8492                 return (CTL_RETVAL_COMPLETE);
8493         }
8494
8495         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8496
8497         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8498         res_key = scsi_8btou64(param->res_key.key);
8499         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8500
8501         /*
8502          * Validate the reservation key here except for SPRO_REG_IGNO
8503          * This must be done for all other service actions
8504          */
8505         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8506                 mtx_lock(&lun->lun_lock);
8507                 if (lun->pr_keys[residx] != 0) {
8508                     if (res_key != lun->pr_keys[residx]) {
8509                                 /*
8510                                  * The current key passed in doesn't match
8511                                  * the one the initiator previously
8512                                  * registered.
8513                                  */
8514                                 mtx_unlock(&lun->lun_lock);
8515                                 free(ctsio->kern_data_ptr, M_CTL);
8516                                 ctl_set_reservation_conflict(ctsio);
8517                                 ctl_done((union ctl_io *)ctsio);
8518                                 return (CTL_RETVAL_COMPLETE);
8519                         }
8520                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8521                         /*
8522                          * We are not registered
8523                          */
8524                         mtx_unlock(&lun->lun_lock);
8525                         free(ctsio->kern_data_ptr, M_CTL);
8526                         ctl_set_reservation_conflict(ctsio);
8527                         ctl_done((union ctl_io *)ctsio);
8528                         return (CTL_RETVAL_COMPLETE);
8529                 } else if (res_key != 0) {
8530                         /*
8531                          * We are not registered and trying to register but
8532                          * the register key isn't zero.
8533                          */
8534                         mtx_unlock(&lun->lun_lock);
8535                         free(ctsio->kern_data_ptr, M_CTL);
8536                         ctl_set_reservation_conflict(ctsio);
8537                         ctl_done((union ctl_io *)ctsio);
8538                         return (CTL_RETVAL_COMPLETE);
8539                 }
8540                 mtx_unlock(&lun->lun_lock);
8541         }
8542
8543         switch (cdb->action & SPRO_ACTION_MASK) {
8544         case SPRO_REGISTER:
8545         case SPRO_REG_IGNO: {
8546
8547 #if 0
8548                 printf("Registration received\n");
8549 #endif
8550
8551                 /*
8552                  * We don't support any of these options, as we report in
8553                  * the read capabilities request (see
8554                  * ctl_persistent_reserve_in(), above).
8555                  */
8556                 if ((param->flags & SPR_SPEC_I_PT)
8557                  || (param->flags & SPR_ALL_TG_PT)
8558                  || (param->flags & SPR_APTPL)) {
8559                         int bit_ptr;
8560
8561                         if (param->flags & SPR_APTPL)
8562                                 bit_ptr = 0;
8563                         else if (param->flags & SPR_ALL_TG_PT)
8564                                 bit_ptr = 2;
8565                         else /* SPR_SPEC_I_PT */
8566                                 bit_ptr = 3;
8567
8568                         free(ctsio->kern_data_ptr, M_CTL);
8569                         ctl_set_invalid_field(ctsio,
8570                                               /*sks_valid*/ 1,
8571                                               /*command*/ 0,
8572                                               /*field*/ 20,
8573                                               /*bit_valid*/ 1,
8574                                               /*bit*/ bit_ptr);
8575                         ctl_done((union ctl_io *)ctsio);
8576                         return (CTL_RETVAL_COMPLETE);
8577                 }
8578
8579                 mtx_lock(&lun->lun_lock);
8580
8581                 /*
8582                  * The initiator wants to clear the
8583                  * key/unregister.
8584                  */
8585                 if (sa_res_key == 0) {
8586                         if ((res_key == 0
8587                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8588                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8589                           && lun->pr_keys[residx] == 0)) {
8590                                 mtx_unlock(&lun->lun_lock);
8591                                 goto done;
8592                         }
8593
8594                         lun->pr_keys[residx] = 0;
8595                         lun->pr_key_count--;
8596
8597                         if (residx == lun->pr_res_idx) {
8598                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8599                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8600
8601                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8602                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8603                                  && lun->pr_key_count) {
8604                                         /*
8605                                          * If the reservation is a registrants
8606                                          * only type we need to generate a UA
8607                                          * for other registered inits.  The
8608                                          * sense code should be RESERVATIONS
8609                                          * RELEASED
8610                                          */
8611
8612                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8613                                                 if (lun->pr_keys[
8614                                                     i + persis_offset] == 0)
8615                                                         continue;
8616                                                 lun->pending_ua[i] |=
8617                                                         CTL_UA_RES_RELEASE;
8618                                         }
8619                                 }
8620                                 lun->res_type = 0;
8621                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8622                                 if (lun->pr_key_count==0) {
8623                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8624                                         lun->res_type = 0;
8625                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8626                                 }
8627                         }
8628                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8629                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8630                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8631                         persis_io.pr.pr_info.residx = residx;
8632                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8633                              &persis_io, sizeof(persis_io), 0 )) >
8634                              CTL_HA_STATUS_SUCCESS) {
8635                                 printf("CTL:Persis Out error returned from "
8636                                        "ctl_ha_msg_send %d\n", isc_retval);
8637                         }
8638                 } else /* sa_res_key != 0 */ {
8639
8640                         /*
8641                          * If we aren't registered currently then increment
8642                          * the key count and set the registered flag.
8643                          */
8644                         if (lun->pr_keys[residx] == 0)
8645                                 lun->pr_key_count++;
8646                         lun->pr_keys[residx] = sa_res_key;
8647
8648                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8649                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8650                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8651                         persis_io.pr.pr_info.residx = residx;
8652                         memcpy(persis_io.pr.pr_info.sa_res_key,
8653                                param->serv_act_res_key,
8654                                sizeof(param->serv_act_res_key));
8655                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8656                              &persis_io, sizeof(persis_io), 0)) >
8657                              CTL_HA_STATUS_SUCCESS) {
8658                                 printf("CTL:Persis Out error returned from "
8659                                        "ctl_ha_msg_send %d\n", isc_retval);
8660                         }
8661                 }
8662                 lun->PRGeneration++;
8663                 mtx_unlock(&lun->lun_lock);
8664
8665                 break;
8666         }
8667         case SPRO_RESERVE:
8668 #if 0
8669                 printf("Reserve executed type %d\n", type);
8670 #endif
8671                 mtx_lock(&lun->lun_lock);
8672                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8673                         /*
8674                          * if this isn't the reservation holder and it's
8675                          * not a "all registrants" type or if the type is
8676                          * different then we have a conflict
8677                          */
8678                         if ((lun->pr_res_idx != residx
8679                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8680                          || lun->res_type != type) {
8681                                 mtx_unlock(&lun->lun_lock);
8682                                 free(ctsio->kern_data_ptr, M_CTL);
8683                                 ctl_set_reservation_conflict(ctsio);
8684                                 ctl_done((union ctl_io *)ctsio);
8685                                 return (CTL_RETVAL_COMPLETE);
8686                         }
8687                         mtx_unlock(&lun->lun_lock);
8688                 } else /* create a reservation */ {
8689                         /*
8690                          * If it's not an "all registrants" type record
8691                          * reservation holder
8692                          */
8693                         if (type != SPR_TYPE_WR_EX_AR
8694                          && type != SPR_TYPE_EX_AC_AR)
8695                                 lun->pr_res_idx = residx; /* Res holder */
8696                         else
8697                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8698
8699                         lun->flags |= CTL_LUN_PR_RESERVED;
8700                         lun->res_type = type;
8701
8702                         mtx_unlock(&lun->lun_lock);
8703
8704                         /* send msg to other side */
8705                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8706                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8707                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8708                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8709                         persis_io.pr.pr_info.res_type = type;
8710                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8711                              &persis_io, sizeof(persis_io), 0)) >
8712                              CTL_HA_STATUS_SUCCESS) {
8713                                 printf("CTL:Persis Out error returned from "
8714                                        "ctl_ha_msg_send %d\n", isc_retval);
8715                         }
8716                 }
8717                 break;
8718
8719         case SPRO_RELEASE:
8720                 mtx_lock(&lun->lun_lock);
8721                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8722                         /* No reservation exists return good status */
8723                         mtx_unlock(&lun->lun_lock);
8724                         goto done;
8725                 }
8726                 /*
8727                  * Is this nexus a reservation holder?
8728                  */
8729                 if (lun->pr_res_idx != residx
8730                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8731                         /*
8732                          * not a res holder return good status but
8733                          * do nothing
8734                          */
8735                         mtx_unlock(&lun->lun_lock);
8736                         goto done;
8737                 }
8738
8739                 if (lun->res_type != type) {
8740                         mtx_unlock(&lun->lun_lock);
8741                         free(ctsio->kern_data_ptr, M_CTL);
8742                         ctl_set_illegal_pr_release(ctsio);
8743                         ctl_done((union ctl_io *)ctsio);
8744                         return (CTL_RETVAL_COMPLETE);
8745                 }
8746
8747                 /* okay to release */
8748                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8749                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8750                 lun->res_type = 0;
8751
8752                 /*
8753                  * if this isn't an exclusive access
8754                  * res generate UA for all other
8755                  * registrants.
8756                  */
8757                 if (type != SPR_TYPE_EX_AC
8758                  && type != SPR_TYPE_WR_EX) {
8759                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8760                                 if (i == residx ||
8761                                     lun->pr_keys[i + persis_offset] == 0)
8762                                         continue;
8763                                 lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8764                         }
8765                 }
8766                 mtx_unlock(&lun->lun_lock);
8767                 /* Send msg to other side */
8768                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8769                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8770                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8771                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8772                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8773                         printf("CTL:Persis Out error returned from "
8774                                "ctl_ha_msg_send %d\n", isc_retval);
8775                 }
8776                 break;
8777
8778         case SPRO_CLEAR:
8779                 /* send msg to other side */
8780
8781                 mtx_lock(&lun->lun_lock);
8782                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8783                 lun->res_type = 0;
8784                 lun->pr_key_count = 0;
8785                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8786
8787                 lun->pr_keys[residx] = 0;
8788
8789                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8790                         if (lun->pr_keys[i] != 0) {
8791                                 if (!persis_offset && i < CTL_MAX_INITIATORS)
8792                                         lun->pending_ua[i] |=
8793                                                 CTL_UA_RES_PREEMPT;
8794                                 else if (persis_offset && i >= persis_offset)
8795                                         lun->pending_ua[i-persis_offset] |=
8796                                             CTL_UA_RES_PREEMPT;
8797
8798                                 lun->pr_keys[i] = 0;
8799                         }
8800                 lun->PRGeneration++;
8801                 mtx_unlock(&lun->lun_lock);
8802                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8803                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8804                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8805                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8806                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8807                         printf("CTL:Persis Out error returned from "
8808                                "ctl_ha_msg_send %d\n", isc_retval);
8809                 }
8810                 break;
8811
8812         case SPRO_PREEMPT: {
8813                 int nretval;
8814
8815                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8816                                           residx, ctsio, cdb, param);
8817                 if (nretval != 0)
8818                         return (CTL_RETVAL_COMPLETE);
8819                 break;
8820         }
8821         default:
8822                 panic("Invalid PR type %x", cdb->action);
8823         }
8824
8825 done:
8826         free(ctsio->kern_data_ptr, M_CTL);
8827         ctl_set_success(ctsio);
8828         ctl_done((union ctl_io *)ctsio);
8829
8830         return (retval);
8831 }
8832
8833 /*
8834  * This routine is for handling a message from the other SC pertaining to
8835  * persistent reserve out. All the error checking will have been done
8836  * so only perorming the action need be done here to keep the two
8837  * in sync.
8838  */
8839 static void
8840 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8841 {
8842         struct ctl_lun *lun;
8843         struct ctl_softc *softc;
8844         int i;
8845         uint32_t targ_lun;
8846
8847         softc = control_softc;
8848
8849         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8850         lun = softc->ctl_luns[targ_lun];
8851         mtx_lock(&lun->lun_lock);
8852         switch(msg->pr.pr_info.action) {
8853         case CTL_PR_REG_KEY:
8854                 if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8855                         lun->pr_key_count++;
8856                 lun->pr_keys[msg->pr.pr_info.residx] =
8857                     scsi_8btou64(msg->pr.pr_info.sa_res_key);
8858                 lun->PRGeneration++;
8859                 break;
8860
8861         case CTL_PR_UNREG_KEY:
8862                 lun->pr_keys[msg->pr.pr_info.residx] = 0;
8863                 lun->pr_key_count--;
8864
8865                 /* XXX Need to see if the reservation has been released */
8866                 /* if so do we need to generate UA? */
8867                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8868                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8869                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8870
8871                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8872                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8873                          && lun->pr_key_count) {
8874                                 /*
8875                                  * If the reservation is a registrants
8876                                  * only type we need to generate a UA
8877                                  * for other registered inits.  The
8878                                  * sense code should be RESERVATIONS
8879                                  * RELEASED
8880                                  */
8881
8882                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8883                                         if (lun->pr_keys[i+
8884                                             persis_offset] == 0)
8885                                                 continue;
8886
8887                                         lun->pending_ua[i] |=
8888                                                 CTL_UA_RES_RELEASE;
8889                                 }
8890                         }
8891                         lun->res_type = 0;
8892                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8893                         if (lun->pr_key_count==0) {
8894                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8895                                 lun->res_type = 0;
8896                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8897                         }
8898                 }
8899                 lun->PRGeneration++;
8900                 break;
8901
8902         case CTL_PR_RESERVE:
8903                 lun->flags |= CTL_LUN_PR_RESERVED;
8904                 lun->res_type = msg->pr.pr_info.res_type;
8905                 lun->pr_res_idx = msg->pr.pr_info.residx;
8906
8907                 break;
8908
8909         case CTL_PR_RELEASE:
8910                 /*
8911                  * if this isn't an exclusive access res generate UA for all
8912                  * other registrants.
8913                  */
8914                 if (lun->res_type != SPR_TYPE_EX_AC
8915                  && lun->res_type != SPR_TYPE_WR_EX) {
8916                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8917                                 if (lun->pr_keys[i+persis_offset] != 0)
8918                                         lun->pending_ua[i] |=
8919                                                 CTL_UA_RES_RELEASE;
8920                 }
8921
8922                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8923                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8924                 lun->res_type = 0;
8925                 break;
8926
8927         case CTL_PR_PREEMPT:
8928                 ctl_pro_preempt_other(lun, msg);
8929                 break;
8930         case CTL_PR_CLEAR:
8931                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8932                 lun->res_type = 0;
8933                 lun->pr_key_count = 0;
8934                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8935
8936                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8937                         if (lun->pr_keys[i] == 0)
8938                                 continue;
8939                         if (!persis_offset
8940                          && i < CTL_MAX_INITIATORS)
8941                                 lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8942                         else if (persis_offset
8943                               && i >= persis_offset)
8944                                 lun->pending_ua[i-persis_offset] |=
8945                                         CTL_UA_RES_PREEMPT;
8946                         lun->pr_keys[i] = 0;
8947                 }
8948                 lun->PRGeneration++;
8949                 break;
8950         }
8951
8952         mtx_unlock(&lun->lun_lock);
8953 }
8954
8955 int
8956 ctl_read_write(struct ctl_scsiio *ctsio)
8957 {
8958         struct ctl_lun *lun;
8959         struct ctl_lba_len_flags *lbalen;
8960         uint64_t lba;
8961         uint32_t num_blocks;
8962         int flags, retval;
8963         int isread;
8964
8965         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8966
8967         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8968
8969         flags = 0;
8970         retval = CTL_RETVAL_COMPLETE;
8971
8972         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8973               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8974         if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8975                 uint32_t residx;
8976
8977                 /*
8978                  * XXX KDM need a lock here.
8979                  */
8980                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8981                 if ((lun->res_type == SPR_TYPE_EX_AC
8982                   && residx != lun->pr_res_idx)
8983                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
8984                    || lun->res_type == SPR_TYPE_EX_AC_AR)
8985                   && lun->pr_keys[residx] == 0)) {
8986                         ctl_set_reservation_conflict(ctsio);
8987                         ctl_done((union ctl_io *)ctsio);
8988                         return (CTL_RETVAL_COMPLETE);
8989                 }
8990         }
8991
8992         switch (ctsio->cdb[0]) {
8993         case READ_6:
8994         case WRITE_6: {
8995                 struct scsi_rw_6 *cdb;
8996
8997                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8998
8999                 lba = scsi_3btoul(cdb->addr);
9000                 /* only 5 bits are valid in the most significant address byte */
9001                 lba &= 0x1fffff;
9002                 num_blocks = cdb->length;
9003                 /*
9004                  * This is correct according to SBC-2.
9005                  */
9006                 if (num_blocks == 0)
9007                         num_blocks = 256;
9008                 break;
9009         }
9010         case READ_10:
9011         case WRITE_10: {
9012                 struct scsi_rw_10 *cdb;
9013
9014                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9015                 if (cdb->byte2 & SRW10_FUA)
9016                         flags |= CTL_LLF_FUA;
9017                 if (cdb->byte2 & SRW10_DPO)
9018                         flags |= CTL_LLF_DPO;
9019                 lba = scsi_4btoul(cdb->addr);
9020                 num_blocks = scsi_2btoul(cdb->length);
9021                 break;
9022         }
9023         case WRITE_VERIFY_10: {
9024                 struct scsi_write_verify_10 *cdb;
9025
9026                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9027                 flags |= CTL_LLF_FUA;
9028                 if (cdb->byte2 & SWV_DPO)
9029                         flags |= CTL_LLF_DPO;
9030                 lba = scsi_4btoul(cdb->addr);
9031                 num_blocks = scsi_2btoul(cdb->length);
9032                 break;
9033         }
9034         case READ_12:
9035         case WRITE_12: {
9036                 struct scsi_rw_12 *cdb;
9037
9038                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9039                 if (cdb->byte2 & SRW12_FUA)
9040                         flags |= CTL_LLF_FUA;
9041                 if (cdb->byte2 & SRW12_DPO)
9042                         flags |= CTL_LLF_DPO;
9043                 lba = scsi_4btoul(cdb->addr);
9044                 num_blocks = scsi_4btoul(cdb->length);
9045                 break;
9046         }
9047         case WRITE_VERIFY_12: {
9048                 struct scsi_write_verify_12 *cdb;
9049
9050                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9051                 flags |= CTL_LLF_FUA;
9052                 if (cdb->byte2 & SWV_DPO)
9053                         flags |= CTL_LLF_DPO;
9054                 lba = scsi_4btoul(cdb->addr);
9055                 num_blocks = scsi_4btoul(cdb->length);
9056                 break;
9057         }
9058         case READ_16:
9059         case WRITE_16: {
9060                 struct scsi_rw_16 *cdb;
9061
9062                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9063                 if (cdb->byte2 & SRW12_FUA)
9064                         flags |= CTL_LLF_FUA;
9065                 if (cdb->byte2 & SRW12_DPO)
9066                         flags |= CTL_LLF_DPO;
9067                 lba = scsi_8btou64(cdb->addr);
9068                 num_blocks = scsi_4btoul(cdb->length);
9069                 break;
9070         }
9071         case WRITE_ATOMIC_16: {
9072                 struct scsi_rw_16 *cdb;
9073
9074                 if (lun->be_lun->atomicblock == 0) {
9075                         ctl_set_invalid_opcode(ctsio);
9076                         ctl_done((union ctl_io *)ctsio);
9077                         return (CTL_RETVAL_COMPLETE);
9078                 }
9079
9080                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9081                 if (cdb->byte2 & SRW12_FUA)
9082                         flags |= CTL_LLF_FUA;
9083                 if (cdb->byte2 & SRW12_DPO)
9084                         flags |= CTL_LLF_DPO;
9085                 lba = scsi_8btou64(cdb->addr);
9086                 num_blocks = scsi_4btoul(cdb->length);
9087                 if (num_blocks > lun->be_lun->atomicblock) {
9088                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9089                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9090                             /*bit*/ 0);
9091                         ctl_done((union ctl_io *)ctsio);
9092                         return (CTL_RETVAL_COMPLETE);
9093                 }
9094                 break;
9095         }
9096         case WRITE_VERIFY_16: {
9097                 struct scsi_write_verify_16 *cdb;
9098
9099                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9100                 flags |= CTL_LLF_FUA;
9101                 if (cdb->byte2 & SWV_DPO)
9102                         flags |= CTL_LLF_DPO;
9103                 lba = scsi_8btou64(cdb->addr);
9104                 num_blocks = scsi_4btoul(cdb->length);
9105                 break;
9106         }
9107         default:
9108                 /*
9109                  * We got a command we don't support.  This shouldn't
9110                  * happen, commands should be filtered out above us.
9111                  */
9112                 ctl_set_invalid_opcode(ctsio);
9113                 ctl_done((union ctl_io *)ctsio);
9114
9115                 return (CTL_RETVAL_COMPLETE);
9116                 break; /* NOTREACHED */
9117         }
9118
9119         /*
9120          * The first check is to make sure we're in bounds, the second
9121          * check is to catch wrap-around problems.  If the lba + num blocks
9122          * is less than the lba, then we've wrapped around and the block
9123          * range is invalid anyway.
9124          */
9125         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9126          || ((lba + num_blocks) < lba)) {
9127                 ctl_set_lba_out_of_range(ctsio);
9128                 ctl_done((union ctl_io *)ctsio);
9129                 return (CTL_RETVAL_COMPLETE);
9130         }
9131
9132         /*
9133          * According to SBC-3, a transfer length of 0 is not an error.
9134          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9135          * translates to 256 blocks for those commands.
9136          */
9137         if (num_blocks == 0) {
9138                 ctl_set_success(ctsio);
9139                 ctl_done((union ctl_io *)ctsio);
9140                 return (CTL_RETVAL_COMPLETE);
9141         }
9142
9143         /* Set FUA and/or DPO if caches are disabled. */
9144         if (isread) {
9145                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9146                     SCP_RCD) != 0)
9147                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9148         } else {
9149                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9150                     SCP_WCE) == 0)
9151                         flags |= CTL_LLF_FUA;
9152         }
9153
9154         lbalen = (struct ctl_lba_len_flags *)
9155             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9156         lbalen->lba = lba;
9157         lbalen->len = num_blocks;
9158         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9159
9160         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9161         ctsio->kern_rel_offset = 0;
9162
9163         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9164
9165         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9166
9167         return (retval);
9168 }
9169
9170 static int
9171 ctl_cnw_cont(union ctl_io *io)
9172 {
9173         struct ctl_scsiio *ctsio;
9174         struct ctl_lun *lun;
9175         struct ctl_lba_len_flags *lbalen;
9176         int retval;
9177
9178         ctsio = &io->scsiio;
9179         ctsio->io_hdr.status = CTL_STATUS_NONE;
9180         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9181         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9182         lbalen = (struct ctl_lba_len_flags *)
9183             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9184         lbalen->flags &= ~CTL_LLF_COMPARE;
9185         lbalen->flags |= CTL_LLF_WRITE;
9186
9187         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9188         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9189         return (retval);
9190 }
9191
9192 int
9193 ctl_cnw(struct ctl_scsiio *ctsio)
9194 {
9195         struct ctl_lun *lun;
9196         struct ctl_lba_len_flags *lbalen;
9197         uint64_t lba;
9198         uint32_t num_blocks;
9199         int flags, retval;
9200
9201         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9202
9203         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9204
9205         flags = 0;
9206         retval = CTL_RETVAL_COMPLETE;
9207
9208         switch (ctsio->cdb[0]) {
9209         case COMPARE_AND_WRITE: {
9210                 struct scsi_compare_and_write *cdb;
9211
9212                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9213                 if (cdb->byte2 & SRW10_FUA)
9214                         flags |= CTL_LLF_FUA;
9215                 if (cdb->byte2 & SRW10_DPO)
9216                         flags |= CTL_LLF_DPO;
9217                 lba = scsi_8btou64(cdb->addr);
9218                 num_blocks = cdb->length;
9219                 break;
9220         }
9221         default:
9222                 /*
9223                  * We got a command we don't support.  This shouldn't
9224                  * happen, commands should be filtered out above us.
9225                  */
9226                 ctl_set_invalid_opcode(ctsio);
9227                 ctl_done((union ctl_io *)ctsio);
9228
9229                 return (CTL_RETVAL_COMPLETE);
9230                 break; /* NOTREACHED */
9231         }
9232
9233         /*
9234          * The first check is to make sure we're in bounds, the second
9235          * check is to catch wrap-around problems.  If the lba + num blocks
9236          * is less than the lba, then we've wrapped around and the block
9237          * range is invalid anyway.
9238          */
9239         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9240          || ((lba + num_blocks) < lba)) {
9241                 ctl_set_lba_out_of_range(ctsio);
9242                 ctl_done((union ctl_io *)ctsio);
9243                 return (CTL_RETVAL_COMPLETE);
9244         }
9245
9246         /*
9247          * According to SBC-3, a transfer length of 0 is not an error.
9248          */
9249         if (num_blocks == 0) {
9250                 ctl_set_success(ctsio);
9251                 ctl_done((union ctl_io *)ctsio);
9252                 return (CTL_RETVAL_COMPLETE);
9253         }
9254
9255         /* Set FUA if write cache is disabled. */
9256         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9257             SCP_WCE) == 0)
9258                 flags |= CTL_LLF_FUA;
9259
9260         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9261         ctsio->kern_rel_offset = 0;
9262
9263         /*
9264          * Set the IO_CONT flag, so that if this I/O gets passed to
9265          * ctl_data_submit_done(), it'll get passed back to
9266          * ctl_ctl_cnw_cont() for further processing.
9267          */
9268         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9269         ctsio->io_cont = ctl_cnw_cont;
9270
9271         lbalen = (struct ctl_lba_len_flags *)
9272             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9273         lbalen->lba = lba;
9274         lbalen->len = num_blocks;
9275         lbalen->flags = CTL_LLF_COMPARE | flags;
9276
9277         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9278         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9279         return (retval);
9280 }
9281
9282 int
9283 ctl_verify(struct ctl_scsiio *ctsio)
9284 {
9285         struct ctl_lun *lun;
9286         struct ctl_lba_len_flags *lbalen;
9287         uint64_t lba;
9288         uint32_t num_blocks;
9289         int bytchk, flags;
9290         int retval;
9291
9292         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9293
9294         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9295
9296         bytchk = 0;
9297         flags = CTL_LLF_FUA;
9298         retval = CTL_RETVAL_COMPLETE;
9299
9300         switch (ctsio->cdb[0]) {
9301         case VERIFY_10: {
9302                 struct scsi_verify_10 *cdb;
9303
9304                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9305                 if (cdb->byte2 & SVFY_BYTCHK)
9306                         bytchk = 1;
9307                 if (cdb->byte2 & SVFY_DPO)
9308                         flags |= CTL_LLF_DPO;
9309                 lba = scsi_4btoul(cdb->addr);
9310                 num_blocks = scsi_2btoul(cdb->length);
9311                 break;
9312         }
9313         case VERIFY_12: {
9314                 struct scsi_verify_12 *cdb;
9315
9316                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9317                 if (cdb->byte2 & SVFY_BYTCHK)
9318                         bytchk = 1;
9319                 if (cdb->byte2 & SVFY_DPO)
9320                         flags |= CTL_LLF_DPO;
9321                 lba = scsi_4btoul(cdb->addr);
9322                 num_blocks = scsi_4btoul(cdb->length);
9323                 break;
9324         }
9325         case VERIFY_16: {
9326                 struct scsi_rw_16 *cdb;
9327
9328                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9329                 if (cdb->byte2 & SVFY_BYTCHK)
9330                         bytchk = 1;
9331                 if (cdb->byte2 & SVFY_DPO)
9332                         flags |= CTL_LLF_DPO;
9333                 lba = scsi_8btou64(cdb->addr);
9334                 num_blocks = scsi_4btoul(cdb->length);
9335                 break;
9336         }
9337         default:
9338                 /*
9339                  * We got a command we don't support.  This shouldn't
9340                  * happen, commands should be filtered out above us.
9341                  */
9342                 ctl_set_invalid_opcode(ctsio);
9343                 ctl_done((union ctl_io *)ctsio);
9344                 return (CTL_RETVAL_COMPLETE);
9345         }
9346
9347         /*
9348          * The first check is to make sure we're in bounds, the second
9349          * check is to catch wrap-around problems.  If the lba + num blocks
9350          * is less than the lba, then we've wrapped around and the block
9351          * range is invalid anyway.
9352          */
9353         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9354          || ((lba + num_blocks) < lba)) {
9355                 ctl_set_lba_out_of_range(ctsio);
9356                 ctl_done((union ctl_io *)ctsio);
9357                 return (CTL_RETVAL_COMPLETE);
9358         }
9359
9360         /*
9361          * According to SBC-3, a transfer length of 0 is not an error.
9362          */
9363         if (num_blocks == 0) {
9364                 ctl_set_success(ctsio);
9365                 ctl_done((union ctl_io *)ctsio);
9366                 return (CTL_RETVAL_COMPLETE);
9367         }
9368
9369         lbalen = (struct ctl_lba_len_flags *)
9370             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9371         lbalen->lba = lba;
9372         lbalen->len = num_blocks;
9373         if (bytchk) {
9374                 lbalen->flags = CTL_LLF_COMPARE | flags;
9375                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9376         } else {
9377                 lbalen->flags = CTL_LLF_VERIFY | flags;
9378                 ctsio->kern_total_len = 0;
9379         }
9380         ctsio->kern_rel_offset = 0;
9381
9382         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9383         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9384         return (retval);
9385 }
9386
9387 int
9388 ctl_report_luns(struct ctl_scsiio *ctsio)
9389 {
9390         struct scsi_report_luns *cdb;
9391         struct scsi_report_luns_data *lun_data;
9392         struct ctl_lun *lun, *request_lun;
9393         int num_luns, retval;
9394         uint32_t alloc_len, lun_datalen;
9395         int num_filled, well_known;
9396         uint32_t initidx, targ_lun_id, lun_id;
9397
9398         retval = CTL_RETVAL_COMPLETE;
9399         well_known = 0;
9400
9401         cdb = (struct scsi_report_luns *)ctsio->cdb;
9402
9403         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9404
9405         mtx_lock(&control_softc->ctl_lock);
9406         num_luns = control_softc->num_luns;
9407         mtx_unlock(&control_softc->ctl_lock);
9408
9409         switch (cdb->select_report) {
9410         case RPL_REPORT_DEFAULT:
9411         case RPL_REPORT_ALL:
9412                 break;
9413         case RPL_REPORT_WELLKNOWN:
9414                 well_known = 1;
9415                 num_luns = 0;
9416                 break;
9417         default:
9418                 ctl_set_invalid_field(ctsio,
9419                                       /*sks_valid*/ 1,
9420                                       /*command*/ 1,
9421                                       /*field*/ 2,
9422                                       /*bit_valid*/ 0,
9423                                       /*bit*/ 0);
9424                 ctl_done((union ctl_io *)ctsio);
9425                 return (retval);
9426                 break; /* NOTREACHED */
9427         }
9428
9429         alloc_len = scsi_4btoul(cdb->length);
9430         /*
9431          * The initiator has to allocate at least 16 bytes for this request,
9432          * so he can at least get the header and the first LUN.  Otherwise
9433          * we reject the request (per SPC-3 rev 14, section 6.21).
9434          */
9435         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9436             sizeof(struct scsi_report_luns_lundata))) {
9437                 ctl_set_invalid_field(ctsio,
9438                                       /*sks_valid*/ 1,
9439                                       /*command*/ 1,
9440                                       /*field*/ 6,
9441                                       /*bit_valid*/ 0,
9442                                       /*bit*/ 0);
9443                 ctl_done((union ctl_io *)ctsio);
9444                 return (retval);
9445         }
9446
9447         request_lun = (struct ctl_lun *)
9448                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9449
9450         lun_datalen = sizeof(*lun_data) +
9451                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9452
9453         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9454         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9455         ctsio->kern_sg_entries = 0;
9456
9457         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9458
9459         mtx_lock(&control_softc->ctl_lock);
9460         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9461                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9462                 if (lun_id >= CTL_MAX_LUNS)
9463                         continue;
9464                 lun = control_softc->ctl_luns[lun_id];
9465                 if (lun == NULL)
9466                         continue;
9467
9468                 if (targ_lun_id <= 0xff) {
9469                         /*
9470                          * Peripheral addressing method, bus number 0.
9471                          */
9472                         lun_data->luns[num_filled].lundata[0] =
9473                                 RPL_LUNDATA_ATYP_PERIPH;
9474                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9475                         num_filled++;
9476                 } else if (targ_lun_id <= 0x3fff) {
9477                         /*
9478                          * Flat addressing method.
9479                          */
9480                         lun_data->luns[num_filled].lundata[0] =
9481                                 RPL_LUNDATA_ATYP_FLAT |
9482                                 (targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9483 #ifdef OLDCTLHEADERS
9484                                 (SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9485                                 (targ_lun_id & SRLD_BUS_LUN_MASK);
9486 #endif
9487                         lun_data->luns[num_filled].lundata[1] =
9488 #ifdef OLDCTLHEADERS
9489                                 targ_lun_id >> SRLD_BUS_LUN_BITS;
9490 #endif
9491                                 targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9492                         num_filled++;
9493                 } else {
9494                         printf("ctl_report_luns: bogus LUN number %jd, "
9495                                "skipping\n", (intmax_t)targ_lun_id);
9496                 }
9497                 /*
9498                  * According to SPC-3, rev 14 section 6.21:
9499                  *
9500                  * "The execution of a REPORT LUNS command to any valid and
9501                  * installed logical unit shall clear the REPORTED LUNS DATA
9502                  * HAS CHANGED unit attention condition for all logical
9503                  * units of that target with respect to the requesting
9504                  * initiator. A valid and installed logical unit is one
9505                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9506                  * INQUIRY data (see 6.4.2)."
9507                  *
9508                  * If request_lun is NULL, the LUN this report luns command
9509                  * was issued to is either disabled or doesn't exist. In that
9510                  * case, we shouldn't clear any pending lun change unit
9511                  * attention.
9512                  */
9513                 if (request_lun != NULL) {
9514                         mtx_lock(&lun->lun_lock);
9515                         lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9516                         mtx_unlock(&lun->lun_lock);
9517                 }
9518         }
9519         mtx_unlock(&control_softc->ctl_lock);
9520
9521         /*
9522          * It's quite possible that we've returned fewer LUNs than we allocated
9523          * space for.  Trim it.
9524          */
9525         lun_datalen = sizeof(*lun_data) +
9526                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9527
9528         if (lun_datalen < alloc_len) {
9529                 ctsio->residual = alloc_len - lun_datalen;
9530                 ctsio->kern_data_len = lun_datalen;
9531                 ctsio->kern_total_len = lun_datalen;
9532         } else {
9533                 ctsio->residual = 0;
9534                 ctsio->kern_data_len = alloc_len;
9535                 ctsio->kern_total_len = alloc_len;
9536         }
9537         ctsio->kern_data_resid = 0;
9538         ctsio->kern_rel_offset = 0;
9539         ctsio->kern_sg_entries = 0;
9540
9541         /*
9542          * We set this to the actual data length, regardless of how much
9543          * space we actually have to return results.  If the user looks at
9544          * this value, he'll know whether or not he allocated enough space
9545          * and reissue the command if necessary.  We don't support well
9546          * known logical units, so if the user asks for that, return none.
9547          */
9548         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9549
9550         /*
9551          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9552          * this request.
9553          */
9554         ctsio->scsi_status = SCSI_STATUS_OK;
9555
9556         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9557         ctsio->be_move_done = ctl_config_move_done;
9558         ctl_datamove((union ctl_io *)ctsio);
9559
9560         return (retval);
9561 }
9562
9563 int
9564 ctl_request_sense(struct ctl_scsiio *ctsio)
9565 {
9566         struct scsi_request_sense *cdb;
9567         struct scsi_sense_data *sense_ptr;
9568         struct ctl_lun *lun;
9569         uint32_t initidx;
9570         int have_error;
9571         scsi_sense_data_type sense_format;
9572
9573         cdb = (struct scsi_request_sense *)ctsio->cdb;
9574
9575         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9576
9577         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9578
9579         /*
9580          * Determine which sense format the user wants.
9581          */
9582         if (cdb->byte2 & SRS_DESC)
9583                 sense_format = SSD_TYPE_DESC;
9584         else
9585                 sense_format = SSD_TYPE_FIXED;
9586
9587         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9588         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9589         ctsio->kern_sg_entries = 0;
9590
9591         /*
9592          * struct scsi_sense_data, which is currently set to 256 bytes, is
9593          * larger than the largest allowed value for the length field in the
9594          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9595          */
9596         ctsio->residual = 0;
9597         ctsio->kern_data_len = cdb->length;
9598         ctsio->kern_total_len = cdb->length;
9599
9600         ctsio->kern_data_resid = 0;
9601         ctsio->kern_rel_offset = 0;
9602         ctsio->kern_sg_entries = 0;
9603
9604         /*
9605          * If we don't have a LUN, we don't have any pending sense.
9606          */
9607         if (lun == NULL)
9608                 goto no_sense;
9609
9610         have_error = 0;
9611         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9612         /*
9613          * Check for pending sense, and then for pending unit attentions.
9614          * Pending sense gets returned first, then pending unit attentions.
9615          */
9616         mtx_lock(&lun->lun_lock);
9617 #ifdef CTL_WITH_CA
9618         if (ctl_is_set(lun->have_ca, initidx)) {
9619                 scsi_sense_data_type stored_format;
9620
9621                 /*
9622                  * Check to see which sense format was used for the stored
9623                  * sense data.
9624                  */
9625                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9626
9627                 /*
9628                  * If the user requested a different sense format than the
9629                  * one we stored, then we need to convert it to the other
9630                  * format.  If we're going from descriptor to fixed format
9631                  * sense data, we may lose things in translation, depending
9632                  * on what options were used.
9633                  *
9634                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9635                  * for some reason we'll just copy it out as-is.
9636                  */
9637                 if ((stored_format == SSD_TYPE_FIXED)
9638                  && (sense_format == SSD_TYPE_DESC))
9639                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9640                             &lun->pending_sense[initidx],
9641                             (struct scsi_sense_data_desc *)sense_ptr);
9642                 else if ((stored_format == SSD_TYPE_DESC)
9643                       && (sense_format == SSD_TYPE_FIXED))
9644                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9645                             &lun->pending_sense[initidx],
9646                             (struct scsi_sense_data_fixed *)sense_ptr);
9647                 else
9648                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9649                                ctl_min(sizeof(*sense_ptr),
9650                                sizeof(lun->pending_sense[initidx])));
9651
9652                 ctl_clear_mask(lun->have_ca, initidx);
9653                 have_error = 1;
9654         } else
9655 #endif
9656         if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9657                 ctl_ua_type ua_type;
9658
9659                 ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9660                                        sense_ptr, sense_format);
9661                 if (ua_type != CTL_UA_NONE)
9662                         have_error = 1;
9663         }
9664         mtx_unlock(&lun->lun_lock);
9665
9666         /*
9667          * We already have a pending error, return it.
9668          */
9669         if (have_error != 0) {
9670                 /*
9671                  * We report the SCSI status as OK, since the status of the
9672                  * request sense command itself is OK.
9673                  */
9674                 ctsio->scsi_status = SCSI_STATUS_OK;
9675
9676                 /*
9677                  * We report 0 for the sense length, because we aren't doing
9678                  * autosense in this case.  We're reporting sense as
9679                  * parameter data.
9680                  */
9681                 ctsio->sense_len = 0;
9682                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9683                 ctsio->be_move_done = ctl_config_move_done;
9684                 ctl_datamove((union ctl_io *)ctsio);
9685
9686                 return (CTL_RETVAL_COMPLETE);
9687         }
9688
9689 no_sense:
9690
9691         /*
9692          * No sense information to report, so we report that everything is
9693          * okay.
9694          */
9695         ctl_set_sense_data(sense_ptr,
9696                            lun,
9697                            sense_format,
9698                            /*current_error*/ 1,
9699                            /*sense_key*/ SSD_KEY_NO_SENSE,
9700                            /*asc*/ 0x00,
9701                            /*ascq*/ 0x00,
9702                            SSD_ELEM_NONE);
9703
9704         ctsio->scsi_status = SCSI_STATUS_OK;
9705
9706         /*
9707          * We report 0 for the sense length, because we aren't doing
9708          * autosense in this case.  We're reporting sense as parameter data.
9709          */
9710         ctsio->sense_len = 0;
9711         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9712         ctsio->be_move_done = ctl_config_move_done;
9713         ctl_datamove((union ctl_io *)ctsio);
9714
9715         return (CTL_RETVAL_COMPLETE);
9716 }
9717
9718 int
9719 ctl_tur(struct ctl_scsiio *ctsio)
9720 {
9721         struct ctl_lun *lun;
9722
9723         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9724
9725         CTL_DEBUG_PRINT(("ctl_tur\n"));
9726
9727         if (lun == NULL)
9728                 return (EINVAL);
9729
9730         ctsio->scsi_status = SCSI_STATUS_OK;
9731         ctsio->io_hdr.status = CTL_SUCCESS;
9732
9733         ctl_done((union ctl_io *)ctsio);
9734
9735         return (CTL_RETVAL_COMPLETE);
9736 }
9737
9738 #ifdef notyet
9739 static int
9740 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9741 {
9742
9743 }
9744 #endif
9745
9746 static int
9747 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9748 {
9749         struct scsi_vpd_supported_pages *pages;
9750         int sup_page_size;
9751         struct ctl_lun *lun;
9752
9753         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9754
9755         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9756             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9757         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9758         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9759         ctsio->kern_sg_entries = 0;
9760
9761         if (sup_page_size < alloc_len) {
9762                 ctsio->residual = alloc_len - sup_page_size;
9763                 ctsio->kern_data_len = sup_page_size;
9764                 ctsio->kern_total_len = sup_page_size;
9765         } else {
9766                 ctsio->residual = 0;
9767                 ctsio->kern_data_len = alloc_len;
9768                 ctsio->kern_total_len = alloc_len;
9769         }
9770         ctsio->kern_data_resid = 0;
9771         ctsio->kern_rel_offset = 0;
9772         ctsio->kern_sg_entries = 0;
9773
9774         /*
9775          * The control device is always connected.  The disk device, on the
9776          * other hand, may not be online all the time.  Need to change this
9777          * to figure out whether the disk device is actually online or not.
9778          */
9779         if (lun != NULL)
9780                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9781                                 lun->be_lun->lun_type;
9782         else
9783                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9784
9785         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9786         /* Supported VPD pages */
9787         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9788         /* Serial Number */
9789         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9790         /* Device Identification */
9791         pages->page_list[2] = SVPD_DEVICE_ID;
9792         /* Extended INQUIRY Data */
9793         pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9794         /* Mode Page Policy */
9795         pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9796         /* SCSI Ports */
9797         pages->page_list[5] = SVPD_SCSI_PORTS;
9798         /* Third-party Copy */
9799         pages->page_list[6] = SVPD_SCSI_TPC;
9800         /* Block limits */
9801         pages->page_list[7] = SVPD_BLOCK_LIMITS;
9802         /* Block Device Characteristics */
9803         pages->page_list[8] = SVPD_BDC;
9804         /* Logical Block Provisioning */
9805         pages->page_list[9] = SVPD_LBP;
9806
9807         ctsio->scsi_status = SCSI_STATUS_OK;
9808
9809         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9810         ctsio->be_move_done = ctl_config_move_done;
9811         ctl_datamove((union ctl_io *)ctsio);
9812
9813         return (CTL_RETVAL_COMPLETE);
9814 }
9815
9816 static int
9817 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9818 {
9819         struct scsi_vpd_unit_serial_number *sn_ptr;
9820         struct ctl_lun *lun;
9821
9822         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9823
9824         ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9825         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9826         ctsio->kern_sg_entries = 0;
9827
9828         if (sizeof(*sn_ptr) < alloc_len) {
9829                 ctsio->residual = alloc_len - sizeof(*sn_ptr);
9830                 ctsio->kern_data_len = sizeof(*sn_ptr);
9831                 ctsio->kern_total_len = sizeof(*sn_ptr);
9832         } else {
9833                 ctsio->residual = 0;
9834                 ctsio->kern_data_len = alloc_len;
9835                 ctsio->kern_total_len = alloc_len;
9836         }
9837         ctsio->kern_data_resid = 0;
9838         ctsio->kern_rel_offset = 0;
9839         ctsio->kern_sg_entries = 0;
9840
9841         /*
9842          * The control device is always connected.  The disk device, on the
9843          * other hand, may not be online all the time.  Need to change this
9844          * to figure out whether the disk device is actually online or not.
9845          */
9846         if (lun != NULL)
9847                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9848                                   lun->be_lun->lun_type;
9849         else
9850                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9851
9852         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9853         sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9854         /*
9855          * If we don't have a LUN, we just leave the serial number as
9856          * all spaces.
9857          */
9858         memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9859         if (lun != NULL) {
9860                 strncpy((char *)sn_ptr->serial_num,
9861                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9862         }
9863         ctsio->scsi_status = SCSI_STATUS_OK;
9864
9865         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9866         ctsio->be_move_done = ctl_config_move_done;
9867         ctl_datamove((union ctl_io *)ctsio);
9868
9869         return (CTL_RETVAL_COMPLETE);
9870 }
9871
9872
9873 static int
9874 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9875 {
9876         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9877         struct ctl_lun *lun;
9878         int data_len;
9879
9880         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9881
9882         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9883         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9884         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9885         ctsio->kern_sg_entries = 0;
9886
9887         if (data_len < alloc_len) {
9888                 ctsio->residual = alloc_len - data_len;
9889                 ctsio->kern_data_len = data_len;
9890                 ctsio->kern_total_len = data_len;
9891         } else {
9892                 ctsio->residual = 0;
9893                 ctsio->kern_data_len = alloc_len;
9894                 ctsio->kern_total_len = alloc_len;
9895         }
9896         ctsio->kern_data_resid = 0;
9897         ctsio->kern_rel_offset = 0;
9898         ctsio->kern_sg_entries = 0;
9899
9900         /*
9901          * The control device is always connected.  The disk device, on the
9902          * other hand, may not be online all the time.
9903          */
9904         if (lun != NULL)
9905                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9906                                      lun->be_lun->lun_type;
9907         else
9908                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9909         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9910         eid_ptr->page_length = data_len - 4;
9911         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9912         eid_ptr->flags3 = SVPD_EID_V_SUP;
9913
9914         ctsio->scsi_status = SCSI_STATUS_OK;
9915         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9916         ctsio->be_move_done = ctl_config_move_done;
9917         ctl_datamove((union ctl_io *)ctsio);
9918
9919         return (CTL_RETVAL_COMPLETE);
9920 }
9921
9922 static int
9923 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9924 {
9925         struct scsi_vpd_mode_page_policy *mpp_ptr;
9926         struct ctl_lun *lun;
9927         int data_len;
9928
9929         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9930
9931         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9932             sizeof(struct scsi_vpd_mode_page_policy_descr);
9933
9934         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9935         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9936         ctsio->kern_sg_entries = 0;
9937
9938         if (data_len < alloc_len) {
9939                 ctsio->residual = alloc_len - data_len;
9940                 ctsio->kern_data_len = data_len;
9941                 ctsio->kern_total_len = data_len;
9942         } else {
9943                 ctsio->residual = 0;
9944                 ctsio->kern_data_len = alloc_len;
9945                 ctsio->kern_total_len = alloc_len;
9946         }
9947         ctsio->kern_data_resid = 0;
9948         ctsio->kern_rel_offset = 0;
9949         ctsio->kern_sg_entries = 0;
9950
9951         /*
9952          * The control device is always connected.  The disk device, on the
9953          * other hand, may not be online all the time.
9954          */
9955         if (lun != NULL)
9956                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9957                                      lun->be_lun->lun_type;
9958         else
9959                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9960         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9961         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9962         mpp_ptr->descr[0].page_code = 0x3f;
9963         mpp_ptr->descr[0].subpage_code = 0xff;
9964         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9965
9966         ctsio->scsi_status = SCSI_STATUS_OK;
9967         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9968         ctsio->be_move_done = ctl_config_move_done;
9969         ctl_datamove((union ctl_io *)ctsio);
9970
9971         return (CTL_RETVAL_COMPLETE);
9972 }
9973
9974 static int
9975 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9976 {
9977         struct scsi_vpd_device_id *devid_ptr;
9978         struct scsi_vpd_id_descriptor *desc;
9979         struct ctl_softc *ctl_softc;
9980         struct ctl_lun *lun;
9981         struct ctl_port *port;
9982         int data_len;
9983         uint8_t proto;
9984
9985         ctl_softc = control_softc;
9986
9987         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9988         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9989
9990         data_len = sizeof(struct scsi_vpd_device_id) +
9991             sizeof(struct scsi_vpd_id_descriptor) +
9992                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9993             sizeof(struct scsi_vpd_id_descriptor) +
9994                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9995         if (lun && lun->lun_devid)
9996                 data_len += lun->lun_devid->len;
9997         if (port->port_devid)
9998                 data_len += port->port_devid->len;
9999         if (port->target_devid)
10000                 data_len += port->target_devid->len;
10001
10002         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10003         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10004         ctsio->kern_sg_entries = 0;
10005
10006         if (data_len < alloc_len) {
10007                 ctsio->residual = alloc_len - data_len;
10008                 ctsio->kern_data_len = data_len;
10009                 ctsio->kern_total_len = data_len;
10010         } else {
10011                 ctsio->residual = 0;
10012                 ctsio->kern_data_len = alloc_len;
10013                 ctsio->kern_total_len = alloc_len;
10014         }
10015         ctsio->kern_data_resid = 0;
10016         ctsio->kern_rel_offset = 0;
10017         ctsio->kern_sg_entries = 0;
10018
10019         /*
10020          * The control device is always connected.  The disk device, on the
10021          * other hand, may not be online all the time.
10022          */
10023         if (lun != NULL)
10024                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10025                                      lun->be_lun->lun_type;
10026         else
10027                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10028         devid_ptr->page_code = SVPD_DEVICE_ID;
10029         scsi_ulto2b(data_len - 4, devid_ptr->length);
10030
10031         if (port->port_type == CTL_PORT_FC)
10032                 proto = SCSI_PROTO_FC << 4;
10033         else if (port->port_type == CTL_PORT_ISCSI)
10034                 proto = SCSI_PROTO_ISCSI << 4;
10035         else
10036                 proto = SCSI_PROTO_SPI << 4;
10037         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10038
10039         /*
10040          * We're using a LUN association here.  i.e., this device ID is a
10041          * per-LUN identifier.
10042          */
10043         if (lun && lun->lun_devid) {
10044                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10045                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10046                     lun->lun_devid->len);
10047         }
10048
10049         /*
10050          * This is for the WWPN which is a port association.
10051          */
10052         if (port->port_devid) {
10053                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10054                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10055                     port->port_devid->len);
10056         }
10057
10058         /*
10059          * This is for the Relative Target Port(type 4h) identifier
10060          */
10061         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10062         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10063             SVPD_ID_TYPE_RELTARG;
10064         desc->length = 4;
10065         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10066         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10067             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10068
10069         /*
10070          * This is for the Target Port Group(type 5h) identifier
10071          */
10072         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10073         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10074             SVPD_ID_TYPE_TPORTGRP;
10075         desc->length = 4;
10076         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10077             &desc->identifier[2]);
10078         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10079             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10080
10081         /*
10082          * This is for the Target identifier
10083          */
10084         if (port->target_devid) {
10085                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10086         }
10087
10088         ctsio->scsi_status = SCSI_STATUS_OK;
10089         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10090         ctsio->be_move_done = ctl_config_move_done;
10091         ctl_datamove((union ctl_io *)ctsio);
10092
10093         return (CTL_RETVAL_COMPLETE);
10094 }
10095
10096 static int
10097 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10098 {
10099         struct ctl_softc *softc = control_softc;
10100         struct scsi_vpd_scsi_ports *sp;
10101         struct scsi_vpd_port_designation *pd;
10102         struct scsi_vpd_port_designation_cont *pdc;
10103         struct ctl_lun *lun;
10104         struct ctl_port *port;
10105         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10106         int num_target_port_groups, single;
10107
10108         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10109
10110         single = ctl_is_single;
10111         if (single)
10112                 num_target_port_groups = 1;
10113         else
10114                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10115         num_target_ports = 0;
10116         iid_len = 0;
10117         id_len = 0;
10118         mtx_lock(&softc->ctl_lock);
10119         STAILQ_FOREACH(port, &softc->port_list, links) {
10120                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10121                         continue;
10122                 if (lun != NULL &&
10123                     ctl_map_lun_back(port->targ_port, lun->lun) >=
10124                     CTL_MAX_LUNS)
10125                         continue;
10126                 num_target_ports++;
10127                 if (port->init_devid)
10128                         iid_len += port->init_devid->len;
10129                 if (port->port_devid)
10130                         id_len += port->port_devid->len;
10131         }
10132         mtx_unlock(&softc->ctl_lock);
10133
10134         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10135             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10136              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10137         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10138         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10139         ctsio->kern_sg_entries = 0;
10140
10141         if (data_len < alloc_len) {
10142                 ctsio->residual = alloc_len - data_len;
10143                 ctsio->kern_data_len = data_len;
10144                 ctsio->kern_total_len = data_len;
10145         } else {
10146                 ctsio->residual = 0;
10147                 ctsio->kern_data_len = alloc_len;
10148                 ctsio->kern_total_len = alloc_len;
10149         }
10150         ctsio->kern_data_resid = 0;
10151         ctsio->kern_rel_offset = 0;
10152         ctsio->kern_sg_entries = 0;
10153
10154         /*
10155          * The control device is always connected.  The disk device, on the
10156          * other hand, may not be online all the time.  Need to change this
10157          * to figure out whether the disk device is actually online or not.
10158          */
10159         if (lun != NULL)
10160                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10161                                   lun->be_lun->lun_type;
10162         else
10163                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10164
10165         sp->page_code = SVPD_SCSI_PORTS;
10166         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10167             sp->page_length);
10168         pd = &sp->design[0];
10169
10170         mtx_lock(&softc->ctl_lock);
10171         if (softc->flags & CTL_FLAG_MASTER_SHELF)
10172                 pg = 0;
10173         else
10174                 pg = 1;
10175         for (g = 0; g < num_target_port_groups; g++) {
10176                 STAILQ_FOREACH(port, &softc->port_list, links) {
10177                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10178                                 continue;
10179                         if (lun != NULL &&
10180                             ctl_map_lun_back(port->targ_port, lun->lun) >=
10181                             CTL_MAX_LUNS)
10182                                 continue;
10183                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10184                         scsi_ulto2b(p, pd->relative_port_id);
10185                         if (port->init_devid && g == pg) {
10186                                 iid_len = port->init_devid->len;
10187                                 memcpy(pd->initiator_transportid,
10188                                     port->init_devid->data, port->init_devid->len);
10189                         } else
10190                                 iid_len = 0;
10191                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10192                         pdc = (struct scsi_vpd_port_designation_cont *)
10193                             (&pd->initiator_transportid[iid_len]);
10194                         if (port->port_devid && g == pg) {
10195                                 id_len = port->port_devid->len;
10196                                 memcpy(pdc->target_port_descriptors,
10197                                     port->port_devid->data, port->port_devid->len);
10198                         } else
10199                                 id_len = 0;
10200                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10201                         pd = (struct scsi_vpd_port_designation *)
10202                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10203                 }
10204         }
10205         mtx_unlock(&softc->ctl_lock);
10206
10207         ctsio->scsi_status = SCSI_STATUS_OK;
10208         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10209         ctsio->be_move_done = ctl_config_move_done;
10210         ctl_datamove((union ctl_io *)ctsio);
10211
10212         return (CTL_RETVAL_COMPLETE);
10213 }
10214
10215 static int
10216 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10217 {
10218         struct scsi_vpd_block_limits *bl_ptr;
10219         struct ctl_lun *lun;
10220         int bs;
10221
10222         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10223
10224         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10225         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10226         ctsio->kern_sg_entries = 0;
10227
10228         if (sizeof(*bl_ptr) < alloc_len) {
10229                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10230                 ctsio->kern_data_len = sizeof(*bl_ptr);
10231                 ctsio->kern_total_len = sizeof(*bl_ptr);
10232         } else {
10233                 ctsio->residual = 0;
10234                 ctsio->kern_data_len = alloc_len;
10235                 ctsio->kern_total_len = alloc_len;
10236         }
10237         ctsio->kern_data_resid = 0;
10238         ctsio->kern_rel_offset = 0;
10239         ctsio->kern_sg_entries = 0;
10240
10241         /*
10242          * The control device is always connected.  The disk device, on the
10243          * other hand, may not be online all the time.  Need to change this
10244          * to figure out whether the disk device is actually online or not.
10245          */
10246         if (lun != NULL)
10247                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10248                                   lun->be_lun->lun_type;
10249         else
10250                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10251
10252         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10253         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10254         bl_ptr->max_cmp_write_len = 0xff;
10255         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10256         if (lun != NULL) {
10257                 bs = lun->be_lun->blocksize;
10258                 scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10259                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10260                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10261                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10262                         if (lun->be_lun->pblockexp != 0) {
10263                                 scsi_ulto4b((1 << lun->be_lun->pblockexp),
10264                                     bl_ptr->opt_unmap_grain);
10265                                 scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10266                                     bl_ptr->unmap_grain_align);
10267                         }
10268                 }
10269                 scsi_ulto4b(lun->be_lun->atomicblock,
10270                     bl_ptr->max_atomic_transfer_length);
10271                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10272                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10273         }
10274         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10275
10276         ctsio->scsi_status = SCSI_STATUS_OK;
10277         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10278         ctsio->be_move_done = ctl_config_move_done;
10279         ctl_datamove((union ctl_io *)ctsio);
10280
10281         return (CTL_RETVAL_COMPLETE);
10282 }
10283
10284 static int
10285 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10286 {
10287         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10288         struct ctl_lun *lun;
10289
10290         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10291
10292         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10293         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10294         ctsio->kern_sg_entries = 0;
10295
10296         if (sizeof(*bdc_ptr) < alloc_len) {
10297                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10298                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10299                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10300         } else {
10301                 ctsio->residual = 0;
10302                 ctsio->kern_data_len = alloc_len;
10303                 ctsio->kern_total_len = alloc_len;
10304         }
10305         ctsio->kern_data_resid = 0;
10306         ctsio->kern_rel_offset = 0;
10307         ctsio->kern_sg_entries = 0;
10308
10309         /*
10310          * The control device is always connected.  The disk device, on the
10311          * other hand, may not be online all the time.  Need to change this
10312          * to figure out whether the disk device is actually online or not.
10313          */
10314         if (lun != NULL)
10315                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10316                                   lun->be_lun->lun_type;
10317         else
10318                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10319         bdc_ptr->page_code = SVPD_BDC;
10320         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10321         scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10322         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10323
10324         ctsio->scsi_status = SCSI_STATUS_OK;
10325         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10326         ctsio->be_move_done = ctl_config_move_done;
10327         ctl_datamove((union ctl_io *)ctsio);
10328
10329         return (CTL_RETVAL_COMPLETE);
10330 }
10331
10332 static int
10333 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10334 {
10335         struct scsi_vpd_logical_block_prov *lbp_ptr;
10336         struct ctl_lun *lun;
10337
10338         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10339
10340         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10341         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10342         ctsio->kern_sg_entries = 0;
10343
10344         if (sizeof(*lbp_ptr) < alloc_len) {
10345                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10346                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10347                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10348         } else {
10349                 ctsio->residual = 0;
10350                 ctsio->kern_data_len = alloc_len;
10351                 ctsio->kern_total_len = alloc_len;
10352         }
10353         ctsio->kern_data_resid = 0;
10354         ctsio->kern_rel_offset = 0;
10355         ctsio->kern_sg_entries = 0;
10356
10357         /*
10358          * The control device is always connected.  The disk device, on the
10359          * other hand, may not be online all the time.  Need to change this
10360          * to figure out whether the disk device is actually online or not.
10361          */
10362         if (lun != NULL)
10363                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10364                                   lun->be_lun->lun_type;
10365         else
10366                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10367
10368         lbp_ptr->page_code = SVPD_LBP;
10369         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10370         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10371                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10372                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10373                 lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10374         }
10375
10376         ctsio->scsi_status = SCSI_STATUS_OK;
10377         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10378         ctsio->be_move_done = ctl_config_move_done;
10379         ctl_datamove((union ctl_io *)ctsio);
10380
10381         return (CTL_RETVAL_COMPLETE);
10382 }
10383
10384 static int
10385 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10386 {
10387         struct scsi_inquiry *cdb;
10388         struct ctl_lun *lun;
10389         int alloc_len, retval;
10390
10391         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10392         cdb = (struct scsi_inquiry *)ctsio->cdb;
10393
10394         retval = CTL_RETVAL_COMPLETE;
10395
10396         alloc_len = scsi_2btoul(cdb->length);
10397
10398         switch (cdb->page_code) {
10399         case SVPD_SUPPORTED_PAGES:
10400                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10401                 break;
10402         case SVPD_UNIT_SERIAL_NUMBER:
10403                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10404                 break;
10405         case SVPD_DEVICE_ID:
10406                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10407                 break;
10408         case SVPD_EXTENDED_INQUIRY_DATA:
10409                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10410                 break;
10411         case SVPD_MODE_PAGE_POLICY:
10412                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10413                 break;
10414         case SVPD_SCSI_PORTS:
10415                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10416                 break;
10417         case SVPD_SCSI_TPC:
10418                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10419                 break;
10420         case SVPD_BLOCK_LIMITS:
10421                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10422                 break;
10423         case SVPD_BDC:
10424                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10425                 break;
10426         case SVPD_LBP:
10427                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10428                 break;
10429         default:
10430                 ctl_set_invalid_field(ctsio,
10431                                       /*sks_valid*/ 1,
10432                                       /*command*/ 1,
10433                                       /*field*/ 2,
10434                                       /*bit_valid*/ 0,
10435                                       /*bit*/ 0);
10436                 ctl_done((union ctl_io *)ctsio);
10437                 retval = CTL_RETVAL_COMPLETE;
10438                 break;
10439         }
10440
10441         return (retval);
10442 }
10443
10444 static int
10445 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10446 {
10447         struct scsi_inquiry_data *inq_ptr;
10448         struct scsi_inquiry *cdb;
10449         struct ctl_softc *ctl_softc;
10450         struct ctl_lun *lun;
10451         char *val;
10452         uint32_t alloc_len, data_len;
10453         ctl_port_type port_type;
10454
10455         ctl_softc = control_softc;
10456
10457         /*
10458          * Figure out whether we're talking to a Fibre Channel port or not.
10459          * We treat the ioctl front end, and any SCSI adapters, as packetized
10460          * SCSI front ends.
10461          */
10462         port_type = ctl_softc->ctl_ports[
10463             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10464         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10465                 port_type = CTL_PORT_SCSI;
10466
10467         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10468         cdb = (struct scsi_inquiry *)ctsio->cdb;
10469         alloc_len = scsi_2btoul(cdb->length);
10470
10471         /*
10472          * We malloc the full inquiry data size here and fill it
10473          * in.  If the user only asks for less, we'll give him
10474          * that much.
10475          */
10476         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10477         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10478         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10479         ctsio->kern_sg_entries = 0;
10480         ctsio->kern_data_resid = 0;
10481         ctsio->kern_rel_offset = 0;
10482
10483         if (data_len < alloc_len) {
10484                 ctsio->residual = alloc_len - data_len;
10485                 ctsio->kern_data_len = data_len;
10486                 ctsio->kern_total_len = data_len;
10487         } else {
10488                 ctsio->residual = 0;
10489                 ctsio->kern_data_len = alloc_len;
10490                 ctsio->kern_total_len = alloc_len;
10491         }
10492
10493         /*
10494          * If we have a LUN configured, report it as connected.  Otherwise,
10495          * report that it is offline or no device is supported, depending 
10496          * on the value of inquiry_pq_no_lun.
10497          *
10498          * According to the spec (SPC-4 r34), the peripheral qualifier
10499          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10500          *
10501          * "A peripheral device having the specified peripheral device type 
10502          * is not connected to this logical unit. However, the device
10503          * server is capable of supporting the specified peripheral device
10504          * type on this logical unit."
10505          *
10506          * According to the same spec, the peripheral qualifier
10507          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10508          *
10509          * "The device server is not capable of supporting a peripheral
10510          * device on this logical unit. For this peripheral qualifier the
10511          * peripheral device type shall be set to 1Fh. All other peripheral
10512          * device type values are reserved for this peripheral qualifier."
10513          *
10514          * Given the text, it would seem that we probably want to report that
10515          * the LUN is offline here.  There is no LUN connected, but we can
10516          * support a LUN at the given LUN number.
10517          *
10518          * In the real world, though, it sounds like things are a little
10519          * different:
10520          *
10521          * - Linux, when presented with a LUN with the offline peripheral
10522          *   qualifier, will create an sg driver instance for it.  So when
10523          *   you attach it to CTL, you wind up with a ton of sg driver
10524          *   instances.  (One for every LUN that Linux bothered to probe.)
10525          *   Linux does this despite the fact that it issues a REPORT LUNs
10526          *   to LUN 0 to get the inventory of supported LUNs.
10527          *
10528          * - There is other anecdotal evidence (from Emulex folks) about
10529          *   arrays that use the offline peripheral qualifier for LUNs that
10530          *   are on the "passive" path in an active/passive array.
10531          *
10532          * So the solution is provide a hopefully reasonable default
10533          * (return bad/no LUN) and allow the user to change the behavior
10534          * with a tunable/sysctl variable.
10535          */
10536         if (lun != NULL)
10537                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10538                                   lun->be_lun->lun_type;
10539         else if (ctl_softc->inquiry_pq_no_lun == 0)
10540                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10541         else
10542                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10543
10544         /* RMB in byte 2 is 0 */
10545         inq_ptr->version = SCSI_REV_SPC4;
10546
10547         /*
10548          * According to SAM-3, even if a device only supports a single
10549          * level of LUN addressing, it should still set the HISUP bit:
10550          *
10551          * 4.9.1 Logical unit numbers overview
10552          *
10553          * All logical unit number formats described in this standard are
10554          * hierarchical in structure even when only a single level in that
10555          * hierarchy is used. The HISUP bit shall be set to one in the
10556          * standard INQUIRY data (see SPC-2) when any logical unit number
10557          * format described in this standard is used.  Non-hierarchical
10558          * formats are outside the scope of this standard.
10559          *
10560          * Therefore we set the HiSup bit here.
10561          *
10562          * The reponse format is 2, per SPC-3.
10563          */
10564         inq_ptr->response_format = SID_HiSup | 2;
10565
10566         inq_ptr->additional_length = data_len -
10567             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10568         CTL_DEBUG_PRINT(("additional_length = %d\n",
10569                          inq_ptr->additional_length));
10570
10571         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10572         /* 16 bit addressing */
10573         if (port_type == CTL_PORT_SCSI)
10574                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10575         /* XXX set the SID_MultiP bit here if we're actually going to
10576            respond on multiple ports */
10577         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10578
10579         /* 16 bit data bus, synchronous transfers */
10580         if (port_type == CTL_PORT_SCSI)
10581                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10582         /*
10583          * XXX KDM do we want to support tagged queueing on the control
10584          * device at all?
10585          */
10586         if ((lun == NULL)
10587          || (lun->be_lun->lun_type != T_PROCESSOR))
10588                 inq_ptr->flags |= SID_CmdQue;
10589         /*
10590          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10591          * We have 8 bytes for the vendor name, and 16 bytes for the device
10592          * name and 4 bytes for the revision.
10593          */
10594         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10595             "vendor")) == NULL) {
10596                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10597         } else {
10598                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10599                 strncpy(inq_ptr->vendor, val,
10600                     min(sizeof(inq_ptr->vendor), strlen(val)));
10601         }
10602         if (lun == NULL) {
10603                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10604                     sizeof(inq_ptr->product));
10605         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10606                 switch (lun->be_lun->lun_type) {
10607                 case T_DIRECT:
10608                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10609                             sizeof(inq_ptr->product));
10610                         break;
10611                 case T_PROCESSOR:
10612                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10613                             sizeof(inq_ptr->product));
10614                         break;
10615                 default:
10616                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10617                             sizeof(inq_ptr->product));
10618                         break;
10619                 }
10620         } else {
10621                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10622                 strncpy(inq_ptr->product, val,
10623                     min(sizeof(inq_ptr->product), strlen(val)));
10624         }
10625
10626         /*
10627          * XXX make this a macro somewhere so it automatically gets
10628          * incremented when we make changes.
10629          */
10630         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10631             "revision")) == NULL) {
10632                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10633         } else {
10634                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10635                 strncpy(inq_ptr->revision, val,
10636                     min(sizeof(inq_ptr->revision), strlen(val)));
10637         }
10638
10639         /*
10640          * For parallel SCSI, we support double transition and single
10641          * transition clocking.  We also support QAS (Quick Arbitration
10642          * and Selection) and Information Unit transfers on both the
10643          * control and array devices.
10644          */
10645         if (port_type == CTL_PORT_SCSI)
10646                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10647                                     SID_SPI_IUS;
10648
10649         /* SAM-5 (no version claimed) */
10650         scsi_ulto2b(0x00A0, inq_ptr->version1);
10651         /* SPC-4 (no version claimed) */
10652         scsi_ulto2b(0x0460, inq_ptr->version2);
10653         if (port_type == CTL_PORT_FC) {
10654                 /* FCP-2 ANSI INCITS.350:2003 */
10655                 scsi_ulto2b(0x0917, inq_ptr->version3);
10656         } else if (port_type == CTL_PORT_SCSI) {
10657                 /* SPI-4 ANSI INCITS.362:200x */
10658                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10659         } else if (port_type == CTL_PORT_ISCSI) {
10660                 /* iSCSI (no version claimed) */
10661                 scsi_ulto2b(0x0960, inq_ptr->version3);
10662         } else if (port_type == CTL_PORT_SAS) {
10663                 /* SAS (no version claimed) */
10664                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10665         }
10666
10667         if (lun == NULL) {
10668                 /* SBC-4 (no version claimed) */
10669                 scsi_ulto2b(0x0600, inq_ptr->version4);
10670         } else {
10671                 switch (lun->be_lun->lun_type) {
10672                 case T_DIRECT:
10673                         /* SBC-4 (no version claimed) */
10674                         scsi_ulto2b(0x0600, inq_ptr->version4);
10675                         break;
10676                 case T_PROCESSOR:
10677                 default:
10678                         break;
10679                 }
10680         }
10681
10682         ctsio->scsi_status = SCSI_STATUS_OK;
10683         if (ctsio->kern_data_len > 0) {
10684                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10685                 ctsio->be_move_done = ctl_config_move_done;
10686                 ctl_datamove((union ctl_io *)ctsio);
10687         } else {
10688                 ctsio->io_hdr.status = CTL_SUCCESS;
10689                 ctl_done((union ctl_io *)ctsio);
10690         }
10691
10692         return (CTL_RETVAL_COMPLETE);
10693 }
10694
10695 int
10696 ctl_inquiry(struct ctl_scsiio *ctsio)
10697 {
10698         struct scsi_inquiry *cdb;
10699         int retval;
10700
10701         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10702
10703         cdb = (struct scsi_inquiry *)ctsio->cdb;
10704         if (cdb->byte2 & SI_EVPD)
10705                 retval = ctl_inquiry_evpd(ctsio);
10706         else if (cdb->page_code == 0)
10707                 retval = ctl_inquiry_std(ctsio);
10708         else {
10709                 ctl_set_invalid_field(ctsio,
10710                                       /*sks_valid*/ 1,
10711                                       /*command*/ 1,
10712                                       /*field*/ 2,
10713                                       /*bit_valid*/ 0,
10714                                       /*bit*/ 0);
10715                 ctl_done((union ctl_io *)ctsio);
10716                 return (CTL_RETVAL_COMPLETE);
10717         }
10718
10719         return (retval);
10720 }
10721
10722 /*
10723  * For known CDB types, parse the LBA and length.
10724  */
10725 static int
10726 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10727 {
10728         if (io->io_hdr.io_type != CTL_IO_SCSI)
10729                 return (1);
10730
10731         switch (io->scsiio.cdb[0]) {
10732         case COMPARE_AND_WRITE: {
10733                 struct scsi_compare_and_write *cdb;
10734
10735                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10736
10737                 *lba = scsi_8btou64(cdb->addr);
10738                 *len = cdb->length;
10739                 break;
10740         }
10741         case READ_6:
10742         case WRITE_6: {
10743                 struct scsi_rw_6 *cdb;
10744
10745                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10746
10747                 *lba = scsi_3btoul(cdb->addr);
10748                 /* only 5 bits are valid in the most significant address byte */
10749                 *lba &= 0x1fffff;
10750                 *len = cdb->length;
10751                 break;
10752         }
10753         case READ_10:
10754         case WRITE_10: {
10755                 struct scsi_rw_10 *cdb;
10756
10757                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10758
10759                 *lba = scsi_4btoul(cdb->addr);
10760                 *len = scsi_2btoul(cdb->length);
10761                 break;
10762         }
10763         case WRITE_VERIFY_10: {
10764                 struct scsi_write_verify_10 *cdb;
10765
10766                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10767
10768                 *lba = scsi_4btoul(cdb->addr);
10769                 *len = scsi_2btoul(cdb->length);
10770                 break;
10771         }
10772         case READ_12:
10773         case WRITE_12: {
10774                 struct scsi_rw_12 *cdb;
10775
10776                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10777
10778                 *lba = scsi_4btoul(cdb->addr);
10779                 *len = scsi_4btoul(cdb->length);
10780                 break;
10781         }
10782         case WRITE_VERIFY_12: {
10783                 struct scsi_write_verify_12 *cdb;
10784
10785                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10786
10787                 *lba = scsi_4btoul(cdb->addr);
10788                 *len = scsi_4btoul(cdb->length);
10789                 break;
10790         }
10791         case READ_16:
10792         case WRITE_16:
10793         case WRITE_ATOMIC_16: {
10794                 struct scsi_rw_16 *cdb;
10795
10796                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10797
10798                 *lba = scsi_8btou64(cdb->addr);
10799                 *len = scsi_4btoul(cdb->length);
10800                 break;
10801         }
10802         case WRITE_VERIFY_16: {
10803                 struct scsi_write_verify_16 *cdb;
10804
10805                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10806
10807                 *lba = scsi_8btou64(cdb->addr);
10808                 *len = scsi_4btoul(cdb->length);
10809                 break;
10810         }
10811         case WRITE_SAME_10: {
10812                 struct scsi_write_same_10 *cdb;
10813
10814                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10815
10816                 *lba = scsi_4btoul(cdb->addr);
10817                 *len = scsi_2btoul(cdb->length);
10818                 break;
10819         }
10820         case WRITE_SAME_16: {
10821                 struct scsi_write_same_16 *cdb;
10822
10823                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10824
10825                 *lba = scsi_8btou64(cdb->addr);
10826                 *len = scsi_4btoul(cdb->length);
10827                 break;
10828         }
10829         case VERIFY_10: {
10830                 struct scsi_verify_10 *cdb;
10831
10832                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10833
10834                 *lba = scsi_4btoul(cdb->addr);
10835                 *len = scsi_2btoul(cdb->length);
10836                 break;
10837         }
10838         case VERIFY_12: {
10839                 struct scsi_verify_12 *cdb;
10840
10841                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10842
10843                 *lba = scsi_4btoul(cdb->addr);
10844                 *len = scsi_4btoul(cdb->length);
10845                 break;
10846         }
10847         case VERIFY_16: {
10848                 struct scsi_verify_16 *cdb;
10849
10850                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10851
10852                 *lba = scsi_8btou64(cdb->addr);
10853                 *len = scsi_4btoul(cdb->length);
10854                 break;
10855         }
10856         case UNMAP: {
10857                 *lba = 0;
10858                 *len = UINT64_MAX;
10859                 break;
10860         }
10861         default:
10862                 return (1);
10863                 break; /* NOTREACHED */
10864         }
10865
10866         return (0);
10867 }
10868
10869 static ctl_action
10870 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10871 {
10872         uint64_t endlba1, endlba2;
10873
10874         endlba1 = lba1 + len1 - 1;
10875         endlba2 = lba2 + len2 - 1;
10876
10877         if ((endlba1 < lba2)
10878          || (endlba2 < lba1))
10879                 return (CTL_ACTION_PASS);
10880         else
10881                 return (CTL_ACTION_BLOCK);
10882 }
10883
10884 static int
10885 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10886 {
10887         struct ctl_ptr_len_flags *ptrlen;
10888         struct scsi_unmap_desc *buf, *end, *range;
10889         uint64_t lba;
10890         uint32_t len;
10891
10892         /* If not UNMAP -- go other way. */
10893         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10894             io->scsiio.cdb[0] != UNMAP)
10895                 return (CTL_ACTION_ERROR);
10896
10897         /* If UNMAP without data -- block and wait for data. */
10898         ptrlen = (struct ctl_ptr_len_flags *)
10899             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10900         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10901             ptrlen->ptr == NULL)
10902                 return (CTL_ACTION_BLOCK);
10903
10904         /* UNMAP with data -- check for collision. */
10905         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10906         end = buf + ptrlen->len / sizeof(*buf);
10907         for (range = buf; range < end; range++) {
10908                 lba = scsi_8btou64(range->lba);
10909                 len = scsi_4btoul(range->length);
10910                 if ((lba < lba2 + len2) && (lba + len > lba2))
10911                         return (CTL_ACTION_BLOCK);
10912         }
10913         return (CTL_ACTION_PASS);
10914 }
10915
10916 static ctl_action
10917 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10918 {
10919         uint64_t lba1, lba2;
10920         uint64_t len1, len2;
10921         int retval;
10922
10923         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10924                 return (CTL_ACTION_ERROR);
10925
10926         retval = ctl_extent_check_unmap(io2, lba1, len1);
10927         if (retval != CTL_ACTION_ERROR)
10928                 return (retval);
10929
10930         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10931                 return (CTL_ACTION_ERROR);
10932
10933         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10934 }
10935
10936 static ctl_action
10937 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10938     union ctl_io *ooa_io)
10939 {
10940         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10941         ctl_serialize_action *serialize_row;
10942
10943         /*
10944          * The initiator attempted multiple untagged commands at the same
10945          * time.  Can't do that.
10946          */
10947         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10948          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10949          && ((pending_io->io_hdr.nexus.targ_port ==
10950               ooa_io->io_hdr.nexus.targ_port)
10951           && (pending_io->io_hdr.nexus.initid.id ==
10952               ooa_io->io_hdr.nexus.initid.id))
10953          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10954                 return (CTL_ACTION_OVERLAP);
10955
10956         /*
10957          * The initiator attempted to send multiple tagged commands with
10958          * the same ID.  (It's fine if different initiators have the same
10959          * tag ID.)
10960          *
10961          * Even if all of those conditions are true, we don't kill the I/O
10962          * if the command ahead of us has been aborted.  We won't end up
10963          * sending it to the FETD, and it's perfectly legal to resend a
10964          * command with the same tag number as long as the previous
10965          * instance of this tag number has been aborted somehow.
10966          */
10967         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10968          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10969          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10970          && ((pending_io->io_hdr.nexus.targ_port ==
10971               ooa_io->io_hdr.nexus.targ_port)
10972           && (pending_io->io_hdr.nexus.initid.id ==
10973               ooa_io->io_hdr.nexus.initid.id))
10974          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10975                 return (CTL_ACTION_OVERLAP_TAG);
10976
10977         /*
10978          * If we get a head of queue tag, SAM-3 says that we should
10979          * immediately execute it.
10980          *
10981          * What happens if this command would normally block for some other
10982          * reason?  e.g. a request sense with a head of queue tag
10983          * immediately after a write.  Normally that would block, but this
10984          * will result in its getting executed immediately...
10985          *
10986          * We currently return "pass" instead of "skip", so we'll end up
10987          * going through the rest of the queue to check for overlapped tags.
10988          *
10989          * XXX KDM check for other types of blockage first??
10990          */
10991         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10992                 return (CTL_ACTION_PASS);
10993
10994         /*
10995          * Ordered tags have to block until all items ahead of them
10996          * have completed.  If we get called with an ordered tag, we always
10997          * block, if something else is ahead of us in the queue.
10998          */
10999         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11000                 return (CTL_ACTION_BLOCK);
11001
11002         /*
11003          * Simple tags get blocked until all head of queue and ordered tags
11004          * ahead of them have completed.  I'm lumping untagged commands in
11005          * with simple tags here.  XXX KDM is that the right thing to do?
11006          */
11007         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11008           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11009          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11010           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11011                 return (CTL_ACTION_BLOCK);
11012
11013         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11014         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11015
11016         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11017
11018         switch (serialize_row[pending_entry->seridx]) {
11019         case CTL_SER_BLOCK:
11020                 return (CTL_ACTION_BLOCK);
11021         case CTL_SER_EXTENT:
11022                 return (ctl_extent_check(pending_io, ooa_io));
11023         case CTL_SER_EXTENTOPT:
11024                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11025                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11026                         return (ctl_extent_check(pending_io, ooa_io));
11027                 /* FALLTHROUGH */
11028         case CTL_SER_PASS:
11029                 return (CTL_ACTION_PASS);
11030         case CTL_SER_BLOCKOPT:
11031                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11032                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11033                         return (CTL_ACTION_BLOCK);
11034                 return (CTL_ACTION_PASS);
11035         case CTL_SER_SKIP:
11036                 return (CTL_ACTION_SKIP);
11037         default:
11038                 panic("invalid serialization value %d",
11039                       serialize_row[pending_entry->seridx]);
11040         }
11041
11042         return (CTL_ACTION_ERROR);
11043 }
11044
11045 /*
11046  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11047  * Assumptions:
11048  * - pending_io is generally either incoming, or on the blocked queue
11049  * - starting I/O is the I/O we want to start the check with.
11050  */
11051 static ctl_action
11052 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11053               union ctl_io *starting_io)
11054 {
11055         union ctl_io *ooa_io;
11056         ctl_action action;
11057
11058         mtx_assert(&lun->lun_lock, MA_OWNED);
11059
11060         /*
11061          * Run back along the OOA queue, starting with the current
11062          * blocked I/O and going through every I/O before it on the
11063          * queue.  If starting_io is NULL, we'll just end up returning
11064          * CTL_ACTION_PASS.
11065          */
11066         for (ooa_io = starting_io; ooa_io != NULL;
11067              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11068              ooa_links)){
11069
11070                 /*
11071                  * This routine just checks to see whether
11072                  * cur_blocked is blocked by ooa_io, which is ahead
11073                  * of it in the queue.  It doesn't queue/dequeue
11074                  * cur_blocked.
11075                  */
11076                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11077                 switch (action) {
11078                 case CTL_ACTION_BLOCK:
11079                 case CTL_ACTION_OVERLAP:
11080                 case CTL_ACTION_OVERLAP_TAG:
11081                 case CTL_ACTION_SKIP:
11082                 case CTL_ACTION_ERROR:
11083                         return (action);
11084                         break; /* NOTREACHED */
11085                 case CTL_ACTION_PASS:
11086                         break;
11087                 default:
11088                         panic("invalid action %d", action);
11089                         break;  /* NOTREACHED */
11090                 }
11091         }
11092
11093         return (CTL_ACTION_PASS);
11094 }
11095
11096 /*
11097  * Assumptions:
11098  * - An I/O has just completed, and has been removed from the per-LUN OOA
11099  *   queue, so some items on the blocked queue may now be unblocked.
11100  */
11101 static int
11102 ctl_check_blocked(struct ctl_lun *lun)
11103 {
11104         union ctl_io *cur_blocked, *next_blocked;
11105
11106         mtx_assert(&lun->lun_lock, MA_OWNED);
11107
11108         /*
11109          * Run forward from the head of the blocked queue, checking each
11110          * entry against the I/Os prior to it on the OOA queue to see if
11111          * there is still any blockage.
11112          *
11113          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11114          * with our removing a variable on it while it is traversing the
11115          * list.
11116          */
11117         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11118              cur_blocked != NULL; cur_blocked = next_blocked) {
11119                 union ctl_io *prev_ooa;
11120                 ctl_action action;
11121
11122                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11123                                                           blocked_links);
11124
11125                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11126                                                       ctl_ooaq, ooa_links);
11127
11128                 /*
11129                  * If cur_blocked happens to be the first item in the OOA
11130                  * queue now, prev_ooa will be NULL, and the action
11131                  * returned will just be CTL_ACTION_PASS.
11132                  */
11133                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11134
11135                 switch (action) {
11136                 case CTL_ACTION_BLOCK:
11137                         /* Nothing to do here, still blocked */
11138                         break;
11139                 case CTL_ACTION_OVERLAP:
11140                 case CTL_ACTION_OVERLAP_TAG:
11141                         /*
11142                          * This shouldn't happen!  In theory we've already
11143                          * checked this command for overlap...
11144                          */
11145                         break;
11146                 case CTL_ACTION_PASS:
11147                 case CTL_ACTION_SKIP: {
11148                         struct ctl_softc *softc;
11149                         const struct ctl_cmd_entry *entry;
11150                         uint32_t initidx;
11151                         int isc_retval;
11152
11153                         /*
11154                          * The skip case shouldn't happen, this transaction
11155                          * should have never made it onto the blocked queue.
11156                          */
11157                         /*
11158                          * This I/O is no longer blocked, we can remove it
11159                          * from the blocked queue.  Since this is a TAILQ
11160                          * (doubly linked list), we can do O(1) removals
11161                          * from any place on the list.
11162                          */
11163                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11164                                      blocked_links);
11165                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11166
11167                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11168                                 /*
11169                                  * Need to send IO back to original side to
11170                                  * run
11171                                  */
11172                                 union ctl_ha_msg msg_info;
11173
11174                                 msg_info.hdr.original_sc =
11175                                         cur_blocked->io_hdr.original_sc;
11176                                 msg_info.hdr.serializing_sc = cur_blocked;
11177                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11178                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11179                                      &msg_info, sizeof(msg_info), 0)) >
11180                                      CTL_HA_STATUS_SUCCESS) {
11181                                         printf("CTL:Check Blocked error from "
11182                                                "ctl_ha_msg_send %d\n",
11183                                                isc_retval);
11184                                 }
11185                                 break;
11186                         }
11187                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11188                         softc = control_softc;
11189
11190                         initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11191
11192                         /*
11193                          * Check this I/O for LUN state changes that may
11194                          * have happened while this command was blocked.
11195                          * The LUN state may have been changed by a command
11196                          * ahead of us in the queue, so we need to re-check
11197                          * for any states that can be caused by SCSI
11198                          * commands.
11199                          */
11200                         if (ctl_scsiio_lun_check(softc, lun, entry,
11201                                                  &cur_blocked->scsiio) == 0) {
11202                                 cur_blocked->io_hdr.flags |=
11203                                                       CTL_FLAG_IS_WAS_ON_RTR;
11204                                 ctl_enqueue_rtr(cur_blocked);
11205                         } else
11206                                 ctl_done(cur_blocked);
11207                         break;
11208                 }
11209                 default:
11210                         /*
11211                          * This probably shouldn't happen -- we shouldn't
11212                          * get CTL_ACTION_ERROR, or anything else.
11213                          */
11214                         break;
11215                 }
11216         }
11217
11218         return (CTL_RETVAL_COMPLETE);
11219 }
11220
11221 /*
11222  * This routine (with one exception) checks LUN flags that can be set by
11223  * commands ahead of us in the OOA queue.  These flags have to be checked
11224  * when a command initially comes in, and when we pull a command off the
11225  * blocked queue and are preparing to execute it.  The reason we have to
11226  * check these flags for commands on the blocked queue is that the LUN
11227  * state may have been changed by a command ahead of us while we're on the
11228  * blocked queue.
11229  *
11230  * Ordering is somewhat important with these checks, so please pay
11231  * careful attention to the placement of any new checks.
11232  */
11233 static int
11234 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11235     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11236 {
11237         int retval;
11238         uint32_t residx;
11239
11240         retval = 0;
11241
11242         mtx_assert(&lun->lun_lock, MA_OWNED);
11243
11244         /*
11245          * If this shelf is a secondary shelf controller, we have to reject
11246          * any media access commands.
11247          */
11248 #if 0
11249         /* No longer needed for HA */
11250         if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11251          && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11252                 ctl_set_lun_standby(ctsio);
11253                 retval = 1;
11254                 goto bailout;
11255         }
11256 #endif
11257
11258         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11259                 if (lun->flags & CTL_LUN_READONLY) {
11260                         ctl_set_sense(ctsio, /*current_error*/ 1,
11261                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11262                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11263                         retval = 1;
11264                         goto bailout;
11265                 }
11266                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11267                     .eca_and_aen & SCP_SWP) != 0) {
11268                         ctl_set_sense(ctsio, /*current_error*/ 1,
11269                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11270                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11271                         retval = 1;
11272                         goto bailout;
11273                 }
11274         }
11275
11276         /*
11277          * Check for a reservation conflict.  If this command isn't allowed
11278          * even on reserved LUNs, and if this initiator isn't the one who
11279          * reserved us, reject the command with a reservation conflict.
11280          */
11281         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11282         if ((lun->flags & CTL_LUN_RESERVED)
11283          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11284                 if (lun->res_idx != residx) {
11285                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11286                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11287                         retval = 1;
11288                         goto bailout;
11289                 }
11290         }
11291
11292         if ((lun->flags & CTL_LUN_PR_RESERVED)
11293          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11294                 /*
11295                  * if we aren't registered or it's a res holder type
11296                  * reservation and this isn't the res holder then set a
11297                  * conflict.
11298                  * NOTE: Commands which might be allowed on write exclusive
11299                  * type reservations are checked in the particular command
11300                  * for a conflict. Read and SSU are the only ones.
11301                  */
11302                 if (lun->pr_keys[residx] == 0
11303                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11304                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11305                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11306                         retval = 1;
11307                         goto bailout;
11308                 }
11309
11310         }
11311
11312         if ((lun->flags & CTL_LUN_OFFLINE)
11313          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11314                 ctl_set_lun_not_ready(ctsio);
11315                 retval = 1;
11316                 goto bailout;
11317         }
11318
11319         /*
11320          * If the LUN is stopped, see if this particular command is allowed
11321          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11322          */
11323         if ((lun->flags & CTL_LUN_STOPPED)
11324          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11325                 /* "Logical unit not ready, initializing cmd. required" */
11326                 ctl_set_lun_stopped(ctsio);
11327                 retval = 1;
11328                 goto bailout;
11329         }
11330
11331         if ((lun->flags & CTL_LUN_INOPERABLE)
11332          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11333                 /* "Medium format corrupted" */
11334                 ctl_set_medium_format_corrupted(ctsio);
11335                 retval = 1;
11336                 goto bailout;
11337         }
11338
11339 bailout:
11340         return (retval);
11341
11342 }
11343
11344 static void
11345 ctl_failover_io(union ctl_io *io, int have_lock)
11346 {
11347         ctl_set_busy(&io->scsiio);
11348         ctl_done(io);
11349 }
11350
11351 static void
11352 ctl_failover(void)
11353 {
11354         struct ctl_lun *lun;
11355         struct ctl_softc *ctl_softc;
11356         union ctl_io *next_io, *pending_io;
11357         union ctl_io *io;
11358         int lun_idx;
11359         int i;
11360
11361         ctl_softc = control_softc;
11362
11363         mtx_lock(&ctl_softc->ctl_lock);
11364         /*
11365          * Remove any cmds from the other SC from the rtr queue.  These
11366          * will obviously only be for LUNs for which we're the primary.
11367          * We can't send status or get/send data for these commands.
11368          * Since they haven't been executed yet, we can just remove them.
11369          * We'll either abort them or delete them below, depending on
11370          * which HA mode we're in.
11371          */
11372 #ifdef notyet
11373         mtx_lock(&ctl_softc->queue_lock);
11374         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11375              io != NULL; io = next_io) {
11376                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11377                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11378                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11379                                       ctl_io_hdr, links);
11380         }
11381         mtx_unlock(&ctl_softc->queue_lock);
11382 #endif
11383
11384         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11385                 lun = ctl_softc->ctl_luns[lun_idx];
11386                 if (lun==NULL)
11387                         continue;
11388
11389                 /*
11390                  * Processor LUNs are primary on both sides.
11391                  * XXX will this always be true?
11392                  */
11393                 if (lun->be_lun->lun_type == T_PROCESSOR)
11394                         continue;
11395
11396                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11397                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11398                         printf("FAILOVER: primary lun %d\n", lun_idx);
11399                         /*
11400                          * Remove all commands from the other SC. First from the
11401                          * blocked queue then from the ooa queue. Once we have
11402                          * removed them. Call ctl_check_blocked to see if there
11403                          * is anything that can run.
11404                          */
11405                         for (io = (union ctl_io *)TAILQ_FIRST(
11406                              &lun->blocked_queue); io != NULL; io = next_io) {
11407
11408                                 next_io = (union ctl_io *)TAILQ_NEXT(
11409                                     &io->io_hdr, blocked_links);
11410
11411                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11412                                         TAILQ_REMOVE(&lun->blocked_queue,
11413                                                      &io->io_hdr,blocked_links);
11414                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11415                                         TAILQ_REMOVE(&lun->ooa_queue,
11416                                                      &io->io_hdr, ooa_links);
11417
11418                                         ctl_free_io(io);
11419                                 }
11420                         }
11421
11422                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11423                              io != NULL; io = next_io) {
11424
11425                                 next_io = (union ctl_io *)TAILQ_NEXT(
11426                                     &io->io_hdr, ooa_links);
11427
11428                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11429
11430                                         TAILQ_REMOVE(&lun->ooa_queue,
11431                                                 &io->io_hdr,
11432                                                 ooa_links);
11433
11434                                         ctl_free_io(io);
11435                                 }
11436                         }
11437                         ctl_check_blocked(lun);
11438                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11439                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11440
11441                         printf("FAILOVER: primary lun %d\n", lun_idx);
11442                         /*
11443                          * Abort all commands from the other SC.  We can't
11444                          * send status back for them now.  These should get
11445                          * cleaned up when they are completed or come out
11446                          * for a datamove operation.
11447                          */
11448                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11449                              io != NULL; io = next_io) {
11450                                 next_io = (union ctl_io *)TAILQ_NEXT(
11451                                         &io->io_hdr, ooa_links);
11452
11453                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11454                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11455                         }
11456                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11457                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11458
11459                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11460
11461                         lun->flags |= CTL_LUN_PRIMARY_SC;
11462
11463                         /*
11464                          * We send all I/O that was sent to this controller
11465                          * and redirected to the other side back with
11466                          * busy status, and have the initiator retry it.
11467                          * Figuring out how much data has been transferred,
11468                          * etc. and picking up where we left off would be 
11469                          * very tricky.
11470                          *
11471                          * XXX KDM need to remove I/O from the blocked
11472                          * queue as well!
11473                          */
11474                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11475                              &lun->ooa_queue); pending_io != NULL;
11476                              pending_io = next_io) {
11477
11478                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11479                                         &pending_io->io_hdr, ooa_links);
11480
11481                                 pending_io->io_hdr.flags &=
11482                                         ~CTL_FLAG_SENT_2OTHER_SC;
11483
11484                                 if (pending_io->io_hdr.flags &
11485                                     CTL_FLAG_IO_ACTIVE) {
11486                                         pending_io->io_hdr.flags |=
11487                                                 CTL_FLAG_FAILOVER;
11488                                 } else {
11489                                         ctl_set_busy(&pending_io->scsiio);
11490                                         ctl_done(pending_io);
11491                                 }
11492                         }
11493
11494                         /*
11495                          * Build Unit Attention
11496                          */
11497                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11498                                 lun->pending_ua[i] |=
11499                                                      CTL_UA_ASYM_ACC_CHANGE;
11500                         }
11501                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11502                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11503                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11504                         /*
11505                          * if the first io on the OOA is not on the RtR queue
11506                          * add it.
11507                          */
11508                         lun->flags |= CTL_LUN_PRIMARY_SC;
11509
11510                         pending_io = (union ctl_io *)TAILQ_FIRST(
11511                             &lun->ooa_queue);
11512                         if (pending_io==NULL) {
11513                                 printf("Nothing on OOA queue\n");
11514                                 continue;
11515                         }
11516
11517                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11518                         if ((pending_io->io_hdr.flags &
11519                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11520                                 pending_io->io_hdr.flags |=
11521                                     CTL_FLAG_IS_WAS_ON_RTR;
11522                                 ctl_enqueue_rtr(pending_io);
11523                         }
11524 #if 0
11525                         else
11526                         {
11527                                 printf("Tag 0x%04x is running\n",
11528                                       pending_io->scsiio.tag_num);
11529                         }
11530 #endif
11531
11532                         next_io = (union ctl_io *)TAILQ_NEXT(
11533                             &pending_io->io_hdr, ooa_links);
11534                         for (pending_io=next_io; pending_io != NULL;
11535                              pending_io = next_io) {
11536                                 pending_io->io_hdr.flags &=
11537                                     ~CTL_FLAG_SENT_2OTHER_SC;
11538                                 next_io = (union ctl_io *)TAILQ_NEXT(
11539                                         &pending_io->io_hdr, ooa_links);
11540                                 if (pending_io->io_hdr.flags &
11541                                     CTL_FLAG_IS_WAS_ON_RTR) {
11542 #if 0
11543                                         printf("Tag 0x%04x is running\n",
11544                                                 pending_io->scsiio.tag_num);
11545 #endif
11546                                         continue;
11547                                 }
11548
11549                                 switch (ctl_check_ooa(lun, pending_io,
11550                                     (union ctl_io *)TAILQ_PREV(
11551                                     &pending_io->io_hdr, ctl_ooaq,
11552                                     ooa_links))) {
11553
11554                                 case CTL_ACTION_BLOCK:
11555                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11556                                                           &pending_io->io_hdr,
11557                                                           blocked_links);
11558                                         pending_io->io_hdr.flags |=
11559                                             CTL_FLAG_BLOCKED;
11560                                         break;
11561                                 case CTL_ACTION_PASS:
11562                                 case CTL_ACTION_SKIP:
11563                                         pending_io->io_hdr.flags |=
11564                                             CTL_FLAG_IS_WAS_ON_RTR;
11565                                         ctl_enqueue_rtr(pending_io);
11566                                         break;
11567                                 case CTL_ACTION_OVERLAP:
11568                                         ctl_set_overlapped_cmd(
11569                                             (struct ctl_scsiio *)pending_io);
11570                                         ctl_done(pending_io);
11571                                         break;
11572                                 case CTL_ACTION_OVERLAP_TAG:
11573                                         ctl_set_overlapped_tag(
11574                                             (struct ctl_scsiio *)pending_io,
11575                                             pending_io->scsiio.tag_num & 0xff);
11576                                         ctl_done(pending_io);
11577                                         break;
11578                                 case CTL_ACTION_ERROR:
11579                                 default:
11580                                         ctl_set_internal_failure(
11581                                                 (struct ctl_scsiio *)pending_io,
11582                                                 0,  // sks_valid
11583                                                 0); //retry count
11584                                         ctl_done(pending_io);
11585                                         break;
11586                                 }
11587                         }
11588
11589                         /*
11590                          * Build Unit Attention
11591                          */
11592                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11593                                 lun->pending_ua[i] |=
11594                                                      CTL_UA_ASYM_ACC_CHANGE;
11595                         }
11596                 } else {
11597                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11598                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11599                 }
11600         }
11601         ctl_pause_rtr = 0;
11602         mtx_unlock(&ctl_softc->ctl_lock);
11603 }
11604
11605 static int
11606 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11607 {
11608         struct ctl_lun *lun;
11609         const struct ctl_cmd_entry *entry;
11610         uint32_t initidx, targ_lun;
11611         int retval;
11612
11613         retval = 0;
11614
11615         lun = NULL;
11616
11617         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11618         if ((targ_lun < CTL_MAX_LUNS)
11619          && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11620                 lun = ctl_softc->ctl_luns[targ_lun];
11621                 /*
11622                  * If the LUN is invalid, pretend that it doesn't exist.
11623                  * It will go away as soon as all pending I/O has been
11624                  * completed.
11625                  */
11626                 if (lun->flags & CTL_LUN_DISABLED) {
11627                         lun = NULL;
11628                 } else {
11629                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11630                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11631                                 lun->be_lun;
11632                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11633                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11634                         }
11635
11636                         /*
11637                          * Every I/O goes into the OOA queue for a
11638                          * particular LUN, and stays there until completion.
11639                          */
11640                         mtx_lock(&lun->lun_lock);
11641                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11642                             ooa_links);
11643                 }
11644         } else {
11645                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11646                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11647         }
11648
11649         /* Get command entry and return error if it is unsuppotyed. */
11650         entry = ctl_validate_command(ctsio);
11651         if (entry == NULL) {
11652                 if (lun)
11653                         mtx_unlock(&lun->lun_lock);
11654                 return (retval);
11655         }
11656
11657         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11658         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11659
11660         /*
11661          * Check to see whether we can send this command to LUNs that don't
11662          * exist.  This should pretty much only be the case for inquiry
11663          * and request sense.  Further checks, below, really require having
11664          * a LUN, so we can't really check the command anymore.  Just put
11665          * it on the rtr queue.
11666          */
11667         if (lun == NULL) {
11668                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11669                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11670                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11671                         return (retval);
11672                 }
11673
11674                 ctl_set_unsupported_lun(ctsio);
11675                 ctl_done((union ctl_io *)ctsio);
11676                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11677                 return (retval);
11678         } else {
11679                 /*
11680                  * Make sure we support this particular command on this LUN.
11681                  * e.g., we don't support writes to the control LUN.
11682                  */
11683                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11684                         mtx_unlock(&lun->lun_lock);
11685                         ctl_set_invalid_opcode(ctsio);
11686                         ctl_done((union ctl_io *)ctsio);
11687                         return (retval);
11688                 }
11689         }
11690
11691         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11692
11693 #ifdef CTL_WITH_CA
11694         /*
11695          * If we've got a request sense, it'll clear the contingent
11696          * allegiance condition.  Otherwise, if we have a CA condition for
11697          * this initiator, clear it, because it sent down a command other
11698          * than request sense.
11699          */
11700         if ((ctsio->cdb[0] != REQUEST_SENSE)
11701          && (ctl_is_set(lun->have_ca, initidx)))
11702                 ctl_clear_mask(lun->have_ca, initidx);
11703 #endif
11704
11705         /*
11706          * If the command has this flag set, it handles its own unit
11707          * attention reporting, we shouldn't do anything.  Otherwise we
11708          * check for any pending unit attentions, and send them back to the
11709          * initiator.  We only do this when a command initially comes in,
11710          * not when we pull it off the blocked queue.
11711          *
11712          * According to SAM-3, section 5.3.2, the order that things get
11713          * presented back to the host is basically unit attentions caused
11714          * by some sort of reset event, busy status, reservation conflicts
11715          * or task set full, and finally any other status.
11716          *
11717          * One issue here is that some of the unit attentions we report
11718          * don't fall into the "reset" category (e.g. "reported luns data
11719          * has changed").  So reporting it here, before the reservation
11720          * check, may be technically wrong.  I guess the only thing to do
11721          * would be to check for and report the reset events here, and then
11722          * check for the other unit attention types after we check for a
11723          * reservation conflict.
11724          *
11725          * XXX KDM need to fix this
11726          */
11727         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11728                 ctl_ua_type ua_type;
11729
11730                 if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11731                         scsi_sense_data_type sense_format;
11732
11733                         if (lun != NULL)
11734                                 sense_format = (lun->flags &
11735                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11736                                     SSD_TYPE_FIXED;
11737                         else
11738                                 sense_format = SSD_TYPE_FIXED;
11739
11740                         ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11741                             &ctsio->sense_data, sense_format);
11742                         if (ua_type != CTL_UA_NONE) {
11743                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11744                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11745                                                        CTL_AUTOSENSE;
11746                                 ctsio->sense_len = SSD_FULL_SIZE;
11747                                 mtx_unlock(&lun->lun_lock);
11748                                 ctl_done((union ctl_io *)ctsio);
11749                                 return (retval);
11750                         }
11751                 }
11752         }
11753
11754
11755         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11756                 mtx_unlock(&lun->lun_lock);
11757                 ctl_done((union ctl_io *)ctsio);
11758                 return (retval);
11759         }
11760
11761         /*
11762          * XXX CHD this is where we want to send IO to other side if
11763          * this LUN is secondary on this SC. We will need to make a copy
11764          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11765          * the copy we send as FROM_OTHER.
11766          * We also need to stuff the address of the original IO so we can
11767          * find it easily. Something similar will need be done on the other
11768          * side so when we are done we can find the copy.
11769          */
11770         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11771                 union ctl_ha_msg msg_info;
11772                 int isc_retval;
11773
11774                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11775
11776                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11777                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11778 #if 0
11779                 printf("1. ctsio %p\n", ctsio);
11780 #endif
11781                 msg_info.hdr.serializing_sc = NULL;
11782                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11783                 msg_info.scsi.tag_num = ctsio->tag_num;
11784                 msg_info.scsi.tag_type = ctsio->tag_type;
11785                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11786
11787                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11788
11789                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11790                     (void *)&msg_info, sizeof(msg_info), 0)) >
11791                     CTL_HA_STATUS_SUCCESS) {
11792                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11793                                isc_retval);
11794                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11795                 } else {
11796 #if 0
11797                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11798 #endif
11799                 }
11800
11801                 /*
11802                  * XXX KDM this I/O is off the incoming queue, but hasn't
11803                  * been inserted on any other queue.  We may need to come
11804                  * up with a holding queue while we wait for serialization
11805                  * so that we have an idea of what we're waiting for from
11806                  * the other side.
11807                  */
11808                 mtx_unlock(&lun->lun_lock);
11809                 return (retval);
11810         }
11811
11812         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11813                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11814                               ctl_ooaq, ooa_links))) {
11815         case CTL_ACTION_BLOCK:
11816                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11817                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11818                                   blocked_links);
11819                 mtx_unlock(&lun->lun_lock);
11820                 return (retval);
11821         case CTL_ACTION_PASS:
11822         case CTL_ACTION_SKIP:
11823                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11824                 mtx_unlock(&lun->lun_lock);
11825                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11826                 break;
11827         case CTL_ACTION_OVERLAP:
11828                 mtx_unlock(&lun->lun_lock);
11829                 ctl_set_overlapped_cmd(ctsio);
11830                 ctl_done((union ctl_io *)ctsio);
11831                 break;
11832         case CTL_ACTION_OVERLAP_TAG:
11833                 mtx_unlock(&lun->lun_lock);
11834                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11835                 ctl_done((union ctl_io *)ctsio);
11836                 break;
11837         case CTL_ACTION_ERROR:
11838         default:
11839                 mtx_unlock(&lun->lun_lock);
11840                 ctl_set_internal_failure(ctsio,
11841                                          /*sks_valid*/ 0,
11842                                          /*retry_count*/ 0);
11843                 ctl_done((union ctl_io *)ctsio);
11844                 break;
11845         }
11846         return (retval);
11847 }
11848
11849 const struct ctl_cmd_entry *
11850 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11851 {
11852         const struct ctl_cmd_entry *entry;
11853         int service_action;
11854
11855         entry = &ctl_cmd_table[ctsio->cdb[0]];
11856         if (sa)
11857                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11858         if (entry->flags & CTL_CMD_FLAG_SA5) {
11859                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11860                 entry = &((const struct ctl_cmd_entry *)
11861                     entry->execute)[service_action];
11862         }
11863         return (entry);
11864 }
11865
11866 const struct ctl_cmd_entry *
11867 ctl_validate_command(struct ctl_scsiio *ctsio)
11868 {
11869         const struct ctl_cmd_entry *entry;
11870         int i, sa;
11871         uint8_t diff;
11872
11873         entry = ctl_get_cmd_entry(ctsio, &sa);
11874         if (entry->execute == NULL) {
11875                 if (sa)
11876                         ctl_set_invalid_field(ctsio,
11877                                               /*sks_valid*/ 1,
11878                                               /*command*/ 1,
11879                                               /*field*/ 1,
11880                                               /*bit_valid*/ 1,
11881                                               /*bit*/ 4);
11882                 else
11883                         ctl_set_invalid_opcode(ctsio);
11884                 ctl_done((union ctl_io *)ctsio);
11885                 return (NULL);
11886         }
11887         KASSERT(entry->length > 0,
11888             ("Not defined length for command 0x%02x/0x%02x",
11889              ctsio->cdb[0], ctsio->cdb[1]));
11890         for (i = 1; i < entry->length; i++) {
11891                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11892                 if (diff == 0)
11893                         continue;
11894                 ctl_set_invalid_field(ctsio,
11895                                       /*sks_valid*/ 1,
11896                                       /*command*/ 1,
11897                                       /*field*/ i,
11898                                       /*bit_valid*/ 1,
11899                                       /*bit*/ fls(diff) - 1);
11900                 ctl_done((union ctl_io *)ctsio);
11901                 return (NULL);
11902         }
11903         return (entry);
11904 }
11905
11906 static int
11907 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11908 {
11909
11910         switch (lun_type) {
11911         case T_PROCESSOR:
11912                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11913                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11914                         return (0);
11915                 break;
11916         case T_DIRECT:
11917                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11918                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11919                         return (0);
11920                 break;
11921         default:
11922                 return (0);
11923         }
11924         return (1);
11925 }
11926
11927 static int
11928 ctl_scsiio(struct ctl_scsiio *ctsio)
11929 {
11930         int retval;
11931         const struct ctl_cmd_entry *entry;
11932
11933         retval = CTL_RETVAL_COMPLETE;
11934
11935         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11936
11937         entry = ctl_get_cmd_entry(ctsio, NULL);
11938
11939         /*
11940          * If this I/O has been aborted, just send it straight to
11941          * ctl_done() without executing it.
11942          */
11943         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11944                 ctl_done((union ctl_io *)ctsio);
11945                 goto bailout;
11946         }
11947
11948         /*
11949          * All the checks should have been handled by ctl_scsiio_precheck().
11950          * We should be clear now to just execute the I/O.
11951          */
11952         retval = entry->execute(ctsio);
11953
11954 bailout:
11955         return (retval);
11956 }
11957
11958 /*
11959  * Since we only implement one target right now, a bus reset simply resets
11960  * our single target.
11961  */
11962 static int
11963 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11964 {
11965         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11966 }
11967
11968 static int
11969 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11970                  ctl_ua_type ua_type)
11971 {
11972         struct ctl_lun *lun;
11973         int retval;
11974
11975         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11976                 union ctl_ha_msg msg_info;
11977
11978                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11979                 msg_info.hdr.nexus = io->io_hdr.nexus;
11980                 if (ua_type==CTL_UA_TARG_RESET)
11981                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11982                 else
11983                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11984                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11985                 msg_info.hdr.original_sc = NULL;
11986                 msg_info.hdr.serializing_sc = NULL;
11987                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11988                     (void *)&msg_info, sizeof(msg_info), 0)) {
11989                 }
11990         }
11991         retval = 0;
11992
11993         mtx_lock(&ctl_softc->ctl_lock);
11994         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11995                 retval += ctl_lun_reset(lun, io, ua_type);
11996         mtx_unlock(&ctl_softc->ctl_lock);
11997
11998         return (retval);
11999 }
12000
12001 /*
12002  * The LUN should always be set.  The I/O is optional, and is used to
12003  * distinguish between I/Os sent by this initiator, and by other
12004  * initiators.  We set unit attention for initiators other than this one.
12005  * SAM-3 is vague on this point.  It does say that a unit attention should
12006  * be established for other initiators when a LUN is reset (see section
12007  * 5.7.3), but it doesn't specifically say that the unit attention should
12008  * be established for this particular initiator when a LUN is reset.  Here
12009  * is the relevant text, from SAM-3 rev 8:
12010  *
12011  * 5.7.2 When a SCSI initiator port aborts its own tasks
12012  *
12013  * When a SCSI initiator port causes its own task(s) to be aborted, no
12014  * notification that the task(s) have been aborted shall be returned to
12015  * the SCSI initiator port other than the completion response for the
12016  * command or task management function action that caused the task(s) to
12017  * be aborted and notification(s) associated with related effects of the
12018  * action (e.g., a reset unit attention condition).
12019  *
12020  * XXX KDM for now, we're setting unit attention for all initiators.
12021  */
12022 static int
12023 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12024 {
12025         union ctl_io *xio;
12026 #if 0
12027         uint32_t initindex;
12028 #endif
12029         int i;
12030
12031         mtx_lock(&lun->lun_lock);
12032         /*
12033          * Run through the OOA queue and abort each I/O.
12034          */
12035 #if 0
12036         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12037 #endif
12038         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12039              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12040                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12041         }
12042
12043         /*
12044          * This version sets unit attention for every
12045          */
12046 #if 0
12047         initindex = ctl_get_initindex(&io->io_hdr.nexus);
12048         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12049                 if (initindex == i)
12050                         continue;
12051                 lun->pending_ua[i] |= ua_type;
12052         }
12053 #endif
12054
12055         /*
12056          * A reset (any kind, really) clears reservations established with
12057          * RESERVE/RELEASE.  It does not clear reservations established
12058          * with PERSISTENT RESERVE OUT, but we don't support that at the
12059          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12060          * reservations made with the RESERVE/RELEASE commands, because
12061          * those commands are obsolete in SPC-3.
12062          */
12063         lun->flags &= ~CTL_LUN_RESERVED;
12064
12065         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12066 #ifdef CTL_WITH_CA
12067                 ctl_clear_mask(lun->have_ca, i);
12068 #endif
12069                 lun->pending_ua[i] |= ua_type;
12070         }
12071         mtx_unlock(&lun->lun_lock);
12072
12073         return (0);
12074 }
12075
12076 static void
12077 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12078     int other_sc)
12079 {
12080         union ctl_io *xio;
12081
12082         mtx_assert(&lun->lun_lock, MA_OWNED);
12083
12084         /*
12085          * Run through the OOA queue and attempt to find the given I/O.
12086          * The target port, initiator ID, tag type and tag number have to
12087          * match the values that we got from the initiator.  If we have an
12088          * untagged command to abort, simply abort the first untagged command
12089          * we come to.  We only allow one untagged command at a time of course.
12090          */
12091         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12092              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12093
12094                 if ((targ_port == UINT32_MAX ||
12095                      targ_port == xio->io_hdr.nexus.targ_port) &&
12096                     (init_id == UINT32_MAX ||
12097                      init_id == xio->io_hdr.nexus.initid.id)) {
12098                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12099                             init_id != xio->io_hdr.nexus.initid.id)
12100                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12101                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12102                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12103                                 union ctl_ha_msg msg_info;
12104
12105                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12106                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12107                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12108                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12109                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12110                                 msg_info.hdr.original_sc = NULL;
12111                                 msg_info.hdr.serializing_sc = NULL;
12112                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12113                                     (void *)&msg_info, sizeof(msg_info), 0);
12114                         }
12115                 }
12116         }
12117 }
12118
12119 static int
12120 ctl_abort_task_set(union ctl_io *io)
12121 {
12122         struct ctl_softc *softc = control_softc;
12123         struct ctl_lun *lun;
12124         uint32_t targ_lun;
12125
12126         /*
12127          * Look up the LUN.
12128          */
12129         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12130         mtx_lock(&softc->ctl_lock);
12131         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12132                 lun = softc->ctl_luns[targ_lun];
12133         else {
12134                 mtx_unlock(&softc->ctl_lock);
12135                 return (1);
12136         }
12137
12138         mtx_lock(&lun->lun_lock);
12139         mtx_unlock(&softc->ctl_lock);
12140         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12141                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12142                     io->io_hdr.nexus.initid.id,
12143                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12144         } else { /* CTL_TASK_CLEAR_TASK_SET */
12145                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12146                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12147         }
12148         mtx_unlock(&lun->lun_lock);
12149         return (0);
12150 }
12151
12152 static int
12153 ctl_i_t_nexus_reset(union ctl_io *io)
12154 {
12155         struct ctl_softc *softc = control_softc;
12156         struct ctl_lun *lun;
12157         uint32_t initindex, residx;
12158
12159         initindex = ctl_get_initindex(&io->io_hdr.nexus);
12160         residx = ctl_get_resindex(&io->io_hdr.nexus);
12161         mtx_lock(&softc->ctl_lock);
12162         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12163                 mtx_lock(&lun->lun_lock);
12164                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12165                     io->io_hdr.nexus.initid.id,
12166                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12167 #ifdef CTL_WITH_CA
12168                 ctl_clear_mask(lun->have_ca, initindex);
12169 #endif
12170                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12171                         lun->flags &= ~CTL_LUN_RESERVED;
12172                 lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12173                 mtx_unlock(&lun->lun_lock);
12174         }
12175         mtx_unlock(&softc->ctl_lock);
12176         return (0);
12177 }
12178
12179 static int
12180 ctl_abort_task(union ctl_io *io)
12181 {
12182         union ctl_io *xio;
12183         struct ctl_lun *lun;
12184         struct ctl_softc *ctl_softc;
12185 #if 0
12186         struct sbuf sb;
12187         char printbuf[128];
12188 #endif
12189         int found;
12190         uint32_t targ_lun;
12191
12192         ctl_softc = control_softc;
12193         found = 0;
12194
12195         /*
12196          * Look up the LUN.
12197          */
12198         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12199         mtx_lock(&ctl_softc->ctl_lock);
12200         if ((targ_lun < CTL_MAX_LUNS)
12201          && (ctl_softc->ctl_luns[targ_lun] != NULL))
12202                 lun = ctl_softc->ctl_luns[targ_lun];
12203         else {
12204                 mtx_unlock(&ctl_softc->ctl_lock);
12205                 return (1);
12206         }
12207
12208 #if 0
12209         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12210                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12211 #endif
12212
12213         mtx_lock(&lun->lun_lock);
12214         mtx_unlock(&ctl_softc->ctl_lock);
12215         /*
12216          * Run through the OOA queue and attempt to find the given I/O.
12217          * The target port, initiator ID, tag type and tag number have to
12218          * match the values that we got from the initiator.  If we have an
12219          * untagged command to abort, simply abort the first untagged command
12220          * we come to.  We only allow one untagged command at a time of course.
12221          */
12222 #if 0
12223         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12224 #endif
12225         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12226              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12227 #if 0
12228                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12229
12230                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12231                             lun->lun, xio->scsiio.tag_num,
12232                             xio->scsiio.tag_type,
12233                             (xio->io_hdr.blocked_links.tqe_prev
12234                             == NULL) ? "" : " BLOCKED",
12235                             (xio->io_hdr.flags &
12236                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12237                             (xio->io_hdr.flags &
12238                             CTL_FLAG_ABORT) ? " ABORT" : "",
12239                             (xio->io_hdr.flags &
12240                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12241                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12242                 sbuf_finish(&sb);
12243                 printf("%s\n", sbuf_data(&sb));
12244 #endif
12245
12246                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12247                  && (xio->io_hdr.nexus.initid.id ==
12248                      io->io_hdr.nexus.initid.id)) {
12249                         /*
12250                          * If the abort says that the task is untagged, the
12251                          * task in the queue must be untagged.  Otherwise,
12252                          * we just check to see whether the tag numbers
12253                          * match.  This is because the QLogic firmware
12254                          * doesn't pass back the tag type in an abort
12255                          * request.
12256                          */
12257 #if 0
12258                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12259                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12260                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12261 #endif
12262                         /*
12263                          * XXX KDM we've got problems with FC, because it
12264                          * doesn't send down a tag type with aborts.  So we
12265                          * can only really go by the tag number...
12266                          * This may cause problems with parallel SCSI.
12267                          * Need to figure that out!!
12268                          */
12269                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12270                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12271                                 found = 1;
12272                                 if ((io->io_hdr.flags &
12273                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12274                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12275                                         union ctl_ha_msg msg_info;
12276
12277                                         io->io_hdr.flags |=
12278                                                         CTL_FLAG_SENT_2OTHER_SC;
12279                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12280                                         msg_info.task.task_action =
12281                                                 CTL_TASK_ABORT_TASK;
12282                                         msg_info.task.tag_num =
12283                                                 io->taskio.tag_num;
12284                                         msg_info.task.tag_type =
12285                                                 io->taskio.tag_type;
12286                                         msg_info.hdr.msg_type =
12287                                                 CTL_MSG_MANAGE_TASKS;
12288                                         msg_info.hdr.original_sc = NULL;
12289                                         msg_info.hdr.serializing_sc = NULL;
12290 #if 0
12291                                         printf("Sent Abort to other side\n");
12292 #endif
12293                                         if (CTL_HA_STATUS_SUCCESS !=
12294                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12295                                                 (void *)&msg_info,
12296                                                 sizeof(msg_info), 0)) {
12297                                         }
12298                                 }
12299 #if 0
12300                                 printf("ctl_abort_task: found I/O to abort\n");
12301 #endif
12302                                 break;
12303                         }
12304                 }
12305         }
12306         mtx_unlock(&lun->lun_lock);
12307
12308         if (found == 0) {
12309                 /*
12310                  * This isn't really an error.  It's entirely possible for
12311                  * the abort and command completion to cross on the wire.
12312                  * This is more of an informative/diagnostic error.
12313                  */
12314 #if 0
12315                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12316                        "%d:%d:%d:%d tag %d type %d\n",
12317                        io->io_hdr.nexus.initid.id,
12318                        io->io_hdr.nexus.targ_port,
12319                        io->io_hdr.nexus.targ_target.id,
12320                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12321                        io->taskio.tag_type);
12322 #endif
12323         }
12324         return (0);
12325 }
12326
12327 static void
12328 ctl_run_task(union ctl_io *io)
12329 {
12330         struct ctl_softc *ctl_softc = control_softc;
12331         int retval = 1;
12332         const char *task_desc;
12333
12334         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12335
12336         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12337             ("ctl_run_task: Unextected io_type %d\n",
12338              io->io_hdr.io_type));
12339
12340         task_desc = ctl_scsi_task_string(&io->taskio);
12341         if (task_desc != NULL) {
12342 #ifdef NEEDTOPORT
12343                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12344                             CTL_TASK_REPORT,
12345                             csevent_LogType_Trace,
12346                             csevent_Severity_Information,
12347                             csevent_AlertLevel_Green,
12348                             csevent_FRU_Firmware,
12349                             csevent_FRU_Unknown,
12350                             "CTL: received task: %s",task_desc);
12351 #endif
12352         } else {
12353 #ifdef NEEDTOPORT
12354                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12355                             CTL_TASK_REPORT,
12356                             csevent_LogType_Trace,
12357                             csevent_Severity_Information,
12358                             csevent_AlertLevel_Green,
12359                             csevent_FRU_Firmware,
12360                             csevent_FRU_Unknown,
12361                             "CTL: received unknown task "
12362                             "type: %d (%#x)",
12363                             io->taskio.task_action,
12364                             io->taskio.task_action);
12365 #endif
12366         }
12367         switch (io->taskio.task_action) {
12368         case CTL_TASK_ABORT_TASK:
12369                 retval = ctl_abort_task(io);
12370                 break;
12371         case CTL_TASK_ABORT_TASK_SET:
12372         case CTL_TASK_CLEAR_TASK_SET:
12373                 retval = ctl_abort_task_set(io);
12374                 break;
12375         case CTL_TASK_CLEAR_ACA:
12376                 break;
12377         case CTL_TASK_I_T_NEXUS_RESET:
12378                 retval = ctl_i_t_nexus_reset(io);
12379                 break;
12380         case CTL_TASK_LUN_RESET: {
12381                 struct ctl_lun *lun;
12382                 uint32_t targ_lun;
12383
12384                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12385                 mtx_lock(&ctl_softc->ctl_lock);
12386                 if ((targ_lun < CTL_MAX_LUNS)
12387                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12388                         lun = ctl_softc->ctl_luns[targ_lun];
12389                 else {
12390                         mtx_unlock(&ctl_softc->ctl_lock);
12391                         retval = 1;
12392                         break;
12393                 }
12394
12395                 if (!(io->io_hdr.flags &
12396                     CTL_FLAG_FROM_OTHER_SC)) {
12397                         union ctl_ha_msg msg_info;
12398
12399                         io->io_hdr.flags |=
12400                                 CTL_FLAG_SENT_2OTHER_SC;
12401                         msg_info.hdr.msg_type =
12402                                 CTL_MSG_MANAGE_TASKS;
12403                         msg_info.hdr.nexus = io->io_hdr.nexus;
12404                         msg_info.task.task_action =
12405                                 CTL_TASK_LUN_RESET;
12406                         msg_info.hdr.original_sc = NULL;
12407                         msg_info.hdr.serializing_sc = NULL;
12408                         if (CTL_HA_STATUS_SUCCESS !=
12409                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12410                             (void *)&msg_info,
12411                             sizeof(msg_info), 0)) {
12412                         }
12413                 }
12414
12415                 retval = ctl_lun_reset(lun, io,
12416                                        CTL_UA_LUN_RESET);
12417                 mtx_unlock(&ctl_softc->ctl_lock);
12418                 break;
12419         }
12420         case CTL_TASK_TARGET_RESET:
12421                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12422                 break;
12423         case CTL_TASK_BUS_RESET:
12424                 retval = ctl_bus_reset(ctl_softc, io);
12425                 break;
12426         case CTL_TASK_PORT_LOGIN:
12427                 break;
12428         case CTL_TASK_PORT_LOGOUT:
12429                 break;
12430         default:
12431                 printf("ctl_run_task: got unknown task management event %d\n",
12432                        io->taskio.task_action);
12433                 break;
12434         }
12435         if (retval == 0)
12436                 io->io_hdr.status = CTL_SUCCESS;
12437         else
12438                 io->io_hdr.status = CTL_ERROR;
12439         ctl_done(io);
12440 }
12441
12442 /*
12443  * For HA operation.  Handle commands that come in from the other
12444  * controller.
12445  */
12446 static void
12447 ctl_handle_isc(union ctl_io *io)
12448 {
12449         int free_io;
12450         struct ctl_lun *lun;
12451         struct ctl_softc *ctl_softc;
12452         uint32_t targ_lun;
12453
12454         ctl_softc = control_softc;
12455
12456         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12457         lun = ctl_softc->ctl_luns[targ_lun];
12458
12459         switch (io->io_hdr.msg_type) {
12460         case CTL_MSG_SERIALIZE:
12461                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12462                 break;
12463         case CTL_MSG_R2R: {
12464                 const struct ctl_cmd_entry *entry;
12465
12466                 /*
12467                  * This is only used in SER_ONLY mode.
12468                  */
12469                 free_io = 0;
12470                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12471                 mtx_lock(&lun->lun_lock);
12472                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12473                     entry, (struct ctl_scsiio *)io) != 0) {
12474                         mtx_unlock(&lun->lun_lock);
12475                         ctl_done(io);
12476                         break;
12477                 }
12478                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12479                 mtx_unlock(&lun->lun_lock);
12480                 ctl_enqueue_rtr(io);
12481                 break;
12482         }
12483         case CTL_MSG_FINISH_IO:
12484                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12485                         free_io = 0;
12486                         ctl_done(io);
12487                 } else {
12488                         free_io = 1;
12489                         mtx_lock(&lun->lun_lock);
12490                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12491                                      ooa_links);
12492                         ctl_check_blocked(lun);
12493                         mtx_unlock(&lun->lun_lock);
12494                 }
12495                 break;
12496         case CTL_MSG_PERS_ACTION:
12497                 ctl_hndl_per_res_out_on_other_sc(
12498                         (union ctl_ha_msg *)&io->presio.pr_msg);
12499                 free_io = 1;
12500                 break;
12501         case CTL_MSG_BAD_JUJU:
12502                 free_io = 0;
12503                 ctl_done(io);
12504                 break;
12505         case CTL_MSG_DATAMOVE:
12506                 /* Only used in XFER mode */
12507                 free_io = 0;
12508                 ctl_datamove_remote(io);
12509                 break;
12510         case CTL_MSG_DATAMOVE_DONE:
12511                 /* Only used in XFER mode */
12512                 free_io = 0;
12513                 io->scsiio.be_move_done(io);
12514                 break;
12515         default:
12516                 free_io = 1;
12517                 printf("%s: Invalid message type %d\n",
12518                        __func__, io->io_hdr.msg_type);
12519                 break;
12520         }
12521         if (free_io)
12522                 ctl_free_io(io);
12523
12524 }
12525
12526
12527 /*
12528  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12529  * there is no match.
12530  */
12531 static ctl_lun_error_pattern
12532 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12533 {
12534         const struct ctl_cmd_entry *entry;
12535         ctl_lun_error_pattern filtered_pattern, pattern;
12536
12537         pattern = desc->error_pattern;
12538
12539         /*
12540          * XXX KDM we need more data passed into this function to match a
12541          * custom pattern, and we actually need to implement custom pattern
12542          * matching.
12543          */
12544         if (pattern & CTL_LUN_PAT_CMD)
12545                 return (CTL_LUN_PAT_CMD);
12546
12547         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12548                 return (CTL_LUN_PAT_ANY);
12549
12550         entry = ctl_get_cmd_entry(ctsio, NULL);
12551
12552         filtered_pattern = entry->pattern & pattern;
12553
12554         /*
12555          * If the user requested specific flags in the pattern (e.g.
12556          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12557          * flags.
12558          *
12559          * If the user did not specify any flags, it doesn't matter whether
12560          * or not the command supports the flags.
12561          */
12562         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12563              (pattern & ~CTL_LUN_PAT_MASK))
12564                 return (CTL_LUN_PAT_NONE);
12565
12566         /*
12567          * If the user asked for a range check, see if the requested LBA
12568          * range overlaps with this command's LBA range.
12569          */
12570         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12571                 uint64_t lba1;
12572                 uint64_t len1;
12573                 ctl_action action;
12574                 int retval;
12575
12576                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12577                 if (retval != 0)
12578                         return (CTL_LUN_PAT_NONE);
12579
12580                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12581                                               desc->lba_range.len);
12582                 /*
12583                  * A "pass" means that the LBA ranges don't overlap, so
12584                  * this doesn't match the user's range criteria.
12585                  */
12586                 if (action == CTL_ACTION_PASS)
12587                         return (CTL_LUN_PAT_NONE);
12588         }
12589
12590         return (filtered_pattern);
12591 }
12592
12593 static void
12594 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12595 {
12596         struct ctl_error_desc *desc, *desc2;
12597
12598         mtx_assert(&lun->lun_lock, MA_OWNED);
12599
12600         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12601                 ctl_lun_error_pattern pattern;
12602                 /*
12603                  * Check to see whether this particular command matches
12604                  * the pattern in the descriptor.
12605                  */
12606                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12607                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12608                         continue;
12609
12610                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12611                 case CTL_LUN_INJ_ABORTED:
12612                         ctl_set_aborted(&io->scsiio);
12613                         break;
12614                 case CTL_LUN_INJ_MEDIUM_ERR:
12615                         ctl_set_medium_error(&io->scsiio);
12616                         break;
12617                 case CTL_LUN_INJ_UA:
12618                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12619                          * OCCURRED */
12620                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12621                         break;
12622                 case CTL_LUN_INJ_CUSTOM:
12623                         /*
12624                          * We're assuming the user knows what he is doing.
12625                          * Just copy the sense information without doing
12626                          * checks.
12627                          */
12628                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12629                               ctl_min(sizeof(desc->custom_sense),
12630                                       sizeof(io->scsiio.sense_data)));
12631                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12632                         io->scsiio.sense_len = SSD_FULL_SIZE;
12633                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12634                         break;
12635                 case CTL_LUN_INJ_NONE:
12636                 default:
12637                         /*
12638                          * If this is an error injection type we don't know
12639                          * about, clear the continuous flag (if it is set)
12640                          * so it will get deleted below.
12641                          */
12642                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12643                         break;
12644                 }
12645                 /*
12646                  * By default, each error injection action is a one-shot
12647                  */
12648                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12649                         continue;
12650
12651                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12652
12653                 free(desc, M_CTL);
12654         }
12655 }
12656
12657 #ifdef CTL_IO_DELAY
12658 static void
12659 ctl_datamove_timer_wakeup(void *arg)
12660 {
12661         union ctl_io *io;
12662
12663         io = (union ctl_io *)arg;
12664
12665         ctl_datamove(io);
12666 }
12667 #endif /* CTL_IO_DELAY */
12668
12669 void
12670 ctl_datamove(union ctl_io *io)
12671 {
12672         void (*fe_datamove)(union ctl_io *io);
12673
12674         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12675
12676         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12677
12678 #ifdef CTL_TIME_IO
12679         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12680                 char str[256];
12681                 char path_str[64];
12682                 struct sbuf sb;
12683
12684                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12685                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12686
12687                 sbuf_cat(&sb, path_str);
12688                 switch (io->io_hdr.io_type) {
12689                 case CTL_IO_SCSI:
12690                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12691                         sbuf_printf(&sb, "\n");
12692                         sbuf_cat(&sb, path_str);
12693                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12694                                     io->scsiio.tag_num, io->scsiio.tag_type);
12695                         break;
12696                 case CTL_IO_TASK:
12697                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12698                                     "Tag Type: %d\n", io->taskio.task_action,
12699                                     io->taskio.tag_num, io->taskio.tag_type);
12700                         break;
12701                 default:
12702                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12703                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12704                         break;
12705                 }
12706                 sbuf_cat(&sb, path_str);
12707                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12708                             (intmax_t)time_uptime - io->io_hdr.start_time);
12709                 sbuf_finish(&sb);
12710                 printf("%s", sbuf_data(&sb));
12711         }
12712 #endif /* CTL_TIME_IO */
12713
12714 #ifdef CTL_IO_DELAY
12715         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12716                 struct ctl_lun *lun;
12717
12718                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12719
12720                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12721         } else {
12722                 struct ctl_lun *lun;
12723
12724                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12725                 if ((lun != NULL)
12726                  && (lun->delay_info.datamove_delay > 0)) {
12727                         struct callout *callout;
12728
12729                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12730                         callout_init(callout, /*mpsafe*/ 1);
12731                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12732                         callout_reset(callout,
12733                                       lun->delay_info.datamove_delay * hz,
12734                                       ctl_datamove_timer_wakeup, io);
12735                         if (lun->delay_info.datamove_type ==
12736                             CTL_DELAY_TYPE_ONESHOT)
12737                                 lun->delay_info.datamove_delay = 0;
12738                         return;
12739                 }
12740         }
12741 #endif
12742
12743         /*
12744          * This command has been aborted.  Set the port status, so we fail
12745          * the data move.
12746          */
12747         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12748                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12749                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12750                        io->io_hdr.nexus.targ_port,
12751                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12752                        io->io_hdr.nexus.targ_lun);
12753                 io->io_hdr.port_status = 31337;
12754                 /*
12755                  * Note that the backend, in this case, will get the
12756                  * callback in its context.  In other cases it may get
12757                  * called in the frontend's interrupt thread context.
12758                  */
12759                 io->scsiio.be_move_done(io);
12760                 return;
12761         }
12762
12763         /*
12764          * If we're in XFER mode and this I/O is from the other shelf
12765          * controller, we need to send the DMA to the other side to
12766          * actually transfer the data to/from the host.  In serialize only
12767          * mode the transfer happens below CTL and ctl_datamove() is only
12768          * called on the machine that originally received the I/O.
12769          */
12770         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12771          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12772                 union ctl_ha_msg msg;
12773                 uint32_t sg_entries_sent;
12774                 int do_sg_copy;
12775                 int i;
12776
12777                 memset(&msg, 0, sizeof(msg));
12778                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12779                 msg.hdr.original_sc = io->io_hdr.original_sc;
12780                 msg.hdr.serializing_sc = io;
12781                 msg.hdr.nexus = io->io_hdr.nexus;
12782                 msg.dt.flags = io->io_hdr.flags;
12783                 /*
12784                  * We convert everything into a S/G list here.  We can't
12785                  * pass by reference, only by value between controllers.
12786                  * So we can't pass a pointer to the S/G list, only as many
12787                  * S/G entries as we can fit in here.  If it's possible for
12788                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12789                  * then we need to break this up into multiple transfers.
12790                  */
12791                 if (io->scsiio.kern_sg_entries == 0) {
12792                         msg.dt.kern_sg_entries = 1;
12793                         /*
12794                          * If this is in cached memory, flush the cache
12795                          * before we send the DMA request to the other
12796                          * controller.  We want to do this in either the
12797                          * read or the write case.  The read case is
12798                          * straightforward.  In the write case, we want to
12799                          * make sure nothing is in the local cache that
12800                          * could overwrite the DMAed data.
12801                          */
12802                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12803                                 /*
12804                                  * XXX KDM use bus_dmamap_sync() here.
12805                                  */
12806                         }
12807
12808                         /*
12809                          * Convert to a physical address if this is a
12810                          * virtual address.
12811                          */
12812                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12813                                 msg.dt.sg_list[0].addr =
12814                                         io->scsiio.kern_data_ptr;
12815                         } else {
12816                                 /*
12817                                  * XXX KDM use busdma here!
12818                                  */
12819 #if 0
12820                                 msg.dt.sg_list[0].addr = (void *)
12821                                         vtophys(io->scsiio.kern_data_ptr);
12822 #endif
12823                         }
12824
12825                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12826                         do_sg_copy = 0;
12827                 } else {
12828                         struct ctl_sg_entry *sgl;
12829
12830                         do_sg_copy = 1;
12831                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12832                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12833                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12834                                 /*
12835                                  * XXX KDM use bus_dmamap_sync() here.
12836                                  */
12837                         }
12838                 }
12839
12840                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12841                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12842                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12843                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12844                 msg.dt.sg_sequence = 0;
12845
12846                 /*
12847                  * Loop until we've sent all of the S/G entries.  On the
12848                  * other end, we'll recompose these S/G entries into one
12849                  * contiguous list before passing it to the
12850                  */
12851                 for (sg_entries_sent = 0; sg_entries_sent <
12852                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12853                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12854                                 sizeof(msg.dt.sg_list[0])),
12855                                 msg.dt.kern_sg_entries - sg_entries_sent);
12856
12857                         if (do_sg_copy != 0) {
12858                                 struct ctl_sg_entry *sgl;
12859                                 int j;
12860
12861                                 sgl = (struct ctl_sg_entry *)
12862                                         io->scsiio.kern_data_ptr;
12863                                 /*
12864                                  * If this is in cached memory, flush the cache
12865                                  * before we send the DMA request to the other
12866                                  * controller.  We want to do this in either
12867                                  * the * read or the write case.  The read
12868                                  * case is straightforward.  In the write
12869                                  * case, we want to make sure nothing is
12870                                  * in the local cache that could overwrite
12871                                  * the DMAed data.
12872                                  */
12873
12874                                 for (i = sg_entries_sent, j = 0;
12875                                      i < msg.dt.cur_sg_entries; i++, j++) {
12876                                         if ((io->io_hdr.flags &
12877                                              CTL_FLAG_NO_DATASYNC) == 0) {
12878                                                 /*
12879                                                  * XXX KDM use bus_dmamap_sync()
12880                                                  */
12881                                         }
12882                                         if ((io->io_hdr.flags &
12883                                              CTL_FLAG_BUS_ADDR) == 0) {
12884                                                 /*
12885                                                  * XXX KDM use busdma.
12886                                                  */
12887 #if 0
12888                                                 msg.dt.sg_list[j].addr =(void *)
12889                                                        vtophys(sgl[i].addr);
12890 #endif
12891                                         } else {
12892                                                 msg.dt.sg_list[j].addr =
12893                                                         sgl[i].addr;
12894                                         }
12895                                         msg.dt.sg_list[j].len = sgl[i].len;
12896                                 }
12897                         }
12898
12899                         sg_entries_sent += msg.dt.cur_sg_entries;
12900                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12901                                 msg.dt.sg_last = 1;
12902                         else
12903                                 msg.dt.sg_last = 0;
12904
12905                         /*
12906                          * XXX KDM drop and reacquire the lock here?
12907                          */
12908                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12909                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12910                                 /*
12911                                  * XXX do something here.
12912                                  */
12913                         }
12914
12915                         msg.dt.sent_sg_entries = sg_entries_sent;
12916                 }
12917                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12918                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12919                         ctl_failover_io(io, /*have_lock*/ 0);
12920
12921         } else {
12922
12923                 /*
12924                  * Lookup the fe_datamove() function for this particular
12925                  * front end.
12926                  */
12927                 fe_datamove =
12928                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12929
12930                 fe_datamove(io);
12931         }
12932 }
12933
12934 static void
12935 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12936 {
12937         union ctl_ha_msg msg;
12938         int isc_status;
12939
12940         memset(&msg, 0, sizeof(msg));
12941
12942         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12943         msg.hdr.original_sc = io;
12944         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12945         msg.hdr.nexus = io->io_hdr.nexus;
12946         msg.hdr.status = io->io_hdr.status;
12947         msg.scsi.tag_num = io->scsiio.tag_num;
12948         msg.scsi.tag_type = io->scsiio.tag_type;
12949         msg.scsi.scsi_status = io->scsiio.scsi_status;
12950         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12951                sizeof(io->scsiio.sense_data));
12952         msg.scsi.sense_len = io->scsiio.sense_len;
12953         msg.scsi.sense_residual = io->scsiio.sense_residual;
12954         msg.scsi.fetd_status = io->io_hdr.port_status;
12955         msg.scsi.residual = io->scsiio.residual;
12956         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12957
12958         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12959                 ctl_failover_io(io, /*have_lock*/ have_lock);
12960                 return;
12961         }
12962
12963         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12964         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12965                 /* XXX do something if this fails */
12966         }
12967
12968 }
12969
12970 /*
12971  * The DMA to the remote side is done, now we need to tell the other side
12972  * we're done so it can continue with its data movement.
12973  */
12974 static void
12975 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12976 {
12977         union ctl_io *io;
12978
12979         io = rq->context;
12980
12981         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12982                 printf("%s: ISC DMA write failed with error %d", __func__,
12983                        rq->ret);
12984                 ctl_set_internal_failure(&io->scsiio,
12985                                          /*sks_valid*/ 1,
12986                                          /*retry_count*/ rq->ret);
12987         }
12988
12989         ctl_dt_req_free(rq);
12990
12991         /*
12992          * In this case, we had to malloc the memory locally.  Free it.
12993          */
12994         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12995                 int i;
12996                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12997                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12998         }
12999         /*
13000          * The data is in local and remote memory, so now we need to send
13001          * status (good or back) back to the other side.
13002          */
13003         ctl_send_datamove_done(io, /*have_lock*/ 0);
13004 }
13005
13006 /*
13007  * We've moved the data from the host/controller into local memory.  Now we
13008  * need to push it over to the remote controller's memory.
13009  */
13010 static int
13011 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13012 {
13013         int retval;
13014
13015         retval = 0;
13016
13017         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13018                                           ctl_datamove_remote_write_cb);
13019
13020         return (retval);
13021 }
13022
13023 static void
13024 ctl_datamove_remote_write(union ctl_io *io)
13025 {
13026         int retval;
13027         void (*fe_datamove)(union ctl_io *io);
13028
13029         /*
13030          * - Get the data from the host/HBA into local memory.
13031          * - DMA memory from the local controller to the remote controller.
13032          * - Send status back to the remote controller.
13033          */
13034
13035         retval = ctl_datamove_remote_sgl_setup(io);
13036         if (retval != 0)
13037                 return;
13038
13039         /* Switch the pointer over so the FETD knows what to do */
13040         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13041
13042         /*
13043          * Use a custom move done callback, since we need to send completion
13044          * back to the other controller, not to the backend on this side.
13045          */
13046         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13047
13048         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13049
13050         fe_datamove(io);
13051
13052         return;
13053
13054 }
13055
13056 static int
13057 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13058 {
13059 #if 0
13060         char str[256];
13061         char path_str[64];
13062         struct sbuf sb;
13063 #endif
13064
13065         /*
13066          * In this case, we had to malloc the memory locally.  Free it.
13067          */
13068         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13069                 int i;
13070                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13071                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13072         }
13073
13074 #if 0
13075         scsi_path_string(io, path_str, sizeof(path_str));
13076         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13077         sbuf_cat(&sb, path_str);
13078         scsi_command_string(&io->scsiio, NULL, &sb);
13079         sbuf_printf(&sb, "\n");
13080         sbuf_cat(&sb, path_str);
13081         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13082                     io->scsiio.tag_num, io->scsiio.tag_type);
13083         sbuf_cat(&sb, path_str);
13084         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13085                     io->io_hdr.flags, io->io_hdr.status);
13086         sbuf_finish(&sb);
13087         printk("%s", sbuf_data(&sb));
13088 #endif
13089
13090
13091         /*
13092          * The read is done, now we need to send status (good or bad) back
13093          * to the other side.
13094          */
13095         ctl_send_datamove_done(io, /*have_lock*/ 0);
13096
13097         return (0);
13098 }
13099
13100 static void
13101 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13102 {
13103         union ctl_io *io;
13104         void (*fe_datamove)(union ctl_io *io);
13105
13106         io = rq->context;
13107
13108         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13109                 printf("%s: ISC DMA read failed with error %d", __func__,
13110                        rq->ret);
13111                 ctl_set_internal_failure(&io->scsiio,
13112                                          /*sks_valid*/ 1,
13113                                          /*retry_count*/ rq->ret);
13114         }
13115
13116         ctl_dt_req_free(rq);
13117
13118         /* Switch the pointer over so the FETD knows what to do */
13119         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13120
13121         /*
13122          * Use a custom move done callback, since we need to send completion
13123          * back to the other controller, not to the backend on this side.
13124          */
13125         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13126
13127         /* XXX KDM add checks like the ones in ctl_datamove? */
13128
13129         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13130
13131         fe_datamove(io);
13132 }
13133
13134 static int
13135 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13136 {
13137         struct ctl_sg_entry *local_sglist, *remote_sglist;
13138         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13139         struct ctl_softc *softc;
13140         int retval;
13141         int i;
13142
13143         retval = 0;
13144         softc = control_softc;
13145
13146         local_sglist = io->io_hdr.local_sglist;
13147         local_dma_sglist = io->io_hdr.local_dma_sglist;
13148         remote_sglist = io->io_hdr.remote_sglist;
13149         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13150
13151         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13152                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13153                         local_sglist[i].len = remote_sglist[i].len;
13154
13155                         /*
13156                          * XXX Detect the situation where the RS-level I/O
13157                          * redirector on the other side has already read the
13158                          * data off of the AOR RS on this side, and
13159                          * transferred it to remote (mirror) memory on the
13160                          * other side.  Since we already have the data in
13161                          * memory here, we just need to use it.
13162                          *
13163                          * XXX KDM this can probably be removed once we
13164                          * get the cache device code in and take the
13165                          * current AOR implementation out.
13166                          */
13167 #ifdef NEEDTOPORT
13168                         if ((remote_sglist[i].addr >=
13169                              (void *)vtophys(softc->mirr->addr))
13170                          && (remote_sglist[i].addr <
13171                              ((void *)vtophys(softc->mirr->addr) +
13172                              CacheMirrorOffset))) {
13173                                 local_sglist[i].addr = remote_sglist[i].addr -
13174                                         CacheMirrorOffset;
13175                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13176                                      CTL_FLAG_DATA_IN)
13177                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13178                         } else {
13179                                 local_sglist[i].addr = remote_sglist[i].addr +
13180                                         CacheMirrorOffset;
13181                         }
13182 #endif
13183 #if 0
13184                         printf("%s: local %p, remote %p, len %d\n",
13185                                __func__, local_sglist[i].addr,
13186                                remote_sglist[i].addr, local_sglist[i].len);
13187 #endif
13188                 }
13189         } else {
13190                 uint32_t len_to_go;
13191
13192                 /*
13193                  * In this case, we don't have automatically allocated
13194                  * memory for this I/O on this controller.  This typically
13195                  * happens with internal CTL I/O -- e.g. inquiry, mode
13196                  * sense, etc.  Anything coming from RAIDCore will have
13197                  * a mirror area available.
13198                  */
13199                 len_to_go = io->scsiio.kern_data_len;
13200
13201                 /*
13202                  * Clear the no datasync flag, we have to use malloced
13203                  * buffers.
13204                  */
13205                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13206
13207                 /*
13208                  * The difficult thing here is that the size of the various
13209                  * S/G segments may be different than the size from the
13210                  * remote controller.  That'll make it harder when DMAing
13211                  * the data back to the other side.
13212                  */
13213                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13214                      sizeof(io->io_hdr.remote_sglist[0])) &&
13215                      (len_to_go > 0); i++) {
13216                         local_sglist[i].len = ctl_min(len_to_go, 131072);
13217                         CTL_SIZE_8B(local_dma_sglist[i].len,
13218                                     local_sglist[i].len);
13219                         local_sglist[i].addr =
13220                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13221
13222                         local_dma_sglist[i].addr = local_sglist[i].addr;
13223
13224                         if (local_sglist[i].addr == NULL) {
13225                                 int j;
13226
13227                                 printf("malloc failed for %zd bytes!",
13228                                        local_dma_sglist[i].len);
13229                                 for (j = 0; j < i; j++) {
13230                                         free(local_sglist[j].addr, M_CTL);
13231                                 }
13232                                 ctl_set_internal_failure(&io->scsiio,
13233                                                          /*sks_valid*/ 1,
13234                                                          /*retry_count*/ 4857);
13235                                 retval = 1;
13236                                 goto bailout_error;
13237                                 
13238                         }
13239                         /* XXX KDM do we need a sync here? */
13240
13241                         len_to_go -= local_sglist[i].len;
13242                 }
13243                 /*
13244                  * Reset the number of S/G entries accordingly.  The
13245                  * original number of S/G entries is available in
13246                  * rem_sg_entries.
13247                  */
13248                 io->scsiio.kern_sg_entries = i;
13249
13250 #if 0
13251                 printf("%s: kern_sg_entries = %d\n", __func__,
13252                        io->scsiio.kern_sg_entries);
13253                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13254                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13255                                local_sglist[i].addr, local_sglist[i].len,
13256                                local_dma_sglist[i].len);
13257 #endif
13258         }
13259
13260
13261         return (retval);
13262
13263 bailout_error:
13264
13265         ctl_send_datamove_done(io, /*have_lock*/ 0);
13266
13267         return (retval);
13268 }
13269
13270 static int
13271 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13272                          ctl_ha_dt_cb callback)
13273 {
13274         struct ctl_ha_dt_req *rq;
13275         struct ctl_sg_entry *remote_sglist, *local_sglist;
13276         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13277         uint32_t local_used, remote_used, total_used;
13278         int retval;
13279         int i, j;
13280
13281         retval = 0;
13282
13283         rq = ctl_dt_req_alloc();
13284
13285         /*
13286          * If we failed to allocate the request, and if the DMA didn't fail
13287          * anyway, set busy status.  This is just a resource allocation
13288          * failure.
13289          */
13290         if ((rq == NULL)
13291          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13292                 ctl_set_busy(&io->scsiio);
13293
13294         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13295
13296                 if (rq != NULL)
13297                         ctl_dt_req_free(rq);
13298
13299                 /*
13300                  * The data move failed.  We need to return status back
13301                  * to the other controller.  No point in trying to DMA
13302                  * data to the remote controller.
13303                  */
13304
13305                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13306
13307                 retval = 1;
13308
13309                 goto bailout;
13310         }
13311
13312         local_sglist = io->io_hdr.local_sglist;
13313         local_dma_sglist = io->io_hdr.local_dma_sglist;
13314         remote_sglist = io->io_hdr.remote_sglist;
13315         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13316         local_used = 0;
13317         remote_used = 0;
13318         total_used = 0;
13319
13320         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13321                 rq->ret = CTL_HA_STATUS_SUCCESS;
13322                 rq->context = io;
13323                 callback(rq);
13324                 goto bailout;
13325         }
13326
13327         /*
13328          * Pull/push the data over the wire from/to the other controller.
13329          * This takes into account the possibility that the local and
13330          * remote sglists may not be identical in terms of the size of
13331          * the elements and the number of elements.
13332          *
13333          * One fundamental assumption here is that the length allocated for
13334          * both the local and remote sglists is identical.  Otherwise, we've
13335          * essentially got a coding error of some sort.
13336          */
13337         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13338                 int isc_ret;
13339                 uint32_t cur_len, dma_length;
13340                 uint8_t *tmp_ptr;
13341
13342                 rq->id = CTL_HA_DATA_CTL;
13343                 rq->command = command;
13344                 rq->context = io;
13345
13346                 /*
13347                  * Both pointers should be aligned.  But it is possible
13348                  * that the allocation length is not.  They should both
13349                  * also have enough slack left over at the end, though,
13350                  * to round up to the next 8 byte boundary.
13351                  */
13352                 cur_len = ctl_min(local_sglist[i].len - local_used,
13353                                   remote_sglist[j].len - remote_used);
13354
13355                 /*
13356                  * In this case, we have a size issue and need to decrease
13357                  * the size, except in the case where we actually have less
13358                  * than 8 bytes left.  In that case, we need to increase
13359                  * the DMA length to get the last bit.
13360                  */
13361                 if ((cur_len & 0x7) != 0) {
13362                         if (cur_len > 0x7) {
13363                                 cur_len = cur_len - (cur_len & 0x7);
13364                                 dma_length = cur_len;
13365                         } else {
13366                                 CTL_SIZE_8B(dma_length, cur_len);
13367                         }
13368
13369                 } else
13370                         dma_length = cur_len;
13371
13372                 /*
13373                  * If we had to allocate memory for this I/O, instead of using
13374                  * the non-cached mirror memory, we'll need to flush the cache
13375                  * before trying to DMA to the other controller.
13376                  *
13377                  * We could end up doing this multiple times for the same
13378                  * segment if we have a larger local segment than remote
13379                  * segment.  That shouldn't be an issue.
13380                  */
13381                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13382                         /*
13383                          * XXX KDM use bus_dmamap_sync() here.
13384                          */
13385                 }
13386
13387                 rq->size = dma_length;
13388
13389                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13390                 tmp_ptr += local_used;
13391
13392                 /* Use physical addresses when talking to ISC hardware */
13393                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13394                         /* XXX KDM use busdma */
13395 #if 0
13396                         rq->local = vtophys(tmp_ptr);
13397 #endif
13398                 } else
13399                         rq->local = tmp_ptr;
13400
13401                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13402                 tmp_ptr += remote_used;
13403                 rq->remote = tmp_ptr;
13404
13405                 rq->callback = NULL;
13406
13407                 local_used += cur_len;
13408                 if (local_used >= local_sglist[i].len) {
13409                         i++;
13410                         local_used = 0;
13411                 }
13412
13413                 remote_used += cur_len;
13414                 if (remote_used >= remote_sglist[j].len) {
13415                         j++;
13416                         remote_used = 0;
13417                 }
13418                 total_used += cur_len;
13419
13420                 if (total_used >= io->scsiio.kern_data_len)
13421                         rq->callback = callback;
13422
13423                 if ((rq->size & 0x7) != 0) {
13424                         printf("%s: warning: size %d is not on 8b boundary\n",
13425                                __func__, rq->size);
13426                 }
13427                 if (((uintptr_t)rq->local & 0x7) != 0) {
13428                         printf("%s: warning: local %p not on 8b boundary\n",
13429                                __func__, rq->local);
13430                 }
13431                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13432                         printf("%s: warning: remote %p not on 8b boundary\n",
13433                                __func__, rq->local);
13434                 }
13435 #if 0
13436                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13437                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13438                        rq->local, rq->remote, rq->size);
13439 #endif
13440
13441                 isc_ret = ctl_dt_single(rq);
13442                 if (isc_ret == CTL_HA_STATUS_WAIT)
13443                         continue;
13444
13445                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13446                         rq->ret = CTL_HA_STATUS_SUCCESS;
13447                 } else {
13448                         rq->ret = isc_ret;
13449                 }
13450                 callback(rq);
13451                 goto bailout;
13452         }
13453
13454 bailout:
13455         return (retval);
13456
13457 }
13458
13459 static void
13460 ctl_datamove_remote_read(union ctl_io *io)
13461 {
13462         int retval;
13463         int i;
13464
13465         /*
13466          * This will send an error to the other controller in the case of a
13467          * failure.
13468          */
13469         retval = ctl_datamove_remote_sgl_setup(io);
13470         if (retval != 0)
13471                 return;
13472
13473         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13474                                           ctl_datamove_remote_read_cb);
13475         if ((retval != 0)
13476          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13477                 /*
13478                  * Make sure we free memory if there was an error..  The
13479                  * ctl_datamove_remote_xfer() function will send the
13480                  * datamove done message, or call the callback with an
13481                  * error if there is a problem.
13482                  */
13483                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13484                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13485         }
13486
13487         return;
13488 }
13489
13490 /*
13491  * Process a datamove request from the other controller.  This is used for
13492  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13493  * first.  Once that is complete, the data gets DMAed into the remote
13494  * controller's memory.  For reads, we DMA from the remote controller's
13495  * memory into our memory first, and then move it out to the FETD.
13496  */
13497 static void
13498 ctl_datamove_remote(union ctl_io *io)
13499 {
13500         struct ctl_softc *softc;
13501
13502         softc = control_softc;
13503
13504         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13505
13506         /*
13507          * Note that we look for an aborted I/O here, but don't do some of
13508          * the other checks that ctl_datamove() normally does.
13509          * We don't need to run the datamove delay code, since that should
13510          * have been done if need be on the other controller.
13511          */
13512         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13513                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13514                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13515                        io->io_hdr.nexus.targ_port,
13516                        io->io_hdr.nexus.targ_target.id,
13517                        io->io_hdr.nexus.targ_lun);
13518                 io->io_hdr.port_status = 31338;
13519                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13520                 return;
13521         }
13522
13523         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13524                 ctl_datamove_remote_write(io);
13525         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13526                 ctl_datamove_remote_read(io);
13527         } else {
13528                 union ctl_ha_msg msg;
13529                 struct scsi_sense_data *sense;
13530                 uint8_t sks[3];
13531                 int retry_count;
13532
13533                 memset(&msg, 0, sizeof(msg));
13534
13535                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13536                 msg.hdr.status = CTL_SCSI_ERROR;
13537                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13538
13539                 retry_count = 4243;
13540
13541                 sense = &msg.scsi.sense_data;
13542                 sks[0] = SSD_SCS_VALID;
13543                 sks[1] = (retry_count >> 8) & 0xff;
13544                 sks[2] = retry_count & 0xff;
13545
13546                 /* "Internal target failure" */
13547                 scsi_set_sense_data(sense,
13548                                     /*sense_format*/ SSD_TYPE_NONE,
13549                                     /*current_error*/ 1,
13550                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13551                                     /*asc*/ 0x44,
13552                                     /*ascq*/ 0x00,
13553                                     /*type*/ SSD_ELEM_SKS,
13554                                     /*size*/ sizeof(sks),
13555                                     /*data*/ sks,
13556                                     SSD_ELEM_NONE);
13557
13558                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13559                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13560                         ctl_failover_io(io, /*have_lock*/ 1);
13561                         return;
13562                 }
13563
13564                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13565                     CTL_HA_STATUS_SUCCESS) {
13566                         /* XXX KDM what to do if this fails? */
13567                 }
13568                 return;
13569         }
13570         
13571 }
13572
13573 static int
13574 ctl_process_done(union ctl_io *io)
13575 {
13576         struct ctl_lun *lun;
13577         struct ctl_softc *ctl_softc;
13578         void (*fe_done)(union ctl_io *io);
13579         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13580
13581         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13582
13583         fe_done =
13584             control_softc->ctl_ports[targ_port]->fe_done;
13585
13586 #ifdef CTL_TIME_IO
13587         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13588                 char str[256];
13589                 char path_str[64];
13590                 struct sbuf sb;
13591
13592                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13593                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13594
13595                 sbuf_cat(&sb, path_str);
13596                 switch (io->io_hdr.io_type) {
13597                 case CTL_IO_SCSI:
13598                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13599                         sbuf_printf(&sb, "\n");
13600                         sbuf_cat(&sb, path_str);
13601                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13602                                     io->scsiio.tag_num, io->scsiio.tag_type);
13603                         break;
13604                 case CTL_IO_TASK:
13605                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13606                                     "Tag Type: %d\n", io->taskio.task_action,
13607                                     io->taskio.tag_num, io->taskio.tag_type);
13608                         break;
13609                 default:
13610                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13611                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13612                         break;
13613                 }
13614                 sbuf_cat(&sb, path_str);
13615                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13616                             (intmax_t)time_uptime - io->io_hdr.start_time);
13617                 sbuf_finish(&sb);
13618                 printf("%s", sbuf_data(&sb));
13619         }
13620 #endif /* CTL_TIME_IO */
13621
13622         switch (io->io_hdr.io_type) {
13623         case CTL_IO_SCSI:
13624                 break;
13625         case CTL_IO_TASK:
13626                 if (bootverbose || verbose > 0)
13627                         ctl_io_error_print(io, NULL);
13628                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13629                         ctl_free_io(io);
13630                 else
13631                         fe_done(io);
13632                 return (CTL_RETVAL_COMPLETE);
13633                 break;
13634         default:
13635                 printf("ctl_process_done: invalid io type %d\n",
13636                        io->io_hdr.io_type);
13637                 panic("ctl_process_done: invalid io type %d\n",
13638                       io->io_hdr.io_type);
13639                 break; /* NOTREACHED */
13640         }
13641
13642         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13643         if (lun == NULL) {
13644                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13645                                  io->io_hdr.nexus.targ_mapped_lun));
13646                 fe_done(io);
13647                 goto bailout;
13648         }
13649         ctl_softc = lun->ctl_softc;
13650
13651         mtx_lock(&lun->lun_lock);
13652
13653         /*
13654          * Check to see if we have any errors to inject here.  We only
13655          * inject errors for commands that don't already have errors set.
13656          */
13657         if ((STAILQ_FIRST(&lun->error_list) != NULL)
13658          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13659                 ctl_inject_error(lun, io);
13660
13661         /*
13662          * XXX KDM how do we treat commands that aren't completed
13663          * successfully?
13664          *
13665          * XXX KDM should we also track I/O latency?
13666          */
13667         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13668             io->io_hdr.io_type == CTL_IO_SCSI) {
13669 #ifdef CTL_TIME_IO
13670                 struct bintime cur_bt;
13671 #endif
13672                 int type;
13673
13674                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13675                     CTL_FLAG_DATA_IN)
13676                         type = CTL_STATS_READ;
13677                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13678                     CTL_FLAG_DATA_OUT)
13679                         type = CTL_STATS_WRITE;
13680                 else
13681                         type = CTL_STATS_NO_IO;
13682
13683                 lun->stats.ports[targ_port].bytes[type] +=
13684                     io->scsiio.kern_total_len;
13685                 lun->stats.ports[targ_port].operations[type]++;
13686 #ifdef CTL_TIME_IO
13687                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13688                    &io->io_hdr.dma_bt);
13689                 lun->stats.ports[targ_port].num_dmas[type] +=
13690                     io->io_hdr.num_dmas;
13691                 getbintime(&cur_bt);
13692                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13693                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13694 #endif
13695         }
13696
13697         /*
13698          * Remove this from the OOA queue.
13699          */
13700         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13701
13702         /*
13703          * Run through the blocked queue on this LUN and see if anything
13704          * has become unblocked, now that this transaction is done.
13705          */
13706         ctl_check_blocked(lun);
13707
13708         /*
13709          * If the LUN has been invalidated, free it if there is nothing
13710          * left on its OOA queue.
13711          */
13712         if ((lun->flags & CTL_LUN_INVALID)
13713          && TAILQ_EMPTY(&lun->ooa_queue)) {
13714                 mtx_unlock(&lun->lun_lock);
13715                 mtx_lock(&ctl_softc->ctl_lock);
13716                 ctl_free_lun(lun);
13717                 mtx_unlock(&ctl_softc->ctl_lock);
13718         } else
13719                 mtx_unlock(&lun->lun_lock);
13720
13721         /*
13722          * If this command has been aborted, make sure we set the status
13723          * properly.  The FETD is responsible for freeing the I/O and doing
13724          * whatever it needs to do to clean up its state.
13725          */
13726         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13727                 ctl_set_task_aborted(&io->scsiio);
13728
13729         /*
13730          * We print out status for every task management command.  For SCSI
13731          * commands, we filter out any unit attention errors; they happen
13732          * on every boot, and would clutter up the log.  Note:  task
13733          * management commands aren't printed here, they are printed above,
13734          * since they should never even make it down here.
13735          */
13736         switch (io->io_hdr.io_type) {
13737         case CTL_IO_SCSI: {
13738                 int error_code, sense_key, asc, ascq;
13739
13740                 sense_key = 0;
13741
13742                 if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13743                  && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13744                         /*
13745                          * Since this is just for printing, no need to
13746                          * show errors here.
13747                          */
13748                         scsi_extract_sense_len(&io->scsiio.sense_data,
13749                                                io->scsiio.sense_len,
13750                                                &error_code,
13751                                                &sense_key,
13752                                                &asc,
13753                                                &ascq,
13754                                                /*show_errors*/ 0);
13755                 }
13756
13757                 if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13758                  && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13759                   || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13760                   || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13761
13762                         if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13763                                 ctl_softc->skipped_prints++;
13764                         } else {
13765                                 uint32_t skipped_prints;
13766
13767                                 skipped_prints = ctl_softc->skipped_prints;
13768
13769                                 ctl_softc->skipped_prints = 0;
13770                                 ctl_softc->last_print_jiffies = time_uptime;
13771
13772                                 if (skipped_prints > 0) {
13773 #ifdef NEEDTOPORT
13774                                         csevent_log(CSC_CTL | CSC_SHELF_SW |
13775                                             CTL_ERROR_REPORT,
13776                                             csevent_LogType_Trace,
13777                                             csevent_Severity_Information,
13778                                             csevent_AlertLevel_Green,
13779                                             csevent_FRU_Firmware,
13780                                             csevent_FRU_Unknown,
13781                                             "High CTL error volume, %d prints "
13782                                             "skipped", skipped_prints);
13783 #endif
13784                                 }
13785                                 if (bootverbose || verbose > 0)
13786                                         ctl_io_error_print(io, NULL);
13787                         }
13788                 }
13789                 break;
13790         }
13791         case CTL_IO_TASK:
13792                 if (bootverbose || verbose > 0)
13793                         ctl_io_error_print(io, NULL);
13794                 break;
13795         default:
13796                 break;
13797         }
13798
13799         /*
13800          * Tell the FETD or the other shelf controller we're done with this
13801          * command.  Note that only SCSI commands get to this point.  Task
13802          * management commands are completed above.
13803          *
13804          * We only send status to the other controller if we're in XFER
13805          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13806          * received the I/O (from CTL's perspective), and so the status is
13807          * generated there.
13808          * 
13809          * XXX KDM if we hold the lock here, we could cause a deadlock
13810          * if the frontend comes back in in this context to queue
13811          * something.
13812          */
13813         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13814          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13815                 union ctl_ha_msg msg;
13816
13817                 memset(&msg, 0, sizeof(msg));
13818                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13819                 msg.hdr.original_sc = io->io_hdr.original_sc;
13820                 msg.hdr.nexus = io->io_hdr.nexus;
13821                 msg.hdr.status = io->io_hdr.status;
13822                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13823                 msg.scsi.tag_num = io->scsiio.tag_num;
13824                 msg.scsi.tag_type = io->scsiio.tag_type;
13825                 msg.scsi.sense_len = io->scsiio.sense_len;
13826                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13827                 msg.scsi.residual = io->scsiio.residual;
13828                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13829                        sizeof(io->scsiio.sense_data));
13830                 /*
13831                  * We copy this whether or not this is an I/O-related
13832                  * command.  Otherwise, we'd have to go and check to see
13833                  * whether it's a read/write command, and it really isn't
13834                  * worth it.
13835                  */
13836                 memcpy(&msg.scsi.lbalen,
13837                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13838                        sizeof(msg.scsi.lbalen));
13839
13840                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13841                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13842                         /* XXX do something here */
13843                 }
13844
13845                 ctl_free_io(io);
13846         } else 
13847                 fe_done(io);
13848
13849 bailout:
13850
13851         return (CTL_RETVAL_COMPLETE);
13852 }
13853
13854 #ifdef CTL_WITH_CA
13855 /*
13856  * Front end should call this if it doesn't do autosense.  When the request
13857  * sense comes back in from the initiator, we'll dequeue this and send it.
13858  */
13859 int
13860 ctl_queue_sense(union ctl_io *io)
13861 {
13862         struct ctl_lun *lun;
13863         struct ctl_softc *ctl_softc;
13864         uint32_t initidx, targ_lun;
13865
13866         ctl_softc = control_softc;
13867
13868         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13869
13870         /*
13871          * LUN lookup will likely move to the ctl_work_thread() once we
13872          * have our new queueing infrastructure (that doesn't put things on
13873          * a per-LUN queue initially).  That is so that we can handle
13874          * things like an INQUIRY to a LUN that we don't have enabled.  We
13875          * can't deal with that right now.
13876          */
13877         mtx_lock(&ctl_softc->ctl_lock);
13878
13879         /*
13880          * If we don't have a LUN for this, just toss the sense
13881          * information.
13882          */
13883         targ_lun = io->io_hdr.nexus.targ_lun;
13884         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13885         if ((targ_lun < CTL_MAX_LUNS)
13886          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13887                 lun = ctl_softc->ctl_luns[targ_lun];
13888         else
13889                 goto bailout;
13890
13891         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13892
13893         mtx_lock(&lun->lun_lock);
13894         /*
13895          * Already have CA set for this LUN...toss the sense information.
13896          */
13897         if (ctl_is_set(lun->have_ca, initidx)) {
13898                 mtx_unlock(&lun->lun_lock);
13899                 goto bailout;
13900         }
13901
13902         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13903                ctl_min(sizeof(lun->pending_sense[initidx]),
13904                sizeof(io->scsiio.sense_data)));
13905         ctl_set_mask(lun->have_ca, initidx);
13906         mtx_unlock(&lun->lun_lock);
13907
13908 bailout:
13909         mtx_unlock(&ctl_softc->ctl_lock);
13910
13911         ctl_free_io(io);
13912
13913         return (CTL_RETVAL_COMPLETE);
13914 }
13915 #endif
13916
13917 /*
13918  * Primary command inlet from frontend ports.  All SCSI and task I/O
13919  * requests must go through this function.
13920  */
13921 int
13922 ctl_queue(union ctl_io *io)
13923 {
13924         struct ctl_softc *ctl_softc;
13925
13926         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13927
13928         ctl_softc = control_softc;
13929
13930 #ifdef CTL_TIME_IO
13931         io->io_hdr.start_time = time_uptime;
13932         getbintime(&io->io_hdr.start_bt);
13933 #endif /* CTL_TIME_IO */
13934
13935         /* Map FE-specific LUN ID into global one. */
13936         io->io_hdr.nexus.targ_mapped_lun =
13937             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13938
13939         switch (io->io_hdr.io_type) {
13940         case CTL_IO_SCSI:
13941         case CTL_IO_TASK:
13942                 ctl_enqueue_incoming(io);
13943                 break;
13944         default:
13945                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13946                 return (EINVAL);
13947         }
13948
13949         return (CTL_RETVAL_COMPLETE);
13950 }
13951
13952 #ifdef CTL_IO_DELAY
13953 static void
13954 ctl_done_timer_wakeup(void *arg)
13955 {
13956         union ctl_io *io;
13957
13958         io = (union ctl_io *)arg;
13959         ctl_done(io);
13960 }
13961 #endif /* CTL_IO_DELAY */
13962
13963 void
13964 ctl_done(union ctl_io *io)
13965 {
13966         struct ctl_softc *ctl_softc;
13967
13968         ctl_softc = control_softc;
13969
13970         /*
13971          * Enable this to catch duplicate completion issues.
13972          */
13973 #if 0
13974         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13975                 printf("%s: type %d msg %d cdb %x iptl: "
13976                        "%d:%d:%d:%d tag 0x%04x "
13977                        "flag %#x status %x\n",
13978                         __func__,
13979                         io->io_hdr.io_type,
13980                         io->io_hdr.msg_type,
13981                         io->scsiio.cdb[0],
13982                         io->io_hdr.nexus.initid.id,
13983                         io->io_hdr.nexus.targ_port,
13984                         io->io_hdr.nexus.targ_target.id,
13985                         io->io_hdr.nexus.targ_lun,
13986                         (io->io_hdr.io_type ==
13987                         CTL_IO_TASK) ?
13988                         io->taskio.tag_num :
13989                         io->scsiio.tag_num,
13990                         io->io_hdr.flags,
13991                         io->io_hdr.status);
13992         } else
13993                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13994 #endif
13995
13996         /*
13997          * This is an internal copy of an I/O, and should not go through
13998          * the normal done processing logic.
13999          */
14000         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14001                 return;
14002
14003         /*
14004          * We need to send a msg to the serializing shelf to finish the IO
14005          * as well.  We don't send a finish message to the other shelf if
14006          * this is a task management command.  Task management commands
14007          * aren't serialized in the OOA queue, but rather just executed on
14008          * both shelf controllers for commands that originated on that
14009          * controller.
14010          */
14011         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14012          && (io->io_hdr.io_type != CTL_IO_TASK)) {
14013                 union ctl_ha_msg msg_io;
14014
14015                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14016                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14017                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14018                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14019                 }
14020                 /* continue on to finish IO */
14021         }
14022 #ifdef CTL_IO_DELAY
14023         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14024                 struct ctl_lun *lun;
14025
14026                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14027
14028                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14029         } else {
14030                 struct ctl_lun *lun;
14031
14032                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14033
14034                 if ((lun != NULL)
14035                  && (lun->delay_info.done_delay > 0)) {
14036                         struct callout *callout;
14037
14038                         callout = (struct callout *)&io->io_hdr.timer_bytes;
14039                         callout_init(callout, /*mpsafe*/ 1);
14040                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14041                         callout_reset(callout,
14042                                       lun->delay_info.done_delay * hz,
14043                                       ctl_done_timer_wakeup, io);
14044                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14045                                 lun->delay_info.done_delay = 0;
14046                         return;
14047                 }
14048         }
14049 #endif /* CTL_IO_DELAY */
14050
14051         ctl_enqueue_done(io);
14052 }
14053
14054 int
14055 ctl_isc(struct ctl_scsiio *ctsio)
14056 {
14057         struct ctl_lun *lun;
14058         int retval;
14059
14060         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14061
14062         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14063
14064         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14065
14066         retval = lun->backend->data_submit((union ctl_io *)ctsio);
14067
14068         return (retval);
14069 }
14070
14071
14072 static void
14073 ctl_work_thread(void *arg)
14074 {
14075         struct ctl_thread *thr = (struct ctl_thread *)arg;
14076         struct ctl_softc *softc = thr->ctl_softc;
14077         union ctl_io *io;
14078         int retval;
14079
14080         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14081
14082         for (;;) {
14083                 retval = 0;
14084
14085                 /*
14086                  * We handle the queues in this order:
14087                  * - ISC
14088                  * - done queue (to free up resources, unblock other commands)
14089                  * - RtR queue
14090                  * - incoming queue
14091                  *
14092                  * If those queues are empty, we break out of the loop and
14093                  * go to sleep.
14094                  */
14095                 mtx_lock(&thr->queue_lock);
14096                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14097                 if (io != NULL) {
14098                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14099                         mtx_unlock(&thr->queue_lock);
14100                         ctl_handle_isc(io);
14101                         continue;
14102                 }
14103                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14104                 if (io != NULL) {
14105                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14106                         /* clear any blocked commands, call fe_done */
14107                         mtx_unlock(&thr->queue_lock);
14108                         retval = ctl_process_done(io);
14109                         continue;
14110                 }
14111                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14112                 if (io != NULL) {
14113                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14114                         mtx_unlock(&thr->queue_lock);
14115                         if (io->io_hdr.io_type == CTL_IO_TASK)
14116                                 ctl_run_task(io);
14117                         else
14118                                 ctl_scsiio_precheck(softc, &io->scsiio);
14119                         continue;
14120                 }
14121                 if (!ctl_pause_rtr) {
14122                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14123                         if (io != NULL) {
14124                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14125                                 mtx_unlock(&thr->queue_lock);
14126                                 retval = ctl_scsiio(&io->scsiio);
14127                                 if (retval != CTL_RETVAL_COMPLETE)
14128                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14129                                 continue;
14130                         }
14131                 }
14132
14133                 /* Sleep until we have something to do. */
14134                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14135         }
14136 }
14137
14138 static void
14139 ctl_lun_thread(void *arg)
14140 {
14141         struct ctl_softc *softc = (struct ctl_softc *)arg;
14142         struct ctl_be_lun *be_lun;
14143         int retval;
14144
14145         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14146
14147         for (;;) {
14148                 retval = 0;
14149                 mtx_lock(&softc->ctl_lock);
14150                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14151                 if (be_lun != NULL) {
14152                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14153                         mtx_unlock(&softc->ctl_lock);
14154                         ctl_create_lun(be_lun);
14155                         continue;
14156                 }
14157
14158                 /* Sleep until we have something to do. */
14159                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14160                     PDROP | PRIBIO, "-", 0);
14161         }
14162 }
14163
14164 static void
14165 ctl_enqueue_incoming(union ctl_io *io)
14166 {
14167         struct ctl_softc *softc = control_softc;
14168         struct ctl_thread *thr;
14169         u_int idx;
14170
14171         idx = (io->io_hdr.nexus.targ_port * 127 +
14172                io->io_hdr.nexus.initid.id) % worker_threads;
14173         thr = &softc->threads[idx];
14174         mtx_lock(&thr->queue_lock);
14175         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14176         mtx_unlock(&thr->queue_lock);
14177         wakeup(thr);
14178 }
14179
14180 static void
14181 ctl_enqueue_rtr(union ctl_io *io)
14182 {
14183         struct ctl_softc *softc = control_softc;
14184         struct ctl_thread *thr;
14185
14186         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14187         mtx_lock(&thr->queue_lock);
14188         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14189         mtx_unlock(&thr->queue_lock);
14190         wakeup(thr);
14191 }
14192
14193 static void
14194 ctl_enqueue_done(union ctl_io *io)
14195 {
14196         struct ctl_softc *softc = control_softc;
14197         struct ctl_thread *thr;
14198
14199         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14200         mtx_lock(&thr->queue_lock);
14201         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14202         mtx_unlock(&thr->queue_lock);
14203         wakeup(thr);
14204 }
14205
14206 static void
14207 ctl_enqueue_isc(union ctl_io *io)
14208 {
14209         struct ctl_softc *softc = control_softc;
14210         struct ctl_thread *thr;
14211
14212         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14213         mtx_lock(&thr->queue_lock);
14214         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14215         mtx_unlock(&thr->queue_lock);
14216         wakeup(thr);
14217 }
14218
14219 /* Initialization and failover */
14220
14221 void
14222 ctl_init_isc_msg(void)
14223 {
14224         printf("CTL: Still calling this thing\n");
14225 }
14226
14227 /*
14228  * Init component
14229  *      Initializes component into configuration defined by bootMode
14230  *      (see hasc-sv.c)
14231  *      returns hasc_Status:
14232  *              OK
14233  *              ERROR - fatal error
14234  */
14235 static ctl_ha_comp_status
14236 ctl_isc_init(struct ctl_ha_component *c)
14237 {
14238         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14239
14240         c->status = ret;
14241         return ret;
14242 }
14243
14244 /* Start component
14245  *      Starts component in state requested. If component starts successfully,
14246  *      it must set its own state to the requestrd state
14247  *      When requested state is HASC_STATE_HA, the component may refine it
14248  *      by adding _SLAVE or _MASTER flags.
14249  *      Currently allowed state transitions are:
14250  *      UNKNOWN->HA             - initial startup
14251  *      UNKNOWN->SINGLE - initial startup when no parter detected
14252  *      HA->SINGLE              - failover
14253  * returns ctl_ha_comp_status:
14254  *              OK      - component successfully started in requested state
14255  *              FAILED  - could not start the requested state, failover may
14256  *                        be possible
14257  *              ERROR   - fatal error detected, no future startup possible
14258  */
14259 static ctl_ha_comp_status
14260 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14261 {
14262         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14263
14264         printf("%s: go\n", __func__);
14265
14266         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14267         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14268                 ctl_is_single = 0;
14269                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14270                     != CTL_HA_STATUS_SUCCESS) {
14271                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14272                         ret = CTL_HA_COMP_STATUS_ERROR;
14273                 }
14274         } else if (CTL_HA_STATE_IS_HA(c->state)
14275                 && CTL_HA_STATE_IS_SINGLE(state)){
14276                 // HA->SINGLE transition
14277                 ctl_failover();
14278                 ctl_is_single = 1;
14279         } else {
14280                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14281                        c->state, state);
14282                 ret = CTL_HA_COMP_STATUS_ERROR;
14283         }
14284         if (CTL_HA_STATE_IS_SINGLE(state))
14285                 ctl_is_single = 1;
14286
14287         c->state = state;
14288         c->status = ret;
14289         return ret;
14290 }
14291
14292 /*
14293  * Quiesce component
14294  * The component must clear any error conditions (set status to OK) and
14295  * prepare itself to another Start call
14296  * returns ctl_ha_comp_status:
14297  *      OK
14298  *      ERROR
14299  */
14300 static ctl_ha_comp_status
14301 ctl_isc_quiesce(struct ctl_ha_component *c)
14302 {
14303         int ret = CTL_HA_COMP_STATUS_OK;
14304
14305         ctl_pause_rtr = 1;
14306         c->status = ret;
14307         return ret;
14308 }
14309
14310 struct ctl_ha_component ctl_ha_component_ctlisc =
14311 {
14312         .name = "CTL ISC",
14313         .state = CTL_HA_STATE_UNKNOWN,
14314         .init = ctl_isc_init,
14315         .start = ctl_isc_start,
14316         .quiesce = ctl_isc_quiesce
14317 };
14318
14319 /*
14320  *  vim: ts=8
14321  */