]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/ctl/ctl.c
Implement ABORT TASK SET and I_T NEXUS RESET task management functions.
[FreeBSD/FreeBSD.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 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
312     &worker_threads, 1, "Number of worker threads");
313 static int verbose = 0;
314 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
315     &verbose, 0, "Show SCSI errors returned to initiator");
316
317 /*
318  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
319  * SCSI Ports (0x88), Block limits (0xB0) and
320  * Logical Block Provisioning (0xB2)
321  */
322 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   6
323
324 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
325                                   int param);
326 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
327 static int ctl_init(void);
328 void ctl_shutdown(void);
329 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
330 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
331 static void ctl_ioctl_online(void *arg);
332 static void ctl_ioctl_offline(void *arg);
333 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
334 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
335 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
336 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
337 static int ctl_ioctl_submit_wait(union ctl_io *io);
338 static void ctl_ioctl_datamove(union ctl_io *io);
339 static void ctl_ioctl_done(union ctl_io *io);
340 static void ctl_ioctl_hard_startstop_callback(void *arg,
341                                               struct cfi_metatask *metatask);
342 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
343 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
344                               struct ctl_ooa *ooa_hdr,
345                               struct ctl_ooa_entry *kern_entries);
346 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
347                      struct thread *td);
348 uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
349 uint32_t ctl_port_idx(int port_num);
350 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
351 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
352 #ifdef unused
353 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
354                                    uint32_t targ_target, uint32_t targ_lun,
355                                    int can_wait);
356 static void ctl_kfree_io(union ctl_io *io);
357 #endif /* unused */
358 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
359                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
360 static int ctl_free_lun(struct ctl_lun *lun);
361 static void ctl_create_lun(struct ctl_be_lun *be_lun);
362 /**
363 static void ctl_failover_change_pages(struct ctl_softc *softc,
364                                       struct ctl_scsiio *ctsio, int master);
365 **/
366
367 static int ctl_do_mode_select(union ctl_io *io);
368 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
369                            uint64_t res_key, uint64_t sa_res_key,
370                            uint8_t type, uint32_t residx,
371                            struct ctl_scsiio *ctsio,
372                            struct scsi_per_res_out *cdb,
373                            struct scsi_per_res_out_parms* param);
374 static void ctl_pro_preempt_other(struct ctl_lun *lun,
375                                   union ctl_ha_msg *msg);
376 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
377 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
378 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
379 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
380 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
381                                          int alloc_len);
382 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
383                                          int alloc_len);
384 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
385 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
386 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
387 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
388 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
389 static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
390                                          union ctl_io *ooa_io);
391 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
392                                 union ctl_io *starting_io);
393 static int ctl_check_blocked(struct ctl_lun *lun);
394 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
395                                 struct ctl_lun *lun,
396                                 const struct ctl_cmd_entry *entry,
397                                 struct ctl_scsiio *ctsio);
398 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
399 static void ctl_failover(void);
400 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
401                                struct ctl_scsiio *ctsio);
402 static int ctl_scsiio(struct ctl_scsiio *ctsio);
403
404 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
405 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
406                             ctl_ua_type ua_type);
407 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
408                          ctl_ua_type ua_type);
409 static int ctl_abort_task(union ctl_io *io);
410 static int ctl_abort_task_set(union ctl_io *io);
411 static int ctl_i_t_nexus_reset(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 = 0, 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_ATSS | RST_LURS | RST_TRS;
7488         data->byte2 |= RST_ITNRS;
7489
7490         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7491         ctsio->be_move_done = ctl_config_move_done;
7492
7493         ctl_datamove((union ctl_io *)ctsio);
7494         return (retval);
7495 }
7496
7497 int
7498 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7499 {
7500         struct ctl_lun *lun;
7501         struct scsi_report_timestamp *cdb;
7502         struct scsi_report_timestamp_data *data;
7503         struct timeval tv;
7504         int64_t timestamp;
7505         int retval;
7506         int alloc_len, total_len;
7507
7508         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7509
7510         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7511         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7512
7513         retval = CTL_RETVAL_COMPLETE;
7514
7515         total_len = sizeof(struct scsi_report_timestamp_data);
7516         alloc_len = scsi_4btoul(cdb->length);
7517
7518         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7519
7520         ctsio->kern_sg_entries = 0;
7521
7522         if (total_len < alloc_len) {
7523                 ctsio->residual = alloc_len - total_len;
7524                 ctsio->kern_data_len = total_len;
7525                 ctsio->kern_total_len = total_len;
7526         } else {
7527                 ctsio->residual = 0;
7528                 ctsio->kern_data_len = alloc_len;
7529                 ctsio->kern_total_len = alloc_len;
7530         }
7531         ctsio->kern_data_resid = 0;
7532         ctsio->kern_rel_offset = 0;
7533
7534         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7535         scsi_ulto2b(sizeof(*data) - 2, data->length);
7536         data->origin = RTS_ORIG_OUTSIDE;
7537         getmicrotime(&tv);
7538         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7539         scsi_ulto4b(timestamp >> 16, data->timestamp);
7540         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7541
7542         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7543         ctsio->be_move_done = ctl_config_move_done;
7544
7545         ctl_datamove((union ctl_io *)ctsio);
7546         return (retval);
7547 }
7548
7549 int
7550 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7551 {
7552         struct scsi_per_res_in *cdb;
7553         int alloc_len, total_len = 0;
7554         /* struct scsi_per_res_in_rsrv in_data; */
7555         struct ctl_lun *lun;
7556         struct ctl_softc *softc;
7557
7558         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7559
7560         softc = control_softc;
7561
7562         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7563
7564         alloc_len = scsi_2btoul(cdb->length);
7565
7566         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7567
7568 retry:
7569         mtx_lock(&lun->lun_lock);
7570         switch (cdb->action) {
7571         case SPRI_RK: /* read keys */
7572                 total_len = sizeof(struct scsi_per_res_in_keys) +
7573                         lun->pr_key_count *
7574                         sizeof(struct scsi_per_res_key);
7575                 break;
7576         case SPRI_RR: /* read reservation */
7577                 if (lun->flags & CTL_LUN_PR_RESERVED)
7578                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7579                 else
7580                         total_len = sizeof(struct scsi_per_res_in_header);
7581                 break;
7582         case SPRI_RC: /* report capabilities */
7583                 total_len = sizeof(struct scsi_per_res_cap);
7584                 break;
7585         default:
7586                 panic("Invalid PR type %x", cdb->action);
7587         }
7588         mtx_unlock(&lun->lun_lock);
7589
7590         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7591
7592         if (total_len < alloc_len) {
7593                 ctsio->residual = alloc_len - total_len;
7594                 ctsio->kern_data_len = total_len;
7595                 ctsio->kern_total_len = total_len;
7596         } else {
7597                 ctsio->residual = 0;
7598                 ctsio->kern_data_len = alloc_len;
7599                 ctsio->kern_total_len = alloc_len;
7600         }
7601
7602         ctsio->kern_data_resid = 0;
7603         ctsio->kern_rel_offset = 0;
7604         ctsio->kern_sg_entries = 0;
7605
7606         mtx_lock(&lun->lun_lock);
7607         switch (cdb->action) {
7608         case SPRI_RK: { // read keys
7609         struct scsi_per_res_in_keys *res_keys;
7610                 int i, key_count;
7611
7612                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7613
7614                 /*
7615                  * We had to drop the lock to allocate our buffer, which
7616                  * leaves time for someone to come in with another
7617                  * persistent reservation.  (That is unlikely, though,
7618                  * since this should be the only persistent reservation
7619                  * command active right now.)
7620                  */
7621                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7622                     (lun->pr_key_count *
7623                      sizeof(struct scsi_per_res_key)))){
7624                         mtx_unlock(&lun->lun_lock);
7625                         free(ctsio->kern_data_ptr, M_CTL);
7626                         printf("%s: reservation length changed, retrying\n",
7627                                __func__);
7628                         goto retry;
7629                 }
7630
7631                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7632
7633                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7634                              lun->pr_key_count, res_keys->header.length);
7635
7636                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7637                         if (!lun->per_res[i].registered)
7638                                 continue;
7639
7640                         /*
7641                          * We used lun->pr_key_count to calculate the
7642                          * size to allocate.  If it turns out the number of
7643                          * initiators with the registered flag set is
7644                          * larger than that (i.e. they haven't been kept in
7645                          * sync), we've got a problem.
7646                          */
7647                         if (key_count >= lun->pr_key_count) {
7648 #ifdef NEEDTOPORT
7649                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7650                                             CTL_PR_ERROR,
7651                                             csevent_LogType_Fault,
7652                                             csevent_AlertLevel_Yellow,
7653                                             csevent_FRU_ShelfController,
7654                                             csevent_FRU_Firmware,
7655                                         csevent_FRU_Unknown,
7656                                             "registered keys %d >= key "
7657                                             "count %d", key_count,
7658                                             lun->pr_key_count);
7659 #endif
7660                                 key_count++;
7661                                 continue;
7662                         }
7663                         memcpy(res_keys->keys[key_count].key,
7664                                lun->per_res[i].res_key.key,
7665                                ctl_min(sizeof(res_keys->keys[key_count].key),
7666                                sizeof(lun->per_res[i].res_key)));
7667                         key_count++;
7668                 }
7669                 break;
7670         }
7671         case SPRI_RR: { // read reservation
7672                 struct scsi_per_res_in_rsrv *res;
7673                 int tmp_len, header_only;
7674
7675                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7676
7677                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7678
7679                 if (lun->flags & CTL_LUN_PR_RESERVED)
7680                 {
7681                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7682                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7683                                     res->header.length);
7684                         header_only = 0;
7685                 } else {
7686                         tmp_len = sizeof(struct scsi_per_res_in_header);
7687                         scsi_ulto4b(0, res->header.length);
7688                         header_only = 1;
7689                 }
7690
7691                 /*
7692                  * We had to drop the lock to allocate our buffer, which
7693                  * leaves time for someone to come in with another
7694                  * persistent reservation.  (That is unlikely, though,
7695                  * since this should be the only persistent reservation
7696                  * command active right now.)
7697                  */
7698                 if (tmp_len != total_len) {
7699                         mtx_unlock(&lun->lun_lock);
7700                         free(ctsio->kern_data_ptr, M_CTL);
7701                         printf("%s: reservation status changed, retrying\n",
7702                                __func__);
7703                         goto retry;
7704                 }
7705
7706                 /*
7707                  * No reservation held, so we're done.
7708                  */
7709                 if (header_only != 0)
7710                         break;
7711
7712                 /*
7713                  * If the registration is an All Registrants type, the key
7714                  * is 0, since it doesn't really matter.
7715                  */
7716                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7717                         memcpy(res->data.reservation,
7718                                &lun->per_res[lun->pr_res_idx].res_key,
7719                                sizeof(struct scsi_per_res_key));
7720                 }
7721                 res->data.scopetype = lun->res_type;
7722                 break;
7723         }
7724         case SPRI_RC:     //report capabilities
7725         {
7726                 struct scsi_per_res_cap *res_cap;
7727                 uint16_t type_mask;
7728
7729                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7730                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7731                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7732                 type_mask = SPRI_TM_WR_EX_AR |
7733                             SPRI_TM_EX_AC_RO |
7734                             SPRI_TM_WR_EX_RO |
7735                             SPRI_TM_EX_AC |
7736                             SPRI_TM_WR_EX |
7737                             SPRI_TM_EX_AC_AR;
7738                 scsi_ulto2b(type_mask, res_cap->type_mask);
7739                 break;
7740         }
7741         case SPRI_RS: //read full status
7742         default:
7743                 /*
7744                  * This is a bug, because we just checked for this above,
7745                  * and should have returned an error.
7746                  */
7747                 panic("Invalid PR type %x", cdb->action);
7748                 break; /* NOTREACHED */
7749         }
7750         mtx_unlock(&lun->lun_lock);
7751
7752         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7753         ctsio->be_move_done = ctl_config_move_done;
7754
7755         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7756                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7757                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7758                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7759                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7760
7761         ctl_datamove((union ctl_io *)ctsio);
7762
7763         return (CTL_RETVAL_COMPLETE);
7764 }
7765
7766 /*
7767  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7768  * it should return.
7769  */
7770 static int
7771 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7772                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7773                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7774                 struct scsi_per_res_out_parms* param)
7775 {
7776         union ctl_ha_msg persis_io;
7777         int retval, i;
7778         int isc_retval;
7779
7780         retval = 0;
7781
7782         mtx_lock(&lun->lun_lock);
7783         if (sa_res_key == 0) {
7784                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7785                         /* validate scope and type */
7786                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7787                              SPR_LU_SCOPE) {
7788                                 mtx_unlock(&lun->lun_lock);
7789                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7790                                                       /*sks_valid*/ 1,
7791                                                       /*command*/ 1,
7792                                                       /*field*/ 2,
7793                                                       /*bit_valid*/ 1,
7794                                                       /*bit*/ 4);
7795                                 ctl_done((union ctl_io *)ctsio);
7796                                 return (1);
7797                         }
7798
7799                         if (type>8 || type==2 || type==4 || type==0) {
7800                                 mtx_unlock(&lun->lun_lock);
7801                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7802                                                       /*sks_valid*/ 1,
7803                                                       /*command*/ 1,
7804                                                       /*field*/ 2,
7805                                                       /*bit_valid*/ 1,
7806                                                       /*bit*/ 0);
7807                                 ctl_done((union ctl_io *)ctsio);
7808                                 return (1);
7809                         }
7810
7811                         /* temporarily unregister this nexus */
7812                         lun->per_res[residx].registered = 0;
7813
7814                         /*
7815                          * Unregister everybody else and build UA for
7816                          * them
7817                          */
7818                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7819                                 if (lun->per_res[i].registered == 0)
7820                                         continue;
7821
7822                                 if (!persis_offset
7823                                  && i <CTL_MAX_INITIATORS)
7824                                         lun->pending_sense[i].ua_pending |=
7825                                                 CTL_UA_REG_PREEMPT;
7826                                 else if (persis_offset
7827                                       && i >= persis_offset)
7828                                         lun->pending_sense[i-persis_offset
7829                                                 ].ua_pending |=
7830                                                 CTL_UA_REG_PREEMPT;
7831                                 lun->per_res[i].registered = 0;
7832                                 memset(&lun->per_res[i].res_key, 0,
7833                                        sizeof(struct scsi_per_res_key));
7834                         }
7835                         lun->per_res[residx].registered = 1;
7836                         lun->pr_key_count = 1;
7837                         lun->res_type = type;
7838                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7839                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7840                                 lun->pr_res_idx = residx;
7841
7842                         /* send msg to other side */
7843                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7844                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7845                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7846                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7847                         persis_io.pr.pr_info.res_type = type;
7848                         memcpy(persis_io.pr.pr_info.sa_res_key,
7849                                param->serv_act_res_key,
7850                                sizeof(param->serv_act_res_key));
7851                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7852                              &persis_io, sizeof(persis_io), 0)) >
7853                              CTL_HA_STATUS_SUCCESS) {
7854                                 printf("CTL:Persis Out error returned "
7855                                        "from ctl_ha_msg_send %d\n",
7856                                        isc_retval);
7857                         }
7858                 } else {
7859                         /* not all registrants */
7860                         mtx_unlock(&lun->lun_lock);
7861                         free(ctsio->kern_data_ptr, M_CTL);
7862                         ctl_set_invalid_field(ctsio,
7863                                               /*sks_valid*/ 1,
7864                                               /*command*/ 0,
7865                                               /*field*/ 8,
7866                                               /*bit_valid*/ 0,
7867                                               /*bit*/ 0);
7868                         ctl_done((union ctl_io *)ctsio);
7869                         return (1);
7870                 }
7871         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7872                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7873                 int found = 0;
7874
7875                 if (res_key == sa_res_key) {
7876                         /* special case */
7877                         /*
7878                          * The spec implies this is not good but doesn't
7879                          * say what to do. There are two choices either
7880                          * generate a res conflict or check condition
7881                          * with illegal field in parameter data. Since
7882                          * that is what is done when the sa_res_key is
7883                          * zero I'll take that approach since this has
7884                          * to do with the sa_res_key.
7885                          */
7886                         mtx_unlock(&lun->lun_lock);
7887                         free(ctsio->kern_data_ptr, M_CTL);
7888                         ctl_set_invalid_field(ctsio,
7889                                               /*sks_valid*/ 1,
7890                                               /*command*/ 0,
7891                                               /*field*/ 8,
7892                                               /*bit_valid*/ 0,
7893                                               /*bit*/ 0);
7894                         ctl_done((union ctl_io *)ctsio);
7895                         return (1);
7896                 }
7897
7898                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7899                         if (lun->per_res[i].registered
7900                          && memcmp(param->serv_act_res_key,
7901                             lun->per_res[i].res_key.key,
7902                             sizeof(struct scsi_per_res_key)) != 0)
7903                                 continue;
7904
7905                         found = 1;
7906                         lun->per_res[i].registered = 0;
7907                         memset(&lun->per_res[i].res_key, 0,
7908                                sizeof(struct scsi_per_res_key));
7909                         lun->pr_key_count--;
7910
7911                         if (!persis_offset
7912                          && i < CTL_MAX_INITIATORS)
7913                                 lun->pending_sense[i].ua_pending |=
7914                                         CTL_UA_REG_PREEMPT;
7915                         else if (persis_offset
7916                               && i >= persis_offset)
7917                                 lun->pending_sense[i-persis_offset].ua_pending|=
7918                                         CTL_UA_REG_PREEMPT;
7919                 }
7920                 if (!found) {
7921                         mtx_unlock(&lun->lun_lock);
7922                         free(ctsio->kern_data_ptr, M_CTL);
7923                         ctl_set_reservation_conflict(ctsio);
7924                         ctl_done((union ctl_io *)ctsio);
7925                         return (CTL_RETVAL_COMPLETE);
7926                 }
7927                 /* send msg to other side */
7928                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7929                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7930                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7931                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
7932                 persis_io.pr.pr_info.res_type = type;
7933                 memcpy(persis_io.pr.pr_info.sa_res_key,
7934                        param->serv_act_res_key,
7935                        sizeof(param->serv_act_res_key));
7936                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7937                      &persis_io, sizeof(persis_io), 0)) >
7938                      CTL_HA_STATUS_SUCCESS) {
7939                         printf("CTL:Persis Out error returned from "
7940                                "ctl_ha_msg_send %d\n", isc_retval);
7941                 }
7942         } else {
7943                 /* Reserved but not all registrants */
7944                 /* sa_res_key is res holder */
7945                 if (memcmp(param->serv_act_res_key,
7946                    lun->per_res[lun->pr_res_idx].res_key.key,
7947                    sizeof(struct scsi_per_res_key)) == 0) {
7948                         /* validate scope and type */
7949                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7950                              SPR_LU_SCOPE) {
7951                                 mtx_unlock(&lun->lun_lock);
7952                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7953                                                       /*sks_valid*/ 1,
7954                                                       /*command*/ 1,
7955                                                       /*field*/ 2,
7956                                                       /*bit_valid*/ 1,
7957                                                       /*bit*/ 4);
7958                                 ctl_done((union ctl_io *)ctsio);
7959                                 return (1);
7960                         }
7961
7962                         if (type>8 || type==2 || type==4 || type==0) {
7963                                 mtx_unlock(&lun->lun_lock);
7964                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7965                                                       /*sks_valid*/ 1,
7966                                                       /*command*/ 1,
7967                                                       /*field*/ 2,
7968                                                       /*bit_valid*/ 1,
7969                                                       /*bit*/ 0);
7970                                 ctl_done((union ctl_io *)ctsio);
7971                                 return (1);
7972                         }
7973
7974                         /*
7975                          * Do the following:
7976                          * if sa_res_key != res_key remove all
7977                          * registrants w/sa_res_key and generate UA
7978                          * for these registrants(Registrations
7979                          * Preempted) if it wasn't an exclusive
7980                          * reservation generate UA(Reservations
7981                          * Preempted) for all other registered nexuses
7982                          * if the type has changed. Establish the new
7983                          * reservation and holder. If res_key and
7984                          * sa_res_key are the same do the above
7985                          * except don't unregister the res holder.
7986                          */
7987
7988                         /*
7989                          * Temporarily unregister so it won't get
7990                          * removed or UA generated
7991                          */
7992                         lun->per_res[residx].registered = 0;
7993                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7994                                 if (lun->per_res[i].registered == 0)
7995                                         continue;
7996
7997                                 if (memcmp(param->serv_act_res_key,
7998                                     lun->per_res[i].res_key.key,
7999                                     sizeof(struct scsi_per_res_key)) == 0) {
8000                                         lun->per_res[i].registered = 0;
8001                                         memset(&lun->per_res[i].res_key,
8002                                                0,
8003                                                sizeof(struct scsi_per_res_key));
8004                                         lun->pr_key_count--;
8005
8006                                         if (!persis_offset
8007                                          && i < CTL_MAX_INITIATORS)
8008                                                 lun->pending_sense[i
8009                                                         ].ua_pending |=
8010                                                         CTL_UA_REG_PREEMPT;
8011                                         else if (persis_offset
8012                                               && i >= persis_offset)
8013                                                 lun->pending_sense[
8014                                                   i-persis_offset].ua_pending |=
8015                                                   CTL_UA_REG_PREEMPT;
8016                                 } else if (type != lun->res_type
8017                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8018                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8019                                                 if (!persis_offset
8020                                                  && i < CTL_MAX_INITIATORS)
8021                                                         lun->pending_sense[i
8022                                                         ].ua_pending |=
8023                                                         CTL_UA_RES_RELEASE;
8024                                                 else if (persis_offset
8025                                                       && i >= persis_offset)
8026                                                         lun->pending_sense[
8027                                                         i-persis_offset
8028                                                         ].ua_pending |=
8029                                                         CTL_UA_RES_RELEASE;
8030                                 }
8031                         }
8032                         lun->per_res[residx].registered = 1;
8033                         lun->res_type = type;
8034                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8035                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8036                                 lun->pr_res_idx = residx;
8037                         else
8038                                 lun->pr_res_idx =
8039                                         CTL_PR_ALL_REGISTRANTS;
8040
8041                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8042                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8043                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8044                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8045                         persis_io.pr.pr_info.res_type = type;
8046                         memcpy(persis_io.pr.pr_info.sa_res_key,
8047                                param->serv_act_res_key,
8048                                sizeof(param->serv_act_res_key));
8049                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8050                              &persis_io, sizeof(persis_io), 0)) >
8051                              CTL_HA_STATUS_SUCCESS) {
8052                                 printf("CTL:Persis Out error returned "
8053                                        "from ctl_ha_msg_send %d\n",
8054                                        isc_retval);
8055                         }
8056                 } else {
8057                         /*
8058                          * sa_res_key is not the res holder just
8059                          * remove registrants
8060                          */
8061                         int found=0;
8062
8063                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8064                                 if (memcmp(param->serv_act_res_key,
8065                                     lun->per_res[i].res_key.key,
8066                                     sizeof(struct scsi_per_res_key)) != 0)
8067                                         continue;
8068
8069                                 found = 1;
8070                                 lun->per_res[i].registered = 0;
8071                                 memset(&lun->per_res[i].res_key, 0,
8072                                        sizeof(struct scsi_per_res_key));
8073                                 lun->pr_key_count--;
8074
8075                                 if (!persis_offset
8076                                  && i < CTL_MAX_INITIATORS)
8077                                         lun->pending_sense[i].ua_pending |=
8078                                                 CTL_UA_REG_PREEMPT;
8079                                 else if (persis_offset
8080                                       && i >= persis_offset)
8081                                         lun->pending_sense[
8082                                                 i-persis_offset].ua_pending |=
8083                                                 CTL_UA_REG_PREEMPT;
8084                         }
8085
8086                         if (!found) {
8087                                 mtx_unlock(&lun->lun_lock);
8088                                 free(ctsio->kern_data_ptr, M_CTL);
8089                                 ctl_set_reservation_conflict(ctsio);
8090                                 ctl_done((union ctl_io *)ctsio);
8091                                 return (1);
8092                         }
8093                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8094                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8095                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8096                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8097                         persis_io.pr.pr_info.res_type = type;
8098                         memcpy(persis_io.pr.pr_info.sa_res_key,
8099                                param->serv_act_res_key,
8100                                sizeof(param->serv_act_res_key));
8101                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8102                              &persis_io, sizeof(persis_io), 0)) >
8103                              CTL_HA_STATUS_SUCCESS) {
8104                                 printf("CTL:Persis Out error returned "
8105                                        "from ctl_ha_msg_send %d\n",
8106                                 isc_retval);
8107                         }
8108                 }
8109         }
8110
8111         lun->PRGeneration++;
8112         mtx_unlock(&lun->lun_lock);
8113
8114         return (retval);
8115 }
8116
8117 static void
8118 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8119 {
8120         int i;
8121
8122         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8123          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8124          || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8125                    msg->pr.pr_info.sa_res_key,
8126                    sizeof(struct scsi_per_res_key)) != 0) {
8127                 uint64_t sa_res_key;
8128                 sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8129
8130                 if (sa_res_key == 0) {
8131                         /* temporarily unregister this nexus */
8132                         lun->per_res[msg->pr.pr_info.residx].registered = 0;
8133
8134                         /*
8135                          * Unregister everybody else and build UA for
8136                          * them
8137                          */
8138                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8139                                 if (lun->per_res[i].registered == 0)
8140                                         continue;
8141
8142                                 if (!persis_offset
8143                                  && i < CTL_MAX_INITIATORS)
8144                                         lun->pending_sense[i].ua_pending |=
8145                                                 CTL_UA_REG_PREEMPT;
8146                                 else if (persis_offset && i >= persis_offset)
8147                                         lun->pending_sense[i -
8148                                                 persis_offset].ua_pending |=
8149                                                 CTL_UA_REG_PREEMPT;
8150                                 lun->per_res[i].registered = 0;
8151                                 memset(&lun->per_res[i].res_key, 0,
8152                                        sizeof(struct scsi_per_res_key));
8153                         }
8154
8155                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8156                         lun->pr_key_count = 1;
8157                         lun->res_type = msg->pr.pr_info.res_type;
8158                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8159                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8160                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8161                 } else {
8162                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8163                                 if (memcmp(msg->pr.pr_info.sa_res_key,
8164                                    lun->per_res[i].res_key.key,
8165                                    sizeof(struct scsi_per_res_key)) != 0)
8166                                         continue;
8167
8168                                 lun->per_res[i].registered = 0;
8169                                 memset(&lun->per_res[i].res_key, 0,
8170                                        sizeof(struct scsi_per_res_key));
8171                                 lun->pr_key_count--;
8172
8173                                 if (!persis_offset
8174                                  && i < persis_offset)
8175                                         lun->pending_sense[i].ua_pending |=
8176                                                 CTL_UA_REG_PREEMPT;
8177                                 else if (persis_offset
8178                                       && i >= persis_offset)
8179                                         lun->pending_sense[i -
8180                                                 persis_offset].ua_pending |=
8181                                                 CTL_UA_REG_PREEMPT;
8182                         }
8183                 }
8184         } else {
8185                 /*
8186                  * Temporarily unregister so it won't get removed
8187                  * or UA generated
8188                  */
8189                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8190                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8191                         if (lun->per_res[i].registered == 0)
8192                                 continue;
8193
8194                         if (memcmp(msg->pr.pr_info.sa_res_key,
8195                            lun->per_res[i].res_key.key,
8196                            sizeof(struct scsi_per_res_key)) == 0) {
8197                                 lun->per_res[i].registered = 0;
8198                                 memset(&lun->per_res[i].res_key, 0,
8199                                        sizeof(struct scsi_per_res_key));
8200                                 lun->pr_key_count--;
8201                                 if (!persis_offset
8202                                  && i < CTL_MAX_INITIATORS)
8203                                         lun->pending_sense[i].ua_pending |=
8204                                                 CTL_UA_REG_PREEMPT;
8205                                 else if (persis_offset
8206                                       && i >= persis_offset)
8207                                         lun->pending_sense[i -
8208                                                 persis_offset].ua_pending |=
8209                                                 CTL_UA_REG_PREEMPT;
8210                         } else if (msg->pr.pr_info.res_type != lun->res_type
8211                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8212                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8213                                         if (!persis_offset
8214                                          && i < persis_offset)
8215                                                 lun->pending_sense[i
8216                                                         ].ua_pending |=
8217                                                         CTL_UA_RES_RELEASE;
8218                                         else if (persis_offset
8219                                               && i >= persis_offset)
8220                                         lun->pending_sense[i -
8221                                                 persis_offset].ua_pending |=
8222                                                 CTL_UA_RES_RELEASE;
8223                         }
8224                 }
8225                 lun->per_res[msg->pr.pr_info.residx].registered = 1;
8226                 lun->res_type = msg->pr.pr_info.res_type;
8227                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8228                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8229                         lun->pr_res_idx = msg->pr.pr_info.residx;
8230                 else
8231                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8232         }
8233         lun->PRGeneration++;
8234
8235 }
8236
8237
8238 int
8239 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8240 {
8241         int retval;
8242         int isc_retval;
8243         u_int32_t param_len;
8244         struct scsi_per_res_out *cdb;
8245         struct ctl_lun *lun;
8246         struct scsi_per_res_out_parms* param;
8247         struct ctl_softc *softc;
8248         uint32_t residx;
8249         uint64_t res_key, sa_res_key;
8250         uint8_t type;
8251         union ctl_ha_msg persis_io;
8252         int    i;
8253
8254         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8255
8256         retval = CTL_RETVAL_COMPLETE;
8257
8258         softc = control_softc;
8259
8260         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8261         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8262
8263         /*
8264          * We only support whole-LUN scope.  The scope & type are ignored for
8265          * register, register and ignore existing key and clear.
8266          * We sometimes ignore scope and type on preempts too!!
8267          * Verify reservation type here as well.
8268          */
8269         type = cdb->scope_type & SPR_TYPE_MASK;
8270         if ((cdb->action == SPRO_RESERVE)
8271          || (cdb->action == SPRO_RELEASE)) {
8272                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8273                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8274                                               /*sks_valid*/ 1,
8275                                               /*command*/ 1,
8276                                               /*field*/ 2,
8277                                               /*bit_valid*/ 1,
8278                                               /*bit*/ 4);
8279                         ctl_done((union ctl_io *)ctsio);
8280                         return (CTL_RETVAL_COMPLETE);
8281                 }
8282
8283                 if (type>8 || type==2 || type==4 || type==0) {
8284                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8285                                               /*sks_valid*/ 1,
8286                                               /*command*/ 1,
8287                                               /*field*/ 2,
8288                                               /*bit_valid*/ 1,
8289                                               /*bit*/ 0);
8290                         ctl_done((union ctl_io *)ctsio);
8291                         return (CTL_RETVAL_COMPLETE);
8292                 }
8293         }
8294
8295         param_len = scsi_4btoul(cdb->length);
8296
8297         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8298                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8299                 ctsio->kern_data_len = param_len;
8300                 ctsio->kern_total_len = param_len;
8301                 ctsio->kern_data_resid = 0;
8302                 ctsio->kern_rel_offset = 0;
8303                 ctsio->kern_sg_entries = 0;
8304                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8305                 ctsio->be_move_done = ctl_config_move_done;
8306                 ctl_datamove((union ctl_io *)ctsio);
8307
8308                 return (CTL_RETVAL_COMPLETE);
8309         }
8310
8311         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8312
8313         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8314         res_key = scsi_8btou64(param->res_key.key);
8315         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8316
8317         /*
8318          * Validate the reservation key here except for SPRO_REG_IGNO
8319          * This must be done for all other service actions
8320          */
8321         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8322                 mtx_lock(&lun->lun_lock);
8323                 if (lun->per_res[residx].registered) {
8324                     if (memcmp(param->res_key.key,
8325                                lun->per_res[residx].res_key.key,
8326                                ctl_min(sizeof(param->res_key),
8327                                sizeof(lun->per_res[residx].res_key))) != 0) {
8328                                 /*
8329                                  * The current key passed in doesn't match
8330                                  * the one the initiator previously
8331                                  * registered.
8332                                  */
8333                                 mtx_unlock(&lun->lun_lock);
8334                                 free(ctsio->kern_data_ptr, M_CTL);
8335                                 ctl_set_reservation_conflict(ctsio);
8336                                 ctl_done((union ctl_io *)ctsio);
8337                                 return (CTL_RETVAL_COMPLETE);
8338                         }
8339                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8340                         /*
8341                          * We are not registered
8342                          */
8343                         mtx_unlock(&lun->lun_lock);
8344                         free(ctsio->kern_data_ptr, M_CTL);
8345                         ctl_set_reservation_conflict(ctsio);
8346                         ctl_done((union ctl_io *)ctsio);
8347                         return (CTL_RETVAL_COMPLETE);
8348                 } else if (res_key != 0) {
8349                         /*
8350                          * We are not registered and trying to register but
8351                          * the register key isn't zero.
8352                          */
8353                         mtx_unlock(&lun->lun_lock);
8354                         free(ctsio->kern_data_ptr, M_CTL);
8355                         ctl_set_reservation_conflict(ctsio);
8356                         ctl_done((union ctl_io *)ctsio);
8357                         return (CTL_RETVAL_COMPLETE);
8358                 }
8359                 mtx_unlock(&lun->lun_lock);
8360         }
8361
8362         switch (cdb->action & SPRO_ACTION_MASK) {
8363         case SPRO_REGISTER:
8364         case SPRO_REG_IGNO: {
8365
8366 #if 0
8367                 printf("Registration received\n");
8368 #endif
8369
8370                 /*
8371                  * We don't support any of these options, as we report in
8372                  * the read capabilities request (see
8373                  * ctl_persistent_reserve_in(), above).
8374                  */
8375                 if ((param->flags & SPR_SPEC_I_PT)
8376                  || (param->flags & SPR_ALL_TG_PT)
8377                  || (param->flags & SPR_APTPL)) {
8378                         int bit_ptr;
8379
8380                         if (param->flags & SPR_APTPL)
8381                                 bit_ptr = 0;
8382                         else if (param->flags & SPR_ALL_TG_PT)
8383                                 bit_ptr = 2;
8384                         else /* SPR_SPEC_I_PT */
8385                                 bit_ptr = 3;
8386
8387                         free(ctsio->kern_data_ptr, M_CTL);
8388                         ctl_set_invalid_field(ctsio,
8389                                               /*sks_valid*/ 1,
8390                                               /*command*/ 0,
8391                                               /*field*/ 20,
8392                                               /*bit_valid*/ 1,
8393                                               /*bit*/ bit_ptr);
8394                         ctl_done((union ctl_io *)ctsio);
8395                         return (CTL_RETVAL_COMPLETE);
8396                 }
8397
8398                 mtx_lock(&lun->lun_lock);
8399
8400                 /*
8401                  * The initiator wants to clear the
8402                  * key/unregister.
8403                  */
8404                 if (sa_res_key == 0) {
8405                         if ((res_key == 0
8406                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8407                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8408                           && !lun->per_res[residx].registered)) {
8409                                 mtx_unlock(&lun->lun_lock);
8410                                 goto done;
8411                         }
8412
8413                         lun->per_res[residx].registered = 0;
8414                         memset(&lun->per_res[residx].res_key,
8415                                0, sizeof(lun->per_res[residx].res_key));
8416                         lun->pr_key_count--;
8417
8418                         if (residx == lun->pr_res_idx) {
8419                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8420                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8421
8422                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8423                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8424                                  && lun->pr_key_count) {
8425                                         /*
8426                                          * If the reservation is a registrants
8427                                          * only type we need to generate a UA
8428                                          * for other registered inits.  The
8429                                          * sense code should be RESERVATIONS
8430                                          * RELEASED
8431                                          */
8432
8433                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8434                                                 if (lun->per_res[
8435                                                     i+persis_offset].registered
8436                                                     == 0)
8437                                                         continue;
8438                                                 lun->pending_sense[i
8439                                                         ].ua_pending |=
8440                                                         CTL_UA_RES_RELEASE;
8441                                         }
8442                                 }
8443                                 lun->res_type = 0;
8444                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8445                                 if (lun->pr_key_count==0) {
8446                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8447                                         lun->res_type = 0;
8448                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8449                                 }
8450                         }
8451                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8452                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8453                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8454                         persis_io.pr.pr_info.residx = residx;
8455                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8456                              &persis_io, sizeof(persis_io), 0 )) >
8457                              CTL_HA_STATUS_SUCCESS) {
8458                                 printf("CTL:Persis Out error returned from "
8459                                        "ctl_ha_msg_send %d\n", isc_retval);
8460                         }
8461                 } else /* sa_res_key != 0 */ {
8462
8463                         /*
8464                          * If we aren't registered currently then increment
8465                          * the key count and set the registered flag.
8466                          */
8467                         if (!lun->per_res[residx].registered) {
8468                                 lun->pr_key_count++;
8469                                 lun->per_res[residx].registered = 1;
8470                         }
8471
8472                         memcpy(&lun->per_res[residx].res_key,
8473                                param->serv_act_res_key,
8474                                ctl_min(sizeof(param->serv_act_res_key),
8475                                sizeof(lun->per_res[residx].res_key)));
8476
8477                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8478                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8479                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8480                         persis_io.pr.pr_info.residx = residx;
8481                         memcpy(persis_io.pr.pr_info.sa_res_key,
8482                                param->serv_act_res_key,
8483                                sizeof(param->serv_act_res_key));
8484                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8485                              &persis_io, sizeof(persis_io), 0)) >
8486                              CTL_HA_STATUS_SUCCESS) {
8487                                 printf("CTL:Persis Out error returned from "
8488                                        "ctl_ha_msg_send %d\n", isc_retval);
8489                         }
8490                 }
8491                 lun->PRGeneration++;
8492                 mtx_unlock(&lun->lun_lock);
8493
8494                 break;
8495         }
8496         case SPRO_RESERVE:
8497 #if 0
8498                 printf("Reserve executed type %d\n", type);
8499 #endif
8500                 mtx_lock(&lun->lun_lock);
8501                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8502                         /*
8503                          * if this isn't the reservation holder and it's
8504                          * not a "all registrants" type or if the type is
8505                          * different then we have a conflict
8506                          */
8507                         if ((lun->pr_res_idx != residx
8508                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8509                          || lun->res_type != type) {
8510                                 mtx_unlock(&lun->lun_lock);
8511                                 free(ctsio->kern_data_ptr, M_CTL);
8512                                 ctl_set_reservation_conflict(ctsio);
8513                                 ctl_done((union ctl_io *)ctsio);
8514                                 return (CTL_RETVAL_COMPLETE);
8515                         }
8516                         mtx_unlock(&lun->lun_lock);
8517                 } else /* create a reservation */ {
8518                         /*
8519                          * If it's not an "all registrants" type record
8520                          * reservation holder
8521                          */
8522                         if (type != SPR_TYPE_WR_EX_AR
8523                          && type != SPR_TYPE_EX_AC_AR)
8524                                 lun->pr_res_idx = residx; /* Res holder */
8525                         else
8526                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8527
8528                         lun->flags |= CTL_LUN_PR_RESERVED;
8529                         lun->res_type = type;
8530
8531                         mtx_unlock(&lun->lun_lock);
8532
8533                         /* send msg to other side */
8534                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8535                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8536                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8537                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8538                         persis_io.pr.pr_info.res_type = type;
8539                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8540                              &persis_io, sizeof(persis_io), 0)) >
8541                              CTL_HA_STATUS_SUCCESS) {
8542                                 printf("CTL:Persis Out error returned from "
8543                                        "ctl_ha_msg_send %d\n", isc_retval);
8544                         }
8545                 }
8546                 break;
8547
8548         case SPRO_RELEASE:
8549                 mtx_lock(&lun->lun_lock);
8550                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8551                         /* No reservation exists return good status */
8552                         mtx_unlock(&lun->lun_lock);
8553                         goto done;
8554                 }
8555                 /*
8556                  * Is this nexus a reservation holder?
8557                  */
8558                 if (lun->pr_res_idx != residx
8559                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8560                         /*
8561                          * not a res holder return good status but
8562                          * do nothing
8563                          */
8564                         mtx_unlock(&lun->lun_lock);
8565                         goto done;
8566                 }
8567
8568                 if (lun->res_type != type) {
8569                         mtx_unlock(&lun->lun_lock);
8570                         free(ctsio->kern_data_ptr, M_CTL);
8571                         ctl_set_illegal_pr_release(ctsio);
8572                         ctl_done((union ctl_io *)ctsio);
8573                         return (CTL_RETVAL_COMPLETE);
8574                 }
8575
8576                 /* okay to release */
8577                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8578                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8579                 lun->res_type = 0;
8580
8581                 /*
8582                  * if this isn't an exclusive access
8583                  * res generate UA for all other
8584                  * registrants.
8585                  */
8586                 if (type != SPR_TYPE_EX_AC
8587                  && type != SPR_TYPE_WR_EX) {
8588                         /*
8589                          * temporarily unregister so we don't generate UA
8590                          */
8591                         lun->per_res[residx].registered = 0;
8592
8593                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8594                                 if (lun->per_res[i+persis_offset].registered
8595                                     == 0)
8596                                         continue;
8597                                 lun->pending_sense[i].ua_pending |=
8598                                         CTL_UA_RES_RELEASE;
8599                         }
8600
8601                         lun->per_res[residx].registered = 1;
8602                 }
8603                 mtx_unlock(&lun->lun_lock);
8604                 /* Send msg to other side */
8605                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8606                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8607                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8608                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8609                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8610                         printf("CTL:Persis Out error returned from "
8611                                "ctl_ha_msg_send %d\n", isc_retval);
8612                 }
8613                 break;
8614
8615         case SPRO_CLEAR:
8616                 /* send msg to other side */
8617
8618                 mtx_lock(&lun->lun_lock);
8619                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8620                 lun->res_type = 0;
8621                 lun->pr_key_count = 0;
8622                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8623
8624
8625                 memset(&lun->per_res[residx].res_key,
8626                        0, sizeof(lun->per_res[residx].res_key));
8627                 lun->per_res[residx].registered = 0;
8628
8629                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8630                         if (lun->per_res[i].registered) {
8631                                 if (!persis_offset && i < CTL_MAX_INITIATORS)
8632                                         lun->pending_sense[i].ua_pending |=
8633                                                 CTL_UA_RES_PREEMPT;
8634                                 else if (persis_offset && i >= persis_offset)
8635                                         lun->pending_sense[i-persis_offset
8636                                             ].ua_pending |= CTL_UA_RES_PREEMPT;
8637
8638                                 memset(&lun->per_res[i].res_key,
8639                                        0, sizeof(struct scsi_per_res_key));
8640                                 lun->per_res[i].registered = 0;
8641                         }
8642                 lun->PRGeneration++;
8643                 mtx_unlock(&lun->lun_lock);
8644                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8645                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8646                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8647                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8648                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8649                         printf("CTL:Persis Out error returned from "
8650                                "ctl_ha_msg_send %d\n", isc_retval);
8651                 }
8652                 break;
8653
8654         case SPRO_PREEMPT: {
8655                 int nretval;
8656
8657                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8658                                           residx, ctsio, cdb, param);
8659                 if (nretval != 0)
8660                         return (CTL_RETVAL_COMPLETE);
8661                 break;
8662         }
8663         default:
8664                 panic("Invalid PR type %x", cdb->action);
8665         }
8666
8667 done:
8668         free(ctsio->kern_data_ptr, M_CTL);
8669         ctl_set_success(ctsio);
8670         ctl_done((union ctl_io *)ctsio);
8671
8672         return (retval);
8673 }
8674
8675 /*
8676  * This routine is for handling a message from the other SC pertaining to
8677  * persistent reserve out. All the error checking will have been done
8678  * so only perorming the action need be done here to keep the two
8679  * in sync.
8680  */
8681 static void
8682 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8683 {
8684         struct ctl_lun *lun;
8685         struct ctl_softc *softc;
8686         int i;
8687         uint32_t targ_lun;
8688
8689         softc = control_softc;
8690
8691         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8692         lun = softc->ctl_luns[targ_lun];
8693         mtx_lock(&lun->lun_lock);
8694         switch(msg->pr.pr_info.action) {
8695         case CTL_PR_REG_KEY:
8696                 if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8697                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8698                         lun->pr_key_count++;
8699                 }
8700                 lun->PRGeneration++;
8701                 memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8702                        msg->pr.pr_info.sa_res_key,
8703                        sizeof(struct scsi_per_res_key));
8704                 break;
8705
8706         case CTL_PR_UNREG_KEY:
8707                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8708                 memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8709                        0, sizeof(struct scsi_per_res_key));
8710                 lun->pr_key_count--;
8711
8712                 /* XXX Need to see if the reservation has been released */
8713                 /* if so do we need to generate UA? */
8714                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8715                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8716                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8717
8718                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8719                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8720                          && lun->pr_key_count) {
8721                                 /*
8722                                  * If the reservation is a registrants
8723                                  * only type we need to generate a UA
8724                                  * for other registered inits.  The
8725                                  * sense code should be RESERVATIONS
8726                                  * RELEASED
8727                                  */
8728
8729                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8730                                         if (lun->per_res[i+
8731                                             persis_offset].registered == 0)
8732                                                 continue;
8733
8734                                         lun->pending_sense[i
8735                                                 ].ua_pending |=
8736                                                 CTL_UA_RES_RELEASE;
8737                                 }
8738                         }
8739                         lun->res_type = 0;
8740                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8741                         if (lun->pr_key_count==0) {
8742                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8743                                 lun->res_type = 0;
8744                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8745                         }
8746                 }
8747                 lun->PRGeneration++;
8748                 break;
8749
8750         case CTL_PR_RESERVE:
8751                 lun->flags |= CTL_LUN_PR_RESERVED;
8752                 lun->res_type = msg->pr.pr_info.res_type;
8753                 lun->pr_res_idx = msg->pr.pr_info.residx;
8754
8755                 break;
8756
8757         case CTL_PR_RELEASE:
8758                 /*
8759                  * if this isn't an exclusive access res generate UA for all
8760                  * other registrants.
8761                  */
8762                 if (lun->res_type != SPR_TYPE_EX_AC
8763                  && lun->res_type != SPR_TYPE_WR_EX) {
8764                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8765                                 if (lun->per_res[i+persis_offset].registered)
8766                                         lun->pending_sense[i].ua_pending |=
8767                                                 CTL_UA_RES_RELEASE;
8768                 }
8769
8770                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8771                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8772                 lun->res_type = 0;
8773                 break;
8774
8775         case CTL_PR_PREEMPT:
8776                 ctl_pro_preempt_other(lun, msg);
8777                 break;
8778         case CTL_PR_CLEAR:
8779                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8780                 lun->res_type = 0;
8781                 lun->pr_key_count = 0;
8782                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8783
8784                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8785                         if (lun->per_res[i].registered == 0)
8786                                 continue;
8787                         if (!persis_offset
8788                          && i < CTL_MAX_INITIATORS)
8789                                 lun->pending_sense[i].ua_pending |=
8790                                         CTL_UA_RES_PREEMPT;
8791                         else if (persis_offset
8792                               && i >= persis_offset)
8793                                 lun->pending_sense[i-persis_offset].ua_pending|=
8794                                         CTL_UA_RES_PREEMPT;
8795                         memset(&lun->per_res[i].res_key, 0,
8796                                sizeof(struct scsi_per_res_key));
8797                         lun->per_res[i].registered = 0;
8798                 }
8799                 lun->PRGeneration++;
8800                 break;
8801         }
8802
8803         mtx_unlock(&lun->lun_lock);
8804 }
8805
8806 int
8807 ctl_read_write(struct ctl_scsiio *ctsio)
8808 {
8809         struct ctl_lun *lun;
8810         struct ctl_lba_len_flags *lbalen;
8811         uint64_t lba;
8812         uint32_t num_blocks;
8813         int fua, dpo;
8814         int retval;
8815         int isread;
8816
8817         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8818
8819         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8820
8821         fua = 0;
8822         dpo = 0;
8823
8824         retval = CTL_RETVAL_COMPLETE;
8825
8826         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8827               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8828         if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8829                 uint32_t residx;
8830
8831                 /*
8832                  * XXX KDM need a lock here.
8833                  */
8834                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8835                 if ((lun->res_type == SPR_TYPE_EX_AC
8836                   && residx != lun->pr_res_idx)
8837                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
8838                    || lun->res_type == SPR_TYPE_EX_AC_AR)
8839                   && !lun->per_res[residx].registered)) {
8840                         ctl_set_reservation_conflict(ctsio);
8841                         ctl_done((union ctl_io *)ctsio);
8842                         return (CTL_RETVAL_COMPLETE);
8843                 }
8844         }
8845
8846         switch (ctsio->cdb[0]) {
8847         case READ_6:
8848         case WRITE_6: {
8849                 struct scsi_rw_6 *cdb;
8850
8851                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8852
8853                 lba = scsi_3btoul(cdb->addr);
8854                 /* only 5 bits are valid in the most significant address byte */
8855                 lba &= 0x1fffff;
8856                 num_blocks = cdb->length;
8857                 /*
8858                  * This is correct according to SBC-2.
8859                  */
8860                 if (num_blocks == 0)
8861                         num_blocks = 256;
8862                 break;
8863         }
8864         case READ_10:
8865         case WRITE_10: {
8866                 struct scsi_rw_10 *cdb;
8867
8868                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8869
8870                 if (cdb->byte2 & SRW10_FUA)
8871                         fua = 1;
8872                 if (cdb->byte2 & SRW10_DPO)
8873                         dpo = 1;
8874
8875                 lba = scsi_4btoul(cdb->addr);
8876                 num_blocks = scsi_2btoul(cdb->length);
8877                 break;
8878         }
8879         case WRITE_VERIFY_10: {
8880                 struct scsi_write_verify_10 *cdb;
8881
8882                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8883
8884                 /*
8885                  * XXX KDM we should do actual write verify support at some
8886                  * point.  This is obviously fake, we're just translating
8887                  * things to a write.  So we don't even bother checking the
8888                  * BYTCHK field, since we don't do any verification.  If
8889                  * the user asks for it, we'll just pretend we did it.
8890                  */
8891                 if (cdb->byte2 & SWV_DPO)
8892                         dpo = 1;
8893
8894                 lba = scsi_4btoul(cdb->addr);
8895                 num_blocks = scsi_2btoul(cdb->length);
8896                 break;
8897         }
8898         case READ_12:
8899         case WRITE_12: {
8900                 struct scsi_rw_12 *cdb;
8901
8902                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8903
8904                 if (cdb->byte2 & SRW12_FUA)
8905                         fua = 1;
8906                 if (cdb->byte2 & SRW12_DPO)
8907                         dpo = 1;
8908                 lba = scsi_4btoul(cdb->addr);
8909                 num_blocks = scsi_4btoul(cdb->length);
8910                 break;
8911         }
8912         case WRITE_VERIFY_12: {
8913                 struct scsi_write_verify_12 *cdb;
8914
8915                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8916
8917                 if (cdb->byte2 & SWV_DPO)
8918                         dpo = 1;
8919                 
8920                 lba = scsi_4btoul(cdb->addr);
8921                 num_blocks = scsi_4btoul(cdb->length);
8922
8923                 break;
8924         }
8925         case READ_16:
8926         case WRITE_16: {
8927                 struct scsi_rw_16 *cdb;
8928
8929                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8930
8931                 if (cdb->byte2 & SRW12_FUA)
8932                         fua = 1;
8933                 if (cdb->byte2 & SRW12_DPO)
8934                         dpo = 1;
8935
8936                 lba = scsi_8btou64(cdb->addr);
8937                 num_blocks = scsi_4btoul(cdb->length);
8938                 break;
8939         }
8940         case WRITE_VERIFY_16: {
8941                 struct scsi_write_verify_16 *cdb;
8942
8943                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8944
8945                 if (cdb->byte2 & SWV_DPO)
8946                         dpo = 1;
8947
8948                 lba = scsi_8btou64(cdb->addr);
8949                 num_blocks = scsi_4btoul(cdb->length);
8950                 break;
8951         }
8952         default:
8953                 /*
8954                  * We got a command we don't support.  This shouldn't
8955                  * happen, commands should be filtered out above us.
8956                  */
8957                 ctl_set_invalid_opcode(ctsio);
8958                 ctl_done((union ctl_io *)ctsio);
8959
8960                 return (CTL_RETVAL_COMPLETE);
8961                 break; /* NOTREACHED */
8962         }
8963
8964         /*
8965          * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8966          * interesting for us, but if RAIDCore is in write-back mode,
8967          * getting it to do write-through for a particular transaction may
8968          * not be possible.
8969          */
8970
8971         /*
8972          * The first check is to make sure we're in bounds, the second
8973          * check is to catch wrap-around problems.  If the lba + num blocks
8974          * is less than the lba, then we've wrapped around and the block
8975          * range is invalid anyway.
8976          */
8977         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8978          || ((lba + num_blocks) < lba)) {
8979                 ctl_set_lba_out_of_range(ctsio);
8980                 ctl_done((union ctl_io *)ctsio);
8981                 return (CTL_RETVAL_COMPLETE);
8982         }
8983
8984         /*
8985          * According to SBC-3, a transfer length of 0 is not an error.
8986          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8987          * translates to 256 blocks for those commands.
8988          */
8989         if (num_blocks == 0) {
8990                 ctl_set_success(ctsio);
8991                 ctl_done((union ctl_io *)ctsio);
8992                 return (CTL_RETVAL_COMPLETE);
8993         }
8994
8995         lbalen = (struct ctl_lba_len_flags *)
8996             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8997         lbalen->lba = lba;
8998         lbalen->len = num_blocks;
8999         lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
9000
9001         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9002         ctsio->kern_rel_offset = 0;
9003
9004         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9005
9006         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9007
9008         return (retval);
9009 }
9010
9011 static int
9012 ctl_cnw_cont(union ctl_io *io)
9013 {
9014         struct ctl_scsiio *ctsio;
9015         struct ctl_lun *lun;
9016         struct ctl_lba_len_flags *lbalen;
9017         int retval;
9018
9019         ctsio = &io->scsiio;
9020         ctsio->io_hdr.status = CTL_STATUS_NONE;
9021         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9022         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9023         lbalen = (struct ctl_lba_len_flags *)
9024             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9025         lbalen->flags = CTL_LLF_WRITE;
9026
9027         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9028         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9029         return (retval);
9030 }
9031
9032 int
9033 ctl_cnw(struct ctl_scsiio *ctsio)
9034 {
9035         struct ctl_lun *lun;
9036         struct ctl_lba_len_flags *lbalen;
9037         uint64_t lba;
9038         uint32_t num_blocks;
9039         int fua, dpo;
9040         int retval;
9041
9042         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9043
9044         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9045
9046         fua = 0;
9047         dpo = 0;
9048
9049         retval = CTL_RETVAL_COMPLETE;
9050
9051         switch (ctsio->cdb[0]) {
9052         case COMPARE_AND_WRITE: {
9053                 struct scsi_compare_and_write *cdb;
9054
9055                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9056
9057                 if (cdb->byte2 & SRW10_FUA)
9058                         fua = 1;
9059                 if (cdb->byte2 & SRW10_DPO)
9060                         dpo = 1;
9061                 lba = scsi_8btou64(cdb->addr);
9062                 num_blocks = cdb->length;
9063                 break;
9064         }
9065         default:
9066                 /*
9067                  * We got a command we don't support.  This shouldn't
9068                  * happen, commands should be filtered out above us.
9069                  */
9070                 ctl_set_invalid_opcode(ctsio);
9071                 ctl_done((union ctl_io *)ctsio);
9072
9073                 return (CTL_RETVAL_COMPLETE);
9074                 break; /* NOTREACHED */
9075         }
9076
9077         /*
9078          * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9079          * interesting for us, but if RAIDCore is in write-back mode,
9080          * getting it to do write-through for a particular transaction may
9081          * not be possible.
9082          */
9083
9084         /*
9085          * The first check is to make sure we're in bounds, the second
9086          * check is to catch wrap-around problems.  If the lba + num blocks
9087          * is less than the lba, then we've wrapped around and the block
9088          * range is invalid anyway.
9089          */
9090         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9091          || ((lba + num_blocks) < lba)) {
9092                 ctl_set_lba_out_of_range(ctsio);
9093                 ctl_done((union ctl_io *)ctsio);
9094                 return (CTL_RETVAL_COMPLETE);
9095         }
9096
9097         /*
9098          * According to SBC-3, a transfer length of 0 is not an error.
9099          */
9100         if (num_blocks == 0) {
9101                 ctl_set_success(ctsio);
9102                 ctl_done((union ctl_io *)ctsio);
9103                 return (CTL_RETVAL_COMPLETE);
9104         }
9105
9106         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9107         ctsio->kern_rel_offset = 0;
9108
9109         /*
9110          * Set the IO_CONT flag, so that if this I/O gets passed to
9111          * ctl_data_submit_done(), it'll get passed back to
9112          * ctl_ctl_cnw_cont() for further processing.
9113          */
9114         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9115         ctsio->io_cont = ctl_cnw_cont;
9116
9117         lbalen = (struct ctl_lba_len_flags *)
9118             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9119         lbalen->lba = lba;
9120         lbalen->len = num_blocks;
9121         lbalen->flags = CTL_LLF_COMPARE;
9122
9123         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9124         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9125         return (retval);
9126 }
9127
9128 int
9129 ctl_verify(struct ctl_scsiio *ctsio)
9130 {
9131         struct ctl_lun *lun;
9132         struct ctl_lba_len_flags *lbalen;
9133         uint64_t lba;
9134         uint32_t num_blocks;
9135         int bytchk, dpo;
9136         int retval;
9137
9138         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9139
9140         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9141
9142         bytchk = 0;
9143         dpo = 0;
9144         retval = CTL_RETVAL_COMPLETE;
9145
9146         switch (ctsio->cdb[0]) {
9147         case VERIFY_10: {
9148                 struct scsi_verify_10 *cdb;
9149
9150                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9151                 if (cdb->byte2 & SVFY_BYTCHK)
9152                         bytchk = 1;
9153                 if (cdb->byte2 & SVFY_DPO)
9154                         dpo = 1;
9155                 lba = scsi_4btoul(cdb->addr);
9156                 num_blocks = scsi_2btoul(cdb->length);
9157                 break;
9158         }
9159         case VERIFY_12: {
9160                 struct scsi_verify_12 *cdb;
9161
9162                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9163                 if (cdb->byte2 & SVFY_BYTCHK)
9164                         bytchk = 1;
9165                 if (cdb->byte2 & SVFY_DPO)
9166                         dpo = 1;
9167                 lba = scsi_4btoul(cdb->addr);
9168                 num_blocks = scsi_4btoul(cdb->length);
9169                 break;
9170         }
9171         case VERIFY_16: {
9172                 struct scsi_rw_16 *cdb;
9173
9174                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9175                 if (cdb->byte2 & SVFY_BYTCHK)
9176                         bytchk = 1;
9177                 if (cdb->byte2 & SVFY_DPO)
9178                         dpo = 1;
9179                 lba = scsi_8btou64(cdb->addr);
9180                 num_blocks = scsi_4btoul(cdb->length);
9181                 break;
9182         }
9183         default:
9184                 /*
9185                  * We got a command we don't support.  This shouldn't
9186                  * happen, commands should be filtered out above us.
9187                  */
9188                 ctl_set_invalid_opcode(ctsio);
9189                 ctl_done((union ctl_io *)ctsio);
9190                 return (CTL_RETVAL_COMPLETE);
9191         }
9192
9193         /*
9194          * The first check is to make sure we're in bounds, the second
9195          * check is to catch wrap-around problems.  If the lba + num blocks
9196          * is less than the lba, then we've wrapped around and the block
9197          * range is invalid anyway.
9198          */
9199         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9200          || ((lba + num_blocks) < lba)) {
9201                 ctl_set_lba_out_of_range(ctsio);
9202                 ctl_done((union ctl_io *)ctsio);
9203                 return (CTL_RETVAL_COMPLETE);
9204         }
9205
9206         /*
9207          * According to SBC-3, a transfer length of 0 is not an error.
9208          */
9209         if (num_blocks == 0) {
9210                 ctl_set_success(ctsio);
9211                 ctl_done((union ctl_io *)ctsio);
9212                 return (CTL_RETVAL_COMPLETE);
9213         }
9214
9215         lbalen = (struct ctl_lba_len_flags *)
9216             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9217         lbalen->lba = lba;
9218         lbalen->len = num_blocks;
9219         if (bytchk) {
9220                 lbalen->flags = CTL_LLF_COMPARE;
9221                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9222         } else {
9223                 lbalen->flags = CTL_LLF_VERIFY;
9224                 ctsio->kern_total_len = 0;
9225         }
9226         ctsio->kern_rel_offset = 0;
9227
9228         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9229         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9230         return (retval);
9231 }
9232
9233 int
9234 ctl_report_luns(struct ctl_scsiio *ctsio)
9235 {
9236         struct scsi_report_luns *cdb;
9237         struct scsi_report_luns_data *lun_data;
9238         struct ctl_lun *lun, *request_lun;
9239         int num_luns, retval;
9240         uint32_t alloc_len, lun_datalen;
9241         int num_filled, well_known;
9242         uint32_t initidx, targ_lun_id, lun_id;
9243
9244         retval = CTL_RETVAL_COMPLETE;
9245         well_known = 0;
9246
9247         cdb = (struct scsi_report_luns *)ctsio->cdb;
9248
9249         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9250
9251         mtx_lock(&control_softc->ctl_lock);
9252         num_luns = control_softc->num_luns;
9253         mtx_unlock(&control_softc->ctl_lock);
9254
9255         switch (cdb->select_report) {
9256         case RPL_REPORT_DEFAULT:
9257         case RPL_REPORT_ALL:
9258                 break;
9259         case RPL_REPORT_WELLKNOWN:
9260                 well_known = 1;
9261                 num_luns = 0;
9262                 break;
9263         default:
9264                 ctl_set_invalid_field(ctsio,
9265                                       /*sks_valid*/ 1,
9266                                       /*command*/ 1,
9267                                       /*field*/ 2,
9268                                       /*bit_valid*/ 0,
9269                                       /*bit*/ 0);
9270                 ctl_done((union ctl_io *)ctsio);
9271                 return (retval);
9272                 break; /* NOTREACHED */
9273         }
9274
9275         alloc_len = scsi_4btoul(cdb->length);
9276         /*
9277          * The initiator has to allocate at least 16 bytes for this request,
9278          * so he can at least get the header and the first LUN.  Otherwise
9279          * we reject the request (per SPC-3 rev 14, section 6.21).
9280          */
9281         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9282             sizeof(struct scsi_report_luns_lundata))) {
9283                 ctl_set_invalid_field(ctsio,
9284                                       /*sks_valid*/ 1,
9285                                       /*command*/ 1,
9286                                       /*field*/ 6,
9287                                       /*bit_valid*/ 0,
9288                                       /*bit*/ 0);
9289                 ctl_done((union ctl_io *)ctsio);
9290                 return (retval);
9291         }
9292
9293         request_lun = (struct ctl_lun *)
9294                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9295
9296         lun_datalen = sizeof(*lun_data) +
9297                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9298
9299         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9300         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9301         ctsio->kern_sg_entries = 0;
9302
9303         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9304
9305         mtx_lock(&control_softc->ctl_lock);
9306         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9307                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9308                 if (lun_id >= CTL_MAX_LUNS)
9309                         continue;
9310                 lun = control_softc->ctl_luns[lun_id];
9311                 if (lun == NULL)
9312                         continue;
9313
9314                 if (targ_lun_id <= 0xff) {
9315                         /*
9316                          * Peripheral addressing method, bus number 0.
9317                          */
9318                         lun_data->luns[num_filled].lundata[0] =
9319                                 RPL_LUNDATA_ATYP_PERIPH;
9320                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9321                         num_filled++;
9322                 } else if (targ_lun_id <= 0x3fff) {
9323                         /*
9324                          * Flat addressing method.
9325                          */
9326                         lun_data->luns[num_filled].lundata[0] =
9327                                 RPL_LUNDATA_ATYP_FLAT |
9328                                 (targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9329 #ifdef OLDCTLHEADERS
9330                                 (SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9331                                 (targ_lun_id & SRLD_BUS_LUN_MASK);
9332 #endif
9333                         lun_data->luns[num_filled].lundata[1] =
9334 #ifdef OLDCTLHEADERS
9335                                 targ_lun_id >> SRLD_BUS_LUN_BITS;
9336 #endif
9337                                 targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9338                         num_filled++;
9339                 } else {
9340                         printf("ctl_report_luns: bogus LUN number %jd, "
9341                                "skipping\n", (intmax_t)targ_lun_id);
9342                 }
9343                 /*
9344                  * According to SPC-3, rev 14 section 6.21:
9345                  *
9346                  * "The execution of a REPORT LUNS command to any valid and
9347                  * installed logical unit shall clear the REPORTED LUNS DATA
9348                  * HAS CHANGED unit attention condition for all logical
9349                  * units of that target with respect to the requesting
9350                  * initiator. A valid and installed logical unit is one
9351                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9352                  * INQUIRY data (see 6.4.2)."
9353                  *
9354                  * If request_lun is NULL, the LUN this report luns command
9355                  * was issued to is either disabled or doesn't exist. In that
9356                  * case, we shouldn't clear any pending lun change unit
9357                  * attention.
9358                  */
9359                 if (request_lun != NULL) {
9360                         mtx_lock(&lun->lun_lock);
9361                         lun->pending_sense[initidx].ua_pending &=
9362                                 ~CTL_UA_LUN_CHANGE;
9363                         mtx_unlock(&lun->lun_lock);
9364                 }
9365         }
9366         mtx_unlock(&control_softc->ctl_lock);
9367
9368         /*
9369          * It's quite possible that we've returned fewer LUNs than we allocated
9370          * space for.  Trim it.
9371          */
9372         lun_datalen = sizeof(*lun_data) +
9373                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9374
9375         if (lun_datalen < alloc_len) {
9376                 ctsio->residual = alloc_len - lun_datalen;
9377                 ctsio->kern_data_len = lun_datalen;
9378                 ctsio->kern_total_len = lun_datalen;
9379         } else {
9380                 ctsio->residual = 0;
9381                 ctsio->kern_data_len = alloc_len;
9382                 ctsio->kern_total_len = alloc_len;
9383         }
9384         ctsio->kern_data_resid = 0;
9385         ctsio->kern_rel_offset = 0;
9386         ctsio->kern_sg_entries = 0;
9387
9388         /*
9389          * We set this to the actual data length, regardless of how much
9390          * space we actually have to return results.  If the user looks at
9391          * this value, he'll know whether or not he allocated enough space
9392          * and reissue the command if necessary.  We don't support well
9393          * known logical units, so if the user asks for that, return none.
9394          */
9395         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9396
9397         /*
9398          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9399          * this request.
9400          */
9401         ctsio->scsi_status = SCSI_STATUS_OK;
9402
9403         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9404         ctsio->be_move_done = ctl_config_move_done;
9405         ctl_datamove((union ctl_io *)ctsio);
9406
9407         return (retval);
9408 }
9409
9410 int
9411 ctl_request_sense(struct ctl_scsiio *ctsio)
9412 {
9413         struct scsi_request_sense *cdb;
9414         struct scsi_sense_data *sense_ptr;
9415         struct ctl_lun *lun;
9416         uint32_t initidx;
9417         int have_error;
9418         scsi_sense_data_type sense_format;
9419
9420         cdb = (struct scsi_request_sense *)ctsio->cdb;
9421
9422         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9423
9424         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9425
9426         /*
9427          * Determine which sense format the user wants.
9428          */
9429         if (cdb->byte2 & SRS_DESC)
9430                 sense_format = SSD_TYPE_DESC;
9431         else
9432                 sense_format = SSD_TYPE_FIXED;
9433
9434         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9435         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9436         ctsio->kern_sg_entries = 0;
9437
9438         /*
9439          * struct scsi_sense_data, which is currently set to 256 bytes, is
9440          * larger than the largest allowed value for the length field in the
9441          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9442          */
9443         ctsio->residual = 0;
9444         ctsio->kern_data_len = cdb->length;
9445         ctsio->kern_total_len = cdb->length;
9446
9447         ctsio->kern_data_resid = 0;
9448         ctsio->kern_rel_offset = 0;
9449         ctsio->kern_sg_entries = 0;
9450
9451         /*
9452          * If we don't have a LUN, we don't have any pending sense.
9453          */
9454         if (lun == NULL)
9455                 goto no_sense;
9456
9457         have_error = 0;
9458         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9459         /*
9460          * Check for pending sense, and then for pending unit attentions.
9461          * Pending sense gets returned first, then pending unit attentions.
9462          */
9463         mtx_lock(&lun->lun_lock);
9464         if (ctl_is_set(lun->have_ca, initidx)) {
9465                 scsi_sense_data_type stored_format;
9466
9467                 /*
9468                  * Check to see which sense format was used for the stored
9469                  * sense data.
9470                  */
9471                 stored_format = scsi_sense_type(
9472                     &lun->pending_sense[initidx].sense);
9473
9474                 /*
9475                  * If the user requested a different sense format than the
9476                  * one we stored, then we need to convert it to the other
9477                  * format.  If we're going from descriptor to fixed format
9478                  * sense data, we may lose things in translation, depending
9479                  * on what options were used.
9480                  *
9481                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9482                  * for some reason we'll just copy it out as-is.
9483                  */
9484                 if ((stored_format == SSD_TYPE_FIXED)
9485                  && (sense_format == SSD_TYPE_DESC))
9486                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9487                             &lun->pending_sense[initidx].sense,
9488                             (struct scsi_sense_data_desc *)sense_ptr);
9489                 else if ((stored_format == SSD_TYPE_DESC)
9490                       && (sense_format == SSD_TYPE_FIXED))
9491                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9492                             &lun->pending_sense[initidx].sense,
9493                             (struct scsi_sense_data_fixed *)sense_ptr);
9494                 else
9495                         memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
9496                                ctl_min(sizeof(*sense_ptr),
9497                                sizeof(lun->pending_sense[initidx].sense)));
9498
9499                 ctl_clear_mask(lun->have_ca, initidx);
9500                 have_error = 1;
9501         } else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
9502                 ctl_ua_type ua_type;
9503
9504                 ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
9505                                        sense_ptr, sense_format);
9506                 if (ua_type != CTL_UA_NONE) {
9507                         have_error = 1;
9508                         /* We're reporting this UA, so clear it */
9509                         lun->pending_sense[initidx].ua_pending &= ~ua_type;
9510                 }
9511         }
9512         mtx_unlock(&lun->lun_lock);
9513
9514         /*
9515          * We already have a pending error, return it.
9516          */
9517         if (have_error != 0) {
9518                 /*
9519                  * We report the SCSI status as OK, since the status of the
9520                  * request sense command itself is OK.
9521                  */
9522                 ctsio->scsi_status = SCSI_STATUS_OK;
9523
9524                 /*
9525                  * We report 0 for the sense length, because we aren't doing
9526                  * autosense in this case.  We're reporting sense as
9527                  * parameter data.
9528                  */
9529                 ctsio->sense_len = 0;
9530                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9531                 ctsio->be_move_done = ctl_config_move_done;
9532                 ctl_datamove((union ctl_io *)ctsio);
9533
9534                 return (CTL_RETVAL_COMPLETE);
9535         }
9536
9537 no_sense:
9538
9539         /*
9540          * No sense information to report, so we report that everything is
9541          * okay.
9542          */
9543         ctl_set_sense_data(sense_ptr,
9544                            lun,
9545                            sense_format,
9546                            /*current_error*/ 1,
9547                            /*sense_key*/ SSD_KEY_NO_SENSE,
9548                            /*asc*/ 0x00,
9549                            /*ascq*/ 0x00,
9550                            SSD_ELEM_NONE);
9551
9552         ctsio->scsi_status = SCSI_STATUS_OK;
9553
9554         /*
9555          * We report 0 for the sense length, because we aren't doing
9556          * autosense in this case.  We're reporting sense as parameter data.
9557          */
9558         ctsio->sense_len = 0;
9559         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9560         ctsio->be_move_done = ctl_config_move_done;
9561         ctl_datamove((union ctl_io *)ctsio);
9562
9563         return (CTL_RETVAL_COMPLETE);
9564 }
9565
9566 int
9567 ctl_tur(struct ctl_scsiio *ctsio)
9568 {
9569         struct ctl_lun *lun;
9570
9571         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9572
9573         CTL_DEBUG_PRINT(("ctl_tur\n"));
9574
9575         if (lun == NULL)
9576                 return (EINVAL);
9577
9578         ctsio->scsi_status = SCSI_STATUS_OK;
9579         ctsio->io_hdr.status = CTL_SUCCESS;
9580
9581         ctl_done((union ctl_io *)ctsio);
9582
9583         return (CTL_RETVAL_COMPLETE);
9584 }
9585
9586 #ifdef notyet
9587 static int
9588 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9589 {
9590
9591 }
9592 #endif
9593
9594 static int
9595 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9596 {
9597         struct scsi_vpd_supported_pages *pages;
9598         int sup_page_size;
9599         struct ctl_lun *lun;
9600
9601         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9602
9603         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9604             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9605         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9606         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9607         ctsio->kern_sg_entries = 0;
9608
9609         if (sup_page_size < alloc_len) {
9610                 ctsio->residual = alloc_len - sup_page_size;
9611                 ctsio->kern_data_len = sup_page_size;
9612                 ctsio->kern_total_len = sup_page_size;
9613         } else {
9614                 ctsio->residual = 0;
9615                 ctsio->kern_data_len = alloc_len;
9616                 ctsio->kern_total_len = alloc_len;
9617         }
9618         ctsio->kern_data_resid = 0;
9619         ctsio->kern_rel_offset = 0;
9620         ctsio->kern_sg_entries = 0;
9621
9622         /*
9623          * The control device is always connected.  The disk device, on the
9624          * other hand, may not be online all the time.  Need to change this
9625          * to figure out whether the disk device is actually online or not.
9626          */
9627         if (lun != NULL)
9628                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9629                                 lun->be_lun->lun_type;
9630         else
9631                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9632
9633         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9634         /* Supported VPD pages */
9635         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9636         /* Serial Number */
9637         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9638         /* Device Identification */
9639         pages->page_list[2] = SVPD_DEVICE_ID;
9640         /* SCSI Ports */
9641         pages->page_list[3] = SVPD_SCSI_PORTS;
9642         /* Block limits */
9643         pages->page_list[4] = SVPD_BLOCK_LIMITS;
9644         /* Logical Block Provisioning */
9645         pages->page_list[5] = SVPD_LBP;
9646
9647         ctsio->scsi_status = SCSI_STATUS_OK;
9648
9649         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9650         ctsio->be_move_done = ctl_config_move_done;
9651         ctl_datamove((union ctl_io *)ctsio);
9652
9653         return (CTL_RETVAL_COMPLETE);
9654 }
9655
9656 static int
9657 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9658 {
9659         struct scsi_vpd_unit_serial_number *sn_ptr;
9660         struct ctl_lun *lun;
9661
9662         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9663
9664         ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9665         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9666         ctsio->kern_sg_entries = 0;
9667
9668         if (sizeof(*sn_ptr) < alloc_len) {
9669                 ctsio->residual = alloc_len - sizeof(*sn_ptr);
9670                 ctsio->kern_data_len = sizeof(*sn_ptr);
9671                 ctsio->kern_total_len = sizeof(*sn_ptr);
9672         } else {
9673                 ctsio->residual = 0;
9674                 ctsio->kern_data_len = alloc_len;
9675                 ctsio->kern_total_len = alloc_len;
9676         }
9677         ctsio->kern_data_resid = 0;
9678         ctsio->kern_rel_offset = 0;
9679         ctsio->kern_sg_entries = 0;
9680
9681         /*
9682          * The control device is always connected.  The disk device, on the
9683          * other hand, may not be online all the time.  Need to change this
9684          * to figure out whether the disk device is actually online or not.
9685          */
9686         if (lun != NULL)
9687                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9688                                   lun->be_lun->lun_type;
9689         else
9690                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9691
9692         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9693         sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9694         /*
9695          * If we don't have a LUN, we just leave the serial number as
9696          * all spaces.
9697          */
9698         memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9699         if (lun != NULL) {
9700                 strncpy((char *)sn_ptr->serial_num,
9701                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9702         }
9703         ctsio->scsi_status = SCSI_STATUS_OK;
9704
9705         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9706         ctsio->be_move_done = ctl_config_move_done;
9707         ctl_datamove((union ctl_io *)ctsio);
9708
9709         return (CTL_RETVAL_COMPLETE);
9710 }
9711
9712
9713 static int
9714 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9715 {
9716         struct scsi_vpd_device_id *devid_ptr;
9717         struct scsi_vpd_id_descriptor *desc;
9718         struct ctl_softc *ctl_softc;
9719         struct ctl_lun *lun;
9720         struct ctl_port *port;
9721         int data_len;
9722         uint8_t proto;
9723
9724         ctl_softc = control_softc;
9725
9726         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9727         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9728
9729         data_len = sizeof(struct scsi_vpd_device_id) +
9730             sizeof(struct scsi_vpd_id_descriptor) +
9731                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9732             sizeof(struct scsi_vpd_id_descriptor) +
9733                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9734         if (lun && lun->lun_devid)
9735                 data_len += lun->lun_devid->len;
9736         if (port->port_devid)
9737                 data_len += port->port_devid->len;
9738         if (port->target_devid)
9739                 data_len += port->target_devid->len;
9740
9741         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9742         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9743         ctsio->kern_sg_entries = 0;
9744
9745         if (data_len < alloc_len) {
9746                 ctsio->residual = alloc_len - data_len;
9747                 ctsio->kern_data_len = data_len;
9748                 ctsio->kern_total_len = data_len;
9749         } else {
9750                 ctsio->residual = 0;
9751                 ctsio->kern_data_len = alloc_len;
9752                 ctsio->kern_total_len = alloc_len;
9753         }
9754         ctsio->kern_data_resid = 0;
9755         ctsio->kern_rel_offset = 0;
9756         ctsio->kern_sg_entries = 0;
9757
9758         /*
9759          * The control device is always connected.  The disk device, on the
9760          * other hand, may not be online all the time.
9761          */
9762         if (lun != NULL)
9763                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9764                                      lun->be_lun->lun_type;
9765         else
9766                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9767         devid_ptr->page_code = SVPD_DEVICE_ID;
9768         scsi_ulto2b(data_len - 4, devid_ptr->length);
9769
9770         if (port->port_type == CTL_PORT_FC)
9771                 proto = SCSI_PROTO_FC << 4;
9772         else if (port->port_type == CTL_PORT_ISCSI)
9773                 proto = SCSI_PROTO_ISCSI << 4;
9774         else
9775                 proto = SCSI_PROTO_SPI << 4;
9776         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9777
9778         /*
9779          * We're using a LUN association here.  i.e., this device ID is a
9780          * per-LUN identifier.
9781          */
9782         if (lun && lun->lun_devid) {
9783                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9784                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9785                     lun->lun_devid->len);
9786         }
9787
9788         /*
9789          * This is for the WWPN which is a port association.
9790          */
9791         if (port->port_devid) {
9792                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9793                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9794                     port->port_devid->len);
9795         }
9796
9797         /*
9798          * This is for the Relative Target Port(type 4h) identifier
9799          */
9800         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9801         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9802             SVPD_ID_TYPE_RELTARG;
9803         desc->length = 4;
9804         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9805         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9806             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9807
9808         /*
9809          * This is for the Target Port Group(type 5h) identifier
9810          */
9811         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9812         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9813             SVPD_ID_TYPE_TPORTGRP;
9814         desc->length = 4;
9815         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9816             &desc->identifier[2]);
9817         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9818             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9819
9820         /*
9821          * This is for the Target identifier
9822          */
9823         if (port->target_devid) {
9824                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9825         }
9826
9827         ctsio->scsi_status = SCSI_STATUS_OK;
9828         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9829         ctsio->be_move_done = ctl_config_move_done;
9830         ctl_datamove((union ctl_io *)ctsio);
9831
9832         return (CTL_RETVAL_COMPLETE);
9833 }
9834
9835 static int
9836 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9837 {
9838         struct ctl_softc *softc = control_softc;
9839         struct scsi_vpd_scsi_ports *sp;
9840         struct scsi_vpd_port_designation *pd;
9841         struct scsi_vpd_port_designation_cont *pdc;
9842         struct ctl_lun *lun;
9843         struct ctl_port *port;
9844         int data_len, num_target_ports, id_len, g, pg, p;
9845         int num_target_port_groups, single;
9846
9847         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9848
9849         single = ctl_is_single;
9850         if (single)
9851                 num_target_port_groups = 1;
9852         else
9853                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9854         num_target_ports = 0;
9855         id_len = 0;
9856         mtx_lock(&softc->ctl_lock);
9857         STAILQ_FOREACH(port, &softc->port_list, links) {
9858                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9859                         continue;
9860                 if (ctl_map_lun_back(port->targ_port, lun->lun) >=
9861                     CTL_MAX_LUNS)
9862                         continue;
9863                 num_target_ports++;
9864                 if (port->port_devid)
9865                         id_len += port->port_devid->len;
9866         }
9867         mtx_unlock(&softc->ctl_lock);
9868
9869         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9870             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9871              sizeof(struct scsi_vpd_port_designation_cont)) + id_len;
9872         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9873         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9874         ctsio->kern_sg_entries = 0;
9875
9876         if (data_len < alloc_len) {
9877                 ctsio->residual = alloc_len - data_len;
9878                 ctsio->kern_data_len = data_len;
9879                 ctsio->kern_total_len = data_len;
9880         } else {
9881                 ctsio->residual = 0;
9882                 ctsio->kern_data_len = alloc_len;
9883                 ctsio->kern_total_len = alloc_len;
9884         }
9885         ctsio->kern_data_resid = 0;
9886         ctsio->kern_rel_offset = 0;
9887         ctsio->kern_sg_entries = 0;
9888
9889         /*
9890          * The control device is always connected.  The disk device, on the
9891          * other hand, may not be online all the time.  Need to change this
9892          * to figure out whether the disk device is actually online or not.
9893          */
9894         if (lun != NULL)
9895                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9896                                   lun->be_lun->lun_type;
9897         else
9898                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9899
9900         sp->page_code = SVPD_SCSI_PORTS;
9901         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9902             sp->page_length);
9903         pd = &sp->design[0];
9904
9905         mtx_lock(&softc->ctl_lock);
9906         if (softc->flags & CTL_FLAG_MASTER_SHELF)
9907                 pg = 0;
9908         else
9909                 pg = 1;
9910         for (g = 0; g < num_target_port_groups; g++) {
9911                 STAILQ_FOREACH(port, &softc->port_list, links) {
9912                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9913                                 continue;
9914                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
9915                             CTL_MAX_LUNS)
9916                                 continue;
9917                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9918                         scsi_ulto2b(p, pd->relative_port_id);
9919                         scsi_ulto2b(0, pd->initiator_transportid_length);
9920                         pdc = (struct scsi_vpd_port_designation_cont *)
9921                             &pd->initiator_transportid[0];
9922                         if (port->port_devid && g == pg) {
9923                                 id_len = port->port_devid->len;
9924                                 scsi_ulto2b(port->port_devid->len,
9925                                     pdc->target_port_descriptors_length);
9926                                 memcpy(pdc->target_port_descriptors,
9927                                     port->port_devid->data, port->port_devid->len);
9928                         } else {
9929                                 id_len = 0;
9930                                 scsi_ulto2b(0, pdc->target_port_descriptors_length);
9931                         }
9932                         pd = (struct scsi_vpd_port_designation *)
9933                             ((uint8_t *)pdc->target_port_descriptors + id_len);
9934                 }
9935         }
9936         mtx_unlock(&softc->ctl_lock);
9937
9938         ctsio->scsi_status = SCSI_STATUS_OK;
9939         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9940         ctsio->be_move_done = ctl_config_move_done;
9941         ctl_datamove((union ctl_io *)ctsio);
9942
9943         return (CTL_RETVAL_COMPLETE);
9944 }
9945
9946 static int
9947 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9948 {
9949         struct scsi_vpd_block_limits *bl_ptr;
9950         struct ctl_lun *lun;
9951         int bs;
9952
9953         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9954         bs = lun->be_lun->blocksize;
9955
9956         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9957         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9958         ctsio->kern_sg_entries = 0;
9959
9960         if (sizeof(*bl_ptr) < alloc_len) {
9961                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9962                 ctsio->kern_data_len = sizeof(*bl_ptr);
9963                 ctsio->kern_total_len = sizeof(*bl_ptr);
9964         } else {
9965                 ctsio->residual = 0;
9966                 ctsio->kern_data_len = alloc_len;
9967                 ctsio->kern_total_len = alloc_len;
9968         }
9969         ctsio->kern_data_resid = 0;
9970         ctsio->kern_rel_offset = 0;
9971         ctsio->kern_sg_entries = 0;
9972
9973         /*
9974          * The control device is always connected.  The disk device, on the
9975          * other hand, may not be online all the time.  Need to change this
9976          * to figure out whether the disk device is actually online or not.
9977          */
9978         if (lun != NULL)
9979                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9980                                   lun->be_lun->lun_type;
9981         else
9982                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9983
9984         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9985         scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
9986         bl_ptr->max_cmp_write_len = 0xff;
9987         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9988         scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
9989         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9990                 scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9991                 scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9992         }
9993         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9994
9995         ctsio->scsi_status = SCSI_STATUS_OK;
9996         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9997         ctsio->be_move_done = ctl_config_move_done;
9998         ctl_datamove((union ctl_io *)ctsio);
9999
10000         return (CTL_RETVAL_COMPLETE);
10001 }
10002
10003 static int
10004 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10005 {
10006         struct scsi_vpd_logical_block_prov *lbp_ptr;
10007         struct ctl_lun *lun;
10008         int bs;
10009
10010         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10011         bs = lun->be_lun->blocksize;
10012
10013         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10014         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10015         ctsio->kern_sg_entries = 0;
10016
10017         if (sizeof(*lbp_ptr) < alloc_len) {
10018                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10019                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10020                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10021         } else {
10022                 ctsio->residual = 0;
10023                 ctsio->kern_data_len = alloc_len;
10024                 ctsio->kern_total_len = alloc_len;
10025         }
10026         ctsio->kern_data_resid = 0;
10027         ctsio->kern_rel_offset = 0;
10028         ctsio->kern_sg_entries = 0;
10029
10030         /*
10031          * The control device is always connected.  The disk device, on the
10032          * other hand, may not be online all the time.  Need to change this
10033          * to figure out whether the disk device is actually online or not.
10034          */
10035         if (lun != NULL)
10036                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10037                                   lun->be_lun->lun_type;
10038         else
10039                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10040
10041         lbp_ptr->page_code = SVPD_LBP;
10042         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
10043                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
10044
10045         ctsio->scsi_status = SCSI_STATUS_OK;
10046         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10047         ctsio->be_move_done = ctl_config_move_done;
10048         ctl_datamove((union ctl_io *)ctsio);
10049
10050         return (CTL_RETVAL_COMPLETE);
10051 }
10052
10053 static int
10054 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10055 {
10056         struct scsi_inquiry *cdb;
10057         struct ctl_lun *lun;
10058         int alloc_len, retval;
10059
10060         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10061         cdb = (struct scsi_inquiry *)ctsio->cdb;
10062
10063         retval = CTL_RETVAL_COMPLETE;
10064
10065         alloc_len = scsi_2btoul(cdb->length);
10066
10067         switch (cdb->page_code) {
10068         case SVPD_SUPPORTED_PAGES:
10069                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10070                 break;
10071         case SVPD_UNIT_SERIAL_NUMBER:
10072                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10073                 break;
10074         case SVPD_DEVICE_ID:
10075                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10076                 break;
10077         case SVPD_SCSI_PORTS:
10078                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10079                 break;
10080         case SVPD_BLOCK_LIMITS:
10081                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10082                 break;
10083         case SVPD_LBP:
10084                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10085                 break;
10086         default:
10087                 ctl_set_invalid_field(ctsio,
10088                                       /*sks_valid*/ 1,
10089                                       /*command*/ 1,
10090                                       /*field*/ 2,
10091                                       /*bit_valid*/ 0,
10092                                       /*bit*/ 0);
10093                 ctl_done((union ctl_io *)ctsio);
10094                 retval = CTL_RETVAL_COMPLETE;
10095                 break;
10096         }
10097
10098         return (retval);
10099 }
10100
10101 static int
10102 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10103 {
10104         struct scsi_inquiry_data *inq_ptr;
10105         struct scsi_inquiry *cdb;
10106         struct ctl_softc *ctl_softc;
10107         struct ctl_lun *lun;
10108         char *val;
10109         uint32_t alloc_len;
10110         int is_fc;
10111
10112         ctl_softc = control_softc;
10113
10114         /*
10115          * Figure out whether we're talking to a Fibre Channel port or not.
10116          * We treat the ioctl front end, and any SCSI adapters, as packetized
10117          * SCSI front ends.
10118          */
10119         if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
10120             CTL_PORT_FC)
10121                 is_fc = 0;
10122         else
10123                 is_fc = 1;
10124
10125         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10126         cdb = (struct scsi_inquiry *)ctsio->cdb;
10127         alloc_len = scsi_2btoul(cdb->length);
10128
10129         /*
10130          * We malloc the full inquiry data size here and fill it
10131          * in.  If the user only asks for less, we'll give him
10132          * that much.
10133          */
10134         ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10135         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10136         ctsio->kern_sg_entries = 0;
10137         ctsio->kern_data_resid = 0;
10138         ctsio->kern_rel_offset = 0;
10139
10140         if (sizeof(*inq_ptr) < alloc_len) {
10141                 ctsio->residual = alloc_len - sizeof(*inq_ptr);
10142                 ctsio->kern_data_len = sizeof(*inq_ptr);
10143                 ctsio->kern_total_len = sizeof(*inq_ptr);
10144         } else {
10145                 ctsio->residual = 0;
10146                 ctsio->kern_data_len = alloc_len;
10147                 ctsio->kern_total_len = alloc_len;
10148         }
10149
10150         /*
10151          * If we have a LUN configured, report it as connected.  Otherwise,
10152          * report that it is offline or no device is supported, depending 
10153          * on the value of inquiry_pq_no_lun.
10154          *
10155          * According to the spec (SPC-4 r34), the peripheral qualifier
10156          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10157          *
10158          * "A peripheral device having the specified peripheral device type 
10159          * is not connected to this logical unit. However, the device
10160          * server is capable of supporting the specified peripheral device
10161          * type on this logical unit."
10162          *
10163          * According to the same spec, the peripheral qualifier
10164          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10165          *
10166          * "The device server is not capable of supporting a peripheral
10167          * device on this logical unit. For this peripheral qualifier the
10168          * peripheral device type shall be set to 1Fh. All other peripheral
10169          * device type values are reserved for this peripheral qualifier."
10170          *
10171          * Given the text, it would seem that we probably want to report that
10172          * the LUN is offline here.  There is no LUN connected, but we can
10173          * support a LUN at the given LUN number.
10174          *
10175          * In the real world, though, it sounds like things are a little
10176          * different:
10177          *
10178          * - Linux, when presented with a LUN with the offline peripheral
10179          *   qualifier, will create an sg driver instance for it.  So when
10180          *   you attach it to CTL, you wind up with a ton of sg driver
10181          *   instances.  (One for every LUN that Linux bothered to probe.)
10182          *   Linux does this despite the fact that it issues a REPORT LUNs
10183          *   to LUN 0 to get the inventory of supported LUNs.
10184          *
10185          * - There is other anecdotal evidence (from Emulex folks) about
10186          *   arrays that use the offline peripheral qualifier for LUNs that
10187          *   are on the "passive" path in an active/passive array.
10188          *
10189          * So the solution is provide a hopefully reasonable default
10190          * (return bad/no LUN) and allow the user to change the behavior
10191          * with a tunable/sysctl variable.
10192          */
10193         if (lun != NULL)
10194                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10195                                   lun->be_lun->lun_type;
10196         else if (ctl_softc->inquiry_pq_no_lun == 0)
10197                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10198         else
10199                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10200
10201         /* RMB in byte 2 is 0 */
10202         inq_ptr->version = SCSI_REV_SPC3;
10203
10204         /*
10205          * According to SAM-3, even if a device only supports a single
10206          * level of LUN addressing, it should still set the HISUP bit:
10207          *
10208          * 4.9.1 Logical unit numbers overview
10209          *
10210          * All logical unit number formats described in this standard are
10211          * hierarchical in structure even when only a single level in that
10212          * hierarchy is used. The HISUP bit shall be set to one in the
10213          * standard INQUIRY data (see SPC-2) when any logical unit number
10214          * format described in this standard is used.  Non-hierarchical
10215          * formats are outside the scope of this standard.
10216          *
10217          * Therefore we set the HiSup bit here.
10218          *
10219          * The reponse format is 2, per SPC-3.
10220          */
10221         inq_ptr->response_format = SID_HiSup | 2;
10222
10223         inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
10224         CTL_DEBUG_PRINT(("additional_length = %d\n",
10225                          inq_ptr->additional_length));
10226
10227         inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
10228         /* 16 bit addressing */
10229         if (is_fc == 0)
10230                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10231         /* XXX set the SID_MultiP bit here if we're actually going to
10232            respond on multiple ports */
10233         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10234
10235         /* 16 bit data bus, synchronous transfers */
10236         /* XXX these flags don't apply for FC */
10237         if (is_fc == 0)
10238                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10239         /*
10240          * XXX KDM do we want to support tagged queueing on the control
10241          * device at all?
10242          */
10243         if ((lun == NULL)
10244          || (lun->be_lun->lun_type != T_PROCESSOR))
10245                 inq_ptr->flags |= SID_CmdQue;
10246         /*
10247          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10248          * We have 8 bytes for the vendor name, and 16 bytes for the device
10249          * name and 4 bytes for the revision.
10250          */
10251         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10252             "vendor")) == NULL) {
10253                 strcpy(inq_ptr->vendor, CTL_VENDOR);
10254         } else {
10255                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10256                 strncpy(inq_ptr->vendor, val,
10257                     min(sizeof(inq_ptr->vendor), strlen(val)));
10258         }
10259         if (lun == NULL) {
10260                 strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10261         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10262                 switch (lun->be_lun->lun_type) {
10263                 case T_DIRECT:
10264                         strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10265                         break;
10266                 case T_PROCESSOR:
10267                         strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10268                         break;
10269                 default:
10270                         strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10271                         break;
10272                 }
10273         } else {
10274                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10275                 strncpy(inq_ptr->product, val,
10276                     min(sizeof(inq_ptr->product), strlen(val)));
10277         }
10278
10279         /*
10280          * XXX make this a macro somewhere so it automatically gets
10281          * incremented when we make changes.
10282          */
10283         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10284             "revision")) == NULL) {
10285                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10286         } else {
10287                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10288                 strncpy(inq_ptr->revision, val,
10289                     min(sizeof(inq_ptr->revision), strlen(val)));
10290         }
10291
10292         /*
10293          * For parallel SCSI, we support double transition and single
10294          * transition clocking.  We also support QAS (Quick Arbitration
10295          * and Selection) and Information Unit transfers on both the
10296          * control and array devices.
10297          */
10298         if (is_fc == 0)
10299                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10300                                     SID_SPI_IUS;
10301
10302         /* SAM-3 */
10303         scsi_ulto2b(0x0060, inq_ptr->version1);
10304         /* SPC-3 (no version claimed) XXX should we claim a version? */
10305         scsi_ulto2b(0x0300, inq_ptr->version2);
10306         if (is_fc) {
10307                 /* FCP-2 ANSI INCITS.350:2003 */
10308                 scsi_ulto2b(0x0917, inq_ptr->version3);
10309         } else {
10310                 /* SPI-4 ANSI INCITS.362:200x */
10311                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10312         }
10313
10314         if (lun == NULL) {
10315                 /* SBC-2 (no version claimed) XXX should we claim a version? */
10316                 scsi_ulto2b(0x0320, inq_ptr->version4);
10317         } else {
10318                 switch (lun->be_lun->lun_type) {
10319                 case T_DIRECT:
10320                         /*
10321                          * SBC-2 (no version claimed) XXX should we claim a
10322                          * version?
10323                          */
10324                         scsi_ulto2b(0x0320, inq_ptr->version4);
10325                         break;
10326                 case T_PROCESSOR:
10327                 default:
10328                         break;
10329                 }
10330         }
10331
10332         ctsio->scsi_status = SCSI_STATUS_OK;
10333         if (ctsio->kern_data_len > 0) {
10334                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10335                 ctsio->be_move_done = ctl_config_move_done;
10336                 ctl_datamove((union ctl_io *)ctsio);
10337         } else {
10338                 ctsio->io_hdr.status = CTL_SUCCESS;
10339                 ctl_done((union ctl_io *)ctsio);
10340         }
10341
10342         return (CTL_RETVAL_COMPLETE);
10343 }
10344
10345 int
10346 ctl_inquiry(struct ctl_scsiio *ctsio)
10347 {
10348         struct scsi_inquiry *cdb;
10349         int retval;
10350
10351         cdb = (struct scsi_inquiry *)ctsio->cdb;
10352
10353         retval = 0;
10354
10355         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10356
10357         /*
10358          * Right now, we don't support the CmdDt inquiry information.
10359          * This would be nice to support in the future.  When we do
10360          * support it, we should change this test so that it checks to make
10361          * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10362          */
10363 #ifdef notyet
10364         if (((cdb->byte2 & SI_EVPD)
10365          && (cdb->byte2 & SI_CMDDT)))
10366 #endif
10367         if (cdb->byte2 & SI_CMDDT) {
10368                 /*
10369                  * Point to the SI_CMDDT bit.  We might change this
10370                  * when we support SI_CMDDT, but since both bits would be
10371                  * "wrong", this should probably just stay as-is then.
10372                  */
10373                 ctl_set_invalid_field(ctsio,
10374                                       /*sks_valid*/ 1,
10375                                       /*command*/ 1,
10376                                       /*field*/ 1,
10377                                       /*bit_valid*/ 1,
10378                                       /*bit*/ 1);
10379                 ctl_done((union ctl_io *)ctsio);
10380                 return (CTL_RETVAL_COMPLETE);
10381         }
10382         if (cdb->byte2 & SI_EVPD)
10383                 retval = ctl_inquiry_evpd(ctsio);
10384 #ifdef notyet
10385         else if (cdb->byte2 & SI_CMDDT)
10386                 retval = ctl_inquiry_cmddt(ctsio);
10387 #endif
10388         else
10389                 retval = ctl_inquiry_std(ctsio);
10390
10391         return (retval);
10392 }
10393
10394 /*
10395  * For known CDB types, parse the LBA and length.
10396  */
10397 static int
10398 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10399 {
10400         if (io->io_hdr.io_type != CTL_IO_SCSI)
10401                 return (1);
10402
10403         switch (io->scsiio.cdb[0]) {
10404         case COMPARE_AND_WRITE: {
10405                 struct scsi_compare_and_write *cdb;
10406
10407                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10408
10409                 *lba = scsi_8btou64(cdb->addr);
10410                 *len = cdb->length;
10411                 break;
10412         }
10413         case READ_6:
10414         case WRITE_6: {
10415                 struct scsi_rw_6 *cdb;
10416
10417                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10418
10419                 *lba = scsi_3btoul(cdb->addr);
10420                 /* only 5 bits are valid in the most significant address byte */
10421                 *lba &= 0x1fffff;
10422                 *len = cdb->length;
10423                 break;
10424         }
10425         case READ_10:
10426         case WRITE_10: {
10427                 struct scsi_rw_10 *cdb;
10428
10429                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10430
10431                 *lba = scsi_4btoul(cdb->addr);
10432                 *len = scsi_2btoul(cdb->length);
10433                 break;
10434         }
10435         case WRITE_VERIFY_10: {
10436                 struct scsi_write_verify_10 *cdb;
10437
10438                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10439
10440                 *lba = scsi_4btoul(cdb->addr);
10441                 *len = scsi_2btoul(cdb->length);
10442                 break;
10443         }
10444         case READ_12:
10445         case WRITE_12: {
10446                 struct scsi_rw_12 *cdb;
10447
10448                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10449
10450                 *lba = scsi_4btoul(cdb->addr);
10451                 *len = scsi_4btoul(cdb->length);
10452                 break;
10453         }
10454         case WRITE_VERIFY_12: {
10455                 struct scsi_write_verify_12 *cdb;
10456
10457                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10458
10459                 *lba = scsi_4btoul(cdb->addr);
10460                 *len = scsi_4btoul(cdb->length);
10461                 break;
10462         }
10463         case READ_16:
10464         case WRITE_16: {
10465                 struct scsi_rw_16 *cdb;
10466
10467                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10468
10469                 *lba = scsi_8btou64(cdb->addr);
10470                 *len = scsi_4btoul(cdb->length);
10471                 break;
10472         }
10473         case WRITE_VERIFY_16: {
10474                 struct scsi_write_verify_16 *cdb;
10475
10476                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10477
10478                 
10479                 *lba = scsi_8btou64(cdb->addr);
10480                 *len = scsi_4btoul(cdb->length);
10481                 break;
10482         }
10483         case WRITE_SAME_10: {
10484                 struct scsi_write_same_10 *cdb;
10485
10486                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10487
10488                 *lba = scsi_4btoul(cdb->addr);
10489                 *len = scsi_2btoul(cdb->length);
10490                 break;
10491         }
10492         case WRITE_SAME_16: {
10493                 struct scsi_write_same_16 *cdb;
10494
10495                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10496
10497                 *lba = scsi_8btou64(cdb->addr);
10498                 *len = scsi_4btoul(cdb->length);
10499                 break;
10500         }
10501         case VERIFY_10: {
10502                 struct scsi_verify_10 *cdb;
10503
10504                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10505
10506                 *lba = scsi_4btoul(cdb->addr);
10507                 *len = scsi_2btoul(cdb->length);
10508                 break;
10509         }
10510         case VERIFY_12: {
10511                 struct scsi_verify_12 *cdb;
10512
10513                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10514
10515                 *lba = scsi_4btoul(cdb->addr);
10516                 *len = scsi_4btoul(cdb->length);
10517                 break;
10518         }
10519         case VERIFY_16: {
10520                 struct scsi_verify_16 *cdb;
10521
10522                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10523
10524                 *lba = scsi_8btou64(cdb->addr);
10525                 *len = scsi_4btoul(cdb->length);
10526                 break;
10527         }
10528         default:
10529                 return (1);
10530                 break; /* NOTREACHED */
10531         }
10532
10533         return (0);
10534 }
10535
10536 static ctl_action
10537 ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10538 {
10539         uint64_t endlba1, endlba2;
10540
10541         endlba1 = lba1 + len1 - 1;
10542         endlba2 = lba2 + len2 - 1;
10543
10544         if ((endlba1 < lba2)
10545          || (endlba2 < lba1))
10546                 return (CTL_ACTION_PASS);
10547         else
10548                 return (CTL_ACTION_BLOCK);
10549 }
10550
10551 static ctl_action
10552 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10553 {
10554         uint64_t lba1, lba2;
10555         uint32_t len1, len2;
10556         int retval;
10557
10558         retval = ctl_get_lba_len(io1, &lba1, &len1);
10559         if (retval != 0)
10560                 return (CTL_ACTION_ERROR);
10561
10562         retval = ctl_get_lba_len(io2, &lba2, &len2);
10563         if (retval != 0)
10564                 return (CTL_ACTION_ERROR);
10565
10566         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10567 }
10568
10569 static ctl_action
10570 ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10571 {
10572         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10573         ctl_serialize_action *serialize_row;
10574
10575         /*
10576          * The initiator attempted multiple untagged commands at the same
10577          * time.  Can't do that.
10578          */
10579         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10580          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10581          && ((pending_io->io_hdr.nexus.targ_port ==
10582               ooa_io->io_hdr.nexus.targ_port)
10583           && (pending_io->io_hdr.nexus.initid.id ==
10584               ooa_io->io_hdr.nexus.initid.id))
10585          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10586                 return (CTL_ACTION_OVERLAP);
10587
10588         /*
10589          * The initiator attempted to send multiple tagged commands with
10590          * the same ID.  (It's fine if different initiators have the same
10591          * tag ID.)
10592          *
10593          * Even if all of those conditions are true, we don't kill the I/O
10594          * if the command ahead of us has been aborted.  We won't end up
10595          * sending it to the FETD, and it's perfectly legal to resend a
10596          * command with the same tag number as long as the previous
10597          * instance of this tag number has been aborted somehow.
10598          */
10599         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10600          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10601          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10602          && ((pending_io->io_hdr.nexus.targ_port ==
10603               ooa_io->io_hdr.nexus.targ_port)
10604           && (pending_io->io_hdr.nexus.initid.id ==
10605               ooa_io->io_hdr.nexus.initid.id))
10606          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10607                 return (CTL_ACTION_OVERLAP_TAG);
10608
10609         /*
10610          * If we get a head of queue tag, SAM-3 says that we should
10611          * immediately execute it.
10612          *
10613          * What happens if this command would normally block for some other
10614          * reason?  e.g. a request sense with a head of queue tag
10615          * immediately after a write.  Normally that would block, but this
10616          * will result in its getting executed immediately...
10617          *
10618          * We currently return "pass" instead of "skip", so we'll end up
10619          * going through the rest of the queue to check for overlapped tags.
10620          *
10621          * XXX KDM check for other types of blockage first??
10622          */
10623         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10624                 return (CTL_ACTION_PASS);
10625
10626         /*
10627          * Ordered tags have to block until all items ahead of them
10628          * have completed.  If we get called with an ordered tag, we always
10629          * block, if something else is ahead of us in the queue.
10630          */
10631         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10632                 return (CTL_ACTION_BLOCK);
10633
10634         /*
10635          * Simple tags get blocked until all head of queue and ordered tags
10636          * ahead of them have completed.  I'm lumping untagged commands in
10637          * with simple tags here.  XXX KDM is that the right thing to do?
10638          */
10639         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10640           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10641          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10642           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10643                 return (CTL_ACTION_BLOCK);
10644
10645         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10646         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10647
10648         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10649
10650         switch (serialize_row[pending_entry->seridx]) {
10651         case CTL_SER_BLOCK:
10652                 return (CTL_ACTION_BLOCK);
10653                 break; /* NOTREACHED */
10654         case CTL_SER_EXTENT:
10655                 return (ctl_extent_check(pending_io, ooa_io));
10656                 break; /* NOTREACHED */
10657         case CTL_SER_PASS:
10658                 return (CTL_ACTION_PASS);
10659                 break; /* NOTREACHED */
10660         case CTL_SER_SKIP:
10661                 return (CTL_ACTION_SKIP);
10662                 break;
10663         default:
10664                 panic("invalid serialization value %d",
10665                       serialize_row[pending_entry->seridx]);
10666                 break; /* NOTREACHED */
10667         }
10668
10669         return (CTL_ACTION_ERROR);
10670 }
10671
10672 /*
10673  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10674  * Assumptions:
10675  * - pending_io is generally either incoming, or on the blocked queue
10676  * - starting I/O is the I/O we want to start the check with.
10677  */
10678 static ctl_action
10679 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10680               union ctl_io *starting_io)
10681 {
10682         union ctl_io *ooa_io;
10683         ctl_action action;
10684
10685         mtx_assert(&lun->lun_lock, MA_OWNED);
10686
10687         /*
10688          * Run back along the OOA queue, starting with the current
10689          * blocked I/O and going through every I/O before it on the
10690          * queue.  If starting_io is NULL, we'll just end up returning
10691          * CTL_ACTION_PASS.
10692          */
10693         for (ooa_io = starting_io; ooa_io != NULL;
10694              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10695              ooa_links)){
10696
10697                 /*
10698                  * This routine just checks to see whether
10699                  * cur_blocked is blocked by ooa_io, which is ahead
10700                  * of it in the queue.  It doesn't queue/dequeue
10701                  * cur_blocked.
10702                  */
10703                 action = ctl_check_for_blockage(pending_io, ooa_io);
10704                 switch (action) {
10705                 case CTL_ACTION_BLOCK:
10706                 case CTL_ACTION_OVERLAP:
10707                 case CTL_ACTION_OVERLAP_TAG:
10708                 case CTL_ACTION_SKIP:
10709                 case CTL_ACTION_ERROR:
10710                         return (action);
10711                         break; /* NOTREACHED */
10712                 case CTL_ACTION_PASS:
10713                         break;
10714                 default:
10715                         panic("invalid action %d", action);
10716                         break;  /* NOTREACHED */
10717                 }
10718         }
10719
10720         return (CTL_ACTION_PASS);
10721 }
10722
10723 /*
10724  * Assumptions:
10725  * - An I/O has just completed, and has been removed from the per-LUN OOA
10726  *   queue, so some items on the blocked queue may now be unblocked.
10727  */
10728 static int
10729 ctl_check_blocked(struct ctl_lun *lun)
10730 {
10731         union ctl_io *cur_blocked, *next_blocked;
10732
10733         mtx_assert(&lun->lun_lock, MA_OWNED);
10734
10735         /*
10736          * Run forward from the head of the blocked queue, checking each
10737          * entry against the I/Os prior to it on the OOA queue to see if
10738          * there is still any blockage.
10739          *
10740          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10741          * with our removing a variable on it while it is traversing the
10742          * list.
10743          */
10744         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10745              cur_blocked != NULL; cur_blocked = next_blocked) {
10746                 union ctl_io *prev_ooa;
10747                 ctl_action action;
10748
10749                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10750                                                           blocked_links);
10751
10752                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10753                                                       ctl_ooaq, ooa_links);
10754
10755                 /*
10756                  * If cur_blocked happens to be the first item in the OOA
10757                  * queue now, prev_ooa will be NULL, and the action
10758                  * returned will just be CTL_ACTION_PASS.
10759                  */
10760                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10761
10762                 switch (action) {
10763                 case CTL_ACTION_BLOCK:
10764                         /* Nothing to do here, still blocked */
10765                         break;
10766                 case CTL_ACTION_OVERLAP:
10767                 case CTL_ACTION_OVERLAP_TAG:
10768                         /*
10769                          * This shouldn't happen!  In theory we've already
10770                          * checked this command for overlap...
10771                          */
10772                         break;
10773                 case CTL_ACTION_PASS:
10774                 case CTL_ACTION_SKIP: {
10775                         struct ctl_softc *softc;
10776                         const struct ctl_cmd_entry *entry;
10777                         uint32_t initidx;
10778                         int isc_retval;
10779
10780                         /*
10781                          * The skip case shouldn't happen, this transaction
10782                          * should have never made it onto the blocked queue.
10783                          */
10784                         /*
10785                          * This I/O is no longer blocked, we can remove it
10786                          * from the blocked queue.  Since this is a TAILQ
10787                          * (doubly linked list), we can do O(1) removals
10788                          * from any place on the list.
10789                          */
10790                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10791                                      blocked_links);
10792                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10793
10794                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10795                                 /*
10796                                  * Need to send IO back to original side to
10797                                  * run
10798                                  */
10799                                 union ctl_ha_msg msg_info;
10800
10801                                 msg_info.hdr.original_sc =
10802                                         cur_blocked->io_hdr.original_sc;
10803                                 msg_info.hdr.serializing_sc = cur_blocked;
10804                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10805                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10806                                      &msg_info, sizeof(msg_info), 0)) >
10807                                      CTL_HA_STATUS_SUCCESS) {
10808                                         printf("CTL:Check Blocked error from "
10809                                                "ctl_ha_msg_send %d\n",
10810                                                isc_retval);
10811                                 }
10812                                 break;
10813                         }
10814                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
10815                         softc = control_softc;
10816
10817                         initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10818
10819                         /*
10820                          * Check this I/O for LUN state changes that may
10821                          * have happened while this command was blocked.
10822                          * The LUN state may have been changed by a command
10823                          * ahead of us in the queue, so we need to re-check
10824                          * for any states that can be caused by SCSI
10825                          * commands.
10826                          */
10827                         if (ctl_scsiio_lun_check(softc, lun, entry,
10828                                                  &cur_blocked->scsiio) == 0) {
10829                                 cur_blocked->io_hdr.flags |=
10830                                                       CTL_FLAG_IS_WAS_ON_RTR;
10831                                 ctl_enqueue_rtr(cur_blocked);
10832                         } else
10833                                 ctl_done(cur_blocked);
10834                         break;
10835                 }
10836                 default:
10837                         /*
10838                          * This probably shouldn't happen -- we shouldn't
10839                          * get CTL_ACTION_ERROR, or anything else.
10840                          */
10841                         break;
10842                 }
10843         }
10844
10845         return (CTL_RETVAL_COMPLETE);
10846 }
10847
10848 /*
10849  * This routine (with one exception) checks LUN flags that can be set by
10850  * commands ahead of us in the OOA queue.  These flags have to be checked
10851  * when a command initially comes in, and when we pull a command off the
10852  * blocked queue and are preparing to execute it.  The reason we have to
10853  * check these flags for commands on the blocked queue is that the LUN
10854  * state may have been changed by a command ahead of us while we're on the
10855  * blocked queue.
10856  *
10857  * Ordering is somewhat important with these checks, so please pay
10858  * careful attention to the placement of any new checks.
10859  */
10860 static int
10861 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10862     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10863 {
10864         int retval;
10865
10866         retval = 0;
10867
10868         mtx_assert(&lun->lun_lock, MA_OWNED);
10869
10870         /*
10871          * If this shelf is a secondary shelf controller, we have to reject
10872          * any media access commands.
10873          */
10874 #if 0
10875         /* No longer needed for HA */
10876         if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
10877          && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
10878                 ctl_set_lun_standby(ctsio);
10879                 retval = 1;
10880                 goto bailout;
10881         }
10882 #endif
10883
10884         /*
10885          * Check for a reservation conflict.  If this command isn't allowed
10886          * even on reserved LUNs, and if this initiator isn't the one who
10887          * reserved us, reject the command with a reservation conflict.
10888          */
10889         if ((lun->flags & CTL_LUN_RESERVED)
10890          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10891                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
10892                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
10893                  || (ctsio->io_hdr.nexus.targ_target.id !=
10894                      lun->rsv_nexus.targ_target.id)) {
10895                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10896                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
10897                         retval = 1;
10898                         goto bailout;
10899                 }
10900         }
10901
10902         if ( (lun->flags & CTL_LUN_PR_RESERVED)
10903          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
10904                 uint32_t residx;
10905
10906                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10907                 /*
10908                  * if we aren't registered or it's a res holder type
10909                  * reservation and this isn't the res holder then set a
10910                  * conflict.
10911                  * NOTE: Commands which might be allowed on write exclusive
10912                  * type reservations are checked in the particular command
10913                  * for a conflict. Read and SSU are the only ones.
10914                  */
10915                 if (!lun->per_res[residx].registered
10916                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10917                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10918                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
10919                         retval = 1;
10920                         goto bailout;
10921                 }
10922
10923         }
10924
10925         if ((lun->flags & CTL_LUN_OFFLINE)
10926          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10927                 ctl_set_lun_not_ready(ctsio);
10928                 retval = 1;
10929                 goto bailout;
10930         }
10931
10932         /*
10933          * If the LUN is stopped, see if this particular command is allowed
10934          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10935          */
10936         if ((lun->flags & CTL_LUN_STOPPED)
10937          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10938                 /* "Logical unit not ready, initializing cmd. required" */
10939                 ctl_set_lun_stopped(ctsio);
10940                 retval = 1;
10941                 goto bailout;
10942         }
10943
10944         if ((lun->flags & CTL_LUN_INOPERABLE)
10945          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10946                 /* "Medium format corrupted" */
10947                 ctl_set_medium_format_corrupted(ctsio);
10948                 retval = 1;
10949                 goto bailout;
10950         }
10951
10952 bailout:
10953         return (retval);
10954
10955 }
10956
10957 static void
10958 ctl_failover_io(union ctl_io *io, int have_lock)
10959 {
10960         ctl_set_busy(&io->scsiio);
10961         ctl_done(io);
10962 }
10963
10964 static void
10965 ctl_failover(void)
10966 {
10967         struct ctl_lun *lun;
10968         struct ctl_softc *ctl_softc;
10969         union ctl_io *next_io, *pending_io;
10970         union ctl_io *io;
10971         int lun_idx;
10972         int i;
10973
10974         ctl_softc = control_softc;
10975
10976         mtx_lock(&ctl_softc->ctl_lock);
10977         /*
10978          * Remove any cmds from the other SC from the rtr queue.  These
10979          * will obviously only be for LUNs for which we're the primary.
10980          * We can't send status or get/send data for these commands.
10981          * Since they haven't been executed yet, we can just remove them.
10982          * We'll either abort them or delete them below, depending on
10983          * which HA mode we're in.
10984          */
10985 #ifdef notyet
10986         mtx_lock(&ctl_softc->queue_lock);
10987         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
10988              io != NULL; io = next_io) {
10989                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10990                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10991                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
10992                                       ctl_io_hdr, links);
10993         }
10994         mtx_unlock(&ctl_softc->queue_lock);
10995 #endif
10996
10997         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
10998                 lun = ctl_softc->ctl_luns[lun_idx];
10999                 if (lun==NULL)
11000                         continue;
11001
11002                 /*
11003                  * Processor LUNs are primary on both sides.
11004                  * XXX will this always be true?
11005                  */
11006                 if (lun->be_lun->lun_type == T_PROCESSOR)
11007                         continue;
11008
11009                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11010                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11011                         printf("FAILOVER: primary lun %d\n", lun_idx);
11012                         /*
11013                          * Remove all commands from the other SC. First from the
11014                          * blocked queue then from the ooa queue. Once we have
11015                          * removed them. Call ctl_check_blocked to see if there
11016                          * is anything that can run.
11017                          */
11018                         for (io = (union ctl_io *)TAILQ_FIRST(
11019                              &lun->blocked_queue); io != NULL; io = next_io) {
11020
11021                                 next_io = (union ctl_io *)TAILQ_NEXT(
11022                                     &io->io_hdr, blocked_links);
11023
11024                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11025                                         TAILQ_REMOVE(&lun->blocked_queue,
11026                                                      &io->io_hdr,blocked_links);
11027                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11028                                         TAILQ_REMOVE(&lun->ooa_queue,
11029                                                      &io->io_hdr, ooa_links);
11030
11031                                         ctl_free_io(io);
11032                                 }
11033                         }
11034
11035                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11036                              io != NULL; io = next_io) {
11037
11038                                 next_io = (union ctl_io *)TAILQ_NEXT(
11039                                     &io->io_hdr, ooa_links);
11040
11041                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11042
11043                                         TAILQ_REMOVE(&lun->ooa_queue,
11044                                                 &io->io_hdr,
11045                                                 ooa_links);
11046
11047                                         ctl_free_io(io);
11048                                 }
11049                         }
11050                         ctl_check_blocked(lun);
11051                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11052                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11053
11054                         printf("FAILOVER: primary lun %d\n", lun_idx);
11055                         /*
11056                          * Abort all commands from the other SC.  We can't
11057                          * send status back for them now.  These should get
11058                          * cleaned up when they are completed or come out
11059                          * for a datamove operation.
11060                          */
11061                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11062                              io != NULL; io = next_io) {
11063                                 next_io = (union ctl_io *)TAILQ_NEXT(
11064                                         &io->io_hdr, ooa_links);
11065
11066                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11067                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11068                         }
11069                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11070                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11071
11072                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11073
11074                         lun->flags |= CTL_LUN_PRIMARY_SC;
11075
11076                         /*
11077                          * We send all I/O that was sent to this controller
11078                          * and redirected to the other side back with
11079                          * busy status, and have the initiator retry it.
11080                          * Figuring out how much data has been transferred,
11081                          * etc. and picking up where we left off would be 
11082                          * very tricky.
11083                          *
11084                          * XXX KDM need to remove I/O from the blocked
11085                          * queue as well!
11086                          */
11087                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11088                              &lun->ooa_queue); pending_io != NULL;
11089                              pending_io = next_io) {
11090
11091                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11092                                         &pending_io->io_hdr, ooa_links);
11093
11094                                 pending_io->io_hdr.flags &=
11095                                         ~CTL_FLAG_SENT_2OTHER_SC;
11096
11097                                 if (pending_io->io_hdr.flags &
11098                                     CTL_FLAG_IO_ACTIVE) {
11099                                         pending_io->io_hdr.flags |=
11100                                                 CTL_FLAG_FAILOVER;
11101                                 } else {
11102                                         ctl_set_busy(&pending_io->scsiio);
11103                                         ctl_done(pending_io);
11104                                 }
11105                         }
11106
11107                         /*
11108                          * Build Unit Attention
11109                          */
11110                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11111                                 lun->pending_sense[i].ua_pending |=
11112                                                      CTL_UA_ASYM_ACC_CHANGE;
11113                         }
11114                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11115                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11116                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11117                         /*
11118                          * if the first io on the OOA is not on the RtR queue
11119                          * add it.
11120                          */
11121                         lun->flags |= CTL_LUN_PRIMARY_SC;
11122
11123                         pending_io = (union ctl_io *)TAILQ_FIRST(
11124                             &lun->ooa_queue);
11125                         if (pending_io==NULL) {
11126                                 printf("Nothing on OOA queue\n");
11127                                 continue;
11128                         }
11129
11130                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11131                         if ((pending_io->io_hdr.flags &
11132                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11133                                 pending_io->io_hdr.flags |=
11134                                     CTL_FLAG_IS_WAS_ON_RTR;
11135                                 ctl_enqueue_rtr(pending_io);
11136                         }
11137 #if 0
11138                         else
11139                         {
11140                                 printf("Tag 0x%04x is running\n",
11141                                       pending_io->scsiio.tag_num);
11142                         }
11143 #endif
11144
11145                         next_io = (union ctl_io *)TAILQ_NEXT(
11146                             &pending_io->io_hdr, ooa_links);
11147                         for (pending_io=next_io; pending_io != NULL;
11148                              pending_io = next_io) {
11149                                 pending_io->io_hdr.flags &=
11150                                     ~CTL_FLAG_SENT_2OTHER_SC;
11151                                 next_io = (union ctl_io *)TAILQ_NEXT(
11152                                         &pending_io->io_hdr, ooa_links);
11153                                 if (pending_io->io_hdr.flags &
11154                                     CTL_FLAG_IS_WAS_ON_RTR) {
11155 #if 0
11156                                         printf("Tag 0x%04x is running\n",
11157                                                 pending_io->scsiio.tag_num);
11158 #endif
11159                                         continue;
11160                                 }
11161
11162                                 switch (ctl_check_ooa(lun, pending_io,
11163                                     (union ctl_io *)TAILQ_PREV(
11164                                     &pending_io->io_hdr, ctl_ooaq,
11165                                     ooa_links))) {
11166
11167                                 case CTL_ACTION_BLOCK:
11168                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11169                                                           &pending_io->io_hdr,
11170                                                           blocked_links);
11171                                         pending_io->io_hdr.flags |=
11172                                             CTL_FLAG_BLOCKED;
11173                                         break;
11174                                 case CTL_ACTION_PASS:
11175                                 case CTL_ACTION_SKIP:
11176                                         pending_io->io_hdr.flags |=
11177                                             CTL_FLAG_IS_WAS_ON_RTR;
11178                                         ctl_enqueue_rtr(pending_io);
11179                                         break;
11180                                 case CTL_ACTION_OVERLAP:
11181                                         ctl_set_overlapped_cmd(
11182                                             (struct ctl_scsiio *)pending_io);
11183                                         ctl_done(pending_io);
11184                                         break;
11185                                 case CTL_ACTION_OVERLAP_TAG:
11186                                         ctl_set_overlapped_tag(
11187                                             (struct ctl_scsiio *)pending_io,
11188                                             pending_io->scsiio.tag_num & 0xff);
11189                                         ctl_done(pending_io);
11190                                         break;
11191                                 case CTL_ACTION_ERROR:
11192                                 default:
11193                                         ctl_set_internal_failure(
11194                                                 (struct ctl_scsiio *)pending_io,
11195                                                 0,  // sks_valid
11196                                                 0); //retry count
11197                                         ctl_done(pending_io);
11198                                         break;
11199                                 }
11200                         }
11201
11202                         /*
11203                          * Build Unit Attention
11204                          */
11205                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11206                                 lun->pending_sense[i].ua_pending |=
11207                                                      CTL_UA_ASYM_ACC_CHANGE;
11208                         }
11209                 } else {
11210                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11211                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11212                 }
11213         }
11214         ctl_pause_rtr = 0;
11215         mtx_unlock(&ctl_softc->ctl_lock);
11216 }
11217
11218 static int
11219 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11220 {
11221         struct ctl_lun *lun;
11222         const struct ctl_cmd_entry *entry;
11223         uint32_t initidx, targ_lun;
11224         int retval;
11225
11226         retval = 0;
11227
11228         lun = NULL;
11229
11230         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11231         if ((targ_lun < CTL_MAX_LUNS)
11232          && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11233                 lun = ctl_softc->ctl_luns[targ_lun];
11234                 /*
11235                  * If the LUN is invalid, pretend that it doesn't exist.
11236                  * It will go away as soon as all pending I/O has been
11237                  * completed.
11238                  */
11239                 if (lun->flags & CTL_LUN_DISABLED) {
11240                         lun = NULL;
11241                 } else {
11242                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11243                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11244                                 lun->be_lun;
11245                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11246                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11247                         }
11248
11249                         /*
11250                          * Every I/O goes into the OOA queue for a
11251                          * particular LUN, and stays there until completion.
11252                          */
11253                         mtx_lock(&lun->lun_lock);
11254                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11255                             ooa_links);
11256                 }
11257         } else {
11258                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11259                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11260         }
11261
11262         /* Get command entry and return error if it is unsuppotyed. */
11263         entry = ctl_validate_command(ctsio);
11264         if (entry == NULL) {
11265                 if (lun)
11266                         mtx_unlock(&lun->lun_lock);
11267                 return (retval);
11268         }
11269
11270         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11271         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11272
11273         /*
11274          * Check to see whether we can send this command to LUNs that don't
11275          * exist.  This should pretty much only be the case for inquiry
11276          * and request sense.  Further checks, below, really require having
11277          * a LUN, so we can't really check the command anymore.  Just put
11278          * it on the rtr queue.
11279          */
11280         if (lun == NULL) {
11281                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11282                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11283                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11284                         return (retval);
11285                 }
11286
11287                 ctl_set_unsupported_lun(ctsio);
11288                 ctl_done((union ctl_io *)ctsio);
11289                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11290                 return (retval);
11291         } else {
11292                 /*
11293                  * Make sure we support this particular command on this LUN.
11294                  * e.g., we don't support writes to the control LUN.
11295                  */
11296                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11297                         mtx_unlock(&lun->lun_lock);
11298                         ctl_set_invalid_opcode(ctsio);
11299                         ctl_done((union ctl_io *)ctsio);
11300                         return (retval);
11301                 }
11302         }
11303
11304         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11305
11306         /*
11307          * If we've got a request sense, it'll clear the contingent
11308          * allegiance condition.  Otherwise, if we have a CA condition for
11309          * this initiator, clear it, because it sent down a command other
11310          * than request sense.
11311          */
11312         if ((ctsio->cdb[0] != REQUEST_SENSE)
11313          && (ctl_is_set(lun->have_ca, initidx)))
11314                 ctl_clear_mask(lun->have_ca, initidx);
11315
11316         /*
11317          * If the command has this flag set, it handles its own unit
11318          * attention reporting, we shouldn't do anything.  Otherwise we
11319          * check for any pending unit attentions, and send them back to the
11320          * initiator.  We only do this when a command initially comes in,
11321          * not when we pull it off the blocked queue.
11322          *
11323          * According to SAM-3, section 5.3.2, the order that things get
11324          * presented back to the host is basically unit attentions caused
11325          * by some sort of reset event, busy status, reservation conflicts
11326          * or task set full, and finally any other status.
11327          *
11328          * One issue here is that some of the unit attentions we report
11329          * don't fall into the "reset" category (e.g. "reported luns data
11330          * has changed").  So reporting it here, before the reservation
11331          * check, may be technically wrong.  I guess the only thing to do
11332          * would be to check for and report the reset events here, and then
11333          * check for the other unit attention types after we check for a
11334          * reservation conflict.
11335          *
11336          * XXX KDM need to fix this
11337          */
11338         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11339                 ctl_ua_type ua_type;
11340
11341                 ua_type = lun->pending_sense[initidx].ua_pending;
11342                 if (ua_type != CTL_UA_NONE) {
11343                         scsi_sense_data_type sense_format;
11344
11345                         if (lun != NULL)
11346                                 sense_format = (lun->flags &
11347                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11348                                     SSD_TYPE_FIXED;
11349                         else
11350                                 sense_format = SSD_TYPE_FIXED;
11351
11352                         ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11353                                                sense_format);
11354                         if (ua_type != CTL_UA_NONE) {
11355                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11356                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11357                                                        CTL_AUTOSENSE;
11358                                 ctsio->sense_len = SSD_FULL_SIZE;
11359                                 lun->pending_sense[initidx].ua_pending &=
11360                                         ~ua_type;
11361                                 mtx_unlock(&lun->lun_lock);
11362                                 ctl_done((union ctl_io *)ctsio);
11363                                 return (retval);
11364                         }
11365                 }
11366         }
11367
11368
11369         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11370                 mtx_unlock(&lun->lun_lock);
11371                 ctl_done((union ctl_io *)ctsio);
11372                 return (retval);
11373         }
11374
11375         /*
11376          * XXX CHD this is where we want to send IO to other side if
11377          * this LUN is secondary on this SC. We will need to make a copy
11378          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11379          * the copy we send as FROM_OTHER.
11380          * We also need to stuff the address of the original IO so we can
11381          * find it easily. Something similar will need be done on the other
11382          * side so when we are done we can find the copy.
11383          */
11384         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11385                 union ctl_ha_msg msg_info;
11386                 int isc_retval;
11387
11388                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11389
11390                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11391                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11392 #if 0
11393                 printf("1. ctsio %p\n", ctsio);
11394 #endif
11395                 msg_info.hdr.serializing_sc = NULL;
11396                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11397                 msg_info.scsi.tag_num = ctsio->tag_num;
11398                 msg_info.scsi.tag_type = ctsio->tag_type;
11399                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11400
11401                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11402
11403                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11404                     (void *)&msg_info, sizeof(msg_info), 0)) >
11405                     CTL_HA_STATUS_SUCCESS) {
11406                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11407                                isc_retval);
11408                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11409                 } else {
11410 #if 0
11411                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11412 #endif
11413                 }
11414
11415                 /*
11416                  * XXX KDM this I/O is off the incoming queue, but hasn't
11417                  * been inserted on any other queue.  We may need to come
11418                  * up with a holding queue while we wait for serialization
11419                  * so that we have an idea of what we're waiting for from
11420                  * the other side.
11421                  */
11422                 mtx_unlock(&lun->lun_lock);
11423                 return (retval);
11424         }
11425
11426         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11427                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11428                               ctl_ooaq, ooa_links))) {
11429         case CTL_ACTION_BLOCK:
11430                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11431                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11432                                   blocked_links);
11433                 mtx_unlock(&lun->lun_lock);
11434                 return (retval);
11435         case CTL_ACTION_PASS:
11436         case CTL_ACTION_SKIP:
11437                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11438                 mtx_unlock(&lun->lun_lock);
11439                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11440                 break;
11441         case CTL_ACTION_OVERLAP:
11442                 mtx_unlock(&lun->lun_lock);
11443                 ctl_set_overlapped_cmd(ctsio);
11444                 ctl_done((union ctl_io *)ctsio);
11445                 break;
11446         case CTL_ACTION_OVERLAP_TAG:
11447                 mtx_unlock(&lun->lun_lock);
11448                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11449                 ctl_done((union ctl_io *)ctsio);
11450                 break;
11451         case CTL_ACTION_ERROR:
11452         default:
11453                 mtx_unlock(&lun->lun_lock);
11454                 ctl_set_internal_failure(ctsio,
11455                                          /*sks_valid*/ 0,
11456                                          /*retry_count*/ 0);
11457                 ctl_done((union ctl_io *)ctsio);
11458                 break;
11459         }
11460         return (retval);
11461 }
11462
11463 const struct ctl_cmd_entry *
11464 ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11465 {
11466         const struct ctl_cmd_entry *entry;
11467         int service_action;
11468
11469         entry = &ctl_cmd_table[ctsio->cdb[0]];
11470         if (entry->flags & CTL_CMD_FLAG_SA5) {
11471                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11472                 entry = &((const struct ctl_cmd_entry *)
11473                     entry->execute)[service_action];
11474         }
11475         return (entry);
11476 }
11477
11478 const struct ctl_cmd_entry *
11479 ctl_validate_command(struct ctl_scsiio *ctsio)
11480 {
11481         const struct ctl_cmd_entry *entry;
11482         int i;
11483         uint8_t diff;
11484
11485         entry = ctl_get_cmd_entry(ctsio);
11486         if (entry->execute == NULL) {
11487                 ctl_set_invalid_opcode(ctsio);
11488                 ctl_done((union ctl_io *)ctsio);
11489                 return (NULL);
11490         }
11491         KASSERT(entry->length > 0,
11492             ("Not defined length for command 0x%02x/0x%02x",
11493              ctsio->cdb[0], ctsio->cdb[1]));
11494         for (i = 1; i < entry->length; i++) {
11495                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11496                 if (diff == 0)
11497                         continue;
11498                 ctl_set_invalid_field(ctsio,
11499                                       /*sks_valid*/ 1,
11500                                       /*command*/ 1,
11501                                       /*field*/ i,
11502                                       /*bit_valid*/ 1,
11503                                       /*bit*/ fls(diff) - 1);
11504                 ctl_done((union ctl_io *)ctsio);
11505                 return (NULL);
11506         }
11507         return (entry);
11508 }
11509
11510 static int
11511 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11512 {
11513
11514         switch (lun_type) {
11515         case T_PROCESSOR:
11516                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11517                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11518                         return (0);
11519                 break;
11520         case T_DIRECT:
11521                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11522                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11523                         return (0);
11524                 break;
11525         default:
11526                 return (0);
11527         }
11528         return (1);
11529 }
11530
11531 static int
11532 ctl_scsiio(struct ctl_scsiio *ctsio)
11533 {
11534         int retval;
11535         const struct ctl_cmd_entry *entry;
11536
11537         retval = CTL_RETVAL_COMPLETE;
11538
11539         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11540
11541         entry = ctl_get_cmd_entry(ctsio);
11542
11543         /*
11544          * If this I/O has been aborted, just send it straight to
11545          * ctl_done() without executing it.
11546          */
11547         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11548                 ctl_done((union ctl_io *)ctsio);
11549                 goto bailout;
11550         }
11551
11552         /*
11553          * All the checks should have been handled by ctl_scsiio_precheck().
11554          * We should be clear now to just execute the I/O.
11555          */
11556         retval = entry->execute(ctsio);
11557
11558 bailout:
11559         return (retval);
11560 }
11561
11562 /*
11563  * Since we only implement one target right now, a bus reset simply resets
11564  * our single target.
11565  */
11566 static int
11567 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11568 {
11569         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11570 }
11571
11572 static int
11573 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11574                  ctl_ua_type ua_type)
11575 {
11576         struct ctl_lun *lun;
11577         int retval;
11578
11579         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11580                 union ctl_ha_msg msg_info;
11581
11582                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11583                 msg_info.hdr.nexus = io->io_hdr.nexus;
11584                 if (ua_type==CTL_UA_TARG_RESET)
11585                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11586                 else
11587                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11588                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11589                 msg_info.hdr.original_sc = NULL;
11590                 msg_info.hdr.serializing_sc = NULL;
11591                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11592                     (void *)&msg_info, sizeof(msg_info), 0)) {
11593                 }
11594         }
11595         retval = 0;
11596
11597         mtx_lock(&ctl_softc->ctl_lock);
11598         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11599                 retval += ctl_lun_reset(lun, io, ua_type);
11600         mtx_unlock(&ctl_softc->ctl_lock);
11601
11602         return (retval);
11603 }
11604
11605 /*
11606  * The LUN should always be set.  The I/O is optional, and is used to
11607  * distinguish between I/Os sent by this initiator, and by other
11608  * initiators.  We set unit attention for initiators other than this one.
11609  * SAM-3 is vague on this point.  It does say that a unit attention should
11610  * be established for other initiators when a LUN is reset (see section
11611  * 5.7.3), but it doesn't specifically say that the unit attention should
11612  * be established for this particular initiator when a LUN is reset.  Here
11613  * is the relevant text, from SAM-3 rev 8:
11614  *
11615  * 5.7.2 When a SCSI initiator port aborts its own tasks
11616  *
11617  * When a SCSI initiator port causes its own task(s) to be aborted, no
11618  * notification that the task(s) have been aborted shall be returned to
11619  * the SCSI initiator port other than the completion response for the
11620  * command or task management function action that caused the task(s) to
11621  * be aborted and notification(s) associated with related effects of the
11622  * action (e.g., a reset unit attention condition).
11623  *
11624  * XXX KDM for now, we're setting unit attention for all initiators.
11625  */
11626 static int
11627 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11628 {
11629         union ctl_io *xio;
11630 #if 0
11631         uint32_t initindex;
11632 #endif
11633         int i;
11634
11635         mtx_lock(&lun->lun_lock);
11636         /*
11637          * Run through the OOA queue and abort each I/O.
11638          */
11639 #if 0
11640         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11641 #endif
11642         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11643              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11644                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
11645         }
11646
11647         /*
11648          * This version sets unit attention for every
11649          */
11650 #if 0
11651         initindex = ctl_get_initindex(&io->io_hdr.nexus);
11652         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11653                 if (initindex == i)
11654                         continue;
11655                 lun->pending_sense[i].ua_pending |= ua_type;
11656         }
11657 #endif
11658
11659         /*
11660          * A reset (any kind, really) clears reservations established with
11661          * RESERVE/RELEASE.  It does not clear reservations established
11662          * with PERSISTENT RESERVE OUT, but we don't support that at the
11663          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11664          * reservations made with the RESERVE/RELEASE commands, because
11665          * those commands are obsolete in SPC-3.
11666          */
11667         lun->flags &= ~CTL_LUN_RESERVED;
11668
11669         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11670                 ctl_clear_mask(lun->have_ca, i);
11671                 lun->pending_sense[i].ua_pending |= ua_type;
11672         }
11673         mtx_lock(&lun->lun_lock);
11674
11675         return (0);
11676 }
11677
11678 static int
11679 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11680     int other_sc)
11681 {
11682         union ctl_io *xio;
11683         int found;
11684
11685         mtx_assert(&lun->lun_lock, MA_OWNED);
11686
11687         /*
11688          * Run through the OOA queue and attempt to find the given I/O.
11689          * The target port, initiator ID, tag type and tag number have to
11690          * match the values that we got from the initiator.  If we have an
11691          * untagged command to abort, simply abort the first untagged command
11692          * we come to.  We only allow one untagged command at a time of course.
11693          */
11694         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11695              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11696
11697                 if ((targ_port == xio->io_hdr.nexus.targ_port) &&
11698                     (init_id == xio->io_hdr.nexus.initid.id)) {
11699                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11700                         found = 1;
11701                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11702                                 union ctl_ha_msg msg_info;
11703
11704                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11705                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11706                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11707                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11708                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11709                                 msg_info.hdr.original_sc = NULL;
11710                                 msg_info.hdr.serializing_sc = NULL;
11711                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11712                                     (void *)&msg_info, sizeof(msg_info), 0);
11713                         }
11714                 }
11715         }
11716         return (found);
11717 }
11718
11719 static int
11720 ctl_abort_task_set(union ctl_io *io)
11721 {
11722         struct ctl_softc *softc = control_softc;
11723         struct ctl_lun *lun;
11724         uint32_t targ_lun;
11725
11726         /*
11727          * Look up the LUN.
11728          */
11729         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11730         mtx_lock(&softc->ctl_lock);
11731         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11732                 lun = softc->ctl_luns[targ_lun];
11733         else {
11734                 mtx_unlock(&softc->ctl_lock);
11735                 return (1);
11736         }
11737
11738         mtx_lock(&lun->lun_lock);
11739         mtx_unlock(&softc->ctl_lock);
11740         ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11741             io->io_hdr.nexus.initid.id,
11742             (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11743         mtx_unlock(&lun->lun_lock);
11744         return (0);
11745 }
11746
11747 static int
11748 ctl_i_t_nexus_reset(union ctl_io *io)
11749 {
11750         struct ctl_softc *softc = control_softc;
11751         struct ctl_lun *lun;
11752         uint32_t initindex;
11753
11754         initindex = ctl_get_initindex(&io->io_hdr.nexus);
11755         mtx_lock(&softc->ctl_lock);
11756         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11757                 mtx_lock(&lun->lun_lock);
11758                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11759                     io->io_hdr.nexus.initid.id,
11760                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11761                 ctl_clear_mask(lun->have_ca, initindex);
11762                 lun->pending_sense[initindex].ua_pending |= CTL_UA_I_T_NEXUS_LOSS;
11763                 mtx_unlock(&lun->lun_lock);
11764         }
11765         mtx_unlock(&softc->ctl_lock);
11766         return (0);
11767 }
11768
11769 static int
11770 ctl_abort_task(union ctl_io *io)
11771 {
11772         union ctl_io *xio;
11773         struct ctl_lun *lun;
11774         struct ctl_softc *ctl_softc;
11775 #if 0
11776         struct sbuf sb;
11777         char printbuf[128];
11778 #endif
11779         int found;
11780         uint32_t targ_lun;
11781
11782         ctl_softc = control_softc;
11783         found = 0;
11784
11785         /*
11786          * Look up the LUN.
11787          */
11788         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11789         mtx_lock(&ctl_softc->ctl_lock);
11790         if ((targ_lun < CTL_MAX_LUNS)
11791          && (ctl_softc->ctl_luns[targ_lun] != NULL))
11792                 lun = ctl_softc->ctl_luns[targ_lun];
11793         else {
11794                 mtx_unlock(&ctl_softc->ctl_lock);
11795                 goto bailout;
11796         }
11797
11798 #if 0
11799         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11800                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11801 #endif
11802
11803         mtx_lock(&lun->lun_lock);
11804         mtx_unlock(&ctl_softc->ctl_lock);
11805         /*
11806          * Run through the OOA queue and attempt to find the given I/O.
11807          * The target port, initiator ID, tag type and tag number have to
11808          * match the values that we got from the initiator.  If we have an
11809          * untagged command to abort, simply abort the first untagged command
11810          * we come to.  We only allow one untagged command at a time of course.
11811          */
11812 #if 0
11813         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11814 #endif
11815         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11816              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11817 #if 0
11818                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11819
11820                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11821                             lun->lun, xio->scsiio.tag_num,
11822                             xio->scsiio.tag_type,
11823                             (xio->io_hdr.blocked_links.tqe_prev
11824                             == NULL) ? "" : " BLOCKED",
11825                             (xio->io_hdr.flags &
11826                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11827                             (xio->io_hdr.flags &
11828                             CTL_FLAG_ABORT) ? " ABORT" : "",
11829                             (xio->io_hdr.flags &
11830                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11831                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11832                 sbuf_finish(&sb);
11833                 printf("%s\n", sbuf_data(&sb));
11834 #endif
11835
11836                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
11837                  && (xio->io_hdr.nexus.initid.id ==
11838                      io->io_hdr.nexus.initid.id)) {
11839                         /*
11840                          * If the abort says that the task is untagged, the
11841                          * task in the queue must be untagged.  Otherwise,
11842                          * we just check to see whether the tag numbers
11843                          * match.  This is because the QLogic firmware
11844                          * doesn't pass back the tag type in an abort
11845                          * request.
11846                          */
11847 #if 0
11848                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11849                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11850                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11851 #endif
11852                         /*
11853                          * XXX KDM we've got problems with FC, because it
11854                          * doesn't send down a tag type with aborts.  So we
11855                          * can only really go by the tag number...
11856                          * This may cause problems with parallel SCSI.
11857                          * Need to figure that out!!
11858                          */
11859                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
11860                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
11861                                 found = 1;
11862                                 if ((io->io_hdr.flags &
11863                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
11864                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11865                                         union ctl_ha_msg msg_info;
11866
11867                                         io->io_hdr.flags |=
11868                                                         CTL_FLAG_SENT_2OTHER_SC;
11869                                         msg_info.hdr.nexus = io->io_hdr.nexus;
11870                                         msg_info.task.task_action =
11871                                                 CTL_TASK_ABORT_TASK;
11872                                         msg_info.task.tag_num =
11873                                                 io->taskio.tag_num;
11874                                         msg_info.task.tag_type =
11875                                                 io->taskio.tag_type;
11876                                         msg_info.hdr.msg_type =
11877                                                 CTL_MSG_MANAGE_TASKS;
11878                                         msg_info.hdr.original_sc = NULL;
11879                                         msg_info.hdr.serializing_sc = NULL;
11880 #if 0
11881                                         printf("Sent Abort to other side\n");
11882 #endif
11883                                         if (CTL_HA_STATUS_SUCCESS !=
11884                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11885                                                 (void *)&msg_info,
11886                                                 sizeof(msg_info), 0)) {
11887                                         }
11888                                 }
11889 #if 0
11890                                 printf("ctl_abort_task: found I/O to abort\n");
11891 #endif
11892                                 break;
11893                         }
11894                 }
11895         }
11896         mtx_unlock(&lun->lun_lock);
11897
11898 bailout:
11899
11900         if (found == 0) {
11901                 /*
11902                  * This isn't really an error.  It's entirely possible for
11903                  * the abort and command completion to cross on the wire.
11904                  * This is more of an informative/diagnostic error.
11905                  */
11906 #if 0
11907                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11908                        "%d:%d:%d:%d tag %d type %d\n",
11909                        io->io_hdr.nexus.initid.id,
11910                        io->io_hdr.nexus.targ_port,
11911                        io->io_hdr.nexus.targ_target.id,
11912                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11913                        io->taskio.tag_type);
11914 #endif
11915                 return (1);
11916         } else
11917                 return (0);
11918 }
11919
11920 /*
11921  * This routine cannot block!  It must be callable from an interrupt
11922  * handler as well as from the work thread.
11923  */
11924 static void
11925 ctl_run_task(union ctl_io *io)
11926 {
11927         struct ctl_softc *ctl_softc;
11928         int retval;
11929         const char *task_desc;
11930
11931         CTL_DEBUG_PRINT(("ctl_run_task\n"));
11932
11933         ctl_softc = control_softc;
11934         retval = 0;
11935
11936         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11937             ("ctl_run_task: Unextected io_type %d\n",
11938              io->io_hdr.io_type));
11939
11940         task_desc = ctl_scsi_task_string(&io->taskio);
11941         if (task_desc != NULL) {
11942 #ifdef NEEDTOPORT
11943                 csevent_log(CSC_CTL | CSC_SHELF_SW |
11944                             CTL_TASK_REPORT,
11945                             csevent_LogType_Trace,
11946                             csevent_Severity_Information,
11947                             csevent_AlertLevel_Green,
11948                             csevent_FRU_Firmware,
11949                             csevent_FRU_Unknown,
11950                             "CTL: received task: %s",task_desc);
11951 #endif
11952         } else {
11953 #ifdef NEEDTOPORT
11954                 csevent_log(CSC_CTL | CSC_SHELF_SW |
11955                             CTL_TASK_REPORT,
11956                             csevent_LogType_Trace,
11957                             csevent_Severity_Information,
11958                             csevent_AlertLevel_Green,
11959                             csevent_FRU_Firmware,
11960                             csevent_FRU_Unknown,
11961                             "CTL: received unknown task "
11962                             "type: %d (%#x)",
11963                             io->taskio.task_action,
11964                             io->taskio.task_action);
11965 #endif
11966         }
11967         switch (io->taskio.task_action) {
11968         case CTL_TASK_ABORT_TASK:
11969                 retval = ctl_abort_task(io);
11970                 break;
11971         case CTL_TASK_ABORT_TASK_SET:
11972                 retval = ctl_abort_task_set(io);
11973                 break;
11974         case CTL_TASK_CLEAR_ACA:
11975                 break;
11976         case CTL_TASK_CLEAR_TASK_SET:
11977                 break;
11978         case CTL_TASK_I_T_NEXUS_RESET:
11979                 retval = ctl_i_t_nexus_reset(io);
11980                 break;
11981         case CTL_TASK_LUN_RESET: {
11982                 struct ctl_lun *lun;
11983                 uint32_t targ_lun;
11984                 int retval;
11985
11986                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11987                 mtx_lock(&ctl_softc->ctl_lock);
11988                 if ((targ_lun < CTL_MAX_LUNS)
11989                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
11990                         lun = ctl_softc->ctl_luns[targ_lun];
11991                 else {
11992                         mtx_unlock(&ctl_softc->ctl_lock);
11993                         retval = 1;
11994                         break;
11995                 }
11996
11997                 if (!(io->io_hdr.flags &
11998                     CTL_FLAG_FROM_OTHER_SC)) {
11999                         union ctl_ha_msg msg_info;
12000
12001                         io->io_hdr.flags |=
12002                                 CTL_FLAG_SENT_2OTHER_SC;
12003                         msg_info.hdr.msg_type =
12004                                 CTL_MSG_MANAGE_TASKS;
12005                         msg_info.hdr.nexus = io->io_hdr.nexus;
12006                         msg_info.task.task_action =
12007                                 CTL_TASK_LUN_RESET;
12008                         msg_info.hdr.original_sc = NULL;
12009                         msg_info.hdr.serializing_sc = NULL;
12010                         if (CTL_HA_STATUS_SUCCESS !=
12011                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12012                             (void *)&msg_info,
12013                             sizeof(msg_info), 0)) {
12014                         }
12015                 }
12016
12017                 retval = ctl_lun_reset(lun, io,
12018                                        CTL_UA_LUN_RESET);
12019                 mtx_unlock(&ctl_softc->ctl_lock);
12020                 break;
12021         }
12022         case CTL_TASK_TARGET_RESET:
12023                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12024                 break;
12025         case CTL_TASK_BUS_RESET:
12026                 retval = ctl_bus_reset(ctl_softc, io);
12027                 break;
12028         case CTL_TASK_PORT_LOGIN:
12029                 break;
12030         case CTL_TASK_PORT_LOGOUT:
12031                 break;
12032         default:
12033                 printf("ctl_run_task: got unknown task management event %d\n",
12034                        io->taskio.task_action);
12035                 break;
12036         }
12037         if (retval == 0)
12038                 io->io_hdr.status = CTL_SUCCESS;
12039         else
12040                 io->io_hdr.status = CTL_ERROR;
12041
12042         /*
12043          * This will queue this I/O to the done queue, but the
12044          * work thread won't be able to process it until we
12045          * return and the lock is released.
12046          */
12047         ctl_done(io);
12048 }
12049
12050 /*
12051  * For HA operation.  Handle commands that come in from the other
12052  * controller.
12053  */
12054 static void
12055 ctl_handle_isc(union ctl_io *io)
12056 {
12057         int free_io;
12058         struct ctl_lun *lun;
12059         struct ctl_softc *ctl_softc;
12060         uint32_t targ_lun;
12061
12062         ctl_softc = control_softc;
12063
12064         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12065         lun = ctl_softc->ctl_luns[targ_lun];
12066
12067         switch (io->io_hdr.msg_type) {
12068         case CTL_MSG_SERIALIZE:
12069                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12070                 break;
12071         case CTL_MSG_R2R: {
12072                 const struct ctl_cmd_entry *entry;
12073
12074                 /*
12075                  * This is only used in SER_ONLY mode.
12076                  */
12077                 free_io = 0;
12078                 entry = ctl_get_cmd_entry(&io->scsiio);
12079                 mtx_lock(&lun->lun_lock);
12080                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12081                     entry, (struct ctl_scsiio *)io) != 0) {
12082                         mtx_unlock(&lun->lun_lock);
12083                         ctl_done(io);
12084                         break;
12085                 }
12086                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12087                 mtx_unlock(&lun->lun_lock);
12088                 ctl_enqueue_rtr(io);
12089                 break;
12090         }
12091         case CTL_MSG_FINISH_IO:
12092                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12093                         free_io = 0;
12094                         ctl_done(io);
12095                 } else {
12096                         free_io = 1;
12097                         mtx_lock(&lun->lun_lock);
12098                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12099                                      ooa_links);
12100                         ctl_check_blocked(lun);
12101                         mtx_unlock(&lun->lun_lock);
12102                 }
12103                 break;
12104         case CTL_MSG_PERS_ACTION:
12105                 ctl_hndl_per_res_out_on_other_sc(
12106                         (union ctl_ha_msg *)&io->presio.pr_msg);
12107                 free_io = 1;
12108                 break;
12109         case CTL_MSG_BAD_JUJU:
12110                 free_io = 0;
12111                 ctl_done(io);
12112                 break;
12113         case CTL_MSG_DATAMOVE:
12114                 /* Only used in XFER mode */
12115                 free_io = 0;
12116                 ctl_datamove_remote(io);
12117                 break;
12118         case CTL_MSG_DATAMOVE_DONE:
12119                 /* Only used in XFER mode */
12120                 free_io = 0;
12121                 io->scsiio.be_move_done(io);
12122                 break;
12123         default:
12124                 free_io = 1;
12125                 printf("%s: Invalid message type %d\n",
12126                        __func__, io->io_hdr.msg_type);
12127                 break;
12128         }
12129         if (free_io)
12130                 ctl_free_io(io);
12131
12132 }
12133
12134
12135 /*
12136  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12137  * there is no match.
12138  */
12139 static ctl_lun_error_pattern
12140 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12141 {
12142         const struct ctl_cmd_entry *entry;
12143         ctl_lun_error_pattern filtered_pattern, pattern;
12144
12145         pattern = desc->error_pattern;
12146
12147         /*
12148          * XXX KDM we need more data passed into this function to match a
12149          * custom pattern, and we actually need to implement custom pattern
12150          * matching.
12151          */
12152         if (pattern & CTL_LUN_PAT_CMD)
12153                 return (CTL_LUN_PAT_CMD);
12154
12155         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12156                 return (CTL_LUN_PAT_ANY);
12157
12158         entry = ctl_get_cmd_entry(ctsio);
12159
12160         filtered_pattern = entry->pattern & pattern;
12161
12162         /*
12163          * If the user requested specific flags in the pattern (e.g.
12164          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12165          * flags.
12166          *
12167          * If the user did not specify any flags, it doesn't matter whether
12168          * or not the command supports the flags.
12169          */
12170         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12171              (pattern & ~CTL_LUN_PAT_MASK))
12172                 return (CTL_LUN_PAT_NONE);
12173
12174         /*
12175          * If the user asked for a range check, see if the requested LBA
12176          * range overlaps with this command's LBA range.
12177          */
12178         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12179                 uint64_t lba1;
12180                 uint32_t len1;
12181                 ctl_action action;
12182                 int retval;
12183
12184                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12185                 if (retval != 0)
12186                         return (CTL_LUN_PAT_NONE);
12187
12188                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12189                                               desc->lba_range.len);
12190                 /*
12191                  * A "pass" means that the LBA ranges don't overlap, so
12192                  * this doesn't match the user's range criteria.
12193                  */
12194                 if (action == CTL_ACTION_PASS)
12195                         return (CTL_LUN_PAT_NONE);
12196         }
12197
12198         return (filtered_pattern);
12199 }
12200
12201 static void
12202 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12203 {
12204         struct ctl_error_desc *desc, *desc2;
12205
12206         mtx_assert(&lun->lun_lock, MA_OWNED);
12207
12208         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12209                 ctl_lun_error_pattern pattern;
12210                 /*
12211                  * Check to see whether this particular command matches
12212                  * the pattern in the descriptor.
12213                  */
12214                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12215                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12216                         continue;
12217
12218                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12219                 case CTL_LUN_INJ_ABORTED:
12220                         ctl_set_aborted(&io->scsiio);
12221                         break;
12222                 case CTL_LUN_INJ_MEDIUM_ERR:
12223                         ctl_set_medium_error(&io->scsiio);
12224                         break;
12225                 case CTL_LUN_INJ_UA:
12226                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12227                          * OCCURRED */
12228                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12229                         break;
12230                 case CTL_LUN_INJ_CUSTOM:
12231                         /*
12232                          * We're assuming the user knows what he is doing.
12233                          * Just copy the sense information without doing
12234                          * checks.
12235                          */
12236                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12237                               ctl_min(sizeof(desc->custom_sense),
12238                                       sizeof(io->scsiio.sense_data)));
12239                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12240                         io->scsiio.sense_len = SSD_FULL_SIZE;
12241                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12242                         break;
12243                 case CTL_LUN_INJ_NONE:
12244                 default:
12245                         /*
12246                          * If this is an error injection type we don't know
12247                          * about, clear the continuous flag (if it is set)
12248                          * so it will get deleted below.
12249                          */
12250                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12251                         break;
12252                 }
12253                 /*
12254                  * By default, each error injection action is a one-shot
12255                  */
12256                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12257                         continue;
12258
12259                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12260
12261                 free(desc, M_CTL);
12262         }
12263 }
12264
12265 #ifdef CTL_IO_DELAY
12266 static void
12267 ctl_datamove_timer_wakeup(void *arg)
12268 {
12269         union ctl_io *io;
12270
12271         io = (union ctl_io *)arg;
12272
12273         ctl_datamove(io);
12274 }
12275 #endif /* CTL_IO_DELAY */
12276
12277 void
12278 ctl_datamove(union ctl_io *io)
12279 {
12280         void (*fe_datamove)(union ctl_io *io);
12281
12282         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12283
12284         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12285
12286 #ifdef CTL_TIME_IO
12287         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12288                 char str[256];
12289                 char path_str[64];
12290                 struct sbuf sb;
12291
12292                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12293                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12294
12295                 sbuf_cat(&sb, path_str);
12296                 switch (io->io_hdr.io_type) {
12297                 case CTL_IO_SCSI:
12298                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12299                         sbuf_printf(&sb, "\n");
12300                         sbuf_cat(&sb, path_str);
12301                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12302                                     io->scsiio.tag_num, io->scsiio.tag_type);
12303                         break;
12304                 case CTL_IO_TASK:
12305                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12306                                     "Tag Type: %d\n", io->taskio.task_action,
12307                                     io->taskio.tag_num, io->taskio.tag_type);
12308                         break;
12309                 default:
12310                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12311                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12312                         break;
12313                 }
12314                 sbuf_cat(&sb, path_str);
12315                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12316                             (intmax_t)time_uptime - io->io_hdr.start_time);
12317                 sbuf_finish(&sb);
12318                 printf("%s", sbuf_data(&sb));
12319         }
12320 #endif /* CTL_TIME_IO */
12321
12322 #ifdef CTL_IO_DELAY
12323         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12324                 struct ctl_lun *lun;
12325
12326                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12327
12328                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12329         } else {
12330                 struct ctl_lun *lun;
12331
12332                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12333                 if ((lun != NULL)
12334                  && (lun->delay_info.datamove_delay > 0)) {
12335                         struct callout *callout;
12336
12337                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12338                         callout_init(callout, /*mpsafe*/ 1);
12339                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12340                         callout_reset(callout,
12341                                       lun->delay_info.datamove_delay * hz,
12342                                       ctl_datamove_timer_wakeup, io);
12343                         if (lun->delay_info.datamove_type ==
12344                             CTL_DELAY_TYPE_ONESHOT)
12345                                 lun->delay_info.datamove_delay = 0;
12346                         return;
12347                 }
12348         }
12349 #endif
12350
12351         /*
12352          * This command has been aborted.  Set the port status, so we fail
12353          * the data move.
12354          */
12355         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12356                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12357                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12358                        io->io_hdr.nexus.targ_port,
12359                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12360                        io->io_hdr.nexus.targ_lun);
12361                 io->io_hdr.status = CTL_CMD_ABORTED;
12362                 io->io_hdr.port_status = 31337;
12363                 /*
12364                  * Note that the backend, in this case, will get the
12365                  * callback in its context.  In other cases it may get
12366                  * called in the frontend's interrupt thread context.
12367                  */
12368                 io->scsiio.be_move_done(io);
12369                 return;
12370         }
12371
12372         /*
12373          * If we're in XFER mode and this I/O is from the other shelf
12374          * controller, we need to send the DMA to the other side to
12375          * actually transfer the data to/from the host.  In serialize only
12376          * mode the transfer happens below CTL and ctl_datamove() is only
12377          * called on the machine that originally received the I/O.
12378          */
12379         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12380          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12381                 union ctl_ha_msg msg;
12382                 uint32_t sg_entries_sent;
12383                 int do_sg_copy;
12384                 int i;
12385
12386                 memset(&msg, 0, sizeof(msg));
12387                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12388                 msg.hdr.original_sc = io->io_hdr.original_sc;
12389                 msg.hdr.serializing_sc = io;
12390                 msg.hdr.nexus = io->io_hdr.nexus;
12391                 msg.dt.flags = io->io_hdr.flags;
12392                 /*
12393                  * We convert everything into a S/G list here.  We can't
12394                  * pass by reference, only by value between controllers.
12395                  * So we can't pass a pointer to the S/G list, only as many
12396                  * S/G entries as we can fit in here.  If it's possible for
12397                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12398                  * then we need to break this up into multiple transfers.
12399                  */
12400                 if (io->scsiio.kern_sg_entries == 0) {
12401                         msg.dt.kern_sg_entries = 1;
12402                         /*
12403                          * If this is in cached memory, flush the cache
12404                          * before we send the DMA request to the other
12405                          * controller.  We want to do this in either the
12406                          * read or the write case.  The read case is
12407                          * straightforward.  In the write case, we want to
12408                          * make sure nothing is in the local cache that
12409                          * could overwrite the DMAed data.
12410                          */
12411                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12412                                 /*
12413                                  * XXX KDM use bus_dmamap_sync() here.
12414                                  */
12415                         }
12416
12417                         /*
12418                          * Convert to a physical address if this is a
12419                          * virtual address.
12420                          */
12421                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12422                                 msg.dt.sg_list[0].addr =
12423                                         io->scsiio.kern_data_ptr;
12424                         } else {
12425                                 /*
12426                                  * XXX KDM use busdma here!
12427                                  */
12428 #if 0
12429                                 msg.dt.sg_list[0].addr = (void *)
12430                                         vtophys(io->scsiio.kern_data_ptr);
12431 #endif
12432                         }
12433
12434                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12435                         do_sg_copy = 0;
12436                 } else {
12437                         struct ctl_sg_entry *sgl;
12438
12439                         do_sg_copy = 1;
12440                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12441                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12442                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12443                                 /*
12444                                  * XXX KDM use bus_dmamap_sync() here.
12445                                  */
12446                         }
12447                 }
12448
12449                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12450                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12451                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12452                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12453                 msg.dt.sg_sequence = 0;
12454
12455                 /*
12456                  * Loop until we've sent all of the S/G entries.  On the
12457                  * other end, we'll recompose these S/G entries into one
12458                  * contiguous list before passing it to the
12459                  */
12460                 for (sg_entries_sent = 0; sg_entries_sent <
12461                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12462                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12463                                 sizeof(msg.dt.sg_list[0])),
12464                                 msg.dt.kern_sg_entries - sg_entries_sent);
12465
12466                         if (do_sg_copy != 0) {
12467                                 struct ctl_sg_entry *sgl;
12468                                 int j;
12469
12470                                 sgl = (struct ctl_sg_entry *)
12471                                         io->scsiio.kern_data_ptr;
12472                                 /*
12473                                  * If this is in cached memory, flush the cache
12474                                  * before we send the DMA request to the other
12475                                  * controller.  We want to do this in either
12476                                  * the * read or the write case.  The read
12477                                  * case is straightforward.  In the write
12478                                  * case, we want to make sure nothing is
12479                                  * in the local cache that could overwrite
12480                                  * the DMAed data.
12481                                  */
12482
12483                                 for (i = sg_entries_sent, j = 0;
12484                                      i < msg.dt.cur_sg_entries; i++, j++) {
12485                                         if ((io->io_hdr.flags &
12486                                              CTL_FLAG_NO_DATASYNC) == 0) {
12487                                                 /*
12488                                                  * XXX KDM use bus_dmamap_sync()
12489                                                  */
12490                                         }
12491                                         if ((io->io_hdr.flags &
12492                                              CTL_FLAG_BUS_ADDR) == 0) {
12493                                                 /*
12494                                                  * XXX KDM use busdma.
12495                                                  */
12496 #if 0
12497                                                 msg.dt.sg_list[j].addr =(void *)
12498                                                        vtophys(sgl[i].addr);
12499 #endif
12500                                         } else {
12501                                                 msg.dt.sg_list[j].addr =
12502                                                         sgl[i].addr;
12503                                         }
12504                                         msg.dt.sg_list[j].len = sgl[i].len;
12505                                 }
12506                         }
12507
12508                         sg_entries_sent += msg.dt.cur_sg_entries;
12509                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12510                                 msg.dt.sg_last = 1;
12511                         else
12512                                 msg.dt.sg_last = 0;
12513
12514                         /*
12515                          * XXX KDM drop and reacquire the lock here?
12516                          */
12517                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12518                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12519                                 /*
12520                                  * XXX do something here.
12521                                  */
12522                         }
12523
12524                         msg.dt.sent_sg_entries = sg_entries_sent;
12525                 }
12526                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12527                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12528                         ctl_failover_io(io, /*have_lock*/ 0);
12529
12530         } else {
12531
12532                 /*
12533                  * Lookup the fe_datamove() function for this particular
12534                  * front end.
12535                  */
12536                 fe_datamove =
12537                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12538
12539                 fe_datamove(io);
12540         }
12541 }
12542
12543 static void
12544 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12545 {
12546         union ctl_ha_msg msg;
12547         int isc_status;
12548
12549         memset(&msg, 0, sizeof(msg));
12550
12551         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12552         msg.hdr.original_sc = io;
12553         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12554         msg.hdr.nexus = io->io_hdr.nexus;
12555         msg.hdr.status = io->io_hdr.status;
12556         msg.scsi.tag_num = io->scsiio.tag_num;
12557         msg.scsi.tag_type = io->scsiio.tag_type;
12558         msg.scsi.scsi_status = io->scsiio.scsi_status;
12559         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12560                sizeof(io->scsiio.sense_data));
12561         msg.scsi.sense_len = io->scsiio.sense_len;
12562         msg.scsi.sense_residual = io->scsiio.sense_residual;
12563         msg.scsi.fetd_status = io->io_hdr.port_status;
12564         msg.scsi.residual = io->scsiio.residual;
12565         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12566
12567         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12568                 ctl_failover_io(io, /*have_lock*/ have_lock);
12569                 return;
12570         }
12571
12572         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12573         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12574                 /* XXX do something if this fails */
12575         }
12576
12577 }
12578
12579 /*
12580  * The DMA to the remote side is done, now we need to tell the other side
12581  * we're done so it can continue with its data movement.
12582  */
12583 static void
12584 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12585 {
12586         union ctl_io *io;
12587
12588         io = rq->context;
12589
12590         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12591                 printf("%s: ISC DMA write failed with error %d", __func__,
12592                        rq->ret);
12593                 ctl_set_internal_failure(&io->scsiio,
12594                                          /*sks_valid*/ 1,
12595                                          /*retry_count*/ rq->ret);
12596         }
12597
12598         ctl_dt_req_free(rq);
12599
12600         /*
12601          * In this case, we had to malloc the memory locally.  Free it.
12602          */
12603         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12604                 int i;
12605                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12606                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12607         }
12608         /*
12609          * The data is in local and remote memory, so now we need to send
12610          * status (good or back) back to the other side.
12611          */
12612         ctl_send_datamove_done(io, /*have_lock*/ 0);
12613 }
12614
12615 /*
12616  * We've moved the data from the host/controller into local memory.  Now we
12617  * need to push it over to the remote controller's memory.
12618  */
12619 static int
12620 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12621 {
12622         int retval;
12623
12624         retval = 0;
12625
12626         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12627                                           ctl_datamove_remote_write_cb);
12628
12629         return (retval);
12630 }
12631
12632 static void
12633 ctl_datamove_remote_write(union ctl_io *io)
12634 {
12635         int retval;
12636         void (*fe_datamove)(union ctl_io *io);
12637
12638         /*
12639          * - Get the data from the host/HBA into local memory.
12640          * - DMA memory from the local controller to the remote controller.
12641          * - Send status back to the remote controller.
12642          */
12643
12644         retval = ctl_datamove_remote_sgl_setup(io);
12645         if (retval != 0)
12646                 return;
12647
12648         /* Switch the pointer over so the FETD knows what to do */
12649         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12650
12651         /*
12652          * Use a custom move done callback, since we need to send completion
12653          * back to the other controller, not to the backend on this side.
12654          */
12655         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12656
12657         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12658
12659         fe_datamove(io);
12660
12661         return;
12662
12663 }
12664
12665 static int
12666 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12667 {
12668 #if 0
12669         char str[256];
12670         char path_str[64];
12671         struct sbuf sb;
12672 #endif
12673
12674         /*
12675          * In this case, we had to malloc the memory locally.  Free it.
12676          */
12677         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12678                 int i;
12679                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12680                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12681         }
12682
12683 #if 0
12684         scsi_path_string(io, path_str, sizeof(path_str));
12685         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12686         sbuf_cat(&sb, path_str);
12687         scsi_command_string(&io->scsiio, NULL, &sb);
12688         sbuf_printf(&sb, "\n");
12689         sbuf_cat(&sb, path_str);
12690         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12691                     io->scsiio.tag_num, io->scsiio.tag_type);
12692         sbuf_cat(&sb, path_str);
12693         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12694                     io->io_hdr.flags, io->io_hdr.status);
12695         sbuf_finish(&sb);
12696         printk("%s", sbuf_data(&sb));
12697 #endif
12698
12699
12700         /*
12701          * The read is done, now we need to send status (good or bad) back
12702          * to the other side.
12703          */
12704         ctl_send_datamove_done(io, /*have_lock*/ 0);
12705
12706         return (0);
12707 }
12708
12709 static void
12710 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12711 {
12712         union ctl_io *io;
12713         void (*fe_datamove)(union ctl_io *io);
12714
12715         io = rq->context;
12716
12717         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12718                 printf("%s: ISC DMA read failed with error %d", __func__,
12719                        rq->ret);
12720                 ctl_set_internal_failure(&io->scsiio,
12721                                          /*sks_valid*/ 1,
12722                                          /*retry_count*/ rq->ret);
12723         }
12724
12725         ctl_dt_req_free(rq);
12726
12727         /* Switch the pointer over so the FETD knows what to do */
12728         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12729
12730         /*
12731          * Use a custom move done callback, since we need to send completion
12732          * back to the other controller, not to the backend on this side.
12733          */
12734         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12735
12736         /* XXX KDM add checks like the ones in ctl_datamove? */
12737
12738         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12739
12740         fe_datamove(io);
12741 }
12742
12743 static int
12744 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12745 {
12746         struct ctl_sg_entry *local_sglist, *remote_sglist;
12747         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12748         struct ctl_softc *softc;
12749         int retval;
12750         int i;
12751
12752         retval = 0;
12753         softc = control_softc;
12754
12755         local_sglist = io->io_hdr.local_sglist;
12756         local_dma_sglist = io->io_hdr.local_dma_sglist;
12757         remote_sglist = io->io_hdr.remote_sglist;
12758         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12759
12760         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12761                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12762                         local_sglist[i].len = remote_sglist[i].len;
12763
12764                         /*
12765                          * XXX Detect the situation where the RS-level I/O
12766                          * redirector on the other side has already read the
12767                          * data off of the AOR RS on this side, and
12768                          * transferred it to remote (mirror) memory on the
12769                          * other side.  Since we already have the data in
12770                          * memory here, we just need to use it.
12771                          *
12772                          * XXX KDM this can probably be removed once we
12773                          * get the cache device code in and take the
12774                          * current AOR implementation out.
12775                          */
12776 #ifdef NEEDTOPORT
12777                         if ((remote_sglist[i].addr >=
12778                              (void *)vtophys(softc->mirr->addr))
12779                          && (remote_sglist[i].addr <
12780                              ((void *)vtophys(softc->mirr->addr) +
12781                              CacheMirrorOffset))) {
12782                                 local_sglist[i].addr = remote_sglist[i].addr -
12783                                         CacheMirrorOffset;
12784                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12785                                      CTL_FLAG_DATA_IN)
12786                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12787                         } else {
12788                                 local_sglist[i].addr = remote_sglist[i].addr +
12789                                         CacheMirrorOffset;
12790                         }
12791 #endif
12792 #if 0
12793                         printf("%s: local %p, remote %p, len %d\n",
12794                                __func__, local_sglist[i].addr,
12795                                remote_sglist[i].addr, local_sglist[i].len);
12796 #endif
12797                 }
12798         } else {
12799                 uint32_t len_to_go;
12800
12801                 /*
12802                  * In this case, we don't have automatically allocated
12803                  * memory for this I/O on this controller.  This typically
12804                  * happens with internal CTL I/O -- e.g. inquiry, mode
12805                  * sense, etc.  Anything coming from RAIDCore will have
12806                  * a mirror area available.
12807                  */
12808                 len_to_go = io->scsiio.kern_data_len;
12809
12810                 /*
12811                  * Clear the no datasync flag, we have to use malloced
12812                  * buffers.
12813                  */
12814                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12815
12816                 /*
12817                  * The difficult thing here is that the size of the various
12818                  * S/G segments may be different than the size from the
12819                  * remote controller.  That'll make it harder when DMAing
12820                  * the data back to the other side.
12821                  */
12822                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12823                      sizeof(io->io_hdr.remote_sglist[0])) &&
12824                      (len_to_go > 0); i++) {
12825                         local_sglist[i].len = ctl_min(len_to_go, 131072);
12826                         CTL_SIZE_8B(local_dma_sglist[i].len,
12827                                     local_sglist[i].len);
12828                         local_sglist[i].addr =
12829                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12830
12831                         local_dma_sglist[i].addr = local_sglist[i].addr;
12832
12833                         if (local_sglist[i].addr == NULL) {
12834                                 int j;
12835
12836                                 printf("malloc failed for %zd bytes!",
12837                                        local_dma_sglist[i].len);
12838                                 for (j = 0; j < i; j++) {
12839                                         free(local_sglist[j].addr, M_CTL);
12840                                 }
12841                                 ctl_set_internal_failure(&io->scsiio,
12842                                                          /*sks_valid*/ 1,
12843                                                          /*retry_count*/ 4857);
12844                                 retval = 1;
12845                                 goto bailout_error;
12846                                 
12847                         }
12848                         /* XXX KDM do we need a sync here? */
12849
12850                         len_to_go -= local_sglist[i].len;
12851                 }
12852                 /*
12853                  * Reset the number of S/G entries accordingly.  The
12854                  * original number of S/G entries is available in
12855                  * rem_sg_entries.
12856                  */
12857                 io->scsiio.kern_sg_entries = i;
12858
12859 #if 0
12860                 printf("%s: kern_sg_entries = %d\n", __func__,
12861                        io->scsiio.kern_sg_entries);
12862                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12863                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
12864                                local_sglist[i].addr, local_sglist[i].len,
12865                                local_dma_sglist[i].len);
12866 #endif
12867         }
12868
12869
12870         return (retval);
12871
12872 bailout_error:
12873
12874         ctl_send_datamove_done(io, /*have_lock*/ 0);
12875
12876         return (retval);
12877 }
12878
12879 static int
12880 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12881                          ctl_ha_dt_cb callback)
12882 {
12883         struct ctl_ha_dt_req *rq;
12884         struct ctl_sg_entry *remote_sglist, *local_sglist;
12885         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
12886         uint32_t local_used, remote_used, total_used;
12887         int retval;
12888         int i, j;
12889
12890         retval = 0;
12891
12892         rq = ctl_dt_req_alloc();
12893
12894         /*
12895          * If we failed to allocate the request, and if the DMA didn't fail
12896          * anyway, set busy status.  This is just a resource allocation
12897          * failure.
12898          */
12899         if ((rq == NULL)
12900          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12901                 ctl_set_busy(&io->scsiio);
12902
12903         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12904
12905                 if (rq != NULL)
12906                         ctl_dt_req_free(rq);
12907
12908                 /*
12909                  * The data move failed.  We need to return status back
12910                  * to the other controller.  No point in trying to DMA
12911                  * data to the remote controller.
12912                  */
12913
12914                 ctl_send_datamove_done(io, /*have_lock*/ 0);
12915
12916                 retval = 1;
12917
12918                 goto bailout;
12919         }
12920
12921         local_sglist = io->io_hdr.local_sglist;
12922         local_dma_sglist = io->io_hdr.local_dma_sglist;
12923         remote_sglist = io->io_hdr.remote_sglist;
12924         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12925         local_used = 0;
12926         remote_used = 0;
12927         total_used = 0;
12928
12929         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12930                 rq->ret = CTL_HA_STATUS_SUCCESS;
12931                 rq->context = io;
12932                 callback(rq);
12933                 goto bailout;
12934         }
12935
12936         /*
12937          * Pull/push the data over the wire from/to the other controller.
12938          * This takes into account the possibility that the local and
12939          * remote sglists may not be identical in terms of the size of
12940          * the elements and the number of elements.
12941          *
12942          * One fundamental assumption here is that the length allocated for
12943          * both the local and remote sglists is identical.  Otherwise, we've
12944          * essentially got a coding error of some sort.
12945          */
12946         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12947                 int isc_ret;
12948                 uint32_t cur_len, dma_length;
12949                 uint8_t *tmp_ptr;
12950
12951                 rq->id = CTL_HA_DATA_CTL;
12952                 rq->command = command;
12953                 rq->context = io;
12954
12955                 /*
12956                  * Both pointers should be aligned.  But it is possible
12957                  * that the allocation length is not.  They should both
12958                  * also have enough slack left over at the end, though,
12959                  * to round up to the next 8 byte boundary.
12960                  */
12961                 cur_len = ctl_min(local_sglist[i].len - local_used,
12962                                   remote_sglist[j].len - remote_used);
12963
12964                 /*
12965                  * In this case, we have a size issue and need to decrease
12966                  * the size, except in the case where we actually have less
12967                  * than 8 bytes left.  In that case, we need to increase
12968                  * the DMA length to get the last bit.
12969                  */
12970                 if ((cur_len & 0x7) != 0) {
12971                         if (cur_len > 0x7) {
12972                                 cur_len = cur_len - (cur_len & 0x7);
12973                                 dma_length = cur_len;
12974                         } else {
12975                                 CTL_SIZE_8B(dma_length, cur_len);
12976                         }
12977
12978                 } else
12979                         dma_length = cur_len;
12980
12981                 /*
12982                  * If we had to allocate memory for this I/O, instead of using
12983                  * the non-cached mirror memory, we'll need to flush the cache
12984                  * before trying to DMA to the other controller.
12985                  *
12986                  * We could end up doing this multiple times for the same
12987                  * segment if we have a larger local segment than remote
12988                  * segment.  That shouldn't be an issue.
12989                  */
12990                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12991                         /*
12992                          * XXX KDM use bus_dmamap_sync() here.
12993                          */
12994                 }
12995
12996                 rq->size = dma_length;
12997
12998                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
12999                 tmp_ptr += local_used;
13000
13001                 /* Use physical addresses when talking to ISC hardware */
13002                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13003                         /* XXX KDM use busdma */
13004 #if 0
13005                         rq->local = vtophys(tmp_ptr);
13006 #endif
13007                 } else
13008                         rq->local = tmp_ptr;
13009
13010                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13011                 tmp_ptr += remote_used;
13012                 rq->remote = tmp_ptr;
13013
13014                 rq->callback = NULL;
13015
13016                 local_used += cur_len;
13017                 if (local_used >= local_sglist[i].len) {
13018                         i++;
13019                         local_used = 0;
13020                 }
13021
13022                 remote_used += cur_len;
13023                 if (remote_used >= remote_sglist[j].len) {
13024                         j++;
13025                         remote_used = 0;
13026                 }
13027                 total_used += cur_len;
13028
13029                 if (total_used >= io->scsiio.kern_data_len)
13030                         rq->callback = callback;
13031
13032                 if ((rq->size & 0x7) != 0) {
13033                         printf("%s: warning: size %d is not on 8b boundary\n",
13034                                __func__, rq->size);
13035                 }
13036                 if (((uintptr_t)rq->local & 0x7) != 0) {
13037                         printf("%s: warning: local %p not on 8b boundary\n",
13038                                __func__, rq->local);
13039                 }
13040                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13041                         printf("%s: warning: remote %p not on 8b boundary\n",
13042                                __func__, rq->local);
13043                 }
13044 #if 0
13045                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13046                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13047                        rq->local, rq->remote, rq->size);
13048 #endif
13049
13050                 isc_ret = ctl_dt_single(rq);
13051                 if (isc_ret == CTL_HA_STATUS_WAIT)
13052                         continue;
13053
13054                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13055                         rq->ret = CTL_HA_STATUS_SUCCESS;
13056                 } else {
13057                         rq->ret = isc_ret;
13058                 }
13059                 callback(rq);
13060                 goto bailout;
13061         }
13062
13063 bailout:
13064         return (retval);
13065
13066 }
13067
13068 static void
13069 ctl_datamove_remote_read(union ctl_io *io)
13070 {
13071         int retval;
13072         int i;
13073
13074         /*
13075          * This will send an error to the other controller in the case of a
13076          * failure.
13077          */
13078         retval = ctl_datamove_remote_sgl_setup(io);
13079         if (retval != 0)
13080                 return;
13081
13082         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13083                                           ctl_datamove_remote_read_cb);
13084         if ((retval != 0)
13085          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13086                 /*
13087                  * Make sure we free memory if there was an error..  The
13088                  * ctl_datamove_remote_xfer() function will send the
13089                  * datamove done message, or call the callback with an
13090                  * error if there is a problem.
13091                  */
13092                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13093                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13094         }
13095
13096         return;
13097 }
13098
13099 /*
13100  * Process a datamove request from the other controller.  This is used for
13101  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13102  * first.  Once that is complete, the data gets DMAed into the remote
13103  * controller's memory.  For reads, we DMA from the remote controller's
13104  * memory into our memory first, and then move it out to the FETD.
13105  */
13106 static void
13107 ctl_datamove_remote(union ctl_io *io)
13108 {
13109         struct ctl_softc *softc;
13110
13111         softc = control_softc;
13112
13113         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13114
13115         /*
13116          * Note that we look for an aborted I/O here, but don't do some of
13117          * the other checks that ctl_datamove() normally does.  We don't
13118          * need to run the task queue, because this I/O is on the ISC
13119          * queue, which is executed by the work thread after the task queue.
13120          * We don't need to run the datamove delay code, since that should
13121          * have been done if need be on the other controller.
13122          */
13123         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13124
13125                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13126                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13127                        io->io_hdr.nexus.targ_port,
13128                        io->io_hdr.nexus.targ_target.id,
13129                        io->io_hdr.nexus.targ_lun);
13130                 io->io_hdr.status = CTL_CMD_ABORTED;
13131                 io->io_hdr.port_status = 31338;
13132
13133                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13134
13135                 return;
13136         }
13137
13138         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13139                 ctl_datamove_remote_write(io);
13140         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13141                 ctl_datamove_remote_read(io);
13142         } else {
13143                 union ctl_ha_msg msg;
13144                 struct scsi_sense_data *sense;
13145                 uint8_t sks[3];
13146                 int retry_count;
13147
13148                 memset(&msg, 0, sizeof(msg));
13149
13150                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13151                 msg.hdr.status = CTL_SCSI_ERROR;
13152                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13153
13154                 retry_count = 4243;
13155
13156                 sense = &msg.scsi.sense_data;
13157                 sks[0] = SSD_SCS_VALID;
13158                 sks[1] = (retry_count >> 8) & 0xff;
13159                 sks[2] = retry_count & 0xff;
13160
13161                 /* "Internal target failure" */
13162                 scsi_set_sense_data(sense,
13163                                     /*sense_format*/ SSD_TYPE_NONE,
13164                                     /*current_error*/ 1,
13165                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13166                                     /*asc*/ 0x44,
13167                                     /*ascq*/ 0x00,
13168                                     /*type*/ SSD_ELEM_SKS,
13169                                     /*size*/ sizeof(sks),
13170                                     /*data*/ sks,
13171                                     SSD_ELEM_NONE);
13172
13173                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13174                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13175                         ctl_failover_io(io, /*have_lock*/ 1);
13176                         return;
13177                 }
13178
13179                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13180                     CTL_HA_STATUS_SUCCESS) {
13181                         /* XXX KDM what to do if this fails? */
13182                 }
13183                 return;
13184         }
13185         
13186 }
13187
13188 static int
13189 ctl_process_done(union ctl_io *io)
13190 {
13191         struct ctl_lun *lun;
13192         struct ctl_softc *ctl_softc;
13193         void (*fe_done)(union ctl_io *io);
13194         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13195
13196         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13197
13198         fe_done =
13199             control_softc->ctl_ports[targ_port]->fe_done;
13200
13201 #ifdef CTL_TIME_IO
13202         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13203                 char str[256];
13204                 char path_str[64];
13205                 struct sbuf sb;
13206
13207                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13208                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13209
13210                 sbuf_cat(&sb, path_str);
13211                 switch (io->io_hdr.io_type) {
13212                 case CTL_IO_SCSI:
13213                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13214                         sbuf_printf(&sb, "\n");
13215                         sbuf_cat(&sb, path_str);
13216                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13217                                     io->scsiio.tag_num, io->scsiio.tag_type);
13218                         break;
13219                 case CTL_IO_TASK:
13220                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13221                                     "Tag Type: %d\n", io->taskio.task_action,
13222                                     io->taskio.tag_num, io->taskio.tag_type);
13223                         break;
13224                 default:
13225                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13226                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13227                         break;
13228                 }
13229                 sbuf_cat(&sb, path_str);
13230                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13231                             (intmax_t)time_uptime - io->io_hdr.start_time);
13232                 sbuf_finish(&sb);
13233                 printf("%s", sbuf_data(&sb));
13234         }
13235 #endif /* CTL_TIME_IO */
13236
13237         switch (io->io_hdr.io_type) {
13238         case CTL_IO_SCSI:
13239                 break;
13240         case CTL_IO_TASK:
13241                 if (bootverbose || verbose > 0)
13242                         ctl_io_error_print(io, NULL);
13243                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13244                         ctl_free_io(io);
13245                 else
13246                         fe_done(io);
13247                 return (CTL_RETVAL_COMPLETE);
13248                 break;
13249         default:
13250                 printf("ctl_process_done: invalid io type %d\n",
13251                        io->io_hdr.io_type);
13252                 panic("ctl_process_done: invalid io type %d\n",
13253                       io->io_hdr.io_type);
13254                 break; /* NOTREACHED */
13255         }
13256
13257         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13258         if (lun == NULL) {
13259                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13260                                  io->io_hdr.nexus.targ_mapped_lun));
13261                 fe_done(io);
13262                 goto bailout;
13263         }
13264         ctl_softc = lun->ctl_softc;
13265
13266         mtx_lock(&lun->lun_lock);
13267
13268         /*
13269          * Check to see if we have any errors to inject here.  We only
13270          * inject errors for commands that don't already have errors set.
13271          */
13272         if ((STAILQ_FIRST(&lun->error_list) != NULL)
13273          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13274                 ctl_inject_error(lun, io);
13275
13276         /*
13277          * XXX KDM how do we treat commands that aren't completed
13278          * successfully?
13279          *
13280          * XXX KDM should we also track I/O latency?
13281          */
13282         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13283             io->io_hdr.io_type == CTL_IO_SCSI) {
13284 #ifdef CTL_TIME_IO
13285                 struct bintime cur_bt;
13286 #endif
13287                 int type;
13288
13289                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13290                     CTL_FLAG_DATA_IN)
13291                         type = CTL_STATS_READ;
13292                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13293                     CTL_FLAG_DATA_OUT)
13294                         type = CTL_STATS_WRITE;
13295                 else
13296                         type = CTL_STATS_NO_IO;
13297
13298                 lun->stats.ports[targ_port].bytes[type] +=
13299                     io->scsiio.kern_total_len;
13300                 lun->stats.ports[targ_port].operations[type]++;
13301 #ifdef CTL_TIME_IO
13302                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13303                    &io->io_hdr.dma_bt);
13304                 lun->stats.ports[targ_port].num_dmas[type] +=
13305                     io->io_hdr.num_dmas;
13306                 getbintime(&cur_bt);
13307                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13308                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13309 #endif
13310         }
13311
13312         /*
13313          * Remove this from the OOA queue.
13314          */
13315         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13316
13317         /*
13318          * Run through the blocked queue on this LUN and see if anything
13319          * has become unblocked, now that this transaction is done.
13320          */
13321         ctl_check_blocked(lun);
13322
13323         /*
13324          * If the LUN has been invalidated, free it if there is nothing
13325          * left on its OOA queue.
13326          */
13327         if ((lun->flags & CTL_LUN_INVALID)
13328          && TAILQ_EMPTY(&lun->ooa_queue)) {
13329                 mtx_unlock(&lun->lun_lock);
13330                 mtx_lock(&ctl_softc->ctl_lock);
13331                 ctl_free_lun(lun);
13332                 mtx_unlock(&ctl_softc->ctl_lock);
13333         } else
13334                 mtx_unlock(&lun->lun_lock);
13335
13336         /*
13337          * If this command has been aborted, make sure we set the status
13338          * properly.  The FETD is responsible for freeing the I/O and doing
13339          * whatever it needs to do to clean up its state.
13340          */
13341         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13342                 io->io_hdr.status = CTL_CMD_ABORTED;
13343
13344         /*
13345          * We print out status for every task management command.  For SCSI
13346          * commands, we filter out any unit attention errors; they happen
13347          * on every boot, and would clutter up the log.  Note:  task
13348          * management commands aren't printed here, they are printed above,
13349          * since they should never even make it down here.
13350          */
13351         switch (io->io_hdr.io_type) {
13352         case CTL_IO_SCSI: {
13353                 int error_code, sense_key, asc, ascq;
13354
13355                 sense_key = 0;
13356
13357                 if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13358                  && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13359                         /*
13360                          * Since this is just for printing, no need to
13361                          * show errors here.
13362                          */
13363                         scsi_extract_sense_len(&io->scsiio.sense_data,
13364                                                io->scsiio.sense_len,
13365                                                &error_code,
13366                                                &sense_key,
13367                                                &asc,
13368                                                &ascq,
13369                                                /*show_errors*/ 0);
13370                 }
13371
13372                 if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13373                  && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13374                   || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13375                   || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13376
13377                         if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13378                                 ctl_softc->skipped_prints++;
13379                         } else {
13380                                 uint32_t skipped_prints;
13381
13382                                 skipped_prints = ctl_softc->skipped_prints;
13383
13384                                 ctl_softc->skipped_prints = 0;
13385                                 ctl_softc->last_print_jiffies = time_uptime;
13386
13387                                 if (skipped_prints > 0) {
13388 #ifdef NEEDTOPORT
13389                                         csevent_log(CSC_CTL | CSC_SHELF_SW |
13390                                             CTL_ERROR_REPORT,
13391                                             csevent_LogType_Trace,
13392                                             csevent_Severity_Information,
13393                                             csevent_AlertLevel_Green,
13394                                             csevent_FRU_Firmware,
13395                                             csevent_FRU_Unknown,
13396                                             "High CTL error volume, %d prints "
13397                                             "skipped", skipped_prints);
13398 #endif
13399                                 }
13400                                 if (bootverbose || verbose > 0)
13401                                         ctl_io_error_print(io, NULL);
13402                         }
13403                 }
13404                 break;
13405         }
13406         case CTL_IO_TASK:
13407                 if (bootverbose || verbose > 0)
13408                         ctl_io_error_print(io, NULL);
13409                 break;
13410         default:
13411                 break;
13412         }
13413
13414         /*
13415          * Tell the FETD or the other shelf controller we're done with this
13416          * command.  Note that only SCSI commands get to this point.  Task
13417          * management commands are completed above.
13418          *
13419          * We only send status to the other controller if we're in XFER
13420          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13421          * received the I/O (from CTL's perspective), and so the status is
13422          * generated there.
13423          * 
13424          * XXX KDM if we hold the lock here, we could cause a deadlock
13425          * if the frontend comes back in in this context to queue
13426          * something.
13427          */
13428         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13429          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13430                 union ctl_ha_msg msg;
13431
13432                 memset(&msg, 0, sizeof(msg));
13433                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13434                 msg.hdr.original_sc = io->io_hdr.original_sc;
13435                 msg.hdr.nexus = io->io_hdr.nexus;
13436                 msg.hdr.status = io->io_hdr.status;
13437                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13438                 msg.scsi.tag_num = io->scsiio.tag_num;
13439                 msg.scsi.tag_type = io->scsiio.tag_type;
13440                 msg.scsi.sense_len = io->scsiio.sense_len;
13441                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13442                 msg.scsi.residual = io->scsiio.residual;
13443                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13444                        sizeof(io->scsiio.sense_data));
13445                 /*
13446                  * We copy this whether or not this is an I/O-related
13447                  * command.  Otherwise, we'd have to go and check to see
13448                  * whether it's a read/write command, and it really isn't
13449                  * worth it.
13450                  */
13451                 memcpy(&msg.scsi.lbalen,
13452                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13453                        sizeof(msg.scsi.lbalen));
13454
13455                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13456                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13457                         /* XXX do something here */
13458                 }
13459
13460                 ctl_free_io(io);
13461         } else 
13462                 fe_done(io);
13463
13464 bailout:
13465
13466         return (CTL_RETVAL_COMPLETE);
13467 }
13468
13469 /*
13470  * Front end should call this if it doesn't do autosense.  When the request
13471  * sense comes back in from the initiator, we'll dequeue this and send it.
13472  */
13473 int
13474 ctl_queue_sense(union ctl_io *io)
13475 {
13476         struct ctl_lun *lun;
13477         struct ctl_softc *ctl_softc;
13478         uint32_t initidx, targ_lun;
13479
13480         ctl_softc = control_softc;
13481
13482         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13483
13484         /*
13485          * LUN lookup will likely move to the ctl_work_thread() once we
13486          * have our new queueing infrastructure (that doesn't put things on
13487          * a per-LUN queue initially).  That is so that we can handle
13488          * things like an INQUIRY to a LUN that we don't have enabled.  We
13489          * can't deal with that right now.
13490          */
13491         mtx_lock(&ctl_softc->ctl_lock);
13492
13493         /*
13494          * If we don't have a LUN for this, just toss the sense
13495          * information.
13496          */
13497         targ_lun = io->io_hdr.nexus.targ_lun;
13498         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13499         if ((targ_lun < CTL_MAX_LUNS)
13500          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13501                 lun = ctl_softc->ctl_luns[targ_lun];
13502         else
13503                 goto bailout;
13504
13505         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13506
13507         mtx_lock(&lun->lun_lock);
13508         /*
13509          * Already have CA set for this LUN...toss the sense information.
13510          */
13511         if (ctl_is_set(lun->have_ca, initidx)) {
13512                 mtx_unlock(&lun->lun_lock);
13513                 goto bailout;
13514         }
13515
13516         memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
13517                ctl_min(sizeof(lun->pending_sense[initidx].sense),
13518                sizeof(io->scsiio.sense_data)));
13519         ctl_set_mask(lun->have_ca, initidx);
13520         mtx_unlock(&lun->lun_lock);
13521
13522 bailout:
13523         mtx_unlock(&ctl_softc->ctl_lock);
13524
13525         ctl_free_io(io);
13526
13527         return (CTL_RETVAL_COMPLETE);
13528 }
13529
13530 /*
13531  * Primary command inlet from frontend ports.  All SCSI and task I/O
13532  * requests must go through this function.
13533  */
13534 int
13535 ctl_queue(union ctl_io *io)
13536 {
13537         struct ctl_softc *ctl_softc;
13538
13539         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13540
13541         ctl_softc = control_softc;
13542
13543 #ifdef CTL_TIME_IO
13544         io->io_hdr.start_time = time_uptime;
13545         getbintime(&io->io_hdr.start_bt);
13546 #endif /* CTL_TIME_IO */
13547
13548         /* Map FE-specific LUN ID into global one. */
13549         io->io_hdr.nexus.targ_mapped_lun =
13550             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13551
13552         switch (io->io_hdr.io_type) {
13553         case CTL_IO_SCSI:
13554                 ctl_enqueue_incoming(io);
13555                 break;
13556         case CTL_IO_TASK:
13557                 ctl_run_task(io);
13558                 break;
13559         default:
13560                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13561                 return (EINVAL);
13562         }
13563
13564         return (CTL_RETVAL_COMPLETE);
13565 }
13566
13567 #ifdef CTL_IO_DELAY
13568 static void
13569 ctl_done_timer_wakeup(void *arg)
13570 {
13571         union ctl_io *io;
13572
13573         io = (union ctl_io *)arg;
13574         ctl_done(io);
13575 }
13576 #endif /* CTL_IO_DELAY */
13577
13578 void
13579 ctl_done(union ctl_io *io)
13580 {
13581         struct ctl_softc *ctl_softc;
13582
13583         ctl_softc = control_softc;
13584
13585         /*
13586          * Enable this to catch duplicate completion issues.
13587          */
13588 #if 0
13589         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13590                 printf("%s: type %d msg %d cdb %x iptl: "
13591                        "%d:%d:%d:%d tag 0x%04x "
13592                        "flag %#x status %x\n",
13593                         __func__,
13594                         io->io_hdr.io_type,
13595                         io->io_hdr.msg_type,
13596                         io->scsiio.cdb[0],
13597                         io->io_hdr.nexus.initid.id,
13598                         io->io_hdr.nexus.targ_port,
13599                         io->io_hdr.nexus.targ_target.id,
13600                         io->io_hdr.nexus.targ_lun,
13601                         (io->io_hdr.io_type ==
13602                         CTL_IO_TASK) ?
13603                         io->taskio.tag_num :
13604                         io->scsiio.tag_num,
13605                         io->io_hdr.flags,
13606                         io->io_hdr.status);
13607         } else
13608                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13609 #endif
13610
13611         /*
13612          * This is an internal copy of an I/O, and should not go through
13613          * the normal done processing logic.
13614          */
13615         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13616                 return;
13617
13618         /*
13619          * We need to send a msg to the serializing shelf to finish the IO
13620          * as well.  We don't send a finish message to the other shelf if
13621          * this is a task management command.  Task management commands
13622          * aren't serialized in the OOA queue, but rather just executed on
13623          * both shelf controllers for commands that originated on that
13624          * controller.
13625          */
13626         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13627          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13628                 union ctl_ha_msg msg_io;
13629
13630                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13631                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13632                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13633                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13634                 }
13635                 /* continue on to finish IO */
13636         }
13637 #ifdef CTL_IO_DELAY
13638         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13639                 struct ctl_lun *lun;
13640
13641                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13642
13643                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13644         } else {
13645                 struct ctl_lun *lun;
13646
13647                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13648
13649                 if ((lun != NULL)
13650                  && (lun->delay_info.done_delay > 0)) {
13651                         struct callout *callout;
13652
13653                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13654                         callout_init(callout, /*mpsafe*/ 1);
13655                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13656                         callout_reset(callout,
13657                                       lun->delay_info.done_delay * hz,
13658                                       ctl_done_timer_wakeup, io);
13659                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13660                                 lun->delay_info.done_delay = 0;
13661                         return;
13662                 }
13663         }
13664 #endif /* CTL_IO_DELAY */
13665
13666         ctl_enqueue_done(io);
13667 }
13668
13669 int
13670 ctl_isc(struct ctl_scsiio *ctsio)
13671 {
13672         struct ctl_lun *lun;
13673         int retval;
13674
13675         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13676
13677         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13678
13679         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13680
13681         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13682
13683         return (retval);
13684 }
13685
13686
13687 static void
13688 ctl_work_thread(void *arg)
13689 {
13690         struct ctl_thread *thr = (struct ctl_thread *)arg;
13691         struct ctl_softc *softc = thr->ctl_softc;
13692         union ctl_io *io;
13693         int retval;
13694
13695         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13696
13697         for (;;) {
13698                 retval = 0;
13699
13700                 /*
13701                  * We handle the queues in this order:
13702                  * - ISC
13703                  * - done queue (to free up resources, unblock other commands)
13704                  * - RtR queue
13705                  * - incoming queue
13706                  *
13707                  * If those queues are empty, we break out of the loop and
13708                  * go to sleep.
13709                  */
13710                 mtx_lock(&thr->queue_lock);
13711                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13712                 if (io != NULL) {
13713                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13714                         mtx_unlock(&thr->queue_lock);
13715                         ctl_handle_isc(io);
13716                         continue;
13717                 }
13718                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13719                 if (io != NULL) {
13720                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13721                         /* clear any blocked commands, call fe_done */
13722                         mtx_unlock(&thr->queue_lock);
13723                         retval = ctl_process_done(io);
13724                         continue;
13725                 }
13726                 if (!ctl_pause_rtr) {
13727                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13728                         if (io != NULL) {
13729                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13730                                 mtx_unlock(&thr->queue_lock);
13731                                 retval = ctl_scsiio(&io->scsiio);
13732                                 if (retval != CTL_RETVAL_COMPLETE)
13733                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13734                                 continue;
13735                         }
13736                 }
13737                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13738                 if (io != NULL) {
13739                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13740                         mtx_unlock(&thr->queue_lock);
13741                         ctl_scsiio_precheck(softc, &io->scsiio);
13742                         continue;
13743                 }
13744
13745                 /* Sleep until we have something to do. */
13746                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13747         }
13748 }
13749
13750 static void
13751 ctl_lun_thread(void *arg)
13752 {
13753         struct ctl_softc *softc = (struct ctl_softc *)arg;
13754         struct ctl_be_lun *be_lun;
13755         int retval;
13756
13757         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13758
13759         for (;;) {
13760                 retval = 0;
13761                 mtx_lock(&softc->ctl_lock);
13762                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13763                 if (be_lun != NULL) {
13764                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13765                         mtx_unlock(&softc->ctl_lock);
13766                         ctl_create_lun(be_lun);
13767                         continue;
13768                 }
13769
13770                 /* Sleep until we have something to do. */
13771                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13772                     PDROP | PRIBIO, "-", 0);
13773         }
13774 }
13775
13776 static void
13777 ctl_enqueue_incoming(union ctl_io *io)
13778 {
13779         struct ctl_softc *softc = control_softc;
13780         struct ctl_thread *thr;
13781
13782         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13783         mtx_lock(&thr->queue_lock);
13784         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13785         mtx_unlock(&thr->queue_lock);
13786         wakeup(thr);
13787 }
13788
13789 static void
13790 ctl_enqueue_rtr(union ctl_io *io)
13791 {
13792         struct ctl_softc *softc = control_softc;
13793         struct ctl_thread *thr;
13794
13795         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13796         mtx_lock(&thr->queue_lock);
13797         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13798         mtx_unlock(&thr->queue_lock);
13799         wakeup(thr);
13800 }
13801
13802 static void
13803 ctl_enqueue_done(union ctl_io *io)
13804 {
13805         struct ctl_softc *softc = control_softc;
13806         struct ctl_thread *thr;
13807
13808         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13809         mtx_lock(&thr->queue_lock);
13810         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13811         mtx_unlock(&thr->queue_lock);
13812         wakeup(thr);
13813 }
13814
13815 static void
13816 ctl_enqueue_isc(union ctl_io *io)
13817 {
13818         struct ctl_softc *softc = control_softc;
13819         struct ctl_thread *thr;
13820
13821         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13822         mtx_lock(&thr->queue_lock);
13823         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13824         mtx_unlock(&thr->queue_lock);
13825         wakeup(thr);
13826 }
13827
13828 /* Initialization and failover */
13829
13830 void
13831 ctl_init_isc_msg(void)
13832 {
13833         printf("CTL: Still calling this thing\n");
13834 }
13835
13836 /*
13837  * Init component
13838  *      Initializes component into configuration defined by bootMode
13839  *      (see hasc-sv.c)
13840  *      returns hasc_Status:
13841  *              OK
13842  *              ERROR - fatal error
13843  */
13844 static ctl_ha_comp_status
13845 ctl_isc_init(struct ctl_ha_component *c)
13846 {
13847         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13848
13849         c->status = ret;
13850         return ret;
13851 }
13852
13853 /* Start component
13854  *      Starts component in state requested. If component starts successfully,
13855  *      it must set its own state to the requestrd state
13856  *      When requested state is HASC_STATE_HA, the component may refine it
13857  *      by adding _SLAVE or _MASTER flags.
13858  *      Currently allowed state transitions are:
13859  *      UNKNOWN->HA             - initial startup
13860  *      UNKNOWN->SINGLE - initial startup when no parter detected
13861  *      HA->SINGLE              - failover
13862  * returns ctl_ha_comp_status:
13863  *              OK      - component successfully started in requested state
13864  *              FAILED  - could not start the requested state, failover may
13865  *                        be possible
13866  *              ERROR   - fatal error detected, no future startup possible
13867  */
13868 static ctl_ha_comp_status
13869 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13870 {
13871         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13872
13873         printf("%s: go\n", __func__);
13874
13875         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13876         if (c->state == CTL_HA_STATE_UNKNOWN ) {
13877                 ctl_is_single = 0;
13878                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13879                     != CTL_HA_STATUS_SUCCESS) {
13880                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13881                         ret = CTL_HA_COMP_STATUS_ERROR;
13882                 }
13883         } else if (CTL_HA_STATE_IS_HA(c->state)
13884                 && CTL_HA_STATE_IS_SINGLE(state)){
13885                 // HA->SINGLE transition
13886                 ctl_failover();
13887                 ctl_is_single = 1;
13888         } else {
13889                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
13890                        c->state, state);
13891                 ret = CTL_HA_COMP_STATUS_ERROR;
13892         }
13893         if (CTL_HA_STATE_IS_SINGLE(state))
13894                 ctl_is_single = 1;
13895
13896         c->state = state;
13897         c->status = ret;
13898         return ret;
13899 }
13900
13901 /*
13902  * Quiesce component
13903  * The component must clear any error conditions (set status to OK) and
13904  * prepare itself to another Start call
13905  * returns ctl_ha_comp_status:
13906  *      OK
13907  *      ERROR
13908  */
13909 static ctl_ha_comp_status
13910 ctl_isc_quiesce(struct ctl_ha_component *c)
13911 {
13912         int ret = CTL_HA_COMP_STATUS_OK;
13913
13914         ctl_pause_rtr = 1;
13915         c->status = ret;
13916         return ret;
13917 }
13918
13919 struct ctl_ha_component ctl_ha_component_ctlisc =
13920 {
13921         .name = "CTL ISC",
13922         .state = CTL_HA_STATE_UNKNOWN,
13923         .init = ctl_isc_init,
13924         .start = ctl_isc_start,
13925         .quiesce = ctl_isc_quiesce
13926 };
13927
13928 /*
13929  *  vim: ts=8
13930  */