]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r268421:
[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 *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         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4482             M_CTL, M_WAITOK | M_ZERO);
4483         lun->lun_devid->len = len;
4484         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4485         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4486         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4487         desc->length = idlen1;
4488         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4489         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4490         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4491                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4492         } else {
4493                 strncpy(t10id->vendor, vendor,
4494                     min(sizeof(t10id->vendor), strlen(vendor)));
4495         }
4496         strncpy((char *)t10id->vendor_spec_id,
4497             (char *)be_lun->device_id, devidlen);
4498         if (scsiname != NULL) {
4499                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4500                     desc->length);
4501                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4502                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4503                     SVPD_ID_TYPE_SCSI_NAME;
4504                 desc->length = idlen2;
4505                 strlcpy(desc->identifier, scsiname, idlen2);
4506         }
4507
4508         mtx_lock(&ctl_softc->ctl_lock);
4509         /*
4510          * See if the caller requested a particular LUN number.  If so, see
4511          * if it is available.  Otherwise, allocate the first available LUN.
4512          */
4513         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4514                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4515                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4516                         mtx_unlock(&ctl_softc->ctl_lock);
4517                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4518                                 printf("ctl: requested LUN ID %d is higher "
4519                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4520                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4521                         } else {
4522                                 /*
4523                                  * XXX KDM return an error, or just assign
4524                                  * another LUN ID in this case??
4525                                  */
4526                                 printf("ctl: requested LUN ID %d is already "
4527                                        "in use\n", be_lun->req_lun_id);
4528                         }
4529                         if (lun->flags & CTL_LUN_MALLOCED)
4530                                 free(lun, M_CTL);
4531                         be_lun->lun_config_status(be_lun->be_lun,
4532                                                   CTL_LUN_CONFIG_FAILURE);
4533                         return (ENOSPC);
4534                 }
4535                 lun_number = be_lun->req_lun_id;
4536         } else {
4537                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4538                 if (lun_number == -1) {
4539                         mtx_unlock(&ctl_softc->ctl_lock);
4540                         printf("ctl: can't allocate LUN on target %ju, out of "
4541                                "LUNs\n", (uintmax_t)target_id.id);
4542                         if (lun->flags & CTL_LUN_MALLOCED)
4543                                 free(lun, M_CTL);
4544                         be_lun->lun_config_status(be_lun->be_lun,
4545                                                   CTL_LUN_CONFIG_FAILURE);
4546                         return (ENOSPC);
4547                 }
4548         }
4549         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4550
4551         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4552         lun->target = target_id;
4553         lun->lun = lun_number;
4554         lun->be_lun = be_lun;
4555         /*
4556          * The processor LUN is always enabled.  Disk LUNs come on line
4557          * disabled, and must be enabled by the backend.
4558          */
4559         lun->flags |= CTL_LUN_DISABLED;
4560         lun->backend = be_lun->be;
4561         be_lun->ctl_lun = lun;
4562         be_lun->lun_id = lun_number;
4563         atomic_add_int(&be_lun->be->num_luns, 1);
4564         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4565                 lun->flags |= CTL_LUN_STOPPED;
4566
4567         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4568                 lun->flags |= CTL_LUN_INOPERABLE;
4569
4570         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4571                 lun->flags |= CTL_LUN_PRIMARY_SC;
4572
4573         lun->ctl_softc = ctl_softc;
4574         TAILQ_INIT(&lun->ooa_queue);
4575         TAILQ_INIT(&lun->blocked_queue);
4576         STAILQ_INIT(&lun->error_list);
4577
4578         /*
4579          * Initialize the mode page index.
4580          */
4581         ctl_init_page_index(lun);
4582
4583         /*
4584          * Set the poweron UA for all initiators on this LUN only.
4585          */
4586         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4587                 lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4588
4589         /*
4590          * Now, before we insert this lun on the lun list, set the lun
4591          * inventory changed UA for all other luns.
4592          */
4593         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4594                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4595                         nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4596                 }
4597         }
4598
4599         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4600
4601         ctl_softc->ctl_luns[lun_number] = lun;
4602
4603         ctl_softc->num_luns++;
4604
4605         /* Setup statistics gathering */
4606         lun->stats.device_type = be_lun->lun_type;
4607         lun->stats.lun_number = lun_number;
4608         if (lun->stats.device_type == T_DIRECT)
4609                 lun->stats.blocksize = be_lun->blocksize;
4610         else
4611                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4612         for (i = 0;i < CTL_MAX_PORTS;i++)
4613                 lun->stats.ports[i].targ_port = i;
4614
4615         mtx_unlock(&ctl_softc->ctl_lock);
4616
4617         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4618
4619         /*
4620          * Run through each registered FETD and bring it online if it isn't
4621          * already.  Enable the target ID if it hasn't been enabled, and
4622          * enable this particular LUN.
4623          */
4624         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4625                 int retval;
4626
4627                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4628                 if (retval != 0) {
4629                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4630                                "%d for lun_enable on target %ju lun %d\n",
4631                                port->port_name, port->targ_port, retval,
4632                                (uintmax_t)target_id.id, lun_number);
4633                 } else
4634                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4635         }
4636         return (0);
4637 }
4638
4639 /*
4640  * Delete a LUN.
4641  * Assumptions:
4642  * - LUN has already been marked invalid and any pending I/O has been taken
4643  *   care of.
4644  */
4645 static int
4646 ctl_free_lun(struct ctl_lun *lun)
4647 {
4648         struct ctl_softc *softc;
4649 #if 0
4650         struct ctl_port *port;
4651 #endif
4652         struct ctl_lun *nlun;
4653         int i;
4654
4655         softc = lun->ctl_softc;
4656
4657         mtx_assert(&softc->ctl_lock, MA_OWNED);
4658
4659         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4660
4661         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4662
4663         softc->ctl_luns[lun->lun] = NULL;
4664
4665         if (!TAILQ_EMPTY(&lun->ooa_queue))
4666                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4667
4668         softc->num_luns--;
4669
4670         /*
4671          * XXX KDM this scheme only works for a single target/multiple LUN
4672          * setup.  It needs to be revamped for a multiple target scheme.
4673          *
4674          * XXX KDM this results in port->lun_disable() getting called twice,
4675          * once when ctl_disable_lun() is called, and a second time here.
4676          * We really need to re-think the LUN disable semantics.  There
4677          * should probably be several steps/levels to LUN removal:
4678          *  - disable
4679          *  - invalidate
4680          *  - free
4681          *
4682          * Right now we only have a disable method when communicating to
4683          * the front end ports, at least for individual LUNs.
4684          */
4685 #if 0
4686         STAILQ_FOREACH(port, &softc->port_list, links) {
4687                 int retval;
4688
4689                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4690                                          lun->lun);
4691                 if (retval != 0) {
4692                         printf("ctl_free_lun: FETD %s port %d returned error "
4693                                "%d for lun_disable on target %ju lun %jd\n",
4694                                port->port_name, port->targ_port, retval,
4695                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4696                 }
4697
4698                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4699                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4700
4701                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4702                         if (retval != 0) {
4703                                 printf("ctl_free_lun: FETD %s port %d "
4704                                        "returned error %d for targ_disable on "
4705                                        "target %ju\n", port->port_name,
4706                                        port->targ_port, retval,
4707                                        (uintmax_t)lun->target.id);
4708                         } else
4709                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4710
4711                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4712                                 continue;
4713
4714 #if 0
4715                         port->port_offline(port->onoff_arg);
4716                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4717 #endif
4718                 }
4719         }
4720 #endif
4721
4722         /*
4723          * Tell the backend to free resources, if this LUN has a backend.
4724          */
4725         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4726         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4727
4728         mtx_destroy(&lun->lun_lock);
4729         free(lun->lun_devid, M_CTL);
4730         if (lun->flags & CTL_LUN_MALLOCED)
4731                 free(lun, M_CTL);
4732
4733         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4734                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4735                         nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4736                 }
4737         }
4738
4739         return (0);
4740 }
4741
4742 static void
4743 ctl_create_lun(struct ctl_be_lun *be_lun)
4744 {
4745         struct ctl_softc *ctl_softc;
4746
4747         ctl_softc = control_softc;
4748
4749         /*
4750          * ctl_alloc_lun() should handle all potential failure cases.
4751          */
4752         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4753 }
4754
4755 int
4756 ctl_add_lun(struct ctl_be_lun *be_lun)
4757 {
4758         struct ctl_softc *ctl_softc = control_softc;
4759
4760         mtx_lock(&ctl_softc->ctl_lock);
4761         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4762         mtx_unlock(&ctl_softc->ctl_lock);
4763         wakeup(&ctl_softc->pending_lun_queue);
4764
4765         return (0);
4766 }
4767
4768 int
4769 ctl_enable_lun(struct ctl_be_lun *be_lun)
4770 {
4771         struct ctl_softc *ctl_softc;
4772         struct ctl_port *port, *nport;
4773         struct ctl_lun *lun;
4774         int retval;
4775
4776         ctl_softc = control_softc;
4777
4778         lun = (struct ctl_lun *)be_lun->ctl_lun;
4779
4780         mtx_lock(&ctl_softc->ctl_lock);
4781         mtx_lock(&lun->lun_lock);
4782         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4783                 /*
4784                  * eh?  Why did we get called if the LUN is already
4785                  * enabled?
4786                  */
4787                 mtx_unlock(&lun->lun_lock);
4788                 mtx_unlock(&ctl_softc->ctl_lock);
4789                 return (0);
4790         }
4791         lun->flags &= ~CTL_LUN_DISABLED;
4792         mtx_unlock(&lun->lun_lock);
4793
4794         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4795                 nport = STAILQ_NEXT(port, links);
4796
4797                 /*
4798                  * Drop the lock while we call the FETD's enable routine.
4799                  * This can lead to a callback into CTL (at least in the
4800                  * case of the internal initiator frontend.
4801                  */
4802                 mtx_unlock(&ctl_softc->ctl_lock);
4803                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4804                 mtx_lock(&ctl_softc->ctl_lock);
4805                 if (retval != 0) {
4806                         printf("%s: FETD %s port %d returned error "
4807                                "%d for lun_enable on target %ju lun %jd\n",
4808                                __func__, port->port_name, port->targ_port, retval,
4809                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4810                 }
4811 #if 0
4812                  else {
4813             /* NOTE:  TODO:  why does lun enable affect port status? */
4814                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4815                 }
4816 #endif
4817         }
4818
4819         mtx_unlock(&ctl_softc->ctl_lock);
4820
4821         return (0);
4822 }
4823
4824 int
4825 ctl_disable_lun(struct ctl_be_lun *be_lun)
4826 {
4827         struct ctl_softc *ctl_softc;
4828         struct ctl_port *port;
4829         struct ctl_lun *lun;
4830         int retval;
4831
4832         ctl_softc = control_softc;
4833
4834         lun = (struct ctl_lun *)be_lun->ctl_lun;
4835
4836         mtx_lock(&ctl_softc->ctl_lock);
4837         mtx_lock(&lun->lun_lock);
4838         if (lun->flags & CTL_LUN_DISABLED) {
4839                 mtx_unlock(&lun->lun_lock);
4840                 mtx_unlock(&ctl_softc->ctl_lock);
4841                 return (0);
4842         }
4843         lun->flags |= CTL_LUN_DISABLED;
4844         mtx_unlock(&lun->lun_lock);
4845
4846         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4847                 mtx_unlock(&ctl_softc->ctl_lock);
4848                 /*
4849                  * Drop the lock before we call the frontend's disable
4850                  * routine, to avoid lock order reversals.
4851                  *
4852                  * XXX KDM what happens if the frontend list changes while
4853                  * we're traversing it?  It's unlikely, but should be handled.
4854                  */
4855                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4856                                          lun->lun);
4857                 mtx_lock(&ctl_softc->ctl_lock);
4858                 if (retval != 0) {
4859                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4860                                "%d for lun_disable on target %ju lun %jd\n",
4861                                port->port_name, port->targ_port, retval,
4862                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4863                 }
4864         }
4865
4866         mtx_unlock(&ctl_softc->ctl_lock);
4867
4868         return (0);
4869 }
4870
4871 int
4872 ctl_start_lun(struct ctl_be_lun *be_lun)
4873 {
4874         struct ctl_softc *ctl_softc;
4875         struct ctl_lun *lun;
4876
4877         ctl_softc = control_softc;
4878
4879         lun = (struct ctl_lun *)be_lun->ctl_lun;
4880
4881         mtx_lock(&lun->lun_lock);
4882         lun->flags &= ~CTL_LUN_STOPPED;
4883         mtx_unlock(&lun->lun_lock);
4884
4885         return (0);
4886 }
4887
4888 int
4889 ctl_stop_lun(struct ctl_be_lun *be_lun)
4890 {
4891         struct ctl_softc *ctl_softc;
4892         struct ctl_lun *lun;
4893
4894         ctl_softc = control_softc;
4895
4896         lun = (struct ctl_lun *)be_lun->ctl_lun;
4897
4898         mtx_lock(&lun->lun_lock);
4899         lun->flags |= CTL_LUN_STOPPED;
4900         mtx_unlock(&lun->lun_lock);
4901
4902         return (0);
4903 }
4904
4905 int
4906 ctl_lun_offline(struct ctl_be_lun *be_lun)
4907 {
4908         struct ctl_softc *ctl_softc;
4909         struct ctl_lun *lun;
4910
4911         ctl_softc = control_softc;
4912
4913         lun = (struct ctl_lun *)be_lun->ctl_lun;
4914
4915         mtx_lock(&lun->lun_lock);
4916         lun->flags |= CTL_LUN_OFFLINE;
4917         mtx_unlock(&lun->lun_lock);
4918
4919         return (0);
4920 }
4921
4922 int
4923 ctl_lun_online(struct ctl_be_lun *be_lun)
4924 {
4925         struct ctl_softc *ctl_softc;
4926         struct ctl_lun *lun;
4927
4928         ctl_softc = control_softc;
4929
4930         lun = (struct ctl_lun *)be_lun->ctl_lun;
4931
4932         mtx_lock(&lun->lun_lock);
4933         lun->flags &= ~CTL_LUN_OFFLINE;
4934         mtx_unlock(&lun->lun_lock);
4935
4936         return (0);
4937 }
4938
4939 int
4940 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4941 {
4942         struct ctl_softc *ctl_softc;
4943         struct ctl_lun *lun;
4944
4945         ctl_softc = control_softc;
4946
4947         lun = (struct ctl_lun *)be_lun->ctl_lun;
4948
4949         mtx_lock(&lun->lun_lock);
4950
4951         /*
4952          * The LUN needs to be disabled before it can be marked invalid.
4953          */
4954         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4955                 mtx_unlock(&lun->lun_lock);
4956                 return (-1);
4957         }
4958         /*
4959          * Mark the LUN invalid.
4960          */
4961         lun->flags |= CTL_LUN_INVALID;
4962
4963         /*
4964          * If there is nothing in the OOA queue, go ahead and free the LUN.
4965          * If we have something in the OOA queue, we'll free it when the
4966          * last I/O completes.
4967          */
4968         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4969                 mtx_unlock(&lun->lun_lock);
4970                 mtx_lock(&ctl_softc->ctl_lock);
4971                 ctl_free_lun(lun);
4972                 mtx_unlock(&ctl_softc->ctl_lock);
4973         } else
4974                 mtx_unlock(&lun->lun_lock);
4975
4976         return (0);
4977 }
4978
4979 int
4980 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4981 {
4982         struct ctl_softc *ctl_softc;
4983         struct ctl_lun *lun;
4984
4985         ctl_softc = control_softc;
4986         lun = (struct ctl_lun *)be_lun->ctl_lun;
4987
4988         mtx_lock(&lun->lun_lock);
4989         lun->flags |= CTL_LUN_INOPERABLE;
4990         mtx_unlock(&lun->lun_lock);
4991
4992         return (0);
4993 }
4994
4995 int
4996 ctl_lun_operable(struct ctl_be_lun *be_lun)
4997 {
4998         struct ctl_softc *ctl_softc;
4999         struct ctl_lun *lun;
5000
5001         ctl_softc = control_softc;
5002         lun = (struct ctl_lun *)be_lun->ctl_lun;
5003
5004         mtx_lock(&lun->lun_lock);
5005         lun->flags &= ~CTL_LUN_INOPERABLE;
5006         mtx_unlock(&lun->lun_lock);
5007
5008         return (0);
5009 }
5010
5011 int
5012 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5013                    int lock)
5014 {
5015         struct ctl_softc *softc;
5016         struct ctl_lun *lun;
5017         struct copan_aps_subpage *current_sp;
5018         struct ctl_page_index *page_index;
5019         int i;
5020
5021         softc = control_softc;
5022
5023         mtx_lock(&softc->ctl_lock);
5024
5025         lun = (struct ctl_lun *)be_lun->ctl_lun;
5026         mtx_lock(&lun->lun_lock);
5027
5028         page_index = NULL;
5029         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5030                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5031                      APS_PAGE_CODE)
5032                         continue;
5033
5034                 if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5035                         continue;
5036                 page_index = &lun->mode_pages.index[i];
5037         }
5038
5039         if (page_index == NULL) {
5040                 mtx_unlock(&lun->lun_lock);
5041                 mtx_unlock(&softc->ctl_lock);
5042                 printf("%s: APS subpage not found for lun %ju!\n", __func__,
5043                        (uintmax_t)lun->lun);
5044                 return (1);
5045         }
5046 #if 0
5047         if ((softc->aps_locked_lun != 0)
5048          && (softc->aps_locked_lun != lun->lun)) {
5049                 printf("%s: attempt to lock LUN %llu when %llu is already "
5050                        "locked\n");
5051                 mtx_unlock(&lun->lun_lock);
5052                 mtx_unlock(&softc->ctl_lock);
5053                 return (1);
5054         }
5055 #endif
5056
5057         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5058                 (page_index->page_len * CTL_PAGE_CURRENT));
5059
5060         if (lock != 0) {
5061                 current_sp->lock_active = APS_LOCK_ACTIVE;
5062                 softc->aps_locked_lun = lun->lun;
5063         } else {
5064                 current_sp->lock_active = 0;
5065                 softc->aps_locked_lun = 0;
5066         }
5067
5068
5069         /*
5070          * If we're in HA mode, try to send the lock message to the other
5071          * side.
5072          */
5073         if (ctl_is_single == 0) {
5074                 int isc_retval;
5075                 union ctl_ha_msg lock_msg;
5076
5077                 lock_msg.hdr.nexus = *nexus;
5078                 lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5079                 if (lock != 0)
5080                         lock_msg.aps.lock_flag = 1;
5081                 else
5082                         lock_msg.aps.lock_flag = 0;
5083                 isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5084                                          sizeof(lock_msg), 0);
5085                 if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5086                         printf("%s: APS (lock=%d) error returned from "
5087                                "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5088                         mtx_unlock(&lun->lun_lock);
5089                         mtx_unlock(&softc->ctl_lock);
5090                         return (1);
5091                 }
5092         }
5093
5094         mtx_unlock(&lun->lun_lock);
5095         mtx_unlock(&softc->ctl_lock);
5096
5097         return (0);
5098 }
5099
5100 void
5101 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5102 {
5103         struct ctl_lun *lun;
5104         struct ctl_softc *softc;
5105         int i;
5106
5107         softc = control_softc;
5108
5109         lun = (struct ctl_lun *)be_lun->ctl_lun;
5110
5111         mtx_lock(&lun->lun_lock);
5112
5113         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
5114                 lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
5115
5116         mtx_unlock(&lun->lun_lock);
5117 }
5118
5119 /*
5120  * Backend "memory move is complete" callback for requests that never
5121  * make it down to say RAIDCore's configuration code.
5122  */
5123 int
5124 ctl_config_move_done(union ctl_io *io)
5125 {
5126         int retval;
5127
5128         retval = CTL_RETVAL_COMPLETE;
5129
5130
5131         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5132         /*
5133          * XXX KDM this shouldn't happen, but what if it does?
5134          */
5135         if (io->io_hdr.io_type != CTL_IO_SCSI)
5136                 panic("I/O type isn't CTL_IO_SCSI!");
5137
5138         if ((io->io_hdr.port_status == 0)
5139          && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5140          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5141                 io->io_hdr.status = CTL_SUCCESS;
5142         else if ((io->io_hdr.port_status != 0)
5143               && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5144               && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5145                 /*
5146                  * For hardware error sense keys, the sense key
5147                  * specific value is defined to be a retry count,
5148                  * but we use it to pass back an internal FETD
5149                  * error code.  XXX KDM  Hopefully the FETD is only
5150                  * using 16 bits for an error code, since that's
5151                  * all the space we have in the sks field.
5152                  */
5153                 ctl_set_internal_failure(&io->scsiio,
5154                                          /*sks_valid*/ 1,
5155                                          /*retry_count*/
5156                                          io->io_hdr.port_status);
5157                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5158                         free(io->scsiio.kern_data_ptr, M_CTL);
5159                 ctl_done(io);
5160                 goto bailout;
5161         }
5162
5163         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5164          || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5165          || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5166                 /*
5167                  * XXX KDM just assuming a single pointer here, and not a
5168                  * S/G list.  If we start using S/G lists for config data,
5169                  * we'll need to know how to clean them up here as well.
5170                  */
5171                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5172                         free(io->scsiio.kern_data_ptr, M_CTL);
5173                 /* Hopefully the user has already set the status... */
5174                 ctl_done(io);
5175         } else {
5176                 /*
5177                  * XXX KDM now we need to continue data movement.  Some
5178                  * options:
5179                  * - call ctl_scsiio() again?  We don't do this for data
5180                  *   writes, because for those at least we know ahead of
5181                  *   time where the write will go and how long it is.  For
5182                  *   config writes, though, that information is largely
5183                  *   contained within the write itself, thus we need to
5184                  *   parse out the data again.
5185                  *
5186                  * - Call some other function once the data is in?
5187                  */
5188
5189                 /*
5190                  * XXX KDM call ctl_scsiio() again for now, and check flag
5191                  * bits to see whether we're allocated or not.
5192                  */
5193                 retval = ctl_scsiio(&io->scsiio);
5194         }
5195 bailout:
5196         return (retval);
5197 }
5198
5199 /*
5200  * This gets called by a backend driver when it is done with a
5201  * data_submit method.
5202  */
5203 void
5204 ctl_data_submit_done(union ctl_io *io)
5205 {
5206         /*
5207          * If the IO_CONT flag is set, we need to call the supplied
5208          * function to continue processing the I/O, instead of completing
5209          * the I/O just yet.
5210          *
5211          * If there is an error, though, we don't want to keep processing.
5212          * Instead, just send status back to the initiator.
5213          */
5214         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5215             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5216             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5217              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5218                 io->scsiio.io_cont(io);
5219                 return;
5220         }
5221         ctl_done(io);
5222 }
5223
5224 /*
5225  * This gets called by a backend driver when it is done with a
5226  * configuration write.
5227  */
5228 void
5229 ctl_config_write_done(union ctl_io *io)
5230 {
5231         /*
5232          * If the IO_CONT flag is set, we need to call the supplied
5233          * function to continue processing the I/O, instead of completing
5234          * the I/O just yet.
5235          *
5236          * If there is an error, though, we don't want to keep processing.
5237          * Instead, just send status back to the initiator.
5238          */
5239         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5240          && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5241           || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5242                 io->scsiio.io_cont(io);
5243                 return;
5244         }
5245         /*
5246          * Since a configuration write can be done for commands that actually
5247          * have data allocated, like write buffer, and commands that have
5248          * no data, like start/stop unit, we need to check here.
5249          */
5250         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5251                 free(io->scsiio.kern_data_ptr, M_CTL);
5252         ctl_done(io);
5253 }
5254
5255 /*
5256  * SCSI release command.
5257  */
5258 int
5259 ctl_scsi_release(struct ctl_scsiio *ctsio)
5260 {
5261         int length, longid, thirdparty_id, resv_id;
5262         struct ctl_softc *ctl_softc;
5263         struct ctl_lun *lun;
5264
5265         length = 0;
5266         resv_id = 0;
5267
5268         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5269
5270         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5271         ctl_softc = control_softc;
5272
5273         switch (ctsio->cdb[0]) {
5274         case RELEASE_10: {
5275                 struct scsi_release_10 *cdb;
5276
5277                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5278
5279                 if (cdb->byte2 & SR10_LONGID)
5280                         longid = 1;
5281                 else
5282                         thirdparty_id = cdb->thirdparty_id;
5283
5284                 resv_id = cdb->resv_id;
5285                 length = scsi_2btoul(cdb->length);
5286                 break;
5287         }
5288         }
5289
5290
5291         /*
5292          * XXX KDM right now, we only support LUN reservation.  We don't
5293          * support 3rd party reservations, or extent reservations, which
5294          * might actually need the parameter list.  If we've gotten this
5295          * far, we've got a LUN reservation.  Anything else got kicked out
5296          * above.  So, according to SPC, ignore the length.
5297          */
5298         length = 0;
5299
5300         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5301          && (length > 0)) {
5302                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5303                 ctsio->kern_data_len = length;
5304                 ctsio->kern_total_len = length;
5305                 ctsio->kern_data_resid = 0;
5306                 ctsio->kern_rel_offset = 0;
5307                 ctsio->kern_sg_entries = 0;
5308                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5309                 ctsio->be_move_done = ctl_config_move_done;
5310                 ctl_datamove((union ctl_io *)ctsio);
5311
5312                 return (CTL_RETVAL_COMPLETE);
5313         }
5314
5315         if (length > 0)
5316                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5317
5318         mtx_lock(&lun->lun_lock);
5319
5320         /*
5321          * According to SPC, it is not an error for an intiator to attempt
5322          * to release a reservation on a LUN that isn't reserved, or that
5323          * is reserved by another initiator.  The reservation can only be
5324          * released, though, by the initiator who made it or by one of
5325          * several reset type events.
5326          */
5327         if (lun->flags & CTL_LUN_RESERVED) {
5328                 if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5329                  && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5330                  && (ctsio->io_hdr.nexus.targ_target.id ==
5331                      lun->rsv_nexus.targ_target.id)) {
5332                         lun->flags &= ~CTL_LUN_RESERVED;
5333                 }
5334         }
5335
5336         mtx_unlock(&lun->lun_lock);
5337
5338         ctsio->scsi_status = SCSI_STATUS_OK;
5339         ctsio->io_hdr.status = CTL_SUCCESS;
5340
5341         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5342                 free(ctsio->kern_data_ptr, M_CTL);
5343                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5344         }
5345
5346         ctl_done((union ctl_io *)ctsio);
5347         return (CTL_RETVAL_COMPLETE);
5348 }
5349
5350 int
5351 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5352 {
5353         int extent, thirdparty, longid;
5354         int resv_id, length;
5355         uint64_t thirdparty_id;
5356         struct ctl_softc *ctl_softc;
5357         struct ctl_lun *lun;
5358
5359         extent = 0;
5360         thirdparty = 0;
5361         longid = 0;
5362         resv_id = 0;
5363         length = 0;
5364         thirdparty_id = 0;
5365
5366         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5367
5368         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5369         ctl_softc = control_softc;
5370
5371         switch (ctsio->cdb[0]) {
5372         case RESERVE_10: {
5373                 struct scsi_reserve_10 *cdb;
5374
5375                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5376
5377                 if (cdb->byte2 & SR10_LONGID)
5378                         longid = 1;
5379                 else
5380                         thirdparty_id = cdb->thirdparty_id;
5381
5382                 resv_id = cdb->resv_id;
5383                 length = scsi_2btoul(cdb->length);
5384                 break;
5385         }
5386         }
5387
5388         /*
5389          * XXX KDM right now, we only support LUN reservation.  We don't
5390          * support 3rd party reservations, or extent reservations, which
5391          * might actually need the parameter list.  If we've gotten this
5392          * far, we've got a LUN reservation.  Anything else got kicked out
5393          * above.  So, according to SPC, ignore the length.
5394          */
5395         length = 0;
5396
5397         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5398          && (length > 0)) {
5399                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5400                 ctsio->kern_data_len = length;
5401                 ctsio->kern_total_len = length;
5402                 ctsio->kern_data_resid = 0;
5403                 ctsio->kern_rel_offset = 0;
5404                 ctsio->kern_sg_entries = 0;
5405                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5406                 ctsio->be_move_done = ctl_config_move_done;
5407                 ctl_datamove((union ctl_io *)ctsio);
5408
5409                 return (CTL_RETVAL_COMPLETE);
5410         }
5411
5412         if (length > 0)
5413                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5414
5415         mtx_lock(&lun->lun_lock);
5416         if (lun->flags & CTL_LUN_RESERVED) {
5417                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5418                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5419                  || (ctsio->io_hdr.nexus.targ_target.id !=
5420                      lun->rsv_nexus.targ_target.id)) {
5421                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5422                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
5423                         goto bailout;
5424                 }
5425         }
5426
5427         lun->flags |= CTL_LUN_RESERVED;
5428         lun->rsv_nexus = ctsio->io_hdr.nexus;
5429
5430         ctsio->scsi_status = SCSI_STATUS_OK;
5431         ctsio->io_hdr.status = CTL_SUCCESS;
5432
5433 bailout:
5434         mtx_unlock(&lun->lun_lock);
5435
5436         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5437                 free(ctsio->kern_data_ptr, M_CTL);
5438                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5439         }
5440
5441         ctl_done((union ctl_io *)ctsio);
5442         return (CTL_RETVAL_COMPLETE);
5443 }
5444
5445 int
5446 ctl_start_stop(struct ctl_scsiio *ctsio)
5447 {
5448         struct scsi_start_stop_unit *cdb;
5449         struct ctl_lun *lun;
5450         struct ctl_softc *ctl_softc;
5451         int retval;
5452
5453         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5454
5455         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5456         ctl_softc = control_softc;
5457         retval = 0;
5458
5459         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5460
5461         /*
5462          * XXX KDM
5463          * We don't support the immediate bit on a stop unit.  In order to
5464          * do that, we would need to code up a way to know that a stop is
5465          * pending, and hold off any new commands until it completes, one
5466          * way or another.  Then we could accept or reject those commands
5467          * depending on its status.  We would almost need to do the reverse
5468          * of what we do below for an immediate start -- return the copy of
5469          * the ctl_io to the FETD with status to send to the host (and to
5470          * free the copy!) and then free the original I/O once the stop
5471          * actually completes.  That way, the OOA queue mechanism can work
5472          * to block commands that shouldn't proceed.  Another alternative
5473          * would be to put the copy in the queue in place of the original,
5474          * and return the original back to the caller.  That could be
5475          * slightly safer..
5476          */
5477         if ((cdb->byte2 & SSS_IMMED)
5478          && ((cdb->how & SSS_START) == 0)) {
5479                 ctl_set_invalid_field(ctsio,
5480                                       /*sks_valid*/ 1,
5481                                       /*command*/ 1,
5482                                       /*field*/ 1,
5483                                       /*bit_valid*/ 1,
5484                                       /*bit*/ 0);
5485                 ctl_done((union ctl_io *)ctsio);
5486                 return (CTL_RETVAL_COMPLETE);
5487         }
5488
5489         if ((lun->flags & CTL_LUN_PR_RESERVED)
5490          && ((cdb->how & SSS_START)==0)) {
5491                 uint32_t residx;
5492
5493                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5494                 if (!lun->per_res[residx].registered
5495                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5496
5497                         ctl_set_reservation_conflict(ctsio);
5498                         ctl_done((union ctl_io *)ctsio);
5499                         return (CTL_RETVAL_COMPLETE);
5500                 }
5501         }
5502
5503         /*
5504          * If there is no backend on this device, we can't start or stop
5505          * it.  In theory we shouldn't get any start/stop commands in the
5506          * first place at this level if the LUN doesn't have a backend.
5507          * That should get stopped by the command decode code.
5508          */
5509         if (lun->backend == NULL) {
5510                 ctl_set_invalid_opcode(ctsio);
5511                 ctl_done((union ctl_io *)ctsio);
5512                 return (CTL_RETVAL_COMPLETE);
5513         }
5514
5515         /*
5516          * XXX KDM Copan-specific offline behavior.
5517          * Figure out a reasonable way to port this?
5518          */
5519 #ifdef NEEDTOPORT
5520         mtx_lock(&lun->lun_lock);
5521
5522         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5523          && (lun->flags & CTL_LUN_OFFLINE)) {
5524                 /*
5525                  * If the LUN is offline, and the on/offline bit isn't set,
5526                  * reject the start or stop.  Otherwise, let it through.
5527                  */
5528                 mtx_unlock(&lun->lun_lock);
5529                 ctl_set_lun_not_ready(ctsio);
5530                 ctl_done((union ctl_io *)ctsio);
5531         } else {
5532                 mtx_unlock(&lun->lun_lock);
5533 #endif /* NEEDTOPORT */
5534                 /*
5535                  * This could be a start or a stop when we're online,
5536                  * or a stop/offline or start/online.  A start or stop when
5537                  * we're offline is covered in the case above.
5538                  */
5539                 /*
5540                  * In the non-immediate case, we send the request to
5541                  * the backend and return status to the user when
5542                  * it is done.
5543                  *
5544                  * In the immediate case, we allocate a new ctl_io
5545                  * to hold a copy of the request, and send that to
5546                  * the backend.  We then set good status on the
5547                  * user's request and return it immediately.
5548                  */
5549                 if (cdb->byte2 & SSS_IMMED) {
5550                         union ctl_io *new_io;
5551
5552                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5553                         if (new_io == NULL) {
5554                                 ctl_set_busy(ctsio);
5555                                 ctl_done((union ctl_io *)ctsio);
5556                         } else {
5557                                 ctl_copy_io((union ctl_io *)ctsio,
5558                                             new_io);
5559                                 retval = lun->backend->config_write(new_io);
5560                                 ctl_set_success(ctsio);
5561                                 ctl_done((union ctl_io *)ctsio);
5562                         }
5563                 } else {
5564                         retval = lun->backend->config_write(
5565                                 (union ctl_io *)ctsio);
5566                 }
5567 #ifdef NEEDTOPORT
5568         }
5569 #endif
5570         return (retval);
5571 }
5572
5573 /*
5574  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5575  * we don't really do anything with the LBA and length fields if the user
5576  * passes them in.  Instead we'll just flush out the cache for the entire
5577  * LUN.
5578  */
5579 int
5580 ctl_sync_cache(struct ctl_scsiio *ctsio)
5581 {
5582         struct ctl_lun *lun;
5583         struct ctl_softc *ctl_softc;
5584         uint64_t starting_lba;
5585         uint32_t block_count;
5586         int retval;
5587
5588         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5589
5590         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5591         ctl_softc = control_softc;
5592         retval = 0;
5593
5594         switch (ctsio->cdb[0]) {
5595         case SYNCHRONIZE_CACHE: {
5596                 struct scsi_sync_cache *cdb;
5597                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5598
5599                 starting_lba = scsi_4btoul(cdb->begin_lba);
5600                 block_count = scsi_2btoul(cdb->lb_count);
5601                 break;
5602         }
5603         case SYNCHRONIZE_CACHE_16: {
5604                 struct scsi_sync_cache_16 *cdb;
5605                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5606
5607                 starting_lba = scsi_8btou64(cdb->begin_lba);
5608                 block_count = scsi_4btoul(cdb->lb_count);
5609                 break;
5610         }
5611         default:
5612                 ctl_set_invalid_opcode(ctsio);
5613                 ctl_done((union ctl_io *)ctsio);
5614                 goto bailout;
5615                 break; /* NOTREACHED */
5616         }
5617
5618         /*
5619          * We check the LBA and length, but don't do anything with them.
5620          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5621          * get flushed.  This check will just help satisfy anyone who wants
5622          * to see an error for an out of range LBA.
5623          */
5624         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5625                 ctl_set_lba_out_of_range(ctsio);
5626                 ctl_done((union ctl_io *)ctsio);
5627                 goto bailout;
5628         }
5629
5630         /*
5631          * If this LUN has no backend, we can't flush the cache anyway.
5632          */
5633         if (lun->backend == NULL) {
5634                 ctl_set_invalid_opcode(ctsio);
5635                 ctl_done((union ctl_io *)ctsio);
5636                 goto bailout;
5637         }
5638
5639         /*
5640          * Check to see whether we're configured to send the SYNCHRONIZE
5641          * CACHE command directly to the back end.
5642          */
5643         mtx_lock(&lun->lun_lock);
5644         if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5645          && (++(lun->sync_count) >= lun->sync_interval)) {
5646                 lun->sync_count = 0;
5647                 mtx_unlock(&lun->lun_lock);
5648                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5649         } else {
5650                 mtx_unlock(&lun->lun_lock);
5651                 ctl_set_success(ctsio);
5652                 ctl_done((union ctl_io *)ctsio);
5653         }
5654
5655 bailout:
5656
5657         return (retval);
5658 }
5659
5660 int
5661 ctl_format(struct ctl_scsiio *ctsio)
5662 {
5663         struct scsi_format *cdb;
5664         struct ctl_lun *lun;
5665         struct ctl_softc *ctl_softc;
5666         int length, defect_list_len;
5667
5668         CTL_DEBUG_PRINT(("ctl_format\n"));
5669
5670         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5671         ctl_softc = control_softc;
5672
5673         cdb = (struct scsi_format *)ctsio->cdb;
5674
5675         length = 0;
5676         if (cdb->byte2 & SF_FMTDATA) {
5677                 if (cdb->byte2 & SF_LONGLIST)
5678                         length = sizeof(struct scsi_format_header_long);
5679                 else
5680                         length = sizeof(struct scsi_format_header_short);
5681         }
5682
5683         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5684          && (length > 0)) {
5685                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5686                 ctsio->kern_data_len = length;
5687                 ctsio->kern_total_len = length;
5688                 ctsio->kern_data_resid = 0;
5689                 ctsio->kern_rel_offset = 0;
5690                 ctsio->kern_sg_entries = 0;
5691                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5692                 ctsio->be_move_done = ctl_config_move_done;
5693                 ctl_datamove((union ctl_io *)ctsio);
5694
5695                 return (CTL_RETVAL_COMPLETE);
5696         }
5697
5698         defect_list_len = 0;
5699
5700         if (cdb->byte2 & SF_FMTDATA) {
5701                 if (cdb->byte2 & SF_LONGLIST) {
5702                         struct scsi_format_header_long *header;
5703
5704                         header = (struct scsi_format_header_long *)
5705                                 ctsio->kern_data_ptr;
5706
5707                         defect_list_len = scsi_4btoul(header->defect_list_len);
5708                         if (defect_list_len != 0) {
5709                                 ctl_set_invalid_field(ctsio,
5710                                                       /*sks_valid*/ 1,
5711                                                       /*command*/ 0,
5712                                                       /*field*/ 2,
5713                                                       /*bit_valid*/ 0,
5714                                                       /*bit*/ 0);
5715                                 goto bailout;
5716                         }
5717                 } else {
5718                         struct scsi_format_header_short *header;
5719
5720                         header = (struct scsi_format_header_short *)
5721                                 ctsio->kern_data_ptr;
5722
5723                         defect_list_len = scsi_2btoul(header->defect_list_len);
5724                         if (defect_list_len != 0) {
5725                                 ctl_set_invalid_field(ctsio,
5726                                                       /*sks_valid*/ 1,
5727                                                       /*command*/ 0,
5728                                                       /*field*/ 2,
5729                                                       /*bit_valid*/ 0,
5730                                                       /*bit*/ 0);
5731                                 goto bailout;
5732                         }
5733                 }
5734         }
5735
5736         /*
5737          * The format command will clear out the "Medium format corrupted"
5738          * status if set by the configuration code.  That status is really
5739          * just a way to notify the host that we have lost the media, and
5740          * get them to issue a command that will basically make them think
5741          * they're blowing away the media.
5742          */
5743         mtx_lock(&lun->lun_lock);
5744         lun->flags &= ~CTL_LUN_INOPERABLE;
5745         mtx_unlock(&lun->lun_lock);
5746
5747         ctsio->scsi_status = SCSI_STATUS_OK;
5748         ctsio->io_hdr.status = CTL_SUCCESS;
5749 bailout:
5750
5751         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5752                 free(ctsio->kern_data_ptr, M_CTL);
5753                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5754         }
5755
5756         ctl_done((union ctl_io *)ctsio);
5757         return (CTL_RETVAL_COMPLETE);
5758 }
5759
5760 int
5761 ctl_read_buffer(struct ctl_scsiio *ctsio)
5762 {
5763         struct scsi_read_buffer *cdb;
5764         struct ctl_lun *lun;
5765         int buffer_offset, len;
5766         static uint8_t descr[4];
5767         static uint8_t echo_descr[4] = { 0 };
5768
5769         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5770
5771         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5772         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5773
5774         if (lun->flags & CTL_LUN_PR_RESERVED) {
5775                 uint32_t residx;
5776
5777                 /*
5778                  * XXX KDM need a lock here.
5779                  */
5780                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5781                 if ((lun->res_type == SPR_TYPE_EX_AC
5782                   && residx != lun->pr_res_idx)
5783                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
5784                    || lun->res_type == SPR_TYPE_EX_AC_AR)
5785                   && !lun->per_res[residx].registered)) {
5786                         ctl_set_reservation_conflict(ctsio);
5787                         ctl_done((union ctl_io *)ctsio);
5788                         return (CTL_RETVAL_COMPLETE);
5789                 }
5790         }
5791
5792         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5793             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5794             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5795                 ctl_set_invalid_field(ctsio,
5796                                       /*sks_valid*/ 1,
5797                                       /*command*/ 1,
5798                                       /*field*/ 1,
5799                                       /*bit_valid*/ 1,
5800                                       /*bit*/ 4);
5801                 ctl_done((union ctl_io *)ctsio);
5802                 return (CTL_RETVAL_COMPLETE);
5803         }
5804
5805         len = scsi_3btoul(cdb->length);
5806         buffer_offset = scsi_3btoul(cdb->offset);
5807
5808         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5809                 ctl_set_invalid_field(ctsio,
5810                                       /*sks_valid*/ 1,
5811                                       /*command*/ 1,
5812                                       /*field*/ 6,
5813                                       /*bit_valid*/ 0,
5814                                       /*bit*/ 0);
5815                 ctl_done((union ctl_io *)ctsio);
5816                 return (CTL_RETVAL_COMPLETE);
5817         }
5818
5819         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5820                 descr[0] = 0;
5821                 scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5822                 ctsio->kern_data_ptr = descr;
5823                 len = min(len, sizeof(descr));
5824         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5825                 ctsio->kern_data_ptr = echo_descr;
5826                 len = min(len, sizeof(echo_descr));
5827         } else
5828                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5829         ctsio->kern_data_len = len;
5830         ctsio->kern_total_len = len;
5831         ctsio->kern_data_resid = 0;
5832         ctsio->kern_rel_offset = 0;
5833         ctsio->kern_sg_entries = 0;
5834         ctsio->be_move_done = ctl_config_move_done;
5835         ctl_datamove((union ctl_io *)ctsio);
5836
5837         return (CTL_RETVAL_COMPLETE);
5838 }
5839
5840 int
5841 ctl_write_buffer(struct ctl_scsiio *ctsio)
5842 {
5843         struct scsi_write_buffer *cdb;
5844         struct ctl_lun *lun;
5845         int buffer_offset, len;
5846
5847         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5848
5849         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5850         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5851
5852         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5853                 ctl_set_invalid_field(ctsio,
5854                                       /*sks_valid*/ 1,
5855                                       /*command*/ 1,
5856                                       /*field*/ 1,
5857                                       /*bit_valid*/ 1,
5858                                       /*bit*/ 4);
5859                 ctl_done((union ctl_io *)ctsio);
5860                 return (CTL_RETVAL_COMPLETE);
5861         }
5862
5863         len = scsi_3btoul(cdb->length);
5864         buffer_offset = scsi_3btoul(cdb->offset);
5865
5866         if (buffer_offset + len > sizeof(lun->write_buffer)) {
5867                 ctl_set_invalid_field(ctsio,
5868                                       /*sks_valid*/ 1,
5869                                       /*command*/ 1,
5870                                       /*field*/ 6,
5871                                       /*bit_valid*/ 0,
5872                                       /*bit*/ 0);
5873                 ctl_done((union ctl_io *)ctsio);
5874                 return (CTL_RETVAL_COMPLETE);
5875         }
5876
5877         /*
5878          * If we've got a kernel request that hasn't been malloced yet,
5879          * malloc it and tell the caller the data buffer is here.
5880          */
5881         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5882                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5883                 ctsio->kern_data_len = len;
5884                 ctsio->kern_total_len = len;
5885                 ctsio->kern_data_resid = 0;
5886                 ctsio->kern_rel_offset = 0;
5887                 ctsio->kern_sg_entries = 0;
5888                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5889                 ctsio->be_move_done = ctl_config_move_done;
5890                 ctl_datamove((union ctl_io *)ctsio);
5891
5892                 return (CTL_RETVAL_COMPLETE);
5893         }
5894
5895         ctl_done((union ctl_io *)ctsio);
5896
5897         return (CTL_RETVAL_COMPLETE);
5898 }
5899
5900 int
5901 ctl_write_same(struct ctl_scsiio *ctsio)
5902 {
5903         struct ctl_lun *lun;
5904         struct ctl_lba_len_flags *lbalen;
5905         uint64_t lba;
5906         uint32_t num_blocks;
5907         int len, retval;
5908         uint8_t byte2;
5909
5910         retval = CTL_RETVAL_COMPLETE;
5911
5912         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5913
5914         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5915
5916         switch (ctsio->cdb[0]) {
5917         case WRITE_SAME_10: {
5918                 struct scsi_write_same_10 *cdb;
5919
5920                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5921
5922                 lba = scsi_4btoul(cdb->addr);
5923                 num_blocks = scsi_2btoul(cdb->length);
5924                 byte2 = cdb->byte2;
5925                 break;
5926         }
5927         case WRITE_SAME_16: {
5928                 struct scsi_write_same_16 *cdb;
5929
5930                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5931
5932                 lba = scsi_8btou64(cdb->addr);
5933                 num_blocks = scsi_4btoul(cdb->length);
5934                 byte2 = cdb->byte2;
5935                 break;
5936         }
5937         default:
5938                 /*
5939                  * We got a command we don't support.  This shouldn't
5940                  * happen, commands should be filtered out above us.
5941                  */
5942                 ctl_set_invalid_opcode(ctsio);
5943                 ctl_done((union ctl_io *)ctsio);
5944
5945                 return (CTL_RETVAL_COMPLETE);
5946                 break; /* NOTREACHED */
5947         }
5948
5949         /*
5950          * The first check is to make sure we're in bounds, the second
5951          * check is to catch wrap-around problems.  If the lba + num blocks
5952          * is less than the lba, then we've wrapped around and the block
5953          * range is invalid anyway.
5954          */
5955         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5956          || ((lba + num_blocks) < lba)) {
5957                 ctl_set_lba_out_of_range(ctsio);
5958                 ctl_done((union ctl_io *)ctsio);
5959                 return (CTL_RETVAL_COMPLETE);
5960         }
5961
5962         /* Zero number of blocks means "to the last logical block" */
5963         if (num_blocks == 0) {
5964                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5965                         ctl_set_invalid_field(ctsio,
5966                                               /*sks_valid*/ 0,
5967                                               /*command*/ 1,
5968                                               /*field*/ 0,
5969                                               /*bit_valid*/ 0,
5970                                               /*bit*/ 0);
5971                         ctl_done((union ctl_io *)ctsio);
5972                         return (CTL_RETVAL_COMPLETE);
5973                 }
5974                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5975         }
5976
5977         len = lun->be_lun->blocksize;
5978
5979         /*
5980          * If we've got a kernel request that hasn't been malloced yet,
5981          * malloc it and tell the caller the data buffer is here.
5982          */
5983         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5984                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5985                 ctsio->kern_data_len = len;
5986                 ctsio->kern_total_len = len;
5987                 ctsio->kern_data_resid = 0;
5988                 ctsio->kern_rel_offset = 0;
5989                 ctsio->kern_sg_entries = 0;
5990                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5991                 ctsio->be_move_done = ctl_config_move_done;
5992                 ctl_datamove((union ctl_io *)ctsio);
5993
5994                 return (CTL_RETVAL_COMPLETE);
5995         }
5996
5997         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5998         lbalen->lba = lba;
5999         lbalen->len = num_blocks;
6000         lbalen->flags = byte2;
6001         retval = lun->backend->config_write((union ctl_io *)ctsio);
6002
6003         return (retval);
6004 }
6005
6006 int
6007 ctl_unmap(struct ctl_scsiio *ctsio)
6008 {
6009         struct ctl_lun *lun;
6010         struct scsi_unmap *cdb;
6011         struct ctl_ptr_len_flags *ptrlen;
6012         struct scsi_unmap_header *hdr;
6013         struct scsi_unmap_desc *buf, *end;
6014         uint64_t lba;
6015         uint32_t num_blocks;
6016         int len, retval;
6017         uint8_t byte2;
6018
6019         retval = CTL_RETVAL_COMPLETE;
6020
6021         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6022
6023         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6024         cdb = (struct scsi_unmap *)ctsio->cdb;
6025
6026         len = scsi_2btoul(cdb->length);
6027         byte2 = cdb->byte2;
6028
6029         /*
6030          * If we've got a kernel request that hasn't been malloced yet,
6031          * malloc it and tell the caller the data buffer is here.
6032          */
6033         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6034                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6035                 ctsio->kern_data_len = len;
6036                 ctsio->kern_total_len = len;
6037                 ctsio->kern_data_resid = 0;
6038                 ctsio->kern_rel_offset = 0;
6039                 ctsio->kern_sg_entries = 0;
6040                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6041                 ctsio->be_move_done = ctl_config_move_done;
6042                 ctl_datamove((union ctl_io *)ctsio);
6043
6044                 return (CTL_RETVAL_COMPLETE);
6045         }
6046
6047         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6048         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6049         if (len < sizeof (*hdr) ||
6050             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6051             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6052             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6053                 ctl_set_invalid_field(ctsio,
6054                                       /*sks_valid*/ 0,
6055                                       /*command*/ 0,
6056                                       /*field*/ 0,
6057                                       /*bit_valid*/ 0,
6058                                       /*bit*/ 0);
6059                 ctl_done((union ctl_io *)ctsio);
6060                 return (CTL_RETVAL_COMPLETE);
6061         }
6062         len = scsi_2btoul(hdr->desc_length);
6063         buf = (struct scsi_unmap_desc *)(hdr + 1);
6064         end = buf + len / sizeof(*buf);
6065
6066         ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6067         ptrlen->ptr = (void *)buf;
6068         ptrlen->len = len;
6069         ptrlen->flags = byte2;
6070
6071         for (; buf < end; buf++) {
6072                 lba = scsi_8btou64(buf->lba);
6073                 num_blocks = scsi_4btoul(buf->length);
6074                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6075                  || ((lba + num_blocks) < lba)) {
6076                         ctl_set_lba_out_of_range(ctsio);
6077                         ctl_done((union ctl_io *)ctsio);
6078                         return (CTL_RETVAL_COMPLETE);
6079                 }
6080         }
6081
6082         retval = lun->backend->config_write((union ctl_io *)ctsio);
6083
6084         return (retval);
6085 }
6086
6087 /*
6088  * Note that this function currently doesn't actually do anything inside
6089  * CTL to enforce things if the DQue bit is turned on.
6090  *
6091  * Also note that this function can't be used in the default case, because
6092  * the DQue bit isn't set in the changeable mask for the control mode page
6093  * anyway.  This is just here as an example for how to implement a page
6094  * handler, and a placeholder in case we want to allow the user to turn
6095  * tagged queueing on and off.
6096  *
6097  * The D_SENSE bit handling is functional, however, and will turn
6098  * descriptor sense on and off for a given LUN.
6099  */
6100 int
6101 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6102                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6103 {
6104         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6105         struct ctl_lun *lun;
6106         struct ctl_softc *softc;
6107         int set_ua;
6108         uint32_t initidx;
6109
6110         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6111         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6112         set_ua = 0;
6113
6114         user_cp = (struct scsi_control_page *)page_ptr;
6115         current_cp = (struct scsi_control_page *)
6116                 (page_index->page_data + (page_index->page_len *
6117                 CTL_PAGE_CURRENT));
6118         saved_cp = (struct scsi_control_page *)
6119                 (page_index->page_data + (page_index->page_len *
6120                 CTL_PAGE_SAVED));
6121
6122         softc = control_softc;
6123
6124         mtx_lock(&lun->lun_lock);
6125         if (((current_cp->rlec & SCP_DSENSE) == 0)
6126          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6127                 /*
6128                  * Descriptor sense is currently turned off and the user
6129                  * wants to turn it on.
6130                  */
6131                 current_cp->rlec |= SCP_DSENSE;
6132                 saved_cp->rlec |= SCP_DSENSE;
6133                 lun->flags |= CTL_LUN_SENSE_DESC;
6134                 set_ua = 1;
6135         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6136                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6137                 /*
6138                  * Descriptor sense is currently turned on, and the user
6139                  * wants to turn it off.
6140                  */
6141                 current_cp->rlec &= ~SCP_DSENSE;
6142                 saved_cp->rlec &= ~SCP_DSENSE;
6143                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6144                 set_ua = 1;
6145         }
6146         if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6147                 if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6148 #ifdef NEEDTOPORT
6149                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6150                                     CTL_UNTAG_TO_UNTAG,
6151                                     csevent_LogType_Trace,
6152                                     csevent_Severity_Information,
6153                                     csevent_AlertLevel_Green,
6154                                     csevent_FRU_Firmware,
6155                                     csevent_FRU_Unknown,
6156                                     "Received untagged to untagged transition");
6157 #endif /* NEEDTOPORT */
6158                 } else {
6159 #ifdef NEEDTOPORT
6160                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6161                                     CTL_UNTAG_TO_TAG,
6162                                     csevent_LogType_ConfigChange,
6163                                     csevent_Severity_Information,
6164                                     csevent_AlertLevel_Green,
6165                                     csevent_FRU_Firmware,
6166                                     csevent_FRU_Unknown,
6167                                     "Received untagged to tagged "
6168                                     "queueing transition");
6169 #endif /* NEEDTOPORT */
6170
6171                         current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6172                         saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6173                         set_ua = 1;
6174                 }
6175         } else {
6176                 if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6177 #ifdef NEEDTOPORT
6178                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6179                                     CTL_TAG_TO_UNTAG,
6180                                     csevent_LogType_ConfigChange,
6181                                     csevent_Severity_Warning,
6182                                     csevent_AlertLevel_Yellow,
6183                                     csevent_FRU_Firmware,
6184                                     csevent_FRU_Unknown,
6185                                     "Received tagged queueing to untagged "
6186                                     "transition");
6187 #endif /* NEEDTOPORT */
6188
6189                         current_cp->queue_flags |= SCP_QUEUE_DQUE;
6190                         saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6191                         set_ua = 1;
6192                 } else {
6193 #ifdef NEEDTOPORT
6194                         csevent_log(CSC_CTL | CSC_SHELF_SW |
6195                                     CTL_TAG_TO_TAG,
6196                                     csevent_LogType_Trace,
6197                                     csevent_Severity_Information,
6198                                     csevent_AlertLevel_Green,
6199                                     csevent_FRU_Firmware,
6200                                     csevent_FRU_Unknown,
6201                                     "Received tagged queueing to tagged "
6202                                     "queueing transition");
6203 #endif /* NEEDTOPORT */
6204                 }
6205         }
6206         if (set_ua != 0) {
6207                 int i;
6208                 /*
6209                  * Let other initiators know that the mode
6210                  * parameters for this LUN have changed.
6211                  */
6212                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6213                         if (i == initidx)
6214                                 continue;
6215
6216                         lun->pending_sense[i].ua_pending |=
6217                                 CTL_UA_MODE_CHANGE;
6218                 }
6219         }
6220         mtx_unlock(&lun->lun_lock);
6221
6222         return (0);
6223 }
6224
6225 int
6226 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6227                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6228 {
6229         return (0);
6230 }
6231
6232 int
6233 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6234                            struct ctl_page_index *page_index, int pc)
6235 {
6236         struct copan_power_subpage *page;
6237
6238         page = (struct copan_power_subpage *)page_index->page_data +
6239                 (page_index->page_len * pc);
6240
6241         switch (pc) {
6242         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6243                 /*
6244                  * We don't update the changable bits for this page.
6245                  */
6246                 break;
6247         case SMS_PAGE_CTRL_CURRENT >> 6:
6248         case SMS_PAGE_CTRL_DEFAULT >> 6:
6249         case SMS_PAGE_CTRL_SAVED >> 6:
6250 #ifdef NEEDTOPORT
6251                 ctl_update_power_subpage(page);
6252 #endif
6253                 break;
6254         default:
6255 #ifdef NEEDTOPORT
6256                 EPRINT(0, "Invalid PC %d!!", pc);
6257 #endif
6258                 break;
6259         }
6260         return (0);
6261 }
6262
6263
6264 int
6265 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6266                    struct ctl_page_index *page_index, uint8_t *page_ptr)
6267 {
6268         struct copan_aps_subpage *user_sp;
6269         struct copan_aps_subpage *current_sp;
6270         union ctl_modepage_info *modepage_info;
6271         struct ctl_softc *softc;
6272         struct ctl_lun *lun;
6273         int retval;
6274
6275         retval = CTL_RETVAL_COMPLETE;
6276         current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6277                      (page_index->page_len * CTL_PAGE_CURRENT));
6278         softc = control_softc;
6279         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6280
6281         user_sp = (struct copan_aps_subpage *)page_ptr;
6282
6283         modepage_info = (union ctl_modepage_info *)
6284                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6285
6286         modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6287         modepage_info->header.subpage = page_index->subpage;
6288         modepage_info->aps.lock_active = user_sp->lock_active;
6289
6290         mtx_lock(&softc->ctl_lock);
6291
6292         /*
6293          * If there is a request to lock the LUN and another LUN is locked
6294          * this is an error. If the requested LUN is already locked ignore
6295          * the request. If no LUN is locked attempt to lock it.
6296          * if there is a request to unlock the LUN and the LUN is currently
6297          * locked attempt to unlock it. Otherwise ignore the request. i.e.
6298          * if another LUN is locked or no LUN is locked.
6299          */
6300         if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6301                 if (softc->aps_locked_lun == lun->lun) {
6302                         /*
6303                          * This LUN is already locked, so we're done.
6304                          */
6305                         retval = CTL_RETVAL_COMPLETE;
6306                 } else if (softc->aps_locked_lun == 0) {
6307                         /*
6308                          * No one has the lock, pass the request to the
6309                          * backend.
6310                          */
6311                         retval = lun->backend->config_write(
6312                                 (union ctl_io *)ctsio);
6313                 } else {
6314                         /*
6315                          * Someone else has the lock, throw out the request.
6316                          */
6317                         ctl_set_already_locked(ctsio);
6318                         free(ctsio->kern_data_ptr, M_CTL);
6319                         ctl_done((union ctl_io *)ctsio);
6320
6321                         /*
6322                          * Set the return value so that ctl_do_mode_select()
6323                          * won't try to complete the command.  We already
6324                          * completed it here.
6325                          */
6326                         retval = CTL_RETVAL_ERROR;
6327                 }
6328         } else if (softc->aps_locked_lun == lun->lun) {
6329                 /*
6330                  * This LUN is locked, so pass the unlock request to the
6331                  * backend.
6332                  */
6333                 retval = lun->backend->config_write((union ctl_io *)ctsio);
6334         }
6335         mtx_unlock(&softc->ctl_lock);
6336
6337         return (retval);
6338 }
6339
6340 int
6341 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6342                                 struct ctl_page_index *page_index,
6343                                 uint8_t *page_ptr)
6344 {
6345         uint8_t *c;
6346         int i;
6347
6348         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6349         ctl_time_io_secs =
6350                 (c[0] << 8) |
6351                 (c[1] << 0) |
6352                 0;
6353         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6354         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6355         printf("page data:");
6356         for (i=0; i<8; i++)
6357                 printf(" %.2x",page_ptr[i]);
6358         printf("\n");
6359         return (0);
6360 }
6361
6362 int
6363 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6364                                struct ctl_page_index *page_index,
6365                                int pc)
6366 {
6367         struct copan_debugconf_subpage *page;
6368
6369         page = (struct copan_debugconf_subpage *)page_index->page_data +
6370                 (page_index->page_len * pc);
6371
6372         switch (pc) {
6373         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6374         case SMS_PAGE_CTRL_DEFAULT >> 6:
6375         case SMS_PAGE_CTRL_SAVED >> 6:
6376                 /*
6377                  * We don't update the changable or default bits for this page.
6378                  */
6379                 break;
6380         case SMS_PAGE_CTRL_CURRENT >> 6:
6381                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6382                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6383                 break;
6384         default:
6385 #ifdef NEEDTOPORT
6386                 EPRINT(0, "Invalid PC %d!!", pc);
6387 #endif /* NEEDTOPORT */
6388                 break;
6389         }
6390         return (0);
6391 }
6392
6393
6394 static int
6395 ctl_do_mode_select(union ctl_io *io)
6396 {
6397         struct scsi_mode_page_header *page_header;
6398         struct ctl_page_index *page_index;
6399         struct ctl_scsiio *ctsio;
6400         int control_dev, page_len;
6401         int page_len_offset, page_len_size;
6402         union ctl_modepage_info *modepage_info;
6403         struct ctl_lun *lun;
6404         int *len_left, *len_used;
6405         int retval, i;
6406
6407         ctsio = &io->scsiio;
6408         page_index = NULL;
6409         page_len = 0;
6410         retval = CTL_RETVAL_COMPLETE;
6411
6412         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6413
6414         if (lun->be_lun->lun_type != T_DIRECT)
6415                 control_dev = 1;
6416         else
6417                 control_dev = 0;
6418
6419         modepage_info = (union ctl_modepage_info *)
6420                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6421         len_left = &modepage_info->header.len_left;
6422         len_used = &modepage_info->header.len_used;
6423
6424 do_next_page:
6425
6426         page_header = (struct scsi_mode_page_header *)
6427                 (ctsio->kern_data_ptr + *len_used);
6428
6429         if (*len_left == 0) {
6430                 free(ctsio->kern_data_ptr, M_CTL);
6431                 ctl_set_success(ctsio);
6432                 ctl_done((union ctl_io *)ctsio);
6433                 return (CTL_RETVAL_COMPLETE);
6434         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6435
6436                 free(ctsio->kern_data_ptr, M_CTL);
6437                 ctl_set_param_len_error(ctsio);
6438                 ctl_done((union ctl_io *)ctsio);
6439                 return (CTL_RETVAL_COMPLETE);
6440
6441         } else if ((page_header->page_code & SMPH_SPF)
6442                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6443
6444                 free(ctsio->kern_data_ptr, M_CTL);
6445                 ctl_set_param_len_error(ctsio);
6446                 ctl_done((union ctl_io *)ctsio);
6447                 return (CTL_RETVAL_COMPLETE);
6448         }
6449
6450
6451         /*
6452          * XXX KDM should we do something with the block descriptor?
6453          */
6454         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6455
6456                 if ((control_dev != 0)
6457                  && (lun->mode_pages.index[i].page_flags &
6458                      CTL_PAGE_FLAG_DISK_ONLY))
6459                         continue;
6460
6461                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6462                     (page_header->page_code & SMPH_PC_MASK))
6463                         continue;
6464
6465                 /*
6466                  * If neither page has a subpage code, then we've got a
6467                  * match.
6468                  */
6469                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6470                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6471                         page_index = &lun->mode_pages.index[i];
6472                         page_len = page_header->page_length;
6473                         break;
6474                 }
6475
6476                 /*
6477                  * If both pages have subpages, then the subpage numbers
6478                  * have to match.
6479                  */
6480                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6481                   && (page_header->page_code & SMPH_SPF)) {
6482                         struct scsi_mode_page_header_sp *sph;
6483
6484                         sph = (struct scsi_mode_page_header_sp *)page_header;
6485
6486                         if (lun->mode_pages.index[i].subpage ==
6487                             sph->subpage) {
6488                                 page_index = &lun->mode_pages.index[i];
6489                                 page_len = scsi_2btoul(sph->page_length);
6490                                 break;
6491                         }
6492                 }
6493         }
6494
6495         /*
6496          * If we couldn't find the page, or if we don't have a mode select
6497          * handler for it, send back an error to the user.
6498          */
6499         if ((page_index == NULL)
6500          || (page_index->select_handler == NULL)) {
6501                 ctl_set_invalid_field(ctsio,
6502                                       /*sks_valid*/ 1,
6503                                       /*command*/ 0,
6504                                       /*field*/ *len_used,
6505                                       /*bit_valid*/ 0,
6506                                       /*bit*/ 0);
6507                 free(ctsio->kern_data_ptr, M_CTL);
6508                 ctl_done((union ctl_io *)ctsio);
6509                 return (CTL_RETVAL_COMPLETE);
6510         }
6511
6512         if (page_index->page_code & SMPH_SPF) {
6513                 page_len_offset = 2;
6514                 page_len_size = 2;
6515         } else {
6516                 page_len_size = 1;
6517                 page_len_offset = 1;
6518         }
6519
6520         /*
6521          * If the length the initiator gives us isn't the one we specify in
6522          * the mode page header, or if they didn't specify enough data in
6523          * the CDB to avoid truncating this page, kick out the request.
6524          */
6525         if ((page_len != (page_index->page_len - page_len_offset -
6526                           page_len_size))
6527          || (*len_left < page_index->page_len)) {
6528
6529
6530                 ctl_set_invalid_field(ctsio,
6531                                       /*sks_valid*/ 1,
6532                                       /*command*/ 0,
6533                                       /*field*/ *len_used + page_len_offset,
6534                                       /*bit_valid*/ 0,
6535                                       /*bit*/ 0);
6536                 free(ctsio->kern_data_ptr, M_CTL);
6537                 ctl_done((union ctl_io *)ctsio);
6538                 return (CTL_RETVAL_COMPLETE);
6539         }
6540
6541         /*
6542          * Run through the mode page, checking to make sure that the bits
6543          * the user changed are actually legal for him to change.
6544          */
6545         for (i = 0; i < page_index->page_len; i++) {
6546                 uint8_t *user_byte, *change_mask, *current_byte;
6547                 int bad_bit;
6548                 int j;
6549
6550                 user_byte = (uint8_t *)page_header + i;
6551                 change_mask = page_index->page_data +
6552                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6553                 current_byte = page_index->page_data +
6554                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6555
6556                 /*
6557                  * Check to see whether the user set any bits in this byte
6558                  * that he is not allowed to set.
6559                  */
6560                 if ((*user_byte & ~(*change_mask)) ==
6561                     (*current_byte & ~(*change_mask)))
6562                         continue;
6563
6564                 /*
6565                  * Go through bit by bit to determine which one is illegal.
6566                  */
6567                 bad_bit = 0;
6568                 for (j = 7; j >= 0; j--) {
6569                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6570                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6571                                 bad_bit = i;
6572                                 break;
6573                         }
6574                 }
6575                 ctl_set_invalid_field(ctsio,
6576                                       /*sks_valid*/ 1,
6577                                       /*command*/ 0,
6578                                       /*field*/ *len_used + i,
6579                                       /*bit_valid*/ 1,
6580                                       /*bit*/ bad_bit);
6581                 free(ctsio->kern_data_ptr, M_CTL);
6582                 ctl_done((union ctl_io *)ctsio);
6583                 return (CTL_RETVAL_COMPLETE);
6584         }
6585
6586         /*
6587          * Decrement these before we call the page handler, since we may
6588          * end up getting called back one way or another before the handler
6589          * returns to this context.
6590          */
6591         *len_left -= page_index->page_len;
6592         *len_used += page_index->page_len;
6593
6594         retval = page_index->select_handler(ctsio, page_index,
6595                                             (uint8_t *)page_header);
6596
6597         /*
6598          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6599          * wait until this queued command completes to finish processing
6600          * the mode page.  If it returns anything other than
6601          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6602          * already set the sense information, freed the data pointer, and
6603          * completed the io for us.
6604          */
6605         if (retval != CTL_RETVAL_COMPLETE)
6606                 goto bailout_no_done;
6607
6608         /*
6609          * If the initiator sent us more than one page, parse the next one.
6610          */
6611         if (*len_left > 0)
6612                 goto do_next_page;
6613
6614         ctl_set_success(ctsio);
6615         free(ctsio->kern_data_ptr, M_CTL);
6616         ctl_done((union ctl_io *)ctsio);
6617
6618 bailout_no_done:
6619
6620         return (CTL_RETVAL_COMPLETE);
6621
6622 }
6623
6624 int
6625 ctl_mode_select(struct ctl_scsiio *ctsio)
6626 {
6627         int param_len, pf, sp;
6628         int header_size, bd_len;
6629         int len_left, len_used;
6630         struct ctl_page_index *page_index;
6631         struct ctl_lun *lun;
6632         int control_dev, page_len;
6633         union ctl_modepage_info *modepage_info;
6634         int retval;
6635
6636         pf = 0;
6637         sp = 0;
6638         page_len = 0;
6639         len_used = 0;
6640         len_left = 0;
6641         retval = 0;
6642         bd_len = 0;
6643         page_index = NULL;
6644
6645         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6646
6647         if (lun->be_lun->lun_type != T_DIRECT)
6648                 control_dev = 1;
6649         else
6650                 control_dev = 0;
6651
6652         switch (ctsio->cdb[0]) {
6653         case MODE_SELECT_6: {
6654                 struct scsi_mode_select_6 *cdb;
6655
6656                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6657
6658                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6659                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6660
6661                 param_len = cdb->length;
6662                 header_size = sizeof(struct scsi_mode_header_6);
6663                 break;
6664         }
6665         case MODE_SELECT_10: {
6666                 struct scsi_mode_select_10 *cdb;
6667
6668                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6669
6670                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6671                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6672
6673                 param_len = scsi_2btoul(cdb->length);
6674                 header_size = sizeof(struct scsi_mode_header_10);
6675                 break;
6676         }
6677         default:
6678                 ctl_set_invalid_opcode(ctsio);
6679                 ctl_done((union ctl_io *)ctsio);
6680                 return (CTL_RETVAL_COMPLETE);
6681                 break; /* NOTREACHED */
6682         }
6683
6684         /*
6685          * From SPC-3:
6686          * "A parameter list length of zero indicates that the Data-Out Buffer
6687          * shall be empty. This condition shall not be considered as an error."
6688          */
6689         if (param_len == 0) {
6690                 ctl_set_success(ctsio);
6691                 ctl_done((union ctl_io *)ctsio);
6692                 return (CTL_RETVAL_COMPLETE);
6693         }
6694
6695         /*
6696          * Since we'll hit this the first time through, prior to
6697          * allocation, we don't need to free a data buffer here.
6698          */
6699         if (param_len < header_size) {
6700                 ctl_set_param_len_error(ctsio);
6701                 ctl_done((union ctl_io *)ctsio);
6702                 return (CTL_RETVAL_COMPLETE);
6703         }
6704
6705         /*
6706          * Allocate the data buffer and grab the user's data.  In theory,
6707          * we shouldn't have to sanity check the parameter list length here
6708          * because the maximum size is 64K.  We should be able to malloc
6709          * that much without too many problems.
6710          */
6711         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6712                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6713                 ctsio->kern_data_len = param_len;
6714                 ctsio->kern_total_len = param_len;
6715                 ctsio->kern_data_resid = 0;
6716                 ctsio->kern_rel_offset = 0;
6717                 ctsio->kern_sg_entries = 0;
6718                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6719                 ctsio->be_move_done = ctl_config_move_done;
6720                 ctl_datamove((union ctl_io *)ctsio);
6721
6722                 return (CTL_RETVAL_COMPLETE);
6723         }
6724
6725         switch (ctsio->cdb[0]) {
6726         case MODE_SELECT_6: {
6727                 struct scsi_mode_header_6 *mh6;
6728
6729                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6730                 bd_len = mh6->blk_desc_len;
6731                 break;
6732         }
6733         case MODE_SELECT_10: {
6734                 struct scsi_mode_header_10 *mh10;
6735
6736                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6737                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6738                 break;
6739         }
6740         default:
6741                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6742                 break;
6743         }
6744
6745         if (param_len < (header_size + bd_len)) {
6746                 free(ctsio->kern_data_ptr, M_CTL);
6747                 ctl_set_param_len_error(ctsio);
6748                 ctl_done((union ctl_io *)ctsio);
6749                 return (CTL_RETVAL_COMPLETE);
6750         }
6751
6752         /*
6753          * Set the IO_CONT flag, so that if this I/O gets passed to
6754          * ctl_config_write_done(), it'll get passed back to
6755          * ctl_do_mode_select() for further processing, or completion if
6756          * we're all done.
6757          */
6758         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6759         ctsio->io_cont = ctl_do_mode_select;
6760
6761         modepage_info = (union ctl_modepage_info *)
6762                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6763
6764         memset(modepage_info, 0, sizeof(*modepage_info));
6765
6766         len_left = param_len - header_size - bd_len;
6767         len_used = header_size + bd_len;
6768
6769         modepage_info->header.len_left = len_left;
6770         modepage_info->header.len_used = len_used;
6771
6772         return (ctl_do_mode_select((union ctl_io *)ctsio));
6773 }
6774
6775 int
6776 ctl_mode_sense(struct ctl_scsiio *ctsio)
6777 {
6778         struct ctl_lun *lun;
6779         int pc, page_code, dbd, llba, subpage;
6780         int alloc_len, page_len, header_len, total_len;
6781         struct scsi_mode_block_descr *block_desc;
6782         struct ctl_page_index *page_index;
6783         int control_dev;
6784
6785         dbd = 0;
6786         llba = 0;
6787         block_desc = NULL;
6788         page_index = NULL;
6789
6790         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6791
6792         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6793
6794         if (lun->be_lun->lun_type != T_DIRECT)
6795                 control_dev = 1;
6796         else
6797                 control_dev = 0;
6798
6799         if (lun->flags & CTL_LUN_PR_RESERVED) {
6800                 uint32_t residx;
6801
6802                 /*
6803                  * XXX KDM need a lock here.
6804                  */
6805                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6806                 if ((lun->res_type == SPR_TYPE_EX_AC
6807                   && residx != lun->pr_res_idx)
6808                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
6809                    || lun->res_type == SPR_TYPE_EX_AC_AR)
6810                   && !lun->per_res[residx].registered)) {
6811                         ctl_set_reservation_conflict(ctsio);
6812                         ctl_done((union ctl_io *)ctsio);
6813                         return (CTL_RETVAL_COMPLETE);
6814                 }
6815         }
6816
6817         switch (ctsio->cdb[0]) {
6818         case MODE_SENSE_6: {
6819                 struct scsi_mode_sense_6 *cdb;
6820
6821                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6822
6823                 header_len = sizeof(struct scsi_mode_hdr_6);
6824                 if (cdb->byte2 & SMS_DBD)
6825                         dbd = 1;
6826                 else
6827                         header_len += sizeof(struct scsi_mode_block_descr);
6828
6829                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6830                 page_code = cdb->page & SMS_PAGE_CODE;
6831                 subpage = cdb->subpage;
6832                 alloc_len = cdb->length;
6833                 break;
6834         }
6835         case MODE_SENSE_10: {
6836                 struct scsi_mode_sense_10 *cdb;
6837
6838                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6839
6840                 header_len = sizeof(struct scsi_mode_hdr_10);
6841
6842                 if (cdb->byte2 & SMS_DBD)
6843                         dbd = 1;
6844                 else
6845                         header_len += sizeof(struct scsi_mode_block_descr);
6846                 if (cdb->byte2 & SMS10_LLBAA)
6847                         llba = 1;
6848                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6849                 page_code = cdb->page & SMS_PAGE_CODE;
6850                 subpage = cdb->subpage;
6851                 alloc_len = scsi_2btoul(cdb->length);
6852                 break;
6853         }
6854         default:
6855                 ctl_set_invalid_opcode(ctsio);
6856                 ctl_done((union ctl_io *)ctsio);
6857                 return (CTL_RETVAL_COMPLETE);
6858                 break; /* NOTREACHED */
6859         }
6860
6861         /*
6862          * We have to make a first pass through to calculate the size of
6863          * the pages that match the user's query.  Then we allocate enough
6864          * memory to hold it, and actually copy the data into the buffer.
6865          */
6866         switch (page_code) {
6867         case SMS_ALL_PAGES_PAGE: {
6868                 int i;
6869
6870                 page_len = 0;
6871
6872                 /*
6873                  * At the moment, values other than 0 and 0xff here are
6874                  * reserved according to SPC-3.
6875                  */
6876                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6877                  && (subpage != SMS_SUBPAGE_ALL)) {
6878                         ctl_set_invalid_field(ctsio,
6879                                               /*sks_valid*/ 1,
6880                                               /*command*/ 1,
6881                                               /*field*/ 3,
6882                                               /*bit_valid*/ 0,
6883                                               /*bit*/ 0);
6884                         ctl_done((union ctl_io *)ctsio);
6885                         return (CTL_RETVAL_COMPLETE);
6886                 }
6887
6888                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6889                         if ((control_dev != 0)
6890                          && (lun->mode_pages.index[i].page_flags &
6891                              CTL_PAGE_FLAG_DISK_ONLY))
6892                                 continue;
6893
6894                         /*
6895                          * We don't use this subpage if the user didn't
6896                          * request all subpages.
6897                          */
6898                         if ((lun->mode_pages.index[i].subpage != 0)
6899                          && (subpage == SMS_SUBPAGE_PAGE_0))
6900                                 continue;
6901
6902 #if 0
6903                         printf("found page %#x len %d\n",
6904                                lun->mode_pages.index[i].page_code &
6905                                SMPH_PC_MASK,
6906                                lun->mode_pages.index[i].page_len);
6907 #endif
6908                         page_len += lun->mode_pages.index[i].page_len;
6909                 }
6910                 break;
6911         }
6912         default: {
6913                 int i;
6914
6915                 page_len = 0;
6916
6917                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6918                         /* Look for the right page code */
6919                         if ((lun->mode_pages.index[i].page_code &
6920                              SMPH_PC_MASK) != page_code)
6921                                 continue;
6922
6923                         /* Look for the right subpage or the subpage wildcard*/
6924                         if ((lun->mode_pages.index[i].subpage != subpage)
6925                          && (subpage != SMS_SUBPAGE_ALL))
6926                                 continue;
6927
6928                         /* Make sure the page is supported for this dev type */
6929                         if ((control_dev != 0)
6930                          && (lun->mode_pages.index[i].page_flags &
6931                              CTL_PAGE_FLAG_DISK_ONLY))
6932                                 continue;
6933
6934 #if 0
6935                         printf("found page %#x len %d\n",
6936                                lun->mode_pages.index[i].page_code &
6937                                SMPH_PC_MASK,
6938                                lun->mode_pages.index[i].page_len);
6939 #endif
6940
6941                         page_len += lun->mode_pages.index[i].page_len;
6942                 }
6943
6944                 if (page_len == 0) {
6945                         ctl_set_invalid_field(ctsio,
6946                                               /*sks_valid*/ 1,
6947                                               /*command*/ 1,
6948                                               /*field*/ 2,
6949                                               /*bit_valid*/ 1,
6950                                               /*bit*/ 5);
6951                         ctl_done((union ctl_io *)ctsio);
6952                         return (CTL_RETVAL_COMPLETE);
6953                 }
6954                 break;
6955         }
6956         }
6957
6958         total_len = header_len + page_len;
6959 #if 0
6960         printf("header_len = %d, page_len = %d, total_len = %d\n",
6961                header_len, page_len, total_len);
6962 #endif
6963
6964         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6965         ctsio->kern_sg_entries = 0;
6966         ctsio->kern_data_resid = 0;
6967         ctsio->kern_rel_offset = 0;
6968         if (total_len < alloc_len) {
6969                 ctsio->residual = alloc_len - total_len;
6970                 ctsio->kern_data_len = total_len;
6971                 ctsio->kern_total_len = total_len;
6972         } else {
6973                 ctsio->residual = 0;
6974                 ctsio->kern_data_len = alloc_len;
6975                 ctsio->kern_total_len = alloc_len;
6976         }
6977
6978         switch (ctsio->cdb[0]) {
6979         case MODE_SENSE_6: {
6980                 struct scsi_mode_hdr_6 *header;
6981
6982                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6983
6984                 header->datalen = ctl_min(total_len - 1, 254);
6985
6986                 if (dbd)
6987                         header->block_descr_len = 0;
6988                 else
6989                         header->block_descr_len =
6990                                 sizeof(struct scsi_mode_block_descr);
6991                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6992                 break;
6993         }
6994         case MODE_SENSE_10: {
6995                 struct scsi_mode_hdr_10 *header;
6996                 int datalen;
6997
6998                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6999
7000                 datalen = ctl_min(total_len - 2, 65533);
7001                 scsi_ulto2b(datalen, header->datalen);
7002                 if (dbd)
7003                         scsi_ulto2b(0, header->block_descr_len);
7004                 else
7005                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7006                                     header->block_descr_len);
7007                 block_desc = (struct scsi_mode_block_descr *)&header[1];
7008                 break;
7009         }
7010         default:
7011                 panic("invalid CDB type %#x", ctsio->cdb[0]);
7012                 break; /* NOTREACHED */
7013         }
7014
7015         /*
7016          * If we've got a disk, use its blocksize in the block
7017          * descriptor.  Otherwise, just set it to 0.
7018          */
7019         if (dbd == 0) {
7020                 if (control_dev != 0)
7021                         scsi_ulto3b(lun->be_lun->blocksize,
7022                                     block_desc->block_len);
7023                 else
7024                         scsi_ulto3b(0, block_desc->block_len);
7025         }
7026
7027         switch (page_code) {
7028         case SMS_ALL_PAGES_PAGE: {
7029                 int i, data_used;
7030
7031                 data_used = header_len;
7032                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7033                         struct ctl_page_index *page_index;
7034
7035                         page_index = &lun->mode_pages.index[i];
7036
7037                         if ((control_dev != 0)
7038                          && (page_index->page_flags &
7039                             CTL_PAGE_FLAG_DISK_ONLY))
7040                                 continue;
7041
7042                         /*
7043                          * We don't use this subpage if the user didn't
7044                          * request all subpages.  We already checked (above)
7045                          * to make sure the user only specified a subpage
7046                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7047                          */
7048                         if ((page_index->subpage != 0)
7049                          && (subpage == SMS_SUBPAGE_PAGE_0))
7050                                 continue;
7051
7052                         /*
7053                          * Call the handler, if it exists, to update the
7054                          * page to the latest values.
7055                          */
7056                         if (page_index->sense_handler != NULL)
7057                                 page_index->sense_handler(ctsio, page_index,pc);
7058
7059                         memcpy(ctsio->kern_data_ptr + data_used,
7060                                page_index->page_data +
7061                                (page_index->page_len * pc),
7062                                page_index->page_len);
7063                         data_used += page_index->page_len;
7064                 }
7065                 break;
7066         }
7067         default: {
7068                 int i, data_used;
7069
7070                 data_used = header_len;
7071
7072                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7073                         struct ctl_page_index *page_index;
7074
7075                         page_index = &lun->mode_pages.index[i];
7076
7077                         /* Look for the right page code */
7078                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7079                                 continue;
7080
7081                         /* Look for the right subpage or the subpage wildcard*/
7082                         if ((page_index->subpage != subpage)
7083                          && (subpage != SMS_SUBPAGE_ALL))
7084                                 continue;
7085
7086                         /* Make sure the page is supported for this dev type */
7087                         if ((control_dev != 0)
7088                          && (page_index->page_flags &
7089                              CTL_PAGE_FLAG_DISK_ONLY))
7090                                 continue;
7091
7092                         /*
7093                          * Call the handler, if it exists, to update the
7094                          * page to the latest values.
7095                          */
7096                         if (page_index->sense_handler != NULL)
7097                                 page_index->sense_handler(ctsio, page_index,pc);
7098
7099                         memcpy(ctsio->kern_data_ptr + data_used,
7100                                page_index->page_data +
7101                                (page_index->page_len * pc),
7102                                page_index->page_len);
7103                         data_used += page_index->page_len;
7104                 }
7105                 break;
7106         }
7107         }
7108
7109         ctsio->scsi_status = SCSI_STATUS_OK;
7110
7111         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7112         ctsio->be_move_done = ctl_config_move_done;
7113         ctl_datamove((union ctl_io *)ctsio);
7114
7115         return (CTL_RETVAL_COMPLETE);
7116 }
7117
7118 int
7119 ctl_read_capacity(struct ctl_scsiio *ctsio)
7120 {
7121         struct scsi_read_capacity *cdb;
7122         struct scsi_read_capacity_data *data;
7123         struct ctl_lun *lun;
7124         uint32_t lba;
7125
7126         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7127
7128         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7129
7130         lba = scsi_4btoul(cdb->addr);
7131         if (((cdb->pmi & SRC_PMI) == 0)
7132          && (lba != 0)) {
7133                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7134                                       /*sks_valid*/ 1,
7135                                       /*command*/ 1,
7136                                       /*field*/ 2,
7137                                       /*bit_valid*/ 0,
7138                                       /*bit*/ 0);
7139                 ctl_done((union ctl_io *)ctsio);
7140                 return (CTL_RETVAL_COMPLETE);
7141         }
7142
7143         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7144
7145         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7146         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7147         ctsio->residual = 0;
7148         ctsio->kern_data_len = sizeof(*data);
7149         ctsio->kern_total_len = sizeof(*data);
7150         ctsio->kern_data_resid = 0;
7151         ctsio->kern_rel_offset = 0;
7152         ctsio->kern_sg_entries = 0;
7153
7154         /*
7155          * If the maximum LBA is greater than 0xfffffffe, the user must
7156          * issue a SERVICE ACTION IN (16) command, with the read capacity
7157          * serivce action set.
7158          */
7159         if (lun->be_lun->maxlba > 0xfffffffe)
7160                 scsi_ulto4b(0xffffffff, data->addr);
7161         else
7162                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7163
7164         /*
7165          * XXX KDM this may not be 512 bytes...
7166          */
7167         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7168
7169         ctsio->scsi_status = SCSI_STATUS_OK;
7170
7171         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7172         ctsio->be_move_done = ctl_config_move_done;
7173         ctl_datamove((union ctl_io *)ctsio);
7174
7175         return (CTL_RETVAL_COMPLETE);
7176 }
7177
7178 int
7179 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7180 {
7181         struct scsi_read_capacity_16 *cdb;
7182         struct scsi_read_capacity_data_long *data;
7183         struct ctl_lun *lun;
7184         uint64_t lba;
7185         uint32_t alloc_len;
7186
7187         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7188
7189         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7190
7191         alloc_len = scsi_4btoul(cdb->alloc_len);
7192         lba = scsi_8btou64(cdb->addr);
7193
7194         if ((cdb->reladr & SRC16_PMI)
7195          && (lba != 0)) {
7196                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7197                                       /*sks_valid*/ 1,
7198                                       /*command*/ 1,
7199                                       /*field*/ 2,
7200                                       /*bit_valid*/ 0,
7201                                       /*bit*/ 0);
7202                 ctl_done((union ctl_io *)ctsio);
7203                 return (CTL_RETVAL_COMPLETE);
7204         }
7205
7206         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7207
7208         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7209         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7210
7211         if (sizeof(*data) < alloc_len) {
7212                 ctsio->residual = alloc_len - sizeof(*data);
7213                 ctsio->kern_data_len = sizeof(*data);
7214                 ctsio->kern_total_len = sizeof(*data);
7215         } else {
7216                 ctsio->residual = 0;
7217                 ctsio->kern_data_len = alloc_len;
7218                 ctsio->kern_total_len = alloc_len;
7219         }
7220         ctsio->kern_data_resid = 0;
7221         ctsio->kern_rel_offset = 0;
7222         ctsio->kern_sg_entries = 0;
7223
7224         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7225         /* XXX KDM this may not be 512 bytes... */
7226         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7227         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7228         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7229         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7230                 data->lalba_lbp[0] |= SRC16_LBPME;
7231
7232         ctsio->scsi_status = SCSI_STATUS_OK;
7233
7234         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7235         ctsio->be_move_done = ctl_config_move_done;
7236         ctl_datamove((union ctl_io *)ctsio);
7237
7238         return (CTL_RETVAL_COMPLETE);
7239 }
7240
7241 int
7242 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7243 {
7244         struct scsi_maintenance_in *cdb;
7245         int retval;
7246         int alloc_len, ext, total_len = 0, g, p, pc, pg;
7247         int num_target_port_groups, num_target_ports, single;
7248         struct ctl_lun *lun;
7249         struct ctl_softc *softc;
7250         struct ctl_port *port;
7251         struct scsi_target_group_data *rtg_ptr;
7252         struct scsi_target_group_data_extended *rtg_ext_ptr;
7253         struct scsi_target_port_group_descriptor *tpg_desc;
7254
7255         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7256
7257         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7258         softc = control_softc;
7259         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7260
7261         retval = CTL_RETVAL_COMPLETE;
7262
7263         switch (cdb->byte2 & STG_PDF_MASK) {
7264         case STG_PDF_LENGTH:
7265                 ext = 0;
7266                 break;
7267         case STG_PDF_EXTENDED:
7268                 ext = 1;
7269                 break;
7270         default:
7271                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7272                                       /*sks_valid*/ 1,
7273                                       /*command*/ 1,
7274                                       /*field*/ 2,
7275                                       /*bit_valid*/ 1,
7276                                       /*bit*/ 5);
7277                 ctl_done((union ctl_io *)ctsio);
7278                 return(retval);
7279         }
7280
7281         single = ctl_is_single;
7282         if (single)
7283                 num_target_port_groups = 1;
7284         else
7285                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7286         num_target_ports = 0;
7287         mtx_lock(&softc->ctl_lock);
7288         STAILQ_FOREACH(port, &softc->port_list, links) {
7289                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7290                         continue;
7291                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7292                         continue;
7293                 num_target_ports++;
7294         }
7295         mtx_unlock(&softc->ctl_lock);
7296
7297         if (ext)
7298                 total_len = sizeof(struct scsi_target_group_data_extended);
7299         else
7300                 total_len = sizeof(struct scsi_target_group_data);
7301         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7302                 num_target_port_groups +
7303             sizeof(struct scsi_target_port_descriptor) *
7304                 num_target_ports * num_target_port_groups;
7305
7306         alloc_len = scsi_4btoul(cdb->length);
7307
7308         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7309
7310         ctsio->kern_sg_entries = 0;
7311
7312         if (total_len < alloc_len) {
7313                 ctsio->residual = alloc_len - total_len;
7314                 ctsio->kern_data_len = total_len;
7315                 ctsio->kern_total_len = total_len;
7316         } else {
7317                 ctsio->residual = 0;
7318                 ctsio->kern_data_len = alloc_len;
7319                 ctsio->kern_total_len = alloc_len;
7320         }
7321         ctsio->kern_data_resid = 0;
7322         ctsio->kern_rel_offset = 0;
7323
7324         if (ext) {
7325                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7326                     ctsio->kern_data_ptr;
7327                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7328                 rtg_ext_ptr->format_type = 0x10;
7329                 rtg_ext_ptr->implicit_transition_time = 0;
7330                 tpg_desc = &rtg_ext_ptr->groups[0];
7331         } else {
7332                 rtg_ptr = (struct scsi_target_group_data *)
7333                     ctsio->kern_data_ptr;
7334                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7335                 tpg_desc = &rtg_ptr->groups[0];
7336         }
7337
7338         pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7339         mtx_lock(&softc->ctl_lock);
7340         for (g = 0; g < num_target_port_groups; g++) {
7341                 if (g == pg)
7342                         tpg_desc->pref_state = TPG_PRIMARY |
7343                             TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7344                 else
7345                         tpg_desc->pref_state =
7346                             TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7347                 tpg_desc->support = TPG_AO_SUP;
7348                 if (!single)
7349                         tpg_desc->support |= TPG_AN_SUP;
7350                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7351                 tpg_desc->status = TPG_IMPLICIT;
7352                 pc = 0;
7353                 STAILQ_FOREACH(port, &softc->port_list, links) {
7354                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7355                                 continue;
7356                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7357                             CTL_MAX_LUNS)
7358                                 continue;
7359                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7360                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7361                             relative_target_port_identifier);
7362                         pc++;
7363                 }
7364                 tpg_desc->target_port_count = pc;
7365                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7366                     &tpg_desc->descriptors[pc];
7367         }
7368         mtx_unlock(&softc->ctl_lock);
7369
7370         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7371         ctsio->be_move_done = ctl_config_move_done;
7372
7373         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7374                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7375                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7376                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7377                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7378
7379         ctl_datamove((union ctl_io *)ctsio);
7380         return(retval);
7381 }
7382
7383 int
7384 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7385 {
7386         struct ctl_lun *lun;
7387         struct scsi_report_supported_opcodes *cdb;
7388         const struct ctl_cmd_entry *entry, *sentry;
7389         struct scsi_report_supported_opcodes_all *all;
7390         struct scsi_report_supported_opcodes_descr *descr;
7391         struct scsi_report_supported_opcodes_one *one;
7392         int retval;
7393         int alloc_len, total_len;
7394         int opcode, service_action, i, j, num;
7395
7396         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7397
7398         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7399         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7400
7401         retval = CTL_RETVAL_COMPLETE;
7402
7403         opcode = cdb->requested_opcode;
7404         service_action = scsi_2btoul(cdb->requested_service_action);
7405         switch (cdb->options & RSO_OPTIONS_MASK) {
7406         case RSO_OPTIONS_ALL:
7407                 num = 0;
7408                 for (i = 0; i < 256; i++) {
7409                         entry = &ctl_cmd_table[i];
7410                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7411                                 for (j = 0; j < 32; j++) {
7412                                         sentry = &((const struct ctl_cmd_entry *)
7413                                             entry->execute)[j];
7414                                         if (ctl_cmd_applicable(
7415                                             lun->be_lun->lun_type, sentry))
7416                                                 num++;
7417                                 }
7418                         } else {
7419                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7420                                     entry))
7421                                         num++;
7422                         }
7423                 }
7424                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7425                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7426                 break;
7427         case RSO_OPTIONS_OC:
7428                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7429                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7430                                               /*sks_valid*/ 1,
7431                                               /*command*/ 1,
7432                                               /*field*/ 2,
7433                                               /*bit_valid*/ 1,
7434                                               /*bit*/ 2);
7435                         ctl_done((union ctl_io *)ctsio);
7436                         return (CTL_RETVAL_COMPLETE);
7437                 }
7438                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7439                 break;
7440         case RSO_OPTIONS_OC_SA:
7441                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7442                     service_action >= 32) {
7443                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7444                                               /*sks_valid*/ 1,
7445                                               /*command*/ 1,
7446                                               /*field*/ 2,
7447                                               /*bit_valid*/ 1,
7448                                               /*bit*/ 2);
7449                         ctl_done((union ctl_io *)ctsio);
7450                         return (CTL_RETVAL_COMPLETE);
7451                 }
7452                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7453                 break;
7454         default:
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
7465         alloc_len = scsi_4btoul(cdb->length);
7466
7467         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7468
7469         ctsio->kern_sg_entries = 0;
7470
7471         if (total_len < alloc_len) {
7472                 ctsio->residual = alloc_len - total_len;
7473                 ctsio->kern_data_len = total_len;
7474                 ctsio->kern_total_len = total_len;
7475         } else {
7476                 ctsio->residual = 0;
7477                 ctsio->kern_data_len = alloc_len;
7478                 ctsio->kern_total_len = alloc_len;
7479         }
7480         ctsio->kern_data_resid = 0;
7481         ctsio->kern_rel_offset = 0;
7482
7483         switch (cdb->options & RSO_OPTIONS_MASK) {
7484         case RSO_OPTIONS_ALL:
7485                 all = (struct scsi_report_supported_opcodes_all *)
7486                     ctsio->kern_data_ptr;
7487                 num = 0;
7488                 for (i = 0; i < 256; i++) {
7489                         entry = &ctl_cmd_table[i];
7490                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7491                                 for (j = 0; j < 32; j++) {
7492                                         sentry = &((const struct ctl_cmd_entry *)
7493                                             entry->execute)[j];
7494                                         if (!ctl_cmd_applicable(
7495                                             lun->be_lun->lun_type, sentry))
7496                                                 continue;
7497                                         descr = &all->descr[num++];
7498                                         descr->opcode = i;
7499                                         scsi_ulto2b(j, descr->service_action);
7500                                         descr->flags = RSO_SERVACTV;
7501                                         scsi_ulto2b(sentry->length,
7502                                             descr->cdb_length);
7503                                 }
7504                         } else {
7505                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7506                                     entry))
7507                                         continue;
7508                                 descr = &all->descr[num++];
7509                                 descr->opcode = i;
7510                                 scsi_ulto2b(0, descr->service_action);
7511                                 descr->flags = 0;
7512                                 scsi_ulto2b(entry->length, descr->cdb_length);
7513                         }
7514                 }
7515                 scsi_ulto4b(
7516                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7517                     all->length);
7518                 break;
7519         case RSO_OPTIONS_OC:
7520                 one = (struct scsi_report_supported_opcodes_one *)
7521                     ctsio->kern_data_ptr;
7522                 entry = &ctl_cmd_table[opcode];
7523                 goto fill_one;
7524         case RSO_OPTIONS_OC_SA:
7525                 one = (struct scsi_report_supported_opcodes_one *)
7526                     ctsio->kern_data_ptr;
7527                 entry = &ctl_cmd_table[opcode];
7528                 entry = &((const struct ctl_cmd_entry *)
7529                     entry->execute)[service_action];
7530 fill_one:
7531                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7532                         one->support = 3;
7533                         scsi_ulto2b(entry->length, one->cdb_length);
7534                         one->cdb_usage[0] = opcode;
7535                         memcpy(&one->cdb_usage[1], entry->usage,
7536                             entry->length - 1);
7537                 } else
7538                         one->support = 1;
7539                 break;
7540         }
7541
7542         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7543         ctsio->be_move_done = ctl_config_move_done;
7544
7545         ctl_datamove((union ctl_io *)ctsio);
7546         return(retval);
7547 }
7548
7549 int
7550 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7551 {
7552         struct ctl_lun *lun;
7553         struct scsi_report_supported_tmf *cdb;
7554         struct scsi_report_supported_tmf_data *data;
7555         int retval;
7556         int alloc_len, total_len;
7557
7558         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7559
7560         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7561         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7562
7563         retval = CTL_RETVAL_COMPLETE;
7564
7565         total_len = sizeof(struct scsi_report_supported_tmf_data);
7566         alloc_len = scsi_4btoul(cdb->length);
7567
7568         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7569
7570         ctsio->kern_sg_entries = 0;
7571
7572         if (total_len < alloc_len) {
7573                 ctsio->residual = alloc_len - total_len;
7574                 ctsio->kern_data_len = total_len;
7575                 ctsio->kern_total_len = total_len;
7576         } else {
7577                 ctsio->residual = 0;
7578                 ctsio->kern_data_len = alloc_len;
7579                 ctsio->kern_total_len = alloc_len;
7580         }
7581         ctsio->kern_data_resid = 0;
7582         ctsio->kern_rel_offset = 0;
7583
7584         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7585         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7586         data->byte2 |= RST_ITNRS;
7587
7588         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7589         ctsio->be_move_done = ctl_config_move_done;
7590
7591         ctl_datamove((union ctl_io *)ctsio);
7592         return (retval);
7593 }
7594
7595 int
7596 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7597 {
7598         struct ctl_lun *lun;
7599         struct scsi_report_timestamp *cdb;
7600         struct scsi_report_timestamp_data *data;
7601         struct timeval tv;
7602         int64_t timestamp;
7603         int retval;
7604         int alloc_len, total_len;
7605
7606         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7607
7608         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7609         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7610
7611         retval = CTL_RETVAL_COMPLETE;
7612
7613         total_len = sizeof(struct scsi_report_timestamp_data);
7614         alloc_len = scsi_4btoul(cdb->length);
7615
7616         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7617
7618         ctsio->kern_sg_entries = 0;
7619
7620         if (total_len < alloc_len) {
7621                 ctsio->residual = alloc_len - total_len;
7622                 ctsio->kern_data_len = total_len;
7623                 ctsio->kern_total_len = total_len;
7624         } else {
7625                 ctsio->residual = 0;
7626                 ctsio->kern_data_len = alloc_len;
7627                 ctsio->kern_total_len = alloc_len;
7628         }
7629         ctsio->kern_data_resid = 0;
7630         ctsio->kern_rel_offset = 0;
7631
7632         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7633         scsi_ulto2b(sizeof(*data) - 2, data->length);
7634         data->origin = RTS_ORIG_OUTSIDE;
7635         getmicrotime(&tv);
7636         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7637         scsi_ulto4b(timestamp >> 16, data->timestamp);
7638         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7639
7640         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7641         ctsio->be_move_done = ctl_config_move_done;
7642
7643         ctl_datamove((union ctl_io *)ctsio);
7644         return (retval);
7645 }
7646
7647 int
7648 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7649 {
7650         struct scsi_per_res_in *cdb;
7651         int alloc_len, total_len = 0;
7652         /* struct scsi_per_res_in_rsrv in_data; */
7653         struct ctl_lun *lun;
7654         struct ctl_softc *softc;
7655
7656         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7657
7658         softc = control_softc;
7659
7660         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7661
7662         alloc_len = scsi_2btoul(cdb->length);
7663
7664         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7665
7666 retry:
7667         mtx_lock(&lun->lun_lock);
7668         switch (cdb->action) {
7669         case SPRI_RK: /* read keys */
7670                 total_len = sizeof(struct scsi_per_res_in_keys) +
7671                         lun->pr_key_count *
7672                         sizeof(struct scsi_per_res_key);
7673                 break;
7674         case SPRI_RR: /* read reservation */
7675                 if (lun->flags & CTL_LUN_PR_RESERVED)
7676                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7677                 else
7678                         total_len = sizeof(struct scsi_per_res_in_header);
7679                 break;
7680         case SPRI_RC: /* report capabilities */
7681                 total_len = sizeof(struct scsi_per_res_cap);
7682                 break;
7683         case SPRI_RS: /* read full status */
7684                 total_len = sizeof(struct scsi_per_res_in_header) +
7685                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7686                     lun->pr_key_count;
7687                 break;
7688         default:
7689                 panic("Invalid PR type %x", cdb->action);
7690         }
7691         mtx_unlock(&lun->lun_lock);
7692
7693         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7694
7695         if (total_len < alloc_len) {
7696                 ctsio->residual = alloc_len - total_len;
7697                 ctsio->kern_data_len = total_len;
7698                 ctsio->kern_total_len = total_len;
7699         } else {
7700                 ctsio->residual = 0;
7701                 ctsio->kern_data_len = alloc_len;
7702                 ctsio->kern_total_len = alloc_len;
7703         }
7704
7705         ctsio->kern_data_resid = 0;
7706         ctsio->kern_rel_offset = 0;
7707         ctsio->kern_sg_entries = 0;
7708
7709         mtx_lock(&lun->lun_lock);
7710         switch (cdb->action) {
7711         case SPRI_RK: { // read keys
7712         struct scsi_per_res_in_keys *res_keys;
7713                 int i, key_count;
7714
7715                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7716
7717                 /*
7718                  * We had to drop the lock to allocate our buffer, which
7719                  * leaves time for someone to come in with another
7720                  * persistent reservation.  (That is unlikely, though,
7721                  * since this should be the only persistent reservation
7722                  * command active right now.)
7723                  */
7724                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7725                     (lun->pr_key_count *
7726                      sizeof(struct scsi_per_res_key)))){
7727                         mtx_unlock(&lun->lun_lock);
7728                         free(ctsio->kern_data_ptr, M_CTL);
7729                         printf("%s: reservation length changed, retrying\n",
7730                                __func__);
7731                         goto retry;
7732                 }
7733
7734                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7735
7736                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7737                              lun->pr_key_count, res_keys->header.length);
7738
7739                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7740                         if (!lun->per_res[i].registered)
7741                                 continue;
7742
7743                         /*
7744                          * We used lun->pr_key_count to calculate the
7745                          * size to allocate.  If it turns out the number of
7746                          * initiators with the registered flag set is
7747                          * larger than that (i.e. they haven't been kept in
7748                          * sync), we've got a problem.
7749                          */
7750                         if (key_count >= lun->pr_key_count) {
7751 #ifdef NEEDTOPORT
7752                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7753                                             CTL_PR_ERROR,
7754                                             csevent_LogType_Fault,
7755                                             csevent_AlertLevel_Yellow,
7756                                             csevent_FRU_ShelfController,
7757                                             csevent_FRU_Firmware,
7758                                         csevent_FRU_Unknown,
7759                                             "registered keys %d >= key "
7760                                             "count %d", key_count,
7761                                             lun->pr_key_count);
7762 #endif
7763                                 key_count++;
7764                                 continue;
7765                         }
7766                         memcpy(res_keys->keys[key_count].key,
7767                                lun->per_res[i].res_key.key,
7768                                ctl_min(sizeof(res_keys->keys[key_count].key),
7769                                sizeof(lun->per_res[i].res_key)));
7770                         key_count++;
7771                 }
7772                 break;
7773         }
7774         case SPRI_RR: { // read reservation
7775                 struct scsi_per_res_in_rsrv *res;
7776                 int tmp_len, header_only;
7777
7778                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7779
7780                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7781
7782                 if (lun->flags & CTL_LUN_PR_RESERVED)
7783                 {
7784                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7785                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7786                                     res->header.length);
7787                         header_only = 0;
7788                 } else {
7789                         tmp_len = sizeof(struct scsi_per_res_in_header);
7790                         scsi_ulto4b(0, res->header.length);
7791                         header_only = 1;
7792                 }
7793
7794                 /*
7795                  * We had to drop the lock to allocate our buffer, which
7796                  * leaves time for someone to come in with another
7797                  * persistent reservation.  (That is unlikely, though,
7798                  * since this should be the only persistent reservation
7799                  * command active right now.)
7800                  */
7801                 if (tmp_len != total_len) {
7802                         mtx_unlock(&lun->lun_lock);
7803                         free(ctsio->kern_data_ptr, M_CTL);
7804                         printf("%s: reservation status changed, retrying\n",
7805                                __func__);
7806                         goto retry;
7807                 }
7808
7809                 /*
7810                  * No reservation held, so we're done.
7811                  */
7812                 if (header_only != 0)
7813                         break;
7814
7815                 /*
7816                  * If the registration is an All Registrants type, the key
7817                  * is 0, since it doesn't really matter.
7818                  */
7819                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7820                         memcpy(res->data.reservation,
7821                                &lun->per_res[lun->pr_res_idx].res_key,
7822                                sizeof(struct scsi_per_res_key));
7823                 }
7824                 res->data.scopetype = lun->res_type;
7825                 break;
7826         }
7827         case SPRI_RC:     //report capabilities
7828         {
7829                 struct scsi_per_res_cap *res_cap;
7830                 uint16_t type_mask;
7831
7832                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7833                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7834                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7835                 type_mask = SPRI_TM_WR_EX_AR |
7836                             SPRI_TM_EX_AC_RO |
7837                             SPRI_TM_WR_EX_RO |
7838                             SPRI_TM_EX_AC |
7839                             SPRI_TM_WR_EX |
7840                             SPRI_TM_EX_AC_AR;
7841                 scsi_ulto2b(type_mask, res_cap->type_mask);
7842                 break;
7843         }
7844         case SPRI_RS: { // read full status
7845                 struct scsi_per_res_in_full *res_status;
7846                 struct scsi_per_res_in_full_desc *res_desc;
7847                 struct ctl_port *port;
7848                 int i, len;
7849
7850                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7851
7852                 /*
7853                  * We had to drop the lock to allocate our buffer, which
7854                  * leaves time for someone to come in with another
7855                  * persistent reservation.  (That is unlikely, though,
7856                  * since this should be the only persistent reservation
7857                  * command active right now.)
7858                  */
7859                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7860                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7861                      lun->pr_key_count)){
7862                         mtx_unlock(&lun->lun_lock);
7863                         free(ctsio->kern_data_ptr, M_CTL);
7864                         printf("%s: reservation length changed, retrying\n",
7865                                __func__);
7866                         goto retry;
7867                 }
7868
7869                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7870
7871                 res_desc = &res_status->desc[0];
7872                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7873                         if (!lun->per_res[i].registered)
7874                                 continue;
7875
7876                         memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7877                             sizeof(res_desc->res_key));
7878                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7879                             (lun->pr_res_idx == i ||
7880                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7881                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7882                                 res_desc->scopetype = lun->res_type;
7883                         }
7884                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7885                             res_desc->rel_trgt_port_id);
7886                         len = 0;
7887                         port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7888                         if (port != NULL)
7889                                 len = ctl_create_iid(port,
7890                                     i % CTL_MAX_INIT_PER_PORT,
7891                                     res_desc->transport_id);
7892                         scsi_ulto4b(len, res_desc->additional_length);
7893                         res_desc = (struct scsi_per_res_in_full_desc *)
7894                             &res_desc->transport_id[len];
7895                 }
7896                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7897                     res_status->header.length);
7898                 break;
7899         }
7900         default:
7901                 /*
7902                  * This is a bug, because we just checked for this above,
7903                  * and should have returned an error.
7904                  */
7905                 panic("Invalid PR type %x", cdb->action);
7906                 break; /* NOTREACHED */
7907         }
7908         mtx_unlock(&lun->lun_lock);
7909
7910         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7911         ctsio->be_move_done = ctl_config_move_done;
7912
7913         CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7914                          ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7915                          ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7916                          ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7917                          ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7918
7919         ctl_datamove((union ctl_io *)ctsio);
7920
7921         return (CTL_RETVAL_COMPLETE);
7922 }
7923
7924 /*
7925  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7926  * it should return.
7927  */
7928 static int
7929 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7930                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7931                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7932                 struct scsi_per_res_out_parms* param)
7933 {
7934         union ctl_ha_msg persis_io;
7935         int retval, i;
7936         int isc_retval;
7937
7938         retval = 0;
7939
7940         mtx_lock(&lun->lun_lock);
7941         if (sa_res_key == 0) {
7942                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7943                         /* validate scope and type */
7944                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7945                              SPR_LU_SCOPE) {
7946                                 mtx_unlock(&lun->lun_lock);
7947                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7948                                                       /*sks_valid*/ 1,
7949                                                       /*command*/ 1,
7950                                                       /*field*/ 2,
7951                                                       /*bit_valid*/ 1,
7952                                                       /*bit*/ 4);
7953                                 ctl_done((union ctl_io *)ctsio);
7954                                 return (1);
7955                         }
7956
7957                         if (type>8 || type==2 || type==4 || type==0) {
7958                                 mtx_unlock(&lun->lun_lock);
7959                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7960                                                       /*sks_valid*/ 1,
7961                                                       /*command*/ 1,
7962                                                       /*field*/ 2,
7963                                                       /*bit_valid*/ 1,
7964                                                       /*bit*/ 0);
7965                                 ctl_done((union ctl_io *)ctsio);
7966                                 return (1);
7967                         }
7968
7969                         /* temporarily unregister this nexus */
7970                         lun->per_res[residx].registered = 0;
7971
7972                         /*
7973                          * Unregister everybody else and build UA for
7974                          * them
7975                          */
7976                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7977                                 if (lun->per_res[i].registered == 0)
7978                                         continue;
7979
7980                                 if (!persis_offset
7981                                  && i <CTL_MAX_INITIATORS)
7982                                         lun->pending_sense[i].ua_pending |=
7983                                                 CTL_UA_REG_PREEMPT;
7984                                 else if (persis_offset
7985                                       && i >= persis_offset)
7986                                         lun->pending_sense[i-persis_offset
7987                                                 ].ua_pending |=
7988                                                 CTL_UA_REG_PREEMPT;
7989                                 lun->per_res[i].registered = 0;
7990                                 memset(&lun->per_res[i].res_key, 0,
7991                                        sizeof(struct scsi_per_res_key));
7992                         }
7993                         lun->per_res[residx].registered = 1;
7994                         lun->pr_key_count = 1;
7995                         lun->res_type = type;
7996                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7997                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7998                                 lun->pr_res_idx = residx;
7999
8000                         /* send msg to other side */
8001                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8002                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8003                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8004                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8005                         persis_io.pr.pr_info.res_type = type;
8006                         memcpy(persis_io.pr.pr_info.sa_res_key,
8007                                param->serv_act_res_key,
8008                                sizeof(param->serv_act_res_key));
8009                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8010                              &persis_io, sizeof(persis_io), 0)) >
8011                              CTL_HA_STATUS_SUCCESS) {
8012                                 printf("CTL:Persis Out error returned "
8013                                        "from ctl_ha_msg_send %d\n",
8014                                        isc_retval);
8015                         }
8016                 } else {
8017                         /* not all registrants */
8018                         mtx_unlock(&lun->lun_lock);
8019                         free(ctsio->kern_data_ptr, M_CTL);
8020                         ctl_set_invalid_field(ctsio,
8021                                               /*sks_valid*/ 1,
8022                                               /*command*/ 0,
8023                                               /*field*/ 8,
8024                                               /*bit_valid*/ 0,
8025                                               /*bit*/ 0);
8026                         ctl_done((union ctl_io *)ctsio);
8027                         return (1);
8028                 }
8029         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8030                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8031                 int found = 0;
8032
8033                 if (res_key == sa_res_key) {
8034                         /* special case */
8035                         /*
8036                          * The spec implies this is not good but doesn't
8037                          * say what to do. There are two choices either
8038                          * generate a res conflict or check condition
8039                          * with illegal field in parameter data. Since
8040                          * that is what is done when the sa_res_key is
8041                          * zero I'll take that approach since this has
8042                          * to do with the sa_res_key.
8043                          */
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
8056                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8057                         if (lun->per_res[i].registered
8058                          && memcmp(param->serv_act_res_key,
8059                             lun->per_res[i].res_key.key,
8060                             sizeof(struct scsi_per_res_key)) != 0)
8061                                 continue;
8062
8063                         found = 1;
8064                         lun->per_res[i].registered = 0;
8065                         memset(&lun->per_res[i].res_key, 0,
8066                                sizeof(struct scsi_per_res_key));
8067                         lun->pr_key_count--;
8068
8069                         if (!persis_offset
8070                          && i < CTL_MAX_INITIATORS)
8071                                 lun->pending_sense[i].ua_pending |=
8072                                         CTL_UA_REG_PREEMPT;
8073                         else if (persis_offset
8074                               && i >= persis_offset)
8075                                 lun->pending_sense[i-persis_offset].ua_pending|=
8076                                         CTL_UA_REG_PREEMPT;
8077                 }
8078                 if (!found) {
8079                         mtx_unlock(&lun->lun_lock);
8080                         free(ctsio->kern_data_ptr, M_CTL);
8081                         ctl_set_reservation_conflict(ctsio);
8082                         ctl_done((union ctl_io *)ctsio);
8083                         return (CTL_RETVAL_COMPLETE);
8084                 }
8085                 /* send msg to other side */
8086                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8087                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8088                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8089                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8090                 persis_io.pr.pr_info.res_type = type;
8091                 memcpy(persis_io.pr.pr_info.sa_res_key,
8092                        param->serv_act_res_key,
8093                        sizeof(param->serv_act_res_key));
8094                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8095                      &persis_io, sizeof(persis_io), 0)) >
8096                      CTL_HA_STATUS_SUCCESS) {
8097                         printf("CTL:Persis Out error returned from "
8098                                "ctl_ha_msg_send %d\n", isc_retval);
8099                 }
8100         } else {
8101                 /* Reserved but not all registrants */
8102                 /* sa_res_key is res holder */
8103                 if (memcmp(param->serv_act_res_key,
8104                    lun->per_res[lun->pr_res_idx].res_key.key,
8105                    sizeof(struct scsi_per_res_key)) == 0) {
8106                         /* validate scope and type */
8107                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8108                              SPR_LU_SCOPE) {
8109                                 mtx_unlock(&lun->lun_lock);
8110                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8111                                                       /*sks_valid*/ 1,
8112                                                       /*command*/ 1,
8113                                                       /*field*/ 2,
8114                                                       /*bit_valid*/ 1,
8115                                                       /*bit*/ 4);
8116                                 ctl_done((union ctl_io *)ctsio);
8117                                 return (1);
8118                         }
8119
8120                         if (type>8 || type==2 || type==4 || type==0) {
8121                                 mtx_unlock(&lun->lun_lock);
8122                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8123                                                       /*sks_valid*/ 1,
8124                                                       /*command*/ 1,
8125                                                       /*field*/ 2,
8126                                                       /*bit_valid*/ 1,
8127                                                       /*bit*/ 0);
8128                                 ctl_done((union ctl_io *)ctsio);
8129                                 return (1);
8130                         }
8131
8132                         /*
8133                          * Do the following:
8134                          * if sa_res_key != res_key remove all
8135                          * registrants w/sa_res_key and generate UA
8136                          * for these registrants(Registrations
8137                          * Preempted) if it wasn't an exclusive
8138                          * reservation generate UA(Reservations
8139                          * Preempted) for all other registered nexuses
8140                          * if the type has changed. Establish the new
8141                          * reservation and holder. If res_key and
8142                          * sa_res_key are the same do the above
8143                          * except don't unregister the res holder.
8144                          */
8145
8146                         /*
8147                          * Temporarily unregister so it won't get
8148                          * removed or UA generated
8149                          */
8150                         lun->per_res[residx].registered = 0;
8151                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8152                                 if (lun->per_res[i].registered == 0)
8153                                         continue;
8154
8155                                 if (memcmp(param->serv_act_res_key,
8156                                     lun->per_res[i].res_key.key,
8157                                     sizeof(struct scsi_per_res_key)) == 0) {
8158                                         lun->per_res[i].registered = 0;
8159                                         memset(&lun->per_res[i].res_key,
8160                                                0,
8161                                                sizeof(struct scsi_per_res_key));
8162                                         lun->pr_key_count--;
8163
8164                                         if (!persis_offset
8165                                          && i < CTL_MAX_INITIATORS)
8166                                                 lun->pending_sense[i
8167                                                         ].ua_pending |=
8168                                                         CTL_UA_REG_PREEMPT;
8169                                         else if (persis_offset
8170                                               && i >= persis_offset)
8171                                                 lun->pending_sense[
8172                                                   i-persis_offset].ua_pending |=
8173                                                   CTL_UA_REG_PREEMPT;
8174                                 } else if (type != lun->res_type
8175                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8176                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8177                                                 if (!persis_offset
8178                                                  && i < CTL_MAX_INITIATORS)
8179                                                         lun->pending_sense[i
8180                                                         ].ua_pending |=
8181                                                         CTL_UA_RES_RELEASE;
8182                                                 else if (persis_offset
8183                                                       && i >= persis_offset)
8184                                                         lun->pending_sense[
8185                                                         i-persis_offset
8186                                                         ].ua_pending |=
8187                                                         CTL_UA_RES_RELEASE;
8188                                 }
8189                         }
8190                         lun->per_res[residx].registered = 1;
8191                         lun->res_type = type;
8192                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8193                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8194                                 lun->pr_res_idx = residx;
8195                         else
8196                                 lun->pr_res_idx =
8197                                         CTL_PR_ALL_REGISTRANTS;
8198
8199                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8200                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8201                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8202                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8203                         persis_io.pr.pr_info.res_type = type;
8204                         memcpy(persis_io.pr.pr_info.sa_res_key,
8205                                param->serv_act_res_key,
8206                                sizeof(param->serv_act_res_key));
8207                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8208                              &persis_io, sizeof(persis_io), 0)) >
8209                              CTL_HA_STATUS_SUCCESS) {
8210                                 printf("CTL:Persis Out error returned "
8211                                        "from ctl_ha_msg_send %d\n",
8212                                        isc_retval);
8213                         }
8214                 } else {
8215                         /*
8216                          * sa_res_key is not the res holder just
8217                          * remove registrants
8218                          */
8219                         int found=0;
8220
8221                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8222                                 if (memcmp(param->serv_act_res_key,
8223                                     lun->per_res[i].res_key.key,
8224                                     sizeof(struct scsi_per_res_key)) != 0)
8225                                         continue;
8226
8227                                 found = 1;
8228                                 lun->per_res[i].registered = 0;
8229                                 memset(&lun->per_res[i].res_key, 0,
8230                                        sizeof(struct scsi_per_res_key));
8231                                 lun->pr_key_count--;
8232
8233                                 if (!persis_offset
8234                                  && i < CTL_MAX_INITIATORS)
8235                                         lun->pending_sense[i].ua_pending |=
8236                                                 CTL_UA_REG_PREEMPT;
8237                                 else if (persis_offset
8238                                       && i >= persis_offset)
8239                                         lun->pending_sense[
8240                                                 i-persis_offset].ua_pending |=
8241                                                 CTL_UA_REG_PREEMPT;
8242                         }
8243
8244                         if (!found) {
8245                                 mtx_unlock(&lun->lun_lock);
8246                                 free(ctsio->kern_data_ptr, M_CTL);
8247                                 ctl_set_reservation_conflict(ctsio);
8248                                 ctl_done((union ctl_io *)ctsio);
8249                                 return (1);
8250                         }
8251                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8252                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8253                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8254                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8255                         persis_io.pr.pr_info.res_type = type;
8256                         memcpy(persis_io.pr.pr_info.sa_res_key,
8257                                param->serv_act_res_key,
8258                                sizeof(param->serv_act_res_key));
8259                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8260                              &persis_io, sizeof(persis_io), 0)) >
8261                              CTL_HA_STATUS_SUCCESS) {
8262                                 printf("CTL:Persis Out error returned "
8263                                        "from ctl_ha_msg_send %d\n",
8264                                 isc_retval);
8265                         }
8266                 }
8267         }
8268
8269         lun->PRGeneration++;
8270         mtx_unlock(&lun->lun_lock);
8271
8272         return (retval);
8273 }
8274
8275 static void
8276 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8277 {
8278         int i;
8279
8280         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8281          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8282          || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8283                    msg->pr.pr_info.sa_res_key,
8284                    sizeof(struct scsi_per_res_key)) != 0) {
8285                 uint64_t sa_res_key;
8286                 sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8287
8288                 if (sa_res_key == 0) {
8289                         /* temporarily unregister this nexus */
8290                         lun->per_res[msg->pr.pr_info.residx].registered = 0;
8291
8292                         /*
8293                          * Unregister everybody else and build UA for
8294                          * them
8295                          */
8296                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8297                                 if (lun->per_res[i].registered == 0)
8298                                         continue;
8299
8300                                 if (!persis_offset
8301                                  && i < CTL_MAX_INITIATORS)
8302                                         lun->pending_sense[i].ua_pending |=
8303                                                 CTL_UA_REG_PREEMPT;
8304                                 else if (persis_offset && i >= persis_offset)
8305                                         lun->pending_sense[i -
8306                                                 persis_offset].ua_pending |=
8307                                                 CTL_UA_REG_PREEMPT;
8308                                 lun->per_res[i].registered = 0;
8309                                 memset(&lun->per_res[i].res_key, 0,
8310                                        sizeof(struct scsi_per_res_key));
8311                         }
8312
8313                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8314                         lun->pr_key_count = 1;
8315                         lun->res_type = msg->pr.pr_info.res_type;
8316                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8317                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8318                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8319                 } else {
8320                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8321                                 if (memcmp(msg->pr.pr_info.sa_res_key,
8322                                    lun->per_res[i].res_key.key,
8323                                    sizeof(struct scsi_per_res_key)) != 0)
8324                                         continue;
8325
8326                                 lun->per_res[i].registered = 0;
8327                                 memset(&lun->per_res[i].res_key, 0,
8328                                        sizeof(struct scsi_per_res_key));
8329                                 lun->pr_key_count--;
8330
8331                                 if (!persis_offset
8332                                  && i < persis_offset)
8333                                         lun->pending_sense[i].ua_pending |=
8334                                                 CTL_UA_REG_PREEMPT;
8335                                 else if (persis_offset
8336                                       && i >= persis_offset)
8337                                         lun->pending_sense[i -
8338                                                 persis_offset].ua_pending |=
8339                                                 CTL_UA_REG_PREEMPT;
8340                         }
8341                 }
8342         } else {
8343                 /*
8344                  * Temporarily unregister so it won't get removed
8345                  * or UA generated
8346                  */
8347                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8348                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8349                         if (lun->per_res[i].registered == 0)
8350                                 continue;
8351
8352                         if (memcmp(msg->pr.pr_info.sa_res_key,
8353                            lun->per_res[i].res_key.key,
8354                            sizeof(struct scsi_per_res_key)) == 0) {
8355                                 lun->per_res[i].registered = 0;
8356                                 memset(&lun->per_res[i].res_key, 0,
8357                                        sizeof(struct scsi_per_res_key));
8358                                 lun->pr_key_count--;
8359                                 if (!persis_offset
8360                                  && i < CTL_MAX_INITIATORS)
8361                                         lun->pending_sense[i].ua_pending |=
8362                                                 CTL_UA_REG_PREEMPT;
8363                                 else if (persis_offset
8364                                       && i >= persis_offset)
8365                                         lun->pending_sense[i -
8366                                                 persis_offset].ua_pending |=
8367                                                 CTL_UA_REG_PREEMPT;
8368                         } else if (msg->pr.pr_info.res_type != lun->res_type
8369                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8370                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8371                                         if (!persis_offset
8372                                          && i < persis_offset)
8373                                                 lun->pending_sense[i
8374                                                         ].ua_pending |=
8375                                                         CTL_UA_RES_RELEASE;
8376                                         else if (persis_offset
8377                                               && i >= persis_offset)
8378                                         lun->pending_sense[i -
8379                                                 persis_offset].ua_pending |=
8380                                                 CTL_UA_RES_RELEASE;
8381                         }
8382                 }
8383                 lun->per_res[msg->pr.pr_info.residx].registered = 1;
8384                 lun->res_type = msg->pr.pr_info.res_type;
8385                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8386                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8387                         lun->pr_res_idx = msg->pr.pr_info.residx;
8388                 else
8389                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8390         }
8391         lun->PRGeneration++;
8392
8393 }
8394
8395
8396 int
8397 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8398 {
8399         int retval;
8400         int isc_retval;
8401         u_int32_t param_len;
8402         struct scsi_per_res_out *cdb;
8403         struct ctl_lun *lun;
8404         struct scsi_per_res_out_parms* param;
8405         struct ctl_softc *softc;
8406         uint32_t residx;
8407         uint64_t res_key, sa_res_key;
8408         uint8_t type;
8409         union ctl_ha_msg persis_io;
8410         int    i;
8411
8412         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8413
8414         retval = CTL_RETVAL_COMPLETE;
8415
8416         softc = control_softc;
8417
8418         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8419         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8420
8421         /*
8422          * We only support whole-LUN scope.  The scope & type are ignored for
8423          * register, register and ignore existing key and clear.
8424          * We sometimes ignore scope and type on preempts too!!
8425          * Verify reservation type here as well.
8426          */
8427         type = cdb->scope_type & SPR_TYPE_MASK;
8428         if ((cdb->action == SPRO_RESERVE)
8429          || (cdb->action == SPRO_RELEASE)) {
8430                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8431                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8432                                               /*sks_valid*/ 1,
8433                                               /*command*/ 1,
8434                                               /*field*/ 2,
8435                                               /*bit_valid*/ 1,
8436                                               /*bit*/ 4);
8437                         ctl_done((union ctl_io *)ctsio);
8438                         return (CTL_RETVAL_COMPLETE);
8439                 }
8440
8441                 if (type>8 || type==2 || type==4 || type==0) {
8442                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8443                                               /*sks_valid*/ 1,
8444                                               /*command*/ 1,
8445                                               /*field*/ 2,
8446                                               /*bit_valid*/ 1,
8447                                               /*bit*/ 0);
8448                         ctl_done((union ctl_io *)ctsio);
8449                         return (CTL_RETVAL_COMPLETE);
8450                 }
8451         }
8452
8453         param_len = scsi_4btoul(cdb->length);
8454
8455         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8456                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8457                 ctsio->kern_data_len = param_len;
8458                 ctsio->kern_total_len = param_len;
8459                 ctsio->kern_data_resid = 0;
8460                 ctsio->kern_rel_offset = 0;
8461                 ctsio->kern_sg_entries = 0;
8462                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8463                 ctsio->be_move_done = ctl_config_move_done;
8464                 ctl_datamove((union ctl_io *)ctsio);
8465
8466                 return (CTL_RETVAL_COMPLETE);
8467         }
8468
8469         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8470
8471         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8472         res_key = scsi_8btou64(param->res_key.key);
8473         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8474
8475         /*
8476          * Validate the reservation key here except for SPRO_REG_IGNO
8477          * This must be done for all other service actions
8478          */
8479         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8480                 mtx_lock(&lun->lun_lock);
8481                 if (lun->per_res[residx].registered) {
8482                     if (memcmp(param->res_key.key,
8483                                lun->per_res[residx].res_key.key,
8484                                ctl_min(sizeof(param->res_key),
8485                                sizeof(lun->per_res[residx].res_key))) != 0) {
8486                                 /*
8487                                  * The current key passed in doesn't match
8488                                  * the one the initiator previously
8489                                  * registered.
8490                                  */
8491                                 mtx_unlock(&lun->lun_lock);
8492                                 free(ctsio->kern_data_ptr, M_CTL);
8493                                 ctl_set_reservation_conflict(ctsio);
8494                                 ctl_done((union ctl_io *)ctsio);
8495                                 return (CTL_RETVAL_COMPLETE);
8496                         }
8497                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8498                         /*
8499                          * We are not registered
8500                          */
8501                         mtx_unlock(&lun->lun_lock);
8502                         free(ctsio->kern_data_ptr, M_CTL);
8503                         ctl_set_reservation_conflict(ctsio);
8504                         ctl_done((union ctl_io *)ctsio);
8505                         return (CTL_RETVAL_COMPLETE);
8506                 } else if (res_key != 0) {
8507                         /*
8508                          * We are not registered and trying to register but
8509                          * the register key isn't zero.
8510                          */
8511                         mtx_unlock(&lun->lun_lock);
8512                         free(ctsio->kern_data_ptr, M_CTL);
8513                         ctl_set_reservation_conflict(ctsio);
8514                         ctl_done((union ctl_io *)ctsio);
8515                         return (CTL_RETVAL_COMPLETE);
8516                 }
8517                 mtx_unlock(&lun->lun_lock);
8518         }
8519
8520         switch (cdb->action & SPRO_ACTION_MASK) {
8521         case SPRO_REGISTER:
8522         case SPRO_REG_IGNO: {
8523
8524 #if 0
8525                 printf("Registration received\n");
8526 #endif
8527
8528                 /*
8529                  * We don't support any of these options, as we report in
8530                  * the read capabilities request (see
8531                  * ctl_persistent_reserve_in(), above).
8532                  */
8533                 if ((param->flags & SPR_SPEC_I_PT)
8534                  || (param->flags & SPR_ALL_TG_PT)
8535                  || (param->flags & SPR_APTPL)) {
8536                         int bit_ptr;
8537
8538                         if (param->flags & SPR_APTPL)
8539                                 bit_ptr = 0;
8540                         else if (param->flags & SPR_ALL_TG_PT)
8541                                 bit_ptr = 2;
8542                         else /* SPR_SPEC_I_PT */
8543                                 bit_ptr = 3;
8544
8545                         free(ctsio->kern_data_ptr, M_CTL);
8546                         ctl_set_invalid_field(ctsio,
8547                                               /*sks_valid*/ 1,
8548                                               /*command*/ 0,
8549                                               /*field*/ 20,
8550                                               /*bit_valid*/ 1,
8551                                               /*bit*/ bit_ptr);
8552                         ctl_done((union ctl_io *)ctsio);
8553                         return (CTL_RETVAL_COMPLETE);
8554                 }
8555
8556                 mtx_lock(&lun->lun_lock);
8557
8558                 /*
8559                  * The initiator wants to clear the
8560                  * key/unregister.
8561                  */
8562                 if (sa_res_key == 0) {
8563                         if ((res_key == 0
8564                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8565                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8566                           && !lun->per_res[residx].registered)) {
8567                                 mtx_unlock(&lun->lun_lock);
8568                                 goto done;
8569                         }
8570
8571                         lun->per_res[residx].registered = 0;
8572                         memset(&lun->per_res[residx].res_key,
8573                                0, sizeof(lun->per_res[residx].res_key));
8574                         lun->pr_key_count--;
8575
8576                         if (residx == lun->pr_res_idx) {
8577                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8578                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8579
8580                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8581                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8582                                  && lun->pr_key_count) {
8583                                         /*
8584                                          * If the reservation is a registrants
8585                                          * only type we need to generate a UA
8586                                          * for other registered inits.  The
8587                                          * sense code should be RESERVATIONS
8588                                          * RELEASED
8589                                          */
8590
8591                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8592                                                 if (lun->per_res[
8593                                                     i+persis_offset].registered
8594                                                     == 0)
8595                                                         continue;
8596                                                 lun->pending_sense[i
8597                                                         ].ua_pending |=
8598                                                         CTL_UA_RES_RELEASE;
8599                                         }
8600                                 }
8601                                 lun->res_type = 0;
8602                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8603                                 if (lun->pr_key_count==0) {
8604                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8605                                         lun->res_type = 0;
8606                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8607                                 }
8608                         }
8609                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8610                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8611                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8612                         persis_io.pr.pr_info.residx = residx;
8613                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8614                              &persis_io, sizeof(persis_io), 0 )) >
8615                              CTL_HA_STATUS_SUCCESS) {
8616                                 printf("CTL:Persis Out error returned from "
8617                                        "ctl_ha_msg_send %d\n", isc_retval);
8618                         }
8619                 } else /* sa_res_key != 0 */ {
8620
8621                         /*
8622                          * If we aren't registered currently then increment
8623                          * the key count and set the registered flag.
8624                          */
8625                         if (!lun->per_res[residx].registered) {
8626                                 lun->pr_key_count++;
8627                                 lun->per_res[residx].registered = 1;
8628                         }
8629
8630                         memcpy(&lun->per_res[residx].res_key,
8631                                param->serv_act_res_key,
8632                                ctl_min(sizeof(param->serv_act_res_key),
8633                                sizeof(lun->per_res[residx].res_key)));
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_REG_KEY;
8638                         persis_io.pr.pr_info.residx = residx;
8639                         memcpy(persis_io.pr.pr_info.sa_res_key,
8640                                param->serv_act_res_key,
8641                                sizeof(param->serv_act_res_key));
8642                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8643                              &persis_io, sizeof(persis_io), 0)) >
8644                              CTL_HA_STATUS_SUCCESS) {
8645                                 printf("CTL:Persis Out error returned from "
8646                                        "ctl_ha_msg_send %d\n", isc_retval);
8647                         }
8648                 }
8649                 lun->PRGeneration++;
8650                 mtx_unlock(&lun->lun_lock);
8651
8652                 break;
8653         }
8654         case SPRO_RESERVE:
8655 #if 0
8656                 printf("Reserve executed type %d\n", type);
8657 #endif
8658                 mtx_lock(&lun->lun_lock);
8659                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8660                         /*
8661                          * if this isn't the reservation holder and it's
8662                          * not a "all registrants" type or if the type is
8663                          * different then we have a conflict
8664                          */
8665                         if ((lun->pr_res_idx != residx
8666                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8667                          || lun->res_type != type) {
8668                                 mtx_unlock(&lun->lun_lock);
8669                                 free(ctsio->kern_data_ptr, M_CTL);
8670                                 ctl_set_reservation_conflict(ctsio);
8671                                 ctl_done((union ctl_io *)ctsio);
8672                                 return (CTL_RETVAL_COMPLETE);
8673                         }
8674                         mtx_unlock(&lun->lun_lock);
8675                 } else /* create a reservation */ {
8676                         /*
8677                          * If it's not an "all registrants" type record
8678                          * reservation holder
8679                          */
8680                         if (type != SPR_TYPE_WR_EX_AR
8681                          && type != SPR_TYPE_EX_AC_AR)
8682                                 lun->pr_res_idx = residx; /* Res holder */
8683                         else
8684                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8685
8686                         lun->flags |= CTL_LUN_PR_RESERVED;
8687                         lun->res_type = type;
8688
8689                         mtx_unlock(&lun->lun_lock);
8690
8691                         /* send msg to other side */
8692                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8693                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8694                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8695                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8696                         persis_io.pr.pr_info.res_type = type;
8697                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8698                              &persis_io, sizeof(persis_io), 0)) >
8699                              CTL_HA_STATUS_SUCCESS) {
8700                                 printf("CTL:Persis Out error returned from "
8701                                        "ctl_ha_msg_send %d\n", isc_retval);
8702                         }
8703                 }
8704                 break;
8705
8706         case SPRO_RELEASE:
8707                 mtx_lock(&lun->lun_lock);
8708                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8709                         /* No reservation exists return good status */
8710                         mtx_unlock(&lun->lun_lock);
8711                         goto done;
8712                 }
8713                 /*
8714                  * Is this nexus a reservation holder?
8715                  */
8716                 if (lun->pr_res_idx != residx
8717                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8718                         /*
8719                          * not a res holder return good status but
8720                          * do nothing
8721                          */
8722                         mtx_unlock(&lun->lun_lock);
8723                         goto done;
8724                 }
8725
8726                 if (lun->res_type != type) {
8727                         mtx_unlock(&lun->lun_lock);
8728                         free(ctsio->kern_data_ptr, M_CTL);
8729                         ctl_set_illegal_pr_release(ctsio);
8730                         ctl_done((union ctl_io *)ctsio);
8731                         return (CTL_RETVAL_COMPLETE);
8732                 }
8733
8734                 /* okay to release */
8735                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8736                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8737                 lun->res_type = 0;
8738
8739                 /*
8740                  * if this isn't an exclusive access
8741                  * res generate UA for all other
8742                  * registrants.
8743                  */
8744                 if (type != SPR_TYPE_EX_AC
8745                  && type != SPR_TYPE_WR_EX) {
8746                         /*
8747                          * temporarily unregister so we don't generate UA
8748                          */
8749                         lun->per_res[residx].registered = 0;
8750
8751                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8752                                 if (lun->per_res[i+persis_offset].registered
8753                                     == 0)
8754                                         continue;
8755                                 lun->pending_sense[i].ua_pending |=
8756                                         CTL_UA_RES_RELEASE;
8757                         }
8758
8759                         lun->per_res[residx].registered = 1;
8760                 }
8761                 mtx_unlock(&lun->lun_lock);
8762                 /* Send msg to other side */
8763                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8764                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8765                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8766                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8767                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8768                         printf("CTL:Persis Out error returned from "
8769                                "ctl_ha_msg_send %d\n", isc_retval);
8770                 }
8771                 break;
8772
8773         case SPRO_CLEAR:
8774                 /* send msg to other side */
8775
8776                 mtx_lock(&lun->lun_lock);
8777                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8778                 lun->res_type = 0;
8779                 lun->pr_key_count = 0;
8780                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8781
8782
8783                 memset(&lun->per_res[residx].res_key,
8784                        0, sizeof(lun->per_res[residx].res_key));
8785                 lun->per_res[residx].registered = 0;
8786
8787                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8788                         if (lun->per_res[i].registered) {
8789                                 if (!persis_offset && i < CTL_MAX_INITIATORS)
8790                                         lun->pending_sense[i].ua_pending |=
8791                                                 CTL_UA_RES_PREEMPT;
8792                                 else if (persis_offset && i >= persis_offset)
8793                                         lun->pending_sense[i-persis_offset
8794                                             ].ua_pending |= CTL_UA_RES_PREEMPT;
8795
8796                                 memset(&lun->per_res[i].res_key,
8797                                        0, sizeof(struct scsi_per_res_key));
8798                                 lun->per_res[i].registered = 0;
8799                         }
8800                 lun->PRGeneration++;
8801                 mtx_unlock(&lun->lun_lock);
8802                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8803                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8804                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8805                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8806                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8807                         printf("CTL:Persis Out error returned from "
8808                                "ctl_ha_msg_send %d\n", isc_retval);
8809                 }
8810                 break;
8811
8812         case SPRO_PREEMPT: {
8813                 int nretval;
8814
8815                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8816                                           residx, ctsio, cdb, param);
8817                 if (nretval != 0)
8818                         return (CTL_RETVAL_COMPLETE);
8819                 break;
8820         }
8821         default:
8822                 panic("Invalid PR type %x", cdb->action);
8823         }
8824
8825 done:
8826         free(ctsio->kern_data_ptr, M_CTL);
8827         ctl_set_success(ctsio);
8828         ctl_done((union ctl_io *)ctsio);
8829
8830         return (retval);
8831 }
8832
8833 /*
8834  * This routine is for handling a message from the other SC pertaining to
8835  * persistent reserve out. All the error checking will have been done
8836  * so only perorming the action need be done here to keep the two
8837  * in sync.
8838  */
8839 static void
8840 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8841 {
8842         struct ctl_lun *lun;
8843         struct ctl_softc *softc;
8844         int i;
8845         uint32_t targ_lun;
8846
8847         softc = control_softc;
8848
8849         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8850         lun = softc->ctl_luns[targ_lun];
8851         mtx_lock(&lun->lun_lock);
8852         switch(msg->pr.pr_info.action) {
8853         case CTL_PR_REG_KEY:
8854                 if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8855                         lun->per_res[msg->pr.pr_info.residx].registered = 1;
8856                         lun->pr_key_count++;
8857                 }
8858                 lun->PRGeneration++;
8859                 memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8860                        msg->pr.pr_info.sa_res_key,
8861                        sizeof(struct scsi_per_res_key));
8862                 break;
8863
8864         case CTL_PR_UNREG_KEY:
8865                 lun->per_res[msg->pr.pr_info.residx].registered = 0;
8866                 memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8867                        0, sizeof(struct scsi_per_res_key));
8868                 lun->pr_key_count--;
8869
8870                 /* XXX Need to see if the reservation has been released */
8871                 /* if so do we need to generate UA? */
8872                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8873                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8874                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8875
8876                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8877                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8878                          && lun->pr_key_count) {
8879                                 /*
8880                                  * If the reservation is a registrants
8881                                  * only type we need to generate a UA
8882                                  * for other registered inits.  The
8883                                  * sense code should be RESERVATIONS
8884                                  * RELEASED
8885                                  */
8886
8887                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8888                                         if (lun->per_res[i+
8889                                             persis_offset].registered == 0)
8890                                                 continue;
8891
8892                                         lun->pending_sense[i
8893                                                 ].ua_pending |=
8894                                                 CTL_UA_RES_RELEASE;
8895                                 }
8896                         }
8897                         lun->res_type = 0;
8898                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8899                         if (lun->pr_key_count==0) {
8900                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8901                                 lun->res_type = 0;
8902                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8903                         }
8904                 }
8905                 lun->PRGeneration++;
8906                 break;
8907
8908         case CTL_PR_RESERVE:
8909                 lun->flags |= CTL_LUN_PR_RESERVED;
8910                 lun->res_type = msg->pr.pr_info.res_type;
8911                 lun->pr_res_idx = msg->pr.pr_info.residx;
8912
8913                 break;
8914
8915         case CTL_PR_RELEASE:
8916                 /*
8917                  * if this isn't an exclusive access res generate UA for all
8918                  * other registrants.
8919                  */
8920                 if (lun->res_type != SPR_TYPE_EX_AC
8921                  && lun->res_type != SPR_TYPE_WR_EX) {
8922                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8923                                 if (lun->per_res[i+persis_offset].registered)
8924                                         lun->pending_sense[i].ua_pending |=
8925                                                 CTL_UA_RES_RELEASE;
8926                 }
8927
8928                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8929                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8930                 lun->res_type = 0;
8931                 break;
8932
8933         case CTL_PR_PREEMPT:
8934                 ctl_pro_preempt_other(lun, msg);
8935                 break;
8936         case CTL_PR_CLEAR:
8937                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8938                 lun->res_type = 0;
8939                 lun->pr_key_count = 0;
8940                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8941
8942                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8943                         if (lun->per_res[i].registered == 0)
8944                                 continue;
8945                         if (!persis_offset
8946                          && i < CTL_MAX_INITIATORS)
8947                                 lun->pending_sense[i].ua_pending |=
8948                                         CTL_UA_RES_PREEMPT;
8949                         else if (persis_offset
8950                               && i >= persis_offset)
8951                                 lun->pending_sense[i-persis_offset].ua_pending|=
8952                                         CTL_UA_RES_PREEMPT;
8953                         memset(&lun->per_res[i].res_key, 0,
8954                                sizeof(struct scsi_per_res_key));
8955                         lun->per_res[i].registered = 0;
8956                 }
8957                 lun->PRGeneration++;
8958                 break;
8959         }
8960
8961         mtx_unlock(&lun->lun_lock);
8962 }
8963
8964 int
8965 ctl_read_write(struct ctl_scsiio *ctsio)
8966 {
8967         struct ctl_lun *lun;
8968         struct ctl_lba_len_flags *lbalen;
8969         uint64_t lba;
8970         uint32_t num_blocks;
8971         int fua, dpo;
8972         int retval;
8973         int isread;
8974
8975         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8976
8977         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8978
8979         fua = 0;
8980         dpo = 0;
8981
8982         retval = CTL_RETVAL_COMPLETE;
8983
8984         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8985               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8986         if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8987                 uint32_t residx;
8988
8989                 /*
8990                  * XXX KDM need a lock here.
8991                  */
8992                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8993                 if ((lun->res_type == SPR_TYPE_EX_AC
8994                   && residx != lun->pr_res_idx)
8995                  || ((lun->res_type == SPR_TYPE_EX_AC_RO
8996                    || lun->res_type == SPR_TYPE_EX_AC_AR)
8997                   && !lun->per_res[residx].registered)) {
8998                         ctl_set_reservation_conflict(ctsio);
8999                         ctl_done((union ctl_io *)ctsio);
9000                         return (CTL_RETVAL_COMPLETE);
9001                 }
9002         }
9003
9004         switch (ctsio->cdb[0]) {
9005         case READ_6:
9006         case WRITE_6: {
9007                 struct scsi_rw_6 *cdb;
9008
9009                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
9010
9011                 lba = scsi_3btoul(cdb->addr);
9012                 /* only 5 bits are valid in the most significant address byte */
9013                 lba &= 0x1fffff;
9014                 num_blocks = cdb->length;
9015                 /*
9016                  * This is correct according to SBC-2.
9017                  */
9018                 if (num_blocks == 0)
9019                         num_blocks = 256;
9020                 break;
9021         }
9022         case READ_10:
9023         case WRITE_10: {
9024                 struct scsi_rw_10 *cdb;
9025
9026                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9027
9028                 if (cdb->byte2 & SRW10_FUA)
9029                         fua = 1;
9030                 if (cdb->byte2 & SRW10_DPO)
9031                         dpo = 1;
9032
9033                 lba = scsi_4btoul(cdb->addr);
9034                 num_blocks = scsi_2btoul(cdb->length);
9035                 break;
9036         }
9037         case WRITE_VERIFY_10: {
9038                 struct scsi_write_verify_10 *cdb;
9039
9040                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9041
9042                 /*
9043                  * XXX KDM we should do actual write verify support at some
9044                  * point.  This is obviously fake, we're just translating
9045                  * things to a write.  So we don't even bother checking the
9046                  * BYTCHK field, since we don't do any verification.  If
9047                  * the user asks for it, we'll just pretend we did it.
9048                  */
9049                 if (cdb->byte2 & SWV_DPO)
9050                         dpo = 1;
9051
9052                 lba = scsi_4btoul(cdb->addr);
9053                 num_blocks = scsi_2btoul(cdb->length);
9054                 break;
9055         }
9056         case READ_12:
9057         case WRITE_12: {
9058                 struct scsi_rw_12 *cdb;
9059
9060                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9061
9062                 if (cdb->byte2 & SRW12_FUA)
9063                         fua = 1;
9064                 if (cdb->byte2 & SRW12_DPO)
9065                         dpo = 1;
9066                 lba = scsi_4btoul(cdb->addr);
9067                 num_blocks = scsi_4btoul(cdb->length);
9068                 break;
9069         }
9070         case WRITE_VERIFY_12: {
9071                 struct scsi_write_verify_12 *cdb;
9072
9073                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9074
9075                 if (cdb->byte2 & SWV_DPO)
9076                         dpo = 1;
9077                 
9078                 lba = scsi_4btoul(cdb->addr);
9079                 num_blocks = scsi_4btoul(cdb->length);
9080
9081                 break;
9082         }
9083         case READ_16:
9084         case WRITE_16: {
9085                 struct scsi_rw_16 *cdb;
9086
9087                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9088
9089                 if (cdb->byte2 & SRW12_FUA)
9090                         fua = 1;
9091                 if (cdb->byte2 & SRW12_DPO)
9092                         dpo = 1;
9093
9094                 lba = scsi_8btou64(cdb->addr);
9095                 num_blocks = scsi_4btoul(cdb->length);
9096                 break;
9097         }
9098         case WRITE_VERIFY_16: {
9099                 struct scsi_write_verify_16 *cdb;
9100
9101                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9102
9103                 if (cdb->byte2 & SWV_DPO)
9104                         dpo = 1;
9105
9106                 lba = scsi_8btou64(cdb->addr);
9107                 num_blocks = scsi_4btoul(cdb->length);
9108                 break;
9109         }
9110         default:
9111                 /*
9112                  * We got a command we don't support.  This shouldn't
9113                  * happen, commands should be filtered out above us.
9114                  */
9115                 ctl_set_invalid_opcode(ctsio);
9116                 ctl_done((union ctl_io *)ctsio);
9117
9118                 return (CTL_RETVAL_COMPLETE);
9119                 break; /* NOTREACHED */
9120         }
9121
9122         /*
9123          * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9124          * interesting for us, but if RAIDCore is in write-back mode,
9125          * getting it to do write-through for a particular transaction may
9126          * not be possible.
9127          */
9128
9129         /*
9130          * The first check is to make sure we're in bounds, the second
9131          * check is to catch wrap-around problems.  If the lba + num blocks
9132          * is less than the lba, then we've wrapped around and the block
9133          * range is invalid anyway.
9134          */
9135         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9136          || ((lba + num_blocks) < lba)) {
9137                 ctl_set_lba_out_of_range(ctsio);
9138                 ctl_done((union ctl_io *)ctsio);
9139                 return (CTL_RETVAL_COMPLETE);
9140         }
9141
9142         /*
9143          * According to SBC-3, a transfer length of 0 is not an error.
9144          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9145          * translates to 256 blocks for those commands.
9146          */
9147         if (num_blocks == 0) {
9148                 ctl_set_success(ctsio);
9149                 ctl_done((union ctl_io *)ctsio);
9150                 return (CTL_RETVAL_COMPLETE);
9151         }
9152
9153         lbalen = (struct ctl_lba_len_flags *)
9154             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9155         lbalen->lba = lba;
9156         lbalen->len = num_blocks;
9157         lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
9158
9159         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9160         ctsio->kern_rel_offset = 0;
9161
9162         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9163
9164         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9165
9166         return (retval);
9167 }
9168
9169 static int
9170 ctl_cnw_cont(union ctl_io *io)
9171 {
9172         struct ctl_scsiio *ctsio;
9173         struct ctl_lun *lun;
9174         struct ctl_lba_len_flags *lbalen;
9175         int retval;
9176
9177         ctsio = &io->scsiio;
9178         ctsio->io_hdr.status = CTL_STATUS_NONE;
9179         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9180         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9181         lbalen = (struct ctl_lba_len_flags *)
9182             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9183         lbalen->flags = CTL_LLF_WRITE;
9184
9185         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9186         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9187         return (retval);
9188 }
9189
9190 int
9191 ctl_cnw(struct ctl_scsiio *ctsio)
9192 {
9193         struct ctl_lun *lun;
9194         struct ctl_lba_len_flags *lbalen;
9195         uint64_t lba;
9196         uint32_t num_blocks;
9197         int fua, dpo;
9198         int retval;
9199
9200         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9201
9202         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9203
9204         fua = 0;
9205         dpo = 0;
9206
9207         retval = CTL_RETVAL_COMPLETE;
9208
9209         switch (ctsio->cdb[0]) {
9210         case COMPARE_AND_WRITE: {
9211                 struct scsi_compare_and_write *cdb;
9212
9213                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9214
9215                 if (cdb->byte2 & SRW10_FUA)
9216                         fua = 1;
9217                 if (cdb->byte2 & SRW10_DPO)
9218                         dpo = 1;
9219                 lba = scsi_8btou64(cdb->addr);
9220                 num_blocks = cdb->length;
9221                 break;
9222         }
9223         default:
9224                 /*
9225                  * We got a command we don't support.  This shouldn't
9226                  * happen, commands should be filtered out above us.
9227                  */
9228                 ctl_set_invalid_opcode(ctsio);
9229                 ctl_done((union ctl_io *)ctsio);
9230
9231                 return (CTL_RETVAL_COMPLETE);
9232                 break; /* NOTREACHED */
9233         }
9234
9235         /*
9236          * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9237          * interesting for us, but if RAIDCore is in write-back mode,
9238          * getting it to do write-through for a particular transaction may
9239          * not be possible.
9240          */
9241
9242         /*
9243          * The first check is to make sure we're in bounds, the second
9244          * check is to catch wrap-around problems.  If the lba + num blocks
9245          * is less than the lba, then we've wrapped around and the block
9246          * range is invalid anyway.
9247          */
9248         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9249          || ((lba + num_blocks) < lba)) {
9250                 ctl_set_lba_out_of_range(ctsio);
9251                 ctl_done((union ctl_io *)ctsio);
9252                 return (CTL_RETVAL_COMPLETE);
9253         }
9254
9255         /*
9256          * According to SBC-3, a transfer length of 0 is not an error.
9257          */
9258         if (num_blocks == 0) {
9259                 ctl_set_success(ctsio);
9260                 ctl_done((union ctl_io *)ctsio);
9261                 return (CTL_RETVAL_COMPLETE);
9262         }
9263
9264         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9265         ctsio->kern_rel_offset = 0;
9266
9267         /*
9268          * Set the IO_CONT flag, so that if this I/O gets passed to
9269          * ctl_data_submit_done(), it'll get passed back to
9270          * ctl_ctl_cnw_cont() for further processing.
9271          */
9272         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9273         ctsio->io_cont = ctl_cnw_cont;
9274
9275         lbalen = (struct ctl_lba_len_flags *)
9276             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9277         lbalen->lba = lba;
9278         lbalen->len = num_blocks;
9279         lbalen->flags = CTL_LLF_COMPARE;
9280
9281         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9282         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9283         return (retval);
9284 }
9285
9286 int
9287 ctl_verify(struct ctl_scsiio *ctsio)
9288 {
9289         struct ctl_lun *lun;
9290         struct ctl_lba_len_flags *lbalen;
9291         uint64_t lba;
9292         uint32_t num_blocks;
9293         int bytchk, dpo;
9294         int retval;
9295
9296         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9297
9298         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9299
9300         bytchk = 0;
9301         dpo = 0;
9302         retval = CTL_RETVAL_COMPLETE;
9303
9304         switch (ctsio->cdb[0]) {
9305         case VERIFY_10: {
9306                 struct scsi_verify_10 *cdb;
9307
9308                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9309                 if (cdb->byte2 & SVFY_BYTCHK)
9310                         bytchk = 1;
9311                 if (cdb->byte2 & SVFY_DPO)
9312                         dpo = 1;
9313                 lba = scsi_4btoul(cdb->addr);
9314                 num_blocks = scsi_2btoul(cdb->length);
9315                 break;
9316         }
9317         case VERIFY_12: {
9318                 struct scsi_verify_12 *cdb;
9319
9320                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9321                 if (cdb->byte2 & SVFY_BYTCHK)
9322                         bytchk = 1;
9323                 if (cdb->byte2 & SVFY_DPO)
9324                         dpo = 1;
9325                 lba = scsi_4btoul(cdb->addr);
9326                 num_blocks = scsi_4btoul(cdb->length);
9327                 break;
9328         }
9329         case VERIFY_16: {
9330                 struct scsi_rw_16 *cdb;
9331
9332                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9333                 if (cdb->byte2 & SVFY_BYTCHK)
9334                         bytchk = 1;
9335                 if (cdb->byte2 & SVFY_DPO)
9336                         dpo = 1;
9337                 lba = scsi_8btou64(cdb->addr);
9338                 num_blocks = scsi_4btoul(cdb->length);
9339                 break;
9340         }
9341         default:
9342                 /*
9343                  * We got a command we don't support.  This shouldn't
9344                  * happen, commands should be filtered out above us.
9345                  */
9346                 ctl_set_invalid_opcode(ctsio);
9347                 ctl_done((union ctl_io *)ctsio);
9348                 return (CTL_RETVAL_COMPLETE);
9349         }
9350
9351         /*
9352          * The first check is to make sure we're in bounds, the second
9353          * check is to catch wrap-around problems.  If the lba + num blocks
9354          * is less than the lba, then we've wrapped around and the block
9355          * range is invalid anyway.
9356          */
9357         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9358          || ((lba + num_blocks) < lba)) {
9359                 ctl_set_lba_out_of_range(ctsio);
9360                 ctl_done((union ctl_io *)ctsio);
9361                 return (CTL_RETVAL_COMPLETE);
9362         }
9363
9364         /*
9365          * According to SBC-3, a transfer length of 0 is not an error.
9366          */
9367         if (num_blocks == 0) {
9368                 ctl_set_success(ctsio);
9369                 ctl_done((union ctl_io *)ctsio);
9370                 return (CTL_RETVAL_COMPLETE);
9371         }
9372
9373         lbalen = (struct ctl_lba_len_flags *)
9374             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9375         lbalen->lba = lba;
9376         lbalen->len = num_blocks;
9377         if (bytchk) {
9378                 lbalen->flags = CTL_LLF_COMPARE;
9379                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9380         } else {
9381                 lbalen->flags = CTL_LLF_VERIFY;
9382                 ctsio->kern_total_len = 0;
9383         }
9384         ctsio->kern_rel_offset = 0;
9385
9386         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9387         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9388         return (retval);
9389 }
9390
9391 int
9392 ctl_report_luns(struct ctl_scsiio *ctsio)
9393 {
9394         struct scsi_report_luns *cdb;
9395         struct scsi_report_luns_data *lun_data;
9396         struct ctl_lun *lun, *request_lun;
9397         int num_luns, retval;
9398         uint32_t alloc_len, lun_datalen;
9399         int num_filled, well_known;
9400         uint32_t initidx, targ_lun_id, lun_id;
9401
9402         retval = CTL_RETVAL_COMPLETE;
9403         well_known = 0;
9404
9405         cdb = (struct scsi_report_luns *)ctsio->cdb;
9406
9407         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9408
9409         mtx_lock(&control_softc->ctl_lock);
9410         num_luns = control_softc->num_luns;
9411         mtx_unlock(&control_softc->ctl_lock);
9412
9413         switch (cdb->select_report) {
9414         case RPL_REPORT_DEFAULT:
9415         case RPL_REPORT_ALL:
9416                 break;
9417         case RPL_REPORT_WELLKNOWN:
9418                 well_known = 1;
9419                 num_luns = 0;
9420                 break;
9421         default:
9422                 ctl_set_invalid_field(ctsio,
9423                                       /*sks_valid*/ 1,
9424                                       /*command*/ 1,
9425                                       /*field*/ 2,
9426                                       /*bit_valid*/ 0,
9427                                       /*bit*/ 0);
9428                 ctl_done((union ctl_io *)ctsio);
9429                 return (retval);
9430                 break; /* NOTREACHED */
9431         }
9432
9433         alloc_len = scsi_4btoul(cdb->length);
9434         /*
9435          * The initiator has to allocate at least 16 bytes for this request,
9436          * so he can at least get the header and the first LUN.  Otherwise
9437          * we reject the request (per SPC-3 rev 14, section 6.21).
9438          */
9439         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9440             sizeof(struct scsi_report_luns_lundata))) {
9441                 ctl_set_invalid_field(ctsio,
9442                                       /*sks_valid*/ 1,
9443                                       /*command*/ 1,
9444                                       /*field*/ 6,
9445                                       /*bit_valid*/ 0,
9446                                       /*bit*/ 0);
9447                 ctl_done((union ctl_io *)ctsio);
9448                 return (retval);
9449         }
9450
9451         request_lun = (struct ctl_lun *)
9452                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9453
9454         lun_datalen = sizeof(*lun_data) +
9455                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9456
9457         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9458         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9459         ctsio->kern_sg_entries = 0;
9460
9461         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9462
9463         mtx_lock(&control_softc->ctl_lock);
9464         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9465                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9466                 if (lun_id >= CTL_MAX_LUNS)
9467                         continue;
9468                 lun = control_softc->ctl_luns[lun_id];
9469                 if (lun == NULL)
9470                         continue;
9471
9472                 if (targ_lun_id <= 0xff) {
9473                         /*
9474                          * Peripheral addressing method, bus number 0.
9475                          */
9476                         lun_data->luns[num_filled].lundata[0] =
9477                                 RPL_LUNDATA_ATYP_PERIPH;
9478                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9479                         num_filled++;
9480                 } else if (targ_lun_id <= 0x3fff) {
9481                         /*
9482                          * Flat addressing method.
9483                          */
9484                         lun_data->luns[num_filled].lundata[0] =
9485                                 RPL_LUNDATA_ATYP_FLAT |
9486                                 (targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9487 #ifdef OLDCTLHEADERS
9488                                 (SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9489                                 (targ_lun_id & SRLD_BUS_LUN_MASK);
9490 #endif
9491                         lun_data->luns[num_filled].lundata[1] =
9492 #ifdef OLDCTLHEADERS
9493                                 targ_lun_id >> SRLD_BUS_LUN_BITS;
9494 #endif
9495                                 targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9496                         num_filled++;
9497                 } else {
9498                         printf("ctl_report_luns: bogus LUN number %jd, "
9499                                "skipping\n", (intmax_t)targ_lun_id);
9500                 }
9501                 /*
9502                  * According to SPC-3, rev 14 section 6.21:
9503                  *
9504                  * "The execution of a REPORT LUNS command to any valid and
9505                  * installed logical unit shall clear the REPORTED LUNS DATA
9506                  * HAS CHANGED unit attention condition for all logical
9507                  * units of that target with respect to the requesting
9508                  * initiator. A valid and installed logical unit is one
9509                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9510                  * INQUIRY data (see 6.4.2)."
9511                  *
9512                  * If request_lun is NULL, the LUN this report luns command
9513                  * was issued to is either disabled or doesn't exist. In that
9514                  * case, we shouldn't clear any pending lun change unit
9515                  * attention.
9516                  */
9517                 if (request_lun != NULL) {
9518                         mtx_lock(&lun->lun_lock);
9519                         lun->pending_sense[initidx].ua_pending &=
9520                                 ~CTL_UA_LUN_CHANGE;
9521                         mtx_unlock(&lun->lun_lock);
9522                 }
9523         }
9524         mtx_unlock(&control_softc->ctl_lock);
9525
9526         /*
9527          * It's quite possible that we've returned fewer LUNs than we allocated
9528          * space for.  Trim it.
9529          */
9530         lun_datalen = sizeof(*lun_data) +
9531                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9532
9533         if (lun_datalen < alloc_len) {
9534                 ctsio->residual = alloc_len - lun_datalen;
9535                 ctsio->kern_data_len = lun_datalen;
9536                 ctsio->kern_total_len = lun_datalen;
9537         } else {
9538                 ctsio->residual = 0;
9539                 ctsio->kern_data_len = alloc_len;
9540                 ctsio->kern_total_len = alloc_len;
9541         }
9542         ctsio->kern_data_resid = 0;
9543         ctsio->kern_rel_offset = 0;
9544         ctsio->kern_sg_entries = 0;
9545
9546         /*
9547          * We set this to the actual data length, regardless of how much
9548          * space we actually have to return results.  If the user looks at
9549          * this value, he'll know whether or not he allocated enough space
9550          * and reissue the command if necessary.  We don't support well
9551          * known logical units, so if the user asks for that, return none.
9552          */
9553         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9554
9555         /*
9556          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9557          * this request.
9558          */
9559         ctsio->scsi_status = SCSI_STATUS_OK;
9560
9561         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9562         ctsio->be_move_done = ctl_config_move_done;
9563         ctl_datamove((union ctl_io *)ctsio);
9564
9565         return (retval);
9566 }
9567
9568 int
9569 ctl_request_sense(struct ctl_scsiio *ctsio)
9570 {
9571         struct scsi_request_sense *cdb;
9572         struct scsi_sense_data *sense_ptr;
9573         struct ctl_lun *lun;
9574         uint32_t initidx;
9575         int have_error;
9576         scsi_sense_data_type sense_format;
9577
9578         cdb = (struct scsi_request_sense *)ctsio->cdb;
9579
9580         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9581
9582         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9583
9584         /*
9585          * Determine which sense format the user wants.
9586          */
9587         if (cdb->byte2 & SRS_DESC)
9588                 sense_format = SSD_TYPE_DESC;
9589         else
9590                 sense_format = SSD_TYPE_FIXED;
9591
9592         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9593         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9594         ctsio->kern_sg_entries = 0;
9595
9596         /*
9597          * struct scsi_sense_data, which is currently set to 256 bytes, is
9598          * larger than the largest allowed value for the length field in the
9599          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9600          */
9601         ctsio->residual = 0;
9602         ctsio->kern_data_len = cdb->length;
9603         ctsio->kern_total_len = cdb->length;
9604
9605         ctsio->kern_data_resid = 0;
9606         ctsio->kern_rel_offset = 0;
9607         ctsio->kern_sg_entries = 0;
9608
9609         /*
9610          * If we don't have a LUN, we don't have any pending sense.
9611          */
9612         if (lun == NULL)
9613                 goto no_sense;
9614
9615         have_error = 0;
9616         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9617         /*
9618          * Check for pending sense, and then for pending unit attentions.
9619          * Pending sense gets returned first, then pending unit attentions.
9620          */
9621         mtx_lock(&lun->lun_lock);
9622         if (ctl_is_set(lun->have_ca, initidx)) {
9623                 scsi_sense_data_type stored_format;
9624
9625                 /*
9626                  * Check to see which sense format was used for the stored
9627                  * sense data.
9628                  */
9629                 stored_format = scsi_sense_type(
9630                     &lun->pending_sense[initidx].sense);
9631
9632                 /*
9633                  * If the user requested a different sense format than the
9634                  * one we stored, then we need to convert it to the other
9635                  * format.  If we're going from descriptor to fixed format
9636                  * sense data, we may lose things in translation, depending
9637                  * on what options were used.
9638                  *
9639                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9640                  * for some reason we'll just copy it out as-is.
9641                  */
9642                 if ((stored_format == SSD_TYPE_FIXED)
9643                  && (sense_format == SSD_TYPE_DESC))
9644                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9645                             &lun->pending_sense[initidx].sense,
9646                             (struct scsi_sense_data_desc *)sense_ptr);
9647                 else if ((stored_format == SSD_TYPE_DESC)
9648                       && (sense_format == SSD_TYPE_FIXED))
9649                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9650                             &lun->pending_sense[initidx].sense,
9651                             (struct scsi_sense_data_fixed *)sense_ptr);
9652                 else
9653                         memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
9654                                ctl_min(sizeof(*sense_ptr),
9655                                sizeof(lun->pending_sense[initidx].sense)));
9656
9657                 ctl_clear_mask(lun->have_ca, initidx);
9658                 have_error = 1;
9659         } else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
9660                 ctl_ua_type ua_type;
9661
9662                 ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
9663                                        sense_ptr, sense_format);
9664                 if (ua_type != CTL_UA_NONE) {
9665                         have_error = 1;
9666                         /* We're reporting this UA, so clear it */
9667                         lun->pending_sense[initidx].ua_pending &= ~ua_type;
9668                 }
9669         }
9670         mtx_unlock(&lun->lun_lock);
9671
9672         /*
9673          * We already have a pending error, return it.
9674          */
9675         if (have_error != 0) {
9676                 /*
9677                  * We report the SCSI status as OK, since the status of the
9678                  * request sense command itself is OK.
9679                  */
9680                 ctsio->scsi_status = SCSI_STATUS_OK;
9681
9682                 /*
9683                  * We report 0 for the sense length, because we aren't doing
9684                  * autosense in this case.  We're reporting sense as
9685                  * parameter data.
9686                  */
9687                 ctsio->sense_len = 0;
9688                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9689                 ctsio->be_move_done = ctl_config_move_done;
9690                 ctl_datamove((union ctl_io *)ctsio);
9691
9692                 return (CTL_RETVAL_COMPLETE);
9693         }
9694
9695 no_sense:
9696
9697         /*
9698          * No sense information to report, so we report that everything is
9699          * okay.
9700          */
9701         ctl_set_sense_data(sense_ptr,
9702                            lun,
9703                            sense_format,
9704                            /*current_error*/ 1,
9705                            /*sense_key*/ SSD_KEY_NO_SENSE,
9706                            /*asc*/ 0x00,
9707                            /*ascq*/ 0x00,
9708                            SSD_ELEM_NONE);
9709
9710         ctsio->scsi_status = SCSI_STATUS_OK;
9711
9712         /*
9713          * We report 0 for the sense length, because we aren't doing
9714          * autosense in this case.  We're reporting sense as parameter data.
9715          */
9716         ctsio->sense_len = 0;
9717         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9718         ctsio->be_move_done = ctl_config_move_done;
9719         ctl_datamove((union ctl_io *)ctsio);
9720
9721         return (CTL_RETVAL_COMPLETE);
9722 }
9723
9724 int
9725 ctl_tur(struct ctl_scsiio *ctsio)
9726 {
9727         struct ctl_lun *lun;
9728
9729         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9730
9731         CTL_DEBUG_PRINT(("ctl_tur\n"));
9732
9733         if (lun == NULL)
9734                 return (EINVAL);
9735
9736         ctsio->scsi_status = SCSI_STATUS_OK;
9737         ctsio->io_hdr.status = CTL_SUCCESS;
9738
9739         ctl_done((union ctl_io *)ctsio);
9740
9741         return (CTL_RETVAL_COMPLETE);
9742 }
9743
9744 #ifdef notyet
9745 static int
9746 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9747 {
9748
9749 }
9750 #endif
9751
9752 static int
9753 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9754 {
9755         struct scsi_vpd_supported_pages *pages;
9756         int sup_page_size;
9757         struct ctl_lun *lun;
9758
9759         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9760
9761         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9762             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9763         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9764         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9765         ctsio->kern_sg_entries = 0;
9766
9767         if (sup_page_size < alloc_len) {
9768                 ctsio->residual = alloc_len - sup_page_size;
9769                 ctsio->kern_data_len = sup_page_size;
9770                 ctsio->kern_total_len = sup_page_size;
9771         } else {
9772                 ctsio->residual = 0;
9773                 ctsio->kern_data_len = alloc_len;
9774                 ctsio->kern_total_len = alloc_len;
9775         }
9776         ctsio->kern_data_resid = 0;
9777         ctsio->kern_rel_offset = 0;
9778         ctsio->kern_sg_entries = 0;
9779
9780         /*
9781          * The control device is always connected.  The disk device, on the
9782          * other hand, may not be online all the time.  Need to change this
9783          * to figure out whether the disk device is actually online or not.
9784          */
9785         if (lun != NULL)
9786                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9787                                 lun->be_lun->lun_type;
9788         else
9789                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9790
9791         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9792         /* Supported VPD pages */
9793         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9794         /* Serial Number */
9795         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9796         /* Device Identification */
9797         pages->page_list[2] = SVPD_DEVICE_ID;
9798         /* SCSI Ports */
9799         pages->page_list[3] = SVPD_SCSI_PORTS;
9800         /* Block limits */
9801         pages->page_list[4] = SVPD_BLOCK_LIMITS;
9802         /* Logical Block Provisioning */
9803         pages->page_list[5] = SVPD_LBP;
9804
9805         ctsio->scsi_status = SCSI_STATUS_OK;
9806
9807         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9808         ctsio->be_move_done = ctl_config_move_done;
9809         ctl_datamove((union ctl_io *)ctsio);
9810
9811         return (CTL_RETVAL_COMPLETE);
9812 }
9813
9814 static int
9815 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9816 {
9817         struct scsi_vpd_unit_serial_number *sn_ptr;
9818         struct ctl_lun *lun;
9819
9820         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9821
9822         ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9823         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9824         ctsio->kern_sg_entries = 0;
9825
9826         if (sizeof(*sn_ptr) < alloc_len) {
9827                 ctsio->residual = alloc_len - sizeof(*sn_ptr);
9828                 ctsio->kern_data_len = sizeof(*sn_ptr);
9829                 ctsio->kern_total_len = sizeof(*sn_ptr);
9830         } else {
9831                 ctsio->residual = 0;
9832                 ctsio->kern_data_len = alloc_len;
9833                 ctsio->kern_total_len = alloc_len;
9834         }
9835         ctsio->kern_data_resid = 0;
9836         ctsio->kern_rel_offset = 0;
9837         ctsio->kern_sg_entries = 0;
9838
9839         /*
9840          * The control device is always connected.  The disk device, on the
9841          * other hand, may not be online all the time.  Need to change this
9842          * to figure out whether the disk device is actually online or not.
9843          */
9844         if (lun != NULL)
9845                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9846                                   lun->be_lun->lun_type;
9847         else
9848                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9849
9850         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9851         sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9852         /*
9853          * If we don't have a LUN, we just leave the serial number as
9854          * all spaces.
9855          */
9856         memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9857         if (lun != NULL) {
9858                 strncpy((char *)sn_ptr->serial_num,
9859                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9860         }
9861         ctsio->scsi_status = SCSI_STATUS_OK;
9862
9863         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9864         ctsio->be_move_done = ctl_config_move_done;
9865         ctl_datamove((union ctl_io *)ctsio);
9866
9867         return (CTL_RETVAL_COMPLETE);
9868 }
9869
9870
9871 static int
9872 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9873 {
9874         struct scsi_vpd_device_id *devid_ptr;
9875         struct scsi_vpd_id_descriptor *desc;
9876         struct ctl_softc *ctl_softc;
9877         struct ctl_lun *lun;
9878         struct ctl_port *port;
9879         int data_len;
9880         uint8_t proto;
9881
9882         ctl_softc = control_softc;
9883
9884         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9885         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9886
9887         data_len = sizeof(struct scsi_vpd_device_id) +
9888             sizeof(struct scsi_vpd_id_descriptor) +
9889                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9890             sizeof(struct scsi_vpd_id_descriptor) +
9891                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9892         if (lun && lun->lun_devid)
9893                 data_len += lun->lun_devid->len;
9894         if (port->port_devid)
9895                 data_len += port->port_devid->len;
9896         if (port->target_devid)
9897                 data_len += port->target_devid->len;
9898
9899         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9900         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9901         ctsio->kern_sg_entries = 0;
9902
9903         if (data_len < alloc_len) {
9904                 ctsio->residual = alloc_len - data_len;
9905                 ctsio->kern_data_len = data_len;
9906                 ctsio->kern_total_len = data_len;
9907         } else {
9908                 ctsio->residual = 0;
9909                 ctsio->kern_data_len = alloc_len;
9910                 ctsio->kern_total_len = alloc_len;
9911         }
9912         ctsio->kern_data_resid = 0;
9913         ctsio->kern_rel_offset = 0;
9914         ctsio->kern_sg_entries = 0;
9915
9916         /*
9917          * The control device is always connected.  The disk device, on the
9918          * other hand, may not be online all the time.
9919          */
9920         if (lun != NULL)
9921                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9922                                      lun->be_lun->lun_type;
9923         else
9924                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9925         devid_ptr->page_code = SVPD_DEVICE_ID;
9926         scsi_ulto2b(data_len - 4, devid_ptr->length);
9927
9928         if (port->port_type == CTL_PORT_FC)
9929                 proto = SCSI_PROTO_FC << 4;
9930         else if (port->port_type == CTL_PORT_ISCSI)
9931                 proto = SCSI_PROTO_ISCSI << 4;
9932         else
9933                 proto = SCSI_PROTO_SPI << 4;
9934         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9935
9936         /*
9937          * We're using a LUN association here.  i.e., this device ID is a
9938          * per-LUN identifier.
9939          */
9940         if (lun && lun->lun_devid) {
9941                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9942                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9943                     lun->lun_devid->len);
9944         }
9945
9946         /*
9947          * This is for the WWPN which is a port association.
9948          */
9949         if (port->port_devid) {
9950                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9951                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9952                     port->port_devid->len);
9953         }
9954
9955         /*
9956          * This is for the Relative Target Port(type 4h) identifier
9957          */
9958         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9959         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9960             SVPD_ID_TYPE_RELTARG;
9961         desc->length = 4;
9962         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9963         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9964             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9965
9966         /*
9967          * This is for the Target Port Group(type 5h) identifier
9968          */
9969         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9970         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9971             SVPD_ID_TYPE_TPORTGRP;
9972         desc->length = 4;
9973         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9974             &desc->identifier[2]);
9975         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9976             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9977
9978         /*
9979          * This is for the Target identifier
9980          */
9981         if (port->target_devid) {
9982                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9983         }
9984
9985         ctsio->scsi_status = SCSI_STATUS_OK;
9986         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9987         ctsio->be_move_done = ctl_config_move_done;
9988         ctl_datamove((union ctl_io *)ctsio);
9989
9990         return (CTL_RETVAL_COMPLETE);
9991 }
9992
9993 static int
9994 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9995 {
9996         struct ctl_softc *softc = control_softc;
9997         struct scsi_vpd_scsi_ports *sp;
9998         struct scsi_vpd_port_designation *pd;
9999         struct scsi_vpd_port_designation_cont *pdc;
10000         struct ctl_lun *lun;
10001         struct ctl_port *port;
10002         int data_len, num_target_ports, id_len, g, pg, p;
10003         int num_target_port_groups, single;
10004
10005         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10006
10007         single = ctl_is_single;
10008         if (single)
10009                 num_target_port_groups = 1;
10010         else
10011                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10012         num_target_ports = 0;
10013         id_len = 0;
10014         mtx_lock(&softc->ctl_lock);
10015         STAILQ_FOREACH(port, &softc->port_list, links) {
10016                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10017                         continue;
10018                 if (ctl_map_lun_back(port->targ_port, lun->lun) >=
10019                     CTL_MAX_LUNS)
10020                         continue;
10021                 num_target_ports++;
10022                 if (port->port_devid)
10023                         id_len += port->port_devid->len;
10024         }
10025         mtx_unlock(&softc->ctl_lock);
10026
10027         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10028             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10029              sizeof(struct scsi_vpd_port_designation_cont)) + id_len;
10030         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10031         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10032         ctsio->kern_sg_entries = 0;
10033
10034         if (data_len < alloc_len) {
10035                 ctsio->residual = alloc_len - data_len;
10036                 ctsio->kern_data_len = data_len;
10037                 ctsio->kern_total_len = data_len;
10038         } else {
10039                 ctsio->residual = 0;
10040                 ctsio->kern_data_len = alloc_len;
10041                 ctsio->kern_total_len = alloc_len;
10042         }
10043         ctsio->kern_data_resid = 0;
10044         ctsio->kern_rel_offset = 0;
10045         ctsio->kern_sg_entries = 0;
10046
10047         /*
10048          * The control device is always connected.  The disk device, on the
10049          * other hand, may not be online all the time.  Need to change this
10050          * to figure out whether the disk device is actually online or not.
10051          */
10052         if (lun != NULL)
10053                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10054                                   lun->be_lun->lun_type;
10055         else
10056                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10057
10058         sp->page_code = SVPD_SCSI_PORTS;
10059         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10060             sp->page_length);
10061         pd = &sp->design[0];
10062
10063         mtx_lock(&softc->ctl_lock);
10064         if (softc->flags & CTL_FLAG_MASTER_SHELF)
10065                 pg = 0;
10066         else
10067                 pg = 1;
10068         for (g = 0; g < num_target_port_groups; g++) {
10069                 STAILQ_FOREACH(port, &softc->port_list, links) {
10070                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10071                                 continue;
10072                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
10073                             CTL_MAX_LUNS)
10074                                 continue;
10075                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10076                         scsi_ulto2b(p, pd->relative_port_id);
10077                         scsi_ulto2b(0, pd->initiator_transportid_length);
10078                         pdc = (struct scsi_vpd_port_designation_cont *)
10079                             &pd->initiator_transportid[0];
10080                         if (port->port_devid && g == pg) {
10081                                 id_len = port->port_devid->len;
10082                                 scsi_ulto2b(port->port_devid->len,
10083                                     pdc->target_port_descriptors_length);
10084                                 memcpy(pdc->target_port_descriptors,
10085                                     port->port_devid->data, port->port_devid->len);
10086                         } else {
10087                                 id_len = 0;
10088                                 scsi_ulto2b(0, pdc->target_port_descriptors_length);
10089                         }
10090                         pd = (struct scsi_vpd_port_designation *)
10091                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10092                 }
10093         }
10094         mtx_unlock(&softc->ctl_lock);
10095
10096         ctsio->scsi_status = SCSI_STATUS_OK;
10097         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10098         ctsio->be_move_done = ctl_config_move_done;
10099         ctl_datamove((union ctl_io *)ctsio);
10100
10101         return (CTL_RETVAL_COMPLETE);
10102 }
10103
10104 static int
10105 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10106 {
10107         struct scsi_vpd_block_limits *bl_ptr;
10108         struct ctl_lun *lun;
10109         int bs;
10110
10111         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10112         bs = lun->be_lun->blocksize;
10113
10114         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10115         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10116         ctsio->kern_sg_entries = 0;
10117
10118         if (sizeof(*bl_ptr) < alloc_len) {
10119                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10120                 ctsio->kern_data_len = sizeof(*bl_ptr);
10121                 ctsio->kern_total_len = sizeof(*bl_ptr);
10122         } else {
10123                 ctsio->residual = 0;
10124                 ctsio->kern_data_len = alloc_len;
10125                 ctsio->kern_total_len = alloc_len;
10126         }
10127         ctsio->kern_data_resid = 0;
10128         ctsio->kern_rel_offset = 0;
10129         ctsio->kern_sg_entries = 0;
10130
10131         /*
10132          * The control device is always connected.  The disk device, on the
10133          * other hand, may not be online all the time.  Need to change this
10134          * to figure out whether the disk device is actually online or not.
10135          */
10136         if (lun != NULL)
10137                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10138                                   lun->be_lun->lun_type;
10139         else
10140                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10141
10142         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10143         scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
10144         bl_ptr->max_cmp_write_len = 0xff;
10145         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10146         scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10147         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10148                 scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10149                 scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10150         }
10151         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10152
10153         ctsio->scsi_status = SCSI_STATUS_OK;
10154         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10155         ctsio->be_move_done = ctl_config_move_done;
10156         ctl_datamove((union ctl_io *)ctsio);
10157
10158         return (CTL_RETVAL_COMPLETE);
10159 }
10160
10161 static int
10162 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10163 {
10164         struct scsi_vpd_logical_block_prov *lbp_ptr;
10165         struct ctl_lun *lun;
10166         int bs;
10167
10168         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10169         bs = lun->be_lun->blocksize;
10170
10171         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10172         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10173         ctsio->kern_sg_entries = 0;
10174
10175         if (sizeof(*lbp_ptr) < alloc_len) {
10176                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10177                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10178                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10179         } else {
10180                 ctsio->residual = 0;
10181                 ctsio->kern_data_len = alloc_len;
10182                 ctsio->kern_total_len = alloc_len;
10183         }
10184         ctsio->kern_data_resid = 0;
10185         ctsio->kern_rel_offset = 0;
10186         ctsio->kern_sg_entries = 0;
10187
10188         /*
10189          * The control device is always connected.  The disk device, on the
10190          * other hand, may not be online all the time.  Need to change this
10191          * to figure out whether the disk device is actually online or not.
10192          */
10193         if (lun != NULL)
10194                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10195                                   lun->be_lun->lun_type;
10196         else
10197                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10198
10199         lbp_ptr->page_code = SVPD_LBP;
10200         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
10201                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
10202
10203         ctsio->scsi_status = SCSI_STATUS_OK;
10204         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10205         ctsio->be_move_done = ctl_config_move_done;
10206         ctl_datamove((union ctl_io *)ctsio);
10207
10208         return (CTL_RETVAL_COMPLETE);
10209 }
10210
10211 static int
10212 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10213 {
10214         struct scsi_inquiry *cdb;
10215         struct ctl_lun *lun;
10216         int alloc_len, retval;
10217
10218         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10219         cdb = (struct scsi_inquiry *)ctsio->cdb;
10220
10221         retval = CTL_RETVAL_COMPLETE;
10222
10223         alloc_len = scsi_2btoul(cdb->length);
10224
10225         switch (cdb->page_code) {
10226         case SVPD_SUPPORTED_PAGES:
10227                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10228                 break;
10229         case SVPD_UNIT_SERIAL_NUMBER:
10230                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10231                 break;
10232         case SVPD_DEVICE_ID:
10233                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10234                 break;
10235         case SVPD_SCSI_PORTS:
10236                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10237                 break;
10238         case SVPD_BLOCK_LIMITS:
10239                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10240                 break;
10241         case SVPD_LBP:
10242                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10243                 break;
10244         default:
10245                 ctl_set_invalid_field(ctsio,
10246                                       /*sks_valid*/ 1,
10247                                       /*command*/ 1,
10248                                       /*field*/ 2,
10249                                       /*bit_valid*/ 0,
10250                                       /*bit*/ 0);
10251                 ctl_done((union ctl_io *)ctsio);
10252                 retval = CTL_RETVAL_COMPLETE;
10253                 break;
10254         }
10255
10256         return (retval);
10257 }
10258
10259 static int
10260 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10261 {
10262         struct scsi_inquiry_data *inq_ptr;
10263         struct scsi_inquiry *cdb;
10264         struct ctl_softc *ctl_softc;
10265         struct ctl_lun *lun;
10266         char *val;
10267         uint32_t alloc_len;
10268         int is_fc;
10269
10270         ctl_softc = control_softc;
10271
10272         /*
10273          * Figure out whether we're talking to a Fibre Channel port or not.
10274          * We treat the ioctl front end, and any SCSI adapters, as packetized
10275          * SCSI front ends.
10276          */
10277         if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
10278             CTL_PORT_FC)
10279                 is_fc = 0;
10280         else
10281                 is_fc = 1;
10282
10283         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10284         cdb = (struct scsi_inquiry *)ctsio->cdb;
10285         alloc_len = scsi_2btoul(cdb->length);
10286
10287         /*
10288          * We malloc the full inquiry data size here and fill it
10289          * in.  If the user only asks for less, we'll give him
10290          * that much.
10291          */
10292         ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10293         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10294         ctsio->kern_sg_entries = 0;
10295         ctsio->kern_data_resid = 0;
10296         ctsio->kern_rel_offset = 0;
10297
10298         if (sizeof(*inq_ptr) < alloc_len) {
10299                 ctsio->residual = alloc_len - sizeof(*inq_ptr);
10300                 ctsio->kern_data_len = sizeof(*inq_ptr);
10301                 ctsio->kern_total_len = sizeof(*inq_ptr);
10302         } else {
10303                 ctsio->residual = 0;
10304                 ctsio->kern_data_len = alloc_len;
10305                 ctsio->kern_total_len = alloc_len;
10306         }
10307
10308         /*
10309          * If we have a LUN configured, report it as connected.  Otherwise,
10310          * report that it is offline or no device is supported, depending 
10311          * on the value of inquiry_pq_no_lun.
10312          *
10313          * According to the spec (SPC-4 r34), the peripheral qualifier
10314          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10315          *
10316          * "A peripheral device having the specified peripheral device type 
10317          * is not connected to this logical unit. However, the device
10318          * server is capable of supporting the specified peripheral device
10319          * type on this logical unit."
10320          *
10321          * According to the same spec, the peripheral qualifier
10322          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10323          *
10324          * "The device server is not capable of supporting a peripheral
10325          * device on this logical unit. For this peripheral qualifier the
10326          * peripheral device type shall be set to 1Fh. All other peripheral
10327          * device type values are reserved for this peripheral qualifier."
10328          *
10329          * Given the text, it would seem that we probably want to report that
10330          * the LUN is offline here.  There is no LUN connected, but we can
10331          * support a LUN at the given LUN number.
10332          *
10333          * In the real world, though, it sounds like things are a little
10334          * different:
10335          *
10336          * - Linux, when presented with a LUN with the offline peripheral
10337          *   qualifier, will create an sg driver instance for it.  So when
10338          *   you attach it to CTL, you wind up with a ton of sg driver
10339          *   instances.  (One for every LUN that Linux bothered to probe.)
10340          *   Linux does this despite the fact that it issues a REPORT LUNs
10341          *   to LUN 0 to get the inventory of supported LUNs.
10342          *
10343          * - There is other anecdotal evidence (from Emulex folks) about
10344          *   arrays that use the offline peripheral qualifier for LUNs that
10345          *   are on the "passive" path in an active/passive array.
10346          *
10347          * So the solution is provide a hopefully reasonable default
10348          * (return bad/no LUN) and allow the user to change the behavior
10349          * with a tunable/sysctl variable.
10350          */
10351         if (lun != NULL)
10352                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10353                                   lun->be_lun->lun_type;
10354         else if (ctl_softc->inquiry_pq_no_lun == 0)
10355                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10356         else
10357                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10358
10359         /* RMB in byte 2 is 0 */
10360         inq_ptr->version = SCSI_REV_SPC3;
10361
10362         /*
10363          * According to SAM-3, even if a device only supports a single
10364          * level of LUN addressing, it should still set the HISUP bit:
10365          *
10366          * 4.9.1 Logical unit numbers overview
10367          *
10368          * All logical unit number formats described in this standard are
10369          * hierarchical in structure even when only a single level in that
10370          * hierarchy is used. The HISUP bit shall be set to one in the
10371          * standard INQUIRY data (see SPC-2) when any logical unit number
10372          * format described in this standard is used.  Non-hierarchical
10373          * formats are outside the scope of this standard.
10374          *
10375          * Therefore we set the HiSup bit here.
10376          *
10377          * The reponse format is 2, per SPC-3.
10378          */
10379         inq_ptr->response_format = SID_HiSup | 2;
10380
10381         inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
10382         CTL_DEBUG_PRINT(("additional_length = %d\n",
10383                          inq_ptr->additional_length));
10384
10385         inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
10386         /* 16 bit addressing */
10387         if (is_fc == 0)
10388                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10389         /* XXX set the SID_MultiP bit here if we're actually going to
10390            respond on multiple ports */
10391         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10392
10393         /* 16 bit data bus, synchronous transfers */
10394         /* XXX these flags don't apply for FC */
10395         if (is_fc == 0)
10396                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10397         /*
10398          * XXX KDM do we want to support tagged queueing on the control
10399          * device at all?
10400          */
10401         if ((lun == NULL)
10402          || (lun->be_lun->lun_type != T_PROCESSOR))
10403                 inq_ptr->flags |= SID_CmdQue;
10404         /*
10405          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10406          * We have 8 bytes for the vendor name, and 16 bytes for the device
10407          * name and 4 bytes for the revision.
10408          */
10409         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10410             "vendor")) == NULL) {
10411                 strcpy(inq_ptr->vendor, CTL_VENDOR);
10412         } else {
10413                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10414                 strncpy(inq_ptr->vendor, val,
10415                     min(sizeof(inq_ptr->vendor), strlen(val)));
10416         }
10417         if (lun == NULL) {
10418                 strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10419         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10420                 switch (lun->be_lun->lun_type) {
10421                 case T_DIRECT:
10422                         strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10423                         break;
10424                 case T_PROCESSOR:
10425                         strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10426                         break;
10427                 default:
10428                         strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10429                         break;
10430                 }
10431         } else {
10432                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10433                 strncpy(inq_ptr->product, val,
10434                     min(sizeof(inq_ptr->product), strlen(val)));
10435         }
10436
10437         /*
10438          * XXX make this a macro somewhere so it automatically gets
10439          * incremented when we make changes.
10440          */
10441         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10442             "revision")) == NULL) {
10443                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10444         } else {
10445                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10446                 strncpy(inq_ptr->revision, val,
10447                     min(sizeof(inq_ptr->revision), strlen(val)));
10448         }
10449
10450         /*
10451          * For parallel SCSI, we support double transition and single
10452          * transition clocking.  We also support QAS (Quick Arbitration
10453          * and Selection) and Information Unit transfers on both the
10454          * control and array devices.
10455          */
10456         if (is_fc == 0)
10457                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10458                                     SID_SPI_IUS;
10459
10460         /* SAM-3 */
10461         scsi_ulto2b(0x0060, inq_ptr->version1);
10462         /* SPC-3 (no version claimed) XXX should we claim a version? */
10463         scsi_ulto2b(0x0300, inq_ptr->version2);
10464         if (is_fc) {
10465                 /* FCP-2 ANSI INCITS.350:2003 */
10466                 scsi_ulto2b(0x0917, inq_ptr->version3);
10467         } else {
10468                 /* SPI-4 ANSI INCITS.362:200x */
10469                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10470         }
10471
10472         if (lun == NULL) {
10473                 /* SBC-2 (no version claimed) XXX should we claim a version? */
10474                 scsi_ulto2b(0x0320, inq_ptr->version4);
10475         } else {
10476                 switch (lun->be_lun->lun_type) {
10477                 case T_DIRECT:
10478                         /*
10479                          * SBC-2 (no version claimed) XXX should we claim a
10480                          * version?
10481                          */
10482                         scsi_ulto2b(0x0320, inq_ptr->version4);
10483                         break;
10484                 case T_PROCESSOR:
10485                 default:
10486                         break;
10487                 }
10488         }
10489
10490         ctsio->scsi_status = SCSI_STATUS_OK;
10491         if (ctsio->kern_data_len > 0) {
10492                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10493                 ctsio->be_move_done = ctl_config_move_done;
10494                 ctl_datamove((union ctl_io *)ctsio);
10495         } else {
10496                 ctsio->io_hdr.status = CTL_SUCCESS;
10497                 ctl_done((union ctl_io *)ctsio);
10498         }
10499
10500         return (CTL_RETVAL_COMPLETE);
10501 }
10502
10503 int
10504 ctl_inquiry(struct ctl_scsiio *ctsio)
10505 {
10506         struct scsi_inquiry *cdb;
10507         int retval;
10508
10509         cdb = (struct scsi_inquiry *)ctsio->cdb;
10510
10511         retval = 0;
10512
10513         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10514
10515         /*
10516          * Right now, we don't support the CmdDt inquiry information.
10517          * This would be nice to support in the future.  When we do
10518          * support it, we should change this test so that it checks to make
10519          * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10520          */
10521 #ifdef notyet
10522         if (((cdb->byte2 & SI_EVPD)
10523          && (cdb->byte2 & SI_CMDDT)))
10524 #endif
10525         if (cdb->byte2 & SI_CMDDT) {
10526                 /*
10527                  * Point to the SI_CMDDT bit.  We might change this
10528                  * when we support SI_CMDDT, but since both bits would be
10529                  * "wrong", this should probably just stay as-is then.
10530                  */
10531                 ctl_set_invalid_field(ctsio,
10532                                       /*sks_valid*/ 1,
10533                                       /*command*/ 1,
10534                                       /*field*/ 1,
10535                                       /*bit_valid*/ 1,
10536                                       /*bit*/ 1);
10537                 ctl_done((union ctl_io *)ctsio);
10538                 return (CTL_RETVAL_COMPLETE);
10539         }
10540         if (cdb->byte2 & SI_EVPD)
10541                 retval = ctl_inquiry_evpd(ctsio);
10542 #ifdef notyet
10543         else if (cdb->byte2 & SI_CMDDT)
10544                 retval = ctl_inquiry_cmddt(ctsio);
10545 #endif
10546         else
10547                 retval = ctl_inquiry_std(ctsio);
10548
10549         return (retval);
10550 }
10551
10552 /*
10553  * For known CDB types, parse the LBA and length.
10554  */
10555 static int
10556 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10557 {
10558         if (io->io_hdr.io_type != CTL_IO_SCSI)
10559                 return (1);
10560
10561         switch (io->scsiio.cdb[0]) {
10562         case COMPARE_AND_WRITE: {
10563                 struct scsi_compare_and_write *cdb;
10564
10565                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10566
10567                 *lba = scsi_8btou64(cdb->addr);
10568                 *len = cdb->length;
10569                 break;
10570         }
10571         case READ_6:
10572         case WRITE_6: {
10573                 struct scsi_rw_6 *cdb;
10574
10575                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10576
10577                 *lba = scsi_3btoul(cdb->addr);
10578                 /* only 5 bits are valid in the most significant address byte */
10579                 *lba &= 0x1fffff;
10580                 *len = cdb->length;
10581                 break;
10582         }
10583         case READ_10:
10584         case WRITE_10: {
10585                 struct scsi_rw_10 *cdb;
10586
10587                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10588
10589                 *lba = scsi_4btoul(cdb->addr);
10590                 *len = scsi_2btoul(cdb->length);
10591                 break;
10592         }
10593         case WRITE_VERIFY_10: {
10594                 struct scsi_write_verify_10 *cdb;
10595
10596                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10597
10598                 *lba = scsi_4btoul(cdb->addr);
10599                 *len = scsi_2btoul(cdb->length);
10600                 break;
10601         }
10602         case READ_12:
10603         case WRITE_12: {
10604                 struct scsi_rw_12 *cdb;
10605
10606                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10607
10608                 *lba = scsi_4btoul(cdb->addr);
10609                 *len = scsi_4btoul(cdb->length);
10610                 break;
10611         }
10612         case WRITE_VERIFY_12: {
10613                 struct scsi_write_verify_12 *cdb;
10614
10615                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10616
10617                 *lba = scsi_4btoul(cdb->addr);
10618                 *len = scsi_4btoul(cdb->length);
10619                 break;
10620         }
10621         case READ_16:
10622         case WRITE_16: {
10623                 struct scsi_rw_16 *cdb;
10624
10625                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10626
10627                 *lba = scsi_8btou64(cdb->addr);
10628                 *len = scsi_4btoul(cdb->length);
10629                 break;
10630         }
10631         case WRITE_VERIFY_16: {
10632                 struct scsi_write_verify_16 *cdb;
10633
10634                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10635
10636                 
10637                 *lba = scsi_8btou64(cdb->addr);
10638                 *len = scsi_4btoul(cdb->length);
10639                 break;
10640         }
10641         case WRITE_SAME_10: {
10642                 struct scsi_write_same_10 *cdb;
10643
10644                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10645
10646                 *lba = scsi_4btoul(cdb->addr);
10647                 *len = scsi_2btoul(cdb->length);
10648                 break;
10649         }
10650         case WRITE_SAME_16: {
10651                 struct scsi_write_same_16 *cdb;
10652
10653                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10654
10655                 *lba = scsi_8btou64(cdb->addr);
10656                 *len = scsi_4btoul(cdb->length);
10657                 break;
10658         }
10659         case VERIFY_10: {
10660                 struct scsi_verify_10 *cdb;
10661
10662                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10663
10664                 *lba = scsi_4btoul(cdb->addr);
10665                 *len = scsi_2btoul(cdb->length);
10666                 break;
10667         }
10668         case VERIFY_12: {
10669                 struct scsi_verify_12 *cdb;
10670
10671                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10672
10673                 *lba = scsi_4btoul(cdb->addr);
10674                 *len = scsi_4btoul(cdb->length);
10675                 break;
10676         }
10677         case VERIFY_16: {
10678                 struct scsi_verify_16 *cdb;
10679
10680                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10681
10682                 *lba = scsi_8btou64(cdb->addr);
10683                 *len = scsi_4btoul(cdb->length);
10684                 break;
10685         }
10686         default:
10687                 return (1);
10688                 break; /* NOTREACHED */
10689         }
10690
10691         return (0);
10692 }
10693
10694 static ctl_action
10695 ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10696 {
10697         uint64_t endlba1, endlba2;
10698
10699         endlba1 = lba1 + len1 - 1;
10700         endlba2 = lba2 + len2 - 1;
10701
10702         if ((endlba1 < lba2)
10703          || (endlba2 < lba1))
10704                 return (CTL_ACTION_PASS);
10705         else
10706                 return (CTL_ACTION_BLOCK);
10707 }
10708
10709 static ctl_action
10710 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10711 {
10712         uint64_t lba1, lba2;
10713         uint32_t len1, len2;
10714         int retval;
10715
10716         retval = ctl_get_lba_len(io1, &lba1, &len1);
10717         if (retval != 0)
10718                 return (CTL_ACTION_ERROR);
10719
10720         retval = ctl_get_lba_len(io2, &lba2, &len2);
10721         if (retval != 0)
10722                 return (CTL_ACTION_ERROR);
10723
10724         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10725 }
10726
10727 static ctl_action
10728 ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10729 {
10730         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10731         ctl_serialize_action *serialize_row;
10732
10733         /*
10734          * The initiator attempted multiple untagged commands at the same
10735          * time.  Can't do that.
10736          */
10737         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10738          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10739          && ((pending_io->io_hdr.nexus.targ_port ==
10740               ooa_io->io_hdr.nexus.targ_port)
10741           && (pending_io->io_hdr.nexus.initid.id ==
10742               ooa_io->io_hdr.nexus.initid.id))
10743          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10744                 return (CTL_ACTION_OVERLAP);
10745
10746         /*
10747          * The initiator attempted to send multiple tagged commands with
10748          * the same ID.  (It's fine if different initiators have the same
10749          * tag ID.)
10750          *
10751          * Even if all of those conditions are true, we don't kill the I/O
10752          * if the command ahead of us has been aborted.  We won't end up
10753          * sending it to the FETD, and it's perfectly legal to resend a
10754          * command with the same tag number as long as the previous
10755          * instance of this tag number has been aborted somehow.
10756          */
10757         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10758          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10759          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10760          && ((pending_io->io_hdr.nexus.targ_port ==
10761               ooa_io->io_hdr.nexus.targ_port)
10762           && (pending_io->io_hdr.nexus.initid.id ==
10763               ooa_io->io_hdr.nexus.initid.id))
10764          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10765                 return (CTL_ACTION_OVERLAP_TAG);
10766
10767         /*
10768          * If we get a head of queue tag, SAM-3 says that we should
10769          * immediately execute it.
10770          *
10771          * What happens if this command would normally block for some other
10772          * reason?  e.g. a request sense with a head of queue tag
10773          * immediately after a write.  Normally that would block, but this
10774          * will result in its getting executed immediately...
10775          *
10776          * We currently return "pass" instead of "skip", so we'll end up
10777          * going through the rest of the queue to check for overlapped tags.
10778          *
10779          * XXX KDM check for other types of blockage first??
10780          */
10781         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10782                 return (CTL_ACTION_PASS);
10783
10784         /*
10785          * Ordered tags have to block until all items ahead of them
10786          * have completed.  If we get called with an ordered tag, we always
10787          * block, if something else is ahead of us in the queue.
10788          */
10789         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10790                 return (CTL_ACTION_BLOCK);
10791
10792         /*
10793          * Simple tags get blocked until all head of queue and ordered tags
10794          * ahead of them have completed.  I'm lumping untagged commands in
10795          * with simple tags here.  XXX KDM is that the right thing to do?
10796          */
10797         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10798           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10799          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10800           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10801                 return (CTL_ACTION_BLOCK);
10802
10803         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10804         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10805
10806         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10807
10808         switch (serialize_row[pending_entry->seridx]) {
10809         case CTL_SER_BLOCK:
10810                 return (CTL_ACTION_BLOCK);
10811                 break; /* NOTREACHED */
10812         case CTL_SER_EXTENT:
10813                 return (ctl_extent_check(pending_io, ooa_io));
10814                 break; /* NOTREACHED */
10815         case CTL_SER_PASS:
10816                 return (CTL_ACTION_PASS);
10817                 break; /* NOTREACHED */
10818         case CTL_SER_SKIP:
10819                 return (CTL_ACTION_SKIP);
10820                 break;
10821         default:
10822                 panic("invalid serialization value %d",
10823                       serialize_row[pending_entry->seridx]);
10824                 break; /* NOTREACHED */
10825         }
10826
10827         return (CTL_ACTION_ERROR);
10828 }
10829
10830 /*
10831  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10832  * Assumptions:
10833  * - pending_io is generally either incoming, or on the blocked queue
10834  * - starting I/O is the I/O we want to start the check with.
10835  */
10836 static ctl_action
10837 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10838               union ctl_io *starting_io)
10839 {
10840         union ctl_io *ooa_io;
10841         ctl_action action;
10842
10843         mtx_assert(&lun->lun_lock, MA_OWNED);
10844
10845         /*
10846          * Run back along the OOA queue, starting with the current
10847          * blocked I/O and going through every I/O before it on the
10848          * queue.  If starting_io is NULL, we'll just end up returning
10849          * CTL_ACTION_PASS.
10850          */
10851         for (ooa_io = starting_io; ooa_io != NULL;
10852              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10853              ooa_links)){
10854
10855                 /*
10856                  * This routine just checks to see whether
10857                  * cur_blocked is blocked by ooa_io, which is ahead
10858                  * of it in the queue.  It doesn't queue/dequeue
10859                  * cur_blocked.
10860                  */
10861                 action = ctl_check_for_blockage(pending_io, ooa_io);
10862                 switch (action) {
10863                 case CTL_ACTION_BLOCK:
10864                 case CTL_ACTION_OVERLAP:
10865                 case CTL_ACTION_OVERLAP_TAG:
10866                 case CTL_ACTION_SKIP:
10867                 case CTL_ACTION_ERROR:
10868                         return (action);
10869                         break; /* NOTREACHED */
10870                 case CTL_ACTION_PASS:
10871                         break;
10872                 default:
10873                         panic("invalid action %d", action);
10874                         break;  /* NOTREACHED */
10875                 }
10876         }
10877
10878         return (CTL_ACTION_PASS);
10879 }
10880
10881 /*
10882  * Assumptions:
10883  * - An I/O has just completed, and has been removed from the per-LUN OOA
10884  *   queue, so some items on the blocked queue may now be unblocked.
10885  */
10886 static int
10887 ctl_check_blocked(struct ctl_lun *lun)
10888 {
10889         union ctl_io *cur_blocked, *next_blocked;
10890
10891         mtx_assert(&lun->lun_lock, MA_OWNED);
10892
10893         /*
10894          * Run forward from the head of the blocked queue, checking each
10895          * entry against the I/Os prior to it on the OOA queue to see if
10896          * there is still any blockage.
10897          *
10898          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10899          * with our removing a variable on it while it is traversing the
10900          * list.
10901          */
10902         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10903              cur_blocked != NULL; cur_blocked = next_blocked) {
10904                 union ctl_io *prev_ooa;
10905                 ctl_action action;
10906
10907                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10908                                                           blocked_links);
10909
10910                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10911                                                       ctl_ooaq, ooa_links);
10912
10913                 /*
10914                  * If cur_blocked happens to be the first item in the OOA
10915                  * queue now, prev_ooa will be NULL, and the action
10916                  * returned will just be CTL_ACTION_PASS.
10917                  */
10918                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10919
10920                 switch (action) {
10921                 case CTL_ACTION_BLOCK:
10922                         /* Nothing to do here, still blocked */
10923                         break;
10924                 case CTL_ACTION_OVERLAP:
10925                 case CTL_ACTION_OVERLAP_TAG:
10926                         /*
10927                          * This shouldn't happen!  In theory we've already
10928                          * checked this command for overlap...
10929                          */
10930                         break;
10931                 case CTL_ACTION_PASS:
10932                 case CTL_ACTION_SKIP: {
10933                         struct ctl_softc *softc;
10934                         const struct ctl_cmd_entry *entry;
10935                         uint32_t initidx;
10936                         int isc_retval;
10937
10938                         /*
10939                          * The skip case shouldn't happen, this transaction
10940                          * should have never made it onto the blocked queue.
10941                          */
10942                         /*
10943                          * This I/O is no longer blocked, we can remove it
10944                          * from the blocked queue.  Since this is a TAILQ
10945                          * (doubly linked list), we can do O(1) removals
10946                          * from any place on the list.
10947                          */
10948                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10949                                      blocked_links);
10950                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10951
10952                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10953                                 /*
10954                                  * Need to send IO back to original side to
10955                                  * run
10956                                  */
10957                                 union ctl_ha_msg msg_info;
10958
10959                                 msg_info.hdr.original_sc =
10960                                         cur_blocked->io_hdr.original_sc;
10961                                 msg_info.hdr.serializing_sc = cur_blocked;
10962                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10963                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10964                                      &msg_info, sizeof(msg_info), 0)) >
10965                                      CTL_HA_STATUS_SUCCESS) {
10966                                         printf("CTL:Check Blocked error from "
10967                                                "ctl_ha_msg_send %d\n",
10968                                                isc_retval);
10969                                 }
10970                                 break;
10971                         }
10972                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
10973                         softc = control_softc;
10974
10975                         initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10976
10977                         /*
10978                          * Check this I/O for LUN state changes that may
10979                          * have happened while this command was blocked.
10980                          * The LUN state may have been changed by a command
10981                          * ahead of us in the queue, so we need to re-check
10982                          * for any states that can be caused by SCSI
10983                          * commands.
10984                          */
10985                         if (ctl_scsiio_lun_check(softc, lun, entry,
10986                                                  &cur_blocked->scsiio) == 0) {
10987                                 cur_blocked->io_hdr.flags |=
10988                                                       CTL_FLAG_IS_WAS_ON_RTR;
10989                                 ctl_enqueue_rtr(cur_blocked);
10990                         } else
10991                                 ctl_done(cur_blocked);
10992                         break;
10993                 }
10994                 default:
10995                         /*
10996                          * This probably shouldn't happen -- we shouldn't
10997                          * get CTL_ACTION_ERROR, or anything else.
10998                          */
10999                         break;
11000                 }
11001         }
11002
11003         return (CTL_RETVAL_COMPLETE);
11004 }
11005
11006 /*
11007  * This routine (with one exception) checks LUN flags that can be set by
11008  * commands ahead of us in the OOA queue.  These flags have to be checked
11009  * when a command initially comes in, and when we pull a command off the
11010  * blocked queue and are preparing to execute it.  The reason we have to
11011  * check these flags for commands on the blocked queue is that the LUN
11012  * state may have been changed by a command ahead of us while we're on the
11013  * blocked queue.
11014  *
11015  * Ordering is somewhat important with these checks, so please pay
11016  * careful attention to the placement of any new checks.
11017  */
11018 static int
11019 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11020     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11021 {
11022         int retval;
11023
11024         retval = 0;
11025
11026         mtx_assert(&lun->lun_lock, MA_OWNED);
11027
11028         /*
11029          * If this shelf is a secondary shelf controller, we have to reject
11030          * any media access commands.
11031          */
11032 #if 0
11033         /* No longer needed for HA */
11034         if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11035          && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11036                 ctl_set_lun_standby(ctsio);
11037                 retval = 1;
11038                 goto bailout;
11039         }
11040 #endif
11041
11042         /*
11043          * Check for a reservation conflict.  If this command isn't allowed
11044          * even on reserved LUNs, and if this initiator isn't the one who
11045          * reserved us, reject the command with a reservation conflict.
11046          */
11047         if ((lun->flags & CTL_LUN_RESERVED)
11048          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11049                 if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
11050                  || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
11051                  || (ctsio->io_hdr.nexus.targ_target.id !=
11052                      lun->rsv_nexus.targ_target.id)) {
11053                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11054                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11055                         retval = 1;
11056                         goto bailout;
11057                 }
11058         }
11059
11060         if ( (lun->flags & CTL_LUN_PR_RESERVED)
11061          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11062                 uint32_t residx;
11063
11064                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11065                 /*
11066                  * if we aren't registered or it's a res holder type
11067                  * reservation and this isn't the res holder then set a
11068                  * conflict.
11069                  * NOTE: Commands which might be allowed on write exclusive
11070                  * type reservations are checked in the particular command
11071                  * for a conflict. Read and SSU are the only ones.
11072                  */
11073                 if (!lun->per_res[residx].registered
11074                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11075                         ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11076                         ctsio->io_hdr.status = CTL_SCSI_ERROR;
11077                         retval = 1;
11078                         goto bailout;
11079                 }
11080
11081         }
11082
11083         if ((lun->flags & CTL_LUN_OFFLINE)
11084          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11085                 ctl_set_lun_not_ready(ctsio);
11086                 retval = 1;
11087                 goto bailout;
11088         }
11089
11090         /*
11091          * If the LUN is stopped, see if this particular command is allowed
11092          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11093          */
11094         if ((lun->flags & CTL_LUN_STOPPED)
11095          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11096                 /* "Logical unit not ready, initializing cmd. required" */
11097                 ctl_set_lun_stopped(ctsio);
11098                 retval = 1;
11099                 goto bailout;
11100         }
11101
11102         if ((lun->flags & CTL_LUN_INOPERABLE)
11103          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11104                 /* "Medium format corrupted" */
11105                 ctl_set_medium_format_corrupted(ctsio);
11106                 retval = 1;
11107                 goto bailout;
11108         }
11109
11110 bailout:
11111         return (retval);
11112
11113 }
11114
11115 static void
11116 ctl_failover_io(union ctl_io *io, int have_lock)
11117 {
11118         ctl_set_busy(&io->scsiio);
11119         ctl_done(io);
11120 }
11121
11122 static void
11123 ctl_failover(void)
11124 {
11125         struct ctl_lun *lun;
11126         struct ctl_softc *ctl_softc;
11127         union ctl_io *next_io, *pending_io;
11128         union ctl_io *io;
11129         int lun_idx;
11130         int i;
11131
11132         ctl_softc = control_softc;
11133
11134         mtx_lock(&ctl_softc->ctl_lock);
11135         /*
11136          * Remove any cmds from the other SC from the rtr queue.  These
11137          * will obviously only be for LUNs for which we're the primary.
11138          * We can't send status or get/send data for these commands.
11139          * Since they haven't been executed yet, we can just remove them.
11140          * We'll either abort them or delete them below, depending on
11141          * which HA mode we're in.
11142          */
11143 #ifdef notyet
11144         mtx_lock(&ctl_softc->queue_lock);
11145         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11146              io != NULL; io = next_io) {
11147                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11148                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11149                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11150                                       ctl_io_hdr, links);
11151         }
11152         mtx_unlock(&ctl_softc->queue_lock);
11153 #endif
11154
11155         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11156                 lun = ctl_softc->ctl_luns[lun_idx];
11157                 if (lun==NULL)
11158                         continue;
11159
11160                 /*
11161                  * Processor LUNs are primary on both sides.
11162                  * XXX will this always be true?
11163                  */
11164                 if (lun->be_lun->lun_type == T_PROCESSOR)
11165                         continue;
11166
11167                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11168                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11169                         printf("FAILOVER: primary lun %d\n", lun_idx);
11170                         /*
11171                          * Remove all commands from the other SC. First from the
11172                          * blocked queue then from the ooa queue. Once we have
11173                          * removed them. Call ctl_check_blocked to see if there
11174                          * is anything that can run.
11175                          */
11176                         for (io = (union ctl_io *)TAILQ_FIRST(
11177                              &lun->blocked_queue); io != NULL; io = next_io) {
11178
11179                                 next_io = (union ctl_io *)TAILQ_NEXT(
11180                                     &io->io_hdr, blocked_links);
11181
11182                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11183                                         TAILQ_REMOVE(&lun->blocked_queue,
11184                                                      &io->io_hdr,blocked_links);
11185                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11186                                         TAILQ_REMOVE(&lun->ooa_queue,
11187                                                      &io->io_hdr, ooa_links);
11188
11189                                         ctl_free_io(io);
11190                                 }
11191                         }
11192
11193                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11194                              io != NULL; io = next_io) {
11195
11196                                 next_io = (union ctl_io *)TAILQ_NEXT(
11197                                     &io->io_hdr, ooa_links);
11198
11199                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11200
11201                                         TAILQ_REMOVE(&lun->ooa_queue,
11202                                                 &io->io_hdr,
11203                                                 ooa_links);
11204
11205                                         ctl_free_io(io);
11206                                 }
11207                         }
11208                         ctl_check_blocked(lun);
11209                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11210                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11211
11212                         printf("FAILOVER: primary lun %d\n", lun_idx);
11213                         /*
11214                          * Abort all commands from the other SC.  We can't
11215                          * send status back for them now.  These should get
11216                          * cleaned up when they are completed or come out
11217                          * for a datamove operation.
11218                          */
11219                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11220                              io != NULL; io = next_io) {
11221                                 next_io = (union ctl_io *)TAILQ_NEXT(
11222                                         &io->io_hdr, ooa_links);
11223
11224                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11225                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11226                         }
11227                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11228                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11229
11230                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11231
11232                         lun->flags |= CTL_LUN_PRIMARY_SC;
11233
11234                         /*
11235                          * We send all I/O that was sent to this controller
11236                          * and redirected to the other side back with
11237                          * busy status, and have the initiator retry it.
11238                          * Figuring out how much data has been transferred,
11239                          * etc. and picking up where we left off would be 
11240                          * very tricky.
11241                          *
11242                          * XXX KDM need to remove I/O from the blocked
11243                          * queue as well!
11244                          */
11245                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11246                              &lun->ooa_queue); pending_io != NULL;
11247                              pending_io = next_io) {
11248
11249                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11250                                         &pending_io->io_hdr, ooa_links);
11251
11252                                 pending_io->io_hdr.flags &=
11253                                         ~CTL_FLAG_SENT_2OTHER_SC;
11254
11255                                 if (pending_io->io_hdr.flags &
11256                                     CTL_FLAG_IO_ACTIVE) {
11257                                         pending_io->io_hdr.flags |=
11258                                                 CTL_FLAG_FAILOVER;
11259                                 } else {
11260                                         ctl_set_busy(&pending_io->scsiio);
11261                                         ctl_done(pending_io);
11262                                 }
11263                         }
11264
11265                         /*
11266                          * Build Unit Attention
11267                          */
11268                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11269                                 lun->pending_sense[i].ua_pending |=
11270                                                      CTL_UA_ASYM_ACC_CHANGE;
11271                         }
11272                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11273                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11274                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11275                         /*
11276                          * if the first io on the OOA is not on the RtR queue
11277                          * add it.
11278                          */
11279                         lun->flags |= CTL_LUN_PRIMARY_SC;
11280
11281                         pending_io = (union ctl_io *)TAILQ_FIRST(
11282                             &lun->ooa_queue);
11283                         if (pending_io==NULL) {
11284                                 printf("Nothing on OOA queue\n");
11285                                 continue;
11286                         }
11287
11288                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11289                         if ((pending_io->io_hdr.flags &
11290                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11291                                 pending_io->io_hdr.flags |=
11292                                     CTL_FLAG_IS_WAS_ON_RTR;
11293                                 ctl_enqueue_rtr(pending_io);
11294                         }
11295 #if 0
11296                         else
11297                         {
11298                                 printf("Tag 0x%04x is running\n",
11299                                       pending_io->scsiio.tag_num);
11300                         }
11301 #endif
11302
11303                         next_io = (union ctl_io *)TAILQ_NEXT(
11304                             &pending_io->io_hdr, ooa_links);
11305                         for (pending_io=next_io; pending_io != NULL;
11306                              pending_io = next_io) {
11307                                 pending_io->io_hdr.flags &=
11308                                     ~CTL_FLAG_SENT_2OTHER_SC;
11309                                 next_io = (union ctl_io *)TAILQ_NEXT(
11310                                         &pending_io->io_hdr, ooa_links);
11311                                 if (pending_io->io_hdr.flags &
11312                                     CTL_FLAG_IS_WAS_ON_RTR) {
11313 #if 0
11314                                         printf("Tag 0x%04x is running\n",
11315                                                 pending_io->scsiio.tag_num);
11316 #endif
11317                                         continue;
11318                                 }
11319
11320                                 switch (ctl_check_ooa(lun, pending_io,
11321                                     (union ctl_io *)TAILQ_PREV(
11322                                     &pending_io->io_hdr, ctl_ooaq,
11323                                     ooa_links))) {
11324
11325                                 case CTL_ACTION_BLOCK:
11326                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11327                                                           &pending_io->io_hdr,
11328                                                           blocked_links);
11329                                         pending_io->io_hdr.flags |=
11330                                             CTL_FLAG_BLOCKED;
11331                                         break;
11332                                 case CTL_ACTION_PASS:
11333                                 case CTL_ACTION_SKIP:
11334                                         pending_io->io_hdr.flags |=
11335                                             CTL_FLAG_IS_WAS_ON_RTR;
11336                                         ctl_enqueue_rtr(pending_io);
11337                                         break;
11338                                 case CTL_ACTION_OVERLAP:
11339                                         ctl_set_overlapped_cmd(
11340                                             (struct ctl_scsiio *)pending_io);
11341                                         ctl_done(pending_io);
11342                                         break;
11343                                 case CTL_ACTION_OVERLAP_TAG:
11344                                         ctl_set_overlapped_tag(
11345                                             (struct ctl_scsiio *)pending_io,
11346                                             pending_io->scsiio.tag_num & 0xff);
11347                                         ctl_done(pending_io);
11348                                         break;
11349                                 case CTL_ACTION_ERROR:
11350                                 default:
11351                                         ctl_set_internal_failure(
11352                                                 (struct ctl_scsiio *)pending_io,
11353                                                 0,  // sks_valid
11354                                                 0); //retry count
11355                                         ctl_done(pending_io);
11356                                         break;
11357                                 }
11358                         }
11359
11360                         /*
11361                          * Build Unit Attention
11362                          */
11363                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11364                                 lun->pending_sense[i].ua_pending |=
11365                                                      CTL_UA_ASYM_ACC_CHANGE;
11366                         }
11367                 } else {
11368                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11369                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11370                 }
11371         }
11372         ctl_pause_rtr = 0;
11373         mtx_unlock(&ctl_softc->ctl_lock);
11374 }
11375
11376 static int
11377 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11378 {
11379         struct ctl_lun *lun;
11380         const struct ctl_cmd_entry *entry;
11381         uint32_t initidx, targ_lun;
11382         int retval;
11383
11384         retval = 0;
11385
11386         lun = NULL;
11387
11388         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11389         if ((targ_lun < CTL_MAX_LUNS)
11390          && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11391                 lun = ctl_softc->ctl_luns[targ_lun];
11392                 /*
11393                  * If the LUN is invalid, pretend that it doesn't exist.
11394                  * It will go away as soon as all pending I/O has been
11395                  * completed.
11396                  */
11397                 if (lun->flags & CTL_LUN_DISABLED) {
11398                         lun = NULL;
11399                 } else {
11400                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11401                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11402                                 lun->be_lun;
11403                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11404                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11405                         }
11406
11407                         /*
11408                          * Every I/O goes into the OOA queue for a
11409                          * particular LUN, and stays there until completion.
11410                          */
11411                         mtx_lock(&lun->lun_lock);
11412                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11413                             ooa_links);
11414                 }
11415         } else {
11416                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11417                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11418         }
11419
11420         /* Get command entry and return error if it is unsuppotyed. */
11421         entry = ctl_validate_command(ctsio);
11422         if (entry == NULL) {
11423                 if (lun)
11424                         mtx_unlock(&lun->lun_lock);
11425                 return (retval);
11426         }
11427
11428         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11429         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11430
11431         /*
11432          * Check to see whether we can send this command to LUNs that don't
11433          * exist.  This should pretty much only be the case for inquiry
11434          * and request sense.  Further checks, below, really require having
11435          * a LUN, so we can't really check the command anymore.  Just put
11436          * it on the rtr queue.
11437          */
11438         if (lun == NULL) {
11439                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11440                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11441                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11442                         return (retval);
11443                 }
11444
11445                 ctl_set_unsupported_lun(ctsio);
11446                 ctl_done((union ctl_io *)ctsio);
11447                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11448                 return (retval);
11449         } else {
11450                 /*
11451                  * Make sure we support this particular command on this LUN.
11452                  * e.g., we don't support writes to the control LUN.
11453                  */
11454                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11455                         mtx_unlock(&lun->lun_lock);
11456                         ctl_set_invalid_opcode(ctsio);
11457                         ctl_done((union ctl_io *)ctsio);
11458                         return (retval);
11459                 }
11460         }
11461
11462         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11463
11464         /*
11465          * If we've got a request sense, it'll clear the contingent
11466          * allegiance condition.  Otherwise, if we have a CA condition for
11467          * this initiator, clear it, because it sent down a command other
11468          * than request sense.
11469          */
11470         if ((ctsio->cdb[0] != REQUEST_SENSE)
11471          && (ctl_is_set(lun->have_ca, initidx)))
11472                 ctl_clear_mask(lun->have_ca, initidx);
11473
11474         /*
11475          * If the command has this flag set, it handles its own unit
11476          * attention reporting, we shouldn't do anything.  Otherwise we
11477          * check for any pending unit attentions, and send them back to the
11478          * initiator.  We only do this when a command initially comes in,
11479          * not when we pull it off the blocked queue.
11480          *
11481          * According to SAM-3, section 5.3.2, the order that things get
11482          * presented back to the host is basically unit attentions caused
11483          * by some sort of reset event, busy status, reservation conflicts
11484          * or task set full, and finally any other status.
11485          *
11486          * One issue here is that some of the unit attentions we report
11487          * don't fall into the "reset" category (e.g. "reported luns data
11488          * has changed").  So reporting it here, before the reservation
11489          * check, may be technically wrong.  I guess the only thing to do
11490          * would be to check for and report the reset events here, and then
11491          * check for the other unit attention types after we check for a
11492          * reservation conflict.
11493          *
11494          * XXX KDM need to fix this
11495          */
11496         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11497                 ctl_ua_type ua_type;
11498
11499                 ua_type = lun->pending_sense[initidx].ua_pending;
11500                 if (ua_type != CTL_UA_NONE) {
11501                         scsi_sense_data_type sense_format;
11502
11503                         if (lun != NULL)
11504                                 sense_format = (lun->flags &
11505                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11506                                     SSD_TYPE_FIXED;
11507                         else
11508                                 sense_format = SSD_TYPE_FIXED;
11509
11510                         ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11511                                                sense_format);
11512                         if (ua_type != CTL_UA_NONE) {
11513                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11514                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11515                                                        CTL_AUTOSENSE;
11516                                 ctsio->sense_len = SSD_FULL_SIZE;
11517                                 lun->pending_sense[initidx].ua_pending &=
11518                                         ~ua_type;
11519                                 mtx_unlock(&lun->lun_lock);
11520                                 ctl_done((union ctl_io *)ctsio);
11521                                 return (retval);
11522                         }
11523                 }
11524         }
11525
11526
11527         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11528                 mtx_unlock(&lun->lun_lock);
11529                 ctl_done((union ctl_io *)ctsio);
11530                 return (retval);
11531         }
11532
11533         /*
11534          * XXX CHD this is where we want to send IO to other side if
11535          * this LUN is secondary on this SC. We will need to make a copy
11536          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11537          * the copy we send as FROM_OTHER.
11538          * We also need to stuff the address of the original IO so we can
11539          * find it easily. Something similar will need be done on the other
11540          * side so when we are done we can find the copy.
11541          */
11542         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11543                 union ctl_ha_msg msg_info;
11544                 int isc_retval;
11545
11546                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11547
11548                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11549                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11550 #if 0
11551                 printf("1. ctsio %p\n", ctsio);
11552 #endif
11553                 msg_info.hdr.serializing_sc = NULL;
11554                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11555                 msg_info.scsi.tag_num = ctsio->tag_num;
11556                 msg_info.scsi.tag_type = ctsio->tag_type;
11557                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11558
11559                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11560
11561                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11562                     (void *)&msg_info, sizeof(msg_info), 0)) >
11563                     CTL_HA_STATUS_SUCCESS) {
11564                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11565                                isc_retval);
11566                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11567                 } else {
11568 #if 0
11569                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11570 #endif
11571                 }
11572
11573                 /*
11574                  * XXX KDM this I/O is off the incoming queue, but hasn't
11575                  * been inserted on any other queue.  We may need to come
11576                  * up with a holding queue while we wait for serialization
11577                  * so that we have an idea of what we're waiting for from
11578                  * the other side.
11579                  */
11580                 mtx_unlock(&lun->lun_lock);
11581                 return (retval);
11582         }
11583
11584         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11585                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11586                               ctl_ooaq, ooa_links))) {
11587         case CTL_ACTION_BLOCK:
11588                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11589                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11590                                   blocked_links);
11591                 mtx_unlock(&lun->lun_lock);
11592                 return (retval);
11593         case CTL_ACTION_PASS:
11594         case CTL_ACTION_SKIP:
11595                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11596                 mtx_unlock(&lun->lun_lock);
11597                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11598                 break;
11599         case CTL_ACTION_OVERLAP:
11600                 mtx_unlock(&lun->lun_lock);
11601                 ctl_set_overlapped_cmd(ctsio);
11602                 ctl_done((union ctl_io *)ctsio);
11603                 break;
11604         case CTL_ACTION_OVERLAP_TAG:
11605                 mtx_unlock(&lun->lun_lock);
11606                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11607                 ctl_done((union ctl_io *)ctsio);
11608                 break;
11609         case CTL_ACTION_ERROR:
11610         default:
11611                 mtx_unlock(&lun->lun_lock);
11612                 ctl_set_internal_failure(ctsio,
11613                                          /*sks_valid*/ 0,
11614                                          /*retry_count*/ 0);
11615                 ctl_done((union ctl_io *)ctsio);
11616                 break;
11617         }
11618         return (retval);
11619 }
11620
11621 const struct ctl_cmd_entry *
11622 ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11623 {
11624         const struct ctl_cmd_entry *entry;
11625         int service_action;
11626
11627         entry = &ctl_cmd_table[ctsio->cdb[0]];
11628         if (entry->flags & CTL_CMD_FLAG_SA5) {
11629                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11630                 entry = &((const struct ctl_cmd_entry *)
11631                     entry->execute)[service_action];
11632         }
11633         return (entry);
11634 }
11635
11636 const struct ctl_cmd_entry *
11637 ctl_validate_command(struct ctl_scsiio *ctsio)
11638 {
11639         const struct ctl_cmd_entry *entry;
11640         int i;
11641         uint8_t diff;
11642
11643         entry = ctl_get_cmd_entry(ctsio);
11644         if (entry->execute == NULL) {
11645                 ctl_set_invalid_opcode(ctsio);
11646                 ctl_done((union ctl_io *)ctsio);
11647                 return (NULL);
11648         }
11649         KASSERT(entry->length > 0,
11650             ("Not defined length for command 0x%02x/0x%02x",
11651              ctsio->cdb[0], ctsio->cdb[1]));
11652         for (i = 1; i < entry->length; i++) {
11653                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11654                 if (diff == 0)
11655                         continue;
11656                 ctl_set_invalid_field(ctsio,
11657                                       /*sks_valid*/ 1,
11658                                       /*command*/ 1,
11659                                       /*field*/ i,
11660                                       /*bit_valid*/ 1,
11661                                       /*bit*/ fls(diff) - 1);
11662                 ctl_done((union ctl_io *)ctsio);
11663                 return (NULL);
11664         }
11665         return (entry);
11666 }
11667
11668 static int
11669 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11670 {
11671
11672         switch (lun_type) {
11673         case T_PROCESSOR:
11674                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11675                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11676                         return (0);
11677                 break;
11678         case T_DIRECT:
11679                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11680                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11681                         return (0);
11682                 break;
11683         default:
11684                 return (0);
11685         }
11686         return (1);
11687 }
11688
11689 static int
11690 ctl_scsiio(struct ctl_scsiio *ctsio)
11691 {
11692         int retval;
11693         const struct ctl_cmd_entry *entry;
11694
11695         retval = CTL_RETVAL_COMPLETE;
11696
11697         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11698
11699         entry = ctl_get_cmd_entry(ctsio);
11700
11701         /*
11702          * If this I/O has been aborted, just send it straight to
11703          * ctl_done() without executing it.
11704          */
11705         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11706                 ctl_done((union ctl_io *)ctsio);
11707                 goto bailout;
11708         }
11709
11710         /*
11711          * All the checks should have been handled by ctl_scsiio_precheck().
11712          * We should be clear now to just execute the I/O.
11713          */
11714         retval = entry->execute(ctsio);
11715
11716 bailout:
11717         return (retval);
11718 }
11719
11720 /*
11721  * Since we only implement one target right now, a bus reset simply resets
11722  * our single target.
11723  */
11724 static int
11725 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11726 {
11727         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11728 }
11729
11730 static int
11731 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11732                  ctl_ua_type ua_type)
11733 {
11734         struct ctl_lun *lun;
11735         int retval;
11736
11737         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11738                 union ctl_ha_msg msg_info;
11739
11740                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11741                 msg_info.hdr.nexus = io->io_hdr.nexus;
11742                 if (ua_type==CTL_UA_TARG_RESET)
11743                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11744                 else
11745                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11746                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11747                 msg_info.hdr.original_sc = NULL;
11748                 msg_info.hdr.serializing_sc = NULL;
11749                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11750                     (void *)&msg_info, sizeof(msg_info), 0)) {
11751                 }
11752         }
11753         retval = 0;
11754
11755         mtx_lock(&ctl_softc->ctl_lock);
11756         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11757                 retval += ctl_lun_reset(lun, io, ua_type);
11758         mtx_unlock(&ctl_softc->ctl_lock);
11759
11760         return (retval);
11761 }
11762
11763 /*
11764  * The LUN should always be set.  The I/O is optional, and is used to
11765  * distinguish between I/Os sent by this initiator, and by other
11766  * initiators.  We set unit attention for initiators other than this one.
11767  * SAM-3 is vague on this point.  It does say that a unit attention should
11768  * be established for other initiators when a LUN is reset (see section
11769  * 5.7.3), but it doesn't specifically say that the unit attention should
11770  * be established for this particular initiator when a LUN is reset.  Here
11771  * is the relevant text, from SAM-3 rev 8:
11772  *
11773  * 5.7.2 When a SCSI initiator port aborts its own tasks
11774  *
11775  * When a SCSI initiator port causes its own task(s) to be aborted, no
11776  * notification that the task(s) have been aborted shall be returned to
11777  * the SCSI initiator port other than the completion response for the
11778  * command or task management function action that caused the task(s) to
11779  * be aborted and notification(s) associated with related effects of the
11780  * action (e.g., a reset unit attention condition).
11781  *
11782  * XXX KDM for now, we're setting unit attention for all initiators.
11783  */
11784 static int
11785 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11786 {
11787         union ctl_io *xio;
11788 #if 0
11789         uint32_t initindex;
11790 #endif
11791         int i;
11792
11793         mtx_lock(&lun->lun_lock);
11794         /*
11795          * Run through the OOA queue and abort each I/O.
11796          */
11797 #if 0
11798         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11799 #endif
11800         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11801              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11802                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11803         }
11804
11805         /*
11806          * This version sets unit attention for every
11807          */
11808 #if 0
11809         initindex = ctl_get_initindex(&io->io_hdr.nexus);
11810         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11811                 if (initindex == i)
11812                         continue;
11813                 lun->pending_sense[i].ua_pending |= ua_type;
11814         }
11815 #endif
11816
11817         /*
11818          * A reset (any kind, really) clears reservations established with
11819          * RESERVE/RELEASE.  It does not clear reservations established
11820          * with PERSISTENT RESERVE OUT, but we don't support that at the
11821          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11822          * reservations made with the RESERVE/RELEASE commands, because
11823          * those commands are obsolete in SPC-3.
11824          */
11825         lun->flags &= ~CTL_LUN_RESERVED;
11826
11827         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11828                 ctl_clear_mask(lun->have_ca, i);
11829                 lun->pending_sense[i].ua_pending |= ua_type;
11830         }
11831         mtx_unlock(&lun->lun_lock);
11832
11833         return (0);
11834 }
11835
11836 static int
11837 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11838     int other_sc)
11839 {
11840         union ctl_io *xio;
11841         int found;
11842
11843         mtx_assert(&lun->lun_lock, MA_OWNED);
11844
11845         /*
11846          * Run through the OOA queue and attempt to find the given I/O.
11847          * The target port, initiator ID, tag type and tag number have to
11848          * match the values that we got from the initiator.  If we have an
11849          * untagged command to abort, simply abort the first untagged command
11850          * we come to.  We only allow one untagged command at a time of course.
11851          */
11852         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11853              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11854
11855                 if ((targ_port == UINT32_MAX ||
11856                      targ_port == xio->io_hdr.nexus.targ_port) &&
11857                     (init_id == UINT32_MAX ||
11858                      init_id == xio->io_hdr.nexus.initid.id)) {
11859                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11860                             init_id != xio->io_hdr.nexus.initid.id)
11861                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11862                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11863                         found = 1;
11864                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11865                                 union ctl_ha_msg msg_info;
11866
11867                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11868                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11869                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11870                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11871                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11872                                 msg_info.hdr.original_sc = NULL;
11873                                 msg_info.hdr.serializing_sc = NULL;
11874                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11875                                     (void *)&msg_info, sizeof(msg_info), 0);
11876                         }
11877                 }
11878         }
11879         return (found);
11880 }
11881
11882 static int
11883 ctl_abort_task_set(union ctl_io *io)
11884 {
11885         struct ctl_softc *softc = control_softc;
11886         struct ctl_lun *lun;
11887         uint32_t targ_lun;
11888
11889         /*
11890          * Look up the LUN.
11891          */
11892         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11893         mtx_lock(&softc->ctl_lock);
11894         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11895                 lun = softc->ctl_luns[targ_lun];
11896         else {
11897                 mtx_unlock(&softc->ctl_lock);
11898                 return (1);
11899         }
11900
11901         mtx_lock(&lun->lun_lock);
11902         mtx_unlock(&softc->ctl_lock);
11903         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11904                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11905                     io->io_hdr.nexus.initid.id,
11906                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11907         } else { /* CTL_TASK_CLEAR_TASK_SET */
11908                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11909                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11910         }
11911         mtx_unlock(&lun->lun_lock);
11912         return (0);
11913 }
11914
11915 static int
11916 ctl_i_t_nexus_reset(union ctl_io *io)
11917 {
11918         struct ctl_softc *softc = control_softc;
11919         struct ctl_lun *lun;
11920         uint32_t initindex;
11921
11922         initindex = ctl_get_initindex(&io->io_hdr.nexus);
11923         mtx_lock(&softc->ctl_lock);
11924         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11925                 mtx_lock(&lun->lun_lock);
11926                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11927                     io->io_hdr.nexus.initid.id,
11928                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11929                 ctl_clear_mask(lun->have_ca, initindex);
11930                 lun->pending_sense[initindex].ua_pending |= CTL_UA_I_T_NEXUS_LOSS;
11931                 mtx_unlock(&lun->lun_lock);
11932         }
11933         mtx_unlock(&softc->ctl_lock);
11934         return (0);
11935 }
11936
11937 static int
11938 ctl_abort_task(union ctl_io *io)
11939 {
11940         union ctl_io *xio;
11941         struct ctl_lun *lun;
11942         struct ctl_softc *ctl_softc;
11943 #if 0
11944         struct sbuf sb;
11945         char printbuf[128];
11946 #endif
11947         int found;
11948         uint32_t targ_lun;
11949
11950         ctl_softc = control_softc;
11951         found = 0;
11952
11953         /*
11954          * Look up the LUN.
11955          */
11956         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11957         mtx_lock(&ctl_softc->ctl_lock);
11958         if ((targ_lun < CTL_MAX_LUNS)
11959          && (ctl_softc->ctl_luns[targ_lun] != NULL))
11960                 lun = ctl_softc->ctl_luns[targ_lun];
11961         else {
11962                 mtx_unlock(&ctl_softc->ctl_lock);
11963                 return (1);
11964         }
11965
11966 #if 0
11967         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11968                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11969 #endif
11970
11971         mtx_lock(&lun->lun_lock);
11972         mtx_unlock(&ctl_softc->ctl_lock);
11973         /*
11974          * Run through the OOA queue and attempt to find the given I/O.
11975          * The target port, initiator ID, tag type and tag number have to
11976          * match the values that we got from the initiator.  If we have an
11977          * untagged command to abort, simply abort the first untagged command
11978          * we come to.  We only allow one untagged command at a time of course.
11979          */
11980 #if 0
11981         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11982 #endif
11983         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11984              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11985 #if 0
11986                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11987
11988                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11989                             lun->lun, xio->scsiio.tag_num,
11990                             xio->scsiio.tag_type,
11991                             (xio->io_hdr.blocked_links.tqe_prev
11992                             == NULL) ? "" : " BLOCKED",
11993                             (xio->io_hdr.flags &
11994                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11995                             (xio->io_hdr.flags &
11996                             CTL_FLAG_ABORT) ? " ABORT" : "",
11997                             (xio->io_hdr.flags &
11998                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11999                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12000                 sbuf_finish(&sb);
12001                 printf("%s\n", sbuf_data(&sb));
12002 #endif
12003
12004                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12005                  && (xio->io_hdr.nexus.initid.id ==
12006                      io->io_hdr.nexus.initid.id)) {
12007                         /*
12008                          * If the abort says that the task is untagged, the
12009                          * task in the queue must be untagged.  Otherwise,
12010                          * we just check to see whether the tag numbers
12011                          * match.  This is because the QLogic firmware
12012                          * doesn't pass back the tag type in an abort
12013                          * request.
12014                          */
12015 #if 0
12016                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12017                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12018                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12019 #endif
12020                         /*
12021                          * XXX KDM we've got problems with FC, because it
12022                          * doesn't send down a tag type with aborts.  So we
12023                          * can only really go by the tag number...
12024                          * This may cause problems with parallel SCSI.
12025                          * Need to figure that out!!
12026                          */
12027                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12028                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12029                                 found = 1;
12030                                 if ((io->io_hdr.flags &
12031                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12032                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12033                                         union ctl_ha_msg msg_info;
12034
12035                                         io->io_hdr.flags |=
12036                                                         CTL_FLAG_SENT_2OTHER_SC;
12037                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12038                                         msg_info.task.task_action =
12039                                                 CTL_TASK_ABORT_TASK;
12040                                         msg_info.task.tag_num =
12041                                                 io->taskio.tag_num;
12042                                         msg_info.task.tag_type =
12043                                                 io->taskio.tag_type;
12044                                         msg_info.hdr.msg_type =
12045                                                 CTL_MSG_MANAGE_TASKS;
12046                                         msg_info.hdr.original_sc = NULL;
12047                                         msg_info.hdr.serializing_sc = NULL;
12048 #if 0
12049                                         printf("Sent Abort to other side\n");
12050 #endif
12051                                         if (CTL_HA_STATUS_SUCCESS !=
12052                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12053                                                 (void *)&msg_info,
12054                                                 sizeof(msg_info), 0)) {
12055                                         }
12056                                 }
12057 #if 0
12058                                 printf("ctl_abort_task: found I/O to abort\n");
12059 #endif
12060                                 break;
12061                         }
12062                 }
12063         }
12064         mtx_unlock(&lun->lun_lock);
12065
12066         if (found == 0) {
12067                 /*
12068                  * This isn't really an error.  It's entirely possible for
12069                  * the abort and command completion to cross on the wire.
12070                  * This is more of an informative/diagnostic error.
12071                  */
12072 #if 0
12073                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12074                        "%d:%d:%d:%d tag %d type %d\n",
12075                        io->io_hdr.nexus.initid.id,
12076                        io->io_hdr.nexus.targ_port,
12077                        io->io_hdr.nexus.targ_target.id,
12078                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12079                        io->taskio.tag_type);
12080 #endif
12081         }
12082         return (0);
12083 }
12084
12085 static void
12086 ctl_run_task(union ctl_io *io)
12087 {
12088         struct ctl_softc *ctl_softc = control_softc;
12089         int retval = 1;
12090         const char *task_desc;
12091
12092         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12093
12094         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12095             ("ctl_run_task: Unextected io_type %d\n",
12096              io->io_hdr.io_type));
12097
12098         task_desc = ctl_scsi_task_string(&io->taskio);
12099         if (task_desc != NULL) {
12100 #ifdef NEEDTOPORT
12101                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12102                             CTL_TASK_REPORT,
12103                             csevent_LogType_Trace,
12104                             csevent_Severity_Information,
12105                             csevent_AlertLevel_Green,
12106                             csevent_FRU_Firmware,
12107                             csevent_FRU_Unknown,
12108                             "CTL: received task: %s",task_desc);
12109 #endif
12110         } else {
12111 #ifdef NEEDTOPORT
12112                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12113                             CTL_TASK_REPORT,
12114                             csevent_LogType_Trace,
12115                             csevent_Severity_Information,
12116                             csevent_AlertLevel_Green,
12117                             csevent_FRU_Firmware,
12118                             csevent_FRU_Unknown,
12119                             "CTL: received unknown task "
12120                             "type: %d (%#x)",
12121                             io->taskio.task_action,
12122                             io->taskio.task_action);
12123 #endif
12124         }
12125         switch (io->taskio.task_action) {
12126         case CTL_TASK_ABORT_TASK:
12127                 retval = ctl_abort_task(io);
12128                 break;
12129         case CTL_TASK_ABORT_TASK_SET:
12130         case CTL_TASK_CLEAR_TASK_SET:
12131                 retval = ctl_abort_task_set(io);
12132                 break;
12133         case CTL_TASK_CLEAR_ACA:
12134                 break;
12135         case CTL_TASK_I_T_NEXUS_RESET:
12136                 retval = ctl_i_t_nexus_reset(io);
12137                 break;
12138         case CTL_TASK_LUN_RESET: {
12139                 struct ctl_lun *lun;
12140                 uint32_t targ_lun;
12141
12142                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12143                 mtx_lock(&ctl_softc->ctl_lock);
12144                 if ((targ_lun < CTL_MAX_LUNS)
12145                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12146                         lun = ctl_softc->ctl_luns[targ_lun];
12147                 else {
12148                         mtx_unlock(&ctl_softc->ctl_lock);
12149                         retval = 1;
12150                         break;
12151                 }
12152
12153                 if (!(io->io_hdr.flags &
12154                     CTL_FLAG_FROM_OTHER_SC)) {
12155                         union ctl_ha_msg msg_info;
12156
12157                         io->io_hdr.flags |=
12158                                 CTL_FLAG_SENT_2OTHER_SC;
12159                         msg_info.hdr.msg_type =
12160                                 CTL_MSG_MANAGE_TASKS;
12161                         msg_info.hdr.nexus = io->io_hdr.nexus;
12162                         msg_info.task.task_action =
12163                                 CTL_TASK_LUN_RESET;
12164                         msg_info.hdr.original_sc = NULL;
12165                         msg_info.hdr.serializing_sc = NULL;
12166                         if (CTL_HA_STATUS_SUCCESS !=
12167                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12168                             (void *)&msg_info,
12169                             sizeof(msg_info), 0)) {
12170                         }
12171                 }
12172
12173                 retval = ctl_lun_reset(lun, io,
12174                                        CTL_UA_LUN_RESET);
12175                 mtx_unlock(&ctl_softc->ctl_lock);
12176                 break;
12177         }
12178         case CTL_TASK_TARGET_RESET:
12179                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12180                 break;
12181         case CTL_TASK_BUS_RESET:
12182                 retval = ctl_bus_reset(ctl_softc, io);
12183                 break;
12184         case CTL_TASK_PORT_LOGIN:
12185                 break;
12186         case CTL_TASK_PORT_LOGOUT:
12187                 break;
12188         default:
12189                 printf("ctl_run_task: got unknown task management event %d\n",
12190                        io->taskio.task_action);
12191                 break;
12192         }
12193         if (retval == 0)
12194                 io->io_hdr.status = CTL_SUCCESS;
12195         else
12196                 io->io_hdr.status = CTL_ERROR;
12197         ctl_done(io);
12198 }
12199
12200 /*
12201  * For HA operation.  Handle commands that come in from the other
12202  * controller.
12203  */
12204 static void
12205 ctl_handle_isc(union ctl_io *io)
12206 {
12207         int free_io;
12208         struct ctl_lun *lun;
12209         struct ctl_softc *ctl_softc;
12210         uint32_t targ_lun;
12211
12212         ctl_softc = control_softc;
12213
12214         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12215         lun = ctl_softc->ctl_luns[targ_lun];
12216
12217         switch (io->io_hdr.msg_type) {
12218         case CTL_MSG_SERIALIZE:
12219                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12220                 break;
12221         case CTL_MSG_R2R: {
12222                 const struct ctl_cmd_entry *entry;
12223
12224                 /*
12225                  * This is only used in SER_ONLY mode.
12226                  */
12227                 free_io = 0;
12228                 entry = ctl_get_cmd_entry(&io->scsiio);
12229                 mtx_lock(&lun->lun_lock);
12230                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12231                     entry, (struct ctl_scsiio *)io) != 0) {
12232                         mtx_unlock(&lun->lun_lock);
12233                         ctl_done(io);
12234                         break;
12235                 }
12236                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12237                 mtx_unlock(&lun->lun_lock);
12238                 ctl_enqueue_rtr(io);
12239                 break;
12240         }
12241         case CTL_MSG_FINISH_IO:
12242                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12243                         free_io = 0;
12244                         ctl_done(io);
12245                 } else {
12246                         free_io = 1;
12247                         mtx_lock(&lun->lun_lock);
12248                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12249                                      ooa_links);
12250                         ctl_check_blocked(lun);
12251                         mtx_unlock(&lun->lun_lock);
12252                 }
12253                 break;
12254         case CTL_MSG_PERS_ACTION:
12255                 ctl_hndl_per_res_out_on_other_sc(
12256                         (union ctl_ha_msg *)&io->presio.pr_msg);
12257                 free_io = 1;
12258                 break;
12259         case CTL_MSG_BAD_JUJU:
12260                 free_io = 0;
12261                 ctl_done(io);
12262                 break;
12263         case CTL_MSG_DATAMOVE:
12264                 /* Only used in XFER mode */
12265                 free_io = 0;
12266                 ctl_datamove_remote(io);
12267                 break;
12268         case CTL_MSG_DATAMOVE_DONE:
12269                 /* Only used in XFER mode */
12270                 free_io = 0;
12271                 io->scsiio.be_move_done(io);
12272                 break;
12273         default:
12274                 free_io = 1;
12275                 printf("%s: Invalid message type %d\n",
12276                        __func__, io->io_hdr.msg_type);
12277                 break;
12278         }
12279         if (free_io)
12280                 ctl_free_io(io);
12281
12282 }
12283
12284
12285 /*
12286  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12287  * there is no match.
12288  */
12289 static ctl_lun_error_pattern
12290 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12291 {
12292         const struct ctl_cmd_entry *entry;
12293         ctl_lun_error_pattern filtered_pattern, pattern;
12294
12295         pattern = desc->error_pattern;
12296
12297         /*
12298          * XXX KDM we need more data passed into this function to match a
12299          * custom pattern, and we actually need to implement custom pattern
12300          * matching.
12301          */
12302         if (pattern & CTL_LUN_PAT_CMD)
12303                 return (CTL_LUN_PAT_CMD);
12304
12305         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12306                 return (CTL_LUN_PAT_ANY);
12307
12308         entry = ctl_get_cmd_entry(ctsio);
12309
12310         filtered_pattern = entry->pattern & pattern;
12311
12312         /*
12313          * If the user requested specific flags in the pattern (e.g.
12314          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12315          * flags.
12316          *
12317          * If the user did not specify any flags, it doesn't matter whether
12318          * or not the command supports the flags.
12319          */
12320         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12321              (pattern & ~CTL_LUN_PAT_MASK))
12322                 return (CTL_LUN_PAT_NONE);
12323
12324         /*
12325          * If the user asked for a range check, see if the requested LBA
12326          * range overlaps with this command's LBA range.
12327          */
12328         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12329                 uint64_t lba1;
12330                 uint32_t len1;
12331                 ctl_action action;
12332                 int retval;
12333
12334                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12335                 if (retval != 0)
12336                         return (CTL_LUN_PAT_NONE);
12337
12338                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12339                                               desc->lba_range.len);
12340                 /*
12341                  * A "pass" means that the LBA ranges don't overlap, so
12342                  * this doesn't match the user's range criteria.
12343                  */
12344                 if (action == CTL_ACTION_PASS)
12345                         return (CTL_LUN_PAT_NONE);
12346         }
12347
12348         return (filtered_pattern);
12349 }
12350
12351 static void
12352 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12353 {
12354         struct ctl_error_desc *desc, *desc2;
12355
12356         mtx_assert(&lun->lun_lock, MA_OWNED);
12357
12358         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12359                 ctl_lun_error_pattern pattern;
12360                 /*
12361                  * Check to see whether this particular command matches
12362                  * the pattern in the descriptor.
12363                  */
12364                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12365                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12366                         continue;
12367
12368                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12369                 case CTL_LUN_INJ_ABORTED:
12370                         ctl_set_aborted(&io->scsiio);
12371                         break;
12372                 case CTL_LUN_INJ_MEDIUM_ERR:
12373                         ctl_set_medium_error(&io->scsiio);
12374                         break;
12375                 case CTL_LUN_INJ_UA:
12376                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12377                          * OCCURRED */
12378                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12379                         break;
12380                 case CTL_LUN_INJ_CUSTOM:
12381                         /*
12382                          * We're assuming the user knows what he is doing.
12383                          * Just copy the sense information without doing
12384                          * checks.
12385                          */
12386                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12387                               ctl_min(sizeof(desc->custom_sense),
12388                                       sizeof(io->scsiio.sense_data)));
12389                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12390                         io->scsiio.sense_len = SSD_FULL_SIZE;
12391                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12392                         break;
12393                 case CTL_LUN_INJ_NONE:
12394                 default:
12395                         /*
12396                          * If this is an error injection type we don't know
12397                          * about, clear the continuous flag (if it is set)
12398                          * so it will get deleted below.
12399                          */
12400                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12401                         break;
12402                 }
12403                 /*
12404                  * By default, each error injection action is a one-shot
12405                  */
12406                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12407                         continue;
12408
12409                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12410
12411                 free(desc, M_CTL);
12412         }
12413 }
12414
12415 #ifdef CTL_IO_DELAY
12416 static void
12417 ctl_datamove_timer_wakeup(void *arg)
12418 {
12419         union ctl_io *io;
12420
12421         io = (union ctl_io *)arg;
12422
12423         ctl_datamove(io);
12424 }
12425 #endif /* CTL_IO_DELAY */
12426
12427 void
12428 ctl_datamove(union ctl_io *io)
12429 {
12430         void (*fe_datamove)(union ctl_io *io);
12431
12432         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12433
12434         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12435
12436 #ifdef CTL_TIME_IO
12437         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12438                 char str[256];
12439                 char path_str[64];
12440                 struct sbuf sb;
12441
12442                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12443                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12444
12445                 sbuf_cat(&sb, path_str);
12446                 switch (io->io_hdr.io_type) {
12447                 case CTL_IO_SCSI:
12448                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12449                         sbuf_printf(&sb, "\n");
12450                         sbuf_cat(&sb, path_str);
12451                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12452                                     io->scsiio.tag_num, io->scsiio.tag_type);
12453                         break;
12454                 case CTL_IO_TASK:
12455                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12456                                     "Tag Type: %d\n", io->taskio.task_action,
12457                                     io->taskio.tag_num, io->taskio.tag_type);
12458                         break;
12459                 default:
12460                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12461                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12462                         break;
12463                 }
12464                 sbuf_cat(&sb, path_str);
12465                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12466                             (intmax_t)time_uptime - io->io_hdr.start_time);
12467                 sbuf_finish(&sb);
12468                 printf("%s", sbuf_data(&sb));
12469         }
12470 #endif /* CTL_TIME_IO */
12471
12472 #ifdef CTL_IO_DELAY
12473         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12474                 struct ctl_lun *lun;
12475
12476                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12477
12478                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12479         } else {
12480                 struct ctl_lun *lun;
12481
12482                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12483                 if ((lun != NULL)
12484                  && (lun->delay_info.datamove_delay > 0)) {
12485                         struct callout *callout;
12486
12487                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12488                         callout_init(callout, /*mpsafe*/ 1);
12489                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12490                         callout_reset(callout,
12491                                       lun->delay_info.datamove_delay * hz,
12492                                       ctl_datamove_timer_wakeup, io);
12493                         if (lun->delay_info.datamove_type ==
12494                             CTL_DELAY_TYPE_ONESHOT)
12495                                 lun->delay_info.datamove_delay = 0;
12496                         return;
12497                 }
12498         }
12499 #endif
12500
12501         /*
12502          * This command has been aborted.  Set the port status, so we fail
12503          * the data move.
12504          */
12505         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12506                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12507                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12508                        io->io_hdr.nexus.targ_port,
12509                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12510                        io->io_hdr.nexus.targ_lun);
12511                 io->io_hdr.port_status = 31337;
12512                 /*
12513                  * Note that the backend, in this case, will get the
12514                  * callback in its context.  In other cases it may get
12515                  * called in the frontend's interrupt thread context.
12516                  */
12517                 io->scsiio.be_move_done(io);
12518                 return;
12519         }
12520
12521         /*
12522          * If we're in XFER mode and this I/O is from the other shelf
12523          * controller, we need to send the DMA to the other side to
12524          * actually transfer the data to/from the host.  In serialize only
12525          * mode the transfer happens below CTL and ctl_datamove() is only
12526          * called on the machine that originally received the I/O.
12527          */
12528         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12529          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12530                 union ctl_ha_msg msg;
12531                 uint32_t sg_entries_sent;
12532                 int do_sg_copy;
12533                 int i;
12534
12535                 memset(&msg, 0, sizeof(msg));
12536                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12537                 msg.hdr.original_sc = io->io_hdr.original_sc;
12538                 msg.hdr.serializing_sc = io;
12539                 msg.hdr.nexus = io->io_hdr.nexus;
12540                 msg.dt.flags = io->io_hdr.flags;
12541                 /*
12542                  * We convert everything into a S/G list here.  We can't
12543                  * pass by reference, only by value between controllers.
12544                  * So we can't pass a pointer to the S/G list, only as many
12545                  * S/G entries as we can fit in here.  If it's possible for
12546                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12547                  * then we need to break this up into multiple transfers.
12548                  */
12549                 if (io->scsiio.kern_sg_entries == 0) {
12550                         msg.dt.kern_sg_entries = 1;
12551                         /*
12552                          * If this is in cached memory, flush the cache
12553                          * before we send the DMA request to the other
12554                          * controller.  We want to do this in either the
12555                          * read or the write case.  The read case is
12556                          * straightforward.  In the write case, we want to
12557                          * make sure nothing is in the local cache that
12558                          * could overwrite the DMAed data.
12559                          */
12560                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12561                                 /*
12562                                  * XXX KDM use bus_dmamap_sync() here.
12563                                  */
12564                         }
12565
12566                         /*
12567                          * Convert to a physical address if this is a
12568                          * virtual address.
12569                          */
12570                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12571                                 msg.dt.sg_list[0].addr =
12572                                         io->scsiio.kern_data_ptr;
12573                         } else {
12574                                 /*
12575                                  * XXX KDM use busdma here!
12576                                  */
12577 #if 0
12578                                 msg.dt.sg_list[0].addr = (void *)
12579                                         vtophys(io->scsiio.kern_data_ptr);
12580 #endif
12581                         }
12582
12583                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12584                         do_sg_copy = 0;
12585                 } else {
12586                         struct ctl_sg_entry *sgl;
12587
12588                         do_sg_copy = 1;
12589                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12590                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12591                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12592                                 /*
12593                                  * XXX KDM use bus_dmamap_sync() here.
12594                                  */
12595                         }
12596                 }
12597
12598                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12599                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12600                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12601                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12602                 msg.dt.sg_sequence = 0;
12603
12604                 /*
12605                  * Loop until we've sent all of the S/G entries.  On the
12606                  * other end, we'll recompose these S/G entries into one
12607                  * contiguous list before passing it to the
12608                  */
12609                 for (sg_entries_sent = 0; sg_entries_sent <
12610                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12611                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12612                                 sizeof(msg.dt.sg_list[0])),
12613                                 msg.dt.kern_sg_entries - sg_entries_sent);
12614
12615                         if (do_sg_copy != 0) {
12616                                 struct ctl_sg_entry *sgl;
12617                                 int j;
12618
12619                                 sgl = (struct ctl_sg_entry *)
12620                                         io->scsiio.kern_data_ptr;
12621                                 /*
12622                                  * If this is in cached memory, flush the cache
12623                                  * before we send the DMA request to the other
12624                                  * controller.  We want to do this in either
12625                                  * the * read or the write case.  The read
12626                                  * case is straightforward.  In the write
12627                                  * case, we want to make sure nothing is
12628                                  * in the local cache that could overwrite
12629                                  * the DMAed data.
12630                                  */
12631
12632                                 for (i = sg_entries_sent, j = 0;
12633                                      i < msg.dt.cur_sg_entries; i++, j++) {
12634                                         if ((io->io_hdr.flags &
12635                                              CTL_FLAG_NO_DATASYNC) == 0) {
12636                                                 /*
12637                                                  * XXX KDM use bus_dmamap_sync()
12638                                                  */
12639                                         }
12640                                         if ((io->io_hdr.flags &
12641                                              CTL_FLAG_BUS_ADDR) == 0) {
12642                                                 /*
12643                                                  * XXX KDM use busdma.
12644                                                  */
12645 #if 0
12646                                                 msg.dt.sg_list[j].addr =(void *)
12647                                                        vtophys(sgl[i].addr);
12648 #endif
12649                                         } else {
12650                                                 msg.dt.sg_list[j].addr =
12651                                                         sgl[i].addr;
12652                                         }
12653                                         msg.dt.sg_list[j].len = sgl[i].len;
12654                                 }
12655                         }
12656
12657                         sg_entries_sent += msg.dt.cur_sg_entries;
12658                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12659                                 msg.dt.sg_last = 1;
12660                         else
12661                                 msg.dt.sg_last = 0;
12662
12663                         /*
12664                          * XXX KDM drop and reacquire the lock here?
12665                          */
12666                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12667                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12668                                 /*
12669                                  * XXX do something here.
12670                                  */
12671                         }
12672
12673                         msg.dt.sent_sg_entries = sg_entries_sent;
12674                 }
12675                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12676                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12677                         ctl_failover_io(io, /*have_lock*/ 0);
12678
12679         } else {
12680
12681                 /*
12682                  * Lookup the fe_datamove() function for this particular
12683                  * front end.
12684                  */
12685                 fe_datamove =
12686                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12687
12688                 fe_datamove(io);
12689         }
12690 }
12691
12692 static void
12693 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12694 {
12695         union ctl_ha_msg msg;
12696         int isc_status;
12697
12698         memset(&msg, 0, sizeof(msg));
12699
12700         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12701         msg.hdr.original_sc = io;
12702         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12703         msg.hdr.nexus = io->io_hdr.nexus;
12704         msg.hdr.status = io->io_hdr.status;
12705         msg.scsi.tag_num = io->scsiio.tag_num;
12706         msg.scsi.tag_type = io->scsiio.tag_type;
12707         msg.scsi.scsi_status = io->scsiio.scsi_status;
12708         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12709                sizeof(io->scsiio.sense_data));
12710         msg.scsi.sense_len = io->scsiio.sense_len;
12711         msg.scsi.sense_residual = io->scsiio.sense_residual;
12712         msg.scsi.fetd_status = io->io_hdr.port_status;
12713         msg.scsi.residual = io->scsiio.residual;
12714         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12715
12716         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12717                 ctl_failover_io(io, /*have_lock*/ have_lock);
12718                 return;
12719         }
12720
12721         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12722         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12723                 /* XXX do something if this fails */
12724         }
12725
12726 }
12727
12728 /*
12729  * The DMA to the remote side is done, now we need to tell the other side
12730  * we're done so it can continue with its data movement.
12731  */
12732 static void
12733 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12734 {
12735         union ctl_io *io;
12736
12737         io = rq->context;
12738
12739         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12740                 printf("%s: ISC DMA write failed with error %d", __func__,
12741                        rq->ret);
12742                 ctl_set_internal_failure(&io->scsiio,
12743                                          /*sks_valid*/ 1,
12744                                          /*retry_count*/ rq->ret);
12745         }
12746
12747         ctl_dt_req_free(rq);
12748
12749         /*
12750          * In this case, we had to malloc the memory locally.  Free it.
12751          */
12752         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12753                 int i;
12754                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12755                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12756         }
12757         /*
12758          * The data is in local and remote memory, so now we need to send
12759          * status (good or back) back to the other side.
12760          */
12761         ctl_send_datamove_done(io, /*have_lock*/ 0);
12762 }
12763
12764 /*
12765  * We've moved the data from the host/controller into local memory.  Now we
12766  * need to push it over to the remote controller's memory.
12767  */
12768 static int
12769 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12770 {
12771         int retval;
12772
12773         retval = 0;
12774
12775         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12776                                           ctl_datamove_remote_write_cb);
12777
12778         return (retval);
12779 }
12780
12781 static void
12782 ctl_datamove_remote_write(union ctl_io *io)
12783 {
12784         int retval;
12785         void (*fe_datamove)(union ctl_io *io);
12786
12787         /*
12788          * - Get the data from the host/HBA into local memory.
12789          * - DMA memory from the local controller to the remote controller.
12790          * - Send status back to the remote controller.
12791          */
12792
12793         retval = ctl_datamove_remote_sgl_setup(io);
12794         if (retval != 0)
12795                 return;
12796
12797         /* Switch the pointer over so the FETD knows what to do */
12798         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12799
12800         /*
12801          * Use a custom move done callback, since we need to send completion
12802          * back to the other controller, not to the backend on this side.
12803          */
12804         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12805
12806         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12807
12808         fe_datamove(io);
12809
12810         return;
12811
12812 }
12813
12814 static int
12815 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12816 {
12817 #if 0
12818         char str[256];
12819         char path_str[64];
12820         struct sbuf sb;
12821 #endif
12822
12823         /*
12824          * In this case, we had to malloc the memory locally.  Free it.
12825          */
12826         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12827                 int i;
12828                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12829                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12830         }
12831
12832 #if 0
12833         scsi_path_string(io, path_str, sizeof(path_str));
12834         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12835         sbuf_cat(&sb, path_str);
12836         scsi_command_string(&io->scsiio, NULL, &sb);
12837         sbuf_printf(&sb, "\n");
12838         sbuf_cat(&sb, path_str);
12839         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12840                     io->scsiio.tag_num, io->scsiio.tag_type);
12841         sbuf_cat(&sb, path_str);
12842         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12843                     io->io_hdr.flags, io->io_hdr.status);
12844         sbuf_finish(&sb);
12845         printk("%s", sbuf_data(&sb));
12846 #endif
12847
12848
12849         /*
12850          * The read is done, now we need to send status (good or bad) back
12851          * to the other side.
12852          */
12853         ctl_send_datamove_done(io, /*have_lock*/ 0);
12854
12855         return (0);
12856 }
12857
12858 static void
12859 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12860 {
12861         union ctl_io *io;
12862         void (*fe_datamove)(union ctl_io *io);
12863
12864         io = rq->context;
12865
12866         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12867                 printf("%s: ISC DMA read failed with error %d", __func__,
12868                        rq->ret);
12869                 ctl_set_internal_failure(&io->scsiio,
12870                                          /*sks_valid*/ 1,
12871                                          /*retry_count*/ rq->ret);
12872         }
12873
12874         ctl_dt_req_free(rq);
12875
12876         /* Switch the pointer over so the FETD knows what to do */
12877         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12878
12879         /*
12880          * Use a custom move done callback, since we need to send completion
12881          * back to the other controller, not to the backend on this side.
12882          */
12883         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12884
12885         /* XXX KDM add checks like the ones in ctl_datamove? */
12886
12887         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12888
12889         fe_datamove(io);
12890 }
12891
12892 static int
12893 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12894 {
12895         struct ctl_sg_entry *local_sglist, *remote_sglist;
12896         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12897         struct ctl_softc *softc;
12898         int retval;
12899         int i;
12900
12901         retval = 0;
12902         softc = control_softc;
12903
12904         local_sglist = io->io_hdr.local_sglist;
12905         local_dma_sglist = io->io_hdr.local_dma_sglist;
12906         remote_sglist = io->io_hdr.remote_sglist;
12907         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12908
12909         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12910                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12911                         local_sglist[i].len = remote_sglist[i].len;
12912
12913                         /*
12914                          * XXX Detect the situation where the RS-level I/O
12915                          * redirector on the other side has already read the
12916                          * data off of the AOR RS on this side, and
12917                          * transferred it to remote (mirror) memory on the
12918                          * other side.  Since we already have the data in
12919                          * memory here, we just need to use it.
12920                          *
12921                          * XXX KDM this can probably be removed once we
12922                          * get the cache device code in and take the
12923                          * current AOR implementation out.
12924                          */
12925 #ifdef NEEDTOPORT
12926                         if ((remote_sglist[i].addr >=
12927                              (void *)vtophys(softc->mirr->addr))
12928                          && (remote_sglist[i].addr <
12929                              ((void *)vtophys(softc->mirr->addr) +
12930                              CacheMirrorOffset))) {
12931                                 local_sglist[i].addr = remote_sglist[i].addr -
12932                                         CacheMirrorOffset;
12933                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12934                                      CTL_FLAG_DATA_IN)
12935                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12936                         } else {
12937                                 local_sglist[i].addr = remote_sglist[i].addr +
12938                                         CacheMirrorOffset;
12939                         }
12940 #endif
12941 #if 0
12942                         printf("%s: local %p, remote %p, len %d\n",
12943                                __func__, local_sglist[i].addr,
12944                                remote_sglist[i].addr, local_sglist[i].len);
12945 #endif
12946                 }
12947         } else {
12948                 uint32_t len_to_go;
12949
12950                 /*
12951                  * In this case, we don't have automatically allocated
12952                  * memory for this I/O on this controller.  This typically
12953                  * happens with internal CTL I/O -- e.g. inquiry, mode
12954                  * sense, etc.  Anything coming from RAIDCore will have
12955                  * a mirror area available.
12956                  */
12957                 len_to_go = io->scsiio.kern_data_len;
12958
12959                 /*
12960                  * Clear the no datasync flag, we have to use malloced
12961                  * buffers.
12962                  */
12963                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12964
12965                 /*
12966                  * The difficult thing here is that the size of the various
12967                  * S/G segments may be different than the size from the
12968                  * remote controller.  That'll make it harder when DMAing
12969                  * the data back to the other side.
12970                  */
12971                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12972                      sizeof(io->io_hdr.remote_sglist[0])) &&
12973                      (len_to_go > 0); i++) {
12974                         local_sglist[i].len = ctl_min(len_to_go, 131072);
12975                         CTL_SIZE_8B(local_dma_sglist[i].len,
12976                                     local_sglist[i].len);
12977                         local_sglist[i].addr =
12978                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12979
12980                         local_dma_sglist[i].addr = local_sglist[i].addr;
12981
12982                         if (local_sglist[i].addr == NULL) {
12983                                 int j;
12984
12985                                 printf("malloc failed for %zd bytes!",
12986                                        local_dma_sglist[i].len);
12987                                 for (j = 0; j < i; j++) {
12988                                         free(local_sglist[j].addr, M_CTL);
12989                                 }
12990                                 ctl_set_internal_failure(&io->scsiio,
12991                                                          /*sks_valid*/ 1,
12992                                                          /*retry_count*/ 4857);
12993                                 retval = 1;
12994                                 goto bailout_error;
12995                                 
12996                         }
12997                         /* XXX KDM do we need a sync here? */
12998
12999                         len_to_go -= local_sglist[i].len;
13000                 }
13001                 /*
13002                  * Reset the number of S/G entries accordingly.  The
13003                  * original number of S/G entries is available in
13004                  * rem_sg_entries.
13005                  */
13006                 io->scsiio.kern_sg_entries = i;
13007
13008 #if 0
13009                 printf("%s: kern_sg_entries = %d\n", __func__,
13010                        io->scsiio.kern_sg_entries);
13011                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13012                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13013                                local_sglist[i].addr, local_sglist[i].len,
13014                                local_dma_sglist[i].len);
13015 #endif
13016         }
13017
13018
13019         return (retval);
13020
13021 bailout_error:
13022
13023         ctl_send_datamove_done(io, /*have_lock*/ 0);
13024
13025         return (retval);
13026 }
13027
13028 static int
13029 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13030                          ctl_ha_dt_cb callback)
13031 {
13032         struct ctl_ha_dt_req *rq;
13033         struct ctl_sg_entry *remote_sglist, *local_sglist;
13034         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13035         uint32_t local_used, remote_used, total_used;
13036         int retval;
13037         int i, j;
13038
13039         retval = 0;
13040
13041         rq = ctl_dt_req_alloc();
13042
13043         /*
13044          * If we failed to allocate the request, and if the DMA didn't fail
13045          * anyway, set busy status.  This is just a resource allocation
13046          * failure.
13047          */
13048         if ((rq == NULL)
13049          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13050                 ctl_set_busy(&io->scsiio);
13051
13052         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13053
13054                 if (rq != NULL)
13055                         ctl_dt_req_free(rq);
13056
13057                 /*
13058                  * The data move failed.  We need to return status back
13059                  * to the other controller.  No point in trying to DMA
13060                  * data to the remote controller.
13061                  */
13062
13063                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13064
13065                 retval = 1;
13066
13067                 goto bailout;
13068         }
13069
13070         local_sglist = io->io_hdr.local_sglist;
13071         local_dma_sglist = io->io_hdr.local_dma_sglist;
13072         remote_sglist = io->io_hdr.remote_sglist;
13073         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13074         local_used = 0;
13075         remote_used = 0;
13076         total_used = 0;
13077
13078         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13079                 rq->ret = CTL_HA_STATUS_SUCCESS;
13080                 rq->context = io;
13081                 callback(rq);
13082                 goto bailout;
13083         }
13084
13085         /*
13086          * Pull/push the data over the wire from/to the other controller.
13087          * This takes into account the possibility that the local and
13088          * remote sglists may not be identical in terms of the size of
13089          * the elements and the number of elements.
13090          *
13091          * One fundamental assumption here is that the length allocated for
13092          * both the local and remote sglists is identical.  Otherwise, we've
13093          * essentially got a coding error of some sort.
13094          */
13095         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13096                 int isc_ret;
13097                 uint32_t cur_len, dma_length;
13098                 uint8_t *tmp_ptr;
13099
13100                 rq->id = CTL_HA_DATA_CTL;
13101                 rq->command = command;
13102                 rq->context = io;
13103
13104                 /*
13105                  * Both pointers should be aligned.  But it is possible
13106                  * that the allocation length is not.  They should both
13107                  * also have enough slack left over at the end, though,
13108                  * to round up to the next 8 byte boundary.
13109                  */
13110                 cur_len = ctl_min(local_sglist[i].len - local_used,
13111                                   remote_sglist[j].len - remote_used);
13112
13113                 /*
13114                  * In this case, we have a size issue and need to decrease
13115                  * the size, except in the case where we actually have less
13116                  * than 8 bytes left.  In that case, we need to increase
13117                  * the DMA length to get the last bit.
13118                  */
13119                 if ((cur_len & 0x7) != 0) {
13120                         if (cur_len > 0x7) {
13121                                 cur_len = cur_len - (cur_len & 0x7);
13122                                 dma_length = cur_len;
13123                         } else {
13124                                 CTL_SIZE_8B(dma_length, cur_len);
13125                         }
13126
13127                 } else
13128                         dma_length = cur_len;
13129
13130                 /*
13131                  * If we had to allocate memory for this I/O, instead of using
13132                  * the non-cached mirror memory, we'll need to flush the cache
13133                  * before trying to DMA to the other controller.
13134                  *
13135                  * We could end up doing this multiple times for the same
13136                  * segment if we have a larger local segment than remote
13137                  * segment.  That shouldn't be an issue.
13138                  */
13139                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13140                         /*
13141                          * XXX KDM use bus_dmamap_sync() here.
13142                          */
13143                 }
13144
13145                 rq->size = dma_length;
13146
13147                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13148                 tmp_ptr += local_used;
13149
13150                 /* Use physical addresses when talking to ISC hardware */
13151                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13152                         /* XXX KDM use busdma */
13153 #if 0
13154                         rq->local = vtophys(tmp_ptr);
13155 #endif
13156                 } else
13157                         rq->local = tmp_ptr;
13158
13159                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13160                 tmp_ptr += remote_used;
13161                 rq->remote = tmp_ptr;
13162
13163                 rq->callback = NULL;
13164
13165                 local_used += cur_len;
13166                 if (local_used >= local_sglist[i].len) {
13167                         i++;
13168                         local_used = 0;
13169                 }
13170
13171                 remote_used += cur_len;
13172                 if (remote_used >= remote_sglist[j].len) {
13173                         j++;
13174                         remote_used = 0;
13175                 }
13176                 total_used += cur_len;
13177
13178                 if (total_used >= io->scsiio.kern_data_len)
13179                         rq->callback = callback;
13180
13181                 if ((rq->size & 0x7) != 0) {
13182                         printf("%s: warning: size %d is not on 8b boundary\n",
13183                                __func__, rq->size);
13184                 }
13185                 if (((uintptr_t)rq->local & 0x7) != 0) {
13186                         printf("%s: warning: local %p not on 8b boundary\n",
13187                                __func__, rq->local);
13188                 }
13189                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13190                         printf("%s: warning: remote %p not on 8b boundary\n",
13191                                __func__, rq->local);
13192                 }
13193 #if 0
13194                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13195                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13196                        rq->local, rq->remote, rq->size);
13197 #endif
13198
13199                 isc_ret = ctl_dt_single(rq);
13200                 if (isc_ret == CTL_HA_STATUS_WAIT)
13201                         continue;
13202
13203                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13204                         rq->ret = CTL_HA_STATUS_SUCCESS;
13205                 } else {
13206                         rq->ret = isc_ret;
13207                 }
13208                 callback(rq);
13209                 goto bailout;
13210         }
13211
13212 bailout:
13213         return (retval);
13214
13215 }
13216
13217 static void
13218 ctl_datamove_remote_read(union ctl_io *io)
13219 {
13220         int retval;
13221         int i;
13222
13223         /*
13224          * This will send an error to the other controller in the case of a
13225          * failure.
13226          */
13227         retval = ctl_datamove_remote_sgl_setup(io);
13228         if (retval != 0)
13229                 return;
13230
13231         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13232                                           ctl_datamove_remote_read_cb);
13233         if ((retval != 0)
13234          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13235                 /*
13236                  * Make sure we free memory if there was an error..  The
13237                  * ctl_datamove_remote_xfer() function will send the
13238                  * datamove done message, or call the callback with an
13239                  * error if there is a problem.
13240                  */
13241                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13242                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13243         }
13244
13245         return;
13246 }
13247
13248 /*
13249  * Process a datamove request from the other controller.  This is used for
13250  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13251  * first.  Once that is complete, the data gets DMAed into the remote
13252  * controller's memory.  For reads, we DMA from the remote controller's
13253  * memory into our memory first, and then move it out to the FETD.
13254  */
13255 static void
13256 ctl_datamove_remote(union ctl_io *io)
13257 {
13258         struct ctl_softc *softc;
13259
13260         softc = control_softc;
13261
13262         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13263
13264         /*
13265          * Note that we look for an aborted I/O here, but don't do some of
13266          * the other checks that ctl_datamove() normally does.
13267          * We don't need to run the datamove delay code, since that should
13268          * have been done if need be on the other controller.
13269          */
13270         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13271                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13272                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13273                        io->io_hdr.nexus.targ_port,
13274                        io->io_hdr.nexus.targ_target.id,
13275                        io->io_hdr.nexus.targ_lun);
13276                 io->io_hdr.port_status = 31338;
13277                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13278                 return;
13279         }
13280
13281         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13282                 ctl_datamove_remote_write(io);
13283         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13284                 ctl_datamove_remote_read(io);
13285         } else {
13286                 union ctl_ha_msg msg;
13287                 struct scsi_sense_data *sense;
13288                 uint8_t sks[3];
13289                 int retry_count;
13290
13291                 memset(&msg, 0, sizeof(msg));
13292
13293                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13294                 msg.hdr.status = CTL_SCSI_ERROR;
13295                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13296
13297                 retry_count = 4243;
13298
13299                 sense = &msg.scsi.sense_data;
13300                 sks[0] = SSD_SCS_VALID;
13301                 sks[1] = (retry_count >> 8) & 0xff;
13302                 sks[2] = retry_count & 0xff;
13303
13304                 /* "Internal target failure" */
13305                 scsi_set_sense_data(sense,
13306                                     /*sense_format*/ SSD_TYPE_NONE,
13307                                     /*current_error*/ 1,
13308                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13309                                     /*asc*/ 0x44,
13310                                     /*ascq*/ 0x00,
13311                                     /*type*/ SSD_ELEM_SKS,
13312                                     /*size*/ sizeof(sks),
13313                                     /*data*/ sks,
13314                                     SSD_ELEM_NONE);
13315
13316                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13317                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13318                         ctl_failover_io(io, /*have_lock*/ 1);
13319                         return;
13320                 }
13321
13322                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13323                     CTL_HA_STATUS_SUCCESS) {
13324                         /* XXX KDM what to do if this fails? */
13325                 }
13326                 return;
13327         }
13328         
13329 }
13330
13331 static int
13332 ctl_process_done(union ctl_io *io)
13333 {
13334         struct ctl_lun *lun;
13335         struct ctl_softc *ctl_softc;
13336         void (*fe_done)(union ctl_io *io);
13337         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13338
13339         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13340
13341         fe_done =
13342             control_softc->ctl_ports[targ_port]->fe_done;
13343
13344 #ifdef CTL_TIME_IO
13345         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13346                 char str[256];
13347                 char path_str[64];
13348                 struct sbuf sb;
13349
13350                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13351                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13352
13353                 sbuf_cat(&sb, path_str);
13354                 switch (io->io_hdr.io_type) {
13355                 case CTL_IO_SCSI:
13356                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13357                         sbuf_printf(&sb, "\n");
13358                         sbuf_cat(&sb, path_str);
13359                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13360                                     io->scsiio.tag_num, io->scsiio.tag_type);
13361                         break;
13362                 case CTL_IO_TASK:
13363                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13364                                     "Tag Type: %d\n", io->taskio.task_action,
13365                                     io->taskio.tag_num, io->taskio.tag_type);
13366                         break;
13367                 default:
13368                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13369                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13370                         break;
13371                 }
13372                 sbuf_cat(&sb, path_str);
13373                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13374                             (intmax_t)time_uptime - io->io_hdr.start_time);
13375                 sbuf_finish(&sb);
13376                 printf("%s", sbuf_data(&sb));
13377         }
13378 #endif /* CTL_TIME_IO */
13379
13380         switch (io->io_hdr.io_type) {
13381         case CTL_IO_SCSI:
13382                 break;
13383         case CTL_IO_TASK:
13384                 if (bootverbose || verbose > 0)
13385                         ctl_io_error_print(io, NULL);
13386                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13387                         ctl_free_io(io);
13388                 else
13389                         fe_done(io);
13390                 return (CTL_RETVAL_COMPLETE);
13391                 break;
13392         default:
13393                 printf("ctl_process_done: invalid io type %d\n",
13394                        io->io_hdr.io_type);
13395                 panic("ctl_process_done: invalid io type %d\n",
13396                       io->io_hdr.io_type);
13397                 break; /* NOTREACHED */
13398         }
13399
13400         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13401         if (lun == NULL) {
13402                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13403                                  io->io_hdr.nexus.targ_mapped_lun));
13404                 fe_done(io);
13405                 goto bailout;
13406         }
13407         ctl_softc = lun->ctl_softc;
13408
13409         mtx_lock(&lun->lun_lock);
13410
13411         /*
13412          * Check to see if we have any errors to inject here.  We only
13413          * inject errors for commands that don't already have errors set.
13414          */
13415         if ((STAILQ_FIRST(&lun->error_list) != NULL)
13416          && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13417                 ctl_inject_error(lun, io);
13418
13419         /*
13420          * XXX KDM how do we treat commands that aren't completed
13421          * successfully?
13422          *
13423          * XXX KDM should we also track I/O latency?
13424          */
13425         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13426             io->io_hdr.io_type == CTL_IO_SCSI) {
13427 #ifdef CTL_TIME_IO
13428                 struct bintime cur_bt;
13429 #endif
13430                 int type;
13431
13432                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13433                     CTL_FLAG_DATA_IN)
13434                         type = CTL_STATS_READ;
13435                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13436                     CTL_FLAG_DATA_OUT)
13437                         type = CTL_STATS_WRITE;
13438                 else
13439                         type = CTL_STATS_NO_IO;
13440
13441                 lun->stats.ports[targ_port].bytes[type] +=
13442                     io->scsiio.kern_total_len;
13443                 lun->stats.ports[targ_port].operations[type]++;
13444 #ifdef CTL_TIME_IO
13445                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13446                    &io->io_hdr.dma_bt);
13447                 lun->stats.ports[targ_port].num_dmas[type] +=
13448                     io->io_hdr.num_dmas;
13449                 getbintime(&cur_bt);
13450                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13451                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13452 #endif
13453         }
13454
13455         /*
13456          * Remove this from the OOA queue.
13457          */
13458         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13459
13460         /*
13461          * Run through the blocked queue on this LUN and see if anything
13462          * has become unblocked, now that this transaction is done.
13463          */
13464         ctl_check_blocked(lun);
13465
13466         /*
13467          * If the LUN has been invalidated, free it if there is nothing
13468          * left on its OOA queue.
13469          */
13470         if ((lun->flags & CTL_LUN_INVALID)
13471          && TAILQ_EMPTY(&lun->ooa_queue)) {
13472                 mtx_unlock(&lun->lun_lock);
13473                 mtx_lock(&ctl_softc->ctl_lock);
13474                 ctl_free_lun(lun);
13475                 mtx_unlock(&ctl_softc->ctl_lock);
13476         } else
13477                 mtx_unlock(&lun->lun_lock);
13478
13479         /*
13480          * If this command has been aborted, make sure we set the status
13481          * properly.  The FETD is responsible for freeing the I/O and doing
13482          * whatever it needs to do to clean up its state.
13483          */
13484         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13485                 ctl_set_task_aborted(&io->scsiio);
13486
13487         /*
13488          * We print out status for every task management command.  For SCSI
13489          * commands, we filter out any unit attention errors; they happen
13490          * on every boot, and would clutter up the log.  Note:  task
13491          * management commands aren't printed here, they are printed above,
13492          * since they should never even make it down here.
13493          */
13494         switch (io->io_hdr.io_type) {
13495         case CTL_IO_SCSI: {
13496                 int error_code, sense_key, asc, ascq;
13497
13498                 sense_key = 0;
13499
13500                 if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13501                  && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13502                         /*
13503                          * Since this is just for printing, no need to
13504                          * show errors here.
13505                          */
13506                         scsi_extract_sense_len(&io->scsiio.sense_data,
13507                                                io->scsiio.sense_len,
13508                                                &error_code,
13509                                                &sense_key,
13510                                                &asc,
13511                                                &ascq,
13512                                                /*show_errors*/ 0);
13513                 }
13514
13515                 if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13516                  && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13517                   || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13518                   || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13519
13520                         if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13521                                 ctl_softc->skipped_prints++;
13522                         } else {
13523                                 uint32_t skipped_prints;
13524
13525                                 skipped_prints = ctl_softc->skipped_prints;
13526
13527                                 ctl_softc->skipped_prints = 0;
13528                                 ctl_softc->last_print_jiffies = time_uptime;
13529
13530                                 if (skipped_prints > 0) {
13531 #ifdef NEEDTOPORT
13532                                         csevent_log(CSC_CTL | CSC_SHELF_SW |
13533                                             CTL_ERROR_REPORT,
13534                                             csevent_LogType_Trace,
13535                                             csevent_Severity_Information,
13536                                             csevent_AlertLevel_Green,
13537                                             csevent_FRU_Firmware,
13538                                             csevent_FRU_Unknown,
13539                                             "High CTL error volume, %d prints "
13540                                             "skipped", skipped_prints);
13541 #endif
13542                                 }
13543                                 if (bootverbose || verbose > 0)
13544                                         ctl_io_error_print(io, NULL);
13545                         }
13546                 }
13547                 break;
13548         }
13549         case CTL_IO_TASK:
13550                 if (bootverbose || verbose > 0)
13551                         ctl_io_error_print(io, NULL);
13552                 break;
13553         default:
13554                 break;
13555         }
13556
13557         /*
13558          * Tell the FETD or the other shelf controller we're done with this
13559          * command.  Note that only SCSI commands get to this point.  Task
13560          * management commands are completed above.
13561          *
13562          * We only send status to the other controller if we're in XFER
13563          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13564          * received the I/O (from CTL's perspective), and so the status is
13565          * generated there.
13566          * 
13567          * XXX KDM if we hold the lock here, we could cause a deadlock
13568          * if the frontend comes back in in this context to queue
13569          * something.
13570          */
13571         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13572          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13573                 union ctl_ha_msg msg;
13574
13575                 memset(&msg, 0, sizeof(msg));
13576                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13577                 msg.hdr.original_sc = io->io_hdr.original_sc;
13578                 msg.hdr.nexus = io->io_hdr.nexus;
13579                 msg.hdr.status = io->io_hdr.status;
13580                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13581                 msg.scsi.tag_num = io->scsiio.tag_num;
13582                 msg.scsi.tag_type = io->scsiio.tag_type;
13583                 msg.scsi.sense_len = io->scsiio.sense_len;
13584                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13585                 msg.scsi.residual = io->scsiio.residual;
13586                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13587                        sizeof(io->scsiio.sense_data));
13588                 /*
13589                  * We copy this whether or not this is an I/O-related
13590                  * command.  Otherwise, we'd have to go and check to see
13591                  * whether it's a read/write command, and it really isn't
13592                  * worth it.
13593                  */
13594                 memcpy(&msg.scsi.lbalen,
13595                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13596                        sizeof(msg.scsi.lbalen));
13597
13598                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13599                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13600                         /* XXX do something here */
13601                 }
13602
13603                 ctl_free_io(io);
13604         } else 
13605                 fe_done(io);
13606
13607 bailout:
13608
13609         return (CTL_RETVAL_COMPLETE);
13610 }
13611
13612 /*
13613  * Front end should call this if it doesn't do autosense.  When the request
13614  * sense comes back in from the initiator, we'll dequeue this and send it.
13615  */
13616 int
13617 ctl_queue_sense(union ctl_io *io)
13618 {
13619         struct ctl_lun *lun;
13620         struct ctl_softc *ctl_softc;
13621         uint32_t initidx, targ_lun;
13622
13623         ctl_softc = control_softc;
13624
13625         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13626
13627         /*
13628          * LUN lookup will likely move to the ctl_work_thread() once we
13629          * have our new queueing infrastructure (that doesn't put things on
13630          * a per-LUN queue initially).  That is so that we can handle
13631          * things like an INQUIRY to a LUN that we don't have enabled.  We
13632          * can't deal with that right now.
13633          */
13634         mtx_lock(&ctl_softc->ctl_lock);
13635
13636         /*
13637          * If we don't have a LUN for this, just toss the sense
13638          * information.
13639          */
13640         targ_lun = io->io_hdr.nexus.targ_lun;
13641         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13642         if ((targ_lun < CTL_MAX_LUNS)
13643          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13644                 lun = ctl_softc->ctl_luns[targ_lun];
13645         else
13646                 goto bailout;
13647
13648         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13649
13650         mtx_lock(&lun->lun_lock);
13651         /*
13652          * Already have CA set for this LUN...toss the sense information.
13653          */
13654         if (ctl_is_set(lun->have_ca, initidx)) {
13655                 mtx_unlock(&lun->lun_lock);
13656                 goto bailout;
13657         }
13658
13659         memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
13660                ctl_min(sizeof(lun->pending_sense[initidx].sense),
13661                sizeof(io->scsiio.sense_data)));
13662         ctl_set_mask(lun->have_ca, initidx);
13663         mtx_unlock(&lun->lun_lock);
13664
13665 bailout:
13666         mtx_unlock(&ctl_softc->ctl_lock);
13667
13668         ctl_free_io(io);
13669
13670         return (CTL_RETVAL_COMPLETE);
13671 }
13672
13673 /*
13674  * Primary command inlet from frontend ports.  All SCSI and task I/O
13675  * requests must go through this function.
13676  */
13677 int
13678 ctl_queue(union ctl_io *io)
13679 {
13680         struct ctl_softc *ctl_softc;
13681
13682         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13683
13684         ctl_softc = control_softc;
13685
13686 #ifdef CTL_TIME_IO
13687         io->io_hdr.start_time = time_uptime;
13688         getbintime(&io->io_hdr.start_bt);
13689 #endif /* CTL_TIME_IO */
13690
13691         /* Map FE-specific LUN ID into global one. */
13692         io->io_hdr.nexus.targ_mapped_lun =
13693             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13694
13695         switch (io->io_hdr.io_type) {
13696         case CTL_IO_SCSI:
13697         case CTL_IO_TASK:
13698                 ctl_enqueue_incoming(io);
13699                 break;
13700         default:
13701                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13702                 return (EINVAL);
13703         }
13704
13705         return (CTL_RETVAL_COMPLETE);
13706 }
13707
13708 #ifdef CTL_IO_DELAY
13709 static void
13710 ctl_done_timer_wakeup(void *arg)
13711 {
13712         union ctl_io *io;
13713
13714         io = (union ctl_io *)arg;
13715         ctl_done(io);
13716 }
13717 #endif /* CTL_IO_DELAY */
13718
13719 void
13720 ctl_done(union ctl_io *io)
13721 {
13722         struct ctl_softc *ctl_softc;
13723
13724         ctl_softc = control_softc;
13725
13726         /*
13727          * Enable this to catch duplicate completion issues.
13728          */
13729 #if 0
13730         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13731                 printf("%s: type %d msg %d cdb %x iptl: "
13732                        "%d:%d:%d:%d tag 0x%04x "
13733                        "flag %#x status %x\n",
13734                         __func__,
13735                         io->io_hdr.io_type,
13736                         io->io_hdr.msg_type,
13737                         io->scsiio.cdb[0],
13738                         io->io_hdr.nexus.initid.id,
13739                         io->io_hdr.nexus.targ_port,
13740                         io->io_hdr.nexus.targ_target.id,
13741                         io->io_hdr.nexus.targ_lun,
13742                         (io->io_hdr.io_type ==
13743                         CTL_IO_TASK) ?
13744                         io->taskio.tag_num :
13745                         io->scsiio.tag_num,
13746                         io->io_hdr.flags,
13747                         io->io_hdr.status);
13748         } else
13749                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13750 #endif
13751
13752         /*
13753          * This is an internal copy of an I/O, and should not go through
13754          * the normal done processing logic.
13755          */
13756         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13757                 return;
13758
13759         /*
13760          * We need to send a msg to the serializing shelf to finish the IO
13761          * as well.  We don't send a finish message to the other shelf if
13762          * this is a task management command.  Task management commands
13763          * aren't serialized in the OOA queue, but rather just executed on
13764          * both shelf controllers for commands that originated on that
13765          * controller.
13766          */
13767         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13768          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13769                 union ctl_ha_msg msg_io;
13770
13771                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13772                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13773                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13774                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13775                 }
13776                 /* continue on to finish IO */
13777         }
13778 #ifdef CTL_IO_DELAY
13779         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13780                 struct ctl_lun *lun;
13781
13782                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13783
13784                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13785         } else {
13786                 struct ctl_lun *lun;
13787
13788                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13789
13790                 if ((lun != NULL)
13791                  && (lun->delay_info.done_delay > 0)) {
13792                         struct callout *callout;
13793
13794                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13795                         callout_init(callout, /*mpsafe*/ 1);
13796                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13797                         callout_reset(callout,
13798                                       lun->delay_info.done_delay * hz,
13799                                       ctl_done_timer_wakeup, io);
13800                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13801                                 lun->delay_info.done_delay = 0;
13802                         return;
13803                 }
13804         }
13805 #endif /* CTL_IO_DELAY */
13806
13807         ctl_enqueue_done(io);
13808 }
13809
13810 int
13811 ctl_isc(struct ctl_scsiio *ctsio)
13812 {
13813         struct ctl_lun *lun;
13814         int retval;
13815
13816         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13817
13818         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13819
13820         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13821
13822         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13823
13824         return (retval);
13825 }
13826
13827
13828 static void
13829 ctl_work_thread(void *arg)
13830 {
13831         struct ctl_thread *thr = (struct ctl_thread *)arg;
13832         struct ctl_softc *softc = thr->ctl_softc;
13833         union ctl_io *io;
13834         int retval;
13835
13836         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13837
13838         for (;;) {
13839                 retval = 0;
13840
13841                 /*
13842                  * We handle the queues in this order:
13843                  * - ISC
13844                  * - done queue (to free up resources, unblock other commands)
13845                  * - RtR queue
13846                  * - incoming queue
13847                  *
13848                  * If those queues are empty, we break out of the loop and
13849                  * go to sleep.
13850                  */
13851                 mtx_lock(&thr->queue_lock);
13852                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13853                 if (io != NULL) {
13854                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13855                         mtx_unlock(&thr->queue_lock);
13856                         ctl_handle_isc(io);
13857                         continue;
13858                 }
13859                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13860                 if (io != NULL) {
13861                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13862                         /* clear any blocked commands, call fe_done */
13863                         mtx_unlock(&thr->queue_lock);
13864                         retval = ctl_process_done(io);
13865                         continue;
13866                 }
13867                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13868                 if (io != NULL) {
13869                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13870                         mtx_unlock(&thr->queue_lock);
13871                         if (io->io_hdr.io_type == CTL_IO_TASK)
13872                                 ctl_run_task(io);
13873                         else
13874                                 ctl_scsiio_precheck(softc, &io->scsiio);
13875                         continue;
13876                 }
13877                 if (!ctl_pause_rtr) {
13878                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13879                         if (io != NULL) {
13880                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13881                                 mtx_unlock(&thr->queue_lock);
13882                                 retval = ctl_scsiio(&io->scsiio);
13883                                 if (retval != CTL_RETVAL_COMPLETE)
13884                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13885                                 continue;
13886                         }
13887                 }
13888
13889                 /* Sleep until we have something to do. */
13890                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13891         }
13892 }
13893
13894 static void
13895 ctl_lun_thread(void *arg)
13896 {
13897         struct ctl_softc *softc = (struct ctl_softc *)arg;
13898         struct ctl_be_lun *be_lun;
13899         int retval;
13900
13901         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13902
13903         for (;;) {
13904                 retval = 0;
13905                 mtx_lock(&softc->ctl_lock);
13906                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13907                 if (be_lun != NULL) {
13908                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13909                         mtx_unlock(&softc->ctl_lock);
13910                         ctl_create_lun(be_lun);
13911                         continue;
13912                 }
13913
13914                 /* Sleep until we have something to do. */
13915                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13916                     PDROP | PRIBIO, "-", 0);
13917         }
13918 }
13919
13920 static void
13921 ctl_enqueue_incoming(union ctl_io *io)
13922 {
13923         struct ctl_softc *softc = control_softc;
13924         struct ctl_thread *thr;
13925         u_int idx;
13926
13927         idx = (io->io_hdr.nexus.targ_port * 127 +
13928                io->io_hdr.nexus.initid.id) % worker_threads;
13929         thr = &softc->threads[idx];
13930         mtx_lock(&thr->queue_lock);
13931         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13932         mtx_unlock(&thr->queue_lock);
13933         wakeup(thr);
13934 }
13935
13936 static void
13937 ctl_enqueue_rtr(union ctl_io *io)
13938 {
13939         struct ctl_softc *softc = control_softc;
13940         struct ctl_thread *thr;
13941
13942         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13943         mtx_lock(&thr->queue_lock);
13944         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13945         mtx_unlock(&thr->queue_lock);
13946         wakeup(thr);
13947 }
13948
13949 static void
13950 ctl_enqueue_done(union ctl_io *io)
13951 {
13952         struct ctl_softc *softc = control_softc;
13953         struct ctl_thread *thr;
13954
13955         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13956         mtx_lock(&thr->queue_lock);
13957         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13958         mtx_unlock(&thr->queue_lock);
13959         wakeup(thr);
13960 }
13961
13962 static void
13963 ctl_enqueue_isc(union ctl_io *io)
13964 {
13965         struct ctl_softc *softc = control_softc;
13966         struct ctl_thread *thr;
13967
13968         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13969         mtx_lock(&thr->queue_lock);
13970         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13971         mtx_unlock(&thr->queue_lock);
13972         wakeup(thr);
13973 }
13974
13975 /* Initialization and failover */
13976
13977 void
13978 ctl_init_isc_msg(void)
13979 {
13980         printf("CTL: Still calling this thing\n");
13981 }
13982
13983 /*
13984  * Init component
13985  *      Initializes component into configuration defined by bootMode
13986  *      (see hasc-sv.c)
13987  *      returns hasc_Status:
13988  *              OK
13989  *              ERROR - fatal error
13990  */
13991 static ctl_ha_comp_status
13992 ctl_isc_init(struct ctl_ha_component *c)
13993 {
13994         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13995
13996         c->status = ret;
13997         return ret;
13998 }
13999
14000 /* Start component
14001  *      Starts component in state requested. If component starts successfully,
14002  *      it must set its own state to the requestrd state
14003  *      When requested state is HASC_STATE_HA, the component may refine it
14004  *      by adding _SLAVE or _MASTER flags.
14005  *      Currently allowed state transitions are:
14006  *      UNKNOWN->HA             - initial startup
14007  *      UNKNOWN->SINGLE - initial startup when no parter detected
14008  *      HA->SINGLE              - failover
14009  * returns ctl_ha_comp_status:
14010  *              OK      - component successfully started in requested state
14011  *              FAILED  - could not start the requested state, failover may
14012  *                        be possible
14013  *              ERROR   - fatal error detected, no future startup possible
14014  */
14015 static ctl_ha_comp_status
14016 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14017 {
14018         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14019
14020         printf("%s: go\n", __func__);
14021
14022         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14023         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14024                 ctl_is_single = 0;
14025                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14026                     != CTL_HA_STATUS_SUCCESS) {
14027                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14028                         ret = CTL_HA_COMP_STATUS_ERROR;
14029                 }
14030         } else if (CTL_HA_STATE_IS_HA(c->state)
14031                 && CTL_HA_STATE_IS_SINGLE(state)){
14032                 // HA->SINGLE transition
14033                 ctl_failover();
14034                 ctl_is_single = 1;
14035         } else {
14036                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14037                        c->state, state);
14038                 ret = CTL_HA_COMP_STATUS_ERROR;
14039         }
14040         if (CTL_HA_STATE_IS_SINGLE(state))
14041                 ctl_is_single = 1;
14042
14043         c->state = state;
14044         c->status = ret;
14045         return ret;
14046 }
14047
14048 /*
14049  * Quiesce component
14050  * The component must clear any error conditions (set status to OK) and
14051  * prepare itself to another Start call
14052  * returns ctl_ha_comp_status:
14053  *      OK
14054  *      ERROR
14055  */
14056 static ctl_ha_comp_status
14057 ctl_isc_quiesce(struct ctl_ha_component *c)
14058 {
14059         int ret = CTL_HA_COMP_STATUS_OK;
14060
14061         ctl_pause_rtr = 1;
14062         c->status = ret;
14063         return ret;
14064 }
14065
14066 struct ctl_ha_component ctl_ha_component_ctlisc =
14067 {
14068         .name = "CTL ISC",
14069         .state = CTL_HA_STATE_UNKNOWN,
14070         .init = ctl_isc_init,
14071         .start = ctl_isc_start,
14072         .quiesce = ctl_isc_quiesce
14073 };
14074
14075 /*
14076  *  vim: ts=8
14077  */