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