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