]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r269149:
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/types.h>
51 #include <sys/kthread.h>
52 #include <sys/bio.h>
53 #include <sys/fcntl.h>
54 #include <sys/lock.h>
55 #include <sys/module.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/malloc.h>
59 #include <sys/conf.h>
60 #include <sys/ioccom.h>
61 #include <sys/queue.h>
62 #include <sys/sbuf.h>
63 #include <sys/smp.h>
64 #include <sys/endian.h>
65 #include <sys/sysctl.h>
66
67 #include <cam/cam.h>
68 #include <cam/scsi/scsi_all.h>
69 #include <cam/scsi/scsi_da.h>
70 #include <cam/ctl/ctl_io.h>
71 #include <cam/ctl/ctl.h>
72 #include <cam/ctl/ctl_frontend.h>
73 #include <cam/ctl/ctl_frontend_internal.h>
74 #include <cam/ctl/ctl_util.h>
75 #include <cam/ctl/ctl_backend.h>
76 #include <cam/ctl/ctl_ioctl.h>
77 #include <cam/ctl/ctl_ha.h>
78 #include <cam/ctl/ctl_private.h>
79 #include <cam/ctl/ctl_debug.h>
80 #include <cam/ctl/ctl_scsi_all.h>
81 #include <cam/ctl/ctl_error.h>
82
83 struct ctl_softc *control_softc = NULL;
84
85 /*
86  * Size and alignment macros needed for Copan-specific HA hardware.  These
87  * can go away when the HA code is re-written, and uses busdma for any
88  * hardware.
89  */
90 #define CTL_ALIGN_8B(target, source, type)                              \
91         if (((uint32_t)source & 0x7) != 0)                              \
92                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93         else                                                            \
94                 target = (type)source;
95
96 #define CTL_SIZE_8B(target, size)                                       \
97         if ((size & 0x7) != 0)                                          \
98                 target = size + (0x8 - (size & 0x7));                   \
99         else                                                            \
100                 target = size;
101
102 #define CTL_ALIGN_8B_MARGIN     16
103
104 /*
105  * Template mode pages.
106  */
107
108 /*
109  * Note that these are default values only.  The actual values will be
110  * filled in when the user does a mode sense.
111  */
112 static struct copan_power_subpage power_page_default = {
113         /*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114         /*subpage*/ PWR_SUBPAGE_CODE,
115         /*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116                          (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117         /*page_version*/ PWR_VERSION,
118         /* total_luns */ 26,
119         /* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120         /*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122                       0, 0, 0, 0, 0, 0}
123 };
124
125 static struct copan_power_subpage power_page_changeable = {
126         /*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127         /*subpage*/ PWR_SUBPAGE_CODE,
128         /*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129                          (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130         /*page_version*/ 0,
131         /* total_luns */ 0,
132         /* max_active_luns*/ 0,
133         /*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134                       0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135                       0, 0, 0, 0, 0, 0}
136 };
137
138 static struct copan_aps_subpage aps_page_default = {
139         APS_PAGE_CODE | SMPH_SPF, //page_code
140         APS_SUBPAGE_CODE, //subpage
141         {(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142          (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143         APS_VERSION, //page_version
144         0, //lock_active
145         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146         0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147         0, 0, 0, 0, 0} //reserved
148 };
149
150 static struct copan_aps_subpage aps_page_changeable = {
151         APS_PAGE_CODE | SMPH_SPF, //page_code
152         APS_SUBPAGE_CODE, //subpage
153         {(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154          (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155         0, //page_version
156         0, //lock_active
157         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158         0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159         0, 0, 0, 0, 0} //reserved
160 };
161
162 static struct copan_debugconf_subpage debugconf_page_default = {
163         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
164         DBGCNF_SUBPAGE_CODE,            /* subpage */
165         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167         DBGCNF_VERSION,                 /* page_version */
168         {CTL_TIME_IO_DEFAULT_SECS>>8,
169          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
170 };
171
172 static struct copan_debugconf_subpage debugconf_page_changeable = {
173         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
174         DBGCNF_SUBPAGE_CODE,            /* subpage */
175         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177         0,                              /* page_version */
178         {0xff,0xff},                    /* ctl_time_io_secs */
179 };
180
181 static struct scsi_format_page format_page_default = {
182         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
183         /*page_length*/sizeof(struct scsi_format_page) - 2,
184         /*tracks_per_zone*/ {0, 0},
185         /*alt_sectors_per_zone*/ {0, 0},
186         /*alt_tracks_per_zone*/ {0, 0},
187         /*alt_tracks_per_lun*/ {0, 0},
188         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190         /*bytes_per_sector*/ {0, 0},
191         /*interleave*/ {0, 0},
192         /*track_skew*/ {0, 0},
193         /*cylinder_skew*/ {0, 0},
194         /*flags*/ SFP_HSEC,
195         /*reserved*/ {0, 0, 0}
196 };
197
198 static struct scsi_format_page format_page_changeable = {
199         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
200         /*page_length*/sizeof(struct scsi_format_page) - 2,
201         /*tracks_per_zone*/ {0, 0},
202         /*alt_sectors_per_zone*/ {0, 0},
203         /*alt_tracks_per_zone*/ {0, 0},
204         /*alt_tracks_per_lun*/ {0, 0},
205         /*sectors_per_track*/ {0, 0},
206         /*bytes_per_sector*/ {0, 0},
207         /*interleave*/ {0, 0},
208         /*track_skew*/ {0, 0},
209         /*cylinder_skew*/ {0, 0},
210         /*flags*/ 0,
211         /*reserved*/ {0, 0, 0}
212 };
213
214 static struct scsi_rigid_disk_page rigid_disk_page_default = {
215         /*page_code*/SMS_RIGID_DISK_PAGE,
216         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217         /*cylinders*/ {0, 0, 0},
218         /*heads*/ CTL_DEFAULT_HEADS,
219         /*start_write_precomp*/ {0, 0, 0},
220         /*start_reduced_current*/ {0, 0, 0},
221         /*step_rate*/ {0, 0},
222         /*landing_zone_cylinder*/ {0, 0, 0},
223         /*rpl*/ SRDP_RPL_DISABLED,
224         /*rotational_offset*/ 0,
225         /*reserved1*/ 0,
226         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227                            CTL_DEFAULT_ROTATION_RATE & 0xff},
228         /*reserved2*/ {0, 0}
229 };
230
231 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232         /*page_code*/SMS_RIGID_DISK_PAGE,
233         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234         /*cylinders*/ {0, 0, 0},
235         /*heads*/ 0,
236         /*start_write_precomp*/ {0, 0, 0},
237         /*start_reduced_current*/ {0, 0, 0},
238         /*step_rate*/ {0, 0},
239         /*landing_zone_cylinder*/ {0, 0, 0},
240         /*rpl*/ 0,
241         /*rotational_offset*/ 0,
242         /*reserved1*/ 0,
243         /*rotation_rate*/ {0, 0},
244         /*reserved2*/ {0, 0}
245 };
246
247 static struct scsi_caching_page caching_page_default = {
248         /*page_code*/SMS_CACHING_PAGE,
249         /*page_length*/sizeof(struct scsi_caching_page) - 2,
250         /*flags1*/ SCP_DISC | SCP_WCE,
251         /*ret_priority*/ 0,
252         /*disable_pf_transfer_len*/ {0xff, 0xff},
253         /*min_prefetch*/ {0, 0},
254         /*max_prefetch*/ {0xff, 0xff},
255         /*max_pf_ceiling*/ {0xff, 0xff},
256         /*flags2*/ 0,
257         /*cache_segments*/ 0,
258         /*cache_seg_size*/ {0, 0},
259         /*reserved*/ 0,
260         /*non_cache_seg_size*/ {0, 0, 0}
261 };
262
263 static struct scsi_caching_page caching_page_changeable = {
264         /*page_code*/SMS_CACHING_PAGE,
265         /*page_length*/sizeof(struct scsi_caching_page) - 2,
266         /*flags1*/ 0,
267         /*ret_priority*/ 0,
268         /*disable_pf_transfer_len*/ {0, 0},
269         /*min_prefetch*/ {0, 0},
270         /*max_prefetch*/ {0, 0},
271         /*max_pf_ceiling*/ {0, 0},
272         /*flags2*/ 0,
273         /*cache_segments*/ 0,
274         /*cache_seg_size*/ {0, 0},
275         /*reserved*/ 0,
276         /*non_cache_seg_size*/ {0, 0, 0}
277 };
278
279 static struct scsi_control_page control_page_default = {
280         /*page_code*/SMS_CONTROL_MODE_PAGE,
281         /*page_length*/sizeof(struct scsi_control_page) - 2,
282         /*rlec*/0,
283         /*queue_flags*/0,
284         /*eca_and_aen*/0,
285         /*flags4*/SCP_TAS,
286         /*aen_holdoff_period*/{0, 0},
287         /*busy_timeout_period*/{0, 0},
288         /*extended_selftest_completion_time*/{0, 0}
289 };
290
291 static struct scsi_control_page control_page_changeable = {
292         /*page_code*/SMS_CONTROL_MODE_PAGE,
293         /*page_length*/sizeof(struct scsi_control_page) - 2,
294         /*rlec*/SCP_DSENSE,
295         /*queue_flags*/0,
296         /*eca_and_aen*/0,
297         /*flags4*/0,
298         /*aen_holdoff_period*/{0, 0},
299         /*busy_timeout_period*/{0, 0},
300         /*extended_selftest_completion_time*/{0, 0}
301 };
302
303
304 /*
305  * XXX KDM move these into the softc.
306  */
307 static int rcv_sync_msg;
308 static int persis_offset;
309 static uint8_t ctl_pause_rtr;
310 static int     ctl_is_single = 1;
311 static int     index_to_aps_page;
312
313 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314 static int worker_threads = -1;
315 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
316 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
317     &worker_threads, 1, "Number of worker threads");
318 static int verbose = 0;
319 TUNABLE_INT("kern.cam.ctl.verbose", &verbose);
320 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
321     &verbose, 0, "Show SCSI errors returned to initiator");
322
323 /*
324  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
325  * SCSI Ports (0x88), Block limits (0xB0) and
326  * Logical Block Provisioning (0xB2)
327  */
328 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   6
329
330 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
331                                   int param);
332 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
333 static int ctl_init(void);
334 void ctl_shutdown(void);
335 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
336 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
337 static void ctl_ioctl_online(void *arg);
338 static void ctl_ioctl_offline(void *arg);
339 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
340 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
341 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
342 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
343 static int ctl_ioctl_submit_wait(union ctl_io *io);
344 static void ctl_ioctl_datamove(union ctl_io *io);
345 static void ctl_ioctl_done(union ctl_io *io);
346 static void ctl_ioctl_hard_startstop_callback(void *arg,
347                                               struct cfi_metatask *metatask);
348 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
349 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
350                               struct ctl_ooa *ooa_hdr,
351                               struct ctl_ooa_entry *kern_entries);
352 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
353                      struct thread *td);
354 uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
355 uint32_t ctl_port_idx(int port_num);
356 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
357 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
358 #ifdef unused
359 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
360                                    uint32_t targ_target, uint32_t targ_lun,
361                                    int can_wait);
362 static void ctl_kfree_io(union ctl_io *io);
363 #endif /* unused */
364 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
365                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
366 static int ctl_free_lun(struct ctl_lun *lun);
367 static void ctl_create_lun(struct ctl_be_lun *be_lun);
368 /**
369 static void ctl_failover_change_pages(struct ctl_softc *softc,
370                                       struct ctl_scsiio *ctsio, int master);
371 **/
372
373 static int ctl_do_mode_select(union ctl_io *io);
374 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
375                            uint64_t res_key, uint64_t sa_res_key,
376                            uint8_t type, uint32_t residx,
377                            struct ctl_scsiio *ctsio,
378                            struct scsi_per_res_out *cdb,
379                            struct scsi_per_res_out_parms* param);
380 static void ctl_pro_preempt_other(struct ctl_lun *lun,
381                                   union ctl_ha_msg *msg);
382 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
383 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
384 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
385 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
386 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
387                                          int alloc_len);
388 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
389                                          int alloc_len);
390 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
391 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
392 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
393 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
394 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
395 static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
396                                          union ctl_io *ooa_io);
397 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
398                                 union ctl_io *starting_io);
399 static int ctl_check_blocked(struct ctl_lun *lun);
400 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
401                                 struct ctl_lun *lun,
402                                 const struct ctl_cmd_entry *entry,
403                                 struct ctl_scsiio *ctsio);
404 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
405 static void ctl_failover(void);
406 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
407                                struct ctl_scsiio *ctsio);
408 static int ctl_scsiio(struct ctl_scsiio *ctsio);
409
410 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
411 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
412                             ctl_ua_type ua_type);
413 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
414                          ctl_ua_type ua_type);
415 static int ctl_abort_task(union ctl_io *io);
416 static int ctl_abort_task_set(union ctl_io *io);
417 static int ctl_i_t_nexus_reset(union ctl_io *io);
418 static void ctl_run_task(union ctl_io *io);
419 #ifdef CTL_IO_DELAY
420 static void ctl_datamove_timer_wakeup(void *arg);
421 static void ctl_done_timer_wakeup(void *arg);
422 #endif /* CTL_IO_DELAY */
423
424 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
425 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
426 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
427 static void ctl_datamove_remote_write(union ctl_io *io);
428 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
429 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
430 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
431 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
432                                     ctl_ha_dt_cb callback);
433 static void ctl_datamove_remote_read(union ctl_io *io);
434 static void ctl_datamove_remote(union ctl_io *io);
435 static int ctl_process_done(union ctl_io *io);
436 static void ctl_lun_thread(void *arg);
437 static void ctl_work_thread(void *arg);
438 static void ctl_enqueue_incoming(union ctl_io *io);
439 static void ctl_enqueue_rtr(union ctl_io *io);
440 static void ctl_enqueue_done(union ctl_io *io);
441 static void ctl_enqueue_isc(union ctl_io *io);
442 static const struct ctl_cmd_entry *
443     ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
444 static const struct ctl_cmd_entry *
445     ctl_validate_command(struct ctl_scsiio *ctsio);
446 static int ctl_cmd_applicable(uint8_t lun_type,
447     const struct ctl_cmd_entry *entry);
448
449 /*
450  * Load the serialization table.  This isn't very pretty, but is probably
451  * the easiest way to do it.
452  */
453 #include "ctl_ser_table.c"
454
455 /*
456  * We only need to define open, close and ioctl routines for this driver.
457  */
458 static struct cdevsw ctl_cdevsw = {
459         .d_version =    D_VERSION,
460         .d_flags =      0,
461         .d_open =       ctl_open,
462         .d_close =      ctl_close,
463         .d_ioctl =      ctl_ioctl,
464         .d_name =       "ctl",
465 };
466
467
468 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
469 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
470
471 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
472
473 static moduledata_t ctl_moduledata = {
474         "ctl",
475         ctl_module_event_handler,
476         NULL
477 };
478
479 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
480 MODULE_VERSION(ctl, 1);
481
482 static struct ctl_frontend ioctl_frontend =
483 {
484         .name = "ioctl",
485 };
486
487 static void
488 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
489                             union ctl_ha_msg *msg_info)
490 {
491         struct ctl_scsiio *ctsio;
492
493         if (msg_info->hdr.original_sc == NULL) {
494                 printf("%s: original_sc == NULL!\n", __func__);
495                 /* XXX KDM now what? */
496                 return;
497         }
498
499         ctsio = &msg_info->hdr.original_sc->scsiio;
500         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
501         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
502         ctsio->io_hdr.status = msg_info->hdr.status;
503         ctsio->scsi_status = msg_info->scsi.scsi_status;
504         ctsio->sense_len = msg_info->scsi.sense_len;
505         ctsio->sense_residual = msg_info->scsi.sense_residual;
506         ctsio->residual = msg_info->scsi.residual;
507         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
508                sizeof(ctsio->sense_data));
509         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
510                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
511         ctl_enqueue_isc((union ctl_io *)ctsio);
512 }
513
514 static void
515 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
516                                 union ctl_ha_msg *msg_info)
517 {
518         struct ctl_scsiio *ctsio;
519
520         if (msg_info->hdr.serializing_sc == NULL) {
521                 printf("%s: serializing_sc == NULL!\n", __func__);
522                 /* XXX KDM now what? */
523                 return;
524         }
525
526         ctsio = &msg_info->hdr.serializing_sc->scsiio;
527 #if 0
528         /*
529          * Attempt to catch the situation where an I/O has
530          * been freed, and we're using it again.
531          */
532         if (ctsio->io_hdr.io_type == 0xff) {
533                 union ctl_io *tmp_io;
534                 tmp_io = (union ctl_io *)ctsio;
535                 printf("%s: %p use after free!\n", __func__,
536                        ctsio);
537                 printf("%s: type %d msg %d cdb %x iptl: "
538                        "%d:%d:%d:%d tag 0x%04x "
539                        "flag %#x status %x\n",
540                         __func__,
541                         tmp_io->io_hdr.io_type,
542                         tmp_io->io_hdr.msg_type,
543                         tmp_io->scsiio.cdb[0],
544                         tmp_io->io_hdr.nexus.initid.id,
545                         tmp_io->io_hdr.nexus.targ_port,
546                         tmp_io->io_hdr.nexus.targ_target.id,
547                         tmp_io->io_hdr.nexus.targ_lun,
548                         (tmp_io->io_hdr.io_type ==
549                         CTL_IO_TASK) ?
550                         tmp_io->taskio.tag_num :
551                         tmp_io->scsiio.tag_num,
552                         tmp_io->io_hdr.flags,
553                         tmp_io->io_hdr.status);
554         }
555 #endif
556         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
557         ctl_enqueue_isc((union ctl_io *)ctsio);
558 }
559
560 /*
561  * ISC (Inter Shelf Communication) event handler.  Events from the HA
562  * subsystem come in here.
563  */
564 static void
565 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
566 {
567         struct ctl_softc *ctl_softc;
568         union ctl_io *io;
569         struct ctl_prio *presio;
570         ctl_ha_status isc_status;
571
572         ctl_softc = control_softc;
573         io = NULL;
574
575
576 #if 0
577         printf("CTL: Isc Msg event %d\n", event);
578 #endif
579         if (event == CTL_HA_EVT_MSG_RECV) {
580                 union ctl_ha_msg msg_info;
581
582                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
583                                              sizeof(msg_info), /*wait*/ 0);
584 #if 0
585                 printf("CTL: msg_type %d\n", msg_info.msg_type);
586 #endif
587                 if (isc_status != 0) {
588                         printf("Error receiving message, status = %d\n",
589                                isc_status);
590                         return;
591                 }
592
593                 switch (msg_info.hdr.msg_type) {
594                 case CTL_MSG_SERIALIZE:
595 #if 0
596                         printf("Serialize\n");
597 #endif
598                         io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
599                         if (io == NULL) {
600                                 printf("ctl_isc_event_handler: can't allocate "
601                                        "ctl_io!\n");
602                                 /* Bad Juju */
603                                 /* Need to set busy and send msg back */
604                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
605                                 msg_info.hdr.status = CTL_SCSI_ERROR;
606                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
607                                 msg_info.scsi.sense_len = 0;
608                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
609                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
610                                 }
611                                 goto bailout;
612                         }
613                         ctl_zero_io(io);
614                         // populate ctsio from msg_info
615                         io->io_hdr.io_type = CTL_IO_SCSI;
616                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
617                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
618 #if 0
619                         printf("pOrig %x\n", (int)msg_info.original_sc);
620 #endif
621                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
622                                             CTL_FLAG_IO_ACTIVE;
623                         /*
624                          * If we're in serialization-only mode, we don't
625                          * want to go through full done processing.  Thus
626                          * the COPY flag.
627                          *
628                          * XXX KDM add another flag that is more specific.
629                          */
630                         if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
631                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
632                         io->io_hdr.nexus = msg_info.hdr.nexus;
633 #if 0
634                         printf("targ %d, port %d, iid %d, lun %d\n",
635                                io->io_hdr.nexus.targ_target.id,
636                                io->io_hdr.nexus.targ_port,
637                                io->io_hdr.nexus.initid.id,
638                                io->io_hdr.nexus.targ_lun);
639 #endif
640                         io->scsiio.tag_num = msg_info.scsi.tag_num;
641                         io->scsiio.tag_type = msg_info.scsi.tag_type;
642                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
643                                CTL_MAX_CDBLEN);
644                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
645                                 const struct ctl_cmd_entry *entry;
646
647                                 entry = ctl_get_cmd_entry(&io->scsiio);
648                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
649                                 io->io_hdr.flags |=
650                                         entry->flags & CTL_FLAG_DATA_MASK;
651                         }
652                         ctl_enqueue_isc(io);
653                         break;
654
655                 /* Performed on the Originating SC, XFER mode only */
656                 case CTL_MSG_DATAMOVE: {
657                         struct ctl_sg_entry *sgl;
658                         int i, j;
659
660                         io = msg_info.hdr.original_sc;
661                         if (io == NULL) {
662                                 printf("%s: original_sc == NULL!\n", __func__);
663                                 /* XXX KDM do something here */
664                                 break;
665                         }
666                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
667                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
668                         /*
669                          * Keep track of this, we need to send it back over
670                          * when the datamove is complete.
671                          */
672                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
673
674                         if (msg_info.dt.sg_sequence == 0) {
675                                 /*
676                                  * XXX KDM we use the preallocated S/G list
677                                  * here, but we'll need to change this to
678                                  * dynamic allocation if we need larger S/G
679                                  * lists.
680                                  */
681                                 if (msg_info.dt.kern_sg_entries >
682                                     sizeof(io->io_hdr.remote_sglist) /
683                                     sizeof(io->io_hdr.remote_sglist[0])) {
684                                         printf("%s: number of S/G entries "
685                                             "needed %u > allocated num %zd\n",
686                                             __func__,
687                                             msg_info.dt.kern_sg_entries,
688                                             sizeof(io->io_hdr.remote_sglist)/
689                                             sizeof(io->io_hdr.remote_sglist[0]));
690                                 
691                                         /*
692                                          * XXX KDM send a message back to
693                                          * the other side to shut down the
694                                          * DMA.  The error will come back
695                                          * through via the normal channel.
696                                          */
697                                         break;
698                                 }
699                                 sgl = io->io_hdr.remote_sglist;
700                                 memset(sgl, 0,
701                                        sizeof(io->io_hdr.remote_sglist));
702
703                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
704
705                                 io->scsiio.kern_sg_entries =
706                                         msg_info.dt.kern_sg_entries;
707                                 io->scsiio.rem_sg_entries =
708                                         msg_info.dt.kern_sg_entries;
709                                 io->scsiio.kern_data_len =
710                                         msg_info.dt.kern_data_len;
711                                 io->scsiio.kern_total_len =
712                                         msg_info.dt.kern_total_len;
713                                 io->scsiio.kern_data_resid =
714                                         msg_info.dt.kern_data_resid;
715                                 io->scsiio.kern_rel_offset =
716                                         msg_info.dt.kern_rel_offset;
717                                 /*
718                                  * Clear out per-DMA flags.
719                                  */
720                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
721                                 /*
722                                  * Add per-DMA flags that are set for this
723                                  * particular DMA request.
724                                  */
725                                 io->io_hdr.flags |= msg_info.dt.flags &
726                                                     CTL_FLAG_RDMA_MASK;
727                         } else
728                                 sgl = (struct ctl_sg_entry *)
729                                         io->scsiio.kern_data_ptr;
730
731                         for (i = msg_info.dt.sent_sg_entries, j = 0;
732                              i < (msg_info.dt.sent_sg_entries +
733                              msg_info.dt.cur_sg_entries); i++, j++) {
734                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
735                                 sgl[i].len = msg_info.dt.sg_list[j].len;
736
737 #if 0
738                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
739                                        __func__,
740                                        msg_info.dt.sg_list[j].addr,
741                                        msg_info.dt.sg_list[j].len,
742                                        sgl[i].addr, sgl[i].len, j, i);
743 #endif
744                         }
745 #if 0
746                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
747                                msg_info.dt.sg_list,
748                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
749 #endif
750
751                         /*
752                          * If this is the last piece of the I/O, we've got
753                          * the full S/G list.  Queue processing in the thread.
754                          * Otherwise wait for the next piece.
755                          */
756                         if (msg_info.dt.sg_last != 0)
757                                 ctl_enqueue_isc(io);
758                         break;
759                 }
760                 /* Performed on the Serializing (primary) SC, XFER mode only */
761                 case CTL_MSG_DATAMOVE_DONE: {
762                         if (msg_info.hdr.serializing_sc == NULL) {
763                                 printf("%s: serializing_sc == NULL!\n",
764                                        __func__);
765                                 /* XXX KDM now what? */
766                                 break;
767                         }
768                         /*
769                          * We grab the sense information here in case
770                          * there was a failure, so we can return status
771                          * back to the initiator.
772                          */
773                         io = msg_info.hdr.serializing_sc;
774                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
775                         io->io_hdr.status = msg_info.hdr.status;
776                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
777                         io->scsiio.sense_len = msg_info.scsi.sense_len;
778                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
779                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
780                         io->scsiio.residual = msg_info.scsi.residual;
781                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
782                                sizeof(io->scsiio.sense_data));
783                         ctl_enqueue_isc(io);
784                         break;
785                 }
786
787                 /* Preformed on Originating SC, SER_ONLY mode */
788                 case CTL_MSG_R2R:
789                         io = msg_info.hdr.original_sc;
790                         if (io == NULL) {
791                                 printf("%s: Major Bummer\n", __func__);
792                                 return;
793                         } else {
794 #if 0
795                                 printf("pOrig %x\n",(int) ctsio);
796 #endif
797                         }
798                         io->io_hdr.msg_type = CTL_MSG_R2R;
799                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
800                         ctl_enqueue_isc(io);
801                         break;
802
803                 /*
804                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
805                  * mode.
806                  * Performed on the Originating (i.e. secondary) SC in XFER
807                  * mode
808                  */
809                 case CTL_MSG_FINISH_IO:
810                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
811                                 ctl_isc_handler_finish_xfer(ctl_softc,
812                                                             &msg_info);
813                         else
814                                 ctl_isc_handler_finish_ser_only(ctl_softc,
815                                                                 &msg_info);
816                         break;
817
818                 /* Preformed on Originating SC */
819                 case CTL_MSG_BAD_JUJU:
820                         io = msg_info.hdr.original_sc;
821                         if (io == NULL) {
822                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
823                                        __func__);
824                                 break;
825                         }
826                         ctl_copy_sense_data(&msg_info, io);
827                         /*
828                          * IO should have already been cleaned up on other
829                          * SC so clear this flag so we won't send a message
830                          * back to finish the IO there.
831                          */
832                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
833                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
834
835                         /* io = msg_info.hdr.serializing_sc; */
836                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
837                         ctl_enqueue_isc(io);
838                         break;
839
840                 /* Handle resets sent from the other side */
841                 case CTL_MSG_MANAGE_TASKS: {
842                         struct ctl_taskio *taskio;
843                         taskio = (struct ctl_taskio *)ctl_alloc_io(
844                                 (void *)ctl_softc->othersc_pool);
845                         if (taskio == NULL) {
846                                 printf("ctl_isc_event_handler: can't allocate "
847                                        "ctl_io!\n");
848                                 /* Bad Juju */
849                                 /* should I just call the proper reset func
850                                    here??? */
851                                 goto bailout;
852                         }
853                         ctl_zero_io((union ctl_io *)taskio);
854                         taskio->io_hdr.io_type = CTL_IO_TASK;
855                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
856                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
857                         taskio->task_action = msg_info.task.task_action;
858                         taskio->tag_num = msg_info.task.tag_num;
859                         taskio->tag_type = msg_info.task.tag_type;
860 #ifdef CTL_TIME_IO
861                         taskio->io_hdr.start_time = time_uptime;
862                         getbintime(&taskio->io_hdr.start_bt);
863 #if 0
864                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
865 #endif
866 #endif /* CTL_TIME_IO */
867                         ctl_run_task((union ctl_io *)taskio);
868                         break;
869                 }
870                 /* Persistent Reserve action which needs attention */
871                 case CTL_MSG_PERS_ACTION:
872                         presio = (struct ctl_prio *)ctl_alloc_io(
873                                 (void *)ctl_softc->othersc_pool);
874                         if (presio == NULL) {
875                                 printf("ctl_isc_event_handler: can't allocate "
876                                        "ctl_io!\n");
877                                 /* Bad Juju */
878                                 /* Need to set busy and send msg back */
879                                 goto bailout;
880                         }
881                         ctl_zero_io((union ctl_io *)presio);
882                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
883                         presio->pr_msg = msg_info.pr;
884                         ctl_enqueue_isc((union ctl_io *)presio);
885                         break;
886                 case CTL_MSG_SYNC_FE:
887                         rcv_sync_msg = 1;
888                         break;
889                 case CTL_MSG_APS_LOCK: {
890                         // It's quicker to execute this then to
891                         // queue it.
892                         struct ctl_lun *lun;
893                         struct ctl_page_index *page_index;
894                         struct copan_aps_subpage *current_sp;
895                         uint32_t targ_lun;
896
897                         targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
898                         lun = ctl_softc->ctl_luns[targ_lun];
899                         mtx_lock(&lun->lun_lock);
900                         page_index = &lun->mode_pages.index[index_to_aps_page];
901                         current_sp = (struct copan_aps_subpage *)
902                                      (page_index->page_data +
903                                      (page_index->page_len * CTL_PAGE_CURRENT));
904
905                         current_sp->lock_active = msg_info.aps.lock_flag;
906                         mtx_unlock(&lun->lun_lock);
907                         break;
908                 }
909                 default:
910                         printf("How did I get here?\n");
911                 }
912         } else if (event == CTL_HA_EVT_MSG_SENT) {
913                 if (param != CTL_HA_STATUS_SUCCESS) {
914                         printf("Bad status from ctl_ha_msg_send status %d\n",
915                                param);
916                 }
917                 return;
918         } else if (event == CTL_HA_EVT_DISCONNECT) {
919                 printf("CTL: Got a disconnect from Isc\n");
920                 return;
921         } else {
922                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
923                 return;
924         }
925
926 bailout:
927         return;
928 }
929
930 static void
931 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
932 {
933         struct scsi_sense_data *sense;
934
935         sense = &dest->scsiio.sense_data;
936         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
937         dest->scsiio.scsi_status = src->scsi.scsi_status;
938         dest->scsiio.sense_len = src->scsi.sense_len;
939         dest->io_hdr.status = src->hdr.status;
940 }
941
942 static int
943 ctl_init(void)
944 {
945         struct ctl_softc *softc;
946         struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
947         struct ctl_port *port;
948         uint8_t sc_id =0;
949         int i, error, retval;
950         //int isc_retval;
951
952         retval = 0;
953         ctl_pause_rtr = 0;
954         rcv_sync_msg = 0;
955
956         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
957                                M_WAITOK | M_ZERO);
958         softc = control_softc;
959
960         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
961                               "cam/ctl");
962
963         softc->dev->si_drv1 = softc;
964
965         /*
966          * By default, return a "bad LUN" peripheral qualifier for unknown
967          * LUNs.  The user can override this default using the tunable or
968          * sysctl.  See the comment in ctl_inquiry_std() for more details.
969          */
970         softc->inquiry_pq_no_lun = 1;
971         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
972                           &softc->inquiry_pq_no_lun);
973         sysctl_ctx_init(&softc->sysctl_ctx);
974         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
975                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
976                 CTLFLAG_RD, 0, "CAM Target Layer");
977
978         if (softc->sysctl_tree == NULL) {
979                 printf("%s: unable to allocate sysctl tree\n", __func__);
980                 destroy_dev(softc->dev);
981                 free(control_softc, M_DEVBUF);
982                 control_softc = NULL;
983                 return (ENOMEM);
984         }
985
986         SYSCTL_ADD_INT(&softc->sysctl_ctx,
987                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
988                        "inquiry_pq_no_lun", CTLFLAG_RW,
989                        &softc->inquiry_pq_no_lun, 0,
990                        "Report no lun possible for invalid LUNs");
991
992         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
993         mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
994         softc->open_count = 0;
995
996         /*
997          * Default to actually sending a SYNCHRONIZE CACHE command down to
998          * the drive.
999          */
1000         softc->flags = CTL_FLAG_REAL_SYNC;
1001
1002         /*
1003          * In Copan's HA scheme, the "master" and "slave" roles are
1004          * figured out through the slot the controller is in.  Although it
1005          * is an active/active system, someone has to be in charge.
1006          */
1007 #ifdef NEEDTOPORT
1008         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1009 #endif
1010
1011         if (sc_id == 0) {
1012                 softc->flags |= CTL_FLAG_MASTER_SHELF;
1013                 persis_offset = 0;
1014         } else
1015                 persis_offset = CTL_MAX_INITIATORS;
1016
1017         /*
1018          * XXX KDM need to figure out where we want to get our target ID
1019          * and WWID.  Is it different on each port?
1020          */
1021         softc->target.id = 0;
1022         softc->target.wwid[0] = 0x12345678;
1023         softc->target.wwid[1] = 0x87654321;
1024         STAILQ_INIT(&softc->lun_list);
1025         STAILQ_INIT(&softc->pending_lun_queue);
1026         STAILQ_INIT(&softc->fe_list);
1027         STAILQ_INIT(&softc->port_list);
1028         STAILQ_INIT(&softc->be_list);
1029         STAILQ_INIT(&softc->io_pools);
1030
1031         if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1032                             &internal_pool)!= 0){
1033                 printf("ctl: can't allocate %d entry internal pool, "
1034                        "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1035                 return (ENOMEM);
1036         }
1037
1038         if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1039                             CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1040                 printf("ctl: can't allocate %d entry emergency pool, "
1041                        "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1042                 ctl_pool_free(internal_pool);
1043                 return (ENOMEM);
1044         }
1045
1046         if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1047                             &other_pool) != 0)
1048         {
1049                 printf("ctl: can't allocate %d entry other SC pool, "
1050                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1051                 ctl_pool_free(internal_pool);
1052                 ctl_pool_free(emergency_pool);
1053                 return (ENOMEM);
1054         }
1055
1056         softc->internal_pool = internal_pool;
1057         softc->emergency_pool = emergency_pool;
1058         softc->othersc_pool = other_pool;
1059
1060         if (worker_threads <= 0)
1061                 worker_threads = max(1, mp_ncpus / 4);
1062         if (worker_threads > CTL_MAX_THREADS)
1063                 worker_threads = CTL_MAX_THREADS;
1064
1065         for (i = 0; i < worker_threads; i++) {
1066                 struct ctl_thread *thr = &softc->threads[i];
1067
1068                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1069                 thr->ctl_softc = softc;
1070                 STAILQ_INIT(&thr->incoming_queue);
1071                 STAILQ_INIT(&thr->rtr_queue);
1072                 STAILQ_INIT(&thr->done_queue);
1073                 STAILQ_INIT(&thr->isc_queue);
1074
1075                 error = kproc_kthread_add(ctl_work_thread, thr,
1076                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1077                 if (error != 0) {
1078                         printf("error creating CTL work thread!\n");
1079                         ctl_pool_free(internal_pool);
1080                         ctl_pool_free(emergency_pool);
1081                         ctl_pool_free(other_pool);
1082                         return (error);
1083                 }
1084         }
1085         error = kproc_kthread_add(ctl_lun_thread, softc,
1086             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1087         if (error != 0) {
1088                 printf("error creating CTL lun thread!\n");
1089                 ctl_pool_free(internal_pool);
1090                 ctl_pool_free(emergency_pool);
1091                 ctl_pool_free(other_pool);
1092                 return (error);
1093         }
1094         if (bootverbose)
1095                 printf("ctl: CAM Target Layer loaded\n");
1096
1097         /*
1098          * Initialize the ioctl front end.
1099          */
1100         ctl_frontend_register(&ioctl_frontend);
1101         port = &softc->ioctl_info.port;
1102         port->frontend = &ioctl_frontend;
1103         sprintf(softc->ioctl_info.port_name, "ioctl");
1104         port->port_type = CTL_PORT_IOCTL;
1105         port->num_requested_ctl_io = 100;
1106         port->port_name = softc->ioctl_info.port_name;
1107         port->port_online = ctl_ioctl_online;
1108         port->port_offline = ctl_ioctl_offline;
1109         port->onoff_arg = &softc->ioctl_info;
1110         port->lun_enable = ctl_ioctl_lun_enable;
1111         port->lun_disable = ctl_ioctl_lun_disable;
1112         port->targ_lun_arg = &softc->ioctl_info;
1113         port->fe_datamove = ctl_ioctl_datamove;
1114         port->fe_done = ctl_ioctl_done;
1115         port->max_targets = 15;
1116         port->max_target_id = 15;
1117
1118         if (ctl_port_register(&softc->ioctl_info.port,
1119                           (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1120                 printf("ctl: ioctl front end registration failed, will "
1121                        "continue anyway\n");
1122         }
1123
1124 #ifdef CTL_IO_DELAY
1125         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1126                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1127                        sizeof(struct callout), CTL_TIMER_BYTES);
1128                 return (EINVAL);
1129         }
1130 #endif /* CTL_IO_DELAY */
1131
1132         return (0);
1133 }
1134
1135 void
1136 ctl_shutdown(void)
1137 {
1138         struct ctl_softc *softc;
1139         struct ctl_lun *lun, *next_lun;
1140         struct ctl_io_pool *pool;
1141
1142         softc = (struct ctl_softc *)control_softc;
1143
1144         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1145                 printf("ctl: ioctl front end deregistration failed\n");
1146
1147         mtx_lock(&softc->ctl_lock);
1148
1149         /*
1150          * Free up each LUN.
1151          */
1152         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1153                 next_lun = STAILQ_NEXT(lun, links);
1154                 ctl_free_lun(lun);
1155         }
1156
1157         mtx_unlock(&softc->ctl_lock);
1158
1159         ctl_frontend_deregister(&ioctl_frontend);
1160
1161         /*
1162          * This will rip the rug out from under any FETDs or anyone else
1163          * that has a pool allocated.  Since we increment our module
1164          * refcount any time someone outside the main CTL module allocates
1165          * a pool, we shouldn't have any problems here.  The user won't be
1166          * able to unload the CTL module until client modules have
1167          * successfully unloaded.
1168          */
1169         while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1170                 ctl_pool_free(pool);
1171
1172 #if 0
1173         ctl_shutdown_thread(softc->work_thread);
1174         mtx_destroy(&softc->queue_lock);
1175 #endif
1176
1177         mtx_destroy(&softc->pool_lock);
1178         mtx_destroy(&softc->ctl_lock);
1179
1180         destroy_dev(softc->dev);
1181
1182         sysctl_ctx_free(&softc->sysctl_ctx);
1183
1184         free(control_softc, M_DEVBUF);
1185         control_softc = NULL;
1186
1187         if (bootverbose)
1188                 printf("ctl: CAM Target Layer unloaded\n");
1189 }
1190
1191 static int
1192 ctl_module_event_handler(module_t mod, int what, void *arg)
1193 {
1194
1195         switch (what) {
1196         case MOD_LOAD:
1197                 return (ctl_init());
1198         case MOD_UNLOAD:
1199                 return (EBUSY);
1200         default:
1201                 return (EOPNOTSUPP);
1202         }
1203 }
1204
1205 /*
1206  * XXX KDM should we do some access checks here?  Bump a reference count to
1207  * prevent a CTL module from being unloaded while someone has it open?
1208  */
1209 static int
1210 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1211 {
1212         return (0);
1213 }
1214
1215 static int
1216 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1217 {
1218         return (0);
1219 }
1220
1221 int
1222 ctl_port_enable(ctl_port_type port_type)
1223 {
1224         struct ctl_softc *softc;
1225         struct ctl_port *port;
1226
1227         if (ctl_is_single == 0) {
1228                 union ctl_ha_msg msg_info;
1229                 int isc_retval;
1230
1231 #if 0
1232                 printf("%s: HA mode, synchronizing frontend enable\n",
1233                         __func__);
1234 #endif
1235                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1236                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1237                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1238                         printf("Sync msg send error retval %d\n", isc_retval);
1239                 }
1240                 if (!rcv_sync_msg) {
1241                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1242                                 sizeof(msg_info), 1);
1243                 }
1244 #if 0
1245                 printf("CTL:Frontend Enable\n");
1246         } else {
1247                 printf("%s: single mode, skipping frontend synchronization\n",
1248                         __func__);
1249 #endif
1250         }
1251
1252         softc = control_softc;
1253
1254         STAILQ_FOREACH(port, &softc->port_list, links) {
1255                 if (port_type & port->port_type)
1256                 {
1257 #if 0
1258                         printf("port %d\n", port->targ_port);
1259 #endif
1260                         ctl_port_online(port);
1261                 }
1262         }
1263
1264         return (0);
1265 }
1266
1267 int
1268 ctl_port_disable(ctl_port_type port_type)
1269 {
1270         struct ctl_softc *softc;
1271         struct ctl_port *port;
1272
1273         softc = control_softc;
1274
1275         STAILQ_FOREACH(port, &softc->port_list, links) {
1276                 if (port_type & port->port_type)
1277                         ctl_port_offline(port);
1278         }
1279
1280         return (0);
1281 }
1282
1283 /*
1284  * Returns 0 for success, 1 for failure.
1285  * Currently the only failure mode is if there aren't enough entries
1286  * allocated.  So, in case of a failure, look at num_entries_dropped,
1287  * reallocate and try again.
1288  */
1289 int
1290 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1291               int *num_entries_filled, int *num_entries_dropped,
1292               ctl_port_type port_type, int no_virtual)
1293 {
1294         struct ctl_softc *softc;
1295         struct ctl_port *port;
1296         int entries_dropped, entries_filled;
1297         int retval;
1298         int i;
1299
1300         softc = control_softc;
1301
1302         retval = 0;
1303         entries_filled = 0;
1304         entries_dropped = 0;
1305
1306         i = 0;
1307         mtx_lock(&softc->ctl_lock);
1308         STAILQ_FOREACH(port, &softc->port_list, links) {
1309                 struct ctl_port_entry *entry;
1310
1311                 if ((port->port_type & port_type) == 0)
1312                         continue;
1313
1314                 if ((no_virtual != 0)
1315                  && (port->virtual_port != 0))
1316                         continue;
1317
1318                 if (entries_filled >= num_entries_alloced) {
1319                         entries_dropped++;
1320                         continue;
1321                 }
1322                 entry = &entries[i];
1323
1324                 entry->port_type = port->port_type;
1325                 strlcpy(entry->port_name, port->port_name,
1326                         sizeof(entry->port_name));
1327                 entry->physical_port = port->physical_port;
1328                 entry->virtual_port = port->virtual_port;
1329                 entry->wwnn = port->wwnn;
1330                 entry->wwpn = port->wwpn;
1331
1332                 i++;
1333                 entries_filled++;
1334         }
1335
1336         mtx_unlock(&softc->ctl_lock);
1337
1338         if (entries_dropped > 0)
1339                 retval = 1;
1340
1341         *num_entries_dropped = entries_dropped;
1342         *num_entries_filled = entries_filled;
1343
1344         return (retval);
1345 }
1346
1347 static void
1348 ctl_ioctl_online(void *arg)
1349 {
1350         struct ctl_ioctl_info *ioctl_info;
1351
1352         ioctl_info = (struct ctl_ioctl_info *)arg;
1353
1354         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1355 }
1356
1357 static void
1358 ctl_ioctl_offline(void *arg)
1359 {
1360         struct ctl_ioctl_info *ioctl_info;
1361
1362         ioctl_info = (struct ctl_ioctl_info *)arg;
1363
1364         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1365 }
1366
1367 /*
1368  * Remove an initiator by port number and initiator ID.
1369  * Returns 0 for success, -1 for failure.
1370  */
1371 int
1372 ctl_remove_initiator(struct ctl_port *port, int iid)
1373 {
1374         struct ctl_softc *softc = control_softc;
1375
1376         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1377
1378         if (iid > CTL_MAX_INIT_PER_PORT) {
1379                 printf("%s: initiator ID %u > maximun %u!\n",
1380                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1381                 return (-1);
1382         }
1383
1384         mtx_lock(&softc->ctl_lock);
1385         port->wwpn_iid[iid].in_use--;
1386         port->wwpn_iid[iid].last_use = time_uptime;
1387         mtx_unlock(&softc->ctl_lock);
1388
1389         return (0);
1390 }
1391
1392 /*
1393  * Add an initiator to the initiator map.
1394  * Returns iid for success, < 0 for failure.
1395  */
1396 int
1397 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1398 {
1399         struct ctl_softc *softc = control_softc;
1400         time_t best_time;
1401         int i, best;
1402
1403         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1404
1405         if (iid >= CTL_MAX_INIT_PER_PORT) {
1406                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1407                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1408                 free(name, M_CTL);
1409                 return (-1);
1410         }
1411
1412         mtx_lock(&softc->ctl_lock);
1413
1414         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1415                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1416                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1417                                 iid = i;
1418                                 break;
1419                         }
1420                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1421                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1422                                 iid = i;
1423                                 break;
1424                         }
1425                 }
1426         }
1427
1428         if (iid < 0) {
1429                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1430                         if (port->wwpn_iid[i].in_use == 0 &&
1431                             port->wwpn_iid[i].wwpn == 0 &&
1432                             port->wwpn_iid[i].name == NULL) {
1433                                 iid = i;
1434                                 break;
1435                         }
1436                 }
1437         }
1438
1439         if (iid < 0) {
1440                 best = -1;
1441                 best_time = INT32_MAX;
1442                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1443                         if (port->wwpn_iid[i].in_use == 0) {
1444                                 if (port->wwpn_iid[i].last_use < best_time) {
1445                                         best = i;
1446                                         best_time = port->wwpn_iid[i].last_use;
1447                                 }
1448                         }
1449                 }
1450                 iid = best;
1451         }
1452
1453         if (iid < 0) {
1454                 mtx_unlock(&softc->ctl_lock);
1455                 free(name, M_CTL);
1456                 return (-2);
1457         }
1458
1459         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1460                 /*
1461                  * This is not an error yet.
1462                  */
1463                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1464 #if 0
1465                         printf("%s: port %d iid %u WWPN %#jx arrived"
1466                             " again\n", __func__, port->targ_port,
1467                             iid, (uintmax_t)wwpn);
1468 #endif
1469                         goto take;
1470                 }
1471                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1472                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1473 #if 0
1474                         printf("%s: port %d iid %u name '%s' arrived"
1475                             " again\n", __func__, port->targ_port,
1476                             iid, name);
1477 #endif
1478                         goto take;
1479                 }
1480
1481                 /*
1482                  * This is an error, but what do we do about it?  The
1483                  * driver is telling us we have a new WWPN for this
1484                  * initiator ID, so we pretty much need to use it.
1485                  */
1486                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1487                     " but WWPN %#jx '%s' is still at that address\n",
1488                     __func__, port->targ_port, iid, wwpn, name,
1489                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1490                     port->wwpn_iid[iid].name);
1491
1492                 /*
1493                  * XXX KDM clear have_ca and ua_pending on each LUN for
1494                  * this initiator.
1495                  */
1496         }
1497 take:
1498         free(port->wwpn_iid[iid].name, M_CTL);
1499         port->wwpn_iid[iid].name = name;
1500         port->wwpn_iid[iid].wwpn = wwpn;
1501         port->wwpn_iid[iid].in_use++;
1502         mtx_unlock(&softc->ctl_lock);
1503
1504         return (iid);
1505 }
1506
1507 static int
1508 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1509 {
1510         int len;
1511
1512         switch (port->port_type) {
1513         case CTL_PORT_FC:
1514         {
1515                 struct scsi_transportid_fcp *id =
1516                     (struct scsi_transportid_fcp *)buf;
1517                 if (port->wwpn_iid[iid].wwpn == 0)
1518                         return (0);
1519                 memset(id, 0, sizeof(*id));
1520                 id->format_protocol = SCSI_PROTO_FC;
1521                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1522                 return (sizeof(*id));
1523         }
1524         case CTL_PORT_ISCSI:
1525         {
1526                 struct scsi_transportid_iscsi_port *id =
1527                     (struct scsi_transportid_iscsi_port *)buf;
1528                 if (port->wwpn_iid[iid].name == NULL)
1529                         return (0);
1530                 memset(id, 0, 256);
1531                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1532                     SCSI_PROTO_ISCSI;
1533                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1534                 len = roundup2(min(len, 252), 4);
1535                 scsi_ulto2b(len, id->additional_length);
1536                 return (sizeof(*id) + len);
1537         }
1538         case CTL_PORT_SAS:
1539         {
1540                 struct scsi_transportid_sas *id =
1541                     (struct scsi_transportid_sas *)buf;
1542                 if (port->wwpn_iid[iid].wwpn == 0)
1543                         return (0);
1544                 memset(id, 0, sizeof(*id));
1545                 id->format_protocol = SCSI_PROTO_SAS;
1546                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1547                 return (sizeof(*id));
1548         }
1549         default:
1550         {
1551                 struct scsi_transportid_spi *id =
1552                     (struct scsi_transportid_spi *)buf;
1553                 memset(id, 0, sizeof(*id));
1554                 id->format_protocol = SCSI_PROTO_SPI;
1555                 scsi_ulto2b(iid, id->scsi_addr);
1556                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1557                 return (sizeof(*id));
1558         }
1559         }
1560 }
1561
1562 static int
1563 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1564 {
1565         return (0);
1566 }
1567
1568 static int
1569 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1570 {
1571         return (0);
1572 }
1573
1574 /*
1575  * Data movement routine for the CTL ioctl frontend port.
1576  */
1577 static int
1578 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1579 {
1580         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1581         struct ctl_sg_entry ext_entry, kern_entry;
1582         int ext_sglen, ext_sg_entries, kern_sg_entries;
1583         int ext_sg_start, ext_offset;
1584         int len_to_copy, len_copied;
1585         int kern_watermark, ext_watermark;
1586         int ext_sglist_malloced;
1587         int i, j;
1588
1589         ext_sglist_malloced = 0;
1590         ext_sg_start = 0;
1591         ext_offset = 0;
1592
1593         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1594
1595         /*
1596          * If this flag is set, fake the data transfer.
1597          */
1598         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1599                 ctsio->ext_data_filled = ctsio->ext_data_len;
1600                 goto bailout;
1601         }
1602
1603         /*
1604          * To simplify things here, if we have a single buffer, stick it in
1605          * a S/G entry and just make it a single entry S/G list.
1606          */
1607         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1608                 int len_seen;
1609
1610                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1611
1612                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1613                                                            M_WAITOK);
1614                 ext_sglist_malloced = 1;
1615                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1616                                    ext_sglen) != 0) {
1617                         ctl_set_internal_failure(ctsio,
1618                                                  /*sks_valid*/ 0,
1619                                                  /*retry_count*/ 0);
1620                         goto bailout;
1621                 }
1622                 ext_sg_entries = ctsio->ext_sg_entries;
1623                 len_seen = 0;
1624                 for (i = 0; i < ext_sg_entries; i++) {
1625                         if ((len_seen + ext_sglist[i].len) >=
1626                              ctsio->ext_data_filled) {
1627                                 ext_sg_start = i;
1628                                 ext_offset = ctsio->ext_data_filled - len_seen;
1629                                 break;
1630                         }
1631                         len_seen += ext_sglist[i].len;
1632                 }
1633         } else {
1634                 ext_sglist = &ext_entry;
1635                 ext_sglist->addr = ctsio->ext_data_ptr;
1636                 ext_sglist->len = ctsio->ext_data_len;
1637                 ext_sg_entries = 1;
1638                 ext_sg_start = 0;
1639                 ext_offset = ctsio->ext_data_filled;
1640         }
1641
1642         if (ctsio->kern_sg_entries > 0) {
1643                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1644                 kern_sg_entries = ctsio->kern_sg_entries;
1645         } else {
1646                 kern_sglist = &kern_entry;
1647                 kern_sglist->addr = ctsio->kern_data_ptr;
1648                 kern_sglist->len = ctsio->kern_data_len;
1649                 kern_sg_entries = 1;
1650         }
1651
1652
1653         kern_watermark = 0;
1654         ext_watermark = ext_offset;
1655         len_copied = 0;
1656         for (i = ext_sg_start, j = 0;
1657              i < ext_sg_entries && j < kern_sg_entries;) {
1658                 uint8_t *ext_ptr, *kern_ptr;
1659
1660                 len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1661                                       kern_sglist[j].len - kern_watermark);
1662
1663                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1664                 ext_ptr = ext_ptr + ext_watermark;
1665                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1666                         /*
1667                          * XXX KDM fix this!
1668                          */
1669                         panic("need to implement bus address support");
1670 #if 0
1671                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1672 #endif
1673                 } else
1674                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1675                 kern_ptr = kern_ptr + kern_watermark;
1676
1677                 kern_watermark += len_to_copy;
1678                 ext_watermark += len_to_copy;
1679
1680                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1681                      CTL_FLAG_DATA_IN) {
1682                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1683                                          "bytes to user\n", len_to_copy));
1684                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1685                                          "to %p\n", kern_ptr, ext_ptr));
1686                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1687                                 ctl_set_internal_failure(ctsio,
1688                                                          /*sks_valid*/ 0,
1689                                                          /*retry_count*/ 0);
1690                                 goto bailout;
1691                         }
1692                 } else {
1693                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1694                                          "bytes from user\n", len_to_copy));
1695                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1696                                          "to %p\n", ext_ptr, kern_ptr));
1697                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1698                                 ctl_set_internal_failure(ctsio,
1699                                                          /*sks_valid*/ 0,
1700                                                          /*retry_count*/0);
1701                                 goto bailout;
1702                         }
1703                 }
1704
1705                 len_copied += len_to_copy;
1706
1707                 if (ext_sglist[i].len == ext_watermark) {
1708                         i++;
1709                         ext_watermark = 0;
1710                 }
1711
1712                 if (kern_sglist[j].len == kern_watermark) {
1713                         j++;
1714                         kern_watermark = 0;
1715                 }
1716         }
1717
1718         ctsio->ext_data_filled += len_copied;
1719
1720         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1721                          "kern_sg_entries: %d\n", ext_sg_entries,
1722                          kern_sg_entries));
1723         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1724                          "kern_data_len = %d\n", ctsio->ext_data_len,
1725                          ctsio->kern_data_len));
1726
1727
1728         /* XXX KDM set residual?? */
1729 bailout:
1730
1731         if (ext_sglist_malloced != 0)
1732                 free(ext_sglist, M_CTL);
1733
1734         return (CTL_RETVAL_COMPLETE);
1735 }
1736
1737 /*
1738  * Serialize a command that went down the "wrong" side, and so was sent to
1739  * this controller for execution.  The logic is a little different than the
1740  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1741  * sent back to the other side, but in the success case, we execute the
1742  * command on this side (XFER mode) or tell the other side to execute it
1743  * (SER_ONLY mode).
1744  */
1745 static int
1746 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1747 {
1748         struct ctl_softc *ctl_softc;
1749         union ctl_ha_msg msg_info;
1750         struct ctl_lun *lun;
1751         int retval = 0;
1752         uint32_t targ_lun;
1753
1754         ctl_softc = control_softc;
1755
1756         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1757         lun = ctl_softc->ctl_luns[targ_lun];
1758         if (lun==NULL)
1759         {
1760                 /*
1761                  * Why isn't LUN defined? The other side wouldn't
1762                  * send a cmd if the LUN is undefined.
1763                  */
1764                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1765
1766                 /* "Logical unit not supported" */
1767                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1768                                    lun,
1769                                    /*sense_format*/SSD_TYPE_NONE,
1770                                    /*current_error*/ 1,
1771                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1772                                    /*asc*/ 0x25,
1773                                    /*ascq*/ 0x00,
1774                                    SSD_ELEM_NONE);
1775
1776                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1777                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1778                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1779                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1780                 msg_info.hdr.serializing_sc = NULL;
1781                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1782                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1783                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1784                 }
1785                 return(1);
1786
1787         }
1788
1789         mtx_lock(&lun->lun_lock);
1790         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1791
1792         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1793                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1794                  ooa_links))) {
1795         case CTL_ACTION_BLOCK:
1796                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1797                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1798                                   blocked_links);
1799                 break;
1800         case CTL_ACTION_PASS:
1801         case CTL_ACTION_SKIP:
1802                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1803                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1804                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1805                 } else {
1806
1807                         /* send msg back to other side */
1808                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1809                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1810                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1811 #if 0
1812                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1813 #endif
1814                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1815                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1816                         }
1817                 }
1818                 break;
1819         case CTL_ACTION_OVERLAP:
1820                 /* OVERLAPPED COMMANDS ATTEMPTED */
1821                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1822                                    lun,
1823                                    /*sense_format*/SSD_TYPE_NONE,
1824                                    /*current_error*/ 1,
1825                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1826                                    /*asc*/ 0x4E,
1827                                    /*ascq*/ 0x00,
1828                                    SSD_ELEM_NONE);
1829
1830                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1831                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1832                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1833                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1834                 msg_info.hdr.serializing_sc = NULL;
1835                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1836 #if 0
1837                 printf("BAD JUJU:Major Bummer Overlap\n");
1838 #endif
1839                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1840                 retval = 1;
1841                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1842                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1843                 }
1844                 break;
1845         case CTL_ACTION_OVERLAP_TAG:
1846                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1847                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1848                                    lun,
1849                                    /*sense_format*/SSD_TYPE_NONE,
1850                                    /*current_error*/ 1,
1851                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1852                                    /*asc*/ 0x4D,
1853                                    /*ascq*/ ctsio->tag_num & 0xff,
1854                                    SSD_ELEM_NONE);
1855
1856                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1857                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1858                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1859                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1860                 msg_info.hdr.serializing_sc = NULL;
1861                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1862 #if 0
1863                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1864 #endif
1865                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1866                 retval = 1;
1867                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1868                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1869                 }
1870                 break;
1871         case CTL_ACTION_ERROR:
1872         default:
1873                 /* "Internal target failure" */
1874                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1875                                    lun,
1876                                    /*sense_format*/SSD_TYPE_NONE,
1877                                    /*current_error*/ 1,
1878                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1879                                    /*asc*/ 0x44,
1880                                    /*ascq*/ 0x00,
1881                                    SSD_ELEM_NONE);
1882
1883                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1884                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1885                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1886                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1887                 msg_info.hdr.serializing_sc = NULL;
1888                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1889 #if 0
1890                 printf("BAD JUJU:Major Bummer HW Error\n");
1891 #endif
1892                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1893                 retval = 1;
1894                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1895                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1896                 }
1897                 break;
1898         }
1899         mtx_unlock(&lun->lun_lock);
1900         return (retval);
1901 }
1902
1903 static int
1904 ctl_ioctl_submit_wait(union ctl_io *io)
1905 {
1906         struct ctl_fe_ioctl_params params;
1907         ctl_fe_ioctl_state last_state;
1908         int done, retval;
1909
1910         retval = 0;
1911
1912         bzero(&params, sizeof(params));
1913
1914         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1915         cv_init(&params.sem, "ctlioccv");
1916         params.state = CTL_IOCTL_INPROG;
1917         last_state = params.state;
1918
1919         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1920
1921         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1922
1923         /* This shouldn't happen */
1924         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1925                 return (retval);
1926
1927         done = 0;
1928
1929         do {
1930                 mtx_lock(&params.ioctl_mtx);
1931                 /*
1932                  * Check the state here, and don't sleep if the state has
1933                  * already changed (i.e. wakeup has already occured, but we
1934                  * weren't waiting yet).
1935                  */
1936                 if (params.state == last_state) {
1937                         /* XXX KDM cv_wait_sig instead? */
1938                         cv_wait(&params.sem, &params.ioctl_mtx);
1939                 }
1940                 last_state = params.state;
1941
1942                 switch (params.state) {
1943                 case CTL_IOCTL_INPROG:
1944                         /* Why did we wake up? */
1945                         /* XXX KDM error here? */
1946                         mtx_unlock(&params.ioctl_mtx);
1947                         break;
1948                 case CTL_IOCTL_DATAMOVE:
1949                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1950
1951                         /*
1952                          * change last_state back to INPROG to avoid
1953                          * deadlock on subsequent data moves.
1954                          */
1955                         params.state = last_state = CTL_IOCTL_INPROG;
1956
1957                         mtx_unlock(&params.ioctl_mtx);
1958                         ctl_ioctl_do_datamove(&io->scsiio);
1959                         /*
1960                          * Note that in some cases, most notably writes,
1961                          * this will queue the I/O and call us back later.
1962                          * In other cases, generally reads, this routine
1963                          * will immediately call back and wake us up,
1964                          * probably using our own context.
1965                          */
1966                         io->scsiio.be_move_done(io);
1967                         break;
1968                 case CTL_IOCTL_DONE:
1969                         mtx_unlock(&params.ioctl_mtx);
1970                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1971                         done = 1;
1972                         break;
1973                 default:
1974                         mtx_unlock(&params.ioctl_mtx);
1975                         /* XXX KDM error here? */
1976                         break;
1977                 }
1978         } while (done == 0);
1979
1980         mtx_destroy(&params.ioctl_mtx);
1981         cv_destroy(&params.sem);
1982
1983         return (CTL_RETVAL_COMPLETE);
1984 }
1985
1986 static void
1987 ctl_ioctl_datamove(union ctl_io *io)
1988 {
1989         struct ctl_fe_ioctl_params *params;
1990
1991         params = (struct ctl_fe_ioctl_params *)
1992                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1993
1994         mtx_lock(&params->ioctl_mtx);
1995         params->state = CTL_IOCTL_DATAMOVE;
1996         cv_broadcast(&params->sem);
1997         mtx_unlock(&params->ioctl_mtx);
1998 }
1999
2000 static void
2001 ctl_ioctl_done(union ctl_io *io)
2002 {
2003         struct ctl_fe_ioctl_params *params;
2004
2005         params = (struct ctl_fe_ioctl_params *)
2006                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2007
2008         mtx_lock(&params->ioctl_mtx);
2009         params->state = CTL_IOCTL_DONE;
2010         cv_broadcast(&params->sem);
2011         mtx_unlock(&params->ioctl_mtx);
2012 }
2013
2014 static void
2015 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2016 {
2017         struct ctl_fe_ioctl_startstop_info *sd_info;
2018
2019         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2020
2021         sd_info->hs_info.status = metatask->status;
2022         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2023         sd_info->hs_info.luns_complete =
2024                 metatask->taskinfo.startstop.luns_complete;
2025         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2026
2027         cv_broadcast(&sd_info->sem);
2028 }
2029
2030 static void
2031 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2032 {
2033         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2034
2035         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2036
2037         mtx_lock(fe_bbr_info->lock);
2038         fe_bbr_info->bbr_info->status = metatask->status;
2039         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2040         fe_bbr_info->wakeup_done = 1;
2041         mtx_unlock(fe_bbr_info->lock);
2042
2043         cv_broadcast(&fe_bbr_info->sem);
2044 }
2045
2046 /*
2047  * Returns 0 for success, errno for failure.
2048  */
2049 static int
2050 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2051                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2052 {
2053         union ctl_io *io;
2054         int retval;
2055
2056         retval = 0;
2057
2058         mtx_lock(&lun->lun_lock);
2059         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2060              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2061              ooa_links)) {
2062                 struct ctl_ooa_entry *entry;
2063
2064                 /*
2065                  * If we've got more than we can fit, just count the
2066                  * remaining entries.
2067                  */
2068                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2069                         continue;
2070
2071                 entry = &kern_entries[*cur_fill_num];
2072
2073                 entry->tag_num = io->scsiio.tag_num;
2074                 entry->lun_num = lun->lun;
2075 #ifdef CTL_TIME_IO
2076                 entry->start_bt = io->io_hdr.start_bt;
2077 #endif
2078                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2079                 entry->cdb_len = io->scsiio.cdb_len;
2080                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2081                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2082
2083                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2084                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2085
2086                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2087                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2088
2089                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2090                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2091
2092                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2093                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2094         }
2095         mtx_unlock(&lun->lun_lock);
2096
2097         return (retval);
2098 }
2099
2100 static void *
2101 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2102                  size_t error_str_len)
2103 {
2104         void *kptr;
2105
2106         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2107
2108         if (copyin(user_addr, kptr, len) != 0) {
2109                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2110                          "from user address %p to kernel address %p", len,
2111                          user_addr, kptr);
2112                 free(kptr, M_CTL);
2113                 return (NULL);
2114         }
2115
2116         return (kptr);
2117 }
2118
2119 static void
2120 ctl_free_args(int num_args, struct ctl_be_arg *args)
2121 {
2122         int i;
2123
2124         if (args == NULL)
2125                 return;
2126
2127         for (i = 0; i < num_args; i++) {
2128                 free(args[i].kname, M_CTL);
2129                 free(args[i].kvalue, M_CTL);
2130         }
2131
2132         free(args, M_CTL);
2133 }
2134
2135 static struct ctl_be_arg *
2136 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2137                 char *error_str, size_t error_str_len)
2138 {
2139         struct ctl_be_arg *args;
2140         int i;
2141
2142         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2143                                 error_str, error_str_len);
2144
2145         if (args == NULL)
2146                 goto bailout;
2147
2148         for (i = 0; i < num_args; i++) {
2149                 args[i].kname = NULL;
2150                 args[i].kvalue = NULL;
2151         }
2152
2153         for (i = 0; i < num_args; i++) {
2154                 uint8_t *tmpptr;
2155
2156                 args[i].kname = ctl_copyin_alloc(args[i].name,
2157                         args[i].namelen, error_str, error_str_len);
2158                 if (args[i].kname == NULL)
2159                         goto bailout;
2160
2161                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2162                         snprintf(error_str, error_str_len, "Argument %d "
2163                                  "name is not NUL-terminated", i);
2164                         goto bailout;
2165                 }
2166
2167                 if (args[i].flags & CTL_BEARG_RD) {
2168                         tmpptr = ctl_copyin_alloc(args[i].value,
2169                                 args[i].vallen, error_str, error_str_len);
2170                         if (tmpptr == NULL)
2171                                 goto bailout;
2172                         if ((args[i].flags & CTL_BEARG_ASCII)
2173                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2174                                 snprintf(error_str, error_str_len, "Argument "
2175                                     "%d value is not NUL-terminated", i);
2176                                 goto bailout;
2177                         }
2178                         args[i].kvalue = tmpptr;
2179                 } else {
2180                         args[i].kvalue = malloc(args[i].vallen,
2181                             M_CTL, M_WAITOK | M_ZERO);
2182                 }
2183         }
2184
2185         return (args);
2186 bailout:
2187
2188         ctl_free_args(num_args, args);
2189
2190         return (NULL);
2191 }
2192
2193 static void
2194 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2195 {
2196         int i;
2197
2198         for (i = 0; i < num_args; i++) {
2199                 if (args[i].flags & CTL_BEARG_WR)
2200                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2201         }
2202 }
2203
2204 /*
2205  * Escape characters that are illegal or not recommended in XML.
2206  */
2207 int
2208 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2209 {
2210         int retval;
2211
2212         retval = 0;
2213
2214         for (; *str; str++) {
2215                 switch (*str) {
2216                 case '&':
2217                         retval = sbuf_printf(sb, "&amp;");
2218                         break;
2219                 case '>':
2220                         retval = sbuf_printf(sb, "&gt;");
2221                         break;
2222                 case '<':
2223                         retval = sbuf_printf(sb, "&lt;");
2224                         break;
2225                 default:
2226                         retval = sbuf_putc(sb, *str);
2227                         break;
2228                 }
2229
2230                 if (retval != 0)
2231                         break;
2232
2233         }
2234
2235         return (retval);
2236 }
2237
2238 static int
2239 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2240           struct thread *td)
2241 {
2242         struct ctl_softc *softc;
2243         int retval;
2244
2245         softc = control_softc;
2246
2247         retval = 0;
2248
2249         switch (cmd) {
2250         case CTL_IO: {
2251                 union ctl_io *io;
2252                 void *pool_tmp;
2253
2254                 /*
2255                  * If we haven't been "enabled", don't allow any SCSI I/O
2256                  * to this FETD.
2257                  */
2258                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2259                         retval = EPERM;
2260                         break;
2261                 }
2262
2263                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2264                 if (io == NULL) {
2265                         printf("ctl_ioctl: can't allocate ctl_io!\n");
2266                         retval = ENOSPC;
2267                         break;
2268                 }
2269
2270                 /*
2271                  * Need to save the pool reference so it doesn't get
2272                  * spammed by the user's ctl_io.
2273                  */
2274                 pool_tmp = io->io_hdr.pool;
2275
2276                 memcpy(io, (void *)addr, sizeof(*io));
2277
2278                 io->io_hdr.pool = pool_tmp;
2279                 /*
2280                  * No status yet, so make sure the status is set properly.
2281                  */
2282                 io->io_hdr.status = CTL_STATUS_NONE;
2283
2284                 /*
2285                  * The user sets the initiator ID, target and LUN IDs.
2286                  */
2287                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2288                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2289                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2290                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2291                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2292
2293                 retval = ctl_ioctl_submit_wait(io);
2294
2295                 if (retval != 0) {
2296                         ctl_free_io(io);
2297                         break;
2298                 }
2299
2300                 memcpy((void *)addr, io, sizeof(*io));
2301
2302                 /* return this to our pool */
2303                 ctl_free_io(io);
2304
2305                 break;
2306         }
2307         case CTL_ENABLE_PORT:
2308         case CTL_DISABLE_PORT:
2309         case CTL_SET_PORT_WWNS: {
2310                 struct ctl_port *port;
2311                 struct ctl_port_entry *entry;
2312
2313                 entry = (struct ctl_port_entry *)addr;
2314                 
2315                 mtx_lock(&softc->ctl_lock);
2316                 STAILQ_FOREACH(port, &softc->port_list, links) {
2317                         int action, done;
2318
2319                         action = 0;
2320                         done = 0;
2321
2322                         if ((entry->port_type == CTL_PORT_NONE)
2323                          && (entry->targ_port == port->targ_port)) {
2324                                 /*
2325                                  * If the user only wants to enable or
2326                                  * disable or set WWNs on a specific port,
2327                                  * do the operation and we're done.
2328                                  */
2329                                 action = 1;
2330                                 done = 1;
2331                         } else if (entry->port_type & port->port_type) {
2332                                 /*
2333                                  * Compare the user's type mask with the
2334                                  * particular frontend type to see if we
2335                                  * have a match.
2336                                  */
2337                                 action = 1;
2338                                 done = 0;
2339
2340                                 /*
2341                                  * Make sure the user isn't trying to set
2342                                  * WWNs on multiple ports at the same time.
2343                                  */
2344                                 if (cmd == CTL_SET_PORT_WWNS) {
2345                                         printf("%s: Can't set WWNs on "
2346                                                "multiple ports\n", __func__);
2347                                         retval = EINVAL;
2348                                         break;
2349                                 }
2350                         }
2351                         if (action != 0) {
2352                                 /*
2353                                  * XXX KDM we have to drop the lock here,
2354                                  * because the online/offline operations
2355                                  * can potentially block.  We need to
2356                                  * reference count the frontends so they
2357                                  * can't go away,
2358                                  */
2359                                 mtx_unlock(&softc->ctl_lock);
2360
2361                                 if (cmd == CTL_ENABLE_PORT) {
2362                                         struct ctl_lun *lun;
2363
2364                                         STAILQ_FOREACH(lun, &softc->lun_list,
2365                                                        links) {
2366                                                 port->lun_enable(port->targ_lun_arg,
2367                                                     lun->target,
2368                                                     lun->lun);
2369                                         }
2370
2371                                         ctl_port_online(port);
2372                                 } else if (cmd == CTL_DISABLE_PORT) {
2373                                         struct ctl_lun *lun;
2374
2375                                         ctl_port_offline(port);
2376
2377                                         STAILQ_FOREACH(lun, &softc->lun_list,
2378                                                        links) {
2379                                                 port->lun_disable(
2380                                                     port->targ_lun_arg,
2381                                                     lun->target,
2382                                                     lun->lun);
2383                                         }
2384                                 }
2385
2386                                 mtx_lock(&softc->ctl_lock);
2387
2388                                 if (cmd == CTL_SET_PORT_WWNS)
2389                                         ctl_port_set_wwns(port,
2390                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2391                                             1 : 0, entry->wwnn,
2392                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2393                                             1 : 0, entry->wwpn);
2394                         }
2395                         if (done != 0)
2396                                 break;
2397                 }
2398                 mtx_unlock(&softc->ctl_lock);
2399                 break;
2400         }
2401         case CTL_GET_PORT_LIST: {
2402                 struct ctl_port *port;
2403                 struct ctl_port_list *list;
2404                 int i;
2405
2406                 list = (struct ctl_port_list *)addr;
2407
2408                 if (list->alloc_len != (list->alloc_num *
2409                     sizeof(struct ctl_port_entry))) {
2410                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2411                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2412                                "%zu\n", __func__, list->alloc_len,
2413                                list->alloc_num, sizeof(struct ctl_port_entry));
2414                         retval = EINVAL;
2415                         break;
2416                 }
2417                 list->fill_len = 0;
2418                 list->fill_num = 0;
2419                 list->dropped_num = 0;
2420                 i = 0;
2421                 mtx_lock(&softc->ctl_lock);
2422                 STAILQ_FOREACH(port, &softc->port_list, links) {
2423                         struct ctl_port_entry entry, *list_entry;
2424
2425                         if (list->fill_num >= list->alloc_num) {
2426                                 list->dropped_num++;
2427                                 continue;
2428                         }
2429
2430                         entry.port_type = port->port_type;
2431                         strlcpy(entry.port_name, port->port_name,
2432                                 sizeof(entry.port_name));
2433                         entry.targ_port = port->targ_port;
2434                         entry.physical_port = port->physical_port;
2435                         entry.virtual_port = port->virtual_port;
2436                         entry.wwnn = port->wwnn;
2437                         entry.wwpn = port->wwpn;
2438                         if (port->status & CTL_PORT_STATUS_ONLINE)
2439                                 entry.online = 1;
2440                         else
2441                                 entry.online = 0;
2442
2443                         list_entry = &list->entries[i];
2444
2445                         retval = copyout(&entry, list_entry, sizeof(entry));
2446                         if (retval != 0) {
2447                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2448                                        "returned %d\n", __func__, retval);
2449                                 break;
2450                         }
2451                         i++;
2452                         list->fill_num++;
2453                         list->fill_len += sizeof(entry);
2454                 }
2455                 mtx_unlock(&softc->ctl_lock);
2456
2457                 /*
2458                  * If this is non-zero, we had a copyout fault, so there's
2459                  * probably no point in attempting to set the status inside
2460                  * the structure.
2461                  */
2462                 if (retval != 0)
2463                         break;
2464
2465                 if (list->dropped_num > 0)
2466                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2467                 else
2468                         list->status = CTL_PORT_LIST_OK;
2469                 break;
2470         }
2471         case CTL_DUMP_OOA: {
2472                 struct ctl_lun *lun;
2473                 union ctl_io *io;
2474                 char printbuf[128];
2475                 struct sbuf sb;
2476
2477                 mtx_lock(&softc->ctl_lock);
2478                 printf("Dumping OOA queues:\n");
2479                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2480                         mtx_lock(&lun->lun_lock);
2481                         for (io = (union ctl_io *)TAILQ_FIRST(
2482                              &lun->ooa_queue); io != NULL;
2483                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2484                              ooa_links)) {
2485                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2486                                          SBUF_FIXEDLEN);
2487                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2488                                             (intmax_t)lun->lun,
2489                                             io->scsiio.tag_num,
2490                                             (io->io_hdr.flags &
2491                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2492                                             (io->io_hdr.flags &
2493                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2494                                             (io->io_hdr.flags &
2495                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2496                                             (io->io_hdr.flags &
2497                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2498                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2499                                 sbuf_finish(&sb);
2500                                 printf("%s\n", sbuf_data(&sb));
2501                         }
2502                         mtx_unlock(&lun->lun_lock);
2503                 }
2504                 printf("OOA queues dump done\n");
2505                 mtx_unlock(&softc->ctl_lock);
2506                 break;
2507         }
2508         case CTL_GET_OOA: {
2509                 struct ctl_lun *lun;
2510                 struct ctl_ooa *ooa_hdr;
2511                 struct ctl_ooa_entry *entries;
2512                 uint32_t cur_fill_num;
2513
2514                 ooa_hdr = (struct ctl_ooa *)addr;
2515
2516                 if ((ooa_hdr->alloc_len == 0)
2517                  || (ooa_hdr->alloc_num == 0)) {
2518                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2519                                "must be non-zero\n", __func__,
2520                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2521                         retval = EINVAL;
2522                         break;
2523                 }
2524
2525                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2526                     sizeof(struct ctl_ooa_entry))) {
2527                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2528                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2529                                __func__, ooa_hdr->alloc_len,
2530                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2531                         retval = EINVAL;
2532                         break;
2533                 }
2534
2535                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2536                 if (entries == NULL) {
2537                         printf("%s: could not allocate %d bytes for OOA "
2538                                "dump\n", __func__, ooa_hdr->alloc_len);
2539                         retval = ENOMEM;
2540                         break;
2541                 }
2542
2543                 mtx_lock(&softc->ctl_lock);
2544                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2545                  && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2546                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2547                         mtx_unlock(&softc->ctl_lock);
2548                         free(entries, M_CTL);
2549                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2550                                __func__, (uintmax_t)ooa_hdr->lun_num);
2551                         retval = EINVAL;
2552                         break;
2553                 }
2554
2555                 cur_fill_num = 0;
2556
2557                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2558                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2559                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2560                                         ooa_hdr, entries);
2561                                 if (retval != 0)
2562                                         break;
2563                         }
2564                         if (retval != 0) {
2565                                 mtx_unlock(&softc->ctl_lock);
2566                                 free(entries, M_CTL);
2567                                 break;
2568                         }
2569                 } else {
2570                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2571
2572                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2573                                                     entries);
2574                 }
2575                 mtx_unlock(&softc->ctl_lock);
2576
2577                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2578                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2579                         sizeof(struct ctl_ooa_entry);
2580                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2581                 if (retval != 0) {
2582                         printf("%s: error copying out %d bytes for OOA dump\n", 
2583                                __func__, ooa_hdr->fill_len);
2584                 }
2585
2586                 getbintime(&ooa_hdr->cur_bt);
2587
2588                 if (cur_fill_num > ooa_hdr->alloc_num) {
2589                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2590                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2591                 } else {
2592                         ooa_hdr->dropped_num = 0;
2593                         ooa_hdr->status = CTL_OOA_OK;
2594                 }
2595
2596                 free(entries, M_CTL);
2597                 break;
2598         }
2599         case CTL_CHECK_OOA: {
2600                 union ctl_io *io;
2601                 struct ctl_lun *lun;
2602                 struct ctl_ooa_info *ooa_info;
2603
2604
2605                 ooa_info = (struct ctl_ooa_info *)addr;
2606
2607                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2608                         ooa_info->status = CTL_OOA_INVALID_LUN;
2609                         break;
2610                 }
2611                 mtx_lock(&softc->ctl_lock);
2612                 lun = softc->ctl_luns[ooa_info->lun_id];
2613                 if (lun == NULL) {
2614                         mtx_unlock(&softc->ctl_lock);
2615                         ooa_info->status = CTL_OOA_INVALID_LUN;
2616                         break;
2617                 }
2618                 mtx_lock(&lun->lun_lock);
2619                 mtx_unlock(&softc->ctl_lock);
2620                 ooa_info->num_entries = 0;
2621                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2622                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2623                      &io->io_hdr, ooa_links)) {
2624                         ooa_info->num_entries++;
2625                 }
2626                 mtx_unlock(&lun->lun_lock);
2627
2628                 ooa_info->status = CTL_OOA_SUCCESS;
2629
2630                 break;
2631         }
2632         case CTL_HARD_START:
2633         case CTL_HARD_STOP: {
2634                 struct ctl_fe_ioctl_startstop_info ss_info;
2635                 struct cfi_metatask *metatask;
2636                 struct mtx hs_mtx;
2637
2638                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2639
2640                 cv_init(&ss_info.sem, "hard start/stop cv" );
2641
2642                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2643                 if (metatask == NULL) {
2644                         retval = ENOMEM;
2645                         mtx_destroy(&hs_mtx);
2646                         break;
2647                 }
2648
2649                 if (cmd == CTL_HARD_START)
2650                         metatask->tasktype = CFI_TASK_STARTUP;
2651                 else
2652                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2653
2654                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2655                 metatask->callback_arg = &ss_info;
2656
2657                 cfi_action(metatask);
2658
2659                 /* Wait for the callback */
2660                 mtx_lock(&hs_mtx);
2661                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2662                 mtx_unlock(&hs_mtx);
2663
2664                 /*
2665                  * All information has been copied from the metatask by the
2666                  * time cv_broadcast() is called, so we free the metatask here.
2667                  */
2668                 cfi_free_metatask(metatask);
2669
2670                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2671
2672                 mtx_destroy(&hs_mtx);
2673                 break;
2674         }
2675         case CTL_BBRREAD: {
2676                 struct ctl_bbrread_info *bbr_info;
2677                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2678                 struct mtx bbr_mtx;
2679                 struct cfi_metatask *metatask;
2680
2681                 bbr_info = (struct ctl_bbrread_info *)addr;
2682
2683                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2684
2685                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2686                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2687
2688                 fe_bbr_info.bbr_info = bbr_info;
2689                 fe_bbr_info.lock = &bbr_mtx;
2690
2691                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2692                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2693
2694                 if (metatask == NULL) {
2695                         mtx_destroy(&bbr_mtx);
2696                         cv_destroy(&fe_bbr_info.sem);
2697                         retval = ENOMEM;
2698                         break;
2699                 }
2700                 metatask->tasktype = CFI_TASK_BBRREAD;
2701                 metatask->callback = ctl_ioctl_bbrread_callback;
2702                 metatask->callback_arg = &fe_bbr_info;
2703                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2704                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2705                 metatask->taskinfo.bbrread.len = bbr_info->len;
2706
2707                 cfi_action(metatask);
2708
2709                 mtx_lock(&bbr_mtx);
2710                 while (fe_bbr_info.wakeup_done == 0)
2711                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2712                 mtx_unlock(&bbr_mtx);
2713
2714                 bbr_info->status = metatask->status;
2715                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2716                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2717                 memcpy(&bbr_info->sense_data,
2718                        &metatask->taskinfo.bbrread.sense_data,
2719                        ctl_min(sizeof(bbr_info->sense_data),
2720                                sizeof(metatask->taskinfo.bbrread.sense_data)));
2721
2722                 cfi_free_metatask(metatask);
2723
2724                 mtx_destroy(&bbr_mtx);
2725                 cv_destroy(&fe_bbr_info.sem);
2726
2727                 break;
2728         }
2729         case CTL_DELAY_IO: {
2730                 struct ctl_io_delay_info *delay_info;
2731 #ifdef CTL_IO_DELAY
2732                 struct ctl_lun *lun;
2733 #endif /* CTL_IO_DELAY */
2734
2735                 delay_info = (struct ctl_io_delay_info *)addr;
2736
2737 #ifdef CTL_IO_DELAY
2738                 mtx_lock(&softc->ctl_lock);
2739
2740                 if ((delay_info->lun_id > CTL_MAX_LUNS)
2741                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2742                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2743                 } else {
2744                         lun = softc->ctl_luns[delay_info->lun_id];
2745                         mtx_lock(&lun->lun_lock);
2746
2747                         delay_info->status = CTL_DELAY_STATUS_OK;
2748
2749                         switch (delay_info->delay_type) {
2750                         case CTL_DELAY_TYPE_CONT:
2751                                 break;
2752                         case CTL_DELAY_TYPE_ONESHOT:
2753                                 break;
2754                         default:
2755                                 delay_info->status =
2756                                         CTL_DELAY_STATUS_INVALID_TYPE;
2757                                 break;
2758                         }
2759
2760                         switch (delay_info->delay_loc) {
2761                         case CTL_DELAY_LOC_DATAMOVE:
2762                                 lun->delay_info.datamove_type =
2763                                         delay_info->delay_type;
2764                                 lun->delay_info.datamove_delay =
2765                                         delay_info->delay_secs;
2766                                 break;
2767                         case CTL_DELAY_LOC_DONE:
2768                                 lun->delay_info.done_type =
2769                                         delay_info->delay_type;
2770                                 lun->delay_info.done_delay =
2771                                         delay_info->delay_secs;
2772                                 break;
2773                         default:
2774                                 delay_info->status =
2775                                         CTL_DELAY_STATUS_INVALID_LOC;
2776                                 break;
2777                         }
2778                         mtx_unlock(&lun->lun_lock);
2779                 }
2780
2781                 mtx_unlock(&softc->ctl_lock);
2782 #else
2783                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2784 #endif /* CTL_IO_DELAY */
2785                 break;
2786         }
2787         case CTL_REALSYNC_SET: {
2788                 int *syncstate;
2789
2790                 syncstate = (int *)addr;
2791
2792                 mtx_lock(&softc->ctl_lock);
2793                 switch (*syncstate) {
2794                 case 0:
2795                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2796                         break;
2797                 case 1:
2798                         softc->flags |= CTL_FLAG_REAL_SYNC;
2799                         break;
2800                 default:
2801                         retval = EINVAL;
2802                         break;
2803                 }
2804                 mtx_unlock(&softc->ctl_lock);
2805                 break;
2806         }
2807         case CTL_REALSYNC_GET: {
2808                 int *syncstate;
2809
2810                 syncstate = (int*)addr;
2811
2812                 mtx_lock(&softc->ctl_lock);
2813                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2814                         *syncstate = 1;
2815                 else
2816                         *syncstate = 0;
2817                 mtx_unlock(&softc->ctl_lock);
2818
2819                 break;
2820         }
2821         case CTL_SETSYNC:
2822         case CTL_GETSYNC: {
2823                 struct ctl_sync_info *sync_info;
2824                 struct ctl_lun *lun;
2825
2826                 sync_info = (struct ctl_sync_info *)addr;
2827
2828                 mtx_lock(&softc->ctl_lock);
2829                 lun = softc->ctl_luns[sync_info->lun_id];
2830                 if (lun == NULL) {
2831                         mtx_unlock(&softc->ctl_lock);
2832                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2833                 }
2834                 /*
2835                  * Get or set the sync interval.  We're not bounds checking
2836                  * in the set case, hopefully the user won't do something
2837                  * silly.
2838                  */
2839                 mtx_lock(&lun->lun_lock);
2840                 mtx_unlock(&softc->ctl_lock);
2841                 if (cmd == CTL_GETSYNC)
2842                         sync_info->sync_interval = lun->sync_interval;
2843                 else
2844                         lun->sync_interval = sync_info->sync_interval;
2845                 mtx_unlock(&lun->lun_lock);
2846
2847                 sync_info->status = CTL_GS_SYNC_OK;
2848
2849                 break;
2850         }
2851         case CTL_GETSTATS: {
2852                 struct ctl_stats *stats;
2853                 struct ctl_lun *lun;
2854                 int i;
2855
2856                 stats = (struct ctl_stats *)addr;
2857
2858                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2859                      stats->alloc_len) {
2860                         stats->status = CTL_SS_NEED_MORE_SPACE;
2861                         stats->num_luns = softc->num_luns;
2862                         break;
2863                 }
2864                 /*
2865                  * XXX KDM no locking here.  If the LUN list changes,
2866                  * things can blow up.
2867                  */
2868                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2869                      i++, lun = STAILQ_NEXT(lun, links)) {
2870                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2871                                          sizeof(lun->stats));
2872                         if (retval != 0)
2873                                 break;
2874                 }
2875                 stats->num_luns = softc->num_luns;
2876                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2877                                  softc->num_luns;
2878                 stats->status = CTL_SS_OK;
2879 #ifdef CTL_TIME_IO
2880                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2881 #else
2882                 stats->flags = CTL_STATS_FLAG_NONE;
2883 #endif
2884                 getnanouptime(&stats->timestamp);
2885                 break;
2886         }
2887         case CTL_ERROR_INJECT: {
2888                 struct ctl_error_desc *err_desc, *new_err_desc;
2889                 struct ctl_lun *lun;
2890
2891                 err_desc = (struct ctl_error_desc *)addr;
2892
2893                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2894                                       M_WAITOK | M_ZERO);
2895                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2896
2897                 mtx_lock(&softc->ctl_lock);
2898                 lun = softc->ctl_luns[err_desc->lun_id];
2899                 if (lun == NULL) {
2900                         mtx_unlock(&softc->ctl_lock);
2901                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2902                                __func__, (uintmax_t)err_desc->lun_id);
2903                         retval = EINVAL;
2904                         break;
2905                 }
2906                 mtx_lock(&lun->lun_lock);
2907                 mtx_unlock(&softc->ctl_lock);
2908
2909                 /*
2910                  * We could do some checking here to verify the validity
2911                  * of the request, but given the complexity of error
2912                  * injection requests, the checking logic would be fairly
2913                  * complex.
2914                  *
2915                  * For now, if the request is invalid, it just won't get
2916                  * executed and might get deleted.
2917                  */
2918                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2919
2920                 /*
2921                  * XXX KDM check to make sure the serial number is unique,
2922                  * in case we somehow manage to wrap.  That shouldn't
2923                  * happen for a very long time, but it's the right thing to
2924                  * do.
2925                  */
2926                 new_err_desc->serial = lun->error_serial;
2927                 err_desc->serial = lun->error_serial;
2928                 lun->error_serial++;
2929
2930                 mtx_unlock(&lun->lun_lock);
2931                 break;
2932         }
2933         case CTL_ERROR_INJECT_DELETE: {
2934                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2935                 struct ctl_lun *lun;
2936                 int delete_done;
2937
2938                 delete_desc = (struct ctl_error_desc *)addr;
2939                 delete_done = 0;
2940
2941                 mtx_lock(&softc->ctl_lock);
2942                 lun = softc->ctl_luns[delete_desc->lun_id];
2943                 if (lun == NULL) {
2944                         mtx_unlock(&softc->ctl_lock);
2945                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2946                                __func__, (uintmax_t)delete_desc->lun_id);
2947                         retval = EINVAL;
2948                         break;
2949                 }
2950                 mtx_lock(&lun->lun_lock);
2951                 mtx_unlock(&softc->ctl_lock);
2952                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2953                         if (desc->serial != delete_desc->serial)
2954                                 continue;
2955
2956                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2957                                       links);
2958                         free(desc, M_CTL);
2959                         delete_done = 1;
2960                 }
2961                 mtx_unlock(&lun->lun_lock);
2962                 if (delete_done == 0) {
2963                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2964                                "error serial %ju on LUN %u\n", __func__, 
2965                                delete_desc->serial, delete_desc->lun_id);
2966                         retval = EINVAL;
2967                         break;
2968                 }
2969                 break;
2970         }
2971         case CTL_DUMP_STRUCTS: {
2972                 int i, j, k, idx;
2973                 struct ctl_port *port;
2974                 struct ctl_frontend *fe;
2975
2976                 mtx_lock(&softc->ctl_lock);
2977                 printf("CTL Persistent Reservation information start:\n");
2978                 for (i = 0; i < CTL_MAX_LUNS; i++) {
2979                         struct ctl_lun *lun;
2980
2981                         lun = softc->ctl_luns[i];
2982
2983                         if ((lun == NULL)
2984                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
2985                                 continue;
2986
2987                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2988                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2989                                         idx = j * CTL_MAX_INIT_PER_PORT + k;
2990                                         if (lun->per_res[idx].registered == 0)
2991                                                 continue;
2992                                         printf("  LUN %d port %d iid %d key "
2993                                                "%#jx\n", i, j, k,
2994                                                (uintmax_t)scsi_8btou64(
2995                                                lun->per_res[idx].res_key.key));
2996                                 }
2997                         }
2998                 }
2999                 printf("CTL Persistent Reservation information end\n");
3000                 printf("CTL Ports:\n");
3001                 STAILQ_FOREACH(port, &softc->port_list, links) {
3002                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3003                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3004                                port->frontend->name, port->port_type,
3005                                port->physical_port, port->virtual_port,
3006                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3007                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3008                                 if (port->wwpn_iid[j].in_use == 0 &&
3009                                     port->wwpn_iid[j].wwpn == 0 &&
3010                                     port->wwpn_iid[j].name == NULL)
3011                                         continue;
3012
3013                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3014                                     j, port->wwpn_iid[j].in_use,
3015                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3016                                     port->wwpn_iid[j].name);
3017                         }
3018                 }
3019                 printf("CTL Port information end\n");
3020                 mtx_unlock(&softc->ctl_lock);
3021                 /*
3022                  * XXX KDM calling this without a lock.  We'd likely want
3023                  * to drop the lock before calling the frontend's dump
3024                  * routine anyway.
3025                  */
3026                 printf("CTL Frontends:\n");
3027                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3028                         printf("  Frontend '%s'\n", fe->name);
3029                         if (fe->fe_dump != NULL)
3030                                 fe->fe_dump();
3031                 }
3032                 printf("CTL Frontend information end\n");
3033                 break;
3034         }
3035         case CTL_LUN_REQ: {
3036                 struct ctl_lun_req *lun_req;
3037                 struct ctl_backend_driver *backend;
3038
3039                 lun_req = (struct ctl_lun_req *)addr;
3040
3041                 backend = ctl_backend_find(lun_req->backend);
3042                 if (backend == NULL) {
3043                         lun_req->status = CTL_LUN_ERROR;
3044                         snprintf(lun_req->error_str,
3045                                  sizeof(lun_req->error_str),
3046                                  "Backend \"%s\" not found.",
3047                                  lun_req->backend);
3048                         break;
3049                 }
3050                 if (lun_req->num_be_args > 0) {
3051                         lun_req->kern_be_args = ctl_copyin_args(
3052                                 lun_req->num_be_args,
3053                                 lun_req->be_args,
3054                                 lun_req->error_str,
3055                                 sizeof(lun_req->error_str));
3056                         if (lun_req->kern_be_args == NULL) {
3057                                 lun_req->status = CTL_LUN_ERROR;
3058                                 break;
3059                         }
3060                 }
3061
3062                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3063
3064                 if (lun_req->num_be_args > 0) {
3065                         ctl_copyout_args(lun_req->num_be_args,
3066                                       lun_req->kern_be_args);
3067                         ctl_free_args(lun_req->num_be_args,
3068                                       lun_req->kern_be_args);
3069                 }
3070                 break;
3071         }
3072         case CTL_LUN_LIST: {
3073                 struct sbuf *sb;
3074                 struct ctl_lun *lun;
3075                 struct ctl_lun_list *list;
3076                 struct ctl_option *opt;
3077
3078                 list = (struct ctl_lun_list *)addr;
3079
3080                 /*
3081                  * Allocate a fixed length sbuf here, based on the length
3082                  * of the user's buffer.  We could allocate an auto-extending
3083                  * buffer, and then tell the user how much larger our
3084                  * amount of data is than his buffer, but that presents
3085                  * some problems:
3086                  *
3087                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3088                  *     we can't hold a lock while calling them with an
3089                  *     auto-extending buffer.
3090                  *
3091                  * 2.  There is not currently a LUN reference counting
3092                  *     mechanism, outside of outstanding transactions on
3093                  *     the LUN's OOA queue.  So a LUN could go away on us
3094                  *     while we're getting the LUN number, backend-specific
3095                  *     information, etc.  Thus, given the way things
3096                  *     currently work, we need to hold the CTL lock while
3097                  *     grabbing LUN information.
3098                  *
3099                  * So, from the user's standpoint, the best thing to do is
3100                  * allocate what he thinks is a reasonable buffer length,
3101                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3102                  * double the buffer length and try again.  (And repeat
3103                  * that until he succeeds.)
3104                  */
3105                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3106                 if (sb == NULL) {
3107                         list->status = CTL_LUN_LIST_ERROR;
3108                         snprintf(list->error_str, sizeof(list->error_str),
3109                                  "Unable to allocate %d bytes for LUN list",
3110                                  list->alloc_len);
3111                         break;
3112                 }
3113
3114                 sbuf_printf(sb, "<ctllunlist>\n");
3115
3116                 mtx_lock(&softc->ctl_lock);
3117                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3118                         mtx_lock(&lun->lun_lock);
3119                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3120                                              (uintmax_t)lun->lun);
3121
3122                         /*
3123                          * Bail out as soon as we see that we've overfilled
3124                          * the buffer.
3125                          */
3126                         if (retval != 0)
3127                                 break;
3128
3129                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3130                                              "</backend_type>\n",
3131                                              (lun->backend == NULL) ?  "none" :
3132                                              lun->backend->name);
3133
3134                         if (retval != 0)
3135                                 break;
3136
3137                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3138                                              lun->be_lun->lun_type);
3139
3140                         if (retval != 0)
3141                                 break;
3142
3143                         if (lun->backend == NULL) {
3144                                 retval = sbuf_printf(sb, "</lun>\n");
3145                                 if (retval != 0)
3146                                         break;
3147                                 continue;
3148                         }
3149
3150                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3151                                              (lun->be_lun->maxlba > 0) ?
3152                                              lun->be_lun->maxlba + 1 : 0);
3153
3154                         if (retval != 0)
3155                                 break;
3156
3157                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3158                                              lun->be_lun->blocksize);
3159
3160                         if (retval != 0)
3161                                 break;
3162
3163                         retval = sbuf_printf(sb, "\t<serial_number>");
3164
3165                         if (retval != 0)
3166                                 break;
3167
3168                         retval = ctl_sbuf_printf_esc(sb,
3169                                                      lun->be_lun->serial_num);
3170
3171                         if (retval != 0)
3172                                 break;
3173
3174                         retval = sbuf_printf(sb, "</serial_number>\n");
3175                 
3176                         if (retval != 0)
3177                                 break;
3178
3179                         retval = sbuf_printf(sb, "\t<device_id>");
3180
3181                         if (retval != 0)
3182                                 break;
3183
3184                         retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3185
3186                         if (retval != 0)
3187                                 break;
3188
3189                         retval = sbuf_printf(sb, "</device_id>\n");
3190
3191                         if (retval != 0)
3192                                 break;
3193
3194                         if (lun->backend->lun_info != NULL) {
3195                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3196                                 if (retval != 0)
3197                                         break;
3198                         }
3199                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3200                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3201                                     opt->name, opt->value, opt->name);
3202                                 if (retval != 0)
3203                                         break;
3204                         }
3205
3206                         retval = sbuf_printf(sb, "</lun>\n");
3207
3208                         if (retval != 0)
3209                                 break;
3210                         mtx_unlock(&lun->lun_lock);
3211                 }
3212                 if (lun != NULL)
3213                         mtx_unlock(&lun->lun_lock);
3214                 mtx_unlock(&softc->ctl_lock);
3215
3216                 if ((retval != 0)
3217                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3218                         retval = 0;
3219                         sbuf_delete(sb);
3220                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3221                         snprintf(list->error_str, sizeof(list->error_str),
3222                                  "Out of space, %d bytes is too small",
3223                                  list->alloc_len);
3224                         break;
3225                 }
3226
3227                 sbuf_finish(sb);
3228
3229                 retval = copyout(sbuf_data(sb), list->lun_xml,
3230                                  sbuf_len(sb) + 1);
3231
3232                 list->fill_len = sbuf_len(sb) + 1;
3233                 list->status = CTL_LUN_LIST_OK;
3234                 sbuf_delete(sb);
3235                 break;
3236         }
3237         case CTL_ISCSI: {
3238                 struct ctl_iscsi *ci;
3239                 struct ctl_frontend *fe;
3240
3241                 ci = (struct ctl_iscsi *)addr;
3242
3243                 fe = ctl_frontend_find("iscsi");
3244                 if (fe == NULL) {
3245                         ci->status = CTL_ISCSI_ERROR;
3246                         snprintf(ci->error_str, sizeof(ci->error_str),
3247                             "Frontend \"iscsi\" not found.");
3248                         break;
3249                 }
3250
3251                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3252                 break;
3253         }
3254         case CTL_PORT_REQ: {
3255                 struct ctl_req *req;
3256                 struct ctl_frontend *fe;
3257
3258                 req = (struct ctl_req *)addr;
3259
3260                 fe = ctl_frontend_find(req->driver);
3261                 if (fe == NULL) {
3262                         req->status = CTL_LUN_ERROR;
3263                         snprintf(req->error_str, sizeof(req->error_str),
3264                             "Frontend \"%s\" not found.", req->driver);
3265                         break;
3266                 }
3267                 if (req->num_args > 0) {
3268                         req->kern_args = ctl_copyin_args(req->num_args,
3269                             req->args, req->error_str, sizeof(req->error_str));
3270                         if (req->kern_args == NULL) {
3271                                 req->status = CTL_LUN_ERROR;
3272                                 break;
3273                         }
3274                 }
3275
3276                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3277
3278                 if (req->num_args > 0) {
3279                         ctl_copyout_args(req->num_args, req->kern_args);
3280                         ctl_free_args(req->num_args, req->kern_args);
3281                 }
3282                 break;
3283         }
3284         case CTL_PORT_LIST: {
3285                 struct sbuf *sb;
3286                 struct ctl_port *port;
3287                 struct ctl_lun_list *list;
3288                 struct ctl_option *opt;
3289
3290                 list = (struct ctl_lun_list *)addr;
3291
3292                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3293                 if (sb == NULL) {
3294                         list->status = CTL_LUN_LIST_ERROR;
3295                         snprintf(list->error_str, sizeof(list->error_str),
3296                                  "Unable to allocate %d bytes for LUN list",
3297                                  list->alloc_len);
3298                         break;
3299                 }
3300
3301                 sbuf_printf(sb, "<ctlportlist>\n");
3302
3303                 mtx_lock(&softc->ctl_lock);
3304                 STAILQ_FOREACH(port, &softc->port_list, links) {
3305                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3306                                              (uintmax_t)port->targ_port);
3307
3308                         /*
3309                          * Bail out as soon as we see that we've overfilled
3310                          * the buffer.
3311                          */
3312                         if (retval != 0)
3313                                 break;
3314
3315                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3316                             "</frontend_type>\n", port->frontend->name);
3317                         if (retval != 0)
3318                                 break;
3319
3320                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3321                                              port->port_type);
3322                         if (retval != 0)
3323                                 break;
3324
3325                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3326                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3327                         if (retval != 0)
3328                                 break;
3329
3330                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3331                             port->port_name);
3332                         if (retval != 0)
3333                                 break;
3334
3335                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3336                             port->physical_port);
3337                         if (retval != 0)
3338                                 break;
3339
3340                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3341                             port->virtual_port);
3342                         if (retval != 0)
3343                                 break;
3344
3345                         retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3346                             (uintmax_t)port->wwnn);
3347                         if (retval != 0)
3348                                 break;
3349
3350                         retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3351                             (uintmax_t)port->wwpn);
3352                         if (retval != 0)
3353                                 break;
3354
3355                         if (port->port_info != NULL) {
3356                                 retval = port->port_info(port->onoff_arg, sb);
3357                                 if (retval != 0)
3358                                         break;
3359                         }
3360                         STAILQ_FOREACH(opt, &port->options, links) {
3361                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3362                                     opt->name, opt->value, opt->name);
3363                                 if (retval != 0)
3364                                         break;
3365                         }
3366
3367                         retval = sbuf_printf(sb, "</targ_port>\n");
3368                         if (retval != 0)
3369                                 break;
3370                 }
3371                 mtx_unlock(&softc->ctl_lock);
3372
3373                 if ((retval != 0)
3374                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3375                         retval = 0;
3376                         sbuf_delete(sb);
3377                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3378                         snprintf(list->error_str, sizeof(list->error_str),
3379                                  "Out of space, %d bytes is too small",
3380                                  list->alloc_len);
3381                         break;
3382                 }
3383
3384                 sbuf_finish(sb);
3385
3386                 retval = copyout(sbuf_data(sb), list->lun_xml,
3387                                  sbuf_len(sb) + 1);
3388
3389                 list->fill_len = sbuf_len(sb) + 1;
3390                 list->status = CTL_LUN_LIST_OK;
3391                 sbuf_delete(sb);
3392                 break;
3393         }
3394         default: {
3395                 /* XXX KDM should we fix this? */
3396 #if 0
3397                 struct ctl_backend_driver *backend;
3398                 unsigned int type;
3399                 int found;
3400
3401                 found = 0;
3402
3403                 /*
3404                  * We encode the backend type as the ioctl type for backend
3405                  * ioctls.  So parse it out here, and then search for a
3406                  * backend of this type.
3407                  */
3408                 type = _IOC_TYPE(cmd);
3409
3410                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3411                         if (backend->type == type) {
3412                                 found = 1;
3413                                 break;
3414                         }
3415                 }
3416                 if (found == 0) {
3417                         printf("ctl: unknown ioctl command %#lx or backend "
3418                                "%d\n", cmd, type);
3419                         retval = EINVAL;
3420                         break;
3421                 }
3422                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3423 #endif
3424                 retval = ENOTTY;
3425                 break;
3426         }
3427         }
3428         return (retval);
3429 }
3430
3431 uint32_t
3432 ctl_get_initindex(struct ctl_nexus *nexus)
3433 {
3434         if (nexus->targ_port < CTL_MAX_PORTS)
3435                 return (nexus->initid.id +
3436                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3437         else
3438                 return (nexus->initid.id +
3439                        ((nexus->targ_port - CTL_MAX_PORTS) *
3440                         CTL_MAX_INIT_PER_PORT));
3441 }
3442
3443 uint32_t
3444 ctl_get_resindex(struct ctl_nexus *nexus)
3445 {
3446         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3447 }
3448
3449 uint32_t
3450 ctl_port_idx(int port_num)
3451 {
3452         if (port_num < CTL_MAX_PORTS)
3453                 return(port_num);
3454         else
3455                 return(port_num - CTL_MAX_PORTS);
3456 }
3457
3458 static uint32_t
3459 ctl_map_lun(int port_num, uint32_t lun_id)
3460 {
3461         struct ctl_port *port;
3462
3463         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3464         if (port == NULL)
3465                 return (UINT32_MAX);
3466         if (port->lun_map == NULL)
3467                 return (lun_id);
3468         return (port->lun_map(port->targ_lun_arg, lun_id));
3469 }
3470
3471 static uint32_t
3472 ctl_map_lun_back(int port_num, uint32_t lun_id)
3473 {
3474         struct ctl_port *port;
3475         uint32_t i;
3476
3477         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3478         if (port->lun_map == NULL)
3479                 return (lun_id);
3480         for (i = 0; i < CTL_MAX_LUNS; i++) {
3481                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3482                         return (i);
3483         }
3484         return (UINT32_MAX);
3485 }
3486
3487 /*
3488  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3489  * that are a power of 2.
3490  */
3491 int
3492 ctl_ffz(uint32_t *mask, uint32_t size)
3493 {
3494         uint32_t num_chunks, num_pieces;
3495         int i, j;
3496
3497         num_chunks = (size >> 5);
3498         if (num_chunks == 0)
3499                 num_chunks++;
3500         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3501
3502         for (i = 0; i < num_chunks; i++) {
3503                 for (j = 0; j < num_pieces; j++) {
3504                         if ((mask[i] & (1 << j)) == 0)
3505                                 return ((i << 5) + j);
3506                 }
3507         }
3508
3509         return (-1);
3510 }
3511
3512 int
3513 ctl_set_mask(uint32_t *mask, uint32_t bit)
3514 {
3515         uint32_t chunk, piece;
3516
3517         chunk = bit >> 5;
3518         piece = bit % (sizeof(uint32_t) * 8);
3519
3520         if ((mask[chunk] & (1 << piece)) != 0)
3521                 return (-1);
3522         else
3523                 mask[chunk] |= (1 << piece);
3524
3525         return (0);
3526 }
3527
3528 int
3529 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3530 {
3531         uint32_t chunk, piece;
3532
3533         chunk = bit >> 5;
3534         piece = bit % (sizeof(uint32_t) * 8);
3535
3536         if ((mask[chunk] & (1 << piece)) == 0)
3537                 return (-1);
3538         else
3539                 mask[chunk] &= ~(1 << piece);
3540
3541         return (0);
3542 }
3543
3544 int
3545 ctl_is_set(uint32_t *mask, uint32_t bit)
3546 {
3547         uint32_t chunk, piece;
3548
3549         chunk = bit >> 5;
3550         piece = bit % (sizeof(uint32_t) * 8);
3551
3552         if ((mask[chunk] & (1 << piece)) == 0)
3553                 return (0);
3554         else
3555                 return (1);
3556 }
3557
3558 #ifdef unused
3559 /*
3560  * The bus, target and lun are optional, they can be filled in later.
3561  * can_wait is used to determine whether we can wait on the malloc or not.
3562  */
3563 union ctl_io*
3564 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3565               uint32_t targ_lun, int can_wait)
3566 {
3567         union ctl_io *io;
3568
3569         if (can_wait)
3570                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3571         else
3572                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3573
3574         if (io != NULL) {
3575                 io->io_hdr.io_type = io_type;
3576                 io->io_hdr.targ_port = targ_port;
3577                 /*
3578                  * XXX KDM this needs to change/go away.  We need to move
3579                  * to a preallocated pool of ctl_scsiio structures.
3580                  */
3581                 io->io_hdr.nexus.targ_target.id = targ_target;
3582                 io->io_hdr.nexus.targ_lun = targ_lun;
3583         }
3584
3585         return (io);
3586 }
3587
3588 void
3589 ctl_kfree_io(union ctl_io *io)
3590 {
3591         free(io, M_CTL);
3592 }
3593 #endif /* unused */
3594
3595 /*
3596  * ctl_softc, pool_type, total_ctl_io are passed in.
3597  * npool is passed out.
3598  */
3599 int
3600 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3601                 uint32_t total_ctl_io, struct ctl_io_pool **npool)
3602 {
3603         uint32_t i;
3604         union ctl_io *cur_io, *next_io;
3605         struct ctl_io_pool *pool;
3606         int retval;
3607
3608         retval = 0;
3609
3610         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3611                                             M_NOWAIT | M_ZERO);
3612         if (pool == NULL) {
3613                 retval = ENOMEM;
3614                 goto bailout;
3615         }
3616
3617         pool->type = pool_type;
3618         pool->ctl_softc = ctl_softc;
3619
3620         mtx_lock(&ctl_softc->pool_lock);
3621         pool->id = ctl_softc->cur_pool_id++;
3622         mtx_unlock(&ctl_softc->pool_lock);
3623
3624         pool->flags = CTL_POOL_FLAG_NONE;
3625         pool->refcount = 1;             /* Reference for validity. */
3626         STAILQ_INIT(&pool->free_queue);
3627
3628         /*
3629          * XXX KDM other options here:
3630          * - allocate a page at a time
3631          * - allocate one big chunk of memory.
3632          * Page allocation might work well, but would take a little more
3633          * tracking.
3634          */
3635         for (i = 0; i < total_ctl_io; i++) {
3636                 cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3637                                                 M_NOWAIT);
3638                 if (cur_io == NULL) {
3639                         retval = ENOMEM;
3640                         break;
3641                 }
3642                 cur_io->io_hdr.pool = pool;
3643                 STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3644                 pool->total_ctl_io++;
3645                 pool->free_ctl_io++;
3646         }
3647
3648         if (retval != 0) {
3649                 for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3650                      cur_io != NULL; cur_io = next_io) {
3651                         next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3652                                                               links);
3653                         STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3654                                       ctl_io_hdr, links);
3655                         free(cur_io, M_CTLIO);
3656                 }
3657
3658                 free(pool, M_CTL);
3659                 goto bailout;
3660         }
3661         mtx_lock(&ctl_softc->pool_lock);
3662         ctl_softc->num_pools++;
3663         STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3664         /*
3665          * Increment our usage count if this is an external consumer, so we
3666          * can't get unloaded until the external consumer (most likely a
3667          * FETD) unloads and frees his pool.
3668          *
3669          * XXX KDM will this increment the caller's module use count, or
3670          * mine?
3671          */
3672 #if 0
3673         if ((pool_type != CTL_POOL_EMERGENCY)
3674          && (pool_type != CTL_POOL_INTERNAL)
3675          && (pool_type != CTL_POOL_4OTHERSC))
3676                 MOD_INC_USE_COUNT;
3677 #endif
3678
3679         mtx_unlock(&ctl_softc->pool_lock);
3680
3681         *npool = pool;
3682
3683 bailout:
3684
3685         return (retval);
3686 }
3687
3688 static int
3689 ctl_pool_acquire(struct ctl_io_pool *pool)
3690 {
3691
3692         mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3693
3694         if (pool->flags & CTL_POOL_FLAG_INVALID)
3695                 return (EINVAL);
3696
3697         pool->refcount++;
3698
3699         return (0);
3700 }
3701
3702 static void
3703 ctl_pool_release(struct ctl_io_pool *pool)
3704 {
3705         struct ctl_softc *ctl_softc = pool->ctl_softc;
3706         union ctl_io *io;
3707
3708         mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3709
3710         if (--pool->refcount != 0)
3711                 return;
3712
3713         while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3714                 STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3715                               links);
3716                 free(io, M_CTLIO);
3717         }
3718
3719         STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3720         ctl_softc->num_pools--;
3721
3722         /*
3723          * XXX KDM will this decrement the caller's usage count or mine?
3724          */
3725 #if 0
3726         if ((pool->type != CTL_POOL_EMERGENCY)
3727          && (pool->type != CTL_POOL_INTERNAL)
3728          && (pool->type != CTL_POOL_4OTHERSC))
3729                 MOD_DEC_USE_COUNT;
3730 #endif
3731
3732         free(pool, M_CTL);
3733 }
3734
3735 void
3736 ctl_pool_free(struct ctl_io_pool *pool)
3737 {
3738         struct ctl_softc *ctl_softc;
3739
3740         if (pool == NULL)
3741                 return;
3742
3743         ctl_softc = pool->ctl_softc;
3744         mtx_lock(&ctl_softc->pool_lock);
3745         pool->flags |= CTL_POOL_FLAG_INVALID;
3746         ctl_pool_release(pool);
3747         mtx_unlock(&ctl_softc->pool_lock);
3748 }
3749
3750 /*
3751  * This routine does not block (except for spinlocks of course).
3752  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3753  * possible.
3754  */
3755 union ctl_io *
3756 ctl_alloc_io(void *pool_ref)
3757 {
3758         union ctl_io *io;
3759         struct ctl_softc *ctl_softc;
3760         struct ctl_io_pool *pool, *npool;
3761         struct ctl_io_pool *emergency_pool;
3762
3763         pool = (struct ctl_io_pool *)pool_ref;
3764
3765         if (pool == NULL) {
3766                 printf("%s: pool is NULL\n", __func__);
3767                 return (NULL);
3768         }
3769
3770         emergency_pool = NULL;
3771
3772         ctl_softc = pool->ctl_softc;
3773
3774         mtx_lock(&ctl_softc->pool_lock);
3775         /*
3776          * First, try to get the io structure from the user's pool.
3777          */
3778         if (ctl_pool_acquire(pool) == 0) {
3779                 io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3780                 if (io != NULL) {
3781                         STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3782                         pool->total_allocated++;
3783                         pool->free_ctl_io--;
3784                         mtx_unlock(&ctl_softc->pool_lock);
3785                         return (io);
3786                 } else
3787                         ctl_pool_release(pool);
3788         }
3789         /*
3790          * If he doesn't have any io structures left, search for an
3791          * emergency pool and grab one from there.
3792          */
3793         STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3794                 if (npool->type != CTL_POOL_EMERGENCY)
3795                         continue;
3796
3797                 if (ctl_pool_acquire(npool) != 0)
3798                         continue;
3799
3800                 emergency_pool = npool;
3801
3802                 io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3803                 if (io != NULL) {
3804                         STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3805                         npool->total_allocated++;
3806                         npool->free_ctl_io--;
3807                         mtx_unlock(&ctl_softc->pool_lock);
3808                         return (io);
3809                 } else
3810                         ctl_pool_release(npool);
3811         }
3812
3813         /* Drop the spinlock before we malloc */
3814         mtx_unlock(&ctl_softc->pool_lock);
3815
3816         /*
3817          * The emergency pool (if it exists) didn't have one, so try an
3818          * atomic (i.e. nonblocking) malloc and see if we get lucky.
3819          */
3820         io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3821         if (io != NULL) {
3822                 /*
3823                  * If the emergency pool exists but is empty, add this
3824                  * ctl_io to its list when it gets freed.
3825                  */
3826                 if (emergency_pool != NULL) {
3827                         mtx_lock(&ctl_softc->pool_lock);
3828                         if (ctl_pool_acquire(emergency_pool) == 0) {
3829                                 io->io_hdr.pool = emergency_pool;
3830                                 emergency_pool->total_ctl_io++;
3831                                 /*
3832                                  * Need to bump this, otherwise
3833                                  * total_allocated and total_freed won't
3834                                  * match when we no longer have anything
3835                                  * outstanding.
3836                                  */
3837                                 emergency_pool->total_allocated++;
3838                         }
3839                         mtx_unlock(&ctl_softc->pool_lock);
3840                 } else
3841                         io->io_hdr.pool = NULL;
3842         }
3843
3844         return (io);
3845 }
3846
3847 void
3848 ctl_free_io(union ctl_io *io)
3849 {
3850         if (io == NULL)
3851                 return;
3852
3853         /*
3854          * If this ctl_io has a pool, return it to that pool.
3855          */
3856         if (io->io_hdr.pool != NULL) {
3857                 struct ctl_io_pool *pool;
3858
3859                 pool = (struct ctl_io_pool *)io->io_hdr.pool;
3860                 mtx_lock(&pool->ctl_softc->pool_lock);
3861                 io->io_hdr.io_type = 0xff;
3862                 STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3863                 pool->total_freed++;
3864                 pool->free_ctl_io++;
3865                 ctl_pool_release(pool);
3866                 mtx_unlock(&pool->ctl_softc->pool_lock);
3867         } else {
3868                 /*
3869                  * Otherwise, just free it.  We probably malloced it and
3870                  * the emergency pool wasn't available.
3871                  */
3872                 free(io, M_CTLIO);
3873         }
3874
3875 }
3876
3877 void
3878 ctl_zero_io(union ctl_io *io)
3879 {
3880         void *pool_ref;
3881
3882         if (io == NULL)
3883                 return;
3884
3885         /*
3886          * May need to preserve linked list pointers at some point too.
3887          */
3888         pool_ref = io->io_hdr.pool;
3889
3890         memset(io, 0, sizeof(*io));
3891
3892         io->io_hdr.pool = pool_ref;
3893 }
3894
3895 /*
3896  * This routine is currently used for internal copies of ctl_ios that need
3897  * to persist for some reason after we've already returned status to the
3898  * FETD.  (Thus the flag set.)
3899  *
3900  * XXX XXX
3901  * Note that this makes a blind copy of all fields in the ctl_io, except
3902  * for the pool reference.  This includes any memory that has been
3903  * allocated!  That memory will no longer be valid after done has been
3904  * called, so this would be VERY DANGEROUS for command that actually does
3905  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3906  * start and stop commands, which don't transfer any data, so this is not a
3907  * problem.  If it is used for anything else, the caller would also need to
3908  * allocate data buffer space and this routine would need to be modified to
3909  * copy the data buffer(s) as well.
3910  */
3911 void
3912 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3913 {
3914         void *pool_ref;
3915
3916         if ((src == NULL)
3917          || (dest == NULL))
3918                 return;
3919
3920         /*
3921          * May need to preserve linked list pointers at some point too.
3922          */
3923         pool_ref = dest->io_hdr.pool;
3924
3925         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3926
3927         dest->io_hdr.pool = pool_ref;
3928         /*
3929          * We need to know that this is an internal copy, and doesn't need
3930          * to get passed back to the FETD that allocated it.
3931          */
3932         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3933 }
3934
3935 #ifdef NEEDTOPORT
3936 static void
3937 ctl_update_power_subpage(struct copan_power_subpage *page)
3938 {
3939         int num_luns, num_partitions, config_type;
3940         struct ctl_softc *softc;
3941         cs_BOOL_t aor_present, shelf_50pct_power;
3942         cs_raidset_personality_t rs_type;
3943         int max_active_luns;
3944
3945         softc = control_softc;
3946
3947         /* subtract out the processor LUN */
3948         num_luns = softc->num_luns - 1;
3949         /*
3950          * Default to 7 LUNs active, which was the only number we allowed
3951          * in the past.
3952          */
3953         max_active_luns = 7;
3954
3955         num_partitions = config_GetRsPartitionInfo();
3956         config_type = config_GetConfigType();
3957         shelf_50pct_power = config_GetShelfPowerMode();
3958         aor_present = config_IsAorRsPresent();
3959
3960         rs_type = ddb_GetRsRaidType(1);
3961         if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3962          && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3963                 EPRINT(0, "Unsupported RS type %d!", rs_type);
3964         }
3965
3966
3967         page->total_luns = num_luns;
3968
3969         switch (config_type) {
3970         case 40:
3971                 /*
3972                  * In a 40 drive configuration, it doesn't matter what DC
3973                  * cards we have, whether we have AOR enabled or not,
3974                  * partitioning or not, or what type of RAIDset we have.
3975                  * In that scenario, we can power up every LUN we present
3976                  * to the user.
3977                  */
3978                 max_active_luns = num_luns;
3979
3980                 break;
3981         case 64:
3982                 if (shelf_50pct_power == CS_FALSE) {
3983                         /* 25% power */
3984                         if (aor_present == CS_TRUE) {
3985                                 if (rs_type ==
3986                                      CS_RAIDSET_PERSONALITY_RAID5) {
3987                                         max_active_luns = 7;
3988                                 } else if (rs_type ==
3989                                          CS_RAIDSET_PERSONALITY_RAID1){
3990                                         max_active_luns = 14;
3991                                 } else {
3992                                         /* XXX KDM now what?? */
3993                                 }
3994                         } else {
3995                                 if (rs_type ==
3996                                      CS_RAIDSET_PERSONALITY_RAID5) {
3997                                         max_active_luns = 8;
3998                                 } else if (rs_type ==
3999                                          CS_RAIDSET_PERSONALITY_RAID1){
4000                                         max_active_luns = 16;
4001                                 } else {
4002                                         /* XXX KDM now what?? */
4003                                 }
4004                         }
4005                 } else {
4006                         /* 50% power */
4007                         /*
4008                          * With 50% power in a 64 drive configuration, we
4009                          * can power all LUNs we present.
4010                          */
4011                         max_active_luns = num_luns;
4012                 }
4013                 break;
4014         case 112:
4015                 if (shelf_50pct_power == CS_FALSE) {
4016                         /* 25% power */
4017                         if (aor_present == CS_TRUE) {
4018                                 if (rs_type ==
4019                                      CS_RAIDSET_PERSONALITY_RAID5) {
4020                                         max_active_luns = 7;
4021                                 } else if (rs_type ==
4022                                          CS_RAIDSET_PERSONALITY_RAID1){
4023                                         max_active_luns = 14;
4024                                 } else {
4025                                         /* XXX KDM now what?? */
4026                                 }
4027                         } else {
4028                                 if (rs_type ==
4029                                      CS_RAIDSET_PERSONALITY_RAID5) {
4030                                         max_active_luns = 8;
4031                                 } else if (rs_type ==
4032                                          CS_RAIDSET_PERSONALITY_RAID1){
4033                                         max_active_luns = 16;
4034                                 } else {
4035                                         /* XXX KDM now what?? */
4036                                 }
4037                         }
4038                 } else {
4039                         /* 50% power */
4040                         if (aor_present == CS_TRUE) {
4041                                 if (rs_type ==
4042                                      CS_RAIDSET_PERSONALITY_RAID5) {
4043                                         max_active_luns = 14;
4044                                 } else if (rs_type ==
4045                                          CS_RAIDSET_PERSONALITY_RAID1){
4046                                         /*
4047                                          * We're assuming here that disk
4048                                          * caching is enabled, and so we're
4049                                          * able to power up half of each
4050                                          * LUN, and cache all writes.
4051                                          */
4052                                         max_active_luns = num_luns;
4053                                 } else {
4054                                         /* XXX KDM now what?? */
4055                                 }
4056                         } else {
4057                                 if (rs_type ==
4058                                      CS_RAIDSET_PERSONALITY_RAID5) {
4059                                         max_active_luns = 15;
4060                                 } else if (rs_type ==
4061                                          CS_RAIDSET_PERSONALITY_RAID1){
4062                                         max_active_luns = 30;
4063                                 } else {
4064                                         /* XXX KDM now what?? */
4065                                 }
4066                         }
4067                 }
4068                 break;
4069         default:
4070                 /*
4071                  * In this case, we have an unknown configuration, so we
4072                  * just use the default from above.
4073                  */
4074                 break;
4075         }
4076
4077         page->max_active_luns = max_active_luns;
4078 #if 0
4079         printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4080                page->total_luns, page->max_active_luns);
4081 #endif
4082 }
4083 #endif /* NEEDTOPORT */
4084
4085 /*
4086  * This routine could be used in the future to load default and/or saved
4087  * mode page parameters for a particuar lun.
4088  */
4089 static int
4090 ctl_init_page_index(struct ctl_lun *lun)
4091 {
4092         int i;
4093         struct ctl_page_index *page_index;
4094         struct ctl_softc *softc;
4095
4096         memcpy(&lun->mode_pages.index, page_index_template,
4097                sizeof(page_index_template));
4098
4099         softc = lun->ctl_softc;
4100
4101         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4102
4103                 page_index = &lun->mode_pages.index[i];
4104                 /*
4105                  * If this is a disk-only mode page, there's no point in
4106                  * setting it up.  For some pages, we have to have some
4107                  * basic information about the disk in order to calculate the
4108                  * mode page data.
4109                  */
4110                 if ((lun->be_lun->lun_type != T_DIRECT)
4111                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4112                         continue;
4113
4114                 switch (page_index->page_code & SMPH_PC_MASK) {
4115                 case SMS_FORMAT_DEVICE_PAGE: {
4116                         struct scsi_format_page *format_page;
4117
4118                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4119                                 panic("subpage is incorrect!");
4120
4121                         /*
4122                          * Sectors per track are set above.  Bytes per
4123                          * sector need to be set here on a per-LUN basis.
4124                          */
4125                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4126                                &format_page_default,
4127                                sizeof(format_page_default));
4128                         memcpy(&lun->mode_pages.format_page[
4129                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4130                                sizeof(format_page_changeable));
4131                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4132                                &format_page_default,
4133                                sizeof(format_page_default));
4134                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4135                                &format_page_default,
4136                                sizeof(format_page_default));
4137
4138                         format_page = &lun->mode_pages.format_page[
4139                                 CTL_PAGE_CURRENT];
4140                         scsi_ulto2b(lun->be_lun->blocksize,
4141                                     format_page->bytes_per_sector);
4142
4143                         format_page = &lun->mode_pages.format_page[
4144                                 CTL_PAGE_DEFAULT];
4145                         scsi_ulto2b(lun->be_lun->blocksize,
4146                                     format_page->bytes_per_sector);
4147
4148                         format_page = &lun->mode_pages.format_page[
4149                                 CTL_PAGE_SAVED];
4150                         scsi_ulto2b(lun->be_lun->blocksize,
4151                                     format_page->bytes_per_sector);
4152
4153                         page_index->page_data =
4154                                 (uint8_t *)lun->mode_pages.format_page;
4155                         break;
4156                 }
4157                 case SMS_RIGID_DISK_PAGE: {
4158                         struct scsi_rigid_disk_page *rigid_disk_page;
4159                         uint32_t sectors_per_cylinder;
4160                         uint64_t cylinders;
4161 #ifndef __XSCALE__
4162                         int shift;
4163 #endif /* !__XSCALE__ */
4164
4165                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4166                                 panic("invalid subpage value %d",
4167                                       page_index->subpage);
4168
4169                         /*
4170                          * Rotation rate and sectors per track are set
4171                          * above.  We calculate the cylinders here based on
4172                          * capacity.  Due to the number of heads and
4173                          * sectors per track we're using, smaller arrays
4174                          * may turn out to have 0 cylinders.  Linux and
4175                          * FreeBSD don't pay attention to these mode pages
4176                          * to figure out capacity, but Solaris does.  It
4177                          * seems to deal with 0 cylinders just fine, and
4178                          * works out a fake geometry based on the capacity.
4179                          */
4180                         memcpy(&lun->mode_pages.rigid_disk_page[
4181                                CTL_PAGE_CURRENT], &rigid_disk_page_default,
4182                                sizeof(rigid_disk_page_default));
4183                         memcpy(&lun->mode_pages.rigid_disk_page[
4184                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4185                                sizeof(rigid_disk_page_changeable));
4186                         memcpy(&lun->mode_pages.rigid_disk_page[
4187                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4188                                sizeof(rigid_disk_page_default));
4189                         memcpy(&lun->mode_pages.rigid_disk_page[
4190                                CTL_PAGE_SAVED], &rigid_disk_page_default,
4191                                sizeof(rigid_disk_page_default));
4192
4193                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4194                                 CTL_DEFAULT_HEADS;
4195
4196                         /*
4197                          * The divide method here will be more accurate,
4198                          * probably, but results in floating point being
4199                          * used in the kernel on i386 (__udivdi3()).  On the
4200                          * XScale, though, __udivdi3() is implemented in
4201                          * software.
4202                          *
4203                          * The shift method for cylinder calculation is
4204                          * accurate if sectors_per_cylinder is a power of
4205                          * 2.  Otherwise it might be slightly off -- you
4206                          * might have a bit of a truncation problem.
4207                          */
4208 #ifdef  __XSCALE__
4209                         cylinders = (lun->be_lun->maxlba + 1) /
4210                                 sectors_per_cylinder;
4211 #else
4212                         for (shift = 31; shift > 0; shift--) {
4213                                 if (sectors_per_cylinder & (1 << shift))
4214                                         break;
4215                         }
4216                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4217 #endif
4218
4219                         /*
4220                          * We've basically got 3 bytes, or 24 bits for the
4221                          * cylinder size in the mode page.  If we're over,
4222                          * just round down to 2^24.
4223                          */
4224                         if (cylinders > 0xffffff)
4225                                 cylinders = 0xffffff;
4226
4227                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4228                                 CTL_PAGE_CURRENT];
4229                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4230
4231                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4232                                 CTL_PAGE_DEFAULT];
4233                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4234
4235                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4236                                 CTL_PAGE_SAVED];
4237                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4238
4239                         page_index->page_data =
4240                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4241                         break;
4242                 }
4243                 case SMS_CACHING_PAGE: {
4244
4245                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4246                                 panic("invalid subpage value %d",
4247                                       page_index->subpage);
4248                         /*
4249                          * Defaults should be okay here, no calculations
4250                          * needed.
4251                          */
4252                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4253                                &caching_page_default,
4254                                sizeof(caching_page_default));
4255                         memcpy(&lun->mode_pages.caching_page[
4256                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4257                                sizeof(caching_page_changeable));
4258                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4259                                &caching_page_default,
4260                                sizeof(caching_page_default));
4261                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4262                                &caching_page_default,
4263                                sizeof(caching_page_default));
4264                         page_index->page_data =
4265                                 (uint8_t *)lun->mode_pages.caching_page;
4266                         break;
4267                 }
4268                 case SMS_CONTROL_MODE_PAGE: {
4269
4270                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4271                                 panic("invalid subpage value %d",
4272                                       page_index->subpage);
4273
4274                         /*
4275                          * Defaults should be okay here, no calculations
4276                          * needed.
4277                          */
4278                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4279                                &control_page_default,
4280                                sizeof(control_page_default));
4281                         memcpy(&lun->mode_pages.control_page[
4282                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4283                                sizeof(control_page_changeable));
4284                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4285                                &control_page_default,
4286                                sizeof(control_page_default));
4287                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4288                                &control_page_default,
4289                                sizeof(control_page_default));
4290                         page_index->page_data =
4291                                 (uint8_t *)lun->mode_pages.control_page;
4292                         break;
4293
4294                 }
4295                 case SMS_VENDOR_SPECIFIC_PAGE:{
4296                         switch (page_index->subpage) {
4297                         case PWR_SUBPAGE_CODE: {
4298                                 struct copan_power_subpage *current_page,
4299                                                            *saved_page;
4300
4301                                 memcpy(&lun->mode_pages.power_subpage[
4302                                        CTL_PAGE_CURRENT],
4303                                        &power_page_default,
4304                                        sizeof(power_page_default));
4305                                 memcpy(&lun->mode_pages.power_subpage[
4306                                        CTL_PAGE_CHANGEABLE],
4307                                        &power_page_changeable,
4308                                        sizeof(power_page_changeable));
4309                                 memcpy(&lun->mode_pages.power_subpage[
4310                                        CTL_PAGE_DEFAULT],
4311                                        &power_page_default,
4312                                        sizeof(power_page_default));
4313                                 memcpy(&lun->mode_pages.power_subpage[
4314                                        CTL_PAGE_SAVED],
4315                                        &power_page_default,
4316                                        sizeof(power_page_default));
4317                                 page_index->page_data =
4318                                     (uint8_t *)lun->mode_pages.power_subpage;
4319
4320                                 current_page = (struct copan_power_subpage *)
4321                                         (page_index->page_data +
4322                                          (page_index->page_len *
4323                                           CTL_PAGE_CURRENT));
4324                                 saved_page = (struct copan_power_subpage *)
4325                                         (page_index->page_data +
4326                                          (page_index->page_len *
4327                                           CTL_PAGE_SAVED));
4328                                 break;
4329                         }
4330                         case APS_SUBPAGE_CODE: {
4331                                 struct copan_aps_subpage *current_page,
4332                                                          *saved_page;
4333
4334                                 // This gets set multiple times but
4335                                 // it should always be the same. It's
4336                                 // only done during init so who cares.
4337                                 index_to_aps_page = i;
4338
4339                                 memcpy(&lun->mode_pages.aps_subpage[
4340                                        CTL_PAGE_CURRENT],
4341                                        &aps_page_default,
4342                                        sizeof(aps_page_default));
4343                                 memcpy(&lun->mode_pages.aps_subpage[
4344                                        CTL_PAGE_CHANGEABLE],
4345                                        &aps_page_changeable,
4346                                        sizeof(aps_page_changeable));
4347                                 memcpy(&lun->mode_pages.aps_subpage[
4348                                        CTL_PAGE_DEFAULT],
4349                                        &aps_page_default,
4350                                        sizeof(aps_page_default));
4351                                 memcpy(&lun->mode_pages.aps_subpage[
4352                                        CTL_PAGE_SAVED],
4353                                        &aps_page_default,
4354                                        sizeof(aps_page_default));
4355                                 page_index->page_data =
4356                                         (uint8_t *)lun->mode_pages.aps_subpage;
4357
4358                                 current_page = (struct copan_aps_subpage *)
4359                                         (page_index->page_data +
4360                                          (page_index->page_len *
4361                                           CTL_PAGE_CURRENT));
4362                                 saved_page = (struct copan_aps_subpage *)
4363                                         (page_index->page_data +
4364                                          (page_index->page_len *
4365                                           CTL_PAGE_SAVED));
4366                                 break;
4367                         }
4368                         case DBGCNF_SUBPAGE_CODE: {
4369                                 struct copan_debugconf_subpage *current_page,
4370                                                                *saved_page;
4371
4372                                 memcpy(&lun->mode_pages.debugconf_subpage[
4373                                        CTL_PAGE_CURRENT],
4374                                        &debugconf_page_default,
4375                                        sizeof(debugconf_page_default));
4376                                 memcpy(&lun->mode_pages.debugconf_subpage[
4377                                        CTL_PAGE_CHANGEABLE],
4378                                        &debugconf_page_changeable,
4379                                        sizeof(debugconf_page_changeable));
4380                                 memcpy(&lun->mode_pages.debugconf_subpage[
4381                                        CTL_PAGE_DEFAULT],
4382                                        &debugconf_page_default,
4383                                        sizeof(debugconf_page_default));
4384                                 memcpy(&lun->mode_pages.debugconf_subpage[
4385                                        CTL_PAGE_SAVED],
4386                                        &debugconf_page_default,
4387                                        sizeof(debugconf_page_default));
4388                                 page_index->page_data =
4389                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4390
4391                                 current_page = (struct copan_debugconf_subpage *)
4392                                         (page_index->page_data +
4393                                          (page_index->page_len *
4394                                           CTL_PAGE_CURRENT));
4395                                 saved_page = (struct copan_debugconf_subpage *)
4396                                         (page_index->page_data +
4397                                          (page_index->page_len *
4398                                           CTL_PAGE_SAVED));
4399                                 break;
4400                         }
4401                         default:
4402                                 panic("invalid subpage value %d",
4403                                       page_index->subpage);
4404                                 break;
4405                         }
4406                         break;
4407                 }
4408                 default:
4409                         panic("invalid page value %d",
4410                               page_index->page_code & SMPH_PC_MASK);
4411                         break;
4412         }
4413         }
4414
4415         return (CTL_RETVAL_COMPLETE);
4416 }
4417
4418 /*
4419  * LUN allocation.
4420  *
4421  * Requirements:
4422  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4423  *   wants us to allocate the LUN and he can block.
4424  * - ctl_softc is always set
4425  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4426  *
4427  * Returns 0 for success, non-zero (errno) for failure.
4428  */
4429 static int
4430 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4431               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4432 {
4433         struct ctl_lun *nlun, *lun;
4434         struct ctl_port *port;
4435         struct scsi_vpd_id_descriptor *desc;
4436         struct scsi_vpd_id_t10 *t10id;
4437         const char *eui, *naa, *scsiname, *vendor;
4438         int lun_number, i, lun_malloced;
4439         int devidlen, idlen1, idlen2 = 0, len;
4440
4441         if (be_lun == NULL)
4442                 return (EINVAL);
4443
4444         /*
4445          * We currently only support Direct Access or Processor LUN types.
4446          */
4447         switch (be_lun->lun_type) {
4448         case T_DIRECT:
4449                 break;
4450         case T_PROCESSOR:
4451                 break;
4452         case T_SEQUENTIAL:
4453         case T_CHANGER:
4454         default:
4455                 be_lun->lun_config_status(be_lun->be_lun,
4456                                           CTL_LUN_CONFIG_FAILURE);
4457                 break;
4458         }
4459         if (ctl_lun == NULL) {
4460                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4461                 lun_malloced = 1;
4462         } else {
4463                 lun_malloced = 0;
4464                 lun = ctl_lun;
4465         }
4466
4467         memset(lun, 0, sizeof(*lun));
4468         if (lun_malloced)
4469                 lun->flags = CTL_LUN_MALLOCED;
4470
4471         /* Generate LUN ID. */
4472         devidlen = max(CTL_DEVID_MIN_LEN,
4473             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4474         idlen1 = sizeof(*t10id) + devidlen;
4475         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4476         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4477         if (scsiname != NULL) {
4478                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4479                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4480         }
4481         eui = ctl_get_opt(&be_lun->options, "eui");
4482         if (eui != NULL) {
4483                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4484         }
4485         naa = ctl_get_opt(&be_lun->options, "naa");
4486         if (naa != NULL) {
4487                 len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4488         }
4489         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4490             M_CTL, M_WAITOK | M_ZERO);
4491         lun->lun_devid->len = len;
4492         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4493         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4494         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4495         desc->length = idlen1;
4496         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4497         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4498         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4499                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4500         } else {
4501                 strncpy(t10id->vendor, vendor,
4502                     min(sizeof(t10id->vendor), strlen(vendor)));
4503         }
4504         strncpy((char *)t10id->vendor_spec_id,
4505             (char *)be_lun->device_id, devidlen);
4506         if (scsiname != NULL) {
4507                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4508                     desc->length);
4509                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4510                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4511                     SVPD_ID_TYPE_SCSI_NAME;
4512                 desc->length = idlen2;
4513                 strlcpy(desc->identifier, scsiname, idlen2);
4514         }
4515         if (eui != NULL) {
4516                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4517                     desc->length);
4518                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4519                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4520                     SVPD_ID_TYPE_EUI64;
4521                 desc->length = 8;
4522                 scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4523         }
4524         if (naa != NULL) {
4525                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4526                     desc->length);
4527                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4528                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4529                     SVPD_ID_TYPE_NAA;
4530                 desc->length = 8;
4531                 scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4532         }
4533
4534         mtx_lock(&ctl_softc->ctl_lock);
4535         /*
4536          * See if the caller requested a particular LUN number.  If so, see
4537          * if it is available.  Otherwise, allocate the first available LUN.
4538          */
4539         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4540                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4541                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4542                         mtx_unlock(&ctl_softc->ctl_lock);
4543                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4544                                 printf("ctl: requested LUN ID %d is higher "
4545                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4546                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4547                         } else {
4548                                 /*
4549                                  * XXX KDM return an error, or just assign
4550                                  * another LUN ID in this case??
4551                                  */
4552                                 printf("ctl: requested LUN ID %d is already "
4553                                        "in use\n", be_lun->req_lun_id);
4554                         }
4555                         if (lun->flags & CTL_LUN_MALLOCED)
4556                                 free(lun, M_CTL);
4557                         be_lun->lun_config_status(be_lun->be_lun,
4558                                                   CTL_LUN_CONFIG_FAILURE);
4559                         return (ENOSPC);
4560                 }
4561                 lun_number = be_lun->req_lun_id;
4562         } else {
4563                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4564                 if (lun_number == -1) {
4565                         mtx_unlock(&ctl_softc->ctl_lock);
4566                         printf("ctl: can't allocate LUN on target %ju, out of "
4567                                "LUNs\n", (uintmax_t)target_id.id);
4568                         if (lun->flags & CTL_LUN_MALLOCED)
4569                                 free(lun, M_CTL);
4570                         be_lun->lun_config_status(be_lun->be_lun,
4571                                                   CTL_LUN_CONFIG_FAILURE);
4572                         return (ENOSPC);
4573                 }
4574         }
4575         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4576
4577         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4578         lun->target = target_id;
4579         lun->lun = lun_number;
4580         lun->be_lun = be_lun;
4581         /*
4582          * The processor LUN is always enabled.  Disk LUNs come on line
4583          * disabled, and must be enabled by the backend.
4584          */
4585         lun->flags |= CTL_LUN_DISABLED;
4586         lun->backend = be_lun->be;
4587         be_lun->ctl_lun = lun;
4588         be_lun->lun_id = lun_number;
4589         atomic_add_int(&be_lun->be->num_luns, 1);
4590         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4591                 lun->flags |= CTL_LUN_STOPPED;
4592
4593         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4594                 lun->flags |= CTL_LUN_INOPERABLE;
4595
4596         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4597                 lun->flags |= CTL_LUN_PRIMARY_SC;
4598
4599         lun->ctl_softc = ctl_softc;
4600         TAILQ_INIT(&lun->ooa_queue);
4601         TAILQ_INIT(&lun->blocked_queue);
4602         STAILQ_INIT(&lun->error_list);
4603
4604         /*
4605          * Initialize the mode page index.
4606          */
4607         ctl_init_page_index(lun);
4608
4609         /*
4610          * Set the poweron UA for all initiators on this LUN only.
4611          */
4612         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4613                 lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4614
4615         /*
4616          * Now, before we insert this lun on the lun list, set the lun
4617          * inventory changed UA for all other luns.
4618          */
4619         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4620                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4621                         nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4622                 }
4623         }
4624
4625         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4626
4627         ctl_softc->ctl_luns[lun_number] = lun;
4628
4629         ctl_softc->num_luns++;
4630
4631         /* Setup statistics gathering */
4632         lun->stats.device_type = be_lun->lun_type;
4633         lun->stats.lun_number = lun_number;
4634         if (lun->stats.device_type == T_DIRECT)
4635                 lun->stats.blocksize = be_lun->blocksize;
4636         else
4637                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4638         for (i = 0;i < CTL_MAX_PORTS;i++)
4639                 lun->stats.ports[i].targ_port = i;
4640
4641         mtx_unlock(&ctl_softc->ctl_lock);
4642
4643         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4644
4645         /*
4646          * Run through each registered FETD and bring it online if it isn't
4647          * already.  Enable the target ID if it hasn't been enabled, and
4648          * enable this particular LUN.
4649          */
4650         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4651                 int retval;
4652
4653                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4654                 if (retval != 0) {
4655                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4656                                "%d for lun_enable on target %ju lun %d\n",
4657                                port->port_name, port->targ_port, retval,
4658                                (uintmax_t)target_id.id, lun_number);
4659                 } else
4660                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4661         }
4662         return (0);
4663 }
4664
4665 /*
4666  * Delete a LUN.
4667  * Assumptions:
4668  * - LUN has already been marked invalid and any pending I/O has been taken
4669  *   care of.
4670  */
4671 static int
4672 ctl_free_lun(struct ctl_lun *lun)
4673 {
4674         struct ctl_softc *softc;
4675 #if 0
4676         struct ctl_port *port;
4677 #endif
4678         struct ctl_lun *nlun;
4679         int i;
4680
4681         softc = lun->ctl_softc;
4682
4683         mtx_assert(&softc->ctl_lock, MA_OWNED);
4684
4685         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4686
4687         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4688
4689         softc->ctl_luns[lun->lun] = NULL;
4690
4691         if (!TAILQ_EMPTY(&lun->ooa_queue))
4692                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4693
4694         softc->num_luns--;
4695
4696         /*
4697          * XXX KDM this scheme only works for a single target/multiple LUN
4698          * setup.  It needs to be revamped for a multiple target scheme.
4699          *
4700          * XXX KDM this results in port->lun_disable() getting called twice,
4701          * once when ctl_disable_lun() is called, and a second time here.
4702          * We really need to re-think the LUN disable semantics.  There
4703          * should probably be several steps/levels to LUN removal:
4704          *  - disable
4705          *  - invalidate
4706          *  - free
4707          *
4708          * Right now we only have a disable method when communicating to
4709          * the front end ports, at least for individual LUNs.
4710          */
4711 #if 0
4712         STAILQ_FOREACH(port, &softc->port_list, links) {
4713                 int retval;
4714
4715                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4716                                          lun->lun);
4717                 if (retval != 0) {
4718                         printf("ctl_free_lun: FETD %s port %d returned error "
4719                                "%d for lun_disable on target %ju lun %jd\n",
4720                                port->port_name, port->targ_port, retval,
4721                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4722                 }
4723
4724                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4725                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4726
4727                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4728                         if (retval != 0) {
4729                                 printf("ctl_free_lun: FETD %s port %d "
4730                                        "returned error %d for targ_disable on "
4731                                        "target %ju\n", port->port_name,
4732                                        port->targ_port, retval,
4733                                        (uintmax_t)lun->target.id);
4734                         } else
4735                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4736
4737                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4738                                 continue;
4739
4740 #if 0
4741                         port->port_offline(port->onoff_arg);
4742                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4743 #endif
4744                 }
4745         }
4746 #endif
4747
4748         /*
4749          * Tell the backend to free resources, if this LUN has a backend.
4750          */
4751         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4752         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4753
4754         mtx_destroy(&lun->lun_lock);
4755         free(lun->lun_devid, M_CTL);
4756         if (lun->flags & CTL_LUN_MALLOCED)
4757                 free(lun, M_CTL);
4758
4759         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4760                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4761                         nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4762                 }
4763         }
4764
4765         return (0);
4766 }
4767
4768 static void
4769 ctl_create_lun(struct ctl_be_lun *be_lun)
4770 {
4771         struct ctl_softc *ctl_softc;
4772
4773         ctl_softc = control_softc;
4774
4775         /*
4776          * ctl_alloc_lun() should handle all potential failure cases.
4777          */
4778         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4779 }
4780
4781 int
4782 ctl_add_lun(struct ctl_be_lun *be_lun)
4783 {
4784         struct ctl_softc *ctl_softc = control_softc;
4785
4786         mtx_lock(&ctl_softc->ctl_lock);
4787         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4788         mtx_unlock(&ctl_softc->ctl_lock);
4789         wakeup(&ctl_softc->pending_lun_queue);
4790
4791         return (0);
4792 }
4793
4794 int
4795 ctl_enable_lun(struct ctl_be_lun *be_lun)
4796 {
4797         struct ctl_softc *ctl_softc;
4798         struct ctl_port *port, *nport;
4799         struct ctl_lun *lun;
4800         int retval;
4801
4802         ctl_softc = control_softc;
4803
4804         lun = (struct ctl_lun *)be_lun->ctl_lun;
4805
4806         mtx_lock(&ctl_softc->ctl_lock);
4807         mtx_lock(&lun->lun_lock);
4808         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4809                 /*
4810                  * eh?  Why did we get called if the LUN is already
4811                  * enabled?
4812                  */
4813                 mtx_unlock(&lun->lun_lock);
4814                 mtx_unlock(&ctl_softc->ctl_lock);
4815                 return (0);
4816         }
4817         lun->flags &= ~CTL_LUN_DISABLED;
4818         mtx_unlock(&lun->lun_lock);
4819
4820         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4821                 nport = STAILQ_NEXT(port, links);
4822
4823                 /*
4824                  * Drop the lock while we call the FETD's enable routine.
4825                  * This can lead to a callback into CTL (at least in the
4826                  * case of the internal initiator frontend.
4827                  */
4828                 mtx_unlock(&ctl_softc->ctl_lock);
4829                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4830                 mtx_lock(&ctl_softc->ctl_lock);
4831                 if (retval != 0) {
4832                         printf("%s: FETD %s port %d returned error "
4833                                "%d for lun_enable on target %ju lun %jd\n",
4834                                __func__, port->port_name, port->targ_port, retval,
4835                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4836                 }
4837 #if 0
4838                  else {
4839             /* NOTE:  TODO:  why does lun enable affect port status? */
4840                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4841                 }
4842 #endif
4843         }
4844
4845         mtx_unlock(&ctl_softc->ctl_lock);
4846
4847         return (0);
4848 }
4849
4850 int
4851 ctl_disable_lun(struct ctl_be_lun *be_lun)
4852 {
4853         struct ctl_softc *ctl_softc;
4854         struct ctl_port *port;
4855         struct ctl_lun *lun;
4856         int retval;
4857
4858         ctl_softc = control_softc;
4859
4860         lun = (struct ctl_lun *)be_lun->ctl_lun;
4861
4862         mtx_lock(&ctl_softc->ctl_lock);
4863         mtx_lock(&lun->lun_lock);
4864         if (lun->flags & CTL_LUN_DISABLED) {
4865                 mtx_unlock(&lun->lun_lock);
4866                 mtx_unlock(&ctl_softc->ctl_lock);
4867                 return (0);
4868         }
4869         lun->flags |= CTL_LUN_DISABLED;
4870         mtx_unlock(&lun->lun_lock);
4871
4872         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4873                 mtx_unlock(&ctl_softc->ctl_lock);
4874                 /*
4875                  * Drop the lock before we call the frontend's disable
4876                  * routine, to avoid lock order reversals.
4877                  *
4878                  * XXX KDM what happens if the frontend list changes while
4879                  * we're traversing it?  It's unlikely, but should be handled.
4880                  */
4881                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4882                                          lun->lun);
4883                 mtx_lock(&ctl_softc->ctl_lock);
4884                 if (retval != 0) {
4885                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4886                                "%d for lun_disable on target %ju lun %jd\n",
4887                                port->port_name, port->targ_port, retval,
4888                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4889                 }
4890         }
4891
4892         mtx_unlock(&ctl_softc->ctl_lock);
4893
4894         return (0);
4895 }
4896
4897 int
4898 ctl_start_lun(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
4905         lun = (struct ctl_lun *)be_lun->ctl_lun;
4906
4907         mtx_lock(&lun->lun_lock);
4908         lun->flags &= ~CTL_LUN_STOPPED;
4909         mtx_unlock(&lun->lun_lock);
4910
4911         return (0);
4912 }
4913
4914 int
4915 ctl_stop_lun(struct ctl_be_lun *be_lun)
4916 {
4917         struct ctl_softc *ctl_softc;
4918         struct ctl_lun *lun;
4919
4920         ctl_softc = control_softc;
4921
4922         lun = (struct ctl_lun *)be_lun->ctl_lun;
4923
4924         mtx_lock(&lun->lun_lock);
4925         lun->flags |= CTL_LUN_STOPPED;
4926         mtx_unlock(&lun->lun_lock);
4927
4928         return (0);
4929 }
4930
4931 int
4932 ctl_lun_offline(struct ctl_be_lun *be_lun)
4933 {
4934         struct ctl_softc *ctl_softc;
4935         struct ctl_lun *lun;
4936
4937         ctl_softc = control_softc;
4938
4939         lun = (struct ctl_lun *)be_lun->ctl_lun;
4940
4941         mtx_lock(&lun->lun_lock);
4942         lun->flags |= CTL_LUN_OFFLINE;
4943         mtx_unlock(&lun->lun_lock);
4944
4945         return (0);
4946 }
4947
4948 int
4949 ctl_lun_online(struct ctl_be_lun *be_lun)
4950 {
4951         struct ctl_softc *ctl_softc;
4952         struct ctl_lun *lun;
4953
4954         ctl_softc = control_softc;
4955
4956         lun = (struct ctl_lun *)be_lun->ctl_lun;
4957
4958         mtx_lock(&lun->lun_lock);
4959         lun->flags &= ~CTL_LUN_OFFLINE;
4960         mtx_unlock(&lun->lun_lock);
4961
4962         return (0);
4963 }
4964
4965 int
4966 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4967 {
4968         struct ctl_softc *ctl_softc;
4969         struct ctl_lun *lun;
4970
4971         ctl_softc = control_softc;
4972
4973         lun = (struct ctl_lun *)be_lun->ctl_lun;
4974
4975         mtx_lock(&lun->lun_lock);
4976
4977         /*
4978          * The LUN needs to be disabled before it can be marked invalid.
4979          */
4980         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4981                 mtx_unlock(&lun->lun_lock);
4982                 return (-1);
4983         }
4984         /*
4985          * Mark the LUN invalid.
4986          */
4987         lun->flags |= CTL_LUN_INVALID;
4988
4989         /*
4990          * If there is nothing in the OOA queue, go ahead and free the LUN.
4991          * If we have something in the OOA queue, we'll free it when the
4992          * last I/O completes.
4993          */
4994         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4995                 mtx_unlock(&lun->lun_lock);
4996                 mtx_lock(&ctl_softc->ctl_lock);
4997                 ctl_free_lun(lun);
4998                 mtx_unlock(&ctl_softc->ctl_lock);
4999         } else
5000                 mtx_unlock(&lun->lun_lock);
5001
5002         return (0);
5003 }
5004
5005 int
5006 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5007 {
5008         struct ctl_softc *ctl_softc;
5009         struct ctl_lun *lun;
5010
5011         ctl_softc = control_softc;
5012         lun = (struct ctl_lun *)be_lun->ctl_lun;
5013
5014         mtx_lock(&lun->lun_lock);
5015         lun->flags |= CTL_LUN_INOPERABLE;
5016         mtx_unlock(&lun->lun_lock);
5017
5018         return (0);
5019 }
5020
5021 int
5022 ctl_lun_operable(struct ctl_be_lun *be_lun)
5023 {
5024         struct ctl_softc *ctl_softc;
5025         struct ctl_lun *lun;
5026
5027         ctl_softc = control_softc;
5028         lun = (struct ctl_lun *)be_lun->ctl_lun;
5029
5030         mtx_lock(&lun->lun_lock);
5031         lun->flags &= ~CTL_LUN_INOPERABLE;
5032         mtx_unlock(&lun->lun_lock);
5033
5034         return (0);
5035 }
5036
5037 int
5038 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5039                    int lock)
5040 {
5041         struct ctl_softc *softc;
5042         struct ctl_lun *lun;
5043         struct copan_aps_subpage *current_sp;
5044         struct ctl_page_index *page_index;
5045         int i;
5046
5047         softc = control_softc;
5048
5049         mtx_lock(&softc->ctl_lock);
5050
5051         lun = (struct ctl_lun *)be_lun->ctl_lun;
5052         mtx_lock(&lun->lun_lock);
5053
5054         page_index = NULL;
5055         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5056                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5057                      APS_PAGE_CODE)
5058                         continue;
5059
5060                 if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5061                         continue;
5062                 page_index = &lun->mode_pages.index[i];
5063         }
5064
5065         if (page_index == NULL) {
5066                 mtx_unlock(&lun->lun_lock);
5067                 mtx_unlock(&softc->ctl_lock);
5068                 printf("%s: APS subpage not found for lun %ju!\n", __func__,
5069                        (uintmax_t)lun->lun);
5070                 return (1);
5071         }
5072 #if 0
5073         if ((softc->aps_locked_lun != 0)
5074          && (softc->aps_locked_lun != lun->lun)) {
5075                 printf("%s: attempt to lock LUN %llu when %llu is already "
5076                        "locked\n");
5077                 mtx_unlock(&lun->lun_lock);
5078                 mtx_unlock(&softc->ctl_lock);
5079                 return (1);
5080         }
5081 #endif
5082
5083         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5084                 (page_index->page_len * CTL_PAGE_CURRENT));
5085
5086         if (lock != 0) {
5087                 current_sp->lock_active = APS_LOCK_ACTIVE;
5088                 softc->aps_locked_lun = lun->lun;
5089         } else {
5090                 current_sp->lock_active = 0;
5091                 softc->aps_locked_lun = 0;
5092         }
5093
5094
5095         /*
5096          * If we're in HA mode, try to send the lock message to the other
5097          * side.
5098          */
5099         if (ctl_is_single == 0) {
5100                 int isc_retval;
5101                 union ctl_ha_msg lock_msg;
5102
5103                 lock_msg.hdr.nexus = *nexus;
5104                 lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5105                 if (lock != 0)
5106                         lock_msg.aps.lock_flag = 1;
5107                 else
5108                         lock_msg.aps.lock_flag = 0;
5109                 isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5110                                          sizeof(lock_msg), 0);
5111                 if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5112                         printf("%s: APS (lock=%d) error returned from "
5113                                "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5114                         mtx_unlock(&lun->lun_lock);
5115                         mtx_unlock(&softc->ctl_lock);
5116                         return (1);
5117                 }
5118         }
5119
5120         mtx_unlock(&lun->lun_lock);
5121         mtx_unlock(&softc->ctl_lock);
5122
5123         return (0);
5124 }
5125
5126 void
5127 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5128 {
5129         struct ctl_lun *lun;
5130         struct ctl_softc *softc;
5131         int i;
5132
5133         softc = control_softc;
5134
5135         lun = (struct ctl_lun *)be_lun->ctl_lun;
5136
5137         mtx_lock(&lun->lun_lock);
5138
5139         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
5140                 lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
5141
5142         mtx_unlock(&lun->lun_lock);
5143 }
5144
5145 /*
5146  * Backend "memory move is complete" callback for requests that never
5147  * make it down to say RAIDCore's configuration code.
5148  */
5149 int
5150 ctl_config_move_done(union ctl_io *io)
5151 {
5152         int retval;
5153
5154         retval = CTL_RETVAL_COMPLETE;
5155
5156
5157         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5158         /*
5159          * XXX KDM this shouldn't happen, but what if it does?
5160          */
5161         if (io->io_hdr.io_type != CTL_IO_SCSI)
5162                 panic("I/O type isn't CTL_IO_SCSI!");
5163
5164         if ((io->io_hdr.port_status == 0)
5165          && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5166          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5167                 io->io_hdr.status = CTL_SUCCESS;
5168         else if ((io->io_hdr.port_status != 0)
5169               && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5170               && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5171                 /*
5172                  * For hardware error sense keys, the sense key
5173                  * specific value is defined to be a retry count,
5174                  * but we use it to pass back an internal FETD
5175                  * error code.  XXX KDM  Hopefully the FETD is only
5176                  * using 16 bits for an error code, since that's
5177                  * all the space we have in the sks field.
5178                  */
5179                 ctl_set_internal_failure(&io->scsiio,
5180                                          /*sks_valid*/ 1,
5181                                          /*retry_count*/
5182                                          io->io_hdr.port_status);
5183                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5184                         free(io->scsiio.kern_data_ptr, M_CTL);
5185                 ctl_done(io);
5186                 goto bailout;
5187         }
5188
5189         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5190          || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5191          || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5192                 /*
5193                  * XXX KDM just assuming a single pointer here, and not a
5194                  * S/G list.  If we start using S/G lists for config data,
5195                  * we'll need to know how to clean them up here as well.
5196                  */
5197                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5198                         free(io->scsiio.kern_data_ptr, M_CTL);
5199                 /* Hopefully the user has already set the status... */
5200                 ctl_done(io);
5201         } else {
5202                 /*
5203                  * XXX KDM now we need to continue data movement.  Some
5204                  * options:
5205                  * - call ctl_scsiio() again?  We don't do this for data
5206                  *   writes, because for those at least we know ahead of
5207                  *   time where the write will go and how long it is.  For
5208                  *   config writes, though, that information is largely
5209                  *   contained within the write itself, thus we need to
5210                  *   parse out the data again.
5211                  *
5212                  * - Call some other function once the data is in?
5213                  */
5214
5215                 /*
5216                  * XXX KDM call ctl_scsiio() again for now, and check flag
5217                  * bits to see whether we're allocated or not.
5218                  */
5219                 retval = ctl_scsiio(&io->scsiio);
5220         }
5221 bailout:
5222         return (retval);
5223 }
5224
5225 /*
5226  * This gets called by a backend driver when it is done with a
5227  * data_submit method.
5228  */
5229 void
5230 ctl_data_submit_done(union ctl_io *io)
5231 {
5232         /*
5233          * If the IO_CONT flag is set, we need to call the supplied
5234          * function to continue processing the I/O, instead of completing
5235          * the I/O just yet.
5236          *
5237          * If there is an error, though, we don't want to keep processing.
5238          * Instead, just send status back to the initiator.
5239          */
5240         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5241             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5242             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5243              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5244                 io->scsiio.io_cont(io);
5245                 return;
5246         }
5247         ctl_done(io);
5248 }
5249
5250 /*
5251  * This gets called by a backend driver when it is done with a
5252  * configuration write.
5253  */
5254 void
5255 ctl_config_write_done(union ctl_io *io)
5256 {
5257         /*
5258          * If the IO_CONT flag is set, we need to call the supplied
5259          * function to continue processing the I/O, instead of completing
5260          * the I/O just yet.
5261          *
5262          * If there is an error, though, we don't want to keep processing.
5263          * Instead, just send status back to the initiator.
5264          */
5265         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5266          && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5267           || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5268                 io->scsiio.io_cont(io);
5269                 return;
5270         }
5271         /*
5272          * Since a configuration write can be done for commands that actually
5273          * have data allocated, like write buffer, and commands that have
5274          * no data, like start/stop unit, we need to check here.
5275          */
5276         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5277                 free(io->scsiio.kern_data_ptr, M_CTL);
5278         ctl_done(io);
5279 }
5280
5281 /*
5282  * SCSI release command.
5283  */
5284 int
5285 ctl_scsi_release(struct ctl_scsiio *ctsio)
5286 {
5287         int length, longid, thirdparty_id, resv_id;
5288         struct ctl_softc *ctl_softc;
5289         struct ctl_lun *lun;
5290
5291         length = 0;
5292         resv_id = 0;
5293
5294         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5295
5296         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5297         ctl_softc = control_softc;
5298
5299         switch (ctsio->cdb[0]) {
5300         case RELEASE_10: {
5301                 struct scsi_release_10 *cdb;
5302
5303                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5304
5305                 if (cdb->byte2 & SR10_LONGID)
5306                         longid = 1;
5307                 else
5308                         thirdparty_id = cdb->thirdparty_id;
5309
5310                 resv_id = cdb->resv_id;
5311                 length = scsi_2btoul(cdb->length);
5312                 break;
5313         }
5314         }
5315
5316
5317         /*
5318          * XXX KDM right now, we only support LUN reservation.  We don't
5319          * support 3rd party reservations, or extent reservations, which
5320          * might actually need the parameter list.  If we've gotten this
5321          * far, we've got a LUN reservation.  Anything else got kicked out
5322          * above.  So, according to SPC, ignore the length.
5323          */
5324         length = 0;
5325
5326         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5327          && (length > 0)) {
5328                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5329                 ctsio->kern_data_len = length;
5330                 ctsio->kern_total_len = length;
5331                 ctsio->kern_data_resid = 0;
5332                 ctsio->kern_rel_offset = 0;
5333                 ctsio->kern_sg_entries = 0;
5334                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5335                 ctsio->be_move_done = ctl_config_move_done;
5336                 ctl_datamove((union ctl_io *)ctsio);
5337
5338                 return (CTL_RETVAL_COMPLETE);
5339         }
5340
5341         if (length > 0)
5342                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5343
5344         mtx_lock(&lun->lun_lock);
5345
5346         /*
5347          * According to SPC, it is not an error for an intiator to attempt
5348          * to release a reservation on a LUN that isn't reserved, or that
5349          * is reserved by another initiator.  The reservation can only be
5350          * released, though, by the initiator who made it or by one of
5351          * several reset type events.
5352          */
5353         if (lun->flags & CTL_LUN_RESERVED) {
5354                 if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5355                  && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5356                  && (ctsio->io_hdr.nexus.targ_target.id ==
5357                      lun->rsv_nexus.targ_target.id)) {
5358                         lun->flags &= ~CTL_LUN_RESERVED;
5359                 }
5360         }
5361
5362         mtx_unlock(&lun->lun_lock);
5363
5364         ctsio->scsi_status = SCSI_STATUS_OK;
5365         ctsio->io_hdr.status = CTL_SUCCESS;
5366
5367         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5368                 free(ctsio->kern_data_ptr, M_CTL);
5369                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5370         }
5371
5372         ctl_done((union ctl_io *)ctsio);
5373         return (CTL_RETVAL_COMPLETE);
5374 }
5375
5376 int
5377 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5378 {
5379         int extent, thirdparty, longid;
5380         int resv_id, length;
5381         uint64_t thirdparty_id;
5382         struct ctl_softc *ctl_softc;
5383         struct ctl_lun *lun;
5384
5385         extent = 0;
5386         thirdparty = 0;
5387         longid = 0;
5388         resv_id = 0;
5389         length = 0;
5390         thirdparty_id = 0;
5391
5392         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5393
5394         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5395         ctl_softc = control_softc;
5396
5397         switch (ctsio->cdb[0]) {
5398         case RESERVE_10: {
5399                 struct scsi_reserve_10 *cdb;
5400
5401                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5402
5403                 if (cdb->byte2 & SR10_LONGID)
5404                         longid = 1;
5405                 else
5406                         thirdparty_id = cdb->thirdparty_id;
5407
5408                 resv_id = cdb->resv_id;
5409                 length = scsi_2btoul(cdb->length);
5410                 break;
5411         }
5412         }
5413
5414         /*
5415          * XXX KDM right now, we only support LUN reservation.  We don't
5416          * support 3rd party reservations, or extent reservations, which
5417          * might actually need the parameter list.  If we've gotten this
5418          * far, we've got a LUN reservation.  Anything else got kicked out
5419          * above.  So, according to SPC, ignore the length.
5420          */
5421         length = 0;
5422
5423         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5424          && (length > 0)) {
5425                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5426                 ctsio->kern_data_len = length;
5427                 ctsio->kern_total_len = length;
5428                 ctsio->kern_data_resid = 0;
5429                 ctsio->kern_rel_offset = 0;
5430                 ctsio->kern_sg_entries = 0;
5431                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5432                 ctsio->be_move_done = ctl_config_move_done;
5433                 ctl_datamove((union ctl_io *)ctsio);
5434
5435                 return (CTL_RETVAL_COMPLETE);
5436         }
5437
5438         if (length > 0)
5439                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5440
5441         mtx_lock(&lun->lun_lock);
5442         if (lun->flags & CTL_LUN_RESERVED) {
5443                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5444                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5445                  || (ctsio->io_hdr.nexus.targ_target.id !=
5446                      lun->rsv_nexus.targ_target.id)) {
5447                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5448                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
5449                         goto bailout;
5450                 }
5451         }
5452
5453         lun->flags |= CTL_LUN_RESERVED;
5454         lun->rsv_nexus = ctsio->io_hdr.nexus;
5455
5456         ctsio->scsi_status = SCSI_STATUS_OK;
5457         ctsio->io_hdr.status = CTL_SUCCESS;
5458
5459 bailout:
5460         mtx_unlock(&lun->lun_lock);
5461
5462         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5463                 free(ctsio->kern_data_ptr, M_CTL);
5464                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5465         }
5466
5467         ctl_done((union ctl_io *)ctsio);
5468         return (CTL_RETVAL_COMPLETE);
5469 }
5470
5471 int
5472 ctl_start_stop(struct ctl_scsiio *ctsio)
5473 {
5474         struct scsi_start_stop_unit *cdb;
5475         struct ctl_lun *lun;
5476         struct ctl_softc *ctl_softc;
5477         int retval;
5478
5479         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5480
5481         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5482         ctl_softc = control_softc;
5483         retval = 0;
5484
5485         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5486
5487         /*
5488          * XXX KDM
5489          * We don't support the immediate bit on a stop unit.  In order to
5490          * do that, we would need to code up a way to know that a stop is
5491          * pending, and hold off any new commands until it completes, one
5492          * way or another.  Then we could accept or reject those commands
5493          * depending on its status.  We would almost need to do the reverse
5494          * of what we do below for an immediate start -- return the copy of
5495          * the ctl_io to the FETD with status to send to the host (and to
5496          * free the copy!) and then free the original I/O once the stop
5497          * actually completes.  That way, the OOA queue mechanism can work
5498          * to block commands that shouldn't proceed.  Another alternative
5499          * would be to put the copy in the queue in place of the original,
5500          * and return the original back to the caller.  That could be
5501          * slightly safer..
5502          */
5503         if ((cdb->byte2 & SSS_IMMED)
5504          && ((cdb->how & SSS_START) == 0)) {
5505                 ctl_set_invalid_field(ctsio,
5506                                       /*sks_valid*/ 1,
5507                                       /*command*/ 1,
5508                                       /*field*/ 1,
5509                                       /*bit_valid*/ 1,
5510                                       /*bit*/ 0);
5511                 ctl_done((union ctl_io *)ctsio);
5512                 return (CTL_RETVAL_COMPLETE);
5513         }
5514
5515         if ((lun->flags & CTL_LUN_PR_RESERVED)
5516          && ((cdb->how & SSS_START)==0)) {
5517                 uint32_t residx;
5518
5519                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5520                 if (!lun->per_res[residx].registered
5521                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5522
5523                         ctl_set_reservation_conflict(ctsio);
5524                         ctl_done((union ctl_io *)ctsio);
5525                         return (CTL_RETVAL_COMPLETE);
5526                 }
5527         }
5528
5529         /*
5530          * If there is no backend on this device, we can't start or stop
5531          * it.  In theory we shouldn't get any start/stop commands in the
5532          * first place at this level if the LUN doesn't have a backend.
5533          * That should get stopped by the command decode code.
5534          */
5535         if (lun->backend == NULL) {
5536                 ctl_set_invalid_opcode(ctsio);
5537                 ctl_done((union ctl_io *)ctsio);
5538                 return (CTL_RETVAL_COMPLETE);
5539         }
5540
5541         /*
5542          * XXX KDM Copan-specific offline behavior.
5543          * Figure out a reasonable way to port this?
5544          */
5545 #ifdef NEEDTOPORT
5546         mtx_lock(&lun->lun_lock);
5547
5548         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5549          && (lun->flags & CTL_LUN_OFFLINE)) {
5550                 /*
5551                  * If the LUN is offline, and the on/offline bit isn't set,
5552                  * reject the start or stop.  Otherwise, let it through.
5553                  */
5554                 mtx_unlock(&lun->lun_lock);
5555                 ctl_set_lun_not_ready(ctsio);
5556                 ctl_done((union ctl_io *)ctsio);
5557         } else {
5558                 mtx_unlock(&lun->lun_lock);
5559 #endif /* NEEDTOPORT */
5560                 /*
5561                  * This could be a start or a stop when we're online,
5562                  * or a stop/offline or start/online.  A start or stop when
5563                  * we're offline is covered in the case above.
5564                  */
5565                 /*
5566                  * In the non-immediate case, we send the request to
5567                  * the backend and return status to the user when
5568                  * it is done.
5569                  *
5570                  * In the immediate case, we allocate a new ctl_io
5571                  * to hold a copy of the request, and send that to
5572                  * the backend.  We then set good status on the
5573                  * user's request and return it immediately.
5574                  */
5575                 if (cdb->byte2 & SSS_IMMED) {
5576                         union ctl_io *new_io;
5577
5578                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5579                         if (new_io == NULL) {
5580                                 ctl_set_busy(ctsio);
5581                                 ctl_done((union ctl_io *)ctsio);
5582                         } else {
5583                                 ctl_copy_io((union ctl_io *)ctsio,
5584                                             new_io);
5585                                 retval = lun->backend->config_write(new_io);
5586                                 ctl_set_success(ctsio);
5587                                 ctl_done((union ctl_io *)ctsio);
5588                         }
5589                 } else {
5590                         retval = lun->backend->config_write(
5591                                 (union ctl_io *)ctsio);
5592                 }
5593 #ifdef NEEDTOPORT
5594         }
5595 #endif
5596         return (retval);
5597 }
5598
5599 /*
5600  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5601  * we don't really do anything with the LBA and length fields if the user
5602  * passes them in.  Instead we'll just flush out the cache for the entire
5603  * LUN.
5604  */
5605 int
5606 ctl_sync_cache(struct ctl_scsiio *ctsio)
5607 {
5608         struct ctl_lun *lun;
5609         struct ctl_softc *ctl_softc;
5610         uint64_t starting_lba;
5611         uint32_t block_count;
5612         int retval;
5613
5614         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5615
5616         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5617         ctl_softc = control_softc;
5618         retval = 0;
5619
5620         switch (ctsio->cdb[0]) {
5621         case SYNCHRONIZE_CACHE: {
5622                 struct scsi_sync_cache *cdb;
5623                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5624
5625                 starting_lba = scsi_4btoul(cdb->begin_lba);
5626                 block_count = scsi_2btoul(cdb->lb_count);
5627                 break;
5628         }
5629         case SYNCHRONIZE_CACHE_16: {
5630                 struct scsi_sync_cache_16 *cdb;
5631                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5632
5633                 starting_lba = scsi_8btou64(cdb->begin_lba);
5634                 block_count = scsi_4btoul(cdb->lb_count);
5635                 break;
5636         }
5637         default:
5638                 ctl_set_invalid_opcode(ctsio);
5639                 ctl_done((union ctl_io *)ctsio);
5640                 goto bailout;
5641                 break; /* NOTREACHED */
5642         }
5643
5644         /*
5645          * We check the LBA and length, but don't do anything with them.
5646          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5647          * get flushed.  This check will just help satisfy anyone who wants
5648          * to see an error for an out of range LBA.
5649          */
5650         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5651                 ctl_set_lba_out_of_range(ctsio);
5652                 ctl_done((union ctl_io *)ctsio);
5653                 goto bailout;
5654         }
5655
5656         /*
5657          * If this LUN has no backend, we can't flush the cache anyway.
5658          */
5659         if (lun->backend == NULL) {
5660                 ctl_set_invalid_opcode(ctsio);
5661                 ctl_done((union ctl_io *)ctsio);
5662                 goto bailout;
5663         }
5664
5665         /*
5666          * Check to see whether we're configured to send the SYNCHRONIZE
5667          * CACHE command directly to the back end.
5668          */
5669         mtx_lock(&lun->lun_lock);
5670         if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5671          && (++(lun->sync_count) >= lun->sync_interval)) {
5672                 lun->sync_count = 0;
5673                 mtx_unlock(&lun->lun_lock);
5674                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5675         } else {
5676                 mtx_unlock(&lun->lun_lock);
5677                 ctl_set_success(ctsio);
5678                 ctl_done((union ctl_io *)ctsio);
5679         }
5680
5681 bailout:
5682
5683         return (retval);
5684 }
5685
5686 int
5687 ctl_format(struct ctl_scsiio *ctsio)
5688 {
5689         struct scsi_format *cdb;
5690         struct ctl_lun *lun;
5691         struct ctl_softc *ctl_softc;
5692         int length, defect_list_len;
5693
5694         CTL_DEBUG_PRINT(("ctl_format\n"));
5695
5696         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5697         ctl_softc = control_softc;
5698
5699         cdb = (struct scsi_format *)ctsio->cdb;
5700
5701         length = 0;
5702         if (cdb->byte2 & SF_FMTDATA) {
5703                 if (cdb->byte2 & SF_LONGLIST)
5704                         length = sizeof(struct scsi_format_header_long);
5705                 else
5706                         length = sizeof(struct scsi_format_header_short);
5707         }
5708
5709         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5710          && (length > 0)) {
5711                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5712                 ctsio->kern_data_len = length;
5713                 ctsio->kern_total_len = length;
5714                 ctsio->kern_data_resid = 0;
5715                 ctsio->kern_rel_offset = 0;
5716                 ctsio->kern_sg_entries = 0;
5717                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5718                 ctsio->be_move_done = ctl_config_move_done;
5719                 ctl_datamove((union ctl_io *)ctsio);
5720
5721                 return (CTL_RETVAL_COMPLETE);
5722         }
5723
5724         defect_list_len = 0;
5725
5726         if (cdb->byte2 & SF_FMTDATA) {
5727                 if (cdb->byte2 & SF_LONGLIST) {
5728                         struct scsi_format_header_long *header;
5729
5730                         header = (struct scsi_format_header_long *)
5731                                 ctsio->kern_data_ptr;
5732
5733                         defect_list_len = scsi_4btoul(header->defect_list_len);
5734                         if (defect_list_len != 0) {
5735                                 ctl_set_invalid_field(ctsio,
5736                                                       /*sks_valid*/ 1,
5737                                                       /*command*/ 0,
5738                                                       /*field*/ 2,
5739                                                       /*bit_valid*/ 0,
5740                                                       /*bit*/ 0);
5741                                 goto bailout;
5742                         }
5743                 } else {
5744                         struct scsi_format_header_short *header;
5745
5746                         header = (struct scsi_format_header_short *)
5747                                 ctsio->kern_data_ptr;
5748
5749                         defect_list_len = scsi_2btoul(header->defect_list_len);
5750                         if (defect_list_len != 0) {
5751                                 ctl_set_invalid_field(ctsio,
5752                                                       /*sks_valid*/ 1,
5753                                                       /*command*/ 0,
5754                                                       /*field*/ 2,
5755                                                       /*bit_valid*/ 0,
5756                                                       /*bit*/ 0);
5757                                 goto bailout;
5758                         }
5759                 }
5760         }
5761
5762         /*
5763          * The format command will clear out the "Medium format corrupted"
5764          * status if set by the configuration code.  That status is really
5765          * just a way to notify the host that we have lost the media, and
5766          * get them to issue a command that will basically make them think
5767          * they're blowing away the media.
5768          */
5769         mtx_lock(&lun->lun_lock);
5770         lun->flags &= ~CTL_LUN_INOPERABLE;
5771         mtx_unlock(&lun->lun_lock);
5772
5773         ctsio->scsi_status = SCSI_STATUS_OK;
5774         ctsio->io_hdr.status = CTL_SUCCESS;
5775 bailout:
5776
5777         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5778                 free(ctsio->kern_data_ptr, M_CTL);
5779                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5780         }
5781
5782         ctl_done((union ctl_io *)ctsio);
5783         return (CTL_RETVAL_COMPLETE);
5784 }
5785
5786 int
5787 ctl_read_buffer(struct ctl_scsiio *ctsio)
5788 {
5789         struct scsi_read_buffer *cdb;
5790         struct ctl_lun *lun;
5791         int buffer_offset, len;
5792         static uint8_t descr[4];
5793         static uint8_t echo_descr[4] = { 0 };
5794
5795         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5796
5797         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5798         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5799
5800         if (lun->flags & CTL_LUN_PR_RESERVED) {
5801                 uint32_t residx;
5802
5803                 /*
5804                  * XXX KDM need a lock here.
5805                  */
5806                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5807                 if ((lun->res_type == SPR_TYPE_EX_AC
5808                   && residx != lun->pr_res_idx)
5809                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
5810                    || lun->res_type == SPR_TYPE_EX_AC_AR)
5811                   && !lun->per_res[residx].registered)) {
5812                         ctl_set_reservation_conflict(ctsio);
5813                         ctl_done((union ctl_io *)ctsio);
5814                         return (CTL_RETVAL_COMPLETE);
5815                 }
5816         }
5817
5818         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5819             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5820             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5821                 ctl_set_invalid_field(ctsio,
5822                                       /*sks_valid*/ 1,
5823                                       /*command*/ 1,
5824                                       /*field*/ 1,
5825                                       /*bit_valid*/ 1,
5826                                       /*bit*/ 4);
5827                 ctl_done((union ctl_io *)ctsio);
5828                 return (CTL_RETVAL_COMPLETE);
5829         }
5830
5831         len = scsi_3btoul(cdb->length);
5832         buffer_offset = scsi_3btoul(cdb->offset);
5833
5834         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5835                 ctl_set_invalid_field(ctsio,
5836                                       /*sks_valid*/ 1,
5837                                       /*command*/ 1,
5838                                       /*field*/ 6,
5839                                       /*bit_valid*/ 0,
5840                                       /*bit*/ 0);
5841                 ctl_done((union ctl_io *)ctsio);
5842                 return (CTL_RETVAL_COMPLETE);
5843         }
5844
5845         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5846                 descr[0] = 0;
5847                 scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5848                 ctsio->kern_data_ptr = descr;
5849                 len = min(len, sizeof(descr));
5850         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5851                 ctsio->kern_data_ptr = echo_descr;
5852                 len = min(len, sizeof(echo_descr));
5853         } else
5854                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5855         ctsio->kern_data_len = len;
5856         ctsio->kern_total_len = len;
5857         ctsio->kern_data_resid = 0;
5858         ctsio->kern_rel_offset = 0;
5859         ctsio->kern_sg_entries = 0;
5860         ctsio->be_move_done = ctl_config_move_done;
5861         ctl_datamove((union ctl_io *)ctsio);
5862
5863         return (CTL_RETVAL_COMPLETE);
5864 }
5865
5866 int
5867 ctl_write_buffer(struct ctl_scsiio *ctsio)
5868 {
5869         struct scsi_write_buffer *cdb;
5870         struct ctl_lun *lun;
5871         int buffer_offset, len;
5872
5873         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5874
5875         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5876         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5877
5878         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5879                 ctl_set_invalid_field(ctsio,
5880                                       /*sks_valid*/ 1,
5881                                       /*command*/ 1,
5882                                       /*field*/ 1,
5883                                       /*bit_valid*/ 1,
5884                                       /*bit*/ 4);
5885                 ctl_done((union ctl_io *)ctsio);
5886                 return (CTL_RETVAL_COMPLETE);
5887         }
5888
5889         len = scsi_3btoul(cdb->length);
5890         buffer_offset = scsi_3btoul(cdb->offset);
5891
5892         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5893                 ctl_set_invalid_field(ctsio,
5894                                       /*sks_valid*/ 1,
5895                                       /*command*/ 1,
5896                                       /*field*/ 6,
5897                                       /*bit_valid*/ 0,
5898                                       /*bit*/ 0);
5899                 ctl_done((union ctl_io *)ctsio);
5900                 return (CTL_RETVAL_COMPLETE);
5901         }
5902
5903         /*
5904          * If we've got a kernel request that hasn't been malloced yet,
5905          * malloc it and tell the caller the data buffer is here.
5906          */
5907         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5908                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5909                 ctsio->kern_data_len = len;
5910                 ctsio->kern_total_len = len;
5911                 ctsio->kern_data_resid = 0;
5912                 ctsio->kern_rel_offset = 0;
5913                 ctsio->kern_sg_entries = 0;
5914                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5915                 ctsio->be_move_done = ctl_config_move_done;
5916                 ctl_datamove((union ctl_io *)ctsio);
5917
5918                 return (CTL_RETVAL_COMPLETE);
5919         }
5920
5921         ctl_done((union ctl_io *)ctsio);
5922
5923         return (CTL_RETVAL_COMPLETE);
5924 }
5925
5926 int
5927 ctl_write_same(struct ctl_scsiio *ctsio)
5928 {
5929         struct ctl_lun *lun;
5930         struct ctl_lba_len_flags *lbalen;
5931         uint64_t lba;
5932         uint32_t num_blocks;
5933         int len, retval;
5934         uint8_t byte2;
5935
5936         retval = CTL_RETVAL_COMPLETE;
5937
5938         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5939
5940         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5941
5942         switch (ctsio->cdb[0]) {
5943         case WRITE_SAME_10: {
5944                 struct scsi_write_same_10 *cdb;
5945
5946                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5947
5948                 lba = scsi_4btoul(cdb->addr);
5949                 num_blocks = scsi_2btoul(cdb->length);
5950                 byte2 = cdb->byte2;
5951                 break;
5952         }
5953         case WRITE_SAME_16: {
5954                 struct scsi_write_same_16 *cdb;
5955
5956                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5957
5958                 lba = scsi_8btou64(cdb->addr);
5959                 num_blocks = scsi_4btoul(cdb->length);
5960                 byte2 = cdb->byte2;
5961                 break;
5962         }
5963         default:
5964                 /*
5965                  * We got a command we don't support.  This shouldn't
5966                  * happen, commands should be filtered out above us.
5967                  */
5968                 ctl_set_invalid_opcode(ctsio);
5969                 ctl_done((union ctl_io *)ctsio);
5970
5971                 return (CTL_RETVAL_COMPLETE);
5972                 break; /* NOTREACHED */
5973         }
5974
5975         /*
5976          * The first check is to make sure we're in bounds, the second
5977          * check is to catch wrap-around problems.  If the lba + num blocks
5978          * is less than the lba, then we've wrapped around and the block
5979          * range is invalid anyway.
5980          */
5981         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5982          || ((lba + num_blocks) < lba)) {
5983                 ctl_set_lba_out_of_range(ctsio);
5984                 ctl_done((union ctl_io *)ctsio);
5985                 return (CTL_RETVAL_COMPLETE);
5986         }
5987
5988         /* Zero number of blocks means "to the last logical block" */
5989         if (num_blocks == 0) {
5990                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5991                         ctl_set_invalid_field(ctsio,
5992                                               /*sks_valid*/ 0,
5993                                               /*command*/ 1,
5994                                               /*field*/ 0,
5995                                               /*bit_valid*/ 0,
5996                                               /*bit*/ 0);
5997                         ctl_done((union ctl_io *)ctsio);
5998                         return (CTL_RETVAL_COMPLETE);
5999                 }
6000                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
6001         }
6002
6003         len = lun->be_lun->blocksize;
6004
6005         /*
6006          * If we've got a kernel request that hasn't been malloced yet,
6007          * malloc it and tell the caller the data buffer is here.
6008          */
6009         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6010                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6011                 ctsio->kern_data_len = len;
6012                 ctsio->kern_total_len = len;
6013                 ctsio->kern_data_resid = 0;
6014                 ctsio->kern_rel_offset = 0;
6015                 ctsio->kern_sg_entries = 0;
6016                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6017                 ctsio->be_move_done = ctl_config_move_done;
6018                 ctl_datamove((union ctl_io *)ctsio);
6019
6020                 return (CTL_RETVAL_COMPLETE);
6021         }
6022
6023         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6024         lbalen->lba = lba;
6025         lbalen->len = num_blocks;
6026         lbalen->flags = byte2;
6027         retval = lun->backend->config_write((union ctl_io *)ctsio);
6028
6029         return (retval);
6030 }
6031
6032 int
6033 ctl_unmap(struct ctl_scsiio *ctsio)
6034 {
6035         struct ctl_lun *lun;
6036         struct scsi_unmap *cdb;
6037         struct ctl_ptr_len_flags *ptrlen;
6038         struct scsi_unmap_header *hdr;
6039         struct scsi_unmap_desc *buf, *end;
6040         uint64_t lba;
6041         uint32_t num_blocks;
6042         int len, retval;
6043         uint8_t byte2;
6044
6045         retval = CTL_RETVAL_COMPLETE;
6046
6047         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6048
6049         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6050         cdb = (struct scsi_unmap *)ctsio->cdb;
6051
6052         len = scsi_2btoul(cdb->length);
6053         byte2 = cdb->byte2;
6054
6055         /*
6056          * If we've got a kernel request that hasn't been malloced yet,
6057          * malloc it and tell the caller the data buffer is here.
6058          */
6059         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6060                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6061                 ctsio->kern_data_len = len;
6062                 ctsio->kern_total_len = len;
6063                 ctsio->kern_data_resid = 0;
6064                 ctsio->kern_rel_offset = 0;
6065                 ctsio->kern_sg_entries = 0;
6066                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6067                 ctsio->be_move_done = ctl_config_move_done;
6068                 ctl_datamove((union ctl_io *)ctsio);
6069
6070                 return (CTL_RETVAL_COMPLETE);
6071         }
6072
6073         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6074         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6075         if (len < sizeof (*hdr) ||
6076             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6077             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6078             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6079                 ctl_set_invalid_field(ctsio,
6080                                       /*sks_valid*/ 0,
6081                                       /*command*/ 0,
6082                                       /*field*/ 0,
6083                                       /*bit_valid*/ 0,
6084                                       /*bit*/ 0);
6085                 ctl_done((union ctl_io *)ctsio);
6086                 return (CTL_RETVAL_COMPLETE);
6087         }
6088         len = scsi_2btoul(hdr->desc_length);
6089         buf = (struct scsi_unmap_desc *)(hdr + 1);
6090         end = buf + len / sizeof(*buf);
6091
6092         ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6093         ptrlen->ptr = (void *)buf;
6094         ptrlen->len = len;
6095         ptrlen->flags = byte2;
6096
6097         for (; buf < end; buf++) {
6098                 lba = scsi_8btou64(buf->lba);
6099                 num_blocks = scsi_4btoul(buf->length);
6100                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6101                  || ((lba + num_blocks) < lba)) {
6102                         ctl_set_lba_out_of_range(ctsio);
6103                         ctl_done((union ctl_io *)ctsio);
6104                         return (CTL_RETVAL_COMPLETE);
6105                 }
6106         }
6107
6108         retval = lun->backend->config_write((union ctl_io *)ctsio);
6109
6110         return (retval);
6111 }
6112
6113 /*
6114  * Note that this function currently doesn't actually do anything inside
6115  * CTL to enforce things if the DQue bit is turned on.
6116  *
6117  * Also note that this function can't be used in the default case, because
6118  * the DQue bit isn't set in the changeable mask for the control mode page
6119  * anyway.  This is just here as an example for how to implement a page
6120  * handler, and a placeholder in case we want to allow the user to turn
6121  * tagged queueing on and off.
6122  *
6123  * The D_SENSE bit handling is functional, however, and will turn
6124  * descriptor sense on and off for a given LUN.
6125  */
6126 int
6127 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6128                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6129 {
6130         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6131         struct ctl_lun *lun;
6132         struct ctl_softc *softc;
6133         int set_ua;
6134         uint32_t initidx;
6135
6136         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6137         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6138         set_ua = 0;
6139
6140         user_cp = (struct scsi_control_page *)page_ptr;
6141         current_cp = (struct scsi_control_page *)
6142                 (page_index->page_data + (page_index->page_len *
6143                 CTL_PAGE_CURRENT));
6144         saved_cp = (struct scsi_control_page *)
6145                 (page_index->page_data + (page_index->page_len *
6146                 CTL_PAGE_SAVED));
6147
6148         softc = control_softc;
6149
6150         mtx_lock(&lun->lun_lock);
6151         if (((current_cp->rlec & SCP_DSENSE) == 0)
6152          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6153                 /*
6154                  * Descriptor sense is currently turned off and the user
6155                  * wants to turn it on.
6156                  */
6157                 current_cp->rlec |= SCP_DSENSE;
6158                 saved_cp->rlec |= SCP_DSENSE;
6159                 lun->flags |= CTL_LUN_SENSE_DESC;
6160                 set_ua = 1;
6161         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6162                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6163                 /*
6164                  * Descriptor sense is currently turned on, and the user
6165                  * wants to turn it off.
6166                  */
6167                 current_cp->rlec &= ~SCP_DSENSE;
6168                 saved_cp->rlec &= ~SCP_DSENSE;
6169                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6170                 set_ua = 1;
6171         }
6172         if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6173                 if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6174 #ifdef NEEDTOPORT
6175                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6176                                     CTL_UNTAG_TO_UNTAG,
6177                                     csevent_LogType_Trace,
6178                                     csevent_Severity_Information,
6179                                     csevent_AlertLevel_Green,
6180                                     csevent_FRU_Firmware,
6181                                     csevent_FRU_Unknown,
6182                                     "Received untagged to untagged transition");
6183 #endif /* NEEDTOPORT */
6184                 } else {
6185 #ifdef NEEDTOPORT
6186                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6187                                     CTL_UNTAG_TO_TAG,
6188                                     csevent_LogType_ConfigChange,
6189                                     csevent_Severity_Information,
6190                                     csevent_AlertLevel_Green,
6191                                     csevent_FRU_Firmware,
6192                                     csevent_FRU_Unknown,
6193                                     "Received untagged to tagged "
6194                                     "queueing transition");
6195 #endif /* NEEDTOPORT */
6196
6197                         current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6198                         saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6199                         set_ua = 1;
6200                 }
6201         } else {
6202                 if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6203 #ifdef NEEDTOPORT
6204                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6205                                     CTL_TAG_TO_UNTAG,
6206                                     csevent_LogType_ConfigChange,
6207                                     csevent_Severity_Warning,
6208                                     csevent_AlertLevel_Yellow,
6209                                     csevent_FRU_Firmware,
6210                                     csevent_FRU_Unknown,
6211                                     "Received tagged queueing to untagged "
6212                                     "transition");
6213 #endif /* NEEDTOPORT */
6214
6215                         current_cp->queue_flags |= SCP_QUEUE_DQUE;
6216                         saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6217                         set_ua = 1;
6218                 } else {
6219 #ifdef NEEDTOPORT
6220                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6221                                     CTL_TAG_TO_TAG,
6222                                     csevent_LogType_Trace,
6223                                     csevent_Severity_Information,
6224                                     csevent_AlertLevel_Green,
6225                                     csevent_FRU_Firmware,
6226                                     csevent_FRU_Unknown,
6227                                     "Received tagged queueing to tagged "
6228                                     "queueing transition");
6229 #endif /* NEEDTOPORT */
6230                 }
6231         }
6232         if (set_ua != 0) {
6233                 int i;
6234                 /*
6235                  * Let other initiators know that the mode
6236                  * parameters for this LUN have changed.
6237                  */
6238                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6239                         if (i == initidx)
6240                                 continue;
6241
6242                         lun->pending_sense[i].ua_pending |=
6243                                 CTL_UA_MODE_CHANGE;
6244                 }
6245         }
6246         mtx_unlock(&lun->lun_lock);
6247
6248         return (0);
6249 }
6250
6251 int
6252 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6253                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6254 {
6255         return (0);
6256 }
6257
6258 int
6259 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6260                            struct ctl_page_index *page_index, int pc)
6261 {
6262         struct copan_power_subpage *page;
6263
6264         page = (struct copan_power_subpage *)page_index->page_data +
6265                 (page_index->page_len * pc);
6266
6267         switch (pc) {
6268         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6269                 /*
6270                  * We don't update the changable bits for this page.
6271                  */
6272                 break;
6273         case SMS_PAGE_CTRL_CURRENT >> 6:
6274         case SMS_PAGE_CTRL_DEFAULT >> 6:
6275         case SMS_PAGE_CTRL_SAVED >> 6:
6276 #ifdef NEEDTOPORT
6277                 ctl_update_power_subpage(page);
6278 #endif
6279                 break;
6280         default:
6281 #ifdef NEEDTOPORT
6282                 EPRINT(0, "Invalid PC %d!!", pc);
6283 #endif
6284                 break;
6285         }
6286         return (0);
6287 }
6288
6289
6290 int
6291 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6292                    struct ctl_page_index *page_index, uint8_t *page_ptr)
6293 {
6294         struct copan_aps_subpage *user_sp;
6295         struct copan_aps_subpage *current_sp;
6296         union ctl_modepage_info *modepage_info;
6297         struct ctl_softc *softc;
6298         struct ctl_lun *lun;
6299         int retval;
6300
6301         retval = CTL_RETVAL_COMPLETE;
6302         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6303                      (page_index->page_len * CTL_PAGE_CURRENT));
6304         softc = control_softc;
6305         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6306
6307         user_sp = (struct copan_aps_subpage *)page_ptr;
6308
6309         modepage_info = (union ctl_modepage_info *)
6310                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6311
6312         modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6313         modepage_info->header.subpage = page_index->subpage;
6314         modepage_info->aps.lock_active = user_sp->lock_active;
6315
6316         mtx_lock(&softc->ctl_lock);
6317
6318         /*
6319          * If there is a request to lock the LUN and another LUN is locked
6320          * this is an error. If the requested LUN is already locked ignore
6321          * the request. If no LUN is locked attempt to lock it.
6322          * if there is a request to unlock the LUN and the LUN is currently
6323          * locked attempt to unlock it. Otherwise ignore the request. i.e.
6324          * if another LUN is locked or no LUN is locked.
6325          */
6326         if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6327                 if (softc->aps_locked_lun == lun->lun) {
6328                         /*
6329                          * This LUN is already locked, so we're done.
6330                          */
6331                         retval = CTL_RETVAL_COMPLETE;
6332                 } else if (softc->aps_locked_lun == 0) {
6333                         /*
6334                          * No one has the lock, pass the request to the
6335                          * backend.
6336                          */
6337                         retval = lun->backend->config_write(
6338                                 (union ctl_io *)ctsio);
6339                 } else {
6340                         /*
6341                          * Someone else has the lock, throw out the request.
6342                          */
6343                         ctl_set_already_locked(ctsio);
6344                         free(ctsio->kern_data_ptr, M_CTL);
6345                         ctl_done((union ctl_io *)ctsio);
6346
6347                         /*
6348                          * Set the return value so that ctl_do_mode_select()
6349                          * won't try to complete the command.  We already
6350                          * completed it here.
6351                          */
6352                         retval = CTL_RETVAL_ERROR;
6353                 }
6354         } else if (softc->aps_locked_lun == lun->lun) {
6355                 /*
6356                  * This LUN is locked, so pass the unlock request to the
6357                  * backend.
6358                  */
6359                 retval = lun->backend->config_write((union ctl_io *)ctsio);
6360         }
6361         mtx_unlock(&softc->ctl_lock);
6362
6363         return (retval);
6364 }
6365
6366 int
6367 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6368                                 struct ctl_page_index *page_index,
6369                                 uint8_t *page_ptr)
6370 {
6371         uint8_t *c;
6372         int i;
6373
6374         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6375         ctl_time_io_secs =
6376                 (c[0] << 8) |
6377                 (c[1] << 0) |
6378                 0;
6379         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6380         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6381         printf("page data:");
6382         for (i=0; i<8; i++)
6383                 printf(" %.2x",page_ptr[i]);
6384         printf("\n");
6385         return (0);
6386 }
6387
6388 int
6389 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6390                                struct ctl_page_index *page_index,
6391                                int pc)
6392 {
6393         struct copan_debugconf_subpage *page;
6394
6395         page = (struct copan_debugconf_subpage *)page_index->page_data +
6396                 (page_index->page_len * pc);
6397
6398         switch (pc) {
6399         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6400         case SMS_PAGE_CTRL_DEFAULT >> 6:
6401         case SMS_PAGE_CTRL_SAVED >> 6:
6402                 /*
6403                  * We don't update the changable or default bits for this page.
6404                  */
6405                 break;
6406         case SMS_PAGE_CTRL_CURRENT >> 6:
6407                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6408                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6409                 break;
6410         default:
6411 #ifdef NEEDTOPORT
6412                 EPRINT(0, "Invalid PC %d!!", pc);
6413 #endif /* NEEDTOPORT */
6414                 break;
6415         }
6416         return (0);
6417 }
6418
6419
6420 static int
6421 ctl_do_mode_select(union ctl_io *io)
6422 {
6423         struct scsi_mode_page_header *page_header;
6424         struct ctl_page_index *page_index;
6425         struct ctl_scsiio *ctsio;
6426         int control_dev, page_len;
6427         int page_len_offset, page_len_size;
6428         union ctl_modepage_info *modepage_info;
6429         struct ctl_lun *lun;
6430         int *len_left, *len_used;
6431         int retval, i;
6432
6433         ctsio = &io->scsiio;
6434         page_index = NULL;
6435         page_len = 0;
6436         retval = CTL_RETVAL_COMPLETE;
6437
6438         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6439
6440         if (lun->be_lun->lun_type != T_DIRECT)
6441                 control_dev = 1;
6442         else
6443                 control_dev = 0;
6444
6445         modepage_info = (union ctl_modepage_info *)
6446                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6447         len_left = &modepage_info->header.len_left;
6448         len_used = &modepage_info->header.len_used;
6449
6450 do_next_page:
6451
6452         page_header = (struct scsi_mode_page_header *)
6453                 (ctsio->kern_data_ptr + *len_used);
6454
6455         if (*len_left == 0) {
6456                 free(ctsio->kern_data_ptr, M_CTL);
6457                 ctl_set_success(ctsio);
6458                 ctl_done((union ctl_io *)ctsio);
6459                 return (CTL_RETVAL_COMPLETE);
6460         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6461
6462                 free(ctsio->kern_data_ptr, M_CTL);
6463                 ctl_set_param_len_error(ctsio);
6464                 ctl_done((union ctl_io *)ctsio);
6465                 return (CTL_RETVAL_COMPLETE);
6466
6467         } else if ((page_header->page_code & SMPH_SPF)
6468                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6469
6470                 free(ctsio->kern_data_ptr, M_CTL);
6471                 ctl_set_param_len_error(ctsio);
6472                 ctl_done((union ctl_io *)ctsio);
6473                 return (CTL_RETVAL_COMPLETE);
6474         }
6475
6476
6477         /*
6478          * XXX KDM should we do something with the block descriptor?
6479          */
6480         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6481
6482                 if ((control_dev != 0)
6483                  && (lun->mode_pages.index[i].page_flags &
6484                      CTL_PAGE_FLAG_DISK_ONLY))
6485                         continue;
6486
6487                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6488                     (page_header->page_code & SMPH_PC_MASK))
6489                         continue;
6490
6491                 /*
6492                  * If neither page has a subpage code, then we've got a
6493                  * match.
6494                  */
6495                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6496                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6497                         page_index = &lun->mode_pages.index[i];
6498                         page_len = page_header->page_length;
6499                         break;
6500                 }
6501
6502                 /*
6503                  * If both pages have subpages, then the subpage numbers
6504                  * have to match.
6505                  */
6506                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6507                   && (page_header->page_code & SMPH_SPF)) {
6508                         struct scsi_mode_page_header_sp *sph;
6509
6510                         sph = (struct scsi_mode_page_header_sp *)page_header;
6511
6512                         if (lun->mode_pages.index[i].subpage ==
6513                             sph->subpage) {
6514                                 page_index = &lun->mode_pages.index[i];
6515                                 page_len = scsi_2btoul(sph->page_length);
6516                                 break;
6517                         }
6518                 }
6519         }
6520
6521         /*
6522          * If we couldn't find the page, or if we don't have a mode select
6523          * handler for it, send back an error to the user.
6524          */
6525         if ((page_index == NULL)
6526          || (page_index->select_handler == NULL)) {
6527                 ctl_set_invalid_field(ctsio,
6528                                       /*sks_valid*/ 1,
6529                                       /*command*/ 0,
6530                                       /*field*/ *len_used,
6531                                       /*bit_valid*/ 0,
6532                                       /*bit*/ 0);
6533                 free(ctsio->kern_data_ptr, M_CTL);
6534                 ctl_done((union ctl_io *)ctsio);
6535                 return (CTL_RETVAL_COMPLETE);
6536         }
6537
6538         if (page_index->page_code & SMPH_SPF) {
6539                 page_len_offset = 2;
6540                 page_len_size = 2;
6541         } else {
6542                 page_len_size = 1;
6543                 page_len_offset = 1;
6544         }
6545
6546         /*
6547          * If the length the initiator gives us isn't the one we specify in
6548          * the mode page header, or if they didn't specify enough data in
6549          * the CDB to avoid truncating this page, kick out the request.
6550          */
6551         if ((page_len != (page_index->page_len - page_len_offset -
6552                           page_len_size))
6553          || (*len_left < page_index->page_len)) {
6554
6555
6556                 ctl_set_invalid_field(ctsio,
6557                                       /*sks_valid*/ 1,
6558                                       /*command*/ 0,
6559                                       /*field*/ *len_used + page_len_offset,
6560                                       /*bit_valid*/ 0,
6561                                       /*bit*/ 0);
6562                 free(ctsio->kern_data_ptr, M_CTL);
6563                 ctl_done((union ctl_io *)ctsio);
6564                 return (CTL_RETVAL_COMPLETE);
6565         }
6566
6567         /*
6568          * Run through the mode page, checking to make sure that the bits
6569          * the user changed are actually legal for him to change.
6570          */
6571         for (i = 0; i < page_index->page_len; i++) {
6572                 uint8_t *user_byte, *change_mask, *current_byte;
6573                 int bad_bit;
6574                 int j;
6575
6576                 user_byte = (uint8_t *)page_header + i;
6577                 change_mask = page_index->page_data +
6578                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6579                 current_byte = page_index->page_data +
6580                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6581
6582                 /*
6583                  * Check to see whether the user set any bits in this byte
6584                  * that he is not allowed to set.
6585                  */
6586                 if ((*user_byte & ~(*change_mask)) ==
6587                     (*current_byte & ~(*change_mask)))
6588                         continue;
6589
6590                 /*
6591                  * Go through bit by bit to determine which one is illegal.
6592                  */
6593                 bad_bit = 0;
6594                 for (j = 7; j >= 0; j--) {
6595                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6596                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6597                                 bad_bit = i;
6598                                 break;
6599                         }
6600                 }
6601                 ctl_set_invalid_field(ctsio,
6602                                       /*sks_valid*/ 1,
6603                                       /*command*/ 0,
6604                                       /*field*/ *len_used + i,
6605                                       /*bit_valid*/ 1,
6606                                       /*bit*/ bad_bit);
6607                 free(ctsio->kern_data_ptr, M_CTL);
6608                 ctl_done((union ctl_io *)ctsio);
6609                 return (CTL_RETVAL_COMPLETE);
6610         }
6611
6612         /*
6613          * Decrement these before we call the page handler, since we may
6614          * end up getting called back one way or another before the handler
6615          * returns to this context.
6616          */
6617         *len_left -= page_index->page_len;
6618         *len_used += page_index->page_len;
6619
6620         retval = page_index->select_handler(ctsio, page_index,
6621                                             (uint8_t *)page_header);
6622
6623         /*
6624          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6625          * wait until this queued command completes to finish processing
6626          * the mode page.  If it returns anything other than
6627          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6628          * already set the sense information, freed the data pointer, and
6629          * completed the io for us.
6630          */
6631         if (retval != CTL_RETVAL_COMPLETE)
6632                 goto bailout_no_done;
6633
6634         /*
6635          * If the initiator sent us more than one page, parse the next one.
6636          */
6637         if (*len_left > 0)
6638                 goto do_next_page;
6639
6640         ctl_set_success(ctsio);
6641         free(ctsio->kern_data_ptr, M_CTL);
6642         ctl_done((union ctl_io *)ctsio);
6643
6644 bailout_no_done:
6645
6646         return (CTL_RETVAL_COMPLETE);
6647
6648 }
6649
6650 int
6651 ctl_mode_select(struct ctl_scsiio *ctsio)
6652 {
6653         int param_len, pf, sp;
6654         int header_size, bd_len;
6655         int len_left, len_used;
6656         struct ctl_page_index *page_index;
6657         struct ctl_lun *lun;
6658         int control_dev, page_len;
6659         union ctl_modepage_info *modepage_info;
6660         int retval;
6661
6662         pf = 0;
6663         sp = 0;
6664         page_len = 0;
6665         len_used = 0;
6666         len_left = 0;
6667         retval = 0;
6668         bd_len = 0;
6669         page_index = NULL;
6670
6671         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6672
6673         if (lun->be_lun->lun_type != T_DIRECT)
6674                 control_dev = 1;
6675         else
6676                 control_dev = 0;
6677
6678         switch (ctsio->cdb[0]) {
6679         case MODE_SELECT_6: {
6680                 struct scsi_mode_select_6 *cdb;
6681
6682                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6683
6684                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6685                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6686
6687                 param_len = cdb->length;
6688                 header_size = sizeof(struct scsi_mode_header_6);
6689                 break;
6690         }
6691         case MODE_SELECT_10: {
6692                 struct scsi_mode_select_10 *cdb;
6693
6694                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6695
6696                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6697                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6698
6699                 param_len = scsi_2btoul(cdb->length);
6700                 header_size = sizeof(struct scsi_mode_header_10);
6701                 break;
6702         }
6703         default:
6704                 ctl_set_invalid_opcode(ctsio);
6705                 ctl_done((union ctl_io *)ctsio);
6706                 return (CTL_RETVAL_COMPLETE);
6707                 break; /* NOTREACHED */
6708         }
6709
6710         /*
6711          * From SPC-3:
6712          * "A parameter list length of zero indicates that the Data-Out Buffer
6713          * shall be empty. This condition shall not be considered as an error."
6714          */
6715         if (param_len == 0) {
6716                 ctl_set_success(ctsio);
6717                 ctl_done((union ctl_io *)ctsio);
6718                 return (CTL_RETVAL_COMPLETE);
6719         }
6720
6721         /*
6722          * Since we'll hit this the first time through, prior to
6723          * allocation, we don't need to free a data buffer here.
6724          */
6725         if (param_len < header_size) {
6726                 ctl_set_param_len_error(ctsio);
6727                 ctl_done((union ctl_io *)ctsio);
6728                 return (CTL_RETVAL_COMPLETE);
6729         }
6730
6731         /*
6732          * Allocate the data buffer and grab the user's data.  In theory,
6733          * we shouldn't have to sanity check the parameter list length here
6734          * because the maximum size is 64K.  We should be able to malloc
6735          * that much without too many problems.
6736          */
6737         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6738                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6739                 ctsio->kern_data_len = param_len;
6740                 ctsio->kern_total_len = param_len;
6741                 ctsio->kern_data_resid = 0;
6742                 ctsio->kern_rel_offset = 0;
6743                 ctsio->kern_sg_entries = 0;
6744                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6745                 ctsio->be_move_done = ctl_config_move_done;
6746                 ctl_datamove((union ctl_io *)ctsio);
6747
6748                 return (CTL_RETVAL_COMPLETE);
6749         }
6750
6751         switch (ctsio->cdb[0]) {
6752         case MODE_SELECT_6: {
6753                 struct scsi_mode_header_6 *mh6;
6754
6755                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6756                 bd_len = mh6->blk_desc_len;
6757                 break;
6758         }
6759         case MODE_SELECT_10: {
6760                 struct scsi_mode_header_10 *mh10;
6761
6762                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6763                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6764                 break;
6765         }
6766         default:
6767                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6768                 break;
6769         }
6770
6771         if (param_len < (header_size + bd_len)) {
6772                 free(ctsio->kern_data_ptr, M_CTL);
6773                 ctl_set_param_len_error(ctsio);
6774                 ctl_done((union ctl_io *)ctsio);
6775                 return (CTL_RETVAL_COMPLETE);
6776         }
6777
6778         /*
6779          * Set the IO_CONT flag, so that if this I/O gets passed to
6780          * ctl_config_write_done(), it'll get passed back to
6781          * ctl_do_mode_select() for further processing, or completion if
6782          * we're all done.
6783          */
6784         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6785         ctsio->io_cont = ctl_do_mode_select;
6786
6787         modepage_info = (union ctl_modepage_info *)
6788                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6789
6790         memset(modepage_info, 0, sizeof(*modepage_info));
6791
6792         len_left = param_len - header_size - bd_len;
6793         len_used = header_size + bd_len;
6794
6795         modepage_info->header.len_left = len_left;
6796         modepage_info->header.len_used = len_used;
6797
6798         return (ctl_do_mode_select((union ctl_io *)ctsio));
6799 }
6800
6801 int
6802 ctl_mode_sense(struct ctl_scsiio *ctsio)
6803 {
6804         struct ctl_lun *lun;
6805         int pc, page_code, dbd, llba, subpage;
6806         int alloc_len, page_len, header_len, total_len;
6807         struct scsi_mode_block_descr *block_desc;
6808         struct ctl_page_index *page_index;
6809         int control_dev;
6810
6811         dbd = 0;
6812         llba = 0;
6813         block_desc = NULL;
6814         page_index = NULL;
6815
6816         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6817
6818         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6819
6820         if (lun->be_lun->lun_type != T_DIRECT)
6821                 control_dev = 1;
6822         else
6823                 control_dev = 0;
6824
6825         if (lun->flags & CTL_LUN_PR_RESERVED) {
6826                 uint32_t residx;
6827
6828                 /*
6829                  * XXX KDM need a lock here.
6830                  */
6831                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6832                 if ((lun->res_type == SPR_TYPE_EX_AC
6833                   && residx != lun->pr_res_idx)
6834                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
6835                    || lun->res_type == SPR_TYPE_EX_AC_AR)
6836                   && !lun->per_res[residx].registered)) {
6837                         ctl_set_reservation_conflict(ctsio);
6838                         ctl_done((union ctl_io *)ctsio);
6839                         return (CTL_RETVAL_COMPLETE);
6840                 }
6841         }
6842
6843         switch (ctsio->cdb[0]) {
6844         case MODE_SENSE_6: {
6845                 struct scsi_mode_sense_6 *cdb;
6846
6847                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6848
6849                 header_len = sizeof(struct scsi_mode_hdr_6);
6850                 if (cdb->byte2 & SMS_DBD)
6851                         dbd = 1;
6852                 else
6853                         header_len += sizeof(struct scsi_mode_block_descr);
6854
6855                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6856                 page_code = cdb->page & SMS_PAGE_CODE;
6857                 subpage = cdb->subpage;
6858                 alloc_len = cdb->length;
6859                 break;
6860         }
6861         case MODE_SENSE_10: {
6862                 struct scsi_mode_sense_10 *cdb;
6863
6864                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6865
6866                 header_len = sizeof(struct scsi_mode_hdr_10);
6867
6868                 if (cdb->byte2 & SMS_DBD)
6869                         dbd = 1;
6870                 else
6871                         header_len += sizeof(struct scsi_mode_block_descr);
6872                 if (cdb->byte2 & SMS10_LLBAA)
6873                         llba = 1;
6874                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6875                 page_code = cdb->page & SMS_PAGE_CODE;
6876                 subpage = cdb->subpage;
6877                 alloc_len = scsi_2btoul(cdb->length);
6878                 break;
6879         }
6880         default:
6881                 ctl_set_invalid_opcode(ctsio);
6882                 ctl_done((union ctl_io *)ctsio);
6883                 return (CTL_RETVAL_COMPLETE);
6884                 break; /* NOTREACHED */
6885         }
6886
6887         /*
6888          * We have to make a first pass through to calculate the size of
6889          * the pages that match the user's query.  Then we allocate enough
6890          * memory to hold it, and actually copy the data into the buffer.
6891          */
6892         switch (page_code) {
6893         case SMS_ALL_PAGES_PAGE: {
6894                 int i;
6895
6896                 page_len = 0;
6897
6898                 /*
6899                  * At the moment, values other than 0 and 0xff here are
6900                  * reserved according to SPC-3.
6901                  */
6902                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6903                  && (subpage != SMS_SUBPAGE_ALL)) {
6904                         ctl_set_invalid_field(ctsio,
6905                                               /*sks_valid*/ 1,
6906                                               /*command*/ 1,
6907                                               /*field*/ 3,
6908                                               /*bit_valid*/ 0,
6909                                               /*bit*/ 0);
6910                         ctl_done((union ctl_io *)ctsio);
6911                         return (CTL_RETVAL_COMPLETE);
6912                 }
6913
6914                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6915                         if ((control_dev != 0)
6916                          && (lun->mode_pages.index[i].page_flags &
6917                              CTL_PAGE_FLAG_DISK_ONLY))
6918                                 continue;
6919
6920                         /*
6921                          * We don't use this subpage if the user didn't
6922                          * request all subpages.
6923                          */
6924                         if ((lun->mode_pages.index[i].subpage != 0)
6925                          && (subpage == SMS_SUBPAGE_PAGE_0))
6926                                 continue;
6927
6928 #if 0
6929                         printf("found page %#x len %d\n",
6930                                lun->mode_pages.index[i].page_code &
6931                                SMPH_PC_MASK,
6932                                lun->mode_pages.index[i].page_len);
6933 #endif
6934                         page_len += lun->mode_pages.index[i].page_len;
6935                 }
6936                 break;
6937         }
6938         default: {
6939                 int i;
6940
6941                 page_len = 0;
6942
6943                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6944                         /* Look for the right page code */
6945                         if ((lun->mode_pages.index[i].page_code &
6946                              SMPH_PC_MASK) != page_code)
6947                                 continue;
6948
6949                         /* Look for the right subpage or the subpage wildcard*/
6950                         if ((lun->mode_pages.index[i].subpage != subpage)
6951                          && (subpage != SMS_SUBPAGE_ALL))
6952                                 continue;
6953
6954                         /* Make sure the page is supported for this dev type */
6955                         if ((control_dev != 0)
6956                          && (lun->mode_pages.index[i].page_flags &
6957                              CTL_PAGE_FLAG_DISK_ONLY))
6958                                 continue;
6959
6960 #if 0
6961                         printf("found page %#x len %d\n",
6962                                lun->mode_pages.index[i].page_code &
6963                                SMPH_PC_MASK,
6964                                lun->mode_pages.index[i].page_len);
6965 #endif
6966
6967                         page_len += lun->mode_pages.index[i].page_len;
6968                 }
6969
6970                 if (page_len == 0) {
6971                         ctl_set_invalid_field(ctsio,
6972                                               /*sks_valid*/ 1,
6973                                               /*command*/ 1,
6974                                               /*field*/ 2,
6975                                               /*bit_valid*/ 1,
6976                                               /*bit*/ 5);
6977                         ctl_done((union ctl_io *)ctsio);
6978                         return (CTL_RETVAL_COMPLETE);
6979                 }
6980                 break;
6981         }
6982         }
6983
6984         total_len = header_len + page_len;
6985 #if 0
6986         printf("header_len = %d, page_len = %d, total_len = %d\n",
6987                header_len, page_len, total_len);
6988 #endif
6989
6990         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6991         ctsio->kern_sg_entries = 0;
6992         ctsio->kern_data_resid = 0;
6993         ctsio->kern_rel_offset = 0;
6994         if (total_len < alloc_len) {
6995                 ctsio->residual = alloc_len - total_len;
6996                 ctsio->kern_data_len = total_len;
6997                 ctsio->kern_total_len = total_len;
6998         } else {
6999                 ctsio->residual = 0;
7000                 ctsio->kern_data_len = alloc_len;
7001                 ctsio->kern_total_len = alloc_len;
7002         }
7003
7004         switch (ctsio->cdb[0]) {
7005         case MODE_SENSE_6: {
7006                 struct scsi_mode_hdr_6 *header;
7007
7008                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7009
7010                 header->datalen = ctl_min(total_len - 1, 254);
7011
7012                 if (dbd)
7013                         header->block_descr_len = 0;
7014                 else
7015                         header->block_descr_len =
7016                                 sizeof(struct scsi_mode_block_descr);
7017                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7018                 break;
7019         }
7020         case MODE_SENSE_10: {
7021                 struct scsi_mode_hdr_10 *header;
7022                 int datalen;
7023
7024                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7025
7026                 datalen = ctl_min(total_len - 2, 65533);
7027                 scsi_ulto2b(datalen, header->datalen);
7028                 if (dbd)
7029                         scsi_ulto2b(0, header->block_descr_len);
7030                 else
7031                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7032                                     header->block_descr_len);
7033                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7034                 break;
7035         }
7036         default:
7037                 panic("invalid CDB type %#x", ctsio->cdb[0]);
7038                 break; /* NOTREACHED */
7039         }
7040
7041         /*
7042          * If we've got a disk, use its blocksize in the block
7043          * descriptor.  Otherwise, just set it to 0.
7044          */
7045         if (dbd == 0) {
7046                 if (control_dev != 0)
7047                         scsi_ulto3b(lun->be_lun->blocksize,
7048                                     block_desc->block_len);
7049                 else
7050                         scsi_ulto3b(0, block_desc->block_len);
7051         }
7052
7053         switch (page_code) {
7054         case SMS_ALL_PAGES_PAGE: {
7055                 int i, data_used;
7056
7057                 data_used = header_len;
7058                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7059                         struct ctl_page_index *page_index;
7060
7061                         page_index = &lun->mode_pages.index[i];
7062
7063                         if ((control_dev != 0)
7064                          && (page_index->page_flags &
7065                             CTL_PAGE_FLAG_DISK_ONLY))
7066                                 continue;
7067
7068                         /*
7069                          * We don't use this subpage if the user didn't
7070                          * request all subpages.  We already checked (above)
7071                          * to make sure the user only specified a subpage
7072                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7073                          */
7074                         if ((page_index->subpage != 0)
7075                          && (subpage == SMS_SUBPAGE_PAGE_0))
7076                                 continue;
7077
7078                         /*
7079                          * Call the handler, if it exists, to update the
7080                          * page to the latest values.
7081                          */
7082                         if (page_index->sense_handler != NULL)
7083                                 page_index->sense_handler(ctsio, page_index,pc);
7084
7085                         memcpy(ctsio->kern_data_ptr + data_used,
7086                                page_index->page_data +
7087                                (page_index->page_len * pc),
7088                                page_index->page_len);
7089                         data_used += page_index->page_len;
7090                 }
7091                 break;
7092         }
7093         default: {
7094                 int i, data_used;
7095
7096                 data_used = header_len;
7097
7098                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7099                         struct ctl_page_index *page_index;
7100
7101                         page_index = &lun->mode_pages.index[i];
7102
7103                         /* Look for the right page code */
7104                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7105                                 continue;
7106
7107                         /* Look for the right subpage or the subpage wildcard*/
7108                         if ((page_index->subpage != subpage)
7109                          && (subpage != SMS_SUBPAGE_ALL))
7110                                 continue;
7111
7112                         /* Make sure the page is supported for this dev type */
7113                         if ((control_dev != 0)
7114                          && (page_index->page_flags &
7115                              CTL_PAGE_FLAG_DISK_ONLY))
7116                                 continue;
7117
7118                         /*
7119                          * Call the handler, if it exists, to update the
7120                          * page to the latest values.
7121                          */
7122                         if (page_index->sense_handler != NULL)
7123                                 page_index->sense_handler(ctsio, page_index,pc);
7124
7125                         memcpy(ctsio->kern_data_ptr + data_used,
7126                                page_index->page_data +
7127                                (page_index->page_len * pc),
7128                                page_index->page_len);
7129                         data_used += page_index->page_len;
7130                 }
7131                 break;
7132         }
7133         }
7134
7135         ctsio->scsi_status = SCSI_STATUS_OK;
7136
7137         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7138         ctsio->be_move_done = ctl_config_move_done;
7139         ctl_datamove((union ctl_io *)ctsio);
7140
7141         return (CTL_RETVAL_COMPLETE);
7142 }
7143
7144 int
7145 ctl_read_capacity(struct ctl_scsiio *ctsio)
7146 {
7147         struct scsi_read_capacity *cdb;
7148         struct scsi_read_capacity_data *data;
7149         struct ctl_lun *lun;
7150         uint32_t lba;
7151
7152         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7153
7154         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7155
7156         lba = scsi_4btoul(cdb->addr);
7157         if (((cdb->pmi & SRC_PMI) == 0)
7158          && (lba != 0)) {
7159                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7160                                       /*sks_valid*/ 1,
7161                                       /*command*/ 1,
7162                                       /*field*/ 2,
7163                                       /*bit_valid*/ 0,
7164                                       /*bit*/ 0);
7165                 ctl_done((union ctl_io *)ctsio);
7166                 return (CTL_RETVAL_COMPLETE);
7167         }
7168
7169         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7170
7171         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7172         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7173         ctsio->residual = 0;
7174         ctsio->kern_data_len = sizeof(*data);
7175         ctsio->kern_total_len = sizeof(*data);
7176         ctsio->kern_data_resid = 0;
7177         ctsio->kern_rel_offset = 0;
7178         ctsio->kern_sg_entries = 0;
7179
7180         /*
7181          * If the maximum LBA is greater than 0xfffffffe, the user must
7182          * issue a SERVICE ACTION IN (16) command, with the read capacity
7183          * serivce action set.
7184          */
7185         if (lun->be_lun->maxlba > 0xfffffffe)
7186                 scsi_ulto4b(0xffffffff, data->addr);
7187         else
7188                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7189
7190         /*
7191          * XXX KDM this may not be 512 bytes...
7192          */
7193         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7194
7195         ctsio->scsi_status = SCSI_STATUS_OK;
7196
7197         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7198         ctsio->be_move_done = ctl_config_move_done;
7199         ctl_datamove((union ctl_io *)ctsio);
7200
7201         return (CTL_RETVAL_COMPLETE);
7202 }
7203
7204 int
7205 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7206 {
7207         struct scsi_read_capacity_16 *cdb;
7208         struct scsi_read_capacity_data_long *data;
7209         struct ctl_lun *lun;
7210         uint64_t lba;
7211         uint32_t alloc_len;
7212
7213         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7214
7215         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7216
7217         alloc_len = scsi_4btoul(cdb->alloc_len);
7218         lba = scsi_8btou64(cdb->addr);
7219
7220         if ((cdb->reladr & SRC16_PMI)
7221          && (lba != 0)) {
7222                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7223                                       /*sks_valid*/ 1,
7224                                       /*command*/ 1,
7225                                       /*field*/ 2,
7226                                       /*bit_valid*/ 0,
7227                                       /*bit*/ 0);
7228                 ctl_done((union ctl_io *)ctsio);
7229                 return (CTL_RETVAL_COMPLETE);
7230         }
7231
7232         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7233
7234         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7235         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7236
7237         if (sizeof(*data) < alloc_len) {
7238                 ctsio->residual = alloc_len - sizeof(*data);
7239                 ctsio->kern_data_len = sizeof(*data);
7240                 ctsio->kern_total_len = sizeof(*data);
7241         } else {
7242                 ctsio->residual = 0;
7243                 ctsio->kern_data_len = alloc_len;
7244                 ctsio->kern_total_len = alloc_len;
7245         }
7246         ctsio->kern_data_resid = 0;
7247         ctsio->kern_rel_offset = 0;
7248         ctsio->kern_sg_entries = 0;
7249
7250         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7251         /* XXX KDM this may not be 512 bytes... */
7252         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7253         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7254         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7255         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7256                 data->lalba_lbp[0] |= SRC16_LBPME;
7257
7258         ctsio->scsi_status = SCSI_STATUS_OK;
7259
7260         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7261         ctsio->be_move_done = ctl_config_move_done;
7262         ctl_datamove((union ctl_io *)ctsio);
7263
7264         return (CTL_RETVAL_COMPLETE);
7265 }
7266
7267 int
7268 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7269 {
7270         struct scsi_maintenance_in *cdb;
7271         int retval;
7272         int alloc_len, ext, total_len = 0, g, p, pc, pg;
7273         int num_target_port_groups, num_target_ports, single;
7274         struct ctl_lun *lun;
7275         struct ctl_softc *softc;
7276         struct ctl_port *port;
7277         struct scsi_target_group_data *rtg_ptr;
7278         struct scsi_target_group_data_extended *rtg_ext_ptr;
7279         struct scsi_target_port_group_descriptor *tpg_desc;
7280
7281         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7282
7283         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7284         softc = control_softc;
7285         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7286
7287         retval = CTL_RETVAL_COMPLETE;
7288
7289         switch (cdb->byte2 & STG_PDF_MASK) {
7290         case STG_PDF_LENGTH:
7291                 ext = 0;
7292                 break;
7293         case STG_PDF_EXTENDED:
7294                 ext = 1;
7295                 break;
7296         default:
7297                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7298                                       /*sks_valid*/ 1,
7299                                       /*command*/ 1,
7300                                       /*field*/ 2,
7301                                       /*bit_valid*/ 1,
7302                                       /*bit*/ 5);
7303                 ctl_done((union ctl_io *)ctsio);
7304                 return(retval);
7305         }
7306
7307         single = ctl_is_single;
7308         if (single)
7309                 num_target_port_groups = 1;
7310         else
7311                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7312         num_target_ports = 0;
7313         mtx_lock(&softc->ctl_lock);
7314         STAILQ_FOREACH(port, &softc->port_list, links) {
7315                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7316                         continue;
7317                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7318                         continue;
7319                 num_target_ports++;
7320         }
7321         mtx_unlock(&softc->ctl_lock);
7322
7323         if (ext)
7324                 total_len = sizeof(struct scsi_target_group_data_extended);
7325         else
7326                 total_len = sizeof(struct scsi_target_group_data);
7327         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7328                 num_target_port_groups +
7329             sizeof(struct scsi_target_port_descriptor) *
7330                 num_target_ports * num_target_port_groups;
7331
7332         alloc_len = scsi_4btoul(cdb->length);
7333
7334         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7335
7336         ctsio->kern_sg_entries = 0;
7337
7338         if (total_len < alloc_len) {
7339                 ctsio->residual = alloc_len - total_len;
7340                 ctsio->kern_data_len = total_len;
7341                 ctsio->kern_total_len = total_len;
7342         } else {
7343                 ctsio->residual = 0;
7344                 ctsio->kern_data_len = alloc_len;
7345                 ctsio->kern_total_len = alloc_len;
7346         }
7347         ctsio->kern_data_resid = 0;
7348         ctsio->kern_rel_offset = 0;
7349
7350         if (ext) {
7351                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7352                     ctsio->kern_data_ptr;
7353                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7354                 rtg_ext_ptr->format_type = 0x10;
7355                 rtg_ext_ptr->implicit_transition_time = 0;
7356                 tpg_desc = &rtg_ext_ptr->groups[0];
7357         } else {
7358                 rtg_ptr = (struct scsi_target_group_data *)
7359                     ctsio->kern_data_ptr;
7360                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7361                 tpg_desc = &rtg_ptr->groups[0];
7362         }
7363
7364         pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7365         mtx_lock(&softc->ctl_lock);
7366         for (g = 0; g < num_target_port_groups; g++) {
7367                 if (g == pg)
7368                         tpg_desc->pref_state = TPG_PRIMARY |
7369                             TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7370                 else
7371                         tpg_desc->pref_state =
7372                             TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7373                 tpg_desc->support = TPG_AO_SUP;
7374                 if (!single)
7375                         tpg_desc->support |= TPG_AN_SUP;
7376                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7377                 tpg_desc->status = TPG_IMPLICIT;
7378                 pc = 0;
7379                 STAILQ_FOREACH(port, &softc->port_list, links) {
7380                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7381                                 continue;
7382                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7383                             CTL_MAX_LUNS)
7384                                 continue;
7385                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7386                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7387                             relative_target_port_identifier);
7388                         pc++;
7389                 }
7390                 tpg_desc->target_port_count = pc;
7391                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7392                     &tpg_desc->descriptors[pc];
7393         }
7394         mtx_unlock(&softc->ctl_lock);
7395
7396         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7397         ctsio->be_move_done = ctl_config_move_done;
7398
7399         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7400                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7401                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7402                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7403                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7404
7405         ctl_datamove((union ctl_io *)ctsio);
7406         return(retval);
7407 }
7408
7409 int
7410 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7411 {
7412         struct ctl_lun *lun;
7413         struct scsi_report_supported_opcodes *cdb;
7414         const struct ctl_cmd_entry *entry, *sentry;
7415         struct scsi_report_supported_opcodes_all *all;
7416         struct scsi_report_supported_opcodes_descr *descr;
7417         struct scsi_report_supported_opcodes_one *one;
7418         int retval;
7419         int alloc_len, total_len;
7420         int opcode, service_action, i, j, num;
7421
7422         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7423
7424         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7425         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7426
7427         retval = CTL_RETVAL_COMPLETE;
7428
7429         opcode = cdb->requested_opcode;
7430         service_action = scsi_2btoul(cdb->requested_service_action);
7431         switch (cdb->options & RSO_OPTIONS_MASK) {
7432         case RSO_OPTIONS_ALL:
7433                 num = 0;
7434                 for (i = 0; i < 256; i++) {
7435                         entry = &ctl_cmd_table[i];
7436                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7437                                 for (j = 0; j < 32; j++) {
7438                                         sentry = &((const struct ctl_cmd_entry *)
7439                                             entry->execute)[j];
7440                                         if (ctl_cmd_applicable(
7441                                             lun->be_lun->lun_type, sentry))
7442                                                 num++;
7443                                 }
7444                         } else {
7445                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7446                                     entry))
7447                                         num++;
7448                         }
7449                 }
7450                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7451                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7452                 break;
7453         case RSO_OPTIONS_OC:
7454                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7455                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7456                                               /*sks_valid*/ 1,
7457                                               /*command*/ 1,
7458                                               /*field*/ 2,
7459                                               /*bit_valid*/ 1,
7460                                               /*bit*/ 2);
7461                         ctl_done((union ctl_io *)ctsio);
7462                         return (CTL_RETVAL_COMPLETE);
7463                 }
7464                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7465                 break;
7466         case RSO_OPTIONS_OC_SA:
7467                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7468                     service_action >= 32) {
7469                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7470                                               /*sks_valid*/ 1,
7471                                               /*command*/ 1,
7472                                               /*field*/ 2,
7473                                               /*bit_valid*/ 1,
7474                                               /*bit*/ 2);
7475                         ctl_done((union ctl_io *)ctsio);
7476                         return (CTL_RETVAL_COMPLETE);
7477                 }
7478                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7479                 break;
7480         default:
7481                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7482                                       /*sks_valid*/ 1,
7483                                       /*command*/ 1,
7484                                       /*field*/ 2,
7485                                       /*bit_valid*/ 1,
7486                                       /*bit*/ 2);
7487                 ctl_done((union ctl_io *)ctsio);
7488                 return (CTL_RETVAL_COMPLETE);
7489         }
7490
7491         alloc_len = scsi_4btoul(cdb->length);
7492
7493         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7494
7495         ctsio->kern_sg_entries = 0;
7496
7497         if (total_len < alloc_len) {
7498                 ctsio->residual = alloc_len - total_len;
7499                 ctsio->kern_data_len = total_len;
7500                 ctsio->kern_total_len = total_len;
7501         } else {
7502                 ctsio->residual = 0;
7503                 ctsio->kern_data_len = alloc_len;
7504                 ctsio->kern_total_len = alloc_len;
7505         }
7506         ctsio->kern_data_resid = 0;
7507         ctsio->kern_rel_offset = 0;
7508
7509         switch (cdb->options & RSO_OPTIONS_MASK) {
7510         case RSO_OPTIONS_ALL:
7511                 all = (struct scsi_report_supported_opcodes_all *)
7512                     ctsio->kern_data_ptr;
7513                 num = 0;
7514                 for (i = 0; i < 256; i++) {
7515                         entry = &ctl_cmd_table[i];
7516                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7517                                 for (j = 0; j < 32; j++) {
7518                                         sentry = &((const struct ctl_cmd_entry *)
7519                                             entry->execute)[j];
7520                                         if (!ctl_cmd_applicable(
7521                                             lun->be_lun->lun_type, sentry))
7522                                                 continue;
7523                                         descr = &all->descr[num++];
7524                                         descr->opcode = i;
7525                                         scsi_ulto2b(j, descr->service_action);
7526                                         descr->flags = RSO_SERVACTV;
7527                                         scsi_ulto2b(sentry->length,
7528                                             descr->cdb_length);
7529                                 }
7530                         } else {
7531                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7532                                     entry))
7533                                         continue;
7534                                 descr = &all->descr[num++];
7535                                 descr->opcode = i;
7536                                 scsi_ulto2b(0, descr->service_action);
7537                                 descr->flags = 0;
7538                                 scsi_ulto2b(entry->length, descr->cdb_length);
7539                         }
7540                 }
7541                 scsi_ulto4b(
7542                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7543                     all->length);
7544                 break;
7545         case RSO_OPTIONS_OC:
7546                 one = (struct scsi_report_supported_opcodes_one *)
7547                     ctsio->kern_data_ptr;
7548                 entry = &ctl_cmd_table[opcode];
7549                 goto fill_one;
7550         case RSO_OPTIONS_OC_SA:
7551                 one = (struct scsi_report_supported_opcodes_one *)
7552                     ctsio->kern_data_ptr;
7553                 entry = &ctl_cmd_table[opcode];
7554                 entry = &((const struct ctl_cmd_entry *)
7555                     entry->execute)[service_action];
7556 fill_one:
7557                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7558                         one->support = 3;
7559                         scsi_ulto2b(entry->length, one->cdb_length);
7560                         one->cdb_usage[0] = opcode;
7561                         memcpy(&one->cdb_usage[1], entry->usage,
7562                             entry->length - 1);
7563                 } else
7564                         one->support = 1;
7565                 break;
7566         }
7567
7568         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7569         ctsio->be_move_done = ctl_config_move_done;
7570
7571         ctl_datamove((union ctl_io *)ctsio);
7572         return(retval);
7573 }
7574
7575 int
7576 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7577 {
7578         struct ctl_lun *lun;
7579         struct scsi_report_supported_tmf *cdb;
7580         struct scsi_report_supported_tmf_data *data;
7581         int retval;
7582         int alloc_len, total_len;
7583
7584         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7585
7586         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7587         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7588
7589         retval = CTL_RETVAL_COMPLETE;
7590
7591         total_len = sizeof(struct scsi_report_supported_tmf_data);
7592         alloc_len = scsi_4btoul(cdb->length);
7593
7594         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7595
7596         ctsio->kern_sg_entries = 0;
7597
7598         if (total_len < alloc_len) {
7599                 ctsio->residual = alloc_len - total_len;
7600                 ctsio->kern_data_len = total_len;
7601                 ctsio->kern_total_len = total_len;
7602         } else {
7603                 ctsio->residual = 0;
7604                 ctsio->kern_data_len = alloc_len;
7605                 ctsio->kern_total_len = alloc_len;
7606         }
7607         ctsio->kern_data_resid = 0;
7608         ctsio->kern_rel_offset = 0;
7609
7610         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7611         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7612         data->byte2 |= RST_ITNRS;
7613
7614         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7615         ctsio->be_move_done = ctl_config_move_done;
7616
7617         ctl_datamove((union ctl_io *)ctsio);
7618         return (retval);
7619 }
7620
7621 int
7622 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7623 {
7624         struct ctl_lun *lun;
7625         struct scsi_report_timestamp *cdb;
7626         struct scsi_report_timestamp_data *data;
7627         struct timeval tv;
7628         int64_t timestamp;
7629         int retval;
7630         int alloc_len, total_len;
7631
7632         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7633
7634         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7635         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7636
7637         retval = CTL_RETVAL_COMPLETE;
7638
7639         total_len = sizeof(struct scsi_report_timestamp_data);
7640         alloc_len = scsi_4btoul(cdb->length);
7641
7642         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7643
7644         ctsio->kern_sg_entries = 0;
7645
7646         if (total_len < alloc_len) {
7647                 ctsio->residual = alloc_len - total_len;
7648                 ctsio->kern_data_len = total_len;
7649                 ctsio->kern_total_len = total_len;
7650         } else {
7651                 ctsio->residual = 0;
7652                 ctsio->kern_data_len = alloc_len;
7653                 ctsio->kern_total_len = alloc_len;
7654         }
7655         ctsio->kern_data_resid = 0;
7656         ctsio->kern_rel_offset = 0;
7657
7658         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7659         scsi_ulto2b(sizeof(*data) - 2, data->length);
7660         data->origin = RTS_ORIG_OUTSIDE;
7661         getmicrotime(&tv);
7662         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7663         scsi_ulto4b(timestamp >> 16, data->timestamp);
7664         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7665
7666         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7667         ctsio->be_move_done = ctl_config_move_done;
7668
7669         ctl_datamove((union ctl_io *)ctsio);
7670         return (retval);
7671 }
7672
7673 int
7674 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7675 {
7676         struct scsi_per_res_in *cdb;
7677         int alloc_len, total_len = 0;
7678         /* struct scsi_per_res_in_rsrv in_data; */
7679         struct ctl_lun *lun;
7680         struct ctl_softc *softc;
7681
7682         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7683
7684         softc = control_softc;
7685
7686         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7687
7688         alloc_len = scsi_2btoul(cdb->length);
7689
7690         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7691
7692 retry:
7693         mtx_lock(&lun->lun_lock);
7694         switch (cdb->action) {
7695         case SPRI_RK: /* read keys */
7696                 total_len = sizeof(struct scsi_per_res_in_keys) +
7697                         lun->pr_key_count *
7698                         sizeof(struct scsi_per_res_key);
7699                 break;
7700         case SPRI_RR: /* read reservation */
7701                 if (lun->flags & CTL_LUN_PR_RESERVED)
7702                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7703                 else
7704                         total_len = sizeof(struct scsi_per_res_in_header);
7705                 break;
7706         case SPRI_RC: /* report capabilities */
7707                 total_len = sizeof(struct scsi_per_res_cap);
7708                 break;
7709         case SPRI_RS: /* read full status */
7710                 total_len = sizeof(struct scsi_per_res_in_header) +
7711                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7712                     lun->pr_key_count;
7713                 break;
7714         default:
7715                 panic("Invalid PR type %x", cdb->action);
7716         }
7717         mtx_unlock(&lun->lun_lock);
7718
7719         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7720
7721         if (total_len < alloc_len) {
7722                 ctsio->residual = alloc_len - total_len;
7723                 ctsio->kern_data_len = total_len;
7724                 ctsio->kern_total_len = total_len;
7725         } else {
7726                 ctsio->residual = 0;
7727                 ctsio->kern_data_len = alloc_len;
7728                 ctsio->kern_total_len = alloc_len;
7729         }
7730
7731         ctsio->kern_data_resid = 0;
7732         ctsio->kern_rel_offset = 0;
7733         ctsio->kern_sg_entries = 0;
7734
7735         mtx_lock(&lun->lun_lock);
7736         switch (cdb->action) {
7737         case SPRI_RK: { // read keys
7738         struct scsi_per_res_in_keys *res_keys;
7739                 int i, key_count;
7740
7741                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7742
7743                 /*
7744                  * We had to drop the lock to allocate our buffer, which
7745                  * leaves time for someone to come in with another
7746                  * persistent reservation.  (That is unlikely, though,
7747                  * since this should be the only persistent reservation
7748                  * command active right now.)
7749                  */
7750                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7751                     (lun->pr_key_count *
7752                      sizeof(struct scsi_per_res_key)))){
7753                         mtx_unlock(&lun->lun_lock);
7754                         free(ctsio->kern_data_ptr, M_CTL);
7755                         printf("%s: reservation length changed, retrying\n",
7756                                __func__);
7757                         goto retry;
7758                 }
7759
7760                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7761
7762                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7763                              lun->pr_key_count, res_keys->header.length);
7764
7765                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7766                         if (!lun->per_res[i].registered)
7767                                 continue;
7768
7769                         /*
7770                          * We used lun->pr_key_count to calculate the
7771                          * size to allocate.  If it turns out the number of
7772                          * initiators with the registered flag set is
7773                          * larger than that (i.e. they haven't been kept in
7774                          * sync), we've got a problem.
7775                          */
7776                         if (key_count >= lun->pr_key_count) {
7777 #ifdef NEEDTOPORT
7778                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7779                                             CTL_PR_ERROR,
7780                                             csevent_LogType_Fault,
7781                                             csevent_AlertLevel_Yellow,
7782                                             csevent_FRU_ShelfController,
7783                                             csevent_FRU_Firmware,
7784                                         csevent_FRU_Unknown,
7785                                             "registered keys %d >= key "
7786                                             "count %d", key_count,
7787                                             lun->pr_key_count);
7788 #endif
7789                                 key_count++;
7790                                 continue;
7791                         }
7792                         memcpy(res_keys->keys[key_count].key,
7793                                lun->per_res[i].res_key.key,
7794                                ctl_min(sizeof(res_keys->keys[key_count].key),
7795                                sizeof(lun->per_res[i].res_key)));
7796                         key_count++;
7797                 }
7798                 break;
7799         }
7800         case SPRI_RR: { // read reservation
7801                 struct scsi_per_res_in_rsrv *res;
7802                 int tmp_len, header_only;
7803
7804                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7805
7806                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7807
7808                 if (lun->flags & CTL_LUN_PR_RESERVED)
7809                 {
7810                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7811                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7812                                     res->header.length);
7813                         header_only = 0;
7814                 } else {
7815                         tmp_len = sizeof(struct scsi_per_res_in_header);
7816                         scsi_ulto4b(0, res->header.length);
7817                         header_only = 1;
7818                 }
7819
7820                 /*
7821                  * We had to drop the lock to allocate our buffer, which
7822                  * leaves time for someone to come in with another
7823                  * persistent reservation.  (That is unlikely, though,
7824                  * since this should be the only persistent reservation
7825                  * command active right now.)
7826                  */
7827                 if (tmp_len != total_len) {
7828                         mtx_unlock(&lun->lun_lock);
7829                         free(ctsio->kern_data_ptr, M_CTL);
7830                         printf("%s: reservation status changed, retrying\n",
7831                                __func__);
7832                         goto retry;
7833                 }
7834
7835                 /*
7836                  * No reservation held, so we're done.
7837                  */
7838                 if (header_only != 0)
7839                         break;
7840
7841                 /*
7842                  * If the registration is an All Registrants type, the key
7843                  * is 0, since it doesn't really matter.
7844                  */
7845                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7846                         memcpy(res->data.reservation,
7847                                &lun->per_res[lun->pr_res_idx].res_key,
7848                                sizeof(struct scsi_per_res_key));
7849                 }
7850                 res->data.scopetype = lun->res_type;
7851                 break;
7852         }
7853         case SPRI_RC:     //report capabilities
7854         {
7855                 struct scsi_per_res_cap *res_cap;
7856                 uint16_t type_mask;
7857
7858                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7859                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7860                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7861                 type_mask = SPRI_TM_WR_EX_AR |
7862                             SPRI_TM_EX_AC_RO |
7863                             SPRI_TM_WR_EX_RO |
7864                             SPRI_TM_EX_AC |
7865                             SPRI_TM_WR_EX |
7866                             SPRI_TM_EX_AC_AR;
7867                 scsi_ulto2b(type_mask, res_cap->type_mask);
7868                 break;
7869         }
7870         case SPRI_RS: { // read full status
7871                 struct scsi_per_res_in_full *res_status;
7872                 struct scsi_per_res_in_full_desc *res_desc;
7873                 struct ctl_port *port;
7874                 int i, len;
7875
7876                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7877
7878                 /*
7879                  * We had to drop the lock to allocate our buffer, which
7880                  * leaves time for someone to come in with another
7881                  * persistent reservation.  (That is unlikely, though,
7882                  * since this should be the only persistent reservation
7883                  * command active right now.)
7884                  */
7885                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7886                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7887                      lun->pr_key_count)){
7888                         mtx_unlock(&lun->lun_lock);
7889                         free(ctsio->kern_data_ptr, M_CTL);
7890                         printf("%s: reservation length changed, retrying\n",
7891                                __func__);
7892                         goto retry;
7893                 }
7894
7895                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7896
7897                 res_desc = &res_status->desc[0];
7898                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7899                         if (!lun->per_res[i].registered)
7900                                 continue;
7901
7902                         memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7903                             sizeof(res_desc->res_key));
7904                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7905                             (lun->pr_res_idx == i ||
7906                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7907                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7908                                 res_desc->scopetype = lun->res_type;
7909                         }
7910                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7911                             res_desc->rel_trgt_port_id);
7912                         len = 0;
7913                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7914                         if (port != NULL)
7915                                 len = ctl_create_iid(port,
7916                                     i % CTL_MAX_INIT_PER_PORT,
7917                                     res_desc->transport_id);
7918                         scsi_ulto4b(len, res_desc->additional_length);
7919                         res_desc = (struct scsi_per_res_in_full_desc *)
7920                             &res_desc->transport_id[len];
7921                 }
7922                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7923                     res_status->header.length);
7924                 break;
7925         }
7926         default:
7927                 /*
7928                  * This is a bug, because we just checked for this above,
7929                  * and should have returned an error.
7930                  */
7931                 panic("Invalid PR type %x", cdb->action);
7932                 break; /* NOTREACHED */
7933         }
7934         mtx_unlock(&lun->lun_lock);
7935
7936         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7937         ctsio->be_move_done = ctl_config_move_done;
7938
7939         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7940                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7941                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7942                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7943                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7944
7945         ctl_datamove((union ctl_io *)ctsio);
7946
7947         return (CTL_RETVAL_COMPLETE);
7948 }
7949
7950 /*
7951  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7952  * it should return.
7953  */
7954 static int
7955 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7956                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7957                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7958                 struct scsi_per_res_out_parms* param)
7959 {
7960         union ctl_ha_msg persis_io;
7961         int retval, i;
7962         int isc_retval;
7963
7964         retval = 0;
7965
7966         mtx_lock(&lun->lun_lock);
7967         if (sa_res_key == 0) {
7968                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7969                         /* validate scope and type */
7970                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7971                              SPR_LU_SCOPE) {
7972                                 mtx_unlock(&lun->lun_lock);
7973                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7974                                                       /*sks_valid*/ 1,
7975                                                       /*command*/ 1,
7976                                                       /*field*/ 2,
7977                                                       /*bit_valid*/ 1,
7978                                                       /*bit*/ 4);
7979                                 ctl_done((union ctl_io *)ctsio);
7980                                 return (1);
7981                         }
7982
7983                         if (type>8 || type==2 || type==4 || type==0) {
7984                                 mtx_unlock(&lun->lun_lock);
7985                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7986                                                       /*sks_valid*/ 1,
7987                                                       /*command*/ 1,
7988                                                       /*field*/ 2,
7989                                                       /*bit_valid*/ 1,
7990                                                       /*bit*/ 0);
7991                                 ctl_done((union ctl_io *)ctsio);
7992                                 return (1);
7993                         }
7994
7995                         /* temporarily unregister this nexus */
7996                         lun->per_res[residx].registered = 0;
7997
7998                         /*
7999                          * Unregister everybody else and build UA for
8000                          * them
8001                          */
8002                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8003                                 if (lun->per_res[i].registered == 0)
8004                                         continue;
8005
8006                                 if (!persis_offset
8007                                  && i <CTL_MAX_INITIATORS)
8008                                         lun->pending_sense[i].ua_pending |=
8009                                                 CTL_UA_REG_PREEMPT;
8010                                 else if (persis_offset
8011                                       && i >= persis_offset)
8012                                         lun->pending_sense[i-persis_offset
8013                                                 ].ua_pending |=
8014                                                 CTL_UA_REG_PREEMPT;
8015                                 lun->per_res[i].registered = 0;
8016                                 memset(&lun->per_res[i].res_key, 0,
8017                                        sizeof(struct scsi_per_res_key));
8018                         }
8019                         lun->per_res[residx].registered = 1;
8020                         lun->pr_key_count = 1;
8021                         lun->res_type = type;
8022                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8023                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8024                                 lun->pr_res_idx = residx;
8025
8026                         /* send msg to other side */
8027                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8028                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8029                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8030                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8031                         persis_io.pr.pr_info.res_type = type;
8032                         memcpy(persis_io.pr.pr_info.sa_res_key,
8033                                param->serv_act_res_key,
8034                                sizeof(param->serv_act_res_key));
8035                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8036                              &persis_io, sizeof(persis_io), 0)) >
8037                              CTL_HA_STATUS_SUCCESS) {
8038                                 printf("CTL:Persis Out error returned "
8039                                        "from ctl_ha_msg_send %d\n",
8040                                        isc_retval);
8041                         }
8042                 } else {
8043                         /* not all registrants */
8044                         mtx_unlock(&lun->lun_lock);
8045                         free(ctsio->kern_data_ptr, M_CTL);
8046                         ctl_set_invalid_field(ctsio,
8047                                               /*sks_valid*/ 1,
8048                                               /*command*/ 0,
8049                                               /*field*/ 8,
8050                                               /*bit_valid*/ 0,
8051                                               /*bit*/ 0);
8052                         ctl_done((union ctl_io *)ctsio);
8053                         return (1);
8054                 }
8055         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8056                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8057                 int found = 0;
8058
8059                 if (res_key == sa_res_key) {
8060                         /* special case */
8061                         /*
8062                          * The spec implies this is not good but doesn't
8063                          * say what to do. There are two choices either
8064                          * generate a res conflict or check condition
8065                          * with illegal field in parameter data. Since
8066                          * that is what is done when the sa_res_key is
8067                          * zero I'll take that approach since this has
8068                          * to do with the sa_res_key.
8069                          */
8070                         mtx_unlock(&lun->lun_lock);
8071                         free(ctsio->kern_data_ptr, M_CTL);
8072                         ctl_set_invalid_field(ctsio,
8073                                               /*sks_valid*/ 1,
8074                                               /*command*/ 0,
8075                                               /*field*/ 8,
8076                                               /*bit_valid*/ 0,
8077                                               /*bit*/ 0);
8078                         ctl_done((union ctl_io *)ctsio);
8079                         return (1);
8080                 }
8081
8082                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8083                         if (lun->per_res[i].registered
8084                          && memcmp(param->serv_act_res_key,
8085                             lun->per_res[i].res_key.key,
8086                             sizeof(struct scsi_per_res_key)) != 0)
8087                                 continue;
8088
8089                         found = 1;
8090                         lun->per_res[i].registered = 0;
8091                         memset(&lun->per_res[i].res_key, 0,
8092                                sizeof(struct scsi_per_res_key));
8093                         lun->pr_key_count--;
8094
8095                         if (!persis_offset
8096                          && i < CTL_MAX_INITIATORS)
8097                                 lun->pending_sense[i].ua_pending |=
8098                                         CTL_UA_REG_PREEMPT;
8099                         else if (persis_offset
8100                               && i >= persis_offset)
8101                                 lun->pending_sense[i-persis_offset].ua_pending|=
8102                                         CTL_UA_REG_PREEMPT;
8103                 }
8104                 if (!found) {
8105                         mtx_unlock(&lun->lun_lock);
8106                         free(ctsio->kern_data_ptr, M_CTL);
8107                         ctl_set_reservation_conflict(ctsio);
8108                         ctl_done((union ctl_io *)ctsio);
8109                         return (CTL_RETVAL_COMPLETE);
8110                 }
8111                 /* send msg to other side */
8112                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8113                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8114                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8115                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8116                 persis_io.pr.pr_info.res_type = type;
8117                 memcpy(persis_io.pr.pr_info.sa_res_key,
8118                        param->serv_act_res_key,
8119                        sizeof(param->serv_act_res_key));
8120                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8121                      &persis_io, sizeof(persis_io), 0)) >
8122                      CTL_HA_STATUS_SUCCESS) {
8123                         printf("CTL:Persis Out error returned from "
8124                                "ctl_ha_msg_send %d\n", isc_retval);
8125                 }
8126         } else {
8127                 /* Reserved but not all registrants */
8128                 /* sa_res_key is res holder */
8129                 if (memcmp(param->serv_act_res_key,
8130                    lun->per_res[lun->pr_res_idx].res_key.key,
8131                    sizeof(struct scsi_per_res_key)) == 0) {
8132                         /* validate scope and type */
8133                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8134                              SPR_LU_SCOPE) {
8135                                 mtx_unlock(&lun->lun_lock);
8136                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8137                                                       /*sks_valid*/ 1,
8138                                                       /*command*/ 1,
8139                                                       /*field*/ 2,
8140                                                       /*bit_valid*/ 1,
8141                                                       /*bit*/ 4);
8142                                 ctl_done((union ctl_io *)ctsio);
8143                                 return (1);
8144                         }
8145
8146                         if (type>8 || type==2 || type==4 || type==0) {
8147                                 mtx_unlock(&lun->lun_lock);
8148                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8149                                                       /*sks_valid*/ 1,
8150                                                       /*command*/ 1,
8151                                                       /*field*/ 2,
8152                                                       /*bit_valid*/ 1,
8153                                                       /*bit*/ 0);
8154                                 ctl_done((union ctl_io *)ctsio);
8155                                 return (1);
8156                         }
8157
8158                         /*
8159                          * Do the following:
8160                          * if sa_res_key != res_key remove all
8161                          * registrants w/sa_res_key and generate UA
8162                          * for these registrants(Registrations
8163                          * Preempted) if it wasn't an exclusive
8164                          * reservation generate UA(Reservations
8165                          * Preempted) for all other registered nexuses
8166                          * if the type has changed. Establish the new
8167                          * reservation and holder. If res_key and
8168                          * sa_res_key are the same do the above
8169                          * except don't unregister the res holder.
8170                          */
8171
8172                         /*
8173                          * Temporarily unregister so it won't get
8174                          * removed or UA generated
8175                          */
8176                         lun->per_res[residx].registered = 0;
8177                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8178                                 if (lun->per_res[i].registered == 0)
8179                                         continue;
8180
8181                                 if (memcmp(param->serv_act_res_key,
8182                                     lun->per_res[i].res_key.key,
8183                                     sizeof(struct scsi_per_res_key)) == 0) {
8184                                         lun->per_res[i].registered = 0;
8185                                         memset(&lun->per_res[i].res_key,
8186                                                0,
8187                                                sizeof(struct scsi_per_res_key));
8188                                         lun->pr_key_count--;
8189
8190                                         if (!persis_offset
8191                                          && i < CTL_MAX_INITIATORS)
8192                                                 lun->pending_sense[i
8193                                                         ].ua_pending |=
8194                                                         CTL_UA_REG_PREEMPT;
8195                                         else if (persis_offset
8196                                               && i >= persis_offset)
8197                                                 lun->pending_sense[
8198                                                   i-persis_offset].ua_pending |=
8199                                                   CTL_UA_REG_PREEMPT;
8200                                 } else if (type != lun->res_type
8201                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8202                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8203                                                 if (!persis_offset
8204                                                  && i < CTL_MAX_INITIATORS)
8205                                                         lun->pending_sense[i
8206                                                         ].ua_pending |=
8207                                                         CTL_UA_RES_RELEASE;
8208                                                 else if (persis_offset
8209                                                       && i >= persis_offset)
8210                                                         lun->pending_sense[
8211                                                         i-persis_offset
8212                                                         ].ua_pending |=
8213                                                         CTL_UA_RES_RELEASE;
8214                                 }
8215                         }
8216                         lun->per_res[residx].registered = 1;
8217                         lun->res_type = type;
8218                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8219                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8220                                 lun->pr_res_idx = residx;
8221                         else
8222                                 lun->pr_res_idx =
8223                                         CTL_PR_ALL_REGISTRANTS;
8224
8225                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8226                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8227                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8228                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8229                         persis_io.pr.pr_info.res_type = type;
8230                         memcpy(persis_io.pr.pr_info.sa_res_key,
8231                                param->serv_act_res_key,
8232                                sizeof(param->serv_act_res_key));
8233                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8234                              &persis_io, sizeof(persis_io), 0)) >
8235                              CTL_HA_STATUS_SUCCESS) {
8236                                 printf("CTL:Persis Out error returned "
8237                                        "from ctl_ha_msg_send %d\n",
8238                                        isc_retval);
8239                         }
8240                 } else {
8241                         /*
8242                          * sa_res_key is not the res holder just
8243                          * remove registrants
8244                          */
8245                         int found=0;
8246
8247                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8248                                 if (memcmp(param->serv_act_res_key,
8249                                     lun->per_res[i].res_key.key,
8250                                     sizeof(struct scsi_per_res_key)) != 0)
8251                                         continue;
8252
8253                                 found = 1;
8254                                 lun->per_res[i].registered = 0;
8255                                 memset(&lun->per_res[i].res_key, 0,
8256                                        sizeof(struct scsi_per_res_key));
8257                                 lun->pr_key_count--;
8258
8259                                 if (!persis_offset
8260                                  && i < CTL_MAX_INITIATORS)
8261                                         lun->pending_sense[i].ua_pending |=
8262                                                 CTL_UA_REG_PREEMPT;
8263                                 else if (persis_offset
8264                                       && i >= persis_offset)
8265                                         lun->pending_sense[
8266                                                 i-persis_offset].ua_pending |=
8267                                                 CTL_UA_REG_PREEMPT;
8268                         }
8269
8270                         if (!found) {
8271                                 mtx_unlock(&lun->lun_lock);
8272                                 free(ctsio->kern_data_ptr, M_CTL);
8273                                 ctl_set_reservation_conflict(ctsio);
8274                                 ctl_done((union ctl_io *)ctsio);
8275                                 return (1);
8276                         }
8277                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8278                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8279                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8280                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8281                         persis_io.pr.pr_info.res_type = type;
8282                         memcpy(persis_io.pr.pr_info.sa_res_key,
8283                                param->serv_act_res_key,
8284                                sizeof(param->serv_act_res_key));
8285                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8286                              &persis_io, sizeof(persis_io), 0)) >
8287                              CTL_HA_STATUS_SUCCESS) {
8288                                 printf("CTL:Persis Out error returned "
8289                                        "from ctl_ha_msg_send %d\n",
8290                                 isc_retval);
8291                         }
8292                 }
8293         }
8294
8295         lun->PRGeneration++;
8296         mtx_unlock(&lun->lun_lock);
8297
8298         return (retval);
8299 }
8300
8301 static void
8302 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8303 {
8304         int i;
8305
8306         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8307          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8308          || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8309                    msg->pr.pr_info.sa_res_key,
8310                    sizeof(struct scsi_per_res_key)) != 0) {
8311                 uint64_t sa_res_key;
8312                 sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8313
8314                 if (sa_res_key == 0) {
8315                         /* temporarily unregister this nexus */
8316                         lun->per_res[msg->pr.pr_info.residx].registered = 0;
8317
8318                         /*
8319                          * Unregister everybody else and build UA for
8320                          * them
8321                          */
8322                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8323                                 if (lun->per_res[i].registered == 0)
8324                                         continue;
8325
8326                                 if (!persis_offset
8327                                  && i < CTL_MAX_INITIATORS)
8328                                         lun->pending_sense[i].ua_pending |=
8329                                                 CTL_UA_REG_PREEMPT;
8330                                 else if (persis_offset && i >= persis_offset)
8331                                         lun->pending_sense[i -
8332                                                 persis_offset].ua_pending |=
8333                                                 CTL_UA_REG_PREEMPT;
8334                                 lun->per_res[i].registered = 0;
8335                                 memset(&lun->per_res[i].res_key, 0,
8336                                        sizeof(struct scsi_per_res_key));
8337                         }
8338
8339                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8340                         lun->pr_key_count = 1;
8341                         lun->res_type = msg->pr.pr_info.res_type;
8342                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8343                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8344                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8345                 } else {
8346                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8347                                 if (memcmp(msg->pr.pr_info.sa_res_key,
8348                                    lun->per_res[i].res_key.key,
8349                                    sizeof(struct scsi_per_res_key)) != 0)
8350                                         continue;
8351
8352                                 lun->per_res[i].registered = 0;
8353                                 memset(&lun->per_res[i].res_key, 0,
8354                                        sizeof(struct scsi_per_res_key));
8355                                 lun->pr_key_count--;
8356
8357                                 if (!persis_offset
8358                                  && i < persis_offset)
8359                                         lun->pending_sense[i].ua_pending |=
8360                                                 CTL_UA_REG_PREEMPT;
8361                                 else if (persis_offset
8362                                       && i >= persis_offset)
8363                                         lun->pending_sense[i -
8364                                                 persis_offset].ua_pending |=
8365                                                 CTL_UA_REG_PREEMPT;
8366                         }
8367                 }
8368         } else {
8369                 /*
8370                  * Temporarily unregister so it won't get removed
8371                  * or UA generated
8372                  */
8373                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8374                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8375                         if (lun->per_res[i].registered == 0)
8376                                 continue;
8377
8378                         if (memcmp(msg->pr.pr_info.sa_res_key,
8379                            lun->per_res[i].res_key.key,
8380                            sizeof(struct scsi_per_res_key)) == 0) {
8381                                 lun->per_res[i].registered = 0;
8382                                 memset(&lun->per_res[i].res_key, 0,
8383                                        sizeof(struct scsi_per_res_key));
8384                                 lun->pr_key_count--;
8385                                 if (!persis_offset
8386                                  && i < CTL_MAX_INITIATORS)
8387                                         lun->pending_sense[i].ua_pending |=
8388                                                 CTL_UA_REG_PREEMPT;
8389                                 else if (persis_offset
8390                                       && i >= persis_offset)
8391                                         lun->pending_sense[i -
8392                                                 persis_offset].ua_pending |=
8393                                                 CTL_UA_REG_PREEMPT;
8394                         } else if (msg->pr.pr_info.res_type != lun->res_type
8395                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8396                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8397                                         if (!persis_offset
8398                                          && i < persis_offset)
8399                                                 lun->pending_sense[i
8400                                                         ].ua_pending |=
8401                                                         CTL_UA_RES_RELEASE;
8402                                         else if (persis_offset
8403                                               && i >= persis_offset)
8404                                         lun->pending_sense[i -
8405                                                 persis_offset].ua_pending |=
8406                                                 CTL_UA_RES_RELEASE;
8407                         }
8408                 }
8409                 lun->per_res[msg->pr.pr_info.residx].registered = 1;
8410                 lun->res_type = msg->pr.pr_info.res_type;
8411                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8412                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8413                         lun->pr_res_idx = msg->pr.pr_info.residx;
8414                 else
8415                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8416         }
8417         lun->PRGeneration++;
8418
8419 }
8420
8421
8422 int
8423 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8424 {
8425         int retval;
8426         int isc_retval;
8427         u_int32_t param_len;
8428         struct scsi_per_res_out *cdb;
8429         struct ctl_lun *lun;
8430         struct scsi_per_res_out_parms* param;
8431         struct ctl_softc *softc;
8432         uint32_t residx;
8433         uint64_t res_key, sa_res_key;
8434         uint8_t type;
8435         union ctl_ha_msg persis_io;
8436         int    i;
8437
8438         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8439
8440         retval = CTL_RETVAL_COMPLETE;
8441
8442         softc = control_softc;
8443
8444         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8445         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8446
8447         /*
8448          * We only support whole-LUN scope.  The scope & type are ignored for
8449          * register, register and ignore existing key and clear.
8450          * We sometimes ignore scope and type on preempts too!!
8451          * Verify reservation type here as well.
8452          */
8453         type = cdb->scope_type & SPR_TYPE_MASK;
8454         if ((cdb->action == SPRO_RESERVE)
8455          || (cdb->action == SPRO_RELEASE)) {
8456                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8457                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8458                                               /*sks_valid*/ 1,
8459                                               /*command*/ 1,
8460                                               /*field*/ 2,
8461                                               /*bit_valid*/ 1,
8462                                               /*bit*/ 4);
8463                         ctl_done((union ctl_io *)ctsio);
8464                         return (CTL_RETVAL_COMPLETE);
8465                 }
8466
8467                 if (type>8 || type==2 || type==4 || type==0) {
8468                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8469                                               /*sks_valid*/ 1,
8470                                               /*command*/ 1,
8471                                               /*field*/ 2,
8472                                               /*bit_valid*/ 1,
8473                                               /*bit*/ 0);
8474                         ctl_done((union ctl_io *)ctsio);
8475                         return (CTL_RETVAL_COMPLETE);
8476                 }
8477         }
8478
8479         param_len = scsi_4btoul(cdb->length);
8480
8481         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8482                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8483                 ctsio->kern_data_len = param_len;
8484                 ctsio->kern_total_len = param_len;
8485                 ctsio->kern_data_resid = 0;
8486                 ctsio->kern_rel_offset = 0;
8487                 ctsio->kern_sg_entries = 0;
8488                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8489                 ctsio->be_move_done = ctl_config_move_done;
8490                 ctl_datamove((union ctl_io *)ctsio);
8491
8492                 return (CTL_RETVAL_COMPLETE);
8493         }
8494
8495         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8496
8497         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8498         res_key = scsi_8btou64(param->res_key.key);
8499         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8500
8501         /*
8502          * Validate the reservation key here except for SPRO_REG_IGNO
8503          * This must be done for all other service actions
8504          */
8505         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8506                 mtx_lock(&lun->lun_lock);
8507                 if (lun->per_res[residx].registered) {
8508                     if (memcmp(param->res_key.key,
8509                                lun->per_res[residx].res_key.key,
8510                                ctl_min(sizeof(param->res_key),
8511                                sizeof(lun->per_res[residx].res_key))) != 0) {
8512                                 /*
8513                                  * The current key passed in doesn't match
8514                                  * the one the initiator previously
8515                                  * registered.
8516                                  */
8517                                 mtx_unlock(&lun->lun_lock);
8518                                 free(ctsio->kern_data_ptr, M_CTL);
8519                                 ctl_set_reservation_conflict(ctsio);
8520                                 ctl_done((union ctl_io *)ctsio);
8521                                 return (CTL_RETVAL_COMPLETE);
8522                         }
8523                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8524                         /*
8525                          * We are not registered
8526                          */
8527                         mtx_unlock(&lun->lun_lock);
8528                         free(ctsio->kern_data_ptr, M_CTL);
8529                         ctl_set_reservation_conflict(ctsio);
8530                         ctl_done((union ctl_io *)ctsio);
8531                         return (CTL_RETVAL_COMPLETE);
8532                 } else if (res_key != 0) {
8533                         /*
8534                          * We are not registered and trying to register but
8535                          * the register key isn't zero.
8536                          */
8537                         mtx_unlock(&lun->lun_lock);
8538                         free(ctsio->kern_data_ptr, M_CTL);
8539                         ctl_set_reservation_conflict(ctsio);
8540                         ctl_done((union ctl_io *)ctsio);
8541                         return (CTL_RETVAL_COMPLETE);
8542                 }
8543                 mtx_unlock(&lun->lun_lock);
8544         }
8545
8546         switch (cdb->action & SPRO_ACTION_MASK) {
8547         case SPRO_REGISTER:
8548         case SPRO_REG_IGNO: {
8549
8550 #if 0
8551                 printf("Registration received\n");
8552 #endif
8553
8554                 /*
8555                  * We don't support any of these options, as we report in
8556                  * the read capabilities request (see
8557                  * ctl_persistent_reserve_in(), above).
8558                  */
8559                 if ((param->flags & SPR_SPEC_I_PT)
8560                  || (param->flags & SPR_ALL_TG_PT)
8561                  || (param->flags & SPR_APTPL)) {
8562                         int bit_ptr;
8563
8564                         if (param->flags & SPR_APTPL)
8565                                 bit_ptr = 0;
8566                         else if (param->flags & SPR_ALL_TG_PT)
8567                                 bit_ptr = 2;
8568                         else /* SPR_SPEC_I_PT */
8569                                 bit_ptr = 3;
8570
8571                         free(ctsio->kern_data_ptr, M_CTL);
8572                         ctl_set_invalid_field(ctsio,
8573                                               /*sks_valid*/ 1,
8574                                               /*command*/ 0,
8575                                               /*field*/ 20,
8576                                               /*bit_valid*/ 1,
8577                                               /*bit*/ bit_ptr);
8578                         ctl_done((union ctl_io *)ctsio);
8579                         return (CTL_RETVAL_COMPLETE);
8580                 }
8581
8582                 mtx_lock(&lun->lun_lock);
8583
8584                 /*
8585                  * The initiator wants to clear the
8586                  * key/unregister.
8587                  */
8588                 if (sa_res_key == 0) {
8589                         if ((res_key == 0
8590                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8591                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8592                           && !lun->per_res[residx].registered)) {
8593                                 mtx_unlock(&lun->lun_lock);
8594                                 goto done;
8595                         }
8596
8597                         lun->per_res[residx].registered = 0;
8598                         memset(&lun->per_res[residx].res_key,
8599                                0, sizeof(lun->per_res[residx].res_key));
8600                         lun->pr_key_count--;
8601
8602                         if (residx == lun->pr_res_idx) {
8603                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8604                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8605
8606                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8607                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8608                                  && lun->pr_key_count) {
8609                                         /*
8610                                          * If the reservation is a registrants
8611                                          * only type we need to generate a UA
8612                                          * for other registered inits.  The
8613                                          * sense code should be RESERVATIONS
8614                                          * RELEASED
8615                                          */
8616
8617                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8618                                                 if (lun->per_res[
8619                                                     i+persis_offset].registered
8620                                                     == 0)
8621                                                         continue;
8622                                                 lun->pending_sense[i
8623                                                         ].ua_pending |=
8624                                                         CTL_UA_RES_RELEASE;
8625                                         }
8626                                 }
8627                                 lun->res_type = 0;
8628                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8629                                 if (lun->pr_key_count==0) {
8630                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8631                                         lun->res_type = 0;
8632                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8633                                 }
8634                         }
8635                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8636                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8637                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8638                         persis_io.pr.pr_info.residx = residx;
8639                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8640                              &persis_io, sizeof(persis_io), 0 )) >
8641                              CTL_HA_STATUS_SUCCESS) {
8642                                 printf("CTL:Persis Out error returned from "
8643                                        "ctl_ha_msg_send %d\n", isc_retval);
8644                         }
8645                 } else /* sa_res_key != 0 */ {
8646
8647                         /*
8648                          * If we aren't registered currently then increment
8649                          * the key count and set the registered flag.
8650                          */
8651                         if (!lun->per_res[residx].registered) {
8652                                 lun->pr_key_count++;
8653                                 lun->per_res[residx].registered = 1;
8654                         }
8655
8656                         memcpy(&lun->per_res[residx].res_key,
8657                                param->serv_act_res_key,
8658                                ctl_min(sizeof(param->serv_act_res_key),
8659                                sizeof(lun->per_res[residx].res_key)));
8660
8661                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8662                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8663                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8664                         persis_io.pr.pr_info.residx = residx;
8665                         memcpy(persis_io.pr.pr_info.sa_res_key,
8666                                param->serv_act_res_key,
8667                                sizeof(param->serv_act_res_key));
8668                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8669                              &persis_io, sizeof(persis_io), 0)) >
8670                              CTL_HA_STATUS_SUCCESS) {
8671                                 printf("CTL:Persis Out error returned from "
8672                                        "ctl_ha_msg_send %d\n", isc_retval);
8673                         }
8674                 }
8675                 lun->PRGeneration++;
8676                 mtx_unlock(&lun->lun_lock);
8677
8678                 break;
8679         }
8680         case SPRO_RESERVE:
8681 #if 0
8682                 printf("Reserve executed type %d\n", type);
8683 #endif
8684                 mtx_lock(&lun->lun_lock);
8685                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8686                         /*
8687                          * if this isn't the reservation holder and it's
8688                          * not a "all registrants" type or if the type is
8689                          * different then we have a conflict
8690                          */
8691                         if ((lun->pr_res_idx != residx
8692                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8693                          || lun->res_type != type) {
8694                                 mtx_unlock(&lun->lun_lock);
8695                                 free(ctsio->kern_data_ptr, M_CTL);
8696                                 ctl_set_reservation_conflict(ctsio);
8697                                 ctl_done((union ctl_io *)ctsio);
8698                                 return (CTL_RETVAL_COMPLETE);
8699                         }
8700                         mtx_unlock(&lun->lun_lock);
8701                 } else /* create a reservation */ {
8702                         /*
8703                          * If it's not an "all registrants" type record
8704                          * reservation holder
8705                          */
8706                         if (type != SPR_TYPE_WR_EX_AR
8707                          && type != SPR_TYPE_EX_AC_AR)
8708                                 lun->pr_res_idx = residx; /* Res holder */
8709                         else
8710                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8711
8712                         lun->flags |= CTL_LUN_PR_RESERVED;
8713                         lun->res_type = type;
8714
8715                         mtx_unlock(&lun->lun_lock);
8716
8717                         /* send msg to other side */
8718                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8719                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8720                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8721                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8722                         persis_io.pr.pr_info.res_type = type;
8723                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8724                              &persis_io, sizeof(persis_io), 0)) >
8725                              CTL_HA_STATUS_SUCCESS) {
8726                                 printf("CTL:Persis Out error returned from "
8727                                        "ctl_ha_msg_send %d\n", isc_retval);
8728                         }
8729                 }
8730                 break;
8731
8732         case SPRO_RELEASE:
8733                 mtx_lock(&lun->lun_lock);
8734                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8735                         /* No reservation exists return good status */
8736                         mtx_unlock(&lun->lun_lock);
8737                         goto done;
8738                 }
8739                 /*
8740                  * Is this nexus a reservation holder?
8741                  */
8742                 if (lun->pr_res_idx != residx
8743                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8744                         /*
8745                          * not a res holder return good status but
8746                          * do nothing
8747                          */
8748                         mtx_unlock(&lun->lun_lock);
8749                         goto done;
8750                 }
8751
8752                 if (lun->res_type != type) {
8753                         mtx_unlock(&lun->lun_lock);
8754                         free(ctsio->kern_data_ptr, M_CTL);
8755                         ctl_set_illegal_pr_release(ctsio);
8756                         ctl_done((union ctl_io *)ctsio);
8757                         return (CTL_RETVAL_COMPLETE);
8758                 }
8759
8760                 /* okay to release */
8761                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8762                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8763                 lun->res_type = 0;
8764
8765                 /*
8766                  * if this isn't an exclusive access
8767                  * res generate UA for all other
8768                  * registrants.
8769                  */
8770                 if (type != SPR_TYPE_EX_AC
8771                  && type != SPR_TYPE_WR_EX) {
8772                         /*
8773                          * temporarily unregister so we don't generate UA
8774                          */
8775                         lun->per_res[residx].registered = 0;
8776
8777                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8778                                 if (lun->per_res[i+persis_offset].registered
8779                                     == 0)
8780                                         continue;
8781                                 lun->pending_sense[i].ua_pending |=
8782                                         CTL_UA_RES_RELEASE;
8783                         }
8784
8785                         lun->per_res[residx].registered = 1;
8786                 }
8787                 mtx_unlock(&lun->lun_lock);
8788                 /* Send msg to other side */
8789                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8790                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8791                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8792                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8793                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8794                         printf("CTL:Persis Out error returned from "
8795                                "ctl_ha_msg_send %d\n", isc_retval);
8796                 }
8797                 break;
8798
8799         case SPRO_CLEAR:
8800                 /* send msg to other side */
8801
8802                 mtx_lock(&lun->lun_lock);
8803                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8804                 lun->res_type = 0;
8805                 lun->pr_key_count = 0;
8806                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8807
8808
8809                 memset(&lun->per_res[residx].res_key,
8810                        0, sizeof(lun->per_res[residx].res_key));
8811                 lun->per_res[residx].registered = 0;
8812
8813                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8814                         if (lun->per_res[i].registered) {
8815                                 if (!persis_offset && i < CTL_MAX_INITIATORS)
8816                                         lun->pending_sense[i].ua_pending |=
8817                                                 CTL_UA_RES_PREEMPT;
8818                                 else if (persis_offset && i >= persis_offset)
8819                                         lun->pending_sense[i-persis_offset
8820                                             ].ua_pending |= CTL_UA_RES_PREEMPT;
8821
8822                                 memset(&lun->per_res[i].res_key,
8823                                        0, sizeof(struct scsi_per_res_key));
8824                                 lun->per_res[i].registered = 0;
8825                         }
8826                 lun->PRGeneration++;
8827                 mtx_unlock(&lun->lun_lock);
8828                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8829                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8830                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8831                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8832                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8833                         printf("CTL:Persis Out error returned from "
8834                                "ctl_ha_msg_send %d\n", isc_retval);
8835                 }
8836                 break;
8837
8838         case SPRO_PREEMPT: {
8839                 int nretval;
8840
8841                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8842                                           residx, ctsio, cdb, param);
8843                 if (nretval != 0)
8844                         return (CTL_RETVAL_COMPLETE);
8845                 break;
8846         }
8847         default:
8848                 panic("Invalid PR type %x", cdb->action);
8849         }
8850
8851 done:
8852         free(ctsio->kern_data_ptr, M_CTL);
8853         ctl_set_success(ctsio);
8854         ctl_done((union ctl_io *)ctsio);
8855
8856         return (retval);
8857 }
8858
8859 /*
8860  * This routine is for handling a message from the other SC pertaining to
8861  * persistent reserve out. All the error checking will have been done
8862  * so only perorming the action need be done here to keep the two
8863  * in sync.
8864  */
8865 static void
8866 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8867 {
8868         struct ctl_lun *lun;
8869         struct ctl_softc *softc;
8870         int i;
8871         uint32_t targ_lun;
8872
8873         softc = control_softc;
8874
8875         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8876         lun = softc->ctl_luns[targ_lun];
8877         mtx_lock(&lun->lun_lock);
8878         switch(msg->pr.pr_info.action) {
8879         case CTL_PR_REG_KEY:
8880                 if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8881                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8882                         lun->pr_key_count++;
8883                 }
8884                 lun->PRGeneration++;
8885                 memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8886                        msg->pr.pr_info.sa_res_key,
8887                        sizeof(struct scsi_per_res_key));
8888                 break;
8889
8890         case CTL_PR_UNREG_KEY:
8891                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8892                 memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8893                        0, sizeof(struct scsi_per_res_key));
8894                 lun->pr_key_count--;
8895
8896                 /* XXX Need to see if the reservation has been released */
8897                 /* if so do we need to generate UA? */
8898                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8899                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8900                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8901
8902                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8903                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8904                          && lun->pr_key_count) {
8905                                 /*
8906                                  * If the reservation is a registrants
8907                                  * only type we need to generate a UA
8908                                  * for other registered inits.  The
8909                                  * sense code should be RESERVATIONS
8910                                  * RELEASED
8911                                  */
8912
8913                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8914                                         if (lun->per_res[i+
8915                                             persis_offset].registered == 0)
8916                                                 continue;
8917
8918                                         lun->pending_sense[i
8919                                                 ].ua_pending |=
8920                                                 CTL_UA_RES_RELEASE;
8921                                 }
8922                         }
8923                         lun->res_type = 0;
8924                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8925                         if (lun->pr_key_count==0) {
8926                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8927                                 lun->res_type = 0;
8928                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8929                         }
8930                 }
8931                 lun->PRGeneration++;
8932                 break;
8933
8934         case CTL_PR_RESERVE:
8935                 lun->flags |= CTL_LUN_PR_RESERVED;
8936                 lun->res_type = msg->pr.pr_info.res_type;
8937                 lun->pr_res_idx = msg->pr.pr_info.residx;
8938
8939                 break;
8940
8941         case CTL_PR_RELEASE:
8942                 /*
8943                  * if this isn't an exclusive access res generate UA for all
8944                  * other registrants.
8945                  */
8946                 if (lun->res_type != SPR_TYPE_EX_AC
8947                  && lun->res_type != SPR_TYPE_WR_EX) {
8948                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8949                                 if (lun->per_res[i+persis_offset].registered)
8950                                         lun->pending_sense[i].ua_pending |=
8951                                                 CTL_UA_RES_RELEASE;
8952                 }
8953
8954                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8955                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8956                 lun->res_type = 0;
8957                 break;
8958
8959         case CTL_PR_PREEMPT:
8960                 ctl_pro_preempt_other(lun, msg);
8961                 break;
8962         case CTL_PR_CLEAR:
8963                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8964                 lun->res_type = 0;
8965                 lun->pr_key_count = 0;
8966                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8967
8968                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8969                         if (lun->per_res[i].registered == 0)
8970                                 continue;
8971                         if (!persis_offset
8972                          && i < CTL_MAX_INITIATORS)
8973                                 lun->pending_sense[i].ua_pending |=
8974                                         CTL_UA_RES_PREEMPT;
8975                         else if (persis_offset
8976                               && i >= persis_offset)
8977                                 lun->pending_sense[i-persis_offset].ua_pending|=
8978                                         CTL_UA_RES_PREEMPT;
8979                         memset(&lun->per_res[i].res_key, 0,
8980                                sizeof(struct scsi_per_res_key));
8981                         lun->per_res[i].registered = 0;
8982                 }
8983                 lun->PRGeneration++;
8984                 break;
8985         }
8986
8987         mtx_unlock(&lun->lun_lock);
8988 }
8989
8990 int
8991 ctl_read_write(struct ctl_scsiio *ctsio)
8992 {
8993         struct ctl_lun *lun;
8994         struct ctl_lba_len_flags *lbalen;
8995         uint64_t lba;
8996         uint32_t num_blocks;
8997         int fua, dpo;
8998         int retval;
8999         int isread;
9000
9001         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9002
9003         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9004
9005         fua = 0;
9006         dpo = 0;
9007
9008         retval = CTL_RETVAL_COMPLETE;
9009
9010         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9011               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9012         if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9013                 uint32_t residx;
9014
9015                 /*
9016                  * XXX KDM need a lock here.
9017                  */
9018                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9019                 if ((lun->res_type == SPR_TYPE_EX_AC
9020                   && residx != lun->pr_res_idx)
9021                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
9022                    || lun->res_type == SPR_TYPE_EX_AC_AR)
9023                   && !lun->per_res[residx].registered)) {
9024                         ctl_set_reservation_conflict(ctsio);
9025                         ctl_done((union ctl_io *)ctsio);
9026                         return (CTL_RETVAL_COMPLETE);
9027                 }
9028         }
9029
9030         switch (ctsio->cdb[0]) {
9031         case READ_6:
9032         case WRITE_6: {
9033                 struct scsi_rw_6 *cdb;
9034
9035                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
9036
9037                 lba = scsi_3btoul(cdb->addr);
9038                 /* only 5 bits are valid in the most significant address byte */
9039                 lba &= 0x1fffff;
9040                 num_blocks = cdb->length;
9041                 /*
9042                  * This is correct according to SBC-2.
9043                  */
9044                 if (num_blocks == 0)
9045                         num_blocks = 256;
9046                 break;
9047         }
9048         case READ_10:
9049         case WRITE_10: {
9050                 struct scsi_rw_10 *cdb;
9051
9052                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9053
9054                 if (cdb->byte2 & SRW10_FUA)
9055                         fua = 1;
9056                 if (cdb->byte2 & SRW10_DPO)
9057                         dpo = 1;
9058
9059                 lba = scsi_4btoul(cdb->addr);
9060                 num_blocks = scsi_2btoul(cdb->length);
9061                 break;
9062         }
9063         case WRITE_VERIFY_10: {
9064                 struct scsi_write_verify_10 *cdb;
9065
9066                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9067
9068                 /*
9069                  * XXX KDM we should do actual write verify support at some
9070                  * point.  This is obviously fake, we're just translating
9071                  * things to a write.  So we don't even bother checking the
9072                  * BYTCHK field, since we don't do any verification.  If
9073                  * the user asks for it, we'll just pretend we did it.
9074                  */
9075                 if (cdb->byte2 & SWV_DPO)
9076                         dpo = 1;
9077
9078                 lba = scsi_4btoul(cdb->addr);
9079                 num_blocks = scsi_2btoul(cdb->length);
9080                 break;
9081         }
9082         case READ_12:
9083         case WRITE_12: {
9084                 struct scsi_rw_12 *cdb;
9085
9086                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9087
9088                 if (cdb->byte2 & SRW12_FUA)
9089                         fua = 1;
9090                 if (cdb->byte2 & SRW12_DPO)
9091                         dpo = 1;
9092                 lba = scsi_4btoul(cdb->addr);
9093                 num_blocks = scsi_4btoul(cdb->length);
9094                 break;
9095         }
9096         case WRITE_VERIFY_12: {
9097                 struct scsi_write_verify_12 *cdb;
9098
9099                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9100
9101                 if (cdb->byte2 & SWV_DPO)
9102                         dpo = 1;
9103                 
9104                 lba = scsi_4btoul(cdb->addr);
9105                 num_blocks = scsi_4btoul(cdb->length);
9106
9107                 break;
9108         }
9109         case READ_16:
9110         case WRITE_16: {
9111                 struct scsi_rw_16 *cdb;
9112
9113                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9114
9115                 if (cdb->byte2 & SRW12_FUA)
9116                         fua = 1;
9117                 if (cdb->byte2 & SRW12_DPO)
9118                         dpo = 1;
9119
9120                 lba = scsi_8btou64(cdb->addr);
9121                 num_blocks = scsi_4btoul(cdb->length);
9122                 break;
9123         }
9124         case WRITE_VERIFY_16: {
9125                 struct scsi_write_verify_16 *cdb;
9126
9127                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9128
9129                 if (cdb->byte2 & SWV_DPO)
9130                         dpo = 1;
9131
9132                 lba = scsi_8btou64(cdb->addr);
9133                 num_blocks = scsi_4btoul(cdb->length);
9134                 break;
9135         }
9136         default:
9137                 /*
9138                  * We got a command we don't support.  This shouldn't
9139                  * happen, commands should be filtered out above us.
9140                  */
9141                 ctl_set_invalid_opcode(ctsio);
9142                 ctl_done((union ctl_io *)ctsio);
9143
9144                 return (CTL_RETVAL_COMPLETE);
9145                 break; /* NOTREACHED */
9146         }
9147
9148         /*
9149          * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9150          * interesting for us, but if RAIDCore is in write-back mode,
9151          * getting it to do write-through for a particular transaction may
9152          * not be possible.
9153          */
9154
9155         /*
9156          * The first check is to make sure we're in bounds, the second
9157          * check is to catch wrap-around problems.  If the lba + num blocks
9158          * is less than the lba, then we've wrapped around and the block
9159          * range is invalid anyway.
9160          */
9161         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9162          || ((lba + num_blocks) < lba)) {
9163                 ctl_set_lba_out_of_range(ctsio);
9164                 ctl_done((union ctl_io *)ctsio);
9165                 return (CTL_RETVAL_COMPLETE);
9166         }
9167
9168         /*
9169          * According to SBC-3, a transfer length of 0 is not an error.
9170          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9171          * translates to 256 blocks for those commands.
9172          */
9173         if (num_blocks == 0) {
9174                 ctl_set_success(ctsio);
9175                 ctl_done((union ctl_io *)ctsio);
9176                 return (CTL_RETVAL_COMPLETE);
9177         }
9178
9179         lbalen = (struct ctl_lba_len_flags *)
9180             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9181         lbalen->lba = lba;
9182         lbalen->len = num_blocks;
9183         lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
9184
9185         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9186         ctsio->kern_rel_offset = 0;
9187
9188         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9189
9190         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9191
9192         return (retval);
9193 }
9194
9195 static int
9196 ctl_cnw_cont(union ctl_io *io)
9197 {
9198         struct ctl_scsiio *ctsio;
9199         struct ctl_lun *lun;
9200         struct ctl_lba_len_flags *lbalen;
9201         int retval;
9202
9203         ctsio = &io->scsiio;
9204         ctsio->io_hdr.status = CTL_STATUS_NONE;
9205         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9206         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9207         lbalen = (struct ctl_lba_len_flags *)
9208             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9209         lbalen->flags = CTL_LLF_WRITE;
9210
9211         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9212         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9213         return (retval);
9214 }
9215
9216 int
9217 ctl_cnw(struct ctl_scsiio *ctsio)
9218 {
9219         struct ctl_lun *lun;
9220         struct ctl_lba_len_flags *lbalen;
9221         uint64_t lba;
9222         uint32_t num_blocks;
9223         int fua, dpo;
9224         int retval;
9225
9226         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9227
9228         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9229
9230         fua = 0;
9231         dpo = 0;
9232
9233         retval = CTL_RETVAL_COMPLETE;
9234
9235         switch (ctsio->cdb[0]) {
9236         case COMPARE_AND_WRITE: {
9237                 struct scsi_compare_and_write *cdb;
9238
9239                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9240
9241                 if (cdb->byte2 & SRW10_FUA)
9242                         fua = 1;
9243                 if (cdb->byte2 & SRW10_DPO)
9244                         dpo = 1;
9245                 lba = scsi_8btou64(cdb->addr);
9246                 num_blocks = cdb->length;
9247                 break;
9248         }
9249         default:
9250                 /*
9251                  * We got a command we don't support.  This shouldn't
9252                  * happen, commands should be filtered out above us.
9253                  */
9254                 ctl_set_invalid_opcode(ctsio);
9255                 ctl_done((union ctl_io *)ctsio);
9256
9257                 return (CTL_RETVAL_COMPLETE);
9258                 break; /* NOTREACHED */
9259         }
9260
9261         /*
9262          * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9263          * interesting for us, but if RAIDCore is in write-back mode,
9264          * getting it to do write-through for a particular transaction may
9265          * not be possible.
9266          */
9267
9268         /*
9269          * The first check is to make sure we're in bounds, the second
9270          * check is to catch wrap-around problems.  If the lba + num blocks
9271          * is less than the lba, then we've wrapped around and the block
9272          * range is invalid anyway.
9273          */
9274         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9275          || ((lba + num_blocks) < lba)) {
9276                 ctl_set_lba_out_of_range(ctsio);
9277                 ctl_done((union ctl_io *)ctsio);
9278                 return (CTL_RETVAL_COMPLETE);
9279         }
9280
9281         /*
9282          * According to SBC-3, a transfer length of 0 is not an error.
9283          */
9284         if (num_blocks == 0) {
9285                 ctl_set_success(ctsio);
9286                 ctl_done((union ctl_io *)ctsio);
9287                 return (CTL_RETVAL_COMPLETE);
9288         }
9289
9290         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9291         ctsio->kern_rel_offset = 0;
9292
9293         /*
9294          * Set the IO_CONT flag, so that if this I/O gets passed to
9295          * ctl_data_submit_done(), it'll get passed back to
9296          * ctl_ctl_cnw_cont() for further processing.
9297          */
9298         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9299         ctsio->io_cont = ctl_cnw_cont;
9300
9301         lbalen = (struct ctl_lba_len_flags *)
9302             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9303         lbalen->lba = lba;
9304         lbalen->len = num_blocks;
9305         lbalen->flags = CTL_LLF_COMPARE;
9306
9307         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9308         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9309         return (retval);
9310 }
9311
9312 int
9313 ctl_verify(struct ctl_scsiio *ctsio)
9314 {
9315         struct ctl_lun *lun;
9316         struct ctl_lba_len_flags *lbalen;
9317         uint64_t lba;
9318         uint32_t num_blocks;
9319         int bytchk, dpo;
9320         int retval;
9321
9322         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9323
9324         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9325
9326         bytchk = 0;
9327         dpo = 0;
9328         retval = CTL_RETVAL_COMPLETE;
9329
9330         switch (ctsio->cdb[0]) {
9331         case VERIFY_10: {
9332                 struct scsi_verify_10 *cdb;
9333
9334                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9335                 if (cdb->byte2 & SVFY_BYTCHK)
9336                         bytchk = 1;
9337                 if (cdb->byte2 & SVFY_DPO)
9338                         dpo = 1;
9339                 lba = scsi_4btoul(cdb->addr);
9340                 num_blocks = scsi_2btoul(cdb->length);
9341                 break;
9342         }
9343         case VERIFY_12: {
9344                 struct scsi_verify_12 *cdb;
9345
9346                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9347                 if (cdb->byte2 & SVFY_BYTCHK)
9348                         bytchk = 1;
9349                 if (cdb->byte2 & SVFY_DPO)
9350                         dpo = 1;
9351                 lba = scsi_4btoul(cdb->addr);
9352                 num_blocks = scsi_4btoul(cdb->length);
9353                 break;
9354         }
9355         case VERIFY_16: {
9356                 struct scsi_rw_16 *cdb;
9357
9358                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9359                 if (cdb->byte2 & SVFY_BYTCHK)
9360                         bytchk = 1;
9361                 if (cdb->byte2 & SVFY_DPO)
9362                         dpo = 1;
9363                 lba = scsi_8btou64(cdb->addr);
9364                 num_blocks = scsi_4btoul(cdb->length);
9365                 break;
9366         }
9367         default:
9368                 /*
9369                  * We got a command we don't support.  This shouldn't
9370                  * happen, commands should be filtered out above us.
9371                  */
9372                 ctl_set_invalid_opcode(ctsio);
9373                 ctl_done((union ctl_io *)ctsio);
9374                 return (CTL_RETVAL_COMPLETE);
9375         }
9376
9377         /*
9378          * The first check is to make sure we're in bounds, the second
9379          * check is to catch wrap-around problems.  If the lba + num blocks
9380          * is less than the lba, then we've wrapped around and the block
9381          * range is invalid anyway.
9382          */
9383         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9384          || ((lba + num_blocks) < lba)) {
9385                 ctl_set_lba_out_of_range(ctsio);
9386                 ctl_done((union ctl_io *)ctsio);
9387                 return (CTL_RETVAL_COMPLETE);
9388         }
9389
9390         /*
9391          * According to SBC-3, a transfer length of 0 is not an error.
9392          */
9393         if (num_blocks == 0) {
9394                 ctl_set_success(ctsio);
9395                 ctl_done((union ctl_io *)ctsio);
9396                 return (CTL_RETVAL_COMPLETE);
9397         }
9398
9399         lbalen = (struct ctl_lba_len_flags *)
9400             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9401         lbalen->lba = lba;
9402         lbalen->len = num_blocks;
9403         if (bytchk) {
9404                 lbalen->flags = CTL_LLF_COMPARE;
9405                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9406         } else {
9407                 lbalen->flags = CTL_LLF_VERIFY;
9408                 ctsio->kern_total_len = 0;
9409         }
9410         ctsio->kern_rel_offset = 0;
9411
9412         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9413         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9414         return (retval);
9415 }
9416
9417 int
9418 ctl_report_luns(struct ctl_scsiio *ctsio)
9419 {
9420         struct scsi_report_luns *cdb;
9421         struct scsi_report_luns_data *lun_data;
9422         struct ctl_lun *lun, *request_lun;
9423         int num_luns, retval;
9424         uint32_t alloc_len, lun_datalen;
9425         int num_filled, well_known;
9426         uint32_t initidx, targ_lun_id, lun_id;
9427
9428         retval = CTL_RETVAL_COMPLETE;
9429         well_known = 0;
9430
9431         cdb = (struct scsi_report_luns *)ctsio->cdb;
9432
9433         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9434
9435         mtx_lock(&control_softc->ctl_lock);
9436         num_luns = control_softc->num_luns;
9437         mtx_unlock(&control_softc->ctl_lock);
9438
9439         switch (cdb->select_report) {
9440         case RPL_REPORT_DEFAULT:
9441         case RPL_REPORT_ALL:
9442                 break;
9443         case RPL_REPORT_WELLKNOWN:
9444                 well_known = 1;
9445                 num_luns = 0;
9446                 break;
9447         default:
9448                 ctl_set_invalid_field(ctsio,
9449                                       /*sks_valid*/ 1,
9450                                       /*command*/ 1,
9451                                       /*field*/ 2,
9452                                       /*bit_valid*/ 0,
9453                                       /*bit*/ 0);
9454                 ctl_done((union ctl_io *)ctsio);
9455                 return (retval);
9456                 break; /* NOTREACHED */
9457         }
9458
9459         alloc_len = scsi_4btoul(cdb->length);
9460         /*
9461          * The initiator has to allocate at least 16 bytes for this request,
9462          * so he can at least get the header and the first LUN.  Otherwise
9463          * we reject the request (per SPC-3 rev 14, section 6.21).
9464          */
9465         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9466             sizeof(struct scsi_report_luns_lundata))) {
9467                 ctl_set_invalid_field(ctsio,
9468                                       /*sks_valid*/ 1,
9469                                       /*command*/ 1,
9470                                       /*field*/ 6,
9471                                       /*bit_valid*/ 0,
9472                                       /*bit*/ 0);
9473                 ctl_done((union ctl_io *)ctsio);
9474                 return (retval);
9475         }
9476
9477         request_lun = (struct ctl_lun *)
9478                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9479
9480         lun_datalen = sizeof(*lun_data) +
9481                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9482
9483         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9484         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9485         ctsio->kern_sg_entries = 0;
9486
9487         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9488
9489         mtx_lock(&control_softc->ctl_lock);
9490         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9491                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9492                 if (lun_id >= CTL_MAX_LUNS)
9493                         continue;
9494                 lun = control_softc->ctl_luns[lun_id];
9495                 if (lun == NULL)
9496                         continue;
9497
9498                 if (targ_lun_id <= 0xff) {
9499                         /*
9500                          * Peripheral addressing method, bus number 0.
9501                          */
9502                         lun_data->luns[num_filled].lundata[0] =
9503                                 RPL_LUNDATA_ATYP_PERIPH;
9504                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9505                         num_filled++;
9506                 } else if (targ_lun_id <= 0x3fff) {
9507                         /*
9508                          * Flat addressing method.
9509                          */
9510                         lun_data->luns[num_filled].lundata[0] =
9511                                 RPL_LUNDATA_ATYP_FLAT |
9512                                 (targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9513 #ifdef OLDCTLHEADERS
9514                                 (SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9515                                 (targ_lun_id & SRLD_BUS_LUN_MASK);
9516 #endif
9517                         lun_data->luns[num_filled].lundata[1] =
9518 #ifdef OLDCTLHEADERS
9519                                 targ_lun_id >> SRLD_BUS_LUN_BITS;
9520 #endif
9521                                 targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9522                         num_filled++;
9523                 } else {
9524                         printf("ctl_report_luns: bogus LUN number %jd, "
9525                                "skipping\n", (intmax_t)targ_lun_id);
9526                 }
9527                 /*
9528                  * According to SPC-3, rev 14 section 6.21:
9529                  *
9530                  * "The execution of a REPORT LUNS command to any valid and
9531                  * installed logical unit shall clear the REPORTED LUNS DATA
9532                  * HAS CHANGED unit attention condition for all logical
9533                  * units of that target with respect to the requesting
9534                  * initiator. A valid and installed logical unit is one
9535                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9536                  * INQUIRY data (see 6.4.2)."
9537                  *
9538                  * If request_lun is NULL, the LUN this report luns command
9539                  * was issued to is either disabled or doesn't exist. In that
9540                  * case, we shouldn't clear any pending lun change unit
9541                  * attention.
9542                  */
9543                 if (request_lun != NULL) {
9544                         mtx_lock(&lun->lun_lock);
9545                         lun->pending_sense[initidx].ua_pending &=
9546                                 ~CTL_UA_LUN_CHANGE;
9547                         mtx_unlock(&lun->lun_lock);
9548                 }
9549         }
9550         mtx_unlock(&control_softc->ctl_lock);
9551
9552         /*
9553          * It's quite possible that we've returned fewer LUNs than we allocated
9554          * space for.  Trim it.
9555          */
9556         lun_datalen = sizeof(*lun_data) +
9557                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9558
9559         if (lun_datalen < alloc_len) {
9560                 ctsio->residual = alloc_len - lun_datalen;
9561                 ctsio->kern_data_len = lun_datalen;
9562                 ctsio->kern_total_len = lun_datalen;
9563         } else {
9564                 ctsio->residual = 0;
9565                 ctsio->kern_data_len = alloc_len;
9566                 ctsio->kern_total_len = alloc_len;
9567         }
9568         ctsio->kern_data_resid = 0;
9569         ctsio->kern_rel_offset = 0;
9570         ctsio->kern_sg_entries = 0;
9571
9572         /*
9573          * We set this to the actual data length, regardless of how much
9574          * space we actually have to return results.  If the user looks at
9575          * this value, he'll know whether or not he allocated enough space
9576          * and reissue the command if necessary.  We don't support well
9577          * known logical units, so if the user asks for that, return none.
9578          */
9579         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9580
9581         /*
9582          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9583          * this request.
9584          */
9585         ctsio->scsi_status = SCSI_STATUS_OK;
9586
9587         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9588         ctsio->be_move_done = ctl_config_move_done;
9589         ctl_datamove((union ctl_io *)ctsio);
9590
9591         return (retval);
9592 }
9593
9594 int
9595 ctl_request_sense(struct ctl_scsiio *ctsio)
9596 {
9597         struct scsi_request_sense *cdb;
9598         struct scsi_sense_data *sense_ptr;
9599         struct ctl_lun *lun;
9600         uint32_t initidx;
9601         int have_error;
9602         scsi_sense_data_type sense_format;
9603
9604         cdb = (struct scsi_request_sense *)ctsio->cdb;
9605
9606         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9607
9608         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9609
9610         /*
9611          * Determine which sense format the user wants.
9612          */
9613         if (cdb->byte2 & SRS_DESC)
9614                 sense_format = SSD_TYPE_DESC;
9615         else
9616                 sense_format = SSD_TYPE_FIXED;
9617
9618         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9619         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9620         ctsio->kern_sg_entries = 0;
9621
9622         /*
9623          * struct scsi_sense_data, which is currently set to 256 bytes, is
9624          * larger than the largest allowed value for the length field in the
9625          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9626          */
9627         ctsio->residual = 0;
9628         ctsio->kern_data_len = cdb->length;
9629         ctsio->kern_total_len = cdb->length;
9630
9631         ctsio->kern_data_resid = 0;
9632         ctsio->kern_rel_offset = 0;
9633         ctsio->kern_sg_entries = 0;
9634
9635         /*
9636          * If we don't have a LUN, we don't have any pending sense.
9637          */
9638         if (lun == NULL)
9639                 goto no_sense;
9640
9641         have_error = 0;
9642         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9643         /*
9644          * Check for pending sense, and then for pending unit attentions.
9645          * Pending sense gets returned first, then pending unit attentions.
9646          */
9647         mtx_lock(&lun->lun_lock);
9648         if (ctl_is_set(lun->have_ca, initidx)) {
9649                 scsi_sense_data_type stored_format;
9650
9651                 /*
9652                  * Check to see which sense format was used for the stored
9653                  * sense data.
9654                  */
9655                 stored_format = scsi_sense_type(
9656                     &lun->pending_sense[initidx].sense);
9657
9658                 /*
9659                  * If the user requested a different sense format than the
9660                  * one we stored, then we need to convert it to the other
9661                  * format.  If we're going from descriptor to fixed format
9662                  * sense data, we may lose things in translation, depending
9663                  * on what options were used.
9664                  *
9665                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9666                  * for some reason we'll just copy it out as-is.
9667                  */
9668                 if ((stored_format == SSD_TYPE_FIXED)
9669                  && (sense_format == SSD_TYPE_DESC))
9670                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9671                             &lun->pending_sense[initidx].sense,
9672                             (struct scsi_sense_data_desc *)sense_ptr);
9673                 else if ((stored_format == SSD_TYPE_DESC)
9674                       && (sense_format == SSD_TYPE_FIXED))
9675                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9676                             &lun->pending_sense[initidx].sense,
9677                             (struct scsi_sense_data_fixed *)sense_ptr);
9678                 else
9679                         memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
9680                                ctl_min(sizeof(*sense_ptr),
9681                                sizeof(lun->pending_sense[initidx].sense)));
9682
9683                 ctl_clear_mask(lun->have_ca, initidx);
9684                 have_error = 1;
9685         } else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
9686                 ctl_ua_type ua_type;
9687
9688                 ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
9689                                        sense_ptr, sense_format);
9690                 if (ua_type != CTL_UA_NONE) {
9691                         have_error = 1;
9692                         /* We're reporting this UA, so clear it */
9693                         lun->pending_sense[initidx].ua_pending &= ~ua_type;
9694                 }
9695         }
9696         mtx_unlock(&lun->lun_lock);
9697
9698         /*
9699          * We already have a pending error, return it.
9700          */
9701         if (have_error != 0) {
9702                 /*
9703                  * We report the SCSI status as OK, since the status of the
9704                  * request sense command itself is OK.
9705                  */
9706                 ctsio->scsi_status = SCSI_STATUS_OK;
9707
9708                 /*
9709                  * We report 0 for the sense length, because we aren't doing
9710                  * autosense in this case.  We're reporting sense as
9711                  * parameter data.
9712                  */
9713                 ctsio->sense_len = 0;
9714                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9715                 ctsio->be_move_done = ctl_config_move_done;
9716                 ctl_datamove((union ctl_io *)ctsio);
9717
9718                 return (CTL_RETVAL_COMPLETE);
9719         }
9720
9721 no_sense:
9722
9723         /*
9724          * No sense information to report, so we report that everything is
9725          * okay.
9726          */
9727         ctl_set_sense_data(sense_ptr,
9728                            lun,
9729                            sense_format,
9730                            /*current_error*/ 1,
9731                            /*sense_key*/ SSD_KEY_NO_SENSE,
9732                            /*asc*/ 0x00,
9733                            /*ascq*/ 0x00,
9734                            SSD_ELEM_NONE);
9735
9736         ctsio->scsi_status = SCSI_STATUS_OK;
9737
9738         /*
9739          * We report 0 for the sense length, because we aren't doing
9740          * autosense in this case.  We're reporting sense as parameter data.
9741          */
9742         ctsio->sense_len = 0;
9743         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9744         ctsio->be_move_done = ctl_config_move_done;
9745         ctl_datamove((union ctl_io *)ctsio);
9746
9747         return (CTL_RETVAL_COMPLETE);
9748 }
9749
9750 int
9751 ctl_tur(struct ctl_scsiio *ctsio)
9752 {
9753         struct ctl_lun *lun;
9754
9755         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9756
9757         CTL_DEBUG_PRINT(("ctl_tur\n"));
9758
9759         if (lun == NULL)
9760                 return (EINVAL);
9761
9762         ctsio->scsi_status = SCSI_STATUS_OK;
9763         ctsio->io_hdr.status = CTL_SUCCESS;
9764
9765         ctl_done((union ctl_io *)ctsio);
9766
9767         return (CTL_RETVAL_COMPLETE);
9768 }
9769
9770 #ifdef notyet
9771 static int
9772 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9773 {
9774
9775 }
9776 #endif
9777
9778 static int
9779 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9780 {
9781         struct scsi_vpd_supported_pages *pages;
9782         int sup_page_size;
9783         struct ctl_lun *lun;
9784
9785         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9786
9787         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9788             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9789         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9790         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9791         ctsio->kern_sg_entries = 0;
9792
9793         if (sup_page_size < alloc_len) {
9794                 ctsio->residual = alloc_len - sup_page_size;
9795                 ctsio->kern_data_len = sup_page_size;
9796                 ctsio->kern_total_len = sup_page_size;
9797         } else {
9798                 ctsio->residual = 0;
9799                 ctsio->kern_data_len = alloc_len;
9800                 ctsio->kern_total_len = alloc_len;
9801         }
9802         ctsio->kern_data_resid = 0;
9803         ctsio->kern_rel_offset = 0;
9804         ctsio->kern_sg_entries = 0;
9805
9806         /*
9807          * The control device is always connected.  The disk device, on the
9808          * other hand, may not be online all the time.  Need to change this
9809          * to figure out whether the disk device is actually online or not.
9810          */
9811         if (lun != NULL)
9812                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9813                                 lun->be_lun->lun_type;
9814         else
9815                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9816
9817         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9818         /* Supported VPD pages */
9819         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9820         /* Serial Number */
9821         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9822         /* Device Identification */
9823         pages->page_list[2] = SVPD_DEVICE_ID;
9824         /* SCSI Ports */
9825         pages->page_list[3] = SVPD_SCSI_PORTS;
9826         /* Block limits */
9827         pages->page_list[4] = SVPD_BLOCK_LIMITS;
9828         /* Logical Block Provisioning */
9829         pages->page_list[5] = SVPD_LBP;
9830
9831         ctsio->scsi_status = SCSI_STATUS_OK;
9832
9833         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9834         ctsio->be_move_done = ctl_config_move_done;
9835         ctl_datamove((union ctl_io *)ctsio);
9836
9837         return (CTL_RETVAL_COMPLETE);
9838 }
9839
9840 static int
9841 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9842 {
9843         struct scsi_vpd_unit_serial_number *sn_ptr;
9844         struct ctl_lun *lun;
9845
9846         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9847
9848         ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9849         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9850         ctsio->kern_sg_entries = 0;
9851
9852         if (sizeof(*sn_ptr) < alloc_len) {
9853                 ctsio->residual = alloc_len - sizeof(*sn_ptr);
9854                 ctsio->kern_data_len = sizeof(*sn_ptr);
9855                 ctsio->kern_total_len = sizeof(*sn_ptr);
9856         } else {
9857                 ctsio->residual = 0;
9858                 ctsio->kern_data_len = alloc_len;
9859                 ctsio->kern_total_len = alloc_len;
9860         }
9861         ctsio->kern_data_resid = 0;
9862         ctsio->kern_rel_offset = 0;
9863         ctsio->kern_sg_entries = 0;
9864
9865         /*
9866          * The control device is always connected.  The disk device, on the
9867          * other hand, may not be online all the time.  Need to change this
9868          * to figure out whether the disk device is actually online or not.
9869          */
9870         if (lun != NULL)
9871                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9872                                   lun->be_lun->lun_type;
9873         else
9874                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9875
9876         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9877         sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9878         /*
9879          * If we don't have a LUN, we just leave the serial number as
9880          * all spaces.
9881          */
9882         memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9883         if (lun != NULL) {
9884                 strncpy((char *)sn_ptr->serial_num,
9885                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9886         }
9887         ctsio->scsi_status = SCSI_STATUS_OK;
9888
9889         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9890         ctsio->be_move_done = ctl_config_move_done;
9891         ctl_datamove((union ctl_io *)ctsio);
9892
9893         return (CTL_RETVAL_COMPLETE);
9894 }
9895
9896
9897 static int
9898 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9899 {
9900         struct scsi_vpd_device_id *devid_ptr;
9901         struct scsi_vpd_id_descriptor *desc;
9902         struct ctl_softc *ctl_softc;
9903         struct ctl_lun *lun;
9904         struct ctl_port *port;
9905         int data_len;
9906         uint8_t proto;
9907
9908         ctl_softc = control_softc;
9909
9910         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9911         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9912
9913         data_len = sizeof(struct scsi_vpd_device_id) +
9914             sizeof(struct scsi_vpd_id_descriptor) +
9915                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9916             sizeof(struct scsi_vpd_id_descriptor) +
9917                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9918         if (lun && lun->lun_devid)
9919                 data_len += lun->lun_devid->len;
9920         if (port->port_devid)
9921                 data_len += port->port_devid->len;
9922         if (port->target_devid)
9923                 data_len += port->target_devid->len;
9924
9925         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9926         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9927         ctsio->kern_sg_entries = 0;
9928
9929         if (data_len < alloc_len) {
9930                 ctsio->residual = alloc_len - data_len;
9931                 ctsio->kern_data_len = data_len;
9932                 ctsio->kern_total_len = data_len;
9933         } else {
9934                 ctsio->residual = 0;
9935                 ctsio->kern_data_len = alloc_len;
9936                 ctsio->kern_total_len = alloc_len;
9937         }
9938         ctsio->kern_data_resid = 0;
9939         ctsio->kern_rel_offset = 0;
9940         ctsio->kern_sg_entries = 0;
9941
9942         /*
9943          * The control device is always connected.  The disk device, on the
9944          * other hand, may not be online all the time.
9945          */
9946         if (lun != NULL)
9947                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9948                                      lun->be_lun->lun_type;
9949         else
9950                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9951         devid_ptr->page_code = SVPD_DEVICE_ID;
9952         scsi_ulto2b(data_len - 4, devid_ptr->length);
9953
9954         if (port->port_type == CTL_PORT_FC)
9955                 proto = SCSI_PROTO_FC << 4;
9956         else if (port->port_type == CTL_PORT_ISCSI)
9957                 proto = SCSI_PROTO_ISCSI << 4;
9958         else
9959                 proto = SCSI_PROTO_SPI << 4;
9960         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9961
9962         /*
9963          * We're using a LUN association here.  i.e., this device ID is a
9964          * per-LUN identifier.
9965          */
9966         if (lun && lun->lun_devid) {
9967                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9968                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9969                     lun->lun_devid->len);
9970         }
9971
9972         /*
9973          * This is for the WWPN which is a port association.
9974          */
9975         if (port->port_devid) {
9976                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9977                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9978                     port->port_devid->len);
9979         }
9980
9981         /*
9982          * This is for the Relative Target Port(type 4h) identifier
9983          */
9984         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9985         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9986             SVPD_ID_TYPE_RELTARG;
9987         desc->length = 4;
9988         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9989         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9990             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9991
9992         /*
9993          * This is for the Target Port Group(type 5h) identifier
9994          */
9995         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9996         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9997             SVPD_ID_TYPE_TPORTGRP;
9998         desc->length = 4;
9999         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10000             &desc->identifier[2]);
10001         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10002             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10003
10004         /*
10005          * This is for the Target identifier
10006          */
10007         if (port->target_devid) {
10008                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10009         }
10010
10011         ctsio->scsi_status = SCSI_STATUS_OK;
10012         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10013         ctsio->be_move_done = ctl_config_move_done;
10014         ctl_datamove((union ctl_io *)ctsio);
10015
10016         return (CTL_RETVAL_COMPLETE);
10017 }
10018
10019 static int
10020 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10021 {
10022         struct ctl_softc *softc = control_softc;
10023         struct scsi_vpd_scsi_ports *sp;
10024         struct scsi_vpd_port_designation *pd;
10025         struct scsi_vpd_port_designation_cont *pdc;
10026         struct ctl_lun *lun;
10027         struct ctl_port *port;
10028         int data_len, num_target_ports, id_len, g, pg, p;
10029         int num_target_port_groups, single;
10030
10031         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10032
10033         single = ctl_is_single;
10034         if (single)
10035                 num_target_port_groups = 1;
10036         else
10037                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10038         num_target_ports = 0;
10039         id_len = 0;
10040         mtx_lock(&softc->ctl_lock);
10041         STAILQ_FOREACH(port, &softc->port_list, links) {
10042                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10043                         continue;
10044                 if (lun != NULL &&
10045                     ctl_map_lun_back(port->targ_port, lun->lun) >=
10046                     CTL_MAX_LUNS)
10047                         continue;
10048                 num_target_ports++;
10049                 if (port->port_devid)
10050                         id_len += port->port_devid->len;
10051         }
10052         mtx_unlock(&softc->ctl_lock);
10053
10054         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10055             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10056              sizeof(struct scsi_vpd_port_designation_cont)) + id_len;
10057         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10058         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10059         ctsio->kern_sg_entries = 0;
10060
10061         if (data_len < alloc_len) {
10062                 ctsio->residual = alloc_len - data_len;
10063                 ctsio->kern_data_len = data_len;
10064                 ctsio->kern_total_len = data_len;
10065         } else {
10066                 ctsio->residual = 0;
10067                 ctsio->kern_data_len = alloc_len;
10068                 ctsio->kern_total_len = alloc_len;
10069         }
10070         ctsio->kern_data_resid = 0;
10071         ctsio->kern_rel_offset = 0;
10072         ctsio->kern_sg_entries = 0;
10073
10074         /*
10075          * The control device is always connected.  The disk device, on the
10076          * other hand, may not be online all the time.  Need to change this
10077          * to figure out whether the disk device is actually online or not.
10078          */
10079         if (lun != NULL)
10080                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10081                                   lun->be_lun->lun_type;
10082         else
10083                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10084
10085         sp->page_code = SVPD_SCSI_PORTS;
10086         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10087             sp->page_length);
10088         pd = &sp->design[0];
10089
10090         mtx_lock(&softc->ctl_lock);
10091         if (softc->flags & CTL_FLAG_MASTER_SHELF)
10092                 pg = 0;
10093         else
10094                 pg = 1;
10095         for (g = 0; g < num_target_port_groups; g++) {
10096                 STAILQ_FOREACH(port, &softc->port_list, links) {
10097                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10098                                 continue;
10099                         if (lun != NULL &&
10100                             ctl_map_lun_back(port->targ_port, lun->lun) >=
10101                             CTL_MAX_LUNS)
10102                                 continue;
10103                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10104                         scsi_ulto2b(p, pd->relative_port_id);
10105                         scsi_ulto2b(0, pd->initiator_transportid_length);
10106                         pdc = (struct scsi_vpd_port_designation_cont *)
10107                             &pd->initiator_transportid[0];
10108                         if (port->port_devid && g == pg) {
10109                                 id_len = port->port_devid->len;
10110                                 scsi_ulto2b(port->port_devid->len,
10111                                     pdc->target_port_descriptors_length);
10112                                 memcpy(pdc->target_port_descriptors,
10113                                     port->port_devid->data, port->port_devid->len);
10114                         } else {
10115                                 id_len = 0;
10116                                 scsi_ulto2b(0, pdc->target_port_descriptors_length);
10117                         }
10118                         pd = (struct scsi_vpd_port_designation *)
10119                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10120                 }
10121         }
10122         mtx_unlock(&softc->ctl_lock);
10123
10124         ctsio->scsi_status = SCSI_STATUS_OK;
10125         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10126         ctsio->be_move_done = ctl_config_move_done;
10127         ctl_datamove((union ctl_io *)ctsio);
10128
10129         return (CTL_RETVAL_COMPLETE);
10130 }
10131
10132 static int
10133 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10134 {
10135         struct scsi_vpd_block_limits *bl_ptr;
10136         struct ctl_lun *lun;
10137         int bs;
10138
10139         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10140
10141         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10142         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10143         ctsio->kern_sg_entries = 0;
10144
10145         if (sizeof(*bl_ptr) < alloc_len) {
10146                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10147                 ctsio->kern_data_len = sizeof(*bl_ptr);
10148                 ctsio->kern_total_len = sizeof(*bl_ptr);
10149         } else {
10150                 ctsio->residual = 0;
10151                 ctsio->kern_data_len = alloc_len;
10152                 ctsio->kern_total_len = alloc_len;
10153         }
10154         ctsio->kern_data_resid = 0;
10155         ctsio->kern_rel_offset = 0;
10156         ctsio->kern_sg_entries = 0;
10157
10158         /*
10159          * The control device is always connected.  The disk device, on the
10160          * other hand, may not be online all the time.  Need to change this
10161          * to figure out whether the disk device is actually online or not.
10162          */
10163         if (lun != NULL)
10164                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10165                                   lun->be_lun->lun_type;
10166         else
10167                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10168
10169         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10170         scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10171         bl_ptr->max_cmp_write_len = 0xff;
10172         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10173         if (lun != NULL) {
10174                 bs = lun->be_lun->blocksize;
10175                 scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10176                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10177                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10178                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10179                 }
10180         }
10181         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10182
10183         ctsio->scsi_status = SCSI_STATUS_OK;
10184         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10185         ctsio->be_move_done = ctl_config_move_done;
10186         ctl_datamove((union ctl_io *)ctsio);
10187
10188         return (CTL_RETVAL_COMPLETE);
10189 }
10190
10191 static int
10192 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10193 {
10194         struct scsi_vpd_logical_block_prov *lbp_ptr;
10195         struct ctl_lun *lun;
10196
10197         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10198
10199         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10200         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10201         ctsio->kern_sg_entries = 0;
10202
10203         if (sizeof(*lbp_ptr) < alloc_len) {
10204                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10205                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10206                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10207         } else {
10208                 ctsio->residual = 0;
10209                 ctsio->kern_data_len = alloc_len;
10210                 ctsio->kern_total_len = alloc_len;
10211         }
10212         ctsio->kern_data_resid = 0;
10213         ctsio->kern_rel_offset = 0;
10214         ctsio->kern_sg_entries = 0;
10215
10216         /*
10217          * The control device is always connected.  The disk device, on the
10218          * other hand, may not be online all the time.  Need to change this
10219          * to figure out whether the disk device is actually online or not.
10220          */
10221         if (lun != NULL)
10222                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10223                                   lun->be_lun->lun_type;
10224         else
10225                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10226
10227         lbp_ptr->page_code = SVPD_LBP;
10228         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
10229                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
10230
10231         ctsio->scsi_status = SCSI_STATUS_OK;
10232         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10233         ctsio->be_move_done = ctl_config_move_done;
10234         ctl_datamove((union ctl_io *)ctsio);
10235
10236         return (CTL_RETVAL_COMPLETE);
10237 }
10238
10239 static int
10240 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10241 {
10242         struct scsi_inquiry *cdb;
10243         struct ctl_lun *lun;
10244         int alloc_len, retval;
10245
10246         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10247         cdb = (struct scsi_inquiry *)ctsio->cdb;
10248
10249         retval = CTL_RETVAL_COMPLETE;
10250
10251         alloc_len = scsi_2btoul(cdb->length);
10252
10253         switch (cdb->page_code) {
10254         case SVPD_SUPPORTED_PAGES:
10255                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10256                 break;
10257         case SVPD_UNIT_SERIAL_NUMBER:
10258                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10259                 break;
10260         case SVPD_DEVICE_ID:
10261                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10262                 break;
10263         case SVPD_SCSI_PORTS:
10264                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10265                 break;
10266         case SVPD_BLOCK_LIMITS:
10267                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10268                 break;
10269         case SVPD_LBP:
10270                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10271                 break;
10272         default:
10273                 ctl_set_invalid_field(ctsio,
10274                                       /*sks_valid*/ 1,
10275                                       /*command*/ 1,
10276                                       /*field*/ 2,
10277                                       /*bit_valid*/ 0,
10278                                       /*bit*/ 0);
10279                 ctl_done((union ctl_io *)ctsio);
10280                 retval = CTL_RETVAL_COMPLETE;
10281                 break;
10282         }
10283
10284         return (retval);
10285 }
10286
10287 static int
10288 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10289 {
10290         struct scsi_inquiry_data *inq_ptr;
10291         struct scsi_inquiry *cdb;
10292         struct ctl_softc *ctl_softc;
10293         struct ctl_lun *lun;
10294         char *val;
10295         uint32_t alloc_len;
10296         int is_fc;
10297
10298         ctl_softc = control_softc;
10299
10300         /*
10301          * Figure out whether we're talking to a Fibre Channel port or not.
10302          * We treat the ioctl front end, and any SCSI adapters, as packetized
10303          * SCSI front ends.
10304          */
10305         if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
10306             CTL_PORT_FC)
10307                 is_fc = 0;
10308         else
10309                 is_fc = 1;
10310
10311         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10312         cdb = (struct scsi_inquiry *)ctsio->cdb;
10313         alloc_len = scsi_2btoul(cdb->length);
10314
10315         /*
10316          * We malloc the full inquiry data size here and fill it
10317          * in.  If the user only asks for less, we'll give him
10318          * that much.
10319          */
10320         ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10321         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10322         ctsio->kern_sg_entries = 0;
10323         ctsio->kern_data_resid = 0;
10324         ctsio->kern_rel_offset = 0;
10325
10326         if (sizeof(*inq_ptr) < alloc_len) {
10327                 ctsio->residual = alloc_len - sizeof(*inq_ptr);
10328                 ctsio->kern_data_len = sizeof(*inq_ptr);
10329                 ctsio->kern_total_len = sizeof(*inq_ptr);
10330         } else {
10331                 ctsio->residual = 0;
10332                 ctsio->kern_data_len = alloc_len;
10333                 ctsio->kern_total_len = alloc_len;
10334         }
10335
10336         /*
10337          * If we have a LUN configured, report it as connected.  Otherwise,
10338          * report that it is offline or no device is supported, depending 
10339          * on the value of inquiry_pq_no_lun.
10340          *
10341          * According to the spec (SPC-4 r34), the peripheral qualifier
10342          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10343          *
10344          * "A peripheral device having the specified peripheral device type 
10345          * is not connected to this logical unit. However, the device
10346          * server is capable of supporting the specified peripheral device
10347          * type on this logical unit."
10348          *
10349          * According to the same spec, the peripheral qualifier
10350          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10351          *
10352          * "The device server is not capable of supporting a peripheral
10353          * device on this logical unit. For this peripheral qualifier the
10354          * peripheral device type shall be set to 1Fh. All other peripheral
10355          * device type values are reserved for this peripheral qualifier."
10356          *
10357          * Given the text, it would seem that we probably want to report that
10358          * the LUN is offline here.  There is no LUN connected, but we can
10359          * support a LUN at the given LUN number.
10360          *
10361          * In the real world, though, it sounds like things are a little
10362          * different:
10363          *
10364          * - Linux, when presented with a LUN with the offline peripheral
10365          *   qualifier, will create an sg driver instance for it.  So when
10366          *   you attach it to CTL, you wind up with a ton of sg driver
10367          *   instances.  (One for every LUN that Linux bothered to probe.)
10368          *   Linux does this despite the fact that it issues a REPORT LUNs
10369          *   to LUN 0 to get the inventory of supported LUNs.
10370          *
10371          * - There is other anecdotal evidence (from Emulex folks) about
10372          *   arrays that use the offline peripheral qualifier for LUNs that
10373          *   are on the "passive" path in an active/passive array.
10374          *
10375          * So the solution is provide a hopefully reasonable default
10376          * (return bad/no LUN) and allow the user to change the behavior
10377          * with a tunable/sysctl variable.
10378          */
10379         if (lun != NULL)
10380                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10381                                   lun->be_lun->lun_type;
10382         else if (ctl_softc->inquiry_pq_no_lun == 0)
10383                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10384         else
10385                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10386
10387         /* RMB in byte 2 is 0 */
10388         inq_ptr->version = SCSI_REV_SPC3;
10389
10390         /*
10391          * According to SAM-3, even if a device only supports a single
10392          * level of LUN addressing, it should still set the HISUP bit:
10393          *
10394          * 4.9.1 Logical unit numbers overview
10395          *
10396          * All logical unit number formats described in this standard are
10397          * hierarchical in structure even when only a single level in that
10398          * hierarchy is used. The HISUP bit shall be set to one in the
10399          * standard INQUIRY data (see SPC-2) when any logical unit number
10400          * format described in this standard is used.  Non-hierarchical
10401          * formats are outside the scope of this standard.
10402          *
10403          * Therefore we set the HiSup bit here.
10404          *
10405          * The reponse format is 2, per SPC-3.
10406          */
10407         inq_ptr->response_format = SID_HiSup | 2;
10408
10409         inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
10410         CTL_DEBUG_PRINT(("additional_length = %d\n",
10411                          inq_ptr->additional_length));
10412
10413         inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
10414         /* 16 bit addressing */
10415         if (is_fc == 0)
10416                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10417         /* XXX set the SID_MultiP bit here if we're actually going to
10418            respond on multiple ports */
10419         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10420
10421         /* 16 bit data bus, synchronous transfers */
10422         /* XXX these flags don't apply for FC */
10423         if (is_fc == 0)
10424                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10425         /*
10426          * XXX KDM do we want to support tagged queueing on the control
10427          * device at all?
10428          */
10429         if ((lun == NULL)
10430          || (lun->be_lun->lun_type != T_PROCESSOR))
10431                 inq_ptr->flags |= SID_CmdQue;
10432         /*
10433          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10434          * We have 8 bytes for the vendor name, and 16 bytes for the device
10435          * name and 4 bytes for the revision.
10436          */
10437         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10438             "vendor")) == NULL) {
10439                 strcpy(inq_ptr->vendor, CTL_VENDOR);
10440         } else {
10441                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10442                 strncpy(inq_ptr->vendor, val,
10443                     min(sizeof(inq_ptr->vendor), strlen(val)));
10444         }
10445         if (lun == NULL) {
10446                 strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10447         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10448                 switch (lun->be_lun->lun_type) {
10449                 case T_DIRECT:
10450                         strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10451                         break;
10452                 case T_PROCESSOR:
10453                         strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10454                         break;
10455                 default:
10456                         strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10457                         break;
10458                 }
10459         } else {
10460                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10461                 strncpy(inq_ptr->product, val,
10462                     min(sizeof(inq_ptr->product), strlen(val)));
10463         }
10464
10465         /*
10466          * XXX make this a macro somewhere so it automatically gets
10467          * incremented when we make changes.
10468          */
10469         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10470             "revision")) == NULL) {
10471                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10472         } else {
10473                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10474                 strncpy(inq_ptr->revision, val,
10475                     min(sizeof(inq_ptr->revision), strlen(val)));
10476         }
10477
10478         /*
10479          * For parallel SCSI, we support double transition and single
10480          * transition clocking.  We also support QAS (Quick Arbitration
10481          * and Selection) and Information Unit transfers on both the
10482          * control and array devices.
10483          */
10484         if (is_fc == 0)
10485                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10486                                     SID_SPI_IUS;
10487
10488         /* SAM-3 */
10489         scsi_ulto2b(0x0060, inq_ptr->version1);
10490         /* SPC-3 (no version claimed) XXX should we claim a version? */
10491         scsi_ulto2b(0x0300, inq_ptr->version2);
10492         if (is_fc) {
10493                 /* FCP-2 ANSI INCITS.350:2003 */
10494                 scsi_ulto2b(0x0917, inq_ptr->version3);
10495         } else {
10496                 /* SPI-4 ANSI INCITS.362:200x */
10497                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10498         }
10499
10500         if (lun == NULL) {
10501                 /* SBC-2 (no version claimed) XXX should we claim a version? */
10502                 scsi_ulto2b(0x0320, inq_ptr->version4);
10503         } else {
10504                 switch (lun->be_lun->lun_type) {
10505                 case T_DIRECT:
10506                         /*
10507                          * SBC-2 (no version claimed) XXX should we claim a
10508                          * version?
10509                          */
10510                         scsi_ulto2b(0x0320, inq_ptr->version4);
10511                         break;
10512                 case T_PROCESSOR:
10513                 default:
10514                         break;
10515                 }
10516         }
10517
10518         ctsio->scsi_status = SCSI_STATUS_OK;
10519         if (ctsio->kern_data_len > 0) {
10520                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10521                 ctsio->be_move_done = ctl_config_move_done;
10522                 ctl_datamove((union ctl_io *)ctsio);
10523         } else {
10524                 ctsio->io_hdr.status = CTL_SUCCESS;
10525                 ctl_done((union ctl_io *)ctsio);
10526         }
10527
10528         return (CTL_RETVAL_COMPLETE);
10529 }
10530
10531 int
10532 ctl_inquiry(struct ctl_scsiio *ctsio)
10533 {
10534         struct scsi_inquiry *cdb;
10535         int retval;
10536
10537         cdb = (struct scsi_inquiry *)ctsio->cdb;
10538
10539         retval = 0;
10540
10541         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10542
10543         /*
10544          * Right now, we don't support the CmdDt inquiry information.
10545          * This would be nice to support in the future.  When we do
10546          * support it, we should change this test so that it checks to make
10547          * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10548          */
10549 #ifdef notyet
10550         if (((cdb->byte2 & SI_EVPD)
10551          && (cdb->byte2 & SI_CMDDT)))
10552 #endif
10553         if (cdb->byte2 & SI_CMDDT) {
10554                 /*
10555                  * Point to the SI_CMDDT bit.  We might change this
10556                  * when we support SI_CMDDT, but since both bits would be
10557                  * "wrong", this should probably just stay as-is then.
10558                  */
10559                 ctl_set_invalid_field(ctsio,
10560                                       /*sks_valid*/ 1,
10561                                       /*command*/ 1,
10562                                       /*field*/ 1,
10563                                       /*bit_valid*/ 1,
10564                                       /*bit*/ 1);
10565                 ctl_done((union ctl_io *)ctsio);
10566                 return (CTL_RETVAL_COMPLETE);
10567         }
10568         if (cdb->byte2 & SI_EVPD)
10569                 retval = ctl_inquiry_evpd(ctsio);
10570 #ifdef notyet
10571         else if (cdb->byte2 & SI_CMDDT)
10572                 retval = ctl_inquiry_cmddt(ctsio);
10573 #endif
10574         else
10575                 retval = ctl_inquiry_std(ctsio);
10576
10577         return (retval);
10578 }
10579
10580 /*
10581  * For known CDB types, parse the LBA and length.
10582  */
10583 static int
10584 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10585 {
10586         if (io->io_hdr.io_type != CTL_IO_SCSI)
10587                 return (1);
10588
10589         switch (io->scsiio.cdb[0]) {
10590         case COMPARE_AND_WRITE: {
10591                 struct scsi_compare_and_write *cdb;
10592
10593                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10594
10595                 *lba = scsi_8btou64(cdb->addr);
10596                 *len = cdb->length;
10597                 break;
10598         }
10599         case READ_6:
10600         case WRITE_6: {
10601                 struct scsi_rw_6 *cdb;
10602
10603                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10604
10605                 *lba = scsi_3btoul(cdb->addr);
10606                 /* only 5 bits are valid in the most significant address byte */
10607                 *lba &= 0x1fffff;
10608                 *len = cdb->length;
10609                 break;
10610         }
10611         case READ_10:
10612         case WRITE_10: {
10613                 struct scsi_rw_10 *cdb;
10614
10615                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10616
10617                 *lba = scsi_4btoul(cdb->addr);
10618                 *len = scsi_2btoul(cdb->length);
10619                 break;
10620         }
10621         case WRITE_VERIFY_10: {
10622                 struct scsi_write_verify_10 *cdb;
10623
10624                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10625
10626                 *lba = scsi_4btoul(cdb->addr);
10627                 *len = scsi_2btoul(cdb->length);
10628                 break;
10629         }
10630         case READ_12:
10631         case WRITE_12: {
10632                 struct scsi_rw_12 *cdb;
10633
10634                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10635
10636                 *lba = scsi_4btoul(cdb->addr);
10637                 *len = scsi_4btoul(cdb->length);
10638                 break;
10639         }
10640         case WRITE_VERIFY_12: {
10641                 struct scsi_write_verify_12 *cdb;
10642
10643                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10644
10645                 *lba = scsi_4btoul(cdb->addr);
10646                 *len = scsi_4btoul(cdb->length);
10647                 break;
10648         }
10649         case READ_16:
10650         case WRITE_16: {
10651                 struct scsi_rw_16 *cdb;
10652
10653                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10654
10655                 *lba = scsi_8btou64(cdb->addr);
10656                 *len = scsi_4btoul(cdb->length);
10657                 break;
10658         }
10659         case WRITE_VERIFY_16: {
10660                 struct scsi_write_verify_16 *cdb;
10661
10662                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10663
10664                 
10665                 *lba = scsi_8btou64(cdb->addr);
10666                 *len = scsi_4btoul(cdb->length);
10667                 break;
10668         }
10669         case WRITE_SAME_10: {
10670                 struct scsi_write_same_10 *cdb;
10671
10672                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10673
10674                 *lba = scsi_4btoul(cdb->addr);
10675                 *len = scsi_2btoul(cdb->length);
10676                 break;
10677         }
10678         case WRITE_SAME_16: {
10679                 struct scsi_write_same_16 *cdb;
10680
10681                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10682
10683                 *lba = scsi_8btou64(cdb->addr);
10684                 *len = scsi_4btoul(cdb->length);
10685                 break;
10686         }
10687         case VERIFY_10: {
10688                 struct scsi_verify_10 *cdb;
10689
10690                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10691
10692                 *lba = scsi_4btoul(cdb->addr);
10693                 *len = scsi_2btoul(cdb->length);
10694                 break;
10695         }
10696         case VERIFY_12: {
10697                 struct scsi_verify_12 *cdb;
10698
10699                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10700
10701                 *lba = scsi_4btoul(cdb->addr);
10702                 *len = scsi_4btoul(cdb->length);
10703                 break;
10704         }
10705         case VERIFY_16: {
10706                 struct scsi_verify_16 *cdb;
10707
10708                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10709
10710                 *lba = scsi_8btou64(cdb->addr);
10711                 *len = scsi_4btoul(cdb->length);
10712                 break;
10713         }
10714         default:
10715                 return (1);
10716                 break; /* NOTREACHED */
10717         }
10718
10719         return (0);
10720 }
10721
10722 static ctl_action
10723 ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10724 {
10725         uint64_t endlba1, endlba2;
10726
10727         endlba1 = lba1 + len1 - 1;
10728         endlba2 = lba2 + len2 - 1;
10729
10730         if ((endlba1 < lba2)
10731          || (endlba2 < lba1))
10732                 return (CTL_ACTION_PASS);
10733         else
10734                 return (CTL_ACTION_BLOCK);
10735 }
10736
10737 static ctl_action
10738 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10739 {
10740         uint64_t lba1, lba2;
10741         uint32_t len1, len2;
10742         int retval;
10743
10744         retval = ctl_get_lba_len(io1, &lba1, &len1);
10745         if (retval != 0)
10746                 return (CTL_ACTION_ERROR);
10747
10748         retval = ctl_get_lba_len(io2, &lba2, &len2);
10749         if (retval != 0)
10750                 return (CTL_ACTION_ERROR);
10751
10752         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10753 }
10754
10755 static ctl_action
10756 ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10757 {
10758         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10759         ctl_serialize_action *serialize_row;
10760
10761         /*
10762          * The initiator attempted multiple untagged commands at the same
10763          * time.  Can't do that.
10764          */
10765         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10766          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10767          && ((pending_io->io_hdr.nexus.targ_port ==
10768               ooa_io->io_hdr.nexus.targ_port)
10769           && (pending_io->io_hdr.nexus.initid.id ==
10770               ooa_io->io_hdr.nexus.initid.id))
10771          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10772                 return (CTL_ACTION_OVERLAP);
10773
10774         /*
10775          * The initiator attempted to send multiple tagged commands with
10776          * the same ID.  (It's fine if different initiators have the same
10777          * tag ID.)
10778          *
10779          * Even if all of those conditions are true, we don't kill the I/O
10780          * if the command ahead of us has been aborted.  We won't end up
10781          * sending it to the FETD, and it's perfectly legal to resend a
10782          * command with the same tag number as long as the previous
10783          * instance of this tag number has been aborted somehow.
10784          */
10785         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10786          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10787          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10788          && ((pending_io->io_hdr.nexus.targ_port ==
10789               ooa_io->io_hdr.nexus.targ_port)
10790           && (pending_io->io_hdr.nexus.initid.id ==
10791               ooa_io->io_hdr.nexus.initid.id))
10792          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10793                 return (CTL_ACTION_OVERLAP_TAG);
10794
10795         /*
10796          * If we get a head of queue tag, SAM-3 says that we should
10797          * immediately execute it.
10798          *
10799          * What happens if this command would normally block for some other
10800          * reason?  e.g. a request sense with a head of queue tag
10801          * immediately after a write.  Normally that would block, but this
10802          * will result in its getting executed immediately...
10803          *
10804          * We currently return "pass" instead of "skip", so we'll end up
10805          * going through the rest of the queue to check for overlapped tags.
10806          *
10807          * XXX KDM check for other types of blockage first??
10808          */
10809         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10810                 return (CTL_ACTION_PASS);
10811
10812         /*
10813          * Ordered tags have to block until all items ahead of them
10814          * have completed.  If we get called with an ordered tag, we always
10815          * block, if something else is ahead of us in the queue.
10816          */
10817         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10818                 return (CTL_ACTION_BLOCK);
10819
10820         /*
10821          * Simple tags get blocked until all head of queue and ordered tags
10822          * ahead of them have completed.  I'm lumping untagged commands in
10823          * with simple tags here.  XXX KDM is that the right thing to do?
10824          */
10825         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10826           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10827          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10828           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10829                 return (CTL_ACTION_BLOCK);
10830
10831         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10832         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10833
10834         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10835
10836         switch (serialize_row[pending_entry->seridx]) {
10837         case CTL_SER_BLOCK:
10838                 return (CTL_ACTION_BLOCK);
10839                 break; /* NOTREACHED */
10840         case CTL_SER_EXTENT:
10841                 return (ctl_extent_check(pending_io, ooa_io));
10842                 break; /* NOTREACHED */
10843         case CTL_SER_PASS:
10844                 return (CTL_ACTION_PASS);
10845                 break; /* NOTREACHED */
10846         case CTL_SER_SKIP:
10847                 return (CTL_ACTION_SKIP);
10848                 break;
10849         default:
10850                 panic("invalid serialization value %d",
10851                       serialize_row[pending_entry->seridx]);
10852                 break; /* NOTREACHED */
10853         }
10854
10855         return (CTL_ACTION_ERROR);
10856 }
10857
10858 /*
10859  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10860  * Assumptions:
10861  * - pending_io is generally either incoming, or on the blocked queue
10862  * - starting I/O is the I/O we want to start the check with.
10863  */
10864 static ctl_action
10865 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10866               union ctl_io *starting_io)
10867 {
10868         union ctl_io *ooa_io;
10869         ctl_action action;
10870
10871         mtx_assert(&lun->lun_lock, MA_OWNED);
10872
10873         /*
10874          * Run back along the OOA queue, starting with the current
10875          * blocked I/O and going through every I/O before it on the
10876          * queue.  If starting_io is NULL, we'll just end up returning
10877          * CTL_ACTION_PASS.
10878          */
10879         for (ooa_io = starting_io; ooa_io != NULL;
10880              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10881              ooa_links)){
10882
10883                 /*
10884                  * This routine just checks to see whether
10885                  * cur_blocked is blocked by ooa_io, which is ahead
10886                  * of it in the queue.  It doesn't queue/dequeue
10887                  * cur_blocked.
10888                  */
10889                 action = ctl_check_for_blockage(pending_io, ooa_io);
10890                 switch (action) {
10891                 case CTL_ACTION_BLOCK:
10892                 case CTL_ACTION_OVERLAP:
10893                 case CTL_ACTION_OVERLAP_TAG:
10894                 case CTL_ACTION_SKIP:
10895                 case CTL_ACTION_ERROR:
10896                         return (action);
10897                         break; /* NOTREACHED */
10898                 case CTL_ACTION_PASS:
10899                         break;
10900                 default:
10901                         panic("invalid action %d", action);
10902                         break;  /* NOTREACHED */
10903                 }
10904         }
10905
10906         return (CTL_ACTION_PASS);
10907 }
10908
10909 /*
10910  * Assumptions:
10911  * - An I/O has just completed, and has been removed from the per-LUN OOA
10912  *   queue, so some items on the blocked queue may now be unblocked.
10913  */
10914 static int
10915 ctl_check_blocked(struct ctl_lun *lun)
10916 {
10917         union ctl_io *cur_blocked, *next_blocked;
10918
10919         mtx_assert(&lun->lun_lock, MA_OWNED);
10920
10921         /*
10922          * Run forward from the head of the blocked queue, checking each
10923          * entry against the I/Os prior to it on the OOA queue to see if
10924          * there is still any blockage.
10925          *
10926          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10927          * with our removing a variable on it while it is traversing the
10928          * list.
10929          */
10930         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10931              cur_blocked != NULL; cur_blocked = next_blocked) {
10932                 union ctl_io *prev_ooa;
10933                 ctl_action action;
10934
10935                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10936                                                           blocked_links);
10937
10938                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10939                                                       ctl_ooaq, ooa_links);
10940
10941                 /*
10942                  * If cur_blocked happens to be the first item in the OOA
10943                  * queue now, prev_ooa will be NULL, and the action
10944                  * returned will just be CTL_ACTION_PASS.
10945                  */
10946                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10947
10948                 switch (action) {
10949                 case CTL_ACTION_BLOCK:
10950                         /* Nothing to do here, still blocked */
10951                         break;
10952                 case CTL_ACTION_OVERLAP:
10953                 case CTL_ACTION_OVERLAP_TAG:
10954                         /*
10955                          * This shouldn't happen!  In theory we've already
10956                          * checked this command for overlap...
10957                          */
10958                         break;
10959                 case CTL_ACTION_PASS:
10960                 case CTL_ACTION_SKIP: {
10961                         struct ctl_softc *softc;
10962                         const struct ctl_cmd_entry *entry;
10963                         uint32_t initidx;
10964                         int isc_retval;
10965
10966                         /*
10967                          * The skip case shouldn't happen, this transaction
10968                          * should have never made it onto the blocked queue.
10969                          */
10970                         /*
10971                          * This I/O is no longer blocked, we can remove it
10972                          * from the blocked queue.  Since this is a TAILQ
10973                          * (doubly linked list), we can do O(1) removals
10974                          * from any place on the list.
10975                          */
10976                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10977                                      blocked_links);
10978                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10979
10980                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10981                                 /*
10982                                  * Need to send IO back to original side to
10983                                  * run
10984                                  */
10985                                 union ctl_ha_msg msg_info;
10986
10987                                 msg_info.hdr.original_sc =
10988                                         cur_blocked->io_hdr.original_sc;
10989                                 msg_info.hdr.serializing_sc = cur_blocked;
10990                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10991                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10992                                      &msg_info, sizeof(msg_info), 0)) >
10993                                      CTL_HA_STATUS_SUCCESS) {
10994                                         printf("CTL:Check Blocked error from "
10995                                                "ctl_ha_msg_send %d\n",
10996                                                isc_retval);
10997                                 }
10998                                 break;
10999                         }
11000                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
11001                         softc = control_softc;
11002
11003                         initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11004
11005                         /*
11006                          * Check this I/O for LUN state changes that may
11007                          * have happened while this command was blocked.
11008                          * The LUN state may have been changed by a command
11009                          * ahead of us in the queue, so we need to re-check
11010                          * for any states that can be caused by SCSI
11011                          * commands.
11012                          */
11013                         if (ctl_scsiio_lun_check(softc, lun, entry,
11014                                                  &cur_blocked->scsiio) == 0) {
11015                                 cur_blocked->io_hdr.flags |=
11016                                                       CTL_FLAG_IS_WAS_ON_RTR;
11017                                 ctl_enqueue_rtr(cur_blocked);
11018                         } else
11019                                 ctl_done(cur_blocked);
11020                         break;
11021                 }
11022                 default:
11023                         /*
11024                          * This probably shouldn't happen -- we shouldn't
11025                          * get CTL_ACTION_ERROR, or anything else.
11026                          */
11027                         break;
11028                 }
11029         }
11030
11031         return (CTL_RETVAL_COMPLETE);
11032 }
11033
11034 /*
11035  * This routine (with one exception) checks LUN flags that can be set by
11036  * commands ahead of us in the OOA queue.  These flags have to be checked
11037  * when a command initially comes in, and when we pull a command off the
11038  * blocked queue and are preparing to execute it.  The reason we have to
11039  * check these flags for commands on the blocked queue is that the LUN
11040  * state may have been changed by a command ahead of us while we're on the
11041  * blocked queue.
11042  *
11043  * Ordering is somewhat important with these checks, so please pay
11044  * careful attention to the placement of any new checks.
11045  */
11046 static int
11047 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11048     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11049 {
11050         int retval;
11051
11052         retval = 0;
11053
11054         mtx_assert(&lun->lun_lock, MA_OWNED);
11055
11056         /*
11057          * If this shelf is a secondary shelf controller, we have to reject
11058          * any media access commands.
11059          */
11060 #if 0
11061         /* No longer needed for HA */
11062         if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11063          && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11064                 ctl_set_lun_standby(ctsio);
11065                 retval = 1;
11066                 goto bailout;
11067         }
11068 #endif
11069
11070         /*
11071          * Check for a reservation conflict.  If this command isn't allowed
11072          * even on reserved LUNs, and if this initiator isn't the one who
11073          * reserved us, reject the command with a reservation conflict.
11074          */
11075         if ((lun->flags & CTL_LUN_RESERVED)
11076          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11077                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11078                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11079                  || (ctsio->io_hdr.nexus.targ_target.id !=
11080                      lun->rsv_nexus.targ_target.id)) {
11081                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11082                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11083                         retval = 1;
11084                         goto bailout;
11085                 }
11086         }
11087
11088         if ( (lun->flags & CTL_LUN_PR_RESERVED)
11089          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11090                 uint32_t residx;
11091
11092                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11093                 /*
11094                  * if we aren't registered or it's a res holder type
11095                  * reservation and this isn't the res holder then set a
11096                  * conflict.
11097                  * NOTE: Commands which might be allowed on write exclusive
11098                  * type reservations are checked in the particular command
11099                  * for a conflict. Read and SSU are the only ones.
11100                  */
11101                 if (!lun->per_res[residx].registered
11102                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11103                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11104                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11105                         retval = 1;
11106                         goto bailout;
11107                 }
11108
11109         }
11110
11111         if ((lun->flags & CTL_LUN_OFFLINE)
11112          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11113                 ctl_set_lun_not_ready(ctsio);
11114                 retval = 1;
11115                 goto bailout;
11116         }
11117
11118         /*
11119          * If the LUN is stopped, see if this particular command is allowed
11120          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11121          */
11122         if ((lun->flags & CTL_LUN_STOPPED)
11123          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11124                 /* "Logical unit not ready, initializing cmd. required" */
11125                 ctl_set_lun_stopped(ctsio);
11126                 retval = 1;
11127                 goto bailout;
11128         }
11129
11130         if ((lun->flags & CTL_LUN_INOPERABLE)
11131          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11132                 /* "Medium format corrupted" */
11133                 ctl_set_medium_format_corrupted(ctsio);
11134                 retval = 1;
11135                 goto bailout;
11136         }
11137
11138 bailout:
11139         return (retval);
11140
11141 }
11142
11143 static void
11144 ctl_failover_io(union ctl_io *io, int have_lock)
11145 {
11146         ctl_set_busy(&io->scsiio);
11147         ctl_done(io);
11148 }
11149
11150 static void
11151 ctl_failover(void)
11152 {
11153         struct ctl_lun *lun;
11154         struct ctl_softc *ctl_softc;
11155         union ctl_io *next_io, *pending_io;
11156         union ctl_io *io;
11157         int lun_idx;
11158         int i;
11159
11160         ctl_softc = control_softc;
11161
11162         mtx_lock(&ctl_softc->ctl_lock);
11163         /*
11164          * Remove any cmds from the other SC from the rtr queue.  These
11165          * will obviously only be for LUNs for which we're the primary.
11166          * We can't send status or get/send data for these commands.
11167          * Since they haven't been executed yet, we can just remove them.
11168          * We'll either abort them or delete them below, depending on
11169          * which HA mode we're in.
11170          */
11171 #ifdef notyet
11172         mtx_lock(&ctl_softc->queue_lock);
11173         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11174              io != NULL; io = next_io) {
11175                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11176                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11177                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11178                                       ctl_io_hdr, links);
11179         }
11180         mtx_unlock(&ctl_softc->queue_lock);
11181 #endif
11182
11183         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11184                 lun = ctl_softc->ctl_luns[lun_idx];
11185                 if (lun==NULL)
11186                         continue;
11187
11188                 /*
11189                  * Processor LUNs are primary on both sides.
11190                  * XXX will this always be true?
11191                  */
11192                 if (lun->be_lun->lun_type == T_PROCESSOR)
11193                         continue;
11194
11195                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11196                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11197                         printf("FAILOVER: primary lun %d\n", lun_idx);
11198                         /*
11199                          * Remove all commands from the other SC. First from the
11200                          * blocked queue then from the ooa queue. Once we have
11201                          * removed them. Call ctl_check_blocked to see if there
11202                          * is anything that can run.
11203                          */
11204                         for (io = (union ctl_io *)TAILQ_FIRST(
11205                              &lun->blocked_queue); io != NULL; io = next_io) {
11206
11207                                 next_io = (union ctl_io *)TAILQ_NEXT(
11208                                     &io->io_hdr, blocked_links);
11209
11210                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11211                                         TAILQ_REMOVE(&lun->blocked_queue,
11212                                                      &io->io_hdr,blocked_links);
11213                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11214                                         TAILQ_REMOVE(&lun->ooa_queue,
11215                                                      &io->io_hdr, ooa_links);
11216
11217                                         ctl_free_io(io);
11218                                 }
11219                         }
11220
11221                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11222                              io != NULL; io = next_io) {
11223
11224                                 next_io = (union ctl_io *)TAILQ_NEXT(
11225                                     &io->io_hdr, ooa_links);
11226
11227                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11228
11229                                         TAILQ_REMOVE(&lun->ooa_queue,
11230                                                 &io->io_hdr,
11231                                                 ooa_links);
11232
11233                                         ctl_free_io(io);
11234                                 }
11235                         }
11236                         ctl_check_blocked(lun);
11237                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11238                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11239
11240                         printf("FAILOVER: primary lun %d\n", lun_idx);
11241                         /*
11242                          * Abort all commands from the other SC.  We can't
11243                          * send status back for them now.  These should get
11244                          * cleaned up when they are completed or come out
11245                          * for a datamove operation.
11246                          */
11247                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11248                              io != NULL; io = next_io) {
11249                                 next_io = (union ctl_io *)TAILQ_NEXT(
11250                                         &io->io_hdr, ooa_links);
11251
11252                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11253                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11254                         }
11255                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11256                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11257
11258                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11259
11260                         lun->flags |= CTL_LUN_PRIMARY_SC;
11261
11262                         /*
11263                          * We send all I/O that was sent to this controller
11264                          * and redirected to the other side back with
11265                          * busy status, and have the initiator retry it.
11266                          * Figuring out how much data has been transferred,
11267                          * etc. and picking up where we left off would be 
11268                          * very tricky.
11269                          *
11270                          * XXX KDM need to remove I/O from the blocked
11271                          * queue as well!
11272                          */
11273                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11274                              &lun->ooa_queue); pending_io != NULL;
11275                              pending_io = next_io) {
11276
11277                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11278                                         &pending_io->io_hdr, ooa_links);
11279
11280                                 pending_io->io_hdr.flags &=
11281                                         ~CTL_FLAG_SENT_2OTHER_SC;
11282
11283                                 if (pending_io->io_hdr.flags &
11284                                     CTL_FLAG_IO_ACTIVE) {
11285                                         pending_io->io_hdr.flags |=
11286                                                 CTL_FLAG_FAILOVER;
11287                                 } else {
11288                                         ctl_set_busy(&pending_io->scsiio);
11289                                         ctl_done(pending_io);
11290                                 }
11291                         }
11292
11293                         /*
11294                          * Build Unit Attention
11295                          */
11296                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11297                                 lun->pending_sense[i].ua_pending |=
11298                                                      CTL_UA_ASYM_ACC_CHANGE;
11299                         }
11300                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11301                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11302                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11303                         /*
11304                          * if the first io on the OOA is not on the RtR queue
11305                          * add it.
11306                          */
11307                         lun->flags |= CTL_LUN_PRIMARY_SC;
11308
11309                         pending_io = (union ctl_io *)TAILQ_FIRST(
11310                             &lun->ooa_queue);
11311                         if (pending_io==NULL) {
11312                                 printf("Nothing on OOA queue\n");
11313                                 continue;
11314                         }
11315
11316                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11317                         if ((pending_io->io_hdr.flags &
11318                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11319                                 pending_io->io_hdr.flags |=
11320                                     CTL_FLAG_IS_WAS_ON_RTR;
11321                                 ctl_enqueue_rtr(pending_io);
11322                         }
11323 #if 0
11324                         else
11325                         {
11326                                 printf("Tag 0x%04x is running\n",
11327                                       pending_io->scsiio.tag_num);
11328                         }
11329 #endif
11330
11331                         next_io = (union ctl_io *)TAILQ_NEXT(
11332                             &pending_io->io_hdr, ooa_links);
11333                         for (pending_io=next_io; pending_io != NULL;
11334                              pending_io = next_io) {
11335                                 pending_io->io_hdr.flags &=
11336                                     ~CTL_FLAG_SENT_2OTHER_SC;
11337                                 next_io = (union ctl_io *)TAILQ_NEXT(
11338                                         &pending_io->io_hdr, ooa_links);
11339                                 if (pending_io->io_hdr.flags &
11340                                     CTL_FLAG_IS_WAS_ON_RTR) {
11341 #if 0
11342                                         printf("Tag 0x%04x is running\n",
11343                                                 pending_io->scsiio.tag_num);
11344 #endif
11345                                         continue;
11346                                 }
11347
11348                                 switch (ctl_check_ooa(lun, pending_io,
11349                                     (union ctl_io *)TAILQ_PREV(
11350                                     &pending_io->io_hdr, ctl_ooaq,
11351                                     ooa_links))) {
11352
11353                                 case CTL_ACTION_BLOCK:
11354                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11355                                                           &pending_io->io_hdr,
11356                                                           blocked_links);
11357                                         pending_io->io_hdr.flags |=
11358                                             CTL_FLAG_BLOCKED;
11359                                         break;
11360                                 case CTL_ACTION_PASS:
11361                                 case CTL_ACTION_SKIP:
11362                                         pending_io->io_hdr.flags |=
11363                                             CTL_FLAG_IS_WAS_ON_RTR;
11364                                         ctl_enqueue_rtr(pending_io);
11365                                         break;
11366                                 case CTL_ACTION_OVERLAP:
11367                                         ctl_set_overlapped_cmd(
11368                                             (struct ctl_scsiio *)pending_io);
11369                                         ctl_done(pending_io);
11370                                         break;
11371                                 case CTL_ACTION_OVERLAP_TAG:
11372                                         ctl_set_overlapped_tag(
11373                                             (struct ctl_scsiio *)pending_io,
11374                                             pending_io->scsiio.tag_num & 0xff);
11375                                         ctl_done(pending_io);
11376                                         break;
11377                                 case CTL_ACTION_ERROR:
11378                                 default:
11379                                         ctl_set_internal_failure(
11380                                                 (struct ctl_scsiio *)pending_io,
11381                                                 0,  // sks_valid
11382                                                 0); //retry count
11383                                         ctl_done(pending_io);
11384                                         break;
11385                                 }
11386                         }
11387
11388                         /*
11389                          * Build Unit Attention
11390                          */
11391                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11392                                 lun->pending_sense[i].ua_pending |=
11393                                                      CTL_UA_ASYM_ACC_CHANGE;
11394                         }
11395                 } else {
11396                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11397                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11398                 }
11399         }
11400         ctl_pause_rtr = 0;
11401         mtx_unlock(&ctl_softc->ctl_lock);
11402 }
11403
11404 static int
11405 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11406 {
11407         struct ctl_lun *lun;
11408         const struct ctl_cmd_entry *entry;
11409         uint32_t initidx, targ_lun;
11410         int retval;
11411
11412         retval = 0;
11413
11414         lun = NULL;
11415
11416         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11417         if ((targ_lun < CTL_MAX_LUNS)
11418          && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11419                 lun = ctl_softc->ctl_luns[targ_lun];
11420                 /*
11421                  * If the LUN is invalid, pretend that it doesn't exist.
11422                  * It will go away as soon as all pending I/O has been
11423                  * completed.
11424                  */
11425                 if (lun->flags & CTL_LUN_DISABLED) {
11426                         lun = NULL;
11427                 } else {
11428                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11429                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11430                                 lun->be_lun;
11431                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11432                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11433                         }
11434
11435                         /*
11436                          * Every I/O goes into the OOA queue for a
11437                          * particular LUN, and stays there until completion.
11438                          */
11439                         mtx_lock(&lun->lun_lock);
11440                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11441                             ooa_links);
11442                 }
11443         } else {
11444                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11445                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11446         }
11447
11448         /* Get command entry and return error if it is unsuppotyed. */
11449         entry = ctl_validate_command(ctsio);
11450         if (entry == NULL) {
11451                 if (lun)
11452                         mtx_unlock(&lun->lun_lock);
11453                 return (retval);
11454         }
11455
11456         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11457         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11458
11459         /*
11460          * Check to see whether we can send this command to LUNs that don't
11461          * exist.  This should pretty much only be the case for inquiry
11462          * and request sense.  Further checks, below, really require having
11463          * a LUN, so we can't really check the command anymore.  Just put
11464          * it on the rtr queue.
11465          */
11466         if (lun == NULL) {
11467                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11468                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11469                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11470                         return (retval);
11471                 }
11472
11473                 ctl_set_unsupported_lun(ctsio);
11474                 ctl_done((union ctl_io *)ctsio);
11475                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11476                 return (retval);
11477         } else {
11478                 /*
11479                  * Make sure we support this particular command on this LUN.
11480                  * e.g., we don't support writes to the control LUN.
11481                  */
11482                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11483                         mtx_unlock(&lun->lun_lock);
11484                         ctl_set_invalid_opcode(ctsio);
11485                         ctl_done((union ctl_io *)ctsio);
11486                         return (retval);
11487                 }
11488         }
11489
11490         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11491
11492         /*
11493          * If we've got a request sense, it'll clear the contingent
11494          * allegiance condition.  Otherwise, if we have a CA condition for
11495          * this initiator, clear it, because it sent down a command other
11496          * than request sense.
11497          */
11498         if ((ctsio->cdb[0] != REQUEST_SENSE)
11499          && (ctl_is_set(lun->have_ca, initidx)))
11500                 ctl_clear_mask(lun->have_ca, initidx);
11501
11502         /*
11503          * If the command has this flag set, it handles its own unit
11504          * attention reporting, we shouldn't do anything.  Otherwise we
11505          * check for any pending unit attentions, and send them back to the
11506          * initiator.  We only do this when a command initially comes in,
11507          * not when we pull it off the blocked queue.
11508          *
11509          * According to SAM-3, section 5.3.2, the order that things get
11510          * presented back to the host is basically unit attentions caused
11511          * by some sort of reset event, busy status, reservation conflicts
11512          * or task set full, and finally any other status.
11513          *
11514          * One issue here is that some of the unit attentions we report
11515          * don't fall into the "reset" category (e.g. "reported luns data
11516          * has changed").  So reporting it here, before the reservation
11517          * check, may be technically wrong.  I guess the only thing to do
11518          * would be to check for and report the reset events here, and then
11519          * check for the other unit attention types after we check for a
11520          * reservation conflict.
11521          *
11522          * XXX KDM need to fix this
11523          */
11524         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11525                 ctl_ua_type ua_type;
11526
11527                 ua_type = lun->pending_sense[initidx].ua_pending;
11528                 if (ua_type != CTL_UA_NONE) {
11529                         scsi_sense_data_type sense_format;
11530
11531                         if (lun != NULL)
11532                                 sense_format = (lun->flags &
11533                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11534                                     SSD_TYPE_FIXED;
11535                         else
11536                                 sense_format = SSD_TYPE_FIXED;
11537
11538                         ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11539                                                sense_format);
11540                         if (ua_type != CTL_UA_NONE) {
11541                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11542                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11543                                                        CTL_AUTOSENSE;
11544                                 ctsio->sense_len = SSD_FULL_SIZE;
11545                                 lun->pending_sense[initidx].ua_pending &=
11546                                         ~ua_type;
11547                                 mtx_unlock(&lun->lun_lock);
11548                                 ctl_done((union ctl_io *)ctsio);
11549                                 return (retval);
11550                         }
11551                 }
11552         }
11553
11554
11555         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11556                 mtx_unlock(&lun->lun_lock);
11557                 ctl_done((union ctl_io *)ctsio);
11558                 return (retval);
11559         }
11560
11561         /*
11562          * XXX CHD this is where we want to send IO to other side if
11563          * this LUN is secondary on this SC. We will need to make a copy
11564          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11565          * the copy we send as FROM_OTHER.
11566          * We also need to stuff the address of the original IO so we can
11567          * find it easily. Something similar will need be done on the other
11568          * side so when we are done we can find the copy.
11569          */
11570         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11571                 union ctl_ha_msg msg_info;
11572                 int isc_retval;
11573
11574                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11575
11576                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11577                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11578 #if 0
11579                 printf("1. ctsio %p\n", ctsio);
11580 #endif
11581                 msg_info.hdr.serializing_sc = NULL;
11582                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11583                 msg_info.scsi.tag_num = ctsio->tag_num;
11584                 msg_info.scsi.tag_type = ctsio->tag_type;
11585                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11586
11587                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11588
11589                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11590                     (void *)&msg_info, sizeof(msg_info), 0)) >
11591                     CTL_HA_STATUS_SUCCESS) {
11592                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11593                                isc_retval);
11594                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11595                 } else {
11596 #if 0
11597                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11598 #endif
11599                 }
11600
11601                 /*
11602                  * XXX KDM this I/O is off the incoming queue, but hasn't
11603                  * been inserted on any other queue.  We may need to come
11604                  * up with a holding queue while we wait for serialization
11605                  * so that we have an idea of what we're waiting for from
11606                  * the other side.
11607                  */
11608                 mtx_unlock(&lun->lun_lock);
11609                 return (retval);
11610         }
11611
11612         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11613                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11614                               ctl_ooaq, ooa_links))) {
11615         case CTL_ACTION_BLOCK:
11616                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11617                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11618                                   blocked_links);
11619                 mtx_unlock(&lun->lun_lock);
11620                 return (retval);
11621         case CTL_ACTION_PASS:
11622         case CTL_ACTION_SKIP:
11623                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11624                 mtx_unlock(&lun->lun_lock);
11625                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11626                 break;
11627         case CTL_ACTION_OVERLAP:
11628                 mtx_unlock(&lun->lun_lock);
11629                 ctl_set_overlapped_cmd(ctsio);
11630                 ctl_done((union ctl_io *)ctsio);
11631                 break;
11632         case CTL_ACTION_OVERLAP_TAG:
11633                 mtx_unlock(&lun->lun_lock);
11634                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11635                 ctl_done((union ctl_io *)ctsio);
11636                 break;
11637         case CTL_ACTION_ERROR:
11638         default:
11639                 mtx_unlock(&lun->lun_lock);
11640                 ctl_set_internal_failure(ctsio,
11641                                          /*sks_valid*/ 0,
11642                                          /*retry_count*/ 0);
11643                 ctl_done((union ctl_io *)ctsio);
11644                 break;
11645         }
11646         return (retval);
11647 }
11648
11649 const struct ctl_cmd_entry *
11650 ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11651 {
11652         const struct ctl_cmd_entry *entry;
11653         int service_action;
11654
11655         entry = &ctl_cmd_table[ctsio->cdb[0]];
11656         if (entry->flags & CTL_CMD_FLAG_SA5) {
11657                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11658                 entry = &((const struct ctl_cmd_entry *)
11659                     entry->execute)[service_action];
11660         }
11661         return (entry);
11662 }
11663
11664 const struct ctl_cmd_entry *
11665 ctl_validate_command(struct ctl_scsiio *ctsio)
11666 {
11667         const struct ctl_cmd_entry *entry;
11668         int i;
11669         uint8_t diff;
11670
11671         entry = ctl_get_cmd_entry(ctsio);
11672         if (entry->execute == NULL) {
11673                 ctl_set_invalid_opcode(ctsio);
11674                 ctl_done((union ctl_io *)ctsio);
11675                 return (NULL);
11676         }
11677         KASSERT(entry->length > 0,
11678             ("Not defined length for command 0x%02x/0x%02x",
11679              ctsio->cdb[0], ctsio->cdb[1]));
11680         for (i = 1; i < entry->length; i++) {
11681                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11682                 if (diff == 0)
11683                         continue;
11684                 ctl_set_invalid_field(ctsio,
11685                                       /*sks_valid*/ 1,
11686                                       /*command*/ 1,
11687                                       /*field*/ i,
11688                                       /*bit_valid*/ 1,
11689                                       /*bit*/ fls(diff) - 1);
11690                 ctl_done((union ctl_io *)ctsio);
11691                 return (NULL);
11692         }
11693         return (entry);
11694 }
11695
11696 static int
11697 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11698 {
11699
11700         switch (lun_type) {
11701         case T_PROCESSOR:
11702                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11703                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11704                         return (0);
11705                 break;
11706         case T_DIRECT:
11707                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11708                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11709                         return (0);
11710                 break;
11711         default:
11712                 return (0);
11713         }
11714         return (1);
11715 }
11716
11717 static int
11718 ctl_scsiio(struct ctl_scsiio *ctsio)
11719 {
11720         int retval;
11721         const struct ctl_cmd_entry *entry;
11722
11723         retval = CTL_RETVAL_COMPLETE;
11724
11725         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11726
11727         entry = ctl_get_cmd_entry(ctsio);
11728
11729         /*
11730          * If this I/O has been aborted, just send it straight to
11731          * ctl_done() without executing it.
11732          */
11733         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11734                 ctl_done((union ctl_io *)ctsio);
11735                 goto bailout;
11736         }
11737
11738         /*
11739          * All the checks should have been handled by ctl_scsiio_precheck().
11740          * We should be clear now to just execute the I/O.
11741          */
11742         retval = entry->execute(ctsio);
11743
11744 bailout:
11745         return (retval);
11746 }
11747
11748 /*
11749  * Since we only implement one target right now, a bus reset simply resets
11750  * our single target.
11751  */
11752 static int
11753 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11754 {
11755         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11756 }
11757
11758 static int
11759 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11760                  ctl_ua_type ua_type)
11761 {
11762         struct ctl_lun *lun;
11763         int retval;
11764
11765         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11766                 union ctl_ha_msg msg_info;
11767
11768                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11769                 msg_info.hdr.nexus = io->io_hdr.nexus;
11770                 if (ua_type==CTL_UA_TARG_RESET)
11771                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11772                 else
11773                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11774                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11775                 msg_info.hdr.original_sc = NULL;
11776                 msg_info.hdr.serializing_sc = NULL;
11777                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11778                     (void *)&msg_info, sizeof(msg_info), 0)) {
11779                 }
11780         }
11781         retval = 0;
11782
11783         mtx_lock(&ctl_softc->ctl_lock);
11784         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11785                 retval += ctl_lun_reset(lun, io, ua_type);
11786         mtx_unlock(&ctl_softc->ctl_lock);
11787
11788         return (retval);
11789 }
11790
11791 /*
11792  * The LUN should always be set.  The I/O is optional, and is used to
11793  * distinguish between I/Os sent by this initiator, and by other
11794  * initiators.  We set unit attention for initiators other than this one.
11795  * SAM-3 is vague on this point.  It does say that a unit attention should
11796  * be established for other initiators when a LUN is reset (see section
11797  * 5.7.3), but it doesn't specifically say that the unit attention should
11798  * be established for this particular initiator when a LUN is reset.  Here
11799  * is the relevant text, from SAM-3 rev 8:
11800  *
11801  * 5.7.2 When a SCSI initiator port aborts its own tasks
11802  *
11803  * When a SCSI initiator port causes its own task(s) to be aborted, no
11804  * notification that the task(s) have been aborted shall be returned to
11805  * the SCSI initiator port other than the completion response for the
11806  * command or task management function action that caused the task(s) to
11807  * be aborted and notification(s) associated with related effects of the
11808  * action (e.g., a reset unit attention condition).
11809  *
11810  * XXX KDM for now, we're setting unit attention for all initiators.
11811  */
11812 static int
11813 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11814 {
11815         union ctl_io *xio;
11816 #if 0
11817         uint32_t initindex;
11818 #endif
11819         int i;
11820
11821         mtx_lock(&lun->lun_lock);
11822         /*
11823          * Run through the OOA queue and abort each I/O.
11824          */
11825 #if 0
11826         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11827 #endif
11828         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11829              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11830                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11831         }
11832
11833         /*
11834          * This version sets unit attention for every
11835          */
11836 #if 0
11837         initindex = ctl_get_initindex(&io->io_hdr.nexus);
11838         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11839                 if (initindex == i)
11840                         continue;
11841                 lun->pending_sense[i].ua_pending |= ua_type;
11842         }
11843 #endif
11844
11845         /*
11846          * A reset (any kind, really) clears reservations established with
11847          * RESERVE/RELEASE.  It does not clear reservations established
11848          * with PERSISTENT RESERVE OUT, but we don't support that at the
11849          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11850          * reservations made with the RESERVE/RELEASE commands, because
11851          * those commands are obsolete in SPC-3.
11852          */
11853         lun->flags &= ~CTL_LUN_RESERVED;
11854
11855         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11856                 ctl_clear_mask(lun->have_ca, i);
11857                 lun->pending_sense[i].ua_pending |= ua_type;
11858         }
11859         mtx_unlock(&lun->lun_lock);
11860
11861         return (0);
11862 }
11863
11864 static int
11865 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11866     int other_sc)
11867 {
11868         union ctl_io *xio;
11869         int found;
11870
11871         mtx_assert(&lun->lun_lock, MA_OWNED);
11872
11873         /*
11874          * Run through the OOA queue and attempt to find the given I/O.
11875          * The target port, initiator ID, tag type and tag number have to
11876          * match the values that we got from the initiator.  If we have an
11877          * untagged command to abort, simply abort the first untagged command
11878          * we come to.  We only allow one untagged command at a time of course.
11879          */
11880         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11881              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11882
11883                 if ((targ_port == UINT32_MAX ||
11884                      targ_port == xio->io_hdr.nexus.targ_port) &&
11885                     (init_id == UINT32_MAX ||
11886                      init_id == xio->io_hdr.nexus.initid.id)) {
11887                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11888                             init_id != xio->io_hdr.nexus.initid.id)
11889                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11890                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11891                         found = 1;
11892                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11893                                 union ctl_ha_msg msg_info;
11894
11895                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11896                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11897                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11898                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11899                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11900                                 msg_info.hdr.original_sc = NULL;
11901                                 msg_info.hdr.serializing_sc = NULL;
11902                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11903                                     (void *)&msg_info, sizeof(msg_info), 0);
11904                         }
11905                 }
11906         }
11907         return (found);
11908 }
11909
11910 static int
11911 ctl_abort_task_set(union ctl_io *io)
11912 {
11913         struct ctl_softc *softc = control_softc;
11914         struct ctl_lun *lun;
11915         uint32_t targ_lun;
11916
11917         /*
11918          * Look up the LUN.
11919          */
11920         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11921         mtx_lock(&softc->ctl_lock);
11922         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11923                 lun = softc->ctl_luns[targ_lun];
11924         else {
11925                 mtx_unlock(&softc->ctl_lock);
11926                 return (1);
11927         }
11928
11929         mtx_lock(&lun->lun_lock);
11930         mtx_unlock(&softc->ctl_lock);
11931         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11932                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11933                     io->io_hdr.nexus.initid.id,
11934                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11935         } else { /* CTL_TASK_CLEAR_TASK_SET */
11936                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11937                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11938         }
11939         mtx_unlock(&lun->lun_lock);
11940         return (0);
11941 }
11942
11943 static int
11944 ctl_i_t_nexus_reset(union ctl_io *io)
11945 {
11946         struct ctl_softc *softc = control_softc;
11947         struct ctl_lun *lun;
11948         uint32_t initindex;
11949
11950         initindex = ctl_get_initindex(&io->io_hdr.nexus);
11951         mtx_lock(&softc->ctl_lock);
11952         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11953                 mtx_lock(&lun->lun_lock);
11954                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11955                     io->io_hdr.nexus.initid.id,
11956                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11957                 ctl_clear_mask(lun->have_ca, initindex);
11958                 lun->pending_sense[initindex].ua_pending |= CTL_UA_I_T_NEXUS_LOSS;
11959                 mtx_unlock(&lun->lun_lock);
11960         }
11961         mtx_unlock(&softc->ctl_lock);
11962         return (0);
11963 }
11964
11965 static int
11966 ctl_abort_task(union ctl_io *io)
11967 {
11968         union ctl_io *xio;
11969         struct ctl_lun *lun;
11970         struct ctl_softc *ctl_softc;
11971 #if 0
11972         struct sbuf sb;
11973         char printbuf[128];
11974 #endif
11975         int found;
11976         uint32_t targ_lun;
11977
11978         ctl_softc = control_softc;
11979         found = 0;
11980
11981         /*
11982          * Look up the LUN.
11983          */
11984         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11985         mtx_lock(&ctl_softc->ctl_lock);
11986         if ((targ_lun < CTL_MAX_LUNS)
11987          && (ctl_softc->ctl_luns[targ_lun] != NULL))
11988                 lun = ctl_softc->ctl_luns[targ_lun];
11989         else {
11990                 mtx_unlock(&ctl_softc->ctl_lock);
11991                 return (1);
11992         }
11993
11994 #if 0
11995         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11996                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11997 #endif
11998
11999         mtx_lock(&lun->lun_lock);
12000         mtx_unlock(&ctl_softc->ctl_lock);
12001         /*
12002          * Run through the OOA queue and attempt to find the given I/O.
12003          * The target port, initiator ID, tag type and tag number have to
12004          * match the values that we got from the initiator.  If we have an
12005          * untagged command to abort, simply abort the first untagged command
12006          * we come to.  We only allow one untagged command at a time of course.
12007          */
12008 #if 0
12009         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12010 #endif
12011         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12012              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12013 #if 0
12014                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12015
12016                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12017                             lun->lun, xio->scsiio.tag_num,
12018                             xio->scsiio.tag_type,
12019                             (xio->io_hdr.blocked_links.tqe_prev
12020                             == NULL) ? "" : " BLOCKED",
12021                             (xio->io_hdr.flags &
12022                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12023                             (xio->io_hdr.flags &
12024                             CTL_FLAG_ABORT) ? " ABORT" : "",
12025                             (xio->io_hdr.flags &
12026                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12027                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12028                 sbuf_finish(&sb);
12029                 printf("%s\n", sbuf_data(&sb));
12030 #endif
12031
12032                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12033                  && (xio->io_hdr.nexus.initid.id ==
12034                      io->io_hdr.nexus.initid.id)) {
12035                         /*
12036                          * If the abort says that the task is untagged, the
12037                          * task in the queue must be untagged.  Otherwise,
12038                          * we just check to see whether the tag numbers
12039                          * match.  This is because the QLogic firmware
12040                          * doesn't pass back the tag type in an abort
12041                          * request.
12042                          */
12043 #if 0
12044                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12045                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12046                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12047 #endif
12048                         /*
12049                          * XXX KDM we've got problems with FC, because it
12050                          * doesn't send down a tag type with aborts.  So we
12051                          * can only really go by the tag number...
12052                          * This may cause problems with parallel SCSI.
12053                          * Need to figure that out!!
12054                          */
12055                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12056                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12057                                 found = 1;
12058                                 if ((io->io_hdr.flags &
12059                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12060                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12061                                         union ctl_ha_msg msg_info;
12062
12063                                         io->io_hdr.flags |=
12064                                                         CTL_FLAG_SENT_2OTHER_SC;
12065                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12066                                         msg_info.task.task_action =
12067                                                 CTL_TASK_ABORT_TASK;
12068                                         msg_info.task.tag_num =
12069                                                 io->taskio.tag_num;
12070                                         msg_info.task.tag_type =
12071                                                 io->taskio.tag_type;
12072                                         msg_info.hdr.msg_type =
12073                                                 CTL_MSG_MANAGE_TASKS;
12074                                         msg_info.hdr.original_sc = NULL;
12075                                         msg_info.hdr.serializing_sc = NULL;
12076 #if 0
12077                                         printf("Sent Abort to other side\n");
12078 #endif
12079                                         if (CTL_HA_STATUS_SUCCESS !=
12080                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12081                                                 (void *)&msg_info,
12082                                                 sizeof(msg_info), 0)) {
12083                                         }
12084                                 }
12085 #if 0
12086                                 printf("ctl_abort_task: found I/O to abort\n");
12087 #endif
12088                                 break;
12089                         }
12090                 }
12091         }
12092         mtx_unlock(&lun->lun_lock);
12093
12094         if (found == 0) {
12095                 /*
12096                  * This isn't really an error.  It's entirely possible for
12097                  * the abort and command completion to cross on the wire.
12098                  * This is more of an informative/diagnostic error.
12099                  */
12100 #if 0
12101                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12102                        "%d:%d:%d:%d tag %d type %d\n",
12103                        io->io_hdr.nexus.initid.id,
12104                        io->io_hdr.nexus.targ_port,
12105                        io->io_hdr.nexus.targ_target.id,
12106                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12107                        io->taskio.tag_type);
12108 #endif
12109         }
12110         return (0);
12111 }
12112
12113 static void
12114 ctl_run_task(union ctl_io *io)
12115 {
12116         struct ctl_softc *ctl_softc = control_softc;
12117         int retval = 1;
12118         const char *task_desc;
12119
12120         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12121
12122         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12123             ("ctl_run_task: Unextected io_type %d\n",
12124              io->io_hdr.io_type));
12125
12126         task_desc = ctl_scsi_task_string(&io->taskio);
12127         if (task_desc != NULL) {
12128 #ifdef NEEDTOPORT
12129                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12130                             CTL_TASK_REPORT,
12131                             csevent_LogType_Trace,
12132                             csevent_Severity_Information,
12133                             csevent_AlertLevel_Green,
12134                             csevent_FRU_Firmware,
12135                             csevent_FRU_Unknown,
12136                             "CTL: received task: %s",task_desc);
12137 #endif
12138         } else {
12139 #ifdef NEEDTOPORT
12140                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12141                             CTL_TASK_REPORT,
12142                             csevent_LogType_Trace,
12143                             csevent_Severity_Information,
12144                             csevent_AlertLevel_Green,
12145                             csevent_FRU_Firmware,
12146                             csevent_FRU_Unknown,
12147                             "CTL: received unknown task "
12148                             "type: %d (%#x)",
12149                             io->taskio.task_action,
12150                             io->taskio.task_action);
12151 #endif
12152         }
12153         switch (io->taskio.task_action) {
12154         case CTL_TASK_ABORT_TASK:
12155                 retval = ctl_abort_task(io);
12156                 break;
12157         case CTL_TASK_ABORT_TASK_SET:
12158         case CTL_TASK_CLEAR_TASK_SET:
12159                 retval = ctl_abort_task_set(io);
12160                 break;
12161         case CTL_TASK_CLEAR_ACA:
12162                 break;
12163         case CTL_TASK_I_T_NEXUS_RESET:
12164                 retval = ctl_i_t_nexus_reset(io);
12165                 break;
12166         case CTL_TASK_LUN_RESET: {
12167                 struct ctl_lun *lun;
12168                 uint32_t targ_lun;
12169
12170                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12171                 mtx_lock(&ctl_softc->ctl_lock);
12172                 if ((targ_lun < CTL_MAX_LUNS)
12173                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12174                         lun = ctl_softc->ctl_luns[targ_lun];
12175                 else {
12176                         mtx_unlock(&ctl_softc->ctl_lock);
12177                         retval = 1;
12178                         break;
12179                 }
12180
12181                 if (!(io->io_hdr.flags &
12182                     CTL_FLAG_FROM_OTHER_SC)) {
12183                         union ctl_ha_msg msg_info;
12184
12185                         io->io_hdr.flags |=
12186                                 CTL_FLAG_SENT_2OTHER_SC;
12187                         msg_info.hdr.msg_type =
12188                                 CTL_MSG_MANAGE_TASKS;
12189                         msg_info.hdr.nexus = io->io_hdr.nexus;
12190                         msg_info.task.task_action =
12191                                 CTL_TASK_LUN_RESET;
12192                         msg_info.hdr.original_sc = NULL;
12193                         msg_info.hdr.serializing_sc = NULL;
12194                         if (CTL_HA_STATUS_SUCCESS !=
12195                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12196                             (void *)&msg_info,
12197                             sizeof(msg_info), 0)) {
12198                         }
12199                 }
12200
12201                 retval = ctl_lun_reset(lun, io,
12202                                        CTL_UA_LUN_RESET);
12203                 mtx_unlock(&ctl_softc->ctl_lock);
12204                 break;
12205         }
12206         case CTL_TASK_TARGET_RESET:
12207                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12208                 break;
12209         case CTL_TASK_BUS_RESET:
12210                 retval = ctl_bus_reset(ctl_softc, io);
12211                 break;
12212         case CTL_TASK_PORT_LOGIN:
12213                 break;
12214         case CTL_TASK_PORT_LOGOUT:
12215                 break;
12216         default:
12217                 printf("ctl_run_task: got unknown task management event %d\n",
12218                        io->taskio.task_action);
12219                 break;
12220         }
12221         if (retval == 0)
12222                 io->io_hdr.status = CTL_SUCCESS;
12223         else
12224                 io->io_hdr.status = CTL_ERROR;
12225         ctl_done(io);
12226 }
12227
12228 /*
12229  * For HA operation.  Handle commands that come in from the other
12230  * controller.
12231  */
12232 static void
12233 ctl_handle_isc(union ctl_io *io)
12234 {
12235         int free_io;
12236         struct ctl_lun *lun;
12237         struct ctl_softc *ctl_softc;
12238         uint32_t targ_lun;
12239
12240         ctl_softc = control_softc;
12241
12242         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12243         lun = ctl_softc->ctl_luns[targ_lun];
12244
12245         switch (io->io_hdr.msg_type) {
12246         case CTL_MSG_SERIALIZE:
12247                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12248                 break;
12249         case CTL_MSG_R2R: {
12250                 const struct ctl_cmd_entry *entry;
12251
12252                 /*
12253                  * This is only used in SER_ONLY mode.
12254                  */
12255                 free_io = 0;
12256                 entry = ctl_get_cmd_entry(&io->scsiio);
12257                 mtx_lock(&lun->lun_lock);
12258                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12259                     entry, (struct ctl_scsiio *)io) != 0) {
12260                         mtx_unlock(&lun->lun_lock);
12261                         ctl_done(io);
12262                         break;
12263                 }
12264                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12265                 mtx_unlock(&lun->lun_lock);
12266                 ctl_enqueue_rtr(io);
12267                 break;
12268         }
12269         case CTL_MSG_FINISH_IO:
12270                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12271                         free_io = 0;
12272                         ctl_done(io);
12273                 } else {
12274                         free_io = 1;
12275                         mtx_lock(&lun->lun_lock);
12276                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12277                                      ooa_links);
12278                         ctl_check_blocked(lun);
12279                         mtx_unlock(&lun->lun_lock);
12280                 }
12281                 break;
12282         case CTL_MSG_PERS_ACTION:
12283                 ctl_hndl_per_res_out_on_other_sc(
12284                         (union ctl_ha_msg *)&io->presio.pr_msg);
12285                 free_io = 1;
12286                 break;
12287         case CTL_MSG_BAD_JUJU:
12288                 free_io = 0;
12289                 ctl_done(io);
12290                 break;
12291         case CTL_MSG_DATAMOVE:
12292                 /* Only used in XFER mode */
12293                 free_io = 0;
12294                 ctl_datamove_remote(io);
12295                 break;
12296         case CTL_MSG_DATAMOVE_DONE:
12297                 /* Only used in XFER mode */
12298                 free_io = 0;
12299                 io->scsiio.be_move_done(io);
12300                 break;
12301         default:
12302                 free_io = 1;
12303                 printf("%s: Invalid message type %d\n",
12304                        __func__, io->io_hdr.msg_type);
12305                 break;
12306         }
12307         if (free_io)
12308                 ctl_free_io(io);
12309
12310 }
12311
12312
12313 /*
12314  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12315  * there is no match.
12316  */
12317 static ctl_lun_error_pattern
12318 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12319 {
12320         const struct ctl_cmd_entry *entry;
12321         ctl_lun_error_pattern filtered_pattern, pattern;
12322
12323         pattern = desc->error_pattern;
12324
12325         /*
12326          * XXX KDM we need more data passed into this function to match a
12327          * custom pattern, and we actually need to implement custom pattern
12328          * matching.
12329          */
12330         if (pattern & CTL_LUN_PAT_CMD)
12331                 return (CTL_LUN_PAT_CMD);
12332
12333         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12334                 return (CTL_LUN_PAT_ANY);
12335
12336         entry = ctl_get_cmd_entry(ctsio);
12337
12338         filtered_pattern = entry->pattern & pattern;
12339
12340         /*
12341          * If the user requested specific flags in the pattern (e.g.
12342          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12343          * flags.
12344          *
12345          * If the user did not specify any flags, it doesn't matter whether
12346          * or not the command supports the flags.
12347          */
12348         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12349              (pattern & ~CTL_LUN_PAT_MASK))
12350                 return (CTL_LUN_PAT_NONE);
12351
12352         /*
12353          * If the user asked for a range check, see if the requested LBA
12354          * range overlaps with this command's LBA range.
12355          */
12356         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12357                 uint64_t lba1;
12358                 uint32_t len1;
12359                 ctl_action action;
12360                 int retval;
12361
12362                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12363                 if (retval != 0)
12364                         return (CTL_LUN_PAT_NONE);
12365
12366                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12367                                               desc->lba_range.len);
12368                 /*
12369                  * A "pass" means that the LBA ranges don't overlap, so
12370                  * this doesn't match the user's range criteria.
12371                  */
12372                 if (action == CTL_ACTION_PASS)
12373                         return (CTL_LUN_PAT_NONE);
12374         }
12375
12376         return (filtered_pattern);
12377 }
12378
12379 static void
12380 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12381 {
12382         struct ctl_error_desc *desc, *desc2;
12383
12384         mtx_assert(&lun->lun_lock, MA_OWNED);
12385
12386         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12387                 ctl_lun_error_pattern pattern;
12388                 /*
12389                  * Check to see whether this particular command matches
12390                  * the pattern in the descriptor.
12391                  */
12392                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12393                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12394                         continue;
12395
12396                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12397                 case CTL_LUN_INJ_ABORTED:
12398                         ctl_set_aborted(&io->scsiio);
12399                         break;
12400                 case CTL_LUN_INJ_MEDIUM_ERR:
12401                         ctl_set_medium_error(&io->scsiio);
12402                         break;
12403                 case CTL_LUN_INJ_UA:
12404                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12405                          * OCCURRED */
12406                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12407                         break;
12408                 case CTL_LUN_INJ_CUSTOM:
12409                         /*
12410                          * We're assuming the user knows what he is doing.
12411                          * Just copy the sense information without doing
12412                          * checks.
12413                          */
12414                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12415                               ctl_min(sizeof(desc->custom_sense),
12416                                       sizeof(io->scsiio.sense_data)));
12417                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12418                         io->scsiio.sense_len = SSD_FULL_SIZE;
12419                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12420                         break;
12421                 case CTL_LUN_INJ_NONE:
12422                 default:
12423                         /*
12424                          * If this is an error injection type we don't know
12425                          * about, clear the continuous flag (if it is set)
12426                          * so it will get deleted below.
12427                          */
12428                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12429                         break;
12430                 }
12431                 /*
12432                  * By default, each error injection action is a one-shot
12433                  */
12434                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12435                         continue;
12436
12437                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12438
12439                 free(desc, M_CTL);
12440         }
12441 }
12442
12443 #ifdef CTL_IO_DELAY
12444 static void
12445 ctl_datamove_timer_wakeup(void *arg)
12446 {
12447         union ctl_io *io;
12448
12449         io = (union ctl_io *)arg;
12450
12451         ctl_datamove(io);
12452 }
12453 #endif /* CTL_IO_DELAY */
12454
12455 void
12456 ctl_datamove(union ctl_io *io)
12457 {
12458         void (*fe_datamove)(union ctl_io *io);
12459
12460         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12461
12462         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12463
12464 #ifdef CTL_TIME_IO
12465         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12466                 char str[256];
12467                 char path_str[64];
12468                 struct sbuf sb;
12469
12470                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12471                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12472
12473                 sbuf_cat(&sb, path_str);
12474                 switch (io->io_hdr.io_type) {
12475                 case CTL_IO_SCSI:
12476                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12477                         sbuf_printf(&sb, "\n");
12478                         sbuf_cat(&sb, path_str);
12479                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12480                                     io->scsiio.tag_num, io->scsiio.tag_type);
12481                         break;
12482                 case CTL_IO_TASK:
12483                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12484                                     "Tag Type: %d\n", io->taskio.task_action,
12485                                     io->taskio.tag_num, io->taskio.tag_type);
12486                         break;
12487                 default:
12488                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12489                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12490                         break;
12491                 }
12492                 sbuf_cat(&sb, path_str);
12493                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12494                             (intmax_t)time_uptime - io->io_hdr.start_time);
12495                 sbuf_finish(&sb);
12496                 printf("%s", sbuf_data(&sb));
12497         }
12498 #endif /* CTL_TIME_IO */
12499
12500 #ifdef CTL_IO_DELAY
12501         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12502                 struct ctl_lun *lun;
12503
12504                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12505
12506                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12507         } else {
12508                 struct ctl_lun *lun;
12509
12510                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12511                 if ((lun != NULL)
12512                  && (lun->delay_info.datamove_delay > 0)) {
12513                         struct callout *callout;
12514
12515                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12516                         callout_init(callout, /*mpsafe*/ 1);
12517                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12518                         callout_reset(callout,
12519                                       lun->delay_info.datamove_delay * hz,
12520                                       ctl_datamove_timer_wakeup, io);
12521                         if (lun->delay_info.datamove_type ==
12522                             CTL_DELAY_TYPE_ONESHOT)
12523                                 lun->delay_info.datamove_delay = 0;
12524                         return;
12525                 }
12526         }
12527 #endif
12528
12529         /*
12530          * This command has been aborted.  Set the port status, so we fail
12531          * the data move.
12532          */
12533         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12534                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12535                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12536                        io->io_hdr.nexus.targ_port,
12537                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12538                        io->io_hdr.nexus.targ_lun);
12539                 io->io_hdr.port_status = 31337;
12540                 /*
12541                  * Note that the backend, in this case, will get the
12542                  * callback in its context.  In other cases it may get
12543                  * called in the frontend's interrupt thread context.
12544                  */
12545                 io->scsiio.be_move_done(io);
12546                 return;
12547         }
12548
12549         /*
12550          * If we're in XFER mode and this I/O is from the other shelf
12551          * controller, we need to send the DMA to the other side to
12552          * actually transfer the data to/from the host.  In serialize only
12553          * mode the transfer happens below CTL and ctl_datamove() is only
12554          * called on the machine that originally received the I/O.
12555          */
12556         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12557          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12558                 union ctl_ha_msg msg;
12559                 uint32_t sg_entries_sent;
12560                 int do_sg_copy;
12561                 int i;
12562
12563                 memset(&msg, 0, sizeof(msg));
12564                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12565                 msg.hdr.original_sc = io->io_hdr.original_sc;
12566                 msg.hdr.serializing_sc = io;
12567                 msg.hdr.nexus = io->io_hdr.nexus;
12568                 msg.dt.flags = io->io_hdr.flags;
12569                 /*
12570                  * We convert everything into a S/G list here.  We can't
12571                  * pass by reference, only by value between controllers.
12572                  * So we can't pass a pointer to the S/G list, only as many
12573                  * S/G entries as we can fit in here.  If it's possible for
12574                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12575                  * then we need to break this up into multiple transfers.
12576                  */
12577                 if (io->scsiio.kern_sg_entries == 0) {
12578                         msg.dt.kern_sg_entries = 1;
12579                         /*
12580                          * If this is in cached memory, flush the cache
12581                          * before we send the DMA request to the other
12582                          * controller.  We want to do this in either the
12583                          * read or the write case.  The read case is
12584                          * straightforward.  In the write case, we want to
12585                          * make sure nothing is in the local cache that
12586                          * could overwrite the DMAed data.
12587                          */
12588                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12589                                 /*
12590                                  * XXX KDM use bus_dmamap_sync() here.
12591                                  */
12592                         }
12593
12594                         /*
12595                          * Convert to a physical address if this is a
12596                          * virtual address.
12597                          */
12598                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12599                                 msg.dt.sg_list[0].addr =
12600                                         io->scsiio.kern_data_ptr;
12601                         } else {
12602                                 /*
12603                                  * XXX KDM use busdma here!
12604                                  */
12605 #if 0
12606                                 msg.dt.sg_list[0].addr = (void *)
12607                                         vtophys(io->scsiio.kern_data_ptr);
12608 #endif
12609                         }
12610
12611                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12612                         do_sg_copy = 0;
12613                 } else {
12614                         struct ctl_sg_entry *sgl;
12615
12616                         do_sg_copy = 1;
12617                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12618                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12619                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12620                                 /*
12621                                  * XXX KDM use bus_dmamap_sync() here.
12622                                  */
12623                         }
12624                 }
12625
12626                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12627                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12628                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12629                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12630                 msg.dt.sg_sequence = 0;
12631
12632                 /*
12633                  * Loop until we've sent all of the S/G entries.  On the
12634                  * other end, we'll recompose these S/G entries into one
12635                  * contiguous list before passing it to the
12636                  */
12637                 for (sg_entries_sent = 0; sg_entries_sent <
12638                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12639                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12640                                 sizeof(msg.dt.sg_list[0])),
12641                                 msg.dt.kern_sg_entries - sg_entries_sent);
12642
12643                         if (do_sg_copy != 0) {
12644                                 struct ctl_sg_entry *sgl;
12645                                 int j;
12646
12647                                 sgl = (struct ctl_sg_entry *)
12648                                         io->scsiio.kern_data_ptr;
12649                                 /*
12650                                  * If this is in cached memory, flush the cache
12651                                  * before we send the DMA request to the other
12652                                  * controller.  We want to do this in either
12653                                  * the * read or the write case.  The read
12654                                  * case is straightforward.  In the write
12655                                  * case, we want to make sure nothing is
12656                                  * in the local cache that could overwrite
12657                                  * the DMAed data.
12658                                  */
12659
12660                                 for (i = sg_entries_sent, j = 0;
12661                                      i < msg.dt.cur_sg_entries; i++, j++) {
12662                                         if ((io->io_hdr.flags &
12663                                              CTL_FLAG_NO_DATASYNC) == 0) {
12664                                                 /*
12665                                                  * XXX KDM use bus_dmamap_sync()
12666                                                  */
12667                                         }
12668                                         if ((io->io_hdr.flags &
12669                                              CTL_FLAG_BUS_ADDR) == 0) {
12670                                                 /*
12671                                                  * XXX KDM use busdma.
12672                                                  */
12673 #if 0
12674                                                 msg.dt.sg_list[j].addr =(void *)
12675                                                        vtophys(sgl[i].addr);
12676 #endif
12677                                         } else {
12678                                                 msg.dt.sg_list[j].addr =
12679                                                         sgl[i].addr;
12680                                         }
12681                                         msg.dt.sg_list[j].len = sgl[i].len;
12682                                 }
12683                         }
12684
12685                         sg_entries_sent += msg.dt.cur_sg_entries;
12686                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12687                                 msg.dt.sg_last = 1;
12688                         else
12689                                 msg.dt.sg_last = 0;
12690
12691                         /*
12692                          * XXX KDM drop and reacquire the lock here?
12693                          */
12694                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12695                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12696                                 /*
12697                                  * XXX do something here.
12698                                  */
12699                         }
12700
12701                         msg.dt.sent_sg_entries = sg_entries_sent;
12702                 }
12703                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12704                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12705                         ctl_failover_io(io, /*have_lock*/ 0);
12706
12707         } else {
12708
12709                 /*
12710                  * Lookup the fe_datamove() function for this particular
12711                  * front end.
12712                  */
12713                 fe_datamove =
12714                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12715
12716                 fe_datamove(io);
12717         }
12718 }
12719
12720 static void
12721 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12722 {
12723         union ctl_ha_msg msg;
12724         int isc_status;
12725
12726         memset(&msg, 0, sizeof(msg));
12727
12728         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12729         msg.hdr.original_sc = io;
12730         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12731         msg.hdr.nexus = io->io_hdr.nexus;
12732         msg.hdr.status = io->io_hdr.status;
12733         msg.scsi.tag_num = io->scsiio.tag_num;
12734         msg.scsi.tag_type = io->scsiio.tag_type;
12735         msg.scsi.scsi_status = io->scsiio.scsi_status;
12736         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12737                sizeof(io->scsiio.sense_data));
12738         msg.scsi.sense_len = io->scsiio.sense_len;
12739         msg.scsi.sense_residual = io->scsiio.sense_residual;
12740         msg.scsi.fetd_status = io->io_hdr.port_status;
12741         msg.scsi.residual = io->scsiio.residual;
12742         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12743
12744         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12745                 ctl_failover_io(io, /*have_lock*/ have_lock);
12746                 return;
12747         }
12748
12749         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12750         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12751                 /* XXX do something if this fails */
12752         }
12753
12754 }
12755
12756 /*
12757  * The DMA to the remote side is done, now we need to tell the other side
12758  * we're done so it can continue with its data movement.
12759  */
12760 static void
12761 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12762 {
12763         union ctl_io *io;
12764
12765         io = rq->context;
12766
12767         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12768                 printf("%s: ISC DMA write failed with error %d", __func__,
12769                        rq->ret);
12770                 ctl_set_internal_failure(&io->scsiio,
12771                                          /*sks_valid*/ 1,
12772                                          /*retry_count*/ rq->ret);
12773         }
12774
12775         ctl_dt_req_free(rq);
12776
12777         /*
12778          * In this case, we had to malloc the memory locally.  Free it.
12779          */
12780         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12781                 int i;
12782                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12783                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12784         }
12785         /*
12786          * The data is in local and remote memory, so now we need to send
12787          * status (good or back) back to the other side.
12788          */
12789         ctl_send_datamove_done(io, /*have_lock*/ 0);
12790 }
12791
12792 /*
12793  * We've moved the data from the host/controller into local memory.  Now we
12794  * need to push it over to the remote controller's memory.
12795  */
12796 static int
12797 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12798 {
12799         int retval;
12800
12801         retval = 0;
12802
12803         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12804                                           ctl_datamove_remote_write_cb);
12805
12806         return (retval);
12807 }
12808
12809 static void
12810 ctl_datamove_remote_write(union ctl_io *io)
12811 {
12812         int retval;
12813         void (*fe_datamove)(union ctl_io *io);
12814
12815         /*
12816          * - Get the data from the host/HBA into local memory.
12817          * - DMA memory from the local controller to the remote controller.
12818          * - Send status back to the remote controller.
12819          */
12820
12821         retval = ctl_datamove_remote_sgl_setup(io);
12822         if (retval != 0)
12823                 return;
12824
12825         /* Switch the pointer over so the FETD knows what to do */
12826         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12827
12828         /*
12829          * Use a custom move done callback, since we need to send completion
12830          * back to the other controller, not to the backend on this side.
12831          */
12832         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12833
12834         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12835
12836         fe_datamove(io);
12837
12838         return;
12839
12840 }
12841
12842 static int
12843 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12844 {
12845 #if 0
12846         char str[256];
12847         char path_str[64];
12848         struct sbuf sb;
12849 #endif
12850
12851         /*
12852          * In this case, we had to malloc the memory locally.  Free it.
12853          */
12854         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12855                 int i;
12856                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12857                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12858         }
12859
12860 #if 0
12861         scsi_path_string(io, path_str, sizeof(path_str));
12862         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12863         sbuf_cat(&sb, path_str);
12864         scsi_command_string(&io->scsiio, NULL, &sb);
12865         sbuf_printf(&sb, "\n");
12866         sbuf_cat(&sb, path_str);
12867         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12868                     io->scsiio.tag_num, io->scsiio.tag_type);
12869         sbuf_cat(&sb, path_str);
12870         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12871                     io->io_hdr.flags, io->io_hdr.status);
12872         sbuf_finish(&sb);
12873         printk("%s", sbuf_data(&sb));
12874 #endif
12875
12876
12877         /*
12878          * The read is done, now we need to send status (good or bad) back
12879          * to the other side.
12880          */
12881         ctl_send_datamove_done(io, /*have_lock*/ 0);
12882
12883         return (0);
12884 }
12885
12886 static void
12887 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12888 {
12889         union ctl_io *io;
12890         void (*fe_datamove)(union ctl_io *io);
12891
12892         io = rq->context;
12893
12894         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12895                 printf("%s: ISC DMA read failed with error %d", __func__,
12896                        rq->ret);
12897                 ctl_set_internal_failure(&io->scsiio,
12898                                          /*sks_valid*/ 1,
12899                                          /*retry_count*/ rq->ret);
12900         }
12901
12902         ctl_dt_req_free(rq);
12903
12904         /* Switch the pointer over so the FETD knows what to do */
12905         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12906
12907         /*
12908          * Use a custom move done callback, since we need to send completion
12909          * back to the other controller, not to the backend on this side.
12910          */
12911         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12912
12913         /* XXX KDM add checks like the ones in ctl_datamove? */
12914
12915         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12916
12917         fe_datamove(io);
12918 }
12919
12920 static int
12921 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12922 {
12923         struct ctl_sg_entry *local_sglist, *remote_sglist;
12924         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12925         struct ctl_softc *softc;
12926         int retval;
12927         int i;
12928
12929         retval = 0;
12930         softc = control_softc;
12931
12932         local_sglist = io->io_hdr.local_sglist;
12933         local_dma_sglist = io->io_hdr.local_dma_sglist;
12934         remote_sglist = io->io_hdr.remote_sglist;
12935         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12936
12937         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12938                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12939                         local_sglist[i].len = remote_sglist[i].len;
12940
12941                         /*
12942                          * XXX Detect the situation where the RS-level I/O
12943                          * redirector on the other side has already read the
12944                          * data off of the AOR RS on this side, and
12945                          * transferred it to remote (mirror) memory on the
12946                          * other side.  Since we already have the data in
12947                          * memory here, we just need to use it.
12948                          *
12949                          * XXX KDM this can probably be removed once we
12950                          * get the cache device code in and take the
12951                          * current AOR implementation out.
12952                          */
12953 #ifdef NEEDTOPORT
12954                         if ((remote_sglist[i].addr >=
12955                              (void *)vtophys(softc->mirr->addr))
12956                          && (remote_sglist[i].addr <
12957                              ((void *)vtophys(softc->mirr->addr) +
12958                              CacheMirrorOffset))) {
12959                                 local_sglist[i].addr = remote_sglist[i].addr -
12960                                         CacheMirrorOffset;
12961                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12962                                      CTL_FLAG_DATA_IN)
12963                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12964                         } else {
12965                                 local_sglist[i].addr = remote_sglist[i].addr +
12966                                         CacheMirrorOffset;
12967                         }
12968 #endif
12969 #if 0
12970                         printf("%s: local %p, remote %p, len %d\n",
12971                                __func__, local_sglist[i].addr,
12972                                remote_sglist[i].addr, local_sglist[i].len);
12973 #endif
12974                 }
12975         } else {
12976                 uint32_t len_to_go;
12977
12978                 /*
12979                  * In this case, we don't have automatically allocated
12980                  * memory for this I/O on this controller.  This typically
12981                  * happens with internal CTL I/O -- e.g. inquiry, mode
12982                  * sense, etc.  Anything coming from RAIDCore will have
12983                  * a mirror area available.
12984                  */
12985                 len_to_go = io->scsiio.kern_data_len;
12986
12987                 /*
12988                  * Clear the no datasync flag, we have to use malloced
12989                  * buffers.
12990                  */
12991                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12992
12993                 /*
12994                  * The difficult thing here is that the size of the various
12995                  * S/G segments may be different than the size from the
12996                  * remote controller.  That'll make it harder when DMAing
12997                  * the data back to the other side.
12998                  */
12999                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13000                      sizeof(io->io_hdr.remote_sglist[0])) &&
13001                      (len_to_go > 0); i++) {
13002                         local_sglist[i].len = ctl_min(len_to_go, 131072);
13003                         CTL_SIZE_8B(local_dma_sglist[i].len,
13004                                     local_sglist[i].len);
13005                         local_sglist[i].addr =
13006                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13007
13008                         local_dma_sglist[i].addr = local_sglist[i].addr;
13009
13010                         if (local_sglist[i].addr == NULL) {
13011                                 int j;
13012
13013                                 printf("malloc failed for %zd bytes!",
13014                                        local_dma_sglist[i].len);
13015                                 for (j = 0; j < i; j++) {
13016                                         free(local_sglist[j].addr, M_CTL);
13017                                 }
13018                                 ctl_set_internal_failure(&io->scsiio,
13019                                                          /*sks_valid*/ 1,
13020                                                          /*retry_count*/ 4857);
13021                                 retval = 1;
13022                                 goto bailout_error;
13023                                 
13024                         }
13025                         /* XXX KDM do we need a sync here? */
13026
13027                         len_to_go -= local_sglist[i].len;
13028                 }
13029                 /*
13030                  * Reset the number of S/G entries accordingly.  The
13031                  * original number of S/G entries is available in
13032                  * rem_sg_entries.
13033                  */
13034                 io->scsiio.kern_sg_entries = i;
13035
13036 #if 0
13037                 printf("%s: kern_sg_entries = %d\n", __func__,
13038                        io->scsiio.kern_sg_entries);
13039                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13040                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13041                                local_sglist[i].addr, local_sglist[i].len,
13042                                local_dma_sglist[i].len);
13043 #endif
13044         }
13045
13046
13047         return (retval);
13048
13049 bailout_error:
13050
13051         ctl_send_datamove_done(io, /*have_lock*/ 0);
13052
13053         return (retval);
13054 }
13055
13056 static int
13057 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13058                          ctl_ha_dt_cb callback)
13059 {
13060         struct ctl_ha_dt_req *rq;
13061         struct ctl_sg_entry *remote_sglist, *local_sglist;
13062         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13063         uint32_t local_used, remote_used, total_used;
13064         int retval;
13065         int i, j;
13066
13067         retval = 0;
13068
13069         rq = ctl_dt_req_alloc();
13070
13071         /*
13072          * If we failed to allocate the request, and if the DMA didn't fail
13073          * anyway, set busy status.  This is just a resource allocation
13074          * failure.
13075          */
13076         if ((rq == NULL)
13077          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13078                 ctl_set_busy(&io->scsiio);
13079
13080         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13081
13082                 if (rq != NULL)
13083                         ctl_dt_req_free(rq);
13084
13085                 /*
13086                  * The data move failed.  We need to return status back
13087                  * to the other controller.  No point in trying to DMA
13088                  * data to the remote controller.
13089                  */
13090
13091                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13092
13093                 retval = 1;
13094
13095                 goto bailout;
13096         }
13097
13098         local_sglist = io->io_hdr.local_sglist;
13099         local_dma_sglist = io->io_hdr.local_dma_sglist;
13100         remote_sglist = io->io_hdr.remote_sglist;
13101         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13102         local_used = 0;
13103         remote_used = 0;
13104         total_used = 0;
13105
13106         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13107                 rq->ret = CTL_HA_STATUS_SUCCESS;
13108                 rq->context = io;
13109                 callback(rq);
13110                 goto bailout;
13111         }
13112
13113         /*
13114          * Pull/push the data over the wire from/to the other controller.
13115          * This takes into account the possibility that the local and
13116          * remote sglists may not be identical in terms of the size of
13117          * the elements and the number of elements.
13118          *
13119          * One fundamental assumption here is that the length allocated for
13120          * both the local and remote sglists is identical.  Otherwise, we've
13121          * essentially got a coding error of some sort.
13122          */
13123         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13124                 int isc_ret;
13125                 uint32_t cur_len, dma_length;
13126                 uint8_t *tmp_ptr;
13127
13128                 rq->id = CTL_HA_DATA_CTL;
13129                 rq->command = command;
13130                 rq->context = io;
13131
13132                 /*
13133                  * Both pointers should be aligned.  But it is possible
13134                  * that the allocation length is not.  They should both
13135                  * also have enough slack left over at the end, though,
13136                  * to round up to the next 8 byte boundary.
13137                  */
13138                 cur_len = ctl_min(local_sglist[i].len - local_used,
13139                                   remote_sglist[j].len - remote_used);
13140
13141                 /*
13142                  * In this case, we have a size issue and need to decrease
13143                  * the size, except in the case where we actually have less
13144                  * than 8 bytes left.  In that case, we need to increase
13145                  * the DMA length to get the last bit.
13146                  */
13147                 if ((cur_len & 0x7) != 0) {
13148                         if (cur_len > 0x7) {
13149                                 cur_len = cur_len - (cur_len & 0x7);
13150                                 dma_length = cur_len;
13151                         } else {
13152                                 CTL_SIZE_8B(dma_length, cur_len);
13153                         }
13154
13155                 } else
13156                         dma_length = cur_len;
13157
13158                 /*
13159                  * If we had to allocate memory for this I/O, instead of using
13160                  * the non-cached mirror memory, we'll need to flush the cache
13161                  * before trying to DMA to the other controller.
13162                  *
13163                  * We could end up doing this multiple times for the same
13164                  * segment if we have a larger local segment than remote
13165                  * segment.  That shouldn't be an issue.
13166                  */
13167                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13168                         /*
13169                          * XXX KDM use bus_dmamap_sync() here.
13170                          */
13171                 }
13172
13173                 rq->size = dma_length;
13174
13175                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13176                 tmp_ptr += local_used;
13177
13178                 /* Use physical addresses when talking to ISC hardware */
13179                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13180                         /* XXX KDM use busdma */
13181 #if 0
13182                         rq->local = vtophys(tmp_ptr);
13183 #endif
13184                 } else
13185                         rq->local = tmp_ptr;
13186
13187                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13188                 tmp_ptr += remote_used;
13189                 rq->remote = tmp_ptr;
13190
13191                 rq->callback = NULL;
13192
13193                 local_used += cur_len;
13194                 if (local_used >= local_sglist[i].len) {
13195                         i++;
13196                         local_used = 0;
13197                 }
13198
13199                 remote_used += cur_len;
13200                 if (remote_used >= remote_sglist[j].len) {
13201                         j++;
13202                         remote_used = 0;
13203                 }
13204                 total_used += cur_len;
13205
13206                 if (total_used >= io->scsiio.kern_data_len)
13207                         rq->callback = callback;
13208
13209                 if ((rq->size & 0x7) != 0) {
13210                         printf("%s: warning: size %d is not on 8b boundary\n",
13211                                __func__, rq->size);
13212                 }
13213                 if (((uintptr_t)rq->local & 0x7) != 0) {
13214                         printf("%s: warning: local %p not on 8b boundary\n",
13215                                __func__, rq->local);
13216                 }
13217                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13218                         printf("%s: warning: remote %p not on 8b boundary\n",
13219                                __func__, rq->local);
13220                 }
13221 #if 0
13222                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13223                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13224                        rq->local, rq->remote, rq->size);
13225 #endif
13226
13227                 isc_ret = ctl_dt_single(rq);
13228                 if (isc_ret == CTL_HA_STATUS_WAIT)
13229                         continue;
13230
13231                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13232                         rq->ret = CTL_HA_STATUS_SUCCESS;
13233                 } else {
13234                         rq->ret = isc_ret;
13235                 }
13236                 callback(rq);
13237                 goto bailout;
13238         }
13239
13240 bailout:
13241         return (retval);
13242
13243 }
13244
13245 static void
13246 ctl_datamove_remote_read(union ctl_io *io)
13247 {
13248         int retval;
13249         int i;
13250
13251         /*
13252          * This will send an error to the other controller in the case of a
13253          * failure.
13254          */
13255         retval = ctl_datamove_remote_sgl_setup(io);
13256         if (retval != 0)
13257                 return;
13258
13259         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13260                                           ctl_datamove_remote_read_cb);
13261         if ((retval != 0)
13262          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13263                 /*
13264                  * Make sure we free memory if there was an error..  The
13265                  * ctl_datamove_remote_xfer() function will send the
13266                  * datamove done message, or call the callback with an
13267                  * error if there is a problem.
13268                  */
13269                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13270                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13271         }
13272
13273         return;
13274 }
13275
13276 /*
13277  * Process a datamove request from the other controller.  This is used for
13278  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13279  * first.  Once that is complete, the data gets DMAed into the remote
13280  * controller's memory.  For reads, we DMA from the remote controller's
13281  * memory into our memory first, and then move it out to the FETD.
13282  */
13283 static void
13284 ctl_datamove_remote(union ctl_io *io)
13285 {
13286         struct ctl_softc *softc;
13287
13288         softc = control_softc;
13289
13290         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13291
13292         /*
13293          * Note that we look for an aborted I/O here, but don't do some of
13294          * the other checks that ctl_datamove() normally does.
13295          * We don't need to run the datamove delay code, since that should
13296          * have been done if need be on the other controller.
13297          */
13298         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13299                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13300                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13301                        io->io_hdr.nexus.targ_port,
13302                        io->io_hdr.nexus.targ_target.id,
13303                        io->io_hdr.nexus.targ_lun);
13304                 io->io_hdr.port_status = 31338;
13305                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13306                 return;
13307         }
13308
13309         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13310                 ctl_datamove_remote_write(io);
13311         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13312                 ctl_datamove_remote_read(io);
13313         } else {
13314                 union ctl_ha_msg msg;
13315                 struct scsi_sense_data *sense;
13316                 uint8_t sks[3];
13317                 int retry_count;
13318
13319                 memset(&msg, 0, sizeof(msg));
13320
13321                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13322                 msg.hdr.status = CTL_SCSI_ERROR;
13323                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13324
13325                 retry_count = 4243;
13326
13327                 sense = &msg.scsi.sense_data;
13328                 sks[0] = SSD_SCS_VALID;
13329                 sks[1] = (retry_count >> 8) & 0xff;
13330                 sks[2] = retry_count & 0xff;
13331
13332                 /* "Internal target failure" */
13333                 scsi_set_sense_data(sense,
13334                                     /*sense_format*/ SSD_TYPE_NONE,
13335                                     /*current_error*/ 1,
13336                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13337                                     /*asc*/ 0x44,
13338                                     /*ascq*/ 0x00,
13339                                     /*type*/ SSD_ELEM_SKS,
13340                                     /*size*/ sizeof(sks),
13341                                     /*data*/ sks,
13342                                     SSD_ELEM_NONE);
13343
13344                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13345                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13346                         ctl_failover_io(io, /*have_lock*/ 1);
13347                         return;
13348                 }
13349
13350                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13351                     CTL_HA_STATUS_SUCCESS) {
13352                         /* XXX KDM what to do if this fails? */
13353                 }
13354                 return;
13355         }
13356         
13357 }
13358
13359 static int
13360 ctl_process_done(union ctl_io *io)
13361 {
13362         struct ctl_lun *lun;
13363         struct ctl_softc *ctl_softc;
13364         void (*fe_done)(union ctl_io *io);
13365         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13366
13367         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13368
13369         fe_done =
13370             control_softc->ctl_ports[targ_port]->fe_done;
13371
13372 #ifdef CTL_TIME_IO
13373         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13374                 char str[256];
13375                 char path_str[64];
13376                 struct sbuf sb;
13377
13378                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13379                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13380
13381                 sbuf_cat(&sb, path_str);
13382                 switch (io->io_hdr.io_type) {
13383                 case CTL_IO_SCSI:
13384                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13385                         sbuf_printf(&sb, "\n");
13386                         sbuf_cat(&sb, path_str);
13387                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13388                                     io->scsiio.tag_num, io->scsiio.tag_type);
13389                         break;
13390                 case CTL_IO_TASK:
13391                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13392                                     "Tag Type: %d\n", io->taskio.task_action,
13393                                     io->taskio.tag_num, io->taskio.tag_type);
13394                         break;
13395                 default:
13396                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13397                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13398                         break;
13399                 }
13400                 sbuf_cat(&sb, path_str);
13401                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13402                             (intmax_t)time_uptime - io->io_hdr.start_time);
13403                 sbuf_finish(&sb);
13404                 printf("%s", sbuf_data(&sb));
13405         }
13406 #endif /* CTL_TIME_IO */
13407
13408         switch (io->io_hdr.io_type) {
13409         case CTL_IO_SCSI:
13410                 break;
13411         case CTL_IO_TASK:
13412                 if (bootverbose || verbose > 0)
13413                         ctl_io_error_print(io, NULL);
13414                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13415                         ctl_free_io(io);
13416                 else
13417                         fe_done(io);
13418                 return (CTL_RETVAL_COMPLETE);
13419                 break;
13420         default:
13421                 printf("ctl_process_done: invalid io type %d\n",
13422                        io->io_hdr.io_type);
13423                 panic("ctl_process_done: invalid io type %d\n",
13424                       io->io_hdr.io_type);
13425                 break; /* NOTREACHED */
13426         }
13427
13428         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13429         if (lun == NULL) {
13430                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13431                                  io->io_hdr.nexus.targ_mapped_lun));
13432                 fe_done(io);
13433                 goto bailout;
13434         }
13435         ctl_softc = lun->ctl_softc;
13436
13437         mtx_lock(&lun->lun_lock);
13438
13439         /*
13440          * Check to see if we have any errors to inject here.  We only
13441          * inject errors for commands that don't already have errors set.
13442          */
13443         if ((STAILQ_FIRST(&lun->error_list) != NULL)
13444          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13445                 ctl_inject_error(lun, io);
13446
13447         /*
13448          * XXX KDM how do we treat commands that aren't completed
13449          * successfully?
13450          *
13451          * XXX KDM should we also track I/O latency?
13452          */
13453         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13454             io->io_hdr.io_type == CTL_IO_SCSI) {
13455 #ifdef CTL_TIME_IO
13456                 struct bintime cur_bt;
13457 #endif
13458                 int type;
13459
13460                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13461                     CTL_FLAG_DATA_IN)
13462                         type = CTL_STATS_READ;
13463                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13464                     CTL_FLAG_DATA_OUT)
13465                         type = CTL_STATS_WRITE;
13466                 else
13467                         type = CTL_STATS_NO_IO;
13468
13469                 lun->stats.ports[targ_port].bytes[type] +=
13470                     io->scsiio.kern_total_len;
13471                 lun->stats.ports[targ_port].operations[type]++;
13472 #ifdef CTL_TIME_IO
13473                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13474                    &io->io_hdr.dma_bt);
13475                 lun->stats.ports[targ_port].num_dmas[type] +=
13476                     io->io_hdr.num_dmas;
13477                 getbintime(&cur_bt);
13478                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13479                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13480 #endif
13481         }
13482
13483         /*
13484          * Remove this from the OOA queue.
13485          */
13486         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13487
13488         /*
13489          * Run through the blocked queue on this LUN and see if anything
13490          * has become unblocked, now that this transaction is done.
13491          */
13492         ctl_check_blocked(lun);
13493
13494         /*
13495          * If the LUN has been invalidated, free it if there is nothing
13496          * left on its OOA queue.
13497          */
13498         if ((lun->flags & CTL_LUN_INVALID)
13499          && TAILQ_EMPTY(&lun->ooa_queue)) {
13500                 mtx_unlock(&lun->lun_lock);
13501                 mtx_lock(&ctl_softc->ctl_lock);
13502                 ctl_free_lun(lun);
13503                 mtx_unlock(&ctl_softc->ctl_lock);
13504         } else
13505                 mtx_unlock(&lun->lun_lock);
13506
13507         /*
13508          * If this command has been aborted, make sure we set the status
13509          * properly.  The FETD is responsible for freeing the I/O and doing
13510          * whatever it needs to do to clean up its state.
13511          */
13512         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13513                 ctl_set_task_aborted(&io->scsiio);
13514
13515         /*
13516          * We print out status for every task management command.  For SCSI
13517          * commands, we filter out any unit attention errors; they happen
13518          * on every boot, and would clutter up the log.  Note:  task
13519          * management commands aren't printed here, they are printed above,
13520          * since they should never even make it down here.
13521          */
13522         switch (io->io_hdr.io_type) {
13523         case CTL_IO_SCSI: {
13524                 int error_code, sense_key, asc, ascq;
13525
13526                 sense_key = 0;
13527
13528                 if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13529                  && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13530                         /*
13531                          * Since this is just for printing, no need to
13532                          * show errors here.
13533                          */
13534                         scsi_extract_sense_len(&io->scsiio.sense_data,
13535                                                io->scsiio.sense_len,
13536                                                &error_code,
13537                                                &sense_key,
13538                                                &asc,
13539                                                &ascq,
13540                                                /*show_errors*/ 0);
13541                 }
13542
13543                 if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13544                  && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13545                   || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13546                   || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13547
13548                         if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13549                                 ctl_softc->skipped_prints++;
13550                         } else {
13551                                 uint32_t skipped_prints;
13552
13553                                 skipped_prints = ctl_softc->skipped_prints;
13554
13555                                 ctl_softc->skipped_prints = 0;
13556                                 ctl_softc->last_print_jiffies = time_uptime;
13557
13558                                 if (skipped_prints > 0) {
13559 #ifdef NEEDTOPORT
13560                                         csevent_log(CSC_CTL | CSC_SHELF_SW |
13561                                             CTL_ERROR_REPORT,
13562                                             csevent_LogType_Trace,
13563                                             csevent_Severity_Information,
13564                                             csevent_AlertLevel_Green,
13565                                             csevent_FRU_Firmware,
13566                                             csevent_FRU_Unknown,
13567                                             "High CTL error volume, %d prints "
13568                                             "skipped", skipped_prints);
13569 #endif
13570                                 }
13571                                 if (bootverbose || verbose > 0)
13572                                         ctl_io_error_print(io, NULL);
13573                         }
13574                 }
13575                 break;
13576         }
13577         case CTL_IO_TASK:
13578                 if (bootverbose || verbose > 0)
13579                         ctl_io_error_print(io, NULL);
13580                 break;
13581         default:
13582                 break;
13583         }
13584
13585         /*
13586          * Tell the FETD or the other shelf controller we're done with this
13587          * command.  Note that only SCSI commands get to this point.  Task
13588          * management commands are completed above.
13589          *
13590          * We only send status to the other controller if we're in XFER
13591          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13592          * received the I/O (from CTL's perspective), and so the status is
13593          * generated there.
13594          * 
13595          * XXX KDM if we hold the lock here, we could cause a deadlock
13596          * if the frontend comes back in in this context to queue
13597          * something.
13598          */
13599         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13600          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13601                 union ctl_ha_msg msg;
13602
13603                 memset(&msg, 0, sizeof(msg));
13604                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13605                 msg.hdr.original_sc = io->io_hdr.original_sc;
13606                 msg.hdr.nexus = io->io_hdr.nexus;
13607                 msg.hdr.status = io->io_hdr.status;
13608                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13609                 msg.scsi.tag_num = io->scsiio.tag_num;
13610                 msg.scsi.tag_type = io->scsiio.tag_type;
13611                 msg.scsi.sense_len = io->scsiio.sense_len;
13612                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13613                 msg.scsi.residual = io->scsiio.residual;
13614                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13615                        sizeof(io->scsiio.sense_data));
13616                 /*
13617                  * We copy this whether or not this is an I/O-related
13618                  * command.  Otherwise, we'd have to go and check to see
13619                  * whether it's a read/write command, and it really isn't
13620                  * worth it.
13621                  */
13622                 memcpy(&msg.scsi.lbalen,
13623                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13624                        sizeof(msg.scsi.lbalen));
13625
13626                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13627                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13628                         /* XXX do something here */
13629                 }
13630
13631                 ctl_free_io(io);
13632         } else 
13633                 fe_done(io);
13634
13635 bailout:
13636
13637         return (CTL_RETVAL_COMPLETE);
13638 }
13639
13640 /*
13641  * Front end should call this if it doesn't do autosense.  When the request
13642  * sense comes back in from the initiator, we'll dequeue this and send it.
13643  */
13644 int
13645 ctl_queue_sense(union ctl_io *io)
13646 {
13647         struct ctl_lun *lun;
13648         struct ctl_softc *ctl_softc;
13649         uint32_t initidx, targ_lun;
13650
13651         ctl_softc = control_softc;
13652
13653         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13654
13655         /*
13656          * LUN lookup will likely move to the ctl_work_thread() once we
13657          * have our new queueing infrastructure (that doesn't put things on
13658          * a per-LUN queue initially).  That is so that we can handle
13659          * things like an INQUIRY to a LUN that we don't have enabled.  We
13660          * can't deal with that right now.
13661          */
13662         mtx_lock(&ctl_softc->ctl_lock);
13663
13664         /*
13665          * If we don't have a LUN for this, just toss the sense
13666          * information.
13667          */
13668         targ_lun = io->io_hdr.nexus.targ_lun;
13669         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13670         if ((targ_lun < CTL_MAX_LUNS)
13671          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13672                 lun = ctl_softc->ctl_luns[targ_lun];
13673         else
13674                 goto bailout;
13675
13676         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13677
13678         mtx_lock(&lun->lun_lock);
13679         /*
13680          * Already have CA set for this LUN...toss the sense information.
13681          */
13682         if (ctl_is_set(lun->have_ca, initidx)) {
13683                 mtx_unlock(&lun->lun_lock);
13684                 goto bailout;
13685         }
13686
13687         memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
13688                ctl_min(sizeof(lun->pending_sense[initidx].sense),
13689                sizeof(io->scsiio.sense_data)));
13690         ctl_set_mask(lun->have_ca, initidx);
13691         mtx_unlock(&lun->lun_lock);
13692
13693 bailout:
13694         mtx_unlock(&ctl_softc->ctl_lock);
13695
13696         ctl_free_io(io);
13697
13698         return (CTL_RETVAL_COMPLETE);
13699 }
13700
13701 /*
13702  * Primary command inlet from frontend ports.  All SCSI and task I/O
13703  * requests must go through this function.
13704  */
13705 int
13706 ctl_queue(union ctl_io *io)
13707 {
13708         struct ctl_softc *ctl_softc;
13709
13710         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13711
13712         ctl_softc = control_softc;
13713
13714 #ifdef CTL_TIME_IO
13715         io->io_hdr.start_time = time_uptime;
13716         getbintime(&io->io_hdr.start_bt);
13717 #endif /* CTL_TIME_IO */
13718
13719         /* Map FE-specific LUN ID into global one. */
13720         io->io_hdr.nexus.targ_mapped_lun =
13721             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13722
13723         switch (io->io_hdr.io_type) {
13724         case CTL_IO_SCSI:
13725         case CTL_IO_TASK:
13726                 ctl_enqueue_incoming(io);
13727                 break;
13728         default:
13729                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13730                 return (EINVAL);
13731         }
13732
13733         return (CTL_RETVAL_COMPLETE);
13734 }
13735
13736 #ifdef CTL_IO_DELAY
13737 static void
13738 ctl_done_timer_wakeup(void *arg)
13739 {
13740         union ctl_io *io;
13741
13742         io = (union ctl_io *)arg;
13743         ctl_done(io);
13744 }
13745 #endif /* CTL_IO_DELAY */
13746
13747 void
13748 ctl_done(union ctl_io *io)
13749 {
13750         struct ctl_softc *ctl_softc;
13751
13752         ctl_softc = control_softc;
13753
13754         /*
13755          * Enable this to catch duplicate completion issues.
13756          */
13757 #if 0
13758         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13759                 printf("%s: type %d msg %d cdb %x iptl: "
13760                        "%d:%d:%d:%d tag 0x%04x "
13761                        "flag %#x status %x\n",
13762                         __func__,
13763                         io->io_hdr.io_type,
13764                         io->io_hdr.msg_type,
13765                         io->scsiio.cdb[0],
13766                         io->io_hdr.nexus.initid.id,
13767                         io->io_hdr.nexus.targ_port,
13768                         io->io_hdr.nexus.targ_target.id,
13769                         io->io_hdr.nexus.targ_lun,
13770                         (io->io_hdr.io_type ==
13771                         CTL_IO_TASK) ?
13772                         io->taskio.tag_num :
13773                         io->scsiio.tag_num,
13774                         io->io_hdr.flags,
13775                         io->io_hdr.status);
13776         } else
13777                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13778 #endif
13779
13780         /*
13781          * This is an internal copy of an I/O, and should not go through
13782          * the normal done processing logic.
13783          */
13784         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13785                 return;
13786
13787         /*
13788          * We need to send a msg to the serializing shelf to finish the IO
13789          * as well.  We don't send a finish message to the other shelf if
13790          * this is a task management command.  Task management commands
13791          * aren't serialized in the OOA queue, but rather just executed on
13792          * both shelf controllers for commands that originated on that
13793          * controller.
13794          */
13795         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13796          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13797                 union ctl_ha_msg msg_io;
13798
13799                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13800                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13801                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13802                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13803                 }
13804                 /* continue on to finish IO */
13805         }
13806 #ifdef CTL_IO_DELAY
13807         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13808                 struct ctl_lun *lun;
13809
13810                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13811
13812                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13813         } else {
13814                 struct ctl_lun *lun;
13815
13816                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13817
13818                 if ((lun != NULL)
13819                  && (lun->delay_info.done_delay > 0)) {
13820                         struct callout *callout;
13821
13822                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13823                         callout_init(callout, /*mpsafe*/ 1);
13824                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13825                         callout_reset(callout,
13826                                       lun->delay_info.done_delay * hz,
13827                                       ctl_done_timer_wakeup, io);
13828                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13829                                 lun->delay_info.done_delay = 0;
13830                         return;
13831                 }
13832         }
13833 #endif /* CTL_IO_DELAY */
13834
13835         ctl_enqueue_done(io);
13836 }
13837
13838 int
13839 ctl_isc(struct ctl_scsiio *ctsio)
13840 {
13841         struct ctl_lun *lun;
13842         int retval;
13843
13844         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13845
13846         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13847
13848         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13849
13850         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13851
13852         return (retval);
13853 }
13854
13855
13856 static void
13857 ctl_work_thread(void *arg)
13858 {
13859         struct ctl_thread *thr = (struct ctl_thread *)arg;
13860         struct ctl_softc *softc = thr->ctl_softc;
13861         union ctl_io *io;
13862         int retval;
13863
13864         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13865
13866         for (;;) {
13867                 retval = 0;
13868
13869                 /*
13870                  * We handle the queues in this order:
13871                  * - ISC
13872                  * - done queue (to free up resources, unblock other commands)
13873                  * - RtR queue
13874                  * - incoming queue
13875                  *
13876                  * If those queues are empty, we break out of the loop and
13877                  * go to sleep.
13878                  */
13879                 mtx_lock(&thr->queue_lock);
13880                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13881                 if (io != NULL) {
13882                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13883                         mtx_unlock(&thr->queue_lock);
13884                         ctl_handle_isc(io);
13885                         continue;
13886                 }
13887                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13888                 if (io != NULL) {
13889                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13890                         /* clear any blocked commands, call fe_done */
13891                         mtx_unlock(&thr->queue_lock);
13892                         retval = ctl_process_done(io);
13893                         continue;
13894                 }
13895                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13896                 if (io != NULL) {
13897                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13898                         mtx_unlock(&thr->queue_lock);
13899                         if (io->io_hdr.io_type == CTL_IO_TASK)
13900                                 ctl_run_task(io);
13901                         else
13902                                 ctl_scsiio_precheck(softc, &io->scsiio);
13903                         continue;
13904                 }
13905                 if (!ctl_pause_rtr) {
13906                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13907                         if (io != NULL) {
13908                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13909                                 mtx_unlock(&thr->queue_lock);
13910                                 retval = ctl_scsiio(&io->scsiio);
13911                                 if (retval != CTL_RETVAL_COMPLETE)
13912                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13913                                 continue;
13914                         }
13915                 }
13916
13917                 /* Sleep until we have something to do. */
13918                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13919         }
13920 }
13921
13922 static void
13923 ctl_lun_thread(void *arg)
13924 {
13925         struct ctl_softc *softc = (struct ctl_softc *)arg;
13926         struct ctl_be_lun *be_lun;
13927         int retval;
13928
13929         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13930
13931         for (;;) {
13932                 retval = 0;
13933                 mtx_lock(&softc->ctl_lock);
13934                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13935                 if (be_lun != NULL) {
13936                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13937                         mtx_unlock(&softc->ctl_lock);
13938                         ctl_create_lun(be_lun);
13939                         continue;
13940                 }
13941
13942                 /* Sleep until we have something to do. */
13943                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13944                     PDROP | PRIBIO, "-", 0);
13945         }
13946 }
13947
13948 static void
13949 ctl_enqueue_incoming(union ctl_io *io)
13950 {
13951         struct ctl_softc *softc = control_softc;
13952         struct ctl_thread *thr;
13953         u_int idx;
13954
13955         idx = (io->io_hdr.nexus.targ_port * 127 +
13956                io->io_hdr.nexus.initid.id) % worker_threads;
13957         thr = &softc->threads[idx];
13958         mtx_lock(&thr->queue_lock);
13959         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13960         mtx_unlock(&thr->queue_lock);
13961         wakeup(thr);
13962 }
13963
13964 static void
13965 ctl_enqueue_rtr(union ctl_io *io)
13966 {
13967         struct ctl_softc *softc = control_softc;
13968         struct ctl_thread *thr;
13969
13970         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13971         mtx_lock(&thr->queue_lock);
13972         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13973         mtx_unlock(&thr->queue_lock);
13974         wakeup(thr);
13975 }
13976
13977 static void
13978 ctl_enqueue_done(union ctl_io *io)
13979 {
13980         struct ctl_softc *softc = control_softc;
13981         struct ctl_thread *thr;
13982
13983         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13984         mtx_lock(&thr->queue_lock);
13985         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13986         mtx_unlock(&thr->queue_lock);
13987         wakeup(thr);
13988 }
13989
13990 static void
13991 ctl_enqueue_isc(union ctl_io *io)
13992 {
13993         struct ctl_softc *softc = control_softc;
13994         struct ctl_thread *thr;
13995
13996         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13997         mtx_lock(&thr->queue_lock);
13998         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13999         mtx_unlock(&thr->queue_lock);
14000         wakeup(thr);
14001 }
14002
14003 /* Initialization and failover */
14004
14005 void
14006 ctl_init_isc_msg(void)
14007 {
14008         printf("CTL: Still calling this thing\n");
14009 }
14010
14011 /*
14012  * Init component
14013  *      Initializes component into configuration defined by bootMode
14014  *      (see hasc-sv.c)
14015  *      returns hasc_Status:
14016  *              OK
14017  *              ERROR - fatal error
14018  */
14019 static ctl_ha_comp_status
14020 ctl_isc_init(struct ctl_ha_component *c)
14021 {
14022         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14023
14024         c->status = ret;
14025         return ret;
14026 }
14027
14028 /* Start component
14029  *      Starts component in state requested. If component starts successfully,
14030  *      it must set its own state to the requestrd state
14031  *      When requested state is HASC_STATE_HA, the component may refine it
14032  *      by adding _SLAVE or _MASTER flags.
14033  *      Currently allowed state transitions are:
14034  *      UNKNOWN->HA             - initial startup
14035  *      UNKNOWN->SINGLE - initial startup when no parter detected
14036  *      HA->SINGLE              - failover
14037  * returns ctl_ha_comp_status:
14038  *              OK      - component successfully started in requested state
14039  *              FAILED  - could not start the requested state, failover may
14040  *                        be possible
14041  *              ERROR   - fatal error detected, no future startup possible
14042  */
14043 static ctl_ha_comp_status
14044 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14045 {
14046         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14047
14048         printf("%s: go\n", __func__);
14049
14050         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14051         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14052                 ctl_is_single = 0;
14053                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14054                     != CTL_HA_STATUS_SUCCESS) {
14055                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14056                         ret = CTL_HA_COMP_STATUS_ERROR;
14057                 }
14058         } else if (CTL_HA_STATE_IS_HA(c->state)
14059                 && CTL_HA_STATE_IS_SINGLE(state)){
14060                 // HA->SINGLE transition
14061                 ctl_failover();
14062                 ctl_is_single = 1;
14063         } else {
14064                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14065                        c->state, state);
14066                 ret = CTL_HA_COMP_STATUS_ERROR;
14067         }
14068         if (CTL_HA_STATE_IS_SINGLE(state))
14069                 ctl_is_single = 1;
14070
14071         c->state = state;
14072         c->status = ret;
14073         return ret;
14074 }
14075
14076 /*
14077  * Quiesce component
14078  * The component must clear any error conditions (set status to OK) and
14079  * prepare itself to another Start call
14080  * returns ctl_ha_comp_status:
14081  *      OK
14082  *      ERROR
14083  */
14084 static ctl_ha_comp_status
14085 ctl_isc_quiesce(struct ctl_ha_component *c)
14086 {
14087         int ret = CTL_HA_COMP_STATUS_OK;
14088
14089         ctl_pause_rtr = 1;
14090         c->status = ret;
14091         return ret;
14092 }
14093
14094 struct ctl_ha_component ctl_ha_component_ctlisc =
14095 {
14096         .name = "CTL ISC",
14097         .state = CTL_HA_STATE_UNKNOWN,
14098         .init = ctl_isc_init,
14099         .start = ctl_isc_start,
14100         .quiesce = ctl_isc_quiesce
14101 };
14102
14103 /*
14104  *  vim: ts=8
14105  */